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 (
{
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 (
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 }) {
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 (
);
}
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 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 (
In Akte:
{items.map((item, index) => (
{index ? · : null}
{item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / ")}
))}
{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}
);
}
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 (
<>
>
);
}
export function DirectionColumn({ direction }) {
const label = directionWord(direction) || "Keine Angabe";
return (
);
}
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(
,
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 (
{DIRECTION_OPTIONS.map(([value, label]) => (
))}
);
}
export function DirectionChoice({ value, disabled, onChange, compact = false, label = "Kommunikationsrichtung" }) {
const select = (
);
if (compact) return {select};
return (
);
}
export function MarkdownEditor({ value, onChange, disabled }) {
return ;
}
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 (
);
}
if (href) {
return {caption};
}
return {caption}
;
}
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 (
<>
{refers.length ? Bezug auf
: null}
{refers.map((item) => (
{canClear ? : null}
))}
{replies.length ? Darauf bezogen
: null}
{replies.map((item) => (
{canClear ? : null}
))}
>
);
}
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 ? (
) : null}
{real ? : null}
{section.title}
{canEdit && onAddContent ? (
) : null}
{count}
{section.documentOn ? {formatDate(section.documentOn)} : null}
{showMenu ? (
<>
{canEdit && onAddSubchapter ? : null}
{canEdit ? : null}
{canDate ? (
) : null}
{movable ? : null}
{movable ? : null}
{canEdit ? (
) : null}
{canEdit ? : null}
>
) : 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 (
{canEdit ? (
<>
Bezug
{(element.refers_to || []).map((item) => (
))}
{(element.referred_by || []).length ? Darauf bezogen
: null}
{(element.referred_by || []).map((item) => (
))}
>
) : null}
{canSort && chapters.length ? (
) : null}
{canSort && custom ? : null}
{canSort && custom ? : null}
{canEdit && onAttach ? : null}
{canEdit && onDispatch ? : null}
{canEdit ? : null}
{canEdit && canDestroy ? : null}
);
}
function TypeGlyph({ name, tone, size = 28 }) {
return (
);
}
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 (
{url ?
: (
<>
>
)}
{url ? (
) : null}
{dropId ? : null}
);
}
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 (
{carrying && (carrying.source === "attachment" || carrying.source === "evidence") ? (
{indicator?.kind === "release" && indicator.place && indicator.title ? `In ${indicator.title} legen` : "In den Vorgang legen"}
) : null}
{viewMode === "chronology" ? "Chronologie" : (activePath || listTitle || "Inhalte")} {shownCount}
{canSort && chapters.length && !picking ? (
) : null}
{canSort ? (
) : sortable ? (
{custom ? "Eigene Reihenfolge" : `Fachliches Datum, ${direction === "desc" ? "absteigend" : "aufsteigend"}`}
) : null}
{pending ?
Ordnung wird gespeichert …
: null}
{picking ? (
{picked.size} ausgewählt
) : null}
{viewMode === "chronology" ? (
) : source.length || chapters.length ? (
renderBlockList()
) : (
Noch keine Unterlage und keine Notiz.
)}
setDialog(null)}>
{dialog?.type === "bulk" && !dialog.host ? (
) : null}
{dialog?.type === "attach" && dialog.host ? (
item.id === dialog.host.id) || dialog.host}
bindings={source}
chapters={chapters}
scope={scopeBody(actionContext(), containerKind, containerId)}
pending={pending}
onClose={() => setDialog(null)}
onDone={() => onChange()}
/>
) : null}
setDialog(null)}>
{dialog?.type === "dispatch" ? (
setDialog(null)}
onDone={() => { setDialog(null); onChange(); }}
/>
) : null}
setDialog(null)}>
{dialog?.type === "place-use" ? (
{dialog.payload.title || dialog.binding.element.title} an {dialog.host.element.title}
) : null}
setDialog(null)}>
{dialog?.type === "evidence" ? (
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}
);
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 (
{insertBefore ? : null}
{section.title && !hideHead ? (
{
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 ? (
) : null}
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}
/>
) : null}
{expanded && section.title && !section.items.length && !section.children?.length ? Noch nichts in diesem Kapitel.
: null}
{expanded && picking && section.items.length ? (
) : null}
{expanded ?
{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 (
-
{indicator?.kind === "order" && indicator?.sectionId === section.id && indicator.index === index ? : null}
{picking ? (
) : null}
{canEdit ? (
saveRowDirection(binding, value)}
/>
) : (
)}
{canEdit || (canSort && custom) ? (
) : null}
{
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) => (
{element.title}
{switches}
{sourceSymbol ? (
) : null}
{facts}
{text ? (
{text}
) : null}
{samePiece ?
{samePiece} : null}
{originText ?
{originText} : null}
{lists}
)}
setDialog({ type: "attach", host: row })}
onDispatch={(row) => setDialog({ type: "dispatch", host: row })}
/>
);
})}
{indicator?.kind === "order" && indicator?.sectionId === section.id && indicator.index === section.items.length ? : null}
: null}
{expanded && section.children?.length ? (
{section.children.map((child) => renderBlock(child, depth + 1, false))}
) : null}
{insertAfter ? : null}
);
}
}
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 (
);
}
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}
);
}
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 (
Eine Frist ist der maßgebliche Termin. Mehrere Aufgaben können davor liegen. Erledigen einer Aufgabe erfüllt die Frist nicht.
Fristen
{record.deadlines?.length ? (
{record.deadlines.map((deadline) => {
const assigned = tasksFor(deadline.id);
const available = tasks.filter((task) => !assigned.some((item) => item.id === task.id));
return (
-
{deadline.title}
{deadline.status === "fulfilled" ? "Erfüllt" : "Offen"} · {formatDate(deadline.due_on)}{deadline.matter_title ? ` · ${deadline.matter_title}` : ""}
{assigned.length ? (
{assigned.map((task) => (
))}
) :
Noch keine Aufgabe vor dieser Frist.}
{available.length ? (
) : null}
{deadline.status === "open" ? : null}
);
})}
) :
Keine Frist.
}
Aufgaben ohne Frist
{loose.length ? (
{loose.map((task) => (
-
))}
) :
Keine Aufgabe ohne Frist.
}
);
}
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 (
{task.title}
{task.status === "done" ? "Erledigt" : "Offen"}{task.due_on ? ` · Arbeitstermin ${formatDate(task.due_on)}` : ""}
{(task.depends_on || []).length ? Hängt ab von {task.depends_on.map((item) => item.title).join(", ")}. : null}
{(task.elements || []).length ? Bezieht sich auf {task.elements.map((item) => item.title).join(", ")}. : null}
{task.status === "open" && task.rights?.edit !== false ?
: null}
{task.rights?.edit !== false ? (
Bezüge
) : null}
);
}
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))} />}
);
}