import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { Link } from "react-router-dom"; import { api, fetchFile, fetchPaperless } from "../api.js"; import { contentSourceSymbol, contentSymbol, symbolUrl } from "../content-symbol.mjs"; import { bezugCount, counterpartLabel, directionSymbol } from "../list-meta.mjs"; import { MarkdownView } from "../markdown.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 ? ( ) : null}
  • ); } export function RecordTree({ items, parentKey, hrefFor }) { const { roots, children } = nestRecords(items, parentKey); if (!roots.length) return null; return ( ); } 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) { if (element?.external?.source === "imap") return "email"; return contentSymbol(element || {}); } export function sourceLabel(element) { const type = SYMBOL_LABEL[elementSymbol(element)] || "Datei"; if (element.external?.source === "paperless") return `${type} · Paperless`; if (element.external?.source === "imap") return "E-Mail"; if (element.kind === "external_ref" && type === "Verweis") return "Referenz"; return type; } export function mailFacts(element) { if (element?.external?.source !== "imap") 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, rows = 12 }) { return (