Korrigiere IMAP-Ordner, MIME-Ansicht und die gemeinsamen Leser, damit große Postfächer, Notizen und verspätete Quellenantworten zuverlässig bleiben.
Deploy Development / deploy (push) Successful in 39s
Test Suite / pytest-backend (push) Successful in 2m29s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 20s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-20 08:47:24 +02:00
1 parent 34c4084a7c
commit c29bd29f34
29 files changed
+2562 -410

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
export function MailBody({ html, text, truncated, notices = [] }) {
return (
<div className="mail-reading">
{html ? <div className="mail-letter__html" dangerouslySetInnerHTML={{ __html: html }} /> : null}
<p className="muted">Vereinfachte Textfassung. Sie ist nicht die formatierte Ansicht.</p>
{text ? <pre className="mail-letter__body">{text}</pre> : <p className="muted">Diese Nachricht hat keinen lesbaren Text.</p>}
{truncated ? <p className="muted">Der Text ist gekürzt, weil die Nachricht sehr groß ist. Das Original bleibt die vollständige E-Mail.</p> : null}
{notices.map((item) => <p key={item} className="notice">{item}</p>)}
</div>
);
}
export 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.archive_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>
);
}
+5
View File
@@ -4,6 +4,11 @@ import { BrowserRouter } from "react-router-dom";
import { App } from "./App.jsx";
import "./styles.css";
if (import.meta.env.DEV && new URLSearchParams(window.location.search).has("probe")) {
const probe = await import("./sources/sample-source.js");
probe.installSampleSource();
}
createRoot(document.getElementById("root")).render(
<React.StrictMode>
<BrowserRouter>
+17 -86
View File
@@ -1,91 +1,22 @@
import { Fragment } from "react";
import ReactMarkdown from "react-markdown";
function inline(text, keyPrefix) {
const pattern = /(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^)\s]+\))/g;
const nodes = [];
let last = 0;
let index = 0;
for (const match of text.matchAll(pattern)) {
if (match.index > last) nodes.push(text.slice(last, match.index));
const token = match[0];
const key = `${keyPrefix}-${index}`;
if (token.startsWith("**")) nodes.push(<strong key={key}>{token.slice(2, -2)}</strong>);
else if (token.startsWith("*")) nodes.push(<em key={key}>{token.slice(1, -1)}</em>);
else if (token.startsWith("`")) nodes.push(<code key={key}>{token.slice(1, -1)}</code>);
else {
const linked = token.match(/^\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)$/);
if (linked) nodes.push(<a key={key} href={linked[2]} rel="noreferrer">{linked[1]}</a>);
}
last = match.index + token.length;
index += 1;
}
if (last < text.length) nodes.push(text.slice(last));
return nodes;
const SAFE_LINK = /^(https?:\/\/|mailto:)/i;
function Link({ href, children }) {
if (!SAFE_LINK.test(href || "")) return <span>{children}</span>;
return <a href={href} rel="noreferrer">{children}</a>;
}
function Image({ alt }) {
return alt ? <span>{alt}</span> : null;
}
export function MarkdownView({ text }) {
const lines = String(text || "").replace(/\r\n/g, "\n").split("\n");
const blocks = [];
let list = null;
let index = 0;
function closeList() {
if (!list) return;
const items = list.items.map((item, itemIndex) => <li key={`${list.key}-${itemIndex}`}>{inline(item, `${list.key}-${itemIndex}`)}</li>);
blocks.push(list.ordered ? <ol key={list.key}>{items}</ol> : <ul key={list.key}>{items}</ul>);
list = null;
}
while (index < lines.length) {
const line = lines[index];
if (line.startsWith("```")) {
closeList();
const body = [];
index += 1;
while (index < lines.length && !lines[index].startsWith("```")) {
body.push(lines[index]);
index += 1;
}
blocks.push(<pre key={`code-${index}`}><code>{body.join("\n")}</code></pre>);
index += 1;
continue;
}
if (line.startsWith(">")) {
closeList();
const body = [];
while (index < lines.length && lines[index].startsWith(">")) {
body.push(lines[index].replace(/^>\s?/, ""));
index += 1;
}
blocks.push(<blockquote key={`q-${index}`}>{body.map((item, itemIndex) => <p key={itemIndex}>{inline(item, `q-${index}-${itemIndex}`)}</p>)}</blockquote>);
continue;
}
const heading = line.match(/^(#{1,3})\s+(.*)$/);
const bullet = line.match(/^\s*[-*]\s+(.*)$/);
const numbered = line.match(/^\s*\d+\.\s+(.*)$/);
if (heading) {
closeList();
const Tag = heading[1].length === 1 ? "h3" : heading[1].length === 2 ? "h4" : "h5";
blocks.push(<Tag key={`h-${index}`}>{inline(heading[2], `h-${index}`)}</Tag>);
index += 1;
continue;
}
if (bullet || numbered) {
if (!list || list.ordered !== Boolean(numbered)) {
closeList();
list = { key: `l-${index}`, ordered: Boolean(numbered), items: [] };
}
list.items.push((bullet || numbered)[1]);
index += 1;
continue;
}
closeList();
if (!line.trim()) {
blocks.push(<Fragment key={`s-${index}`} />);
index += 1;
continue;
}
blocks.push(<p key={`p-${index}`}>{inline(line, `p-${index}`)}</p>);
index += 1;
}
closeList();
return <div className="markdown">{blocks}</div>;
return (
<div className="markdown">
<ReactMarkdown components={{ a: Link, img: Image }}>
{String(text || "")}
</ReactMarkdown>
</div>
);
}
+10 -107
View File
@@ -1,9 +1,8 @@
import { useContext, useEffect, useRef, useState } from "react";
import { SessionContext } from "../session.js";
import { documentToText, downloadMailPart, fetchExternal, fetchFile, fetchMailPart, isDirty, markDirty, textToDocument, api } from "../api.js";
import { MarkdownView } from "../markdown.jsx";
import { NoteEditor } from "../notes.jsx";
import { SourceAssignment, noteEditor, representationOf } from "../sources/registry.jsx";
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";
@@ -132,14 +131,14 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
useEffect(() => {
if (!element) return undefined;
const kind = representationOf(element);
if (kind === "note" || kind === "mail") setPhase("ready");
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 || representationOf(element) === "note" || representationOf(element) === "mail" || representationOf(element) === "locked" || representationOf(element) === "unassigned" || !element.preview?.available) return undefined;
if (!element || stageFor(representationOf(element)) || representationOf(element) === "locked" || representationOf(element) === "unassigned" || !element.preview?.available) return undefined;
let alive = true;
let url = "";
setPage(1);
@@ -206,7 +205,7 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
}, [element?.id, element?.kind, element?.external?.source, element?.external?.resolution, element?.file?.protection_profile, element?.preview?.available, context?.kind, context?.id]);
useEffect(() => {
if (!element || representationOf(element) !== "mail") return undefined;
if (!element || stageFor("mail") || representationOf(element) !== "mail") return undefined;
if (shownIndex === null) {
setPhase("ready");
setPdf(null);
@@ -275,7 +274,7 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
}, [element?.id, element?.external?.source, shownIndex, letter, context?.kind, context?.id]);
useEffect(() => {
if (!element || representationOf(element) !== "mail") return undefined;
if (!element || stageFor("mail") || representationOf(element) !== "mail") return undefined;
let alive = true;
const params = new URLSearchParams();
if (context?.kind && context?.id) {
@@ -366,52 +365,8 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
}
}
async function saveNote(event) {
event.preventDefault();
setError("");
try {
const updated = await noteEditor.save({
api,
element,
context,
document: textToDocument(text),
});
pendingNote.current = text;
editingRef.current = false;
setEditingNote(false);
markDirty(false);
setNotice(updated.notice || "Der gemeinsame Text ist gespeichert.");
onReload();
} catch (err) {
if (err.status === 409) {
setError("Der Stand hat sich geändert. Der eingegebene Text bleibt stehen. Bitte neu laden.");
return;
}
setError(err.message);
}
}
function beginNote() {
pendingNote.current = "";
editingRef.current = true;
setText(documentToText(element.document));
setNoteSession((current) => current + 1);
setEditingNote(true);
setError("");
setNotice("");
}
function cancelNote() {
pendingNote.current = "";
editingRef.current = false;
setText(documentToText(element.document));
setEditingNote(false);
markDirty(false);
setError("");
}
function requestClose() {
if (editingRef.current && isDirty() && !window.confirm("Ungespeicherte Eingaben verwerfen?")) return;
if (isDirty() && !window.confirm("Ungespeicherte Eingaben verwerfen?")) return;
markDirty(false);
onClose();
}
@@ -538,6 +493,7 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
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";
@@ -589,61 +545,8 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
onDetach={() => {}}
onUnfold={() => {}}
/>
{isMail ? (
<article className="mail-letter">
<p className="mail-letter__way"><DirectionColumn direction={shownDirection} />{directionWord(shownDirection) ? <span>{directionWord(shownDirection)}</span> : null}</p>
<p><span>Von</span> {mailDetail.message_from || "Ohne Absender"}</p>
<p><span>An</span> {mailDetail.message_to || "Ohne Empfänger"}</p>
{mailDetail.message_cc ? <p><span>Kopie</span> {mailDetail.message_cc}</p> : null}
{letter?.complete ? (
<>
<MailAttachments files={letter.attachments} current={shownIndex} onOpen={(file) => {
setError("");
setShownFor((current) => (
current?.elementId === element.id && current.index === file.index ? null : { elementId: element.id, index: file.index }
));
}} />
{shownFile ? <p className="mail-attachment__caption">Anlage: {shownFile.filename}</p> : null}
{shownFile && phase === "loading" ? <p className="muted">Die Anlage wird geladen …</p> : null}
{media === "image" && blobUrl ? (
<img className="reader-image" alt={shownFile?.filename || element.title} src={blobUrl} style={{ width: `${Math.round(scale * 100)}%` }} />
) : null}
{media === "pdf" && pdf ? <canvas ref={canvasRef} className="reader-canvas" /> : null}
{media === "pdf-frame" && blobUrl ? <iframe className="reader-frame" title={shownFile?.filename || element.title} src={blobUrl} /> : null}
{media === "other" && blobUrl ? (
<div className="reader-pane__state">
<p>Diese Anlage lässt sich hier nicht als Seite zeigen.</p>
<a href={blobUrl} target="_blank" rel="noreferrer">Anlage öffnen</a>
</div>
) : null}
{letter.text ? <pre className="mail-letter__body">{letter.text}</pre> : (
<p className="muted">Diese Nachricht hat keinen lesbaren Text. Die vollständige E-Mail bleibt abrufbar.</p>
)}
<button type="button" onClick={() => openMailPart("original", "nachricht.eml")}>Vollständige E-Mail</button>
</>
) : (
<p className="muted">{error ? "Die vollständige Nachricht konnte nicht geladen werden." : "Die vollständige Nachricht wird geladen …"}</p>
)}
</article>
) : null}
{element.kind === "note" && noteEditor.available ? (
editingNote && binding.rights.edit ? (
<form className="reader-note" onSubmit={saveNote}>
<NoteEditor key={noteSession} value={text} onChange={(value) => { setText(value); markDirty(true); }} />
<p className="muted">Diese Änderung betrifft den gemeinsamen Inhalt der Notiz, nicht die hiesige Anmerkung. Gespeichert wird Markdown.</p>
{notice ? <p className="notice">{notice}</p> : null}
<div className="row">
<button type="submit">Text speichern</button>
<button type="button" className="quiet" onClick={cancelNote}>Abbrechen</button>
</div>
</form>
) : (
<div className="reader-note">
{text.trim() ? <MarkdownView text={text} /> : <p className="muted">Die Notiz ist leer.</p>}
{notice ? <p className="notice">{notice}</p> : null}
{binding.rights.edit ? <button type="button" onClick={beginNote}>Bearbeiten</button> : <p className="muted">In diesem Kontext nur lesbar.</p>}
</div>
)
{Stage ? (
<Stage element={element} context={context} binding={binding} onReload={onReload} shownDirection={shownDirection} />
) : null}
<form className="stack reader-direction" onSubmit={(event) => event.preventDefault()}>
<DirectionChoice
+47 -14
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { api, fetchBlob } from "../api.js";
import { MailBody } from "../mail-view.jsx";
import { SourceFrame, moduleFor, registerSourceModule, sourceModules } from "../sources/registry.jsx";
const SEARCH_LIMITS = {
@@ -201,6 +202,9 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
const [previewUrl, setPreviewUrl] = useState("");
const [pending, setPending] = useState(false);
const [error, setError] = useState("");
const searchRef = useRef(0);
const previewRef = useRef(0);
const facetRef = useRef(0);
useEffect(() => {
api("/api/v1/connectors")
@@ -217,13 +221,15 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
setFacets({ correspondents: [], document_types: [], tags: [] });
return undefined;
}
const token = facetRef.current + 1;
facetRef.current = token;
let alive = true;
api(`/api/v1/sources/paperless/facets?connector_id=${connectorId}`)
.then((data) => {
if (alive) setFacets(data);
if (alive && token === facetRef.current) setFacets(data);
})
.catch((err) => {
if (alive) setError(err.message);
if (alive && token === facetRef.current) setError(err.message);
});
return () => {
alive = false;
@@ -253,6 +259,12 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
return params;
}
function invalidate() {
searchRef.current += 1;
previewRef.current += 1;
facetRef.current += 1;
}
async function runSearch(event, page = "") {
event?.preventDefault();
setError("");
@@ -260,12 +272,17 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
setError("Wähle zuerst den Paperless-Zugang.");
return;
}
const token = searchRef.current + 1;
searchRef.current = token;
const asked = connectorId;
try {
const data = await api(`/api/v1/sources/paperless/documents?${paramsFor(page)}`);
if (token !== searchRef.current) return;
setItems(data.items || []);
setNextPage(data.next_page || data.continuation || null);
if (data.connector_id) setConnectorId(data.connector_id);
if (!asked && data.connector_id) setConnectorId(data.connector_id);
} catch (err) {
if (token !== searchRef.current) return;
setError(err.message);
}
}
@@ -291,11 +308,15 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
setError("");
if (previewUrl) URL.revokeObjectURL(previewUrl);
setPreviewUrl("");
const token = previewRef.current + 1;
previewRef.current = token;
const bound = item.connector_id || connectorId;
try {
const bound = item.connector_id || connectorId;
const blob = await fetchBlob(`/api/v1/sources/paperless/documents/${item.id}/preview?connector_id=${bound}`);
if (token !== previewRef.current) return;
setPreviewUrl(URL.createObjectURL(blob));
} catch (err) {
if (token !== previewRef.current) return;
setError(err.message);
}
}
@@ -366,7 +387,16 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
{connectors.length > 1 ? (
<label>
Paperless-Zugang
<select value={connectorId} onChange={(event) => { setConnectorId(event.target.value); setItems([]); setNextPage(null); }}>
<select value={connectorId} onChange={(event) => {
invalidate();
if (previewUrl) URL.revokeObjectURL(previewUrl);
setPreviewUrl("");
setConnectorId(event.target.value);
setFilters(EMPTY_FILTERS);
setItems([]);
setNextPage(null);
setFacets({ correspondents: [], document_types: [], tags: [] });
}}>
<option value="">Zugang wählen</option>
{connectors.map((item) => (
<option key={item.id} value={item.id}>{item.name}</option>
@@ -567,6 +597,7 @@ export function MailPicker({ context, placement, chapterId = "", chapterTitle =
const [items, setItems] = useState([]);
const [nextBefore, setNextBefore] = useState(null);
const [incomplete, setIncomplete] = useState(false);
const [contradictory, setContradictory] = useState(false);
const [uidValidity, setUidValidity] = useState(null);
const [notice, setNotice] = useState("");
const [selectedKey, setSelectedKey] = useState("");
@@ -587,6 +618,7 @@ export function MailPicker({ context, placement, chapterId = "", chapterTitle =
if (token !== requestRef.current) return;
setUidValidity(data.uidvalidity ?? null);
setIncomplete(Boolean(data.incomplete));
setContradictory(Boolean(data.contradictory));
setNextBefore(data.next_before ?? data.continuation ?? null);
if (data.restarted) {
setItems(data.items || []);
@@ -644,6 +676,7 @@ export function MailPicker({ context, placement, chapterId = "", chapterTitle =
setItems([]);
setNextBefore(null);
setIncomplete(false);
setContradictory(false);
setNotice("");
setSelectedKey("");
setPreview(null);
@@ -805,12 +838,14 @@ export function MailPicker({ context, placement, chapterId = "", chapterTitle =
{accountId && !loading && !mailbox && !error ? <p className="muted">Dieses Konto hat keine lesbaren Fächer.</p> : null}
{loading ? <p className="muted">{loading}</p> : null}
{!loading && mailbox && !items.length && !error ? (
<p className="muted">
{incomplete
? "In diesem Abschnitt gibt es keine Treffer. Die Suche ist noch nicht zu Ende."
: query
? "In diesem Fach gibt es dazu keine Nachricht."
: "In diesem Fach gibt es keine Nachricht."}
<p className={contradictory ? "notice" : "muted"}>
{contradictory
? "Das Fach meldet Nachrichten, aber es kam keine Liste an. Das Fach gilt deshalb nicht als leer."
: incomplete
? "In diesem Abschnitt gibt es keine Treffer. Die Suche ist noch nicht zu Ende."
: query
? "In diesem Fach gibt es dazu keine Nachricht."
: "In diesem Fach gibt es keine Nachricht."}
</p>
) : null}
<div className="mail-list">
@@ -847,9 +882,7 @@ export function MailPicker({ context, placement, chapterId = "", chapterTitle =
<MailFiles files={preview?.attachments || selected.attachments || []} />
{previewError ? <p className="error">{previewError}</p> : null}
{selected && !preview && !previewError ? <p className="muted">Vorschau wird geladen …</p> : null}
{preview?.text ? <pre className="mail-letter__body">{preview.text}</pre> : null}
{preview?.text_truncated ? <p className="muted">Der Text ist gekürzt, weil die Nachricht sehr groß ist.</p> : null}
{preview && !preview.text ? <p className="muted">Diese Nachricht hat keinen lesbaren Text.</p> : null}
{preview ? <MailBody html={preview.html} text={preview.text} truncated={preview.text_truncated} notices={preview.notices} /> : null}
<ErrorNote error={error} />
<button type="button" onClick={() => link(selected)} disabled={!selected.uid || adopting}>{adopting ? "Wird übernommen …" : "Übernehmen"}</button>
</>
+8 -20
View File
@@ -1,11 +1,17 @@
import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { api, documentToText, downloadFile, fetchExternal, markDirty, textToDocument } from "../api.js";
import { MarkdownView } from "../markdown.jsx";
import { stageFor } from "../sources/registry.jsx";
import "../sources/builtin-views.jsx";
import { NoteEditor } from "../notes.jsx";
import { moduleFor } from "../sources/registry-core.js";
import { Modal } from "./Modal.jsx";
function RegisteredNote(props) {
const Stage = stageFor("note");
return Stage ? <Stage {...props} /> : null;
}
export function ErrorNote({ error }) {
if (!error) return null;
return <p className="error">{error}</p>;
@@ -190,25 +196,7 @@ function Binding({ binding, context, canEdit, isOwner, onChange }) {
</div>
</header>
<DateLine dates={dates} />
{element.kind === "note" ? (
editingNote && binding.rights.edit ? (
<form onSubmit={saveNote} className="stack">
<NoteEditor value={text} onChange={(value) => { setText(value); markDirty(true); }} />
<p className="muted">Diese Änderung betrifft den gemeinsamen Inhalt der Notiz.</p>
{notice ? <p className="notice">{notice}</p> : null}
<div className="row">
<button type="submit">Text speichern</button>
<button type="button" className="quiet" onClick={() => { setText(documentToText(element.document)); setEditingNote(false); markDirty(false); }}>Abbrechen</button>
</div>
</form>
) : (
<div className="stack">
{text.trim() ? <MarkdownView text={text} /> : <p className="muted">Die Notiz ist leer.</p>}
{notice ? <p className="notice">{notice}</p> : null}
{binding.rights.edit ? <button type="button" onClick={() => setEditingNote(true)}>Bearbeiten</button> : <p className="muted">In diesem Kontext nur lesbar.</p>}
</div>
)
) : null}
{element.kind === "note" ? <RegisteredNote element={element} context={context} binding={binding} onReload={onChange} /> : null}
{element.kind === "file" && element.file ? (
element.file.status === "active" ? (
<button type="button" onClick={() => downloadFile(element.id, context, element.file.filename)}>
+284
View File
@@ -0,0 +1,284 @@
import { useEffect, useRef, useState } from "react";
import { api, documentToText, downloadMailPart, fetchExternal, fetchMailPart, markDirty, textToDocument } from "../api.js";
import { MailAttachments, MailBody } from "../mail-view.jsx";
import { MarkdownView } from "../markdown.jsx";
import { NoteEditor } from "../notes.jsx";
import { DirectionColumn, directionWord } from "../pages/content.jsx";
import workerSrc from "pdfjs-dist/build/pdf.worker.min.mjs?url";
import { editors, registerStage } from "./registry.jsx";
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";
}
export function NoteStage({ element, context, binding, onReload }) {
const editor = editors.note;
const [text, setText] = useState(() => documentToText(element.document));
const [editing, setEditing] = useState(false);
const [session, setSession] = useState(0);
const [notice, setNotice] = useState("");
const [error, setError] = useState("");
const draft = useRef("");
const editingRef = useRef(false);
useEffect(() => {
if (editingRef.current) return undefined;
const saved = documentToText(element.document);
if (!draft.current || draft.current === saved) {
draft.current = "";
setText(saved);
}
return undefined;
}, [element.id, element.version, element.document]);
async function save(event) {
event.preventDefault();
setError("");
try {
const updated = await editor.save({ api, element, context, document: textToDocument(text) });
draft.current = text;
editingRef.current = false;
setEditing(false);
markDirty(false);
setNotice(updated.notice || "Der gemeinsame Text ist gespeichert.");
onReload?.();
} catch (err) {
if (err.status === 409) {
setError("Der Stand hat sich geändert. Der eingegebene Text bleibt stehen. Bitte neu laden.");
return;
}
setError(err.message);
}
}
function begin() {
draft.current = "";
editingRef.current = true;
setText(documentToText(element.document));
setSession((current) => current + 1);
setEditing(true);
setError("");
setNotice("");
}
function cancel() {
draft.current = "";
editingRef.current = false;
setText(documentToText(element.document));
setEditing(false);
markDirty(false);
setError("");
}
if (!editor?.available) return null;
if (editing && binding?.rights?.edit) {
return (
<form className="reader-note" onSubmit={save}>
<NoteEditor key={session} value={text} onChange={(value) => { setText(value); markDirty(true); }} />
<p className="muted">Diese Änderung betrifft den gemeinsamen Inhalt der Notiz, nicht die hiesige Anmerkung. Gespeichert wird Markdown.</p>
{error ? <p className="error">{error}</p> : null}
{notice ? <p className="notice">{notice}</p> : null}
<div className="row">
<button type="submit">Text speichern</button>
<button type="button" className="quiet" onClick={cancel}>Abbrechen</button>
</div>
</form>
);
}
return (
<div className="reader-note">
{text.trim() ? <MarkdownView text={text} /> : <p className="muted">Die Notiz ist leer.</p>}
{error ? <p className="error">{error}</p> : null}
{notice ? <p className="notice">{notice}</p> : null}
{binding?.rights?.edit ? <button type="button" onClick={begin}>Bearbeiten</button> : <p className="muted">In diesem Kontext nur lesbar.</p>}
</div>
);
}
export function TextStage({ element, context }) {
const [text, setText] = useState("");
const [error, setError] = useState("");
useEffect(() => {
let alive = true;
fetchExternal(element.id, context)
.then(async (blob) => {
if (alive) setText(await blob.text());
})
.catch((err) => {
if (alive) setError(err.message || "Der Text ist nicht verfügbar.");
});
return () => {
alive = false;
};
}, [element.id, context?.kind, context?.id]);
return (
<div>
{error ? <p className="error">{error}</p> : null}
<pre className="mail-letter__body">{text}</pre>
</div>
);
}
export function MailStage({ element, context, shownDirection }) {
const [letter, setLetter] = useState(null);
const [error, setError] = useState("");
const [shownFor, setShownFor] = useState(null);
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 canvasRef = useRef(null);
const objectUrl = useRef("");
const shownIndex = shownFor?.elementId === element?.id ? shownFor.index : null;
const shownFile = (letter?.attachments || []).find((item) => item.index === shownIndex) || null;
useEffect(() => {
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(() => {
if (shownIndex === null) return undefined;
const file = (letter?.attachments || []).find((item) => item.index === shownIndex);
if (!file) return undefined;
let alive = true;
setPhase("loading");
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");
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");
setError(err.message || "Die Anlage ist nicht verfügbar.");
});
return () => {
alive = false;
};
}, [element.id, shownIndex, letter, context?.kind, context?.id]);
useEffect(() => () => {
pdf?.destroy?.();
if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
}, [pdf]);
useEffect(() => {
if (!pdf || !canvasRef.current) return undefined;
let alive = true;
pdf.getPage(page).then((pdfPage) => {
if (!alive || !canvasRef.current) return;
const canvas = canvasRef.current;
const context2d = canvas.getContext("2d");
const viewport = pdfPage.getViewport({ scale: 1 });
canvas.width = viewport.width;
canvas.height = viewport.height;
return pdfPage.render({ canvasContext: context2d, viewport }).promise;
}).catch(() => {});
return () => {
alive = false;
};
}, [pdf, page]);
async function openOriginal() {
setError("");
try {
await downloadMailPart(element.id, context, "original", "nachricht.eml");
} catch (err) {
setError(err.message);
}
}
return (
<article className="mail-letter">
<p className="mail-letter__way"><DirectionColumn direction={shownDirection} />{directionWord(shownDirection) ? <span>{directionWord(shownDirection)}</span> : null}</p>
<p><span>Von</span> {letter?.message_from || "Ohne Absender"}</p>
<p><span>An</span> {letter?.message_to || "Ohne Empfänger"}</p>
{letter?.message_cc ? <p><span>Kopie</span> {letter.message_cc}</p> : null}
{error ? <p className="error">{error}</p> : null}
{letter ? (
<>
<MailAttachments files={letter.attachments} current={shownIndex} onOpen={(file) => {
setError("");
setShownFor((current) => (
current?.elementId === element.id && current.index === file.index ? null : { elementId: element.id, index: file.index }
));
}} />
{shownFile ? <p className="mail-attachment__caption">Anlage: {shownFile.filename}</p> : null}
{shownFile && phase === "loading" ? <p className="muted">Die Anlage wird geladen …</p> : null}
{media === "image" && blobUrl ? <img className="reader-image" alt={shownFile?.filename || element.title} src={blobUrl} /> : null}
{media === "pdf" && pdf ? <canvas ref={canvasRef} className="reader-canvas" /> : null}
{media === "pdf-frame" && blobUrl ? <iframe className="reader-frame" title={shownFile?.filename || element.title} src={blobUrl} /> : null}
{media === "other" && blobUrl ? <a href={blobUrl} target="_blank" rel="noreferrer">Anlage öffnen</a> : null}
{pages > 1 ? (
<div className="reader-pages">
<button type="button" disabled={page <= 1} onClick={() => setPage((current) => Math.max(1, current - 1))}>Vorherige Seite</button>
<span>{page} / {pages}</span>
<button type="button" disabled={page >= pages} onClick={() => setPage((current) => Math.min(pages, current + 1))}>Nächste Seite</button>
</div>
) : null}
<MailBody html={letter.html} text={letter.text} truncated={letter.text_truncated} notices={letter.notices} />
<button type="button" onClick={openOriginal}>Vollständige E-Mail</button>
</>
) : (
<p className="muted">{error ? "Die vollständige Nachricht konnte nicht geladen werden." : "Die vollständige Nachricht wird geladen …"}</p>
)}
</article>
);
}
registerStage("note", NoteStage);
registerStage("mail", MailStage);
registerStage("text", TextStage);
+23
View File
@@ -0,0 +1,23 @@
import { editors, registerRepresentation, registerStage } from "./registry.jsx";
export function FixtureStage({ element }) {
return (
<article data-stage="fixture">
<h2>{element.title}</h2>
<p>{element.preview?.text}</p>
</article>
);
}
export function installFixture() {
registerRepresentation("fixture", "fixture");
registerStage("fixture", FixtureStage);
editors.fixture = {
id: "fixture",
available: true,
async save() {
return { notice: "gespeichert" };
},
};
return FixtureStage;
}
+20 -3
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { api } from "../api.js";
import { TargetLine } from "../pages/content.jsx";
import { ErrorNote } from "../pages/widgets.jsx";
@@ -26,6 +26,17 @@ const representationReaders = new Map([
["markdown", "note"],
]);
const stages = new Map();
export function registerStage(id, component) {
stages.set(id, component);
return component;
}
export function stageFor(id) {
return stages.get(id) || null;
}
export function registerRepresentation(media, reader) {
representationReaders.set(media, reader);
}
@@ -59,6 +70,7 @@ export function StandardSourcePicker({ sourceKind, context, placement, chapterId
const [items, setItems] = useState([]);
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
const searchRef = useRef(0);
const hint = module?.searchHint || "Suche im heute unterstützten Umfang dieser Quelle.";
useEffect(() => {
@@ -78,13 +90,18 @@ export function StandardSourcePicker({ sourceKind, context, placement, chapterId
setError("Wähle zuerst den Zugang.");
return;
}
const token = searchRef.current + 1;
searchRef.current = token;
const asked = connectorId;
const params = new URLSearchParams({ q: query });
if (connectorId) params.set("connector_id", connectorId);
try {
const data = await api(`/api/v1/sources/${sourceKind}/search?${params}`);
if (token !== searchRef.current) return;
setItems(data.items || []);
if (data.connector_id) setConnectorId(data.connector_id);
if (!asked && data.connector_id) setConnectorId(data.connector_id);
} catch (err) {
if (token !== searchRef.current) return;
setError(err.message);
}
}
@@ -120,7 +137,7 @@ export function StandardSourcePicker({ sourceKind, context, placement, chapterId
{connectors.length > 1 ? (
<label>
Zugang
<select value={connectorId} onChange={(event) => setConnectorId(event.target.value)}>
<select value={connectorId} onChange={(event) => { searchRef.current += 1; setConnectorId(event.target.value); setItems([]); }}>
<option value="">Zugang wählen</option>
{connectors.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
</select>
+29
View File
@@ -1,5 +1,33 @@
import { createElement, useState } from "react";
import { api } from "../api.js";
import { registerSourceModule, unregisterSourceModule } from "./registry-core.js";
function SampleForm({ onSaved, onError, connectorId = "", initialName = "Beispielquelle", settings = null }) {
const [name, setName] = useState(initialName);
const [catalog, setCatalog] = useState(settings?.catalog || "alpha");
async function submit(event) {
event.preventDefault();
onError("");
try {
const body = { kind: "sample", name, config: { catalog } };
if (connectorId) await api(`/api/v1/connectors/${connectorId}`, { method: "PATCH", body });
else await api("/api/v1/connectors", { method: "POST", body });
await onSaved();
} catch (err) {
onError(err.message);
}
}
return createElement(
"form",
{ onSubmit: submit, className: "stack" },
createElement("label", null, "Name ", createElement("input", { value: name, onChange: (event) => setName(event.target.value), required: true })),
createElement("label", null, "Katalog ", createElement("input", { value: catalog, onChange: (event) => setCatalog(event.target.value), required: true })),
createElement("button", { type: "submit" }, connectorId ? "Zugang erneuern" : "Beispielquelle verbinden"),
);
}
export function installSampleSource() {
return registerSourceModule({
kind: "sample",
@@ -7,6 +35,7 @@ export function installSampleSource() {
addLabel: "Beispielquelle",
representation: "text",
manual: true,
Form: SampleForm,
});
}
+17
View File
@@ -1050,6 +1050,23 @@ button.hierarchy__row { width: 100%; min-height: 34px; padding: 6px 8px; border:
font: inherit;
color: var(--text1);
}
.mail-letter__html {
overflow-wrap: anywhere;
max-width: 100%;
}
.mail-letter__html img,
.mail-letter__html table {
max-width: 100%;
}
.mail-letter__html table {
border-collapse: collapse;
}
.mail-letter__html td,
.mail-letter__html th {
border: 1px solid var(--line);
padding: 4px 6px;
vertical-align: top;
}
@media (min-width: 900px) {
.record-layout { grid-template-columns: minmax(220px, 280px) minmax(0, 1fr); }