Files
tsumugu/frontend/src/pages/ReadingPane.jsx
T
StommerandClaude Sonnet 5.5 075525ee17
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 5m35s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 22s
Steuere das Herunterladen von Originalen je Rolle, benenne Dateien richtig und zeige HTML-Mails gesichert im Sandbox-Rahmen.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 14:22:35 +02:00

669 lines
26 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { 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 <p className="muted">Keine Anhänge.</p>;
return (
<ul className="mail-files">
{files.map((file) => (
<li key={`${file.index ?? "name"}-${file.filename}`}>
{onOpen && Number.isInteger(file.index) ? (
<button type="button" className={file.index === current ? "quiet is-current" : "quiet"} aria-pressed={file.index === current} onClick={() => onOpen(file)}>{file.filename}</button>
) : file.filename}
</li>
))}
</ul>
);
}
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 (
<section className="schriftwechsel" aria-label="Schriftwechsel">
<h3>Schriftwechsel</h3>
<p>Verbundene Schreiben bleiben als Bezug sichtbar. Weitere Schreiben, die dazwischen ein- oder ausgegangen sind, bleiben in der Liste an ihrer eigenen Stelle.</p>
{items.map((item) => (
<button
key={item.id}
type="button"
className={item.current ? "schriftwechsel__item is-current" : "schriftwechsel__item"}
disabled={item.current || !onOpenRelated}
onClick={() => onOpenRelated?.(item.id)}
>
<DirectionColumn direction={item.direction} />
<span>{formatDate(item.document_on)}</span>
<strong>{item.current ? `${item.title} · diese Unterlage` : item.title}</strong>
{directionWord(item.direction) ? <span>{directionWord(item.direction)}</span> : <span />}
</button>
))}
</section>
);
}
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 (
<section className="reader-pane" aria-label="Leser">
<header className="reader-pane__bar">
<button type="button" className="quiet" onClick={onClose}>Zurück zu {backLabel || "den Inhalten"}</button>
</header>
<p className="muted reader-pane__state">Diese Unterlage ist hier nicht sichtbar.</p>
</section>
);
}
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 (
<section className="reader-pane" aria-label="Leser">
<header className="reader-pane__bar">
<button type="button" className="reader-back" onClick={onClose}>
<span aria-hidden="true">‹</span> {backLabel || "Inhalte"}
</button>
<div className="reader-pane__heading">
<div className="reader-title">
<DirectionColumn direction={shownDirection} />
<h2>{element.title}</h2>
{binding.rights.edit ? (
<button type="button" className="icon-button icon-button--compact" aria-label="Titel ändern" onClick={renameTitle}>
<NavIcon name="pencil" />
</button>
) : null}
</div>
<p className="reader-facts">
<span>{formatDate(element.dates?.document_on)} · {sourceLabel(element)}</span>
{directionWord(shownDirection) ? <span>{directionWord(shownDirection)}</span> : null}
{mailFacts(element) ? <span>{mailFacts(element)}</span> : null}
{dateCaption(element, shownDirection) ? <span>{dateCaption(element, shownDirection)}</span> : null}
</p>
</div>
<div className="reader-pane__tools">
{element.kind !== "note" && !isMail && binding.rights.download ? (
<button type="button" className="icon-button" aria-label="Original herunterladen" title="Original herunterladen" onClick={openOriginal}>
<NavIcon name="link" />
</button>
) : null}
<button ref={closeRef} type="button" className="icon-button" aria-label="Leser schließen" onClick={requestClose}>
<NavIcon name="close" />
</button>
</div>
</header>
<div className="reader-pane__stage">
<ErrorNote error={error} />
<Correspondence element={element} direction={shownDirection} onOpenRelated={onOpenRelated} />
<UnitDetail
binding={binding}
canEdit={false}
pending={false}
onOpen={(elementId) => onOpenRelated?.(elementId)}
onDetach={() => {}}
onUnfold={() => {}}
/>
{Stage ? (
<Stage element={element} context={context} binding={binding} onReload={onReload} shownDirection={shownDirection} />
) : null}
<form className="stack reader-direction" onSubmit={(event) => event.preventDefault()}>
<DirectionChoice
value={directionValue(communication)}
disabled={!binding.rights.edit}
onChange={saveDirection}
/>
<p className="muted">Keine Angabe bleibt leer. Versand- und Zugangsdatum ändern die Richtung nicht.</p>
</form>
{!isMail && locked ? (
<div className="reader-pane__state">
<p>Die Metadaten sind sichtbar. Der Inhalt ist geschützt und wird in dieser Lieferung nicht entschlüsselt.</p>
</div>
) : null}
{!isMail && unassigned ? (
<div className="reader-pane__state">
<SourceAssignment element={element} onAssigned={onReload} owner={ownsElement} />
</div>
) : null}
{!isMail && !locked && !unassigned && phase === "loading" ? <p className="reader-pane__state">Vorschau wird geladen …</p> : null}
{!isMail && !locked && !unassigned && phase === "missing" ? (
<div className="reader-pane__state">
<p>Für diesen Inhalt gibt es keine eingebaute Vorschau.</p>
{binding.rights.download ? <button type="button" onClick={openOriginal}>Original herunterladen</button> : null}
</div>
) : null}
{!isMail && phase === "error" ? (
<div className="reader-pane__state">
<p>Die Vorschau ist nicht verfügbar.</p>
{binding.rights.download ? <button type="button" onClick={openOriginal}>Original herunterladen</button> : null}
</div>
) : null}
{!isMail && media === "text" ? <pre className="mail-letter__body">{sourceText}</pre> : null}
{!isMail && media === "image" && blobUrl ? (
<img className="reader-image" alt={element.title} src={blobUrl} style={{ width: `${Math.round(scale * 100)}%` }} />
) : null}
{!isMail && media === "pdf" && pdf ? <canvas ref={canvasRef} className="reader-canvas" /> : null}
{!isMail && media === "pdf-frame" && blobUrl ? <DocumentView title={element.title} url={blobUrl} /> : null}
{!isMail && media === "other" && blobUrl ? (
<div className="reader-pane__state">
<p>Die Datei ist geladen, aber hier nicht als Seite darstellbar.</p>
{binding.rights.download ? <a href={blobUrl} target="_blank" rel="noreferrer">Original öffnen</a> : null}
</div>
) : null}
</div>
<footer className="reader-pane__foot">
{pages > 1 || media === "image" ? (
<div className="reader-controls">
{pages > 1 ? (
<div className="reader-pages">
<button type="button" className="icon-button" aria-label="Vorherige Seite" disabled={page <= 1} onClick={() => setPage((current) => Math.max(1, current - 1))}>‹</button>
<span>{page} / {pages}</span>
<button type="button" className="icon-button" aria-label="Nächste Seite" disabled={page >= pages} onClick={() => setPage((current) => Math.min(pages, current + 1))}>›</button>
</div>
) : <span />}
<div className="reader-zoom">
<button type="button" className="icon-button" aria-label="Verkleinern" disabled={scale <= SCALES[0]} onClick={() => setScale((current) => SCALES[Math.max(0, SCALES.indexOf(current) - 1)] || current)}>−</button>
<span>{Math.round(scale * 100)}%</span>
<button type="button" className="icon-button" aria-label="Vergrößern" disabled={scale >= SCALES[SCALES.length - 1]} onClick={() => setScale((current) => SCALES[Math.min(SCALES.length - 1, SCALES.indexOf(current) + 1)] || current)}>+</button>
</div>
</div>
) : null}
<button type="button" className="quiet" onClick={() => setAnnotate((open) => !open)}>{annotate ? "Anmerkung schließen" : "Anmerkung"}</button>
</footer>
{annotate ? (
<div className="reader-annotate">
<h3>Anmerkung in diesem Zusammenhang</h3>
<p className="muted">Sie gilt nur hier und ändert den gemeinsamen Inhalt nicht.</p>
{binding.annotations?.length ? (
<ul className="notes">
{binding.annotations.map((item) => (
<li key={item.id}><strong>{item.author_display_name}</strong> {item.body}</li>
))}
</ul>
) : <p className="muted">Noch keine Anmerkung.</p>}
{binding.rights.edit ? (
<form className="stack" onSubmit={annotateSubmit}>
<label>
Neue Anmerkung
<textarea rows={3} value={note} onChange={(event) => { setNote(event.target.value); markDirty(true); }} required />
</label>
<button type="submit">Anmerkung speichern</button>
</form>
) : null}
{binding.rights.edit ? (
<form className="stack" onSubmit={saveSummary}>
<label>
Kurzbeschreibung, optional
<textarea rows={2} maxLength={400} value={summary} onChange={(event) => { setSummary(event.target.value); markDirty(true); }} />
</label>
<button type="submit" className="quiet">Kurzbeschreibung speichern</button>
</form>
) : null}
{binding.rights.edit ? (
<form className="stack" onSubmit={saveDate}>
<label>
{element.kind === "note" ? "Bezugsdatum, optional" : "Dokumentdatum, optional"}
<DateField value={documentOn} onChange={(value) => { setDocumentOn(value); markDirty(true); }} />
</label>
<label>
Versand, optional
<DateField value={sentOn} onChange={(value) => { setSentOn(value); markDirty(true); }} />
</label>
<label>
Zugang, optional
<DateField value={receivedOn} onChange={(value) => { setReceivedOn(value); markDirty(true); }} />
</label>
<button type="submit" className="quiet">Datum speichern</button>
</form>
) : null}
<div className="row">
{canDetach ? <button type="button" className="quiet" onClick={detach}>Aus diesem Zusammenhang entfernen</button> : null}
{canDestroy ? <button type="button" className="danger" onClick={destroy}>Überall löschen</button> : null}
</div>
</div>
) : null}
</section>
);
}