import { DocumentView } from "./DocumentView.jsx";
import { useContext, useEffect, useRef, useState } from "react";
import { SessionContext } from "../session.js";
import { documentToText, downloadMailPart, fetchExternal, fetchFile, fetchMailPart, isDirty, markDirty, saveDocument, textToDocument, api } from "../api.js";
import { SourceAssignment, representationOf, stageFor } from "../sources/registry.jsx";
import "../sources/builtin-views.jsx";
import { ErrorNote } from "./widgets.jsx";
import { UnitDetail } from "./correspondence.jsx";
import { dateCaption, DateField, DirectionChoice, DirectionColumn, directionValue, directionWord, formatDate, mailFacts, sourceLabel } from "./content.jsx";
import { NavIcon } from "./icons.jsx";
import workerSrc from "pdfjs-dist/legacy/build/pdf.worker.min.mjs?url";
const SCALES = [0.75, 1, 1.25, 1.5, 2];
function previewKind(type, filename) {
const media = (type || "").toLowerCase();
const name = (filename || "").toLowerCase();
if (media.startsWith("image/") || /\.(png|jpe?g|gif|webp)$/.test(name)) return "image";
if (media.includes("pdf") || name.endsWith(".pdf")) return "pdf";
return "other";
}
function MailAttachments({ files, current, onOpen }) {
if (!files?.length) return
Keine Anhänge.
;
return (
{files.map((file) => (
{onOpen && Number.isInteger(file.index) ? (
onOpen(file)}>{file.filename}
) : file.filename}
))}
);
}
function Correspondence({ element, direction, onOpenRelated }) {
const refers = element.refers_to || [];
const replies = element.referred_by || [];
if (!refers.length && !replies.length) return null;
const current = {
id: element.id,
title: element.title,
document_on: element.dates?.document_on || null,
direction: direction || null,
current: true,
};
const seen = new Set();
const items = [];
for (const item of [...refers, current, ...replies]) {
if (seen.has(item.id)) continue;
seen.add(item.id);
items.push({ ...item, current: item.id === element.id });
}
items.sort((left, right) => String(left.document_on || "9999-99-99").localeCompare(String(right.document_on || "9999-99-99")));
return (
Schriftwechsel
Verbundene Schreiben bleiben als Bezug sichtbar. Weitere Schreiben, die dazwischen ein- oder ausgegangen sind, bleiben in der Liste an ihrer eigenen Stelle.
{items.map((item) => (
onOpenRelated?.(item.id)}
>
{formatDate(item.document_on)}
{item.current ? `${item.title} · diese Unterlage` : item.title}
{directionWord(item.direction) ? {directionWord(item.direction)} : }
))}
);
}
export function ReadingPane({ binding, context, backLabel, onClose, onReload, canDetach, canDestroy, onOpenRelated }) {
const element = binding?.element;
const { session } = useContext(SessionContext) || {};
const ownsElement = Boolean(session?.account?.id && element?.owner_subject_id === session.account.id);
const [error, setError] = useState("");
const [phase, setPhase] = useState("idle");
const [media, setMedia] = useState("");
const [blobUrl, setBlobUrl] = useState("");
const [pdf, setPdf] = useState(null);
const [page, setPage] = useState(1);
const [pages, setPages] = useState(0);
const [scale, setScale] = useState(1);
const [text, setText] = useState("");
const [sourceText, setSourceText] = useState("");
const [note, setNote] = useState("");
const [summary, setSummary] = useState("");
const [documentOn, setDocumentOn] = useState("");
const [sentOn, setSentOn] = useState("");
const [receivedOn, setReceivedOn] = useState("");
const [notice, setNotice] = useState("");
const [annotate, setAnnotate] = useState(false);
const [editingNote, setEditingNote] = useState(false);
const [noteSession, setNoteSession] = useState(0);
const editingRef = useRef(false);
const pendingNote = useRef("");
const [letter, setLetter] = useState(null);
const [shownFor, setShownFor] = useState(null);
const shownIndex = shownFor?.elementId === element?.id ? shownFor.index : null;
const canvasRef = useRef(null);
const objectUrl = useRef("");
const closeRef = useRef(null);
useEffect(() => {
closeRef.current?.focus();
}, [binding?.id]);
useEffect(() => {
if (!element) return undefined;
if (!editingRef.current) {
const saved = element.kind === "note" ? documentToText(element.document) : "";
if (!pendingNote.current || pendingNote.current === saved) {
pendingNote.current = "";
setText(saved);
}
}
setDocumentOn(element.dates?.document_on || "");
setSentOn(element.dates?.sent_on || "");
setReceivedOn(element.dates?.received_on || "");
setSummary(element.summary || "");
setNotice("");
return undefined;
}, [element?.id, element?.version, element?.summary, element?.document, element?.dates?.document_on, element?.dates?.sent_on, element?.dates?.received_on]);
useEffect(() => {
if (!element) return undefined;
const kind = representationOf(element);
if (stageFor(kind) || kind === "note" || kind === "mail") setPhase("ready");
else if (kind === "locked" || kind === "unassigned" || !element.preview?.available) setPhase("missing");
setError("");
return undefined;
}, [element?.id, element?.kind, element?.external?.source, element?.external?.resolution, element?.file?.protection_profile, element?.preview?.available]);
useEffect(() => {
if (!element || stageFor(representationOf(element)) || representationOf(element) === "locked" || representationOf(element) === "unassigned" || !element.preview?.available) return undefined;
let alive = true;
let url = "";
setPage(1);
setPdf(null);
setPages(0);
setMedia("");
setLetter(null);
if (objectUrl.current) {
URL.revokeObjectURL(objectUrl.current);
objectUrl.current = "";
}
setBlobUrl("");
setPhase("loading");
const view = representationOf(element);
const load = view === "source-file" || view === "text" ? fetchExternal(element.id, context) : fetchFile(element.id, context);
load.then(async (blob) => {
if (!alive) return;
if (view === "text") {
setSourceText(await blob.text());
setMedia("text");
setPhase("ready");
return;
}
url = URL.createObjectURL(blob);
setBlobUrl(url);
if (blob.type.startsWith("image/")) {
setMedia("image");
setPhase("ready");
return;
}
if (blob.type.includes("pdf") || element.file?.content_type === "application/pdf") {
setMedia("pdf");
try {
const bytes = await blob.arrayBuffer();
const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
const doc = await pdfjs.getDocument({ data: bytes }).promise;
if (!alive) {
doc.destroy();
return;
}
setPdf(doc);
setPages(doc.numPages);
setPhase("ready");
} catch (err) {
if (!alive) return;
setMedia("pdf-frame");
setPhase("ready");
setError("");
}
return;
}
setMedia("other");
setPhase("ready");
}).catch((err) => {
if (!alive) return;
setPhase("error");
setError(err.message || "Die Vorschau ist nicht verfügbar.");
});
return () => {
alive = false;
if (url) URL.revokeObjectURL(url);
};
}, [element?.id, element?.kind, element?.external?.source, element?.external?.resolution, element?.file?.protection_profile, element?.preview?.available, context?.kind, context?.id]);
useEffect(() => {
if (!element || stageFor("mail") || representationOf(element) !== "mail") return undefined;
if (shownIndex === null) {
setPhase("ready");
setPdf(null);
setPages(0);
setPage(1);
setMedia("");
if (objectUrl.current) {
URL.revokeObjectURL(objectUrl.current);
objectUrl.current = "";
}
setBlobUrl("");
return undefined;
}
const file = (letter?.attachments || []).find((item) => item.index === shownIndex);
if (!file) return undefined;
let alive = true;
setPhase("loading");
setPdf(null);
setPages(0);
setPage(1);
setMedia("");
fetchMailPart(element.id, context, `attachments/${file.index}`).then(async (blob) => {
if (!alive) return;
if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
const url = URL.createObjectURL(blob);
objectUrl.current = url;
setBlobUrl(url);
const kind = previewKind(blob.type || file.content_type, file.filename);
if (kind === "image") {
setMedia("image");
setPhase("ready");
return;
}
if (kind === "pdf") {
setMedia("pdf");
try {
const bytes = await blob.arrayBuffer();
const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
const doc = await pdfjs.getDocument({ data: bytes }).promise;
if (!alive) {
doc.destroy();
return;
}
setPdf(doc);
setPages(doc.numPages);
setPhase("ready");
} catch (err) {
if (!alive) return;
setMedia("pdf-frame");
setPhase("ready");
}
return;
}
setMedia("other");
setPhase("ready");
}).catch((err) => {
if (!alive) return;
setPhase("ready");
setMedia("");
setError(err.message || "Die Anlage ist nicht verfügbar.");
});
return () => {
alive = false;
};
}, [element?.id, element?.external?.source, shownIndex, letter, context?.kind, context?.id]);
useEffect(() => {
if (!element || stageFor("mail") || representationOf(element) !== "mail") return undefined;
let alive = true;
const params = new URLSearchParams();
if (context?.kind && context?.id) {
params.set("context_kind", context.kind);
params.set("context_id", context.id);
}
api(`/api/v1/external-refs/${element.id}/mail?${params}`)
.then((data) => {
if (alive) setLetter(data);
})
.catch((err) => {
if (!alive) return;
setLetter(null);
setError(err.message || "Die Nachricht konnte nicht geladen werden.");
});
return () => {
alive = false;
};
}, [element?.id, element?.external?.source, context?.kind, context?.id]);
useEffect(() => () => {
pdf?.destroy?.();
}, [pdf]);
useEffect(() => {
if (!pdf || !canvasRef.current) return undefined;
let alive = true;
const task = { cancel: null };
pdf.getPage(page).then((pdfPage) => {
if (!alive) return;
const canvas = canvasRef.current;
const context2d = canvas?.getContext("2d");
if (!canvas || !context2d) return;
const base = pdfPage.getViewport({ scale: 1 });
const viewport = pdfPage.getViewport({ scale: Math.min(scale, Math.sqrt(12_000_000 / (base.width * base.height))) });
canvas.width = viewport.width;
canvas.height = viewport.height;
const render = pdfPage.render({ canvasContext: context2d, viewport });
task.cancel = () => render.cancel();
return render.promise;
}).catch((err) => {
if (!alive || err?.name === "RenderingCancelledException") return;
setPhase("error");
setError("Die Seite konnte nicht dargestellt werden.");
});
return () => {
alive = false;
task.cancel?.();
};
}, [pdf, page, scale]);
useEffect(() => {
function onKey(event) {
if (event.key === "Escape") {
onClose();
return;
}
const tag = event.target?.tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
if (!pages) return;
if (event.key === "ArrowRight") setPage((current) => Math.min(pages, current + 1));
if (event.key === "ArrowLeft") setPage((current) => Math.max(1, current - 1));
}
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose, pages]);
async function openMailPart(suffix, filename) {
setError("");
try {
await downloadMailPart(element.id, context, suffix, filename);
} catch (err) {
setError(err.message);
}
}
async function openOriginal() {
setError("");
try {
const view = representationOf(element);
const path = view === "source-file" || view === "text"
? `/api/v1/external-refs/${element.id}/content`
: `/api/v1/files/${element.id}/content`;
await saveDocument(path, context, element.file?.filename || element.title || "dokument");
} catch (err) {
setError(err.message);
}
}
function requestClose() {
if (isDirty() && !window.confirm("Ungespeicherte Eingaben verwerfen?")) return;
markDirty(false);
onClose();
}
async function saveSummary(event) {
event.preventDefault();
setError("");
try {
await api(`/api/v1/elements/${element.id}/summary`, {
method: "PATCH",
body: { expected_version: element.version, summary: summary.trim() || null, context },
});
markDirty(false);
onReload();
} catch (err) {
setError(err.message);
}
}
async function saveDirection(value) {
setError("");
try {
await api(`/api/v1/bindings/${binding.id}/communication`, {
method: "PATCH",
body: { expected_version: element.version, direction: value || null, context },
});
onReload();
} catch (err) {
setError(err.message);
}
}
async function renameTitle() {
const title = window.prompt("Titel", element.title);
if (!title || title.trim() === element.title) return;
setError("");
try {
await api(`/api/v1/elements/${element.id}/title`, {
method: "PATCH",
body: { expected_version: element.version, title: title.trim(), context },
});
onReload();
} catch (err) {
setError(err.message);
}
}
async function saveDate(event) {
event.preventDefault();
setError("");
try {
await api(`/api/v1/elements/${element.id}/dates`, {
method: "PATCH",
body: {
expected_version: element.version,
document_on: documentOn || null,
sent_on: sentOn || null,
received_on: receivedOn || null,
context,
},
});
markDirty(false);
onReload();
} catch (err) {
setError(err.message);
}
}
async function annotateSubmit(event) {
event.preventDefault();
const search = new URLSearchParams();
search.set("context_kind", context.kind);
search.set("context_id", context.id);
try {
await api(`/api/v1/bindings/${binding.id}/annotations?${search}`, { method: "POST", body: { body: note } });
setNote("");
markDirty(false);
onReload();
} catch (err) {
setError(err.message);
}
}
async function detach() {
if (!window.confirm("Aus diesem Zusammenhang entfernen? Die Unterlage bleibt an anderen Stellen erhalten.")) return;
const search = new URLSearchParams();
search.set("context_kind", context.kind);
search.set("context_id", context.id);
setError("");
try {
await api(`/api/v1/bindings/${binding.id}?${search}`, { method: "DELETE" });
markDirty(false);
onClose();
onReload();
} catch (err) {
setError(err.message);
}
}
async function destroy() {
if (!window.confirm("Überall löschen? Alle Einbindungen verschwinden. Eine Paperless-Quelle bleibt unangetastet.")) return;
setError("");
try {
await api(`/api/v1/elements/${element.id}/delete`, { method: "POST", body: { expected_version: element.version } });
markDirty(false);
onClose();
onReload();
} catch (err) {
setError(err.message);
}
}
if (!binding) {
return (
Zurück zu {backLabel || "den Inhalten"}
Diese Unterlage ist hier nicht sichtbar.
);
}
const communication = binding.communication || {};
const shownDirection = communication.direction || null;
const kind = representationOf(element);
const Stage = stageFor(kind);
const isMail = kind === "mail";
const locked = kind === "locked";
const unassigned = kind === "unassigned";
const mailDetail = letter || element.external?.detail || {};
const shownFile = isMail ? (letter?.attachments || []).find((item) => item.index === shownIndex) || null : null;
return (
‹ {backLabel || "Inhalte"}
{element.title}
{binding.rights.edit ? (
) : null}
{formatDate(element.dates?.document_on)} · {sourceLabel(element)}
{directionWord(shownDirection) ? {directionWord(shownDirection)} : null}
{mailFacts(element) ? {mailFacts(element)} : null}
{dateCaption(element, shownDirection) ? {dateCaption(element, shownDirection)} : null}
{element.kind !== "note" && !isMail && binding.rights.download ? (
) : null}
onOpenRelated?.(elementId)}
onDetach={() => {}}
onUnfold={() => {}}
/>
{Stage ? (
) : null}
{!isMail && locked ? (
Die Metadaten sind sichtbar. Der Inhalt ist geschützt und wird in dieser Lieferung nicht entschlüsselt.
) : null}
{!isMail && unassigned ? (
) : null}
{!isMail && !locked && !unassigned && phase === "loading" ? Vorschau wird geladen …
: null}
{!isMail && !locked && !unassigned && phase === "missing" ? (
Für diesen Inhalt gibt es keine eingebaute Vorschau.
{binding.rights.download ?
Original herunterladen : null}
) : null}
{!isMail && phase === "error" ? (
Die Vorschau ist nicht verfügbar.
{binding.rights.download ?
Original herunterladen : null}
) : null}
{!isMail && media === "text" ? {sourceText} : null}
{!isMail && media === "image" && blobUrl ? (
) : null}
{!isMail && media === "pdf" && pdf ? : null}
{!isMail && media === "pdf-frame" && blobUrl ? : null}
{!isMail && media === "other" && blobUrl ? (
Die Datei ist geladen, aber hier nicht als Seite darstellbar.
{binding.rights.download ?
Original öffnen : null}
) : null}
{pages > 1 || media === "image" ? (
{pages > 1 ? (
setPage((current) => Math.max(1, current - 1))}>‹
{page} / {pages}
= pages} onClick={() => setPage((current) => Math.min(pages, current + 1))}>›
) :
}
setScale((current) => SCALES[Math.max(0, SCALES.indexOf(current) - 1)] || current)}>−
{Math.round(scale * 100)}%
= SCALES[SCALES.length - 1]} onClick={() => setScale((current) => SCALES[Math.min(SCALES.length - 1, SCALES.indexOf(current) + 1)] || current)}>+
) : null}
setAnnotate((open) => !open)}>{annotate ? "Anmerkung schließen" : "Anmerkung"}
{annotate ? (
Anmerkung in diesem Zusammenhang
Sie gilt nur hier und ändert den gemeinsamen Inhalt nicht.
{binding.annotations?.length ? (
{binding.annotations.map((item) => (
{item.author_display_name} {item.body}
))}
) :
Noch keine Anmerkung.
}
{binding.rights.edit ? (
) : null}
{binding.rights.edit ? (
Kurzbeschreibung, optional
{ setSummary(event.target.value); markDirty(true); }} />
Kurzbeschreibung speichern
) : null}
{binding.rights.edit ? (
{element.kind === "note" ? "Bezugsdatum, optional" : "Dokumentdatum, optional"}
{ setDocumentOn(value); markDirty(true); }} />
Versand, optional
{ setSentOn(value); markDirty(true); }} />
Zugang, optional
{ setReceivedOn(value); markDirty(true); }} />
Datum speichern
) : null}
{canDetach ? Aus diesem Zusammenhang entfernen : null}
{canDestroy ? Überall löschen : null}
) : null}
);
}