Oeffne Kapitel und Dokument auf derselben Arbeitsflaeche, damit Pfad, Rechte und eigene Reihenfolge beim Lesen erhalten bleiben.
Deploy Development / deploy (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 56s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 9s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-17 14:19:06 +02:00
1 parent 94ef46d8eb
commit 448e9a06ff
34 files changed
+2998 -696

No files matched your search

+293 -143
View File
@@ -1,11 +1,14 @@
import { useContext, useEffect, useRef, useState } from "react";
import { Link, useParams, useSearchParams } from "react-router-dom";
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
import { api, markDirty, textToDocument } from "../api.js";
import { SessionContext } from "../session.js";
import { Modal } from "./Modal.jsx";
import { MailPicker, PaperlessPicker } from "./Sources.jsx";
import { ErrorNote, ShareBox } from "./widgets.jsx";
import { ContentBoard, ObjectMenu, OrderChoice, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, selectionOf, withSelection, writeSelection } from "./content.jsx";
import { ContentBoard, ObjectMenu, OrderChoice, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, saveChapterOrder, writeSelection } from "./content.jsx";
import { ReadingPane } from "./ReadingPane.jsx";
import { StructureNavigator, Workspace, rememberScroll, restoreScroll, useWorkspaceLayout } from "./workspace.jsx";
import { NavIcon } from "./icons.jsx";
export function CaseList() {
const { session } = useContext(SessionContext);
@@ -208,12 +211,12 @@ function mergedCaseItems(record, direction, caseId) {
...(record.bindings || []).map((binding) => ({
...binding,
origin: chapterOrigin("Direkt in dieser Akte", record.chapters, binding.chapter_id),
readerHref: `/cases/${caseId}/items/${binding.id}`,
readerHref: `/cases/${caseId}?eintrag=${binding.id}${binding.chapter_id ? `&kapitel=${binding.chapter_id}` : ""}`,
})),
...(record.contained || []).flatMap((group) => (group.bindings || []).map((binding) => ({
...binding,
origin: chapterOrigin(matterOrigin(group), group.chapters, binding.chapter_id),
readerHref: `/matters/${group.matter_id}/items/${binding.id}?context_kind=case&context_id=${caseId}`,
readerHref: `/matters/${group.matter_id}?context_kind=case&context_id=${caseId}&eintrag=${binding.id}${binding.chapter_id ? `&kapitel=${binding.chapter_id}` : ""}`,
}))),
];
const counts = {};
@@ -227,16 +230,72 @@ function mergedCaseItems(record, direction, caseId) {
return [...dated, ...undated];
}
function matterNode(matter, caseId) {
const query = `?context_kind=case&context_id=${caseId}`;
return {
id: matter.id,
title: matter.title,
kind: matter.kind_label || "Vorgang",
href: `/matters/${matter.id}${query}`,
current: false,
children: (matter.children || []).map((child) => matterNode(child, caseId)),
};
}
function caseNodes(record, parentRecord) {
const self = {
id: record.id,
title: record.title,
kind: record.kind_label || "Akte",
href: null,
current: true,
children: [
...(record.subcases || []).map((item) => ({
id: item.id,
title: item.title,
kind: "Unterakte",
href: `/cases/${item.id}`,
current: false,
children: [],
})),
...(record.matters || []).map((matter) => matterNode(matter, record.id)),
],
};
if (!parentRecord) return [self];
const siblings = (parentRecord.subcases || []).map((item) => (item.id === record.id ? self : {
id: item.id,
title: item.title,
kind: "Unterakte",
href: `/cases/${item.id}`,
current: false,
children: [],
}));
return [{
id: parentRecord.id,
title: parentRecord.title,
kind: "Akte",
href: `/cases/${parentRecord.id}`,
current: false,
children: siblings.length ? siblings : [self],
}];
}
export function CaseDetail() {
const { id } = useParams();
const navigate = useNavigate();
const [params, setParams] = useSearchParams();
const { scope, chapterId } = selectionOf(params);
const rawScope = params.get("bereich") || "";
const overview = rawScope === "all" || rawScope === "ueberblick";
const chapterId = overview ? "" : (params.get("kapitel") || "");
const entryId = params.get("eintrag") || "";
const [record, setRecord] = useState(null);
const [parentTree, setParentTree] = useState(null);
const [error, setError] = useState("");
const [modal, setModal] = useState("");
const [view, setView] = useState("contents");
const [dateDir, setDateDir] = useState("asc");
const [outlineOpen, setOutlineOpen] = useState(false);
const { width, structureOpen, setStructureOpen } = useWorkspaceLayout();
const listRef = useRef(null);
const pendingChapter = useRef("");
const context = { kind: "case", id };
@@ -254,7 +313,8 @@ export function CaseDetail() {
setView("contents");
setModal("");
setDateDir("asc");
setOutlineOpen(false);
setStructureOpen(false);
setParentTree(null);
api(`/api/v1/cases/${id}`).then((detail) => {
if (!alive) return;
pendingChapter.current = "";
@@ -266,158 +326,248 @@ export function CaseDetail() {
}, [id]);
useEffect(() => {
if (!record || record.id !== id) return;
const known = new Set(["all", "direct", ...(record.contained || []).map((item) => item.matter_id)]);
const nextScope = known.has(scope) ? scope : "all";
const chapters = nextScope === "direct"
? (record.chapters || [])
: (record.contained || []).find((item) => item.matter_id === nextScope)?.chapters || [];
const nextChapter = chapterId && chapters.some((chapter) => chapter.id === chapterId) ? chapterId : "";
if (chapterId && !nextChapter && pendingChapter.current === chapterId) return;
if (nextScope !== scope || nextChapter !== chapterId) writeSelection(params, setParams, nextScope, nextChapter);
}, [record, id, scope, chapterId, params, setParams]);
if (!record || record.id !== id || !record.parent_case_id) return undefined;
let alive = true;
api(`/api/v1/cases/${record.parent_case_id}`).then((parent) => {
if (alive) setParentTree(parent);
}).catch(() => {
if (alive) setParentTree(null);
});
return () => {
alive = false;
};
}, [record, id]);
function choose(nextScope, nextChapter = "") {
writeSelection(params, setParams, nextScope, nextChapter);
useEffect(() => {
if (!record || record.id !== id) return;
const matterId = rawScope && !["all", "ueberblick", "direkt", "direct"].includes(rawScope) ? rawScope : "";
if (matterId && (record.contained || []).some((item) => item.matter_id === matterId)) {
const next = new URLSearchParams();
next.set("context_kind", "case");
next.set("context_id", id);
const chapter = params.get("kapitel");
if (chapter) next.set("kapitel", chapter);
navigate(`/matters/${matterId}?${next.toString()}`, { replace: true });
return;
}
if (!overview && chapterId && !(record.chapters || []).some((chapter) => chapter.id === chapterId)) {
if (pendingChapter.current === chapterId) return;
writeSelection(params, setParams, "direct", "");
}
}, [record, id, rawScope, overview, chapterId, params, setParams, navigate]);
useEffect(() => {
if (!record || record.id !== id || !entryId || overview) return;
const binding = (record.bindings || []).find((item) => item.id === entryId);
if (!binding) return;
const nextChapter = binding.chapter_id || "";
if ((chapterId || "") !== nextChapter) writeSelection(params, setParams, "direct", nextChapter);
}, [record, id, entryId, overview, chapterId, params, setParams]);
useEffect(() => {
if (entryId) return;
restoreScroll(listRef.current, `tsumugu-scroll:case:${id}:${chapterId}:${overview ? "over" : "direct"}`);
}, [entryId, id, chapterId, overview, record]);
function chooseChapter(next) {
const updated = new URLSearchParams(params);
updated.delete("bereich");
updated.delete("eintrag");
if (next) updated.set("kapitel", next);
else updated.delete("kapitel");
setParams(updated);
setView("contents");
setOutlineOpen(false);
setStructureOpen(false);
}
function showOverview() {
const updated = new URLSearchParams(params);
updated.set("bereich", "ueberblick");
updated.delete("kapitel");
updated.delete("eintrag");
setParams(updated);
setView("contents");
setStructureOpen(false);
}
function openEntry(binding) {
rememberScroll(listRef.current, `tsumugu-scroll:case:${id}:${chapterId}:direct`);
const updated = new URLSearchParams(params);
updated.delete("bereich");
updated.set("eintrag", binding.id);
if (binding.chapter_id) updated.set("kapitel", binding.chapter_id);
else updated.delete("kapitel");
setParams(updated);
setView("contents");
}
function closeEntry() {
const updated = new URLSearchParams(params);
updated.delete("eintrag");
setParams(updated, { replace: true });
}
async function moveChapter(chapterIdToMove, delta) {
const ids = (record?.chapters || []).map((chapter) => chapter.id);
const index = ids.indexOf(chapterIdToMove);
const target = index + delta;
if (!record || index < 0 || target < 0 || target >= ids.length) return;
const [moved] = ids.splice(index, 1);
ids.splice(target, 0, moved);
try {
await saveChapterOrder({ containerKind: "case", containerId: id, record, ids });
await load();
} catch (err) {
setError(err.message);
}
}
if (error && !record) return <main className="page"><ErrorNote error={error} /></main>;
if (!record) return <main className="page"><p className="muted">Akte wird geladen …</p></main>;
const group = scope !== "all" && scope !== "direct"
? (record.contained || []).find((item) => item.matter_id === scope) || null
: null;
const target = scope === "direct"
? {
scope: "direct",
label: `Akte ${record.title}`,
edit: Boolean(record.rights?.edit),
chapters: record.chapters || [],
chapterPath: `/api/v1/cases/${id}/chapters`,
}
: group
? {
scope: group.matter_id,
label: `${group.kind_label || "Vorgang"} ${group.title}`,
edit: Boolean(group.rights?.edit),
chapters: group.chapters || [],
chapterPath: `/api/v1/matters/${group.matter_id}/chapters?context_kind=case&context_id=${id}`,
}
: null;
const activeChapter = target?.chapters.find((chapter) => chapter.id === chapterId) || null;
const canEdit = Boolean(record.rights?.edit);
const targetLabel = `${record.kind_label || "Akte"} ${record.title}`;
const activeChapter = (record.chapters || []).find((chapter) => chapter.id === chapterId) || null;
const chapters = (record.chapters || []).map((chapter) => ({
...chapter,
count: (record.bindings || []).filter((item) => item.chapter_id === chapter.id).length,
}));
const merged = mergedCaseItems(record, dateDir, id);
const addPlacement = group ? { kind: "matter", id: group.matter_id } : null;
const contexts = [
...(parentTree ? [{ id: parentTree.id, label: parentTree.title }] : []),
{ id: record.id, label: record.title },
];
const entry = overview ? null : ((record.bindings || []).find((item) => item.id === entryId) || null);
const hasContained = Boolean(record.contained?.length);
return (
<main className="page">
<header className="page-head">
<>
<Workspace
width={width}
structureOpen={structureOpen}
setStructureOpen={setStructureOpen}
hasEntry={Boolean(entryId) && !overview}
listRef={listRef}
nav={(
<StructureNavigator
contexts={contexts}
contextValue={id}
onContext={parentTree ? ((next) => { if (next !== id) navigate(`/cases/${next}`); }) : null}
nodes={caseNodes(record, parentTree)}
chapters={chapters}
chapterId={overview ? "" : chapterId}
allCount={(record.bindings || []).length}
overview={hasContained ? { active: overview, count: merged.length, onSelect: showOverview } : null}
chapterHeading={`Kapitel in ${record.title}`}
onChapter={chooseChapter}
onAddChapter={canEdit ? () => setModal("chapter") : null}
canAddChapter={canEdit}
onMoveChapter={moveChapter}
canReorder={canEdit && chapters.length > 1}
links={[]}
onNavigate={() => setStructureOpen(false)}
onClose={width < 1500 ? () => setStructureOpen(false) : null}
/>
)}
reader={entryId && !overview ? (
<ReadingPane
binding={entry}
context={context}
backLabel={activeChapter?.title || "Alle Inhalte"}
onClose={closeEntry}
onReload={load}
canDetach={canEdit}
canDestroy={Boolean(record.is_owner)}
/>
) : null}
>
<header className="workspace-head">
<div>
<Trail items={caseTrail(record, id, group, scope, activeChapter)} />
<p className="eyebrow">{record.kind_label || "Akte"} · {record.home_scope_name}</p>
<h1>{record.title}</h1>
<p className="muted">{record.status === "open" ? "Offen" : "Geschlossen"}</p>
<Trail items={record.trail} />
<div className="title-row">
<h1>{record.title}</h1>
<span className={record.status === "open" ? "status-pill" : "status-pill is-closed"}>{record.status === "open" ? "Offen" : "Geschlossen"}</span>
</div>
</div>
<div className="page-actions">
{target?.edit ? <button type="button" onClick={() => setModal("add")}>Inhalt hinzufügen</button> : null}
{width < 1500 ? <button type="button" className="quiet" onClick={() => setStructureOpen(true)}>Struktur</button> : null}
{canEdit ? (
<button type="button" className="desktop-add" onClick={() => setModal("add")}>
<NavIcon name="plus" /> Inhalt hinzufügen
</button>
) : null}
<ObjectMenu view={view} onView={setView}>
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("matter")}>Vorgang anlegen und zuordnen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("assign")}>Vorhandenen Vorgang zuordnen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("subcase")}>Unterakte anlegen</button> : null}
{record.rights.share || record.is_owner ? <button type="button" className="quiet" onClick={() => setModal("share")}>Teilen</button> : null}
</ObjectMenu>
{target && !target.edit ? <p className="muted">In {target.label} fehlt das Bearbeitungsrecht.</p> : null}
</div>
</header>
{!canEdit ? <p className="muted">In {targetLabel} fehlt das Bearbeitungsrecht.</p> : null}
<ErrorNote error={error} />
<div className="record-layout">
<aside className={outlineOpen ? "outline is-open" : "outline"}>
<button type="button" className="outline__toggle" onClick={() => setOutlineOpen((open) => !open)}>{outlineOpen ? "Bereiche schließen" : "Bereiche"}</button>
<div className="outline__body">
<CaseOutline
record={record}
caseId={id}
scope={scope}
chapterId={chapterId}
onScope={(next) => choose(next)}
onChapter={(nextScope, nextChapter) => choose(nextScope, nextChapter)}
/>
</div>
</aside>
<div className="record-main">
<WorkSwitch view={view} onView={setView} />
{view === "contents" ? (
<p className="target-line">
{target ? (
<>Bearbeitet wird <strong>{target.label}</strong>{activeChapter ? <> · Kapitel <strong>{activeChapter.title}</strong></> : null}</>
) : (
"Lesesicht aller Inhalte. Zum Bearbeiten einen Bereich in der Gliederung wählen."
)}
</p>
) : null}
{view === "contents" && scope === "all" ? (
<div className="stack">
<OrderChoice mode="date" direction={dateDir} onChange={(_mode, next) => setDateDir(next)} />
<ContentBoard
record={{ bindings: merged, chapters: [], content_order: "date", content_order_dir: dateDir, rights: { edit: false }, version: record.version }}
bindings={merged}
sortable={false}
containerKind="case"
containerId={id}
onChange={load}
itemHref={(binding) => binding.readerHref}
/>
</div>
) : null}
{view === "contents" && scope === "direct" ? (
<ContentBoard
record={record}
containerKind="case"
containerId={id}
onlyChapter={chapterId}
onChange={load}
itemHref={(binding) => withSelection(`/cases/${id}/items/${binding.id}`, params)}
/>
) : null}
{view === "contents" && group ? (
<ContentBoard
record={{ ...group, rights: group.rights, chapters: group.chapters || [] }}
bindings={group.bindings}
context={context}
containerKind="matter"
containerId={group.matter_id}
onlyChapter={chapterId}
onChange={load}
itemHref={(binding) => withSelection(`/matters/${group.matter_id}/items/${binding.id}?context_kind=case&context_id=${id}`, params)}
/>
) : null}
{view === "contents" && scope !== "all" && scope !== "direct" && !group ? (
<p className="muted">Dieser Bereich hat in der Akte keine eigenen Unterlagen.</p>
) : null}
{view === "work" ? <WorkLists record={record} context={context} onChange={load} /> : null}
{view === "course" || view === "audit" ? (
<SurfaceView view={view} coursePath={`/api/v1/cases/${id}/course`} auditPath={`/api/v1/cases/${id}/chronology`} />
) : null}
{view === "links" ? (
<div className="stack">
<h2>Zuordnungen</h2>
<p className="muted">Unterakten, Vorgänge und Freigaben dieses Objekts.</p>
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("matter")}>Vorgang anlegen und zuordnen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("assign")}>Vorhandenen Vorgang zuordnen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("subcase")}>Unterakte anlegen</button> : null}
</div>
) : null}
<WorkSwitch view={view} onView={setView} />
{view === "contents" && overview ? (
<div className="stack">
<p className="muted">Überblick über direkte Inhalte und Inhalte der zugeordneten Vorgänge. Herkunft steht an jeder Zeile. Neue Inhalte und die eigene Reihenfolge gelten in der Akte oder im geöffneten Vorgang.</p>
<OrderChoice mode="date" direction={dateDir} onChange={(_mode, next) => setDateDir(next)} />
<ContentBoard
record={{ bindings: merged, chapters: [], content_order: "date", content_order_dir: dateDir, rights: { edit: false }, version: record.version }}
bindings={merged}
sortable={false}
listTitle="Überblick"
containerKind="case"
containerId={id}
onChange={load}
itemHref={(binding) => binding.readerHref}
/>
</div>
</div>
) : null}
{view === "contents" && !overview ? (
<ContentBoard
record={record}
containerKind="case"
containerId={id}
onlyChapter={chapterId}
selectedId={entryId}
listTitle={activeChapter ? activeChapter.title : "Alle Inhalte"}
onOpen={openEntry}
onChange={load}
itemHref={(binding) => {
const search = new URLSearchParams();
search.set("eintrag", binding.id);
if (binding.chapter_id) search.set("kapitel", binding.chapter_id);
return `/cases/${id}?${search}`;
}}
/>
) : null}
{view === "work" ? <WorkLists record={record} context={context} onChange={load} /> : null}
{view === "course" || view === "audit" ? (
<SurfaceView view={view} coursePath={`/api/v1/cases/${id}/course`} auditPath={`/api/v1/cases/${id}/chronology`} />
) : null}
{view === "links" ? (
<div className="stack">
<h2>Zuordnungen</h2>
<p className="muted">Unterakten, Vorgänge und Freigaben dieses Objekts.</p>
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("matter")}>Vorgang anlegen und zuordnen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("assign")}>Vorhandenen Vorgang zuordnen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("subcase")}>Unterakte anlegen</button> : null}
</div>
) : null}
{canEdit && view === "contents" && !overview ? (
<button type="button" className="mobile-add" onClick={() => setModal("add")}>
<NavIcon name="plus" /> Inhalt hinzufügen
</button>
) : null}
</Workspace>
<Modal open={modal === "matter"} title="Vorgang anlegen und zuordnen" onClose={() => setModal("")}>
<NewMatter caseId={id} homeScopeId={record.home_scope_id} onChange={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "assign"} title="Vorhandenen Vorgang zuordnen" onClose={() => setModal("")}>
<AssignMatter caseId={id} onChange={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "add" && Boolean(target)} title={target ? `Hinzufügen in ${target.label}` : "Hinzufügen"} onClose={() => setModal("")}>
<TargetLine label={target?.label} chapters={target?.chapters} chapterId={activeChapter?.id || ""} />
<Modal open={modal === "add"} title={`Hinzufügen in ${targetLabel}`} onClose={() => setModal("")}>
<TargetLine label={targetLabel} chapters={record.chapters} chapterId={activeChapter?.id || ""} />
<div className="add-choices">
<button type="button" onClick={() => setModal("chapter")}>Kapitel</button>
<button type="button" onClick={() => setModal("note")}>Notiz</button>
@@ -426,29 +576,29 @@ export function CaseDetail() {
<button type="button" onClick={() => setModal("mail")}>E-Mail</button>
</div>
</Modal>
<Modal open={modal === "note" && Boolean(target)} title="Notiz" onClose={() => setModal("")}>
<NoteForm context={context} placement={addPlacement} chapters={target?.chapters || []} initialChapter={activeChapter?.id || ""} targetLabel={target?.label || ""} onChange={() => { setModal(""); load(); }} />
<Modal open={modal === "note"} title="Notiz" onClose={() => setModal("")}>
<NoteForm context={context} chapters={record.chapters} initialChapter={activeChapter?.id || ""} targetLabel={targetLabel} onChange={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "file" && Boolean(target)} title="Datei" onClose={() => setModal("")}>
<FileForm context={context} placement={addPlacement} chapters={target?.chapters || []} initialChapter={activeChapter?.id || ""} targetLabel={target?.label || ""} onChange={() => { setModal(""); load(); }} />
<Modal open={modal === "file"} title="Datei" onClose={() => setModal("")}>
<FileForm context={context} chapters={record.chapters} initialChapter={activeChapter?.id || ""} targetLabel={targetLabel} onChange={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "paperless" && Boolean(target)} title="Aus Paperless" onClose={() => setModal("")}>
<PaperlessPicker context={context} placement={addPlacement} chapterId={activeChapter?.id || ""} chapterTitle={activeChapter?.title || ""} targetLabel={target?.label || ""} onDone={() => { setModal(""); load(); }} />
<Modal open={modal === "paperless"} title="Aus Paperless" onClose={() => setModal("")}>
<PaperlessPicker context={context} chapterId={activeChapter?.id || ""} chapterTitle={activeChapter?.title || ""} targetLabel={targetLabel} onDone={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "mail" && Boolean(target)} title="E-Mail verbinden" wide onClose={() => setModal("")}>
<MailPicker context={context} placement={addPlacement} chapterId={activeChapter?.id || ""} chapterTitle={activeChapter?.title || ""} targetLabel={target?.label || ""} onDone={() => { setModal(""); load(); }} />
<Modal open={modal === "mail"} title="E-Mail verbinden" wide onClose={() => setModal("")}>
<MailPicker context={context} chapterId={activeChapter?.id || ""} chapterTitle={activeChapter?.title || ""} targetLabel={targetLabel} onDone={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "subcase"} title="Unterakte anlegen" onClose={() => setModal("")}>
<NewSubcase parentId={id} onChange={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "chapter" && Boolean(target)} title={target ? `Kapitel in ${target.label} hinzufügen` : "Kapitel hinzufügen"} onClose={() => setModal("")}>
<Modal open={modal === "chapter"} title={`Kapitel in ${targetLabel} hinzufügen`} onClose={() => setModal("")}>
<ChapterForm
path={target?.chapterPath || ""}
path={`/api/v1/cases/${id}/chapters`}
onChange={(created) => {
setModal("");
if (created?.id && target) {
if (created?.id) {
pendingChapter.current = created.id;
writeSelection(params, setParams, target.scope, created.id);
writeSelection(params, setParams, "direct", created.id);
}
load();
}}
@@ -457,7 +607,7 @@ export function CaseDetail() {
<Modal open={modal === "share"} title="Teilen" onClose={() => setModal("")}>
<ShareBox path={`/api/v1/cases/${id}/grants`} grants={record.grants || []} onChange={load} />
</Modal>
</main>
</>
);
}
+2
View File
@@ -2,6 +2,7 @@ import { useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { api, applySession } from "../api.js";
import { SessionContext } from "../session.js";
import { Mark } from "./icons.jsx";
export function Login() {
const { setSession } = useContext(SessionContext);
@@ -61,6 +62,7 @@ export function Login() {
return (
<main className="login">
<section className="card login-card">
<p className="login-mark" aria-hidden="true"><Mark size={72} /></p>
<p className="eyebrow">Jinkendo</p>
<h1>Tsumugu</h1>
<p className="lead">Akten, Vorgänge und Fristen an einem Ort. Die erste Lieferung organisiert und verfolgt.</p>
+321 -139
View File
@@ -1,12 +1,15 @@
import { useContext, useEffect, useRef, useState } from "react";
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
import { api, markDirty } from "../api.js";
import { api, isDirty, markDirty } from "../api.js";
import { SessionContext } from "../session.js";
import { Modal } from "./Modal.jsx";
import { MailPicker, PaperlessPicker } from "./Sources.jsx";
import { ErrorNote, ShareBox } from "./widgets.jsx";
import { ChapterForm, FileForm, NoteForm } from "./Cases.jsx";
import { ContentBoard, ObjectMenu, Placements, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, formatDate, matterOpenHref, writeChapter } from "./content.jsx";
import { ContentBoard, ObjectMenu, Placements, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, matterOpenHref, saveChapterOrder, writeChapter } from "./content.jsx";
import { ReadingPane } from "./ReadingPane.jsx";
import { StructureNavigator, Workspace, rememberScroll, restoreScroll, useWorkspaceLayout } from "./workspace.jsx";
import { NavIcon } from "./icons.jsx";
function pageContext(params) {
const kind = params.get("context_kind");
@@ -79,78 +82,99 @@ export function MatterList() {
);
}
function matterTrail(record, chapter, href) {
if (!chapter) return record.trail;
const items = (record.trail || []).map((item, index, all) => (
index === all.length - 1 ? { ...item, href } : item
));
items.push({ label: `Kapitel ${chapter.title}`, href: null });
return items;
function contextQuery(inherited) {
return inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : "";
}
function MatterOutline({ record, inherited, chapterId, onChapter }) {
const matterQuery = inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : "";
const hasParent = Boolean(record.parent_matter_id && record.parent_title);
const hasChildren = Boolean(record.submatters?.length);
const hasCases = Boolean(record.placements?.length);
return (
<nav className="outline-nav" aria-label="Gliederung">
<h2>Gliederung</h2>
<button type="button" className={chapterId ? "hierarchy__row" : "hierarchy__row is-current"} onClick={() => onChapter("")}>
<span className="hierarchy__kind">Überblick</span>
<strong>Alle Inhalte</strong>
</button>
{hasParent ? (
<p className="hierarchy__parent">Übergeordnet: <Link to={`/matters/${record.parent_matter_id}${matterQuery}`}>Vorgang {record.parent_title}</Link></p>
) : null}
{hasCases ? (
<>
<h3>In diesen Akten</h3>
<ul className="hierarchy">
{record.placements.map((link) => (
<li key={link.case_id}>
<Link className="hierarchy__row" to={link.href}>
<span className="hierarchy__kind">Akte</span>
<strong>{link.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "")}</strong>
{link.current ? <span className="muted">aktueller Handlungskontext</span> : null}
</Link>
</li>
))}
</ul>
</>
) : null}
{hasChildren ? (
<>
<h3>Teilvorgänge</h3>
<ul className="hierarchy">
{record.submatters.map((item) => (
<li key={item.id}>
<Link className="hierarchy__row" to={`/matters/${item.id}${matterQuery}`}>
<span className="hierarchy__kind">Teilvorgang</span>
<strong>{item.title}</strong>
</Link>
</li>
))}
</ul>
</>
) : null}
{record.chapters?.length ? (
<>
<h3>Kapitel</h3>
<ul className="hierarchy">
{record.chapters.map((chapter) => (
<li key={chapter.id}>
<button type="button" className={chapterId === chapter.id ? "hierarchy__row is-current" : "hierarchy__row"} onClick={() => onChapter(chapter.id)}>
<span className="hierarchy__kind">Kapitel</span>
<strong>{chapter.title}</strong>
</button>
</li>
))}
</ul>
</>
) : null}
</nav>
);
function mapMatterNodes(nodes, activeId, query) {
return (nodes || []).map((node) => ({
id: node.id,
title: node.title,
kind: node.kind_label || "Vorgang",
href: `/matters/${node.id}${query}`,
current: node.id === activeId,
children: mapMatterNodes(node.children, activeId, query),
}));
}
function caseNodes(caseRecord, parentRecord, activeId, contextId) {
const query = `?context_kind=case&context_id=${contextId}`;
const self = {
id: caseRecord.id,
title: caseRecord.title,
kind: caseRecord.kind_label || "Akte",
href: `/cases/${caseRecord.id}`,
current: false,
children: [
...(caseRecord.subcases || []).map((item) => ({
id: item.id,
title: item.title,
kind: "Unterakte",
href: `/cases/${item.id}`,
current: false,
children: [],
})),
...mapMatterNodes(caseRecord.matters, activeId, query),
],
};
if (!parentRecord) return [self];
const siblings = (parentRecord.subcases || []).map((item) => (item.id === caseRecord.id ? self : {
id: item.id,
title: item.title,
kind: "Unterakte",
href: `/cases/${item.id}`,
current: false,
children: [],
}));
return [{
id: parentRecord.id,
title: parentRecord.title,
kind: "Akte",
href: `/cases/${parentRecord.id}`,
current: false,
children: [
...(siblings.length ? siblings : [self]),
...mapMatterNodes(parentRecord.matters, activeId, `?context_kind=case&context_id=${parentRecord.id}`),
],
}];
}
function loneNodes(record, query) {
const current = {
id: record.id,
title: record.title,
kind: record.kind_label || "Vorgang",
href: null,
current: true,
children: (record.submatters || []).map((item) => ({
id: item.id,
title: item.title,
kind: "Teilvorgang",
href: `/matters/${item.id}${query}`,
current: false,
children: [],
})),
};
if (record.parent_matter_id && record.parent_title) {
return [{
id: record.parent_matter_id,
title: record.parent_title,
kind: "Vorgang",
href: `/matters/${record.parent_matter_id}${query}`,
current: false,
children: [current],
}];
}
return [current];
}
function objectTrail(record, query) {
const items = [{ label: "Vorgänge", href: "/matters" }];
if (record.parent_matter_id && record.parent_title) {
items.push({ label: record.parent_title, href: `/matters/${record.parent_matter_id}${query}` });
}
items.push({ label: record.title, href: null });
return items;
}
export function MatterDetail() {
@@ -164,8 +188,12 @@ export function MatterDetail() {
const rightsContext = inherited || { kind: "matter", id };
const placement = inherited?.kind === "case" ? { kind: "matter", id } : null;
const [view, setView] = useState("contents");
const [outlineOpen, setOutlineOpen] = useState(false);
const { width, structureOpen, setStructureOpen } = useWorkspaceLayout();
const listRef = useRef(null);
const [caseTree, setCaseTree] = useState(null);
const [parentTree, setParentTree] = useState(null);
const pendingChapter = useRef("");
const entryId = params.get("eintrag") || "";
async function load() {
const query = inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : "";
@@ -181,7 +209,7 @@ export function MatterDetail() {
setError("");
setView("contents");
setModal("");
setOutlineOpen(false);
setStructureOpen(false);
const query = inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : "";
api(`/api/v1/matters/${id}${query}`).then((detail) => {
if (!alive) return;
@@ -205,95 +233,249 @@ export function MatterDetail() {
}
}, [record, id, chapterId, params, setParams]);
useEffect(() => {
if (inherited?.kind !== "case") {
setCaseTree(null);
setParentTree(null);
return undefined;
}
let alive = true;
api(`/api/v1/cases/${inherited.id}`).then((detail) => {
if (!alive) return;
setCaseTree(detail);
if (!detail.parent_case_id) {
setParentTree(null);
return;
}
api(`/api/v1/cases/${detail.parent_case_id}`).then((parent) => {
if (alive) setParentTree(parent);
}).catch(() => {
if (alive) setParentTree(null);
});
}).catch(() => {
if (alive) setCaseTree(null);
});
return () => {
alive = false;
};
}, [inherited?.kind, inherited?.id]);
useEffect(() => {
if (!record || record.id !== id || !entryId) return;
const binding = (record.bindings || []).find((item) => item.id === entryId);
if (!binding) return;
const nextChapter = binding.chapter_id || "";
if ((chapterId || "") !== nextChapter) writeChapter(params, setParams, nextChapter);
}, [record, id, entryId, chapterId, params, setParams]);
useEffect(() => {
if (entryId) return;
restoreScroll(listRef.current, `tsumugu-scroll:${id}:${chapterId}`);
}, [entryId, id, chapterId, record]);
function chooseChapter(next) {
writeChapter(params, setParams, next);
const updated = new URLSearchParams(params);
if (next) updated.set("kapitel", next);
else updated.delete("kapitel");
updated.delete("eintrag");
updated.delete("bereich");
setParams(updated);
setView("contents");
setOutlineOpen(false);
setStructureOpen(false);
}
function openEntry(binding) {
rememberScroll(listRef.current, `tsumugu-scroll:${id}:${chapterId}`);
const updated = new URLSearchParams(params);
updated.set("eintrag", binding.id);
if (binding.chapter_id) updated.set("kapitel", binding.chapter_id);
else updated.delete("kapitel");
setParams(updated);
setView("contents");
}
function closeEntry() {
const updated = new URLSearchParams(params);
updated.delete("eintrag");
setParams(updated, { replace: true });
}
function switchContext(caseId) {
if (caseId === (inherited?.id || "")) return;
if (isDirty() && !window.confirm("Ungespeicherte Eingaben verwerfen und den Aktenkontext wechseln?")) return;
const updated = new URLSearchParams();
if (caseId) {
updated.set("context_kind", "case");
updated.set("context_id", caseId);
}
setParams(updated);
setStructureOpen(false);
}
async function moveChapter(chapterIdToMove, delta) {
const ids = (record?.chapters || []).map((chapter) => chapter.id);
const index = ids.indexOf(chapterIdToMove);
const target = index + delta;
if (!record || index < 0 || target < 0 || target >= ids.length) return;
const [moved] = ids.splice(index, 1);
ids.splice(target, 0, moved);
try {
await saveChapterOrder({ containerKind: "matter", containerId: id, record, context: inherited, ids });
await load();
} catch (err) {
setError(err.message);
}
}
if (error && !record) return <main className="page"><ErrorNote error={error} /></main>;
if (!record) return <main className="page"><p className="muted">Vorgang wird geladen …</p></main>;
const query = inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : "";
const query = contextQuery(inherited);
const targetLabel = `${record.kind_label || "Vorgang"} ${record.title}`;
const activeChapter = (record.chapters || []).find((chapter) => chapter.id === chapterId) || null;
const canEdit = Boolean(record.rights?.edit);
const chapters = (record.chapters || []).map((chapter) => ({
...chapter,
count: (record.bindings || []).filter((item) => item.chapter_id === chapter.id).length,
}));
const contexts = (record.placements || []).map((item) => ({
id: item.case_id,
label: item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / "),
}));
const contextValue = inherited?.kind === "case" ? inherited.id : (contexts.length === 1 ? contexts[0].id : "");
const nodes = caseTree ? caseNodes(caseTree, parentTree, id, inherited.id) : loneNodes(record, query);
const links = [
...(record.cross_links || []).map((item) => ({
id: `cross-${item.id}`,
title: item.title,
kind: "Querverweis",
href: `/matters/${item.matter_id}${query}`,
})),
...(record.case_links || []).filter((item) => item.case_id !== inherited?.id).map((item) => ({
id: `case-${item.id}`,
title: item.title,
kind: "Weitere Akte",
href: `/cases/${item.case_id}`,
})),
];
const entry = (record.bindings || []).find((item) => item.id === entryId) || null;
const scrollKey = `tsumugu-scroll:${id}:${chapterId}`;
return (
<main className="page">
<header className="page-head">
<>
<Workspace
width={width}
structureOpen={structureOpen}
setStructureOpen={setStructureOpen}
hasEntry={Boolean(entryId)}
listRef={listRef}
nav={(
<StructureNavigator
contexts={contexts.length > 1 && !inherited ? [{ id: "", label: "Keine Akte gewählt" }, ...contexts] : contexts}
contextValue={contextValue}
onContext={contexts.length > 1 ? switchContext : null}
nodes={nodes}
chapters={chapters}
chapterId={chapterId}
allCount={(record.bindings || []).length}
chapterHeading={`Kapitel in ${record.title}`}
onChapter={chooseChapter}
onAddChapter={canEdit ? () => setModal("chapter") : null}
canAddChapter={canEdit}
onMoveChapter={moveChapter}
canReorder={canEdit && chapters.length > 1}
links={links}
onNavigate={() => setStructureOpen(false)}
onClose={width < 1500 ? () => setStructureOpen(false) : null}
/>
)}
reader={entryId ? (
<ReadingPane
binding={entry}
context={rightsContext}
backLabel={activeChapter?.title || "Alle Inhalte"}
onClose={closeEntry}
onReload={load}
canDetach={canEdit}
canDestroy={Boolean(record.is_owner)}
/>
) : null}
>
<header className="workspace-head">
<div>
<Trail items={matterTrail(record, activeChapter, `/matters/${id}${query}`)} />
<Trail items={objectTrail(record, query)} />
<Placements items={record.placements} />
<p className="eyebrow">{record.kind_label || "Vorgang"} · {record.home_scope_name}</p>
<h1>{record.title}</h1>
<p className="muted">{record.status === "open" ? "Offen" : "Geschlossen"}</p>
<div className="title-row">
<h1>{record.title}</h1>
<span className={record.status === "open" ? "status-pill" : "status-pill is-closed"}>{record.status === "open" ? "Offen" : "Geschlossen"}</span>
</div>
</div>
<div className="page-actions">
{canEdit ? <button type="button" onClick={() => setModal("add")}>Inhalt hinzufügen</button> : null}
{width < 1500 ? <button type="button" className="quiet" onClick={() => setStructureOpen(true)}>Struktur</button> : null}
{canEdit ? (
<button type="button" className="desktop-add" onClick={() => setModal("add")}>
<NavIcon name="plus" /> Inhalt hinzufügen
</button>
) : null}
<ObjectMenu view={view} onView={setView}>
{canEdit ? <button type="button" className="quiet" onClick={() => setModal("submatter")}>Teilvorgang anlegen</button> : null}
{canEdit ? <button type="button" className="quiet" onClick={() => setModal("cross")}>Querverweis</button> : null}
{record.rights.share || record.is_owner ? <button type="button" className="quiet" onClick={() => setModal("share")}>Teilen</button> : null}
</ObjectMenu>
{!canEdit ? <p className="muted">In {targetLabel} fehlt das Bearbeitungsrecht.</p> : null}
</div>
</header>
{!canEdit ? <p className="muted">In {targetLabel} fehlt das Bearbeitungsrecht.</p> : null}
<ErrorNote error={error} />
<div className="record-layout">
<aside className={outlineOpen ? "outline is-open" : "outline"}>
<button type="button" className="outline__toggle" onClick={() => setOutlineOpen((open) => !open)}>{outlineOpen ? "Bereiche schließen" : "Bereiche"}</button>
<div className="outline__body">
<MatterOutline record={record} inherited={inherited} chapterId={chapterId} onChapter={chooseChapter} />
</div>
</aside>
<div className="record-main">
<WorkSwitch view={view} onView={setView} />
{view === "contents" ? (
<>
<p className="target-line">
Bearbeitet wird <strong>{targetLabel}</strong>
{activeChapter ? <> · Kapitel <strong>{activeChapter.title}</strong></> : null}
</p>
<ContentBoard
record={record}
context={inherited}
containerKind="matter"
containerId={id}
onlyChapter={chapterId}
onChange={load}
itemHref={(binding) => {
const search = new URLSearchParams(query.replace(/^\?/, ""));
if (chapterId) search.set("kapitel", chapterId);
const next = search.toString();
return `/matters/${id}/items/${binding.id}${next ? `?${next}` : ""}`;
}}
/>
</>
) : null}
{view === "work" ? (
<div className="stack">
{record.rights.edit ? <button type="button" onClick={() => setModal("work")}>Aufgabe oder Frist</button> : null}
<WorkLists record={record} context={inherited} onChange={load} />
</div>
) : null}
{view === "course" || view === "audit" ? (
<SurfaceView view={view} coursePath={`/api/v1/matters/${id}/course${query}`} auditPath={`/api/v1/matters/${id}/chronology${query}`} />
) : null}
{view === "links" ? (
<div className="stack">
<h2>Zuordnungen</h2>
{record.case_links?.length ? record.case_links.map((item) => (
<p key={item.id}><Link to={`/cases/${item.case_id}`}>Akte {item.title}</Link></p>
)) : <p className="muted">Noch keiner Akte zugeordnet.</p>}
{record.cross_links?.length ? record.cross_links.map((item) => (
<p key={item.id}>Querverweis <Link to={matterOpenHref({ id: item.matter_id, contexts: [] })}>{item.title}</Link></p>
)) : <p className="muted">Kein Querverweis.</p>}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("cross")}>Querverweis</button> : null}
</div>
) : null}
<WorkSwitch view={view} onView={setView} />
{view === "contents" ? (
<ContentBoard
record={record}
context={inherited}
containerKind="matter"
containerId={id}
onlyChapter={chapterId}
selectedId={entryId}
listTitle={activeChapter ? activeChapter.title : "Alle Inhalte"}
onOpen={(binding) => {
rememberScroll(listRef.current, scrollKey);
openEntry(binding);
}}
onChange={load}
itemHref={(binding) => {
const search = new URLSearchParams(query.replace(/^\?/, ""));
search.set("eintrag", binding.id);
if (binding.chapter_id) search.set("kapitel", binding.chapter_id);
return `/matters/${id}?${search}`;
}}
/>
) : null}
{view === "work" ? (
<div className="stack">
{record.rights.edit ? <button type="button" onClick={() => setModal("work")}>Aufgabe oder Frist</button> : null}
<WorkLists record={record} context={inherited} onChange={load} />
</div>
</div>
) : null}
{view === "course" || view === "audit" ? (
<SurfaceView view={view} coursePath={`/api/v1/matters/${id}/course${query}`} auditPath={`/api/v1/matters/${id}/chronology${query}`} />
) : null}
{view === "links" ? (
<div className="stack">
<h2>Zuordnungen</h2>
{record.case_links?.length ? record.case_links.map((item) => (
<p key={item.id}><Link to={`/cases/${item.case_id}`}>Akte {item.title}</Link></p>
)) : <p className="muted">Noch keiner Akte zugeordnet.</p>}
{record.cross_links?.length ? record.cross_links.map((item) => (
<p key={item.id}>Querverweis <Link to={matterOpenHref({ id: item.matter_id, contexts: [] })}>{item.title}</Link></p>
)) : <p className="muted">Kein Querverweis.</p>}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("cross")}>Querverweis</button> : null}
</div>
) : null}
{canEdit && view === "contents" ? (
<button type="button" className="mobile-add" onClick={() => setModal("add")}>
<NavIcon name="plus" /> Inhalt hinzufügen
</button>
) : null}
</Workspace>
<Modal open={modal === "work"} title="Aufgabe oder Frist" onClose={() => setModal("")}>
<WorkForms matterId={id} context={inherited} tasks={record.tasks} onChange={() => { setModal(""); load(); }} />
</Modal>
@@ -341,7 +523,7 @@ export function MatterDetail() {
<Modal open={modal === "share"} title="Teilen" onClose={() => setModal("")}>
<ShareBox path={`/api/v1/matters/${id}/grants`} grants={record.grants || []} onChange={load} />
</Modal>
</main>
</>
);
}
+11 -3
View File
@@ -1,7 +1,10 @@
import { useEffect } from "react";
import { useEffect, useRef } from "react";
import { isDirty, markDirty } from "../api.js";
export function Modal({ open, title, onClose, wide = false, children }) {
const dialogRef = useRef(null);
const restoreRef = useRef(null);
function requestClose() {
if (isDirty() && !window.confirm("Ungespeicherte Eingaben verwerfen?")) return;
markDirty(false);
@@ -10,6 +13,10 @@ export function Modal({ open, title, onClose, wide = false, children }) {
useEffect(() => {
if (!open) return undefined;
restoreRef.current = document.activeElement;
const node = dialogRef.current;
const focusable = node?.querySelector("input, textarea, select, button");
(focusable || node)?.focus();
function onKey(event) {
if (event.key === "Escape") requestClose();
}
@@ -19,13 +26,14 @@ export function Modal({ open, title, onClose, wide = false, children }) {
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = previous;
restoreRef.current?.focus?.();
};
}, [open, onClose]);
}, [open]);
if (!open) return null;
return (
<div className="modal-overlay" onClick={(event) => { if (event.target === event.currentTarget) requestClose(); }}>
<div className={wide ? "modal modal--wide" : "modal"} role="dialog" aria-modal="true" aria-label={title}>
<div ref={dialogRef} className={wide ? "modal modal--wide" : "modal"} role="dialog" aria-modal="true" aria-label={title} tabIndex={-1}>
<header className="modal__bar">
<h2>{title}</h2>
<button type="button" className="quiet" onClick={requestClose}>Schließen</button>
+4 -287
View File
@@ -1,294 +1,11 @@
import { useEffect, useState } from "react";
import { Link, useLocation, useNavigate, useParams, useSearchParams } from "react-router-dom";
import { api, documentToText, fetchFile, fetchPaperless, markDirty, textToDocument } from "../api.js";
import { ErrorNote } from "./widgets.jsx";
import { formatDate, kindLabel, Trail } from "./content.jsx";
function pageContext(params) {
const kind = params.get("context_kind");
const id = params.get("context_id");
if (!kind || !id || kind === "direct") return null;
return { kind, id };
}
function returnHref(kind, id, params) {
const bereich = params.get("bereich");
const kapitel = params.get("kapitel");
const contextKind = params.get("context_kind");
const contextId = params.get("context_id");
if (kind === "matters" && bereich && contextKind === "case" && contextId) {
const search = new URLSearchParams();
search.set("bereich", bereich);
if (kapitel) search.set("kapitel", kapitel);
return `/cases/${contextId}?${search}`;
}
const search = new URLSearchParams();
if (kind === "matters" && contextKind && contextId && contextKind !== "direct") {
search.set("context_kind", contextKind);
search.set("context_id", contextId);
}
if (kind === "cases" && bereich) search.set("bereich", bereich);
if (kapitel) search.set("kapitel", kapitel);
const query = search.toString();
return `/${kind}/${id}${query ? `?${query}` : ""}`;
}
import { Navigate, useLocation, useParams, useSearchParams } from "react-router-dom";
export function Reader() {
const location = useLocation();
const kind = location.pathname.startsWith("/cases") ? "cases" : "matters";
const { id, bindingId } = useParams();
const [params] = useSearchParams();
const inherited = pageContext(params);
const [record, setRecord] = useState(null);
const [error, setError] = useState("");
const [previewUrl, setPreviewUrl] = useState("");
const [text, setText] = useState("");
const [note, setNote] = useState("");
const [documentOn, setDocumentOn] = useState("");
const [summary, setSummary] = useState("");
const [previewKind, setPreviewKind] = useState("");
const [notice, setNotice] = useState("");
const navigate = useNavigate();
const context = kind === "cases" ? { kind: "case", id } : (inherited || { kind: "matter", id });
const query = kind === "matters" && inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : "";
async function load() {
const detail = await api(`/api/v1/${kind}/${id}${query}`);
const pools = [...(detail.bindings || [])];
for (const group of detail.contained || []) pools.push(...group.bindings);
const binding = pools.find((item) => item.id === bindingId);
if (!binding) {
setRecord(detail);
setError("Diese Unterlage ist in dieser Ansicht nicht sichtbar.");
return;
}
setRecord({ ...detail, binding });
setText(binding.element.kind === "note" ? documentToText(binding.element.document) : "");
setDocumentOn(binding.element.dates?.document_on || "");
setSummary(binding.element.summary || "");
setError("");
}
useEffect(() => {
setRecord(null);
setPreviewUrl((current) => {
if (current) URL.revokeObjectURL(current);
return "";
});
load().catch((err) => setError(err.message));
}, [kind, id, bindingId, query]);
useEffect(() => () => {
if (previewUrl) URL.revokeObjectURL(previewUrl);
}, [previewUrl]);
useEffect(() => {
const element = record?.binding?.element;
if (!element || element.kind === "note") return undefined;
if (!element.preview?.available) return undefined;
let alive = true;
const load = element.kind === "external_ref" ? fetchPaperless(element.id, context) : fetchFile(element.id, context);
load.then((blob) => {
if (!alive) return;
const next = URL.createObjectURL(blob);
setPreviewUrl((current) => {
if (current) URL.revokeObjectURL(current);
return next;
});
if (blob.type.startsWith("image/")) setPreviewKind("image");
else if (blob.type.includes("pdf")) setPreviewKind("pdf");
else setPreviewKind("other");
}).catch((err) => {
if (alive) setError(err.message);
});
return () => {
alive = false;
};
}, [record?.binding?.id]);
if (error && !record?.binding) {
return <main className="page"><ErrorNote error={error} /><p><Link to={returnHref(kind, id, params)}>Zurück</Link></p></main>;
}
if (!record?.binding) return <main className="page"><p className="muted">Unterlage wird geladen …</p></main>;
const binding = record.binding;
const element = binding.element;
const back = returnHref(kind, id, params);
async function openFile() {
setError("");
try {
const blob = element.kind === "external_ref"
? await fetchPaperless(element.id, context)
: await fetchFile(element.id, context);
if (previewUrl) URL.revokeObjectURL(previewUrl);
setPreviewUrl(URL.createObjectURL(blob));
} catch (err) {
setError(err.message);
}
}
async function saveNote(event) {
event.preventDefault();
setError("");
try {
const updated = await api(`/api/v1/notes/${element.id}`, {
method: "PATCH",
body: { expected_version: element.version, document: textToDocument(text), context },
});
markDirty(false);
setNotice(updated.notice || "Der gemeinsame Text ist gespeichert.");
load();
} catch (err) {
setError(err.message);
}
}
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);
load();
} 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: element.dates?.sent_on || null,
received_on: element.dates?.received_on || null,
context,
},
});
markDirty(false);
load();
} catch (err) {
setError(err.message);
}
}
async function annotate(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);
load();
} 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);
await api(`/api/v1/bindings/${binding.id}?${search}`, { method: "DELETE" });
navigate(back);
}
async function destroy() {
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 } });
navigate(back);
}
return (
<main className="page reader">
<Trail items={[...(record.trail || []).map((item, index, all) => (index === all.length - 1 ? { ...item, href: back } : item)), { label: element.title, href: null }]} />
<p><Link to={back}>{kind === "cases" ? "Zurück zur Akte" : "Zurück zum Vorgang"}</Link></p>
<header className="page-head">
<div>
<p className="eyebrow">{kindLabel(element.kind)}</p>
<h1>{element.title}</h1>
<p className="muted">Fachliches Datum: {formatDate(element.dates?.document_on)}</p>
</div>
</header>
<ErrorNote error={error} />
{element.kind === "note" ? (
<form className="stack" onSubmit={saveNote}>
<label>
Gemeinsamer Text
<textarea rows={8} value={text} disabled={!binding.rights.edit} onChange={(event) => { setText(event.target.value); markDirty(true); }} />
</label>
<p className="muted">Diese Änderung betrifft den gemeinsamen Inhalt der Notiz.</p>
{notice ? <p className="notice">{notice}</p> : null}
{binding.rights.edit ? <button type="submit">Text speichern</button> : <p className="muted">In diesem Kontext nur lesbar.</p>}
</form>
) : previewUrl && previewKind === "image" ? (
<img className="reader-preview" alt={element.title} src={previewUrl} />
) : previewUrl ? (
<iframe className="preview" title={element.title} src={previewUrl} />
) : (
<div className="stack">
<p className="muted">{element.preview?.available ? "Vorschau wird geladen …" : "Für diesen Typ gibt es keine eingebaute Vorschau."}</p>
<button type="button" onClick={openFile}>{element.kind === "external_ref" ? "Paperless öffnen" : "Datei öffnen"}</button>
</div>
)}
{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>
) : element.summary ? <p>{element.summary}</p> : null}
{binding.rights.edit ? (
<form className="stack" onSubmit={saveDate}>
<label>
{element.kind === "note" ? "Bezugsdatum, optional" : "Dokumentdatum, optional"}
<input type="date" value={documentOn} onChange={(event) => { setDocumentOn(event.target.value); markDirty(true); }} />
</label>
<button type="submit" className="quiet">Datum speichern</button>
</form>
) : null}
<section className="section">
<h2>Anmerkung in diesem Zusammenhang</h2>
<p className="muted">Die Anmerkung gilt nur hier, nicht für den gemeinsamen Inhalt.</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={annotate}>
<label>
Neue Anmerkung
<textarea rows={3} value={note} onChange={(event) => { setNote(event.target.value); markDirty(true); }} required />
</label>
<button type="submit" className="quiet">Anmerkung speichern</button>
</form>
) : null}
</section>
<details className="fold">
<summary>Weitere Aktionen</summary>
<div className="row">
{record.rights?.edit ? <button type="button" className="quiet" onClick={detach}>Aus diesem Zusammenhang entfernen</button> : null}
{record.is_owner ? <button type="button" className="danger" onClick={destroy}>Überall löschen</button> : null}
</div>
</details>
</main>
);
const next = new URLSearchParams(params);
next.set("eintrag", bindingId);
return <Navigate to={`/${kind}/${id}?${next.toString()}`} replace />;
}
+382
View File
@@ -0,0 +1,382 @@
import { useEffect, useRef, useState } from "react";
import { documentToText, fetchFile, fetchPaperless, markDirty, textToDocument, api } from "../api.js";
import { ErrorNote } from "./widgets.jsx";
import { formatDate, kindLabel } from "./content.jsx";
import { NavIcon } from "./icons.jsx";
import workerSrc from "pdfjs-dist/build/pdf.worker.min.mjs?url";
const SCALES = [0.75, 1, 1.25, 1.5, 2];
export function ReadingPane({ binding, context, backLabel, onClose, onReload, canDetach, canDestroy }) {
const element = binding?.element;
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 [note, setNote] = useState("");
const [summary, setSummary] = useState("");
const [documentOn, setDocumentOn] = useState("");
const [notice, setNotice] = useState("");
const [annotate, setAnnotate] = useState(false);
const canvasRef = useRef(null);
const closeRef = useRef(null);
useEffect(() => {
closeRef.current?.focus();
}, [binding?.id]);
useEffect(() => {
if (!element) return undefined;
setText(element.kind === "note" ? documentToText(element.document) : "");
setDocumentOn(element.dates?.document_on || "");
setSummary(element.summary || "");
setError("");
setNotice("");
setPage(1);
setPdf(null);
setPages(0);
setMedia("");
setPhase(element.kind === "note" ? "ready" : element.preview?.available ? "loading" : "missing");
return undefined;
}, [element?.id, element?.version]);
useEffect(() => {
if (!element || element.kind === "note" || !element.preview?.available) return undefined;
let alive = true;
let url = "";
setPhase("loading");
const load = element.kind === "external_ref" ? fetchPaperless(element.id, context) : fetchFile(element.id, context);
load.then(async (blob) => {
if (!alive) 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");
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?.preview?.available, 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 viewport = pdfPage.getViewport({ scale });
const canvas = canvasRef.current;
const context2d = canvas.getContext("2d");
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 openOriginal() {
setError("");
try {
const blob = element.kind === "external_ref"
? await fetchPaperless(element.id, context)
: await fetchFile(element.id, context);
const url = URL.createObjectURL(blob);
window.open(url, "_blank", "noopener");
setTimeout(() => URL.revokeObjectURL(url), 60000);
} catch (err) {
setError(err.message);
}
}
async function saveNote(event) {
event.preventDefault();
setError("");
try {
const updated = await api(`/api/v1/notes/${element.id}`, {
method: "PATCH",
body: { expected_version: element.version, document: textToDocument(text), context },
});
markDirty(false);
setNotice(updated.notice || "Der gemeinsame Text ist gespeichert.");
onReload();
} catch (err) {
setError(err.message);
}
}
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 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: element.dates?.sent_on || null,
received_on: element.dates?.received_on || 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);
await api(`/api/v1/bindings/${binding.id}?${search}`, { method: "DELETE" });
onClose();
onReload();
}
async function destroy() {
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 } });
onClose();
onReload();
}
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 typeLabel = element.kind === "file" && element.file?.content_type === "application/pdf"
? "PDF"
: element.kind === "external_ref"
? (element.external?.source === "imap" ? "E-Mail" : kindLabel(element.kind))
: kindLabel(element.kind);
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">
<h2>{element.title}</h2>
<p>{formatDate(element.dates?.document_on)} · {typeLabel}</p>
</div>
<div className="reader-pane__tools">
{element.kind !== "note" ? (
<button type="button" className="icon-button" aria-label="Original öffnen" onClick={openOriginal}>
<NavIcon name="link" />
</button>
) : null}
<button ref={closeRef} type="button" className="icon-button" aria-label="Leser schließen" onClick={onClose}>
<NavIcon name="close" />
</button>
</div>
</header>
<div className="reader-pane__stage">
<ErrorNote error={error} />
{element.kind === "note" ? (
<form className="reader-note" onSubmit={saveNote}>
<label>
Gemeinsamer Text
<textarea rows={12} value={text} disabled={!binding.rights.edit} onChange={(event) => { setText(event.target.value); markDirty(true); }} />
</label>
<p className="muted">Diese Änderung betrifft den gemeinsamen Inhalt der Notiz, nicht die hiesige Anmerkung.</p>
{notice ? <p className="notice">{notice}</p> : null}
{binding.rights.edit ? <button type="submit">Text speichern</button> : <p className="muted">In diesem Kontext nur lesbar.</p>}
</form>
) : null}
{phase === "loading" ? <p className="reader-pane__state">Vorschau wird geladen …</p> : null}
{phase === "missing" ? (
<div className="reader-pane__state">
<p>Für diesen Inhalt gibt es keine eingebaute Vorschau.</p>
<button type="button" onClick={openOriginal}>Original öffnen</button>
</div>
) : null}
{phase === "error" ? (
<div className="reader-pane__state">
<p>Die Vorschau ist nicht verfügbar.</p>
<button type="button" onClick={openOriginal}>Original öffnen</button>
</div>
) : null}
{media === "image" && blobUrl ? (
<img className="reader-image" alt={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={element.title} src={blobUrl} /> : null}
{media === "other" && blobUrl ? (
<div className="reader-pane__state">
<p>Die Datei ist geladen, aber hier nicht als Seite darstellbar.</p>
<a href={blobUrl} target="_blank" rel="noreferrer">Original öffnen</a>
</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"}
<input type="date" value={documentOn} onChange={(event) => { setDocumentOn(event.target.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>
);
}
+8 -2
View File
@@ -46,8 +46,14 @@ function Result({ item }) {
if (item.kind === "matter") return <Link to={matterOpenHref(item)}>{item.title}</Link>;
const context = item.contexts?.[0];
if (!context) return <span>{item.title}</span>;
if (context.kind === "case") return <Link to={`/cases/${context.id}`}>{item.title}</Link>;
return <Link to={`/matters/${context.id}`}>{item.title}</Link>;
const search = new URLSearchParams();
if (context.binding_id) search.set("eintrag", context.binding_id);
if (context.chapter_id) search.set("kapitel", context.chapter_id);
const query = search.toString();
if (context.kind === "case") {
return <Link to={`/cases/${context.id}${query ? `?${query}` : ""}`}>{item.title}</Link>;
}
return <Link to={`/matters/${context.id}${query ? `?${query}` : ""}`}>{item.title}</Link>;
}
function label(kind) {
+117 -66
View File
@@ -1,110 +1,161 @@
import { useContext, useState } from "react";
import { NavLink, Outlet, useNavigate } from "react-router-dom";
import { useContext, useEffect, useState } from "react";
import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
import { SessionContext } from "../session.js";
import { Mark, NavIcon } from "./icons.jsx";
const NAV_KEY = "tsumugu-nav-expanded";
const WORK = [
{ to: "/", end: true, label: "Übersicht", icon: "home" },
{ to: "/matters", label: "Vorgänge", icon: "layers" },
{ to: "/cases", label: "Akten", icon: "folder" },
{ to: "/work", label: "Aufgaben", icon: "check" },
{ to: "/", end: true, label: "Übersicht", short: "Start", icon: "home" },
{ to: "/matters", label: "Vorgänge", short: "Vorgänge", icon: "layers" },
{ to: "/cases", label: "Akten", short: "Akten", icon: "folder" },
{ to: "/work", label: "Aufgaben", short: "Aufgaben", icon: "check" },
];
const ADMIN = [
{ to: "/settings", label: "Verwaltung", icon: "rooms" },
];
function initials(name) {
const parts = String(name || "").trim().split(/\s+/).filter(Boolean);
if (!parts.length) return "·";
return parts.slice(0, 2).map((part) => part[0]).join("").toUpperCase();
}
export function Shell() {
const { session, logout } = useContext(SessionContext);
const navigate = useNavigate();
const location = useLocation();
const [expanded, setExpanded] = useState(() => {
try {
return localStorage.getItem(NAV_KEY) !== "0";
} catch {
return true;
}
});
const [query, setQuery] = useState("");
const items = [...WORK, ...ADMIN];
const [more, setMore] = useState(false);
const [width, setWidth] = useState(() => window.innerWidth);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
useEffect(() => {
setMore(false);
}, [location.pathname]);
const forcedCompact = width < 1180;
const compact = forcedCompact || !expanded;
function toggleNav() {
setExpanded((value) => {
const next = !value;
try {
localStorage.setItem(NAV_KEY, next ? "1" : "0");
} catch {
/* Die Breite bleibt auch ohne gespeicherte Präferenz bedienbar. */
}
return next;
});
}
function onSearch(event) {
event.preventDefault();
const term = query.trim();
if (term.length < 2) return;
navigate(`/search?q=${encodeURIComponent(term)}`);
setQuery("");
}
return (
<div className="app-shell">
<aside className="desktop-sidebar" aria-label="Hauptnavigation">
<div className="desktop-sidebar__brand">
<div className="desktop-sidebar__logo" aria-hidden="true" />
<div className="desktop-sidebar__title">Tsumugu</div>
<div className={`app-shell${compact ? " is-compact" : ""}`}>
<aside className="rail" aria-label="Hauptnavigation">
<div className="rail__brand">
<Mark />
<span className="rail__name">Tsumugu</span>
</div>
<nav className="desktop-sidebar__nav">
{items.map((item) => (
<NavLink key={item.to} to={item.to} end={item.end} className={({ isActive }) => `desktop-sidebar__link${isActive ? " active" : ""}`}>
<button
type="button"
className="rail__toggle"
aria-expanded={!compact}
aria-label={compact ? "Navigation ausklappen" : "Navigation einklappen"}
onClick={toggleNav}
disabled={forcedCompact}
title={forcedCompact ? "Bei dieser Breite bleibt die Navigation kompakt" : undefined}
>
<NavIcon name="menu" />
</button>
<nav className="rail__nav">
{WORK.map((item) => (
<NavLink key={item.to} to={item.to} end={item.end} className={({ isActive }) => `rail__link${isActive ? " active" : ""}`} aria-label={item.label}>
<NavIcon name={item.icon} />
<span>{item.label}</span>
<span className="rail__label">{item.label}</span>
</NavLink>
))}
</nav>
<div className="desktop-sidebar__footer">
<div className="desktop-sidebar__user-text">
<span className="desktop-sidebar__user-name">{session.account.display_name}</span>
<div className="rail__foot">
<form className="rail__search" onSubmit={onSearch}>
<label className="visually-hidden" htmlFor="rail-search">Suchen</label>
<input id="rail-search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Suchen" />
</form>
{compact ? (
<button type="button" className="rail__link rail__button" aria-label="Suchen" onClick={() => { if (forcedCompact) navigate("/search"); else toggleNav(); }}>
<NavIcon name="search" />
</button>
) : null}
<NavLink to="/settings" className={({ isActive }) => `rail__link${isActive ? " active" : ""}`} aria-label="Verwaltung">
<NavIcon name="gear" />
<span className="rail__label">Verwaltung</span>
</NavLink>
<div className="rail__user">
<span className="avatar" title={session.account.display_name}>{initials(session.account.display_name)}</span>
<span className="rail__user-name">{session.account.display_name}</span>
<button type="button" className="icon-button rail__logout" aria-label="Abmelden" onClick={logout}>
<NavIcon name="logout" />
</button>
</div>
<button type="button" className="desktop-sidebar__logout" onClick={logout} title="Abmelden">
<NavIcon name="logout" />
</button>
</div>
</aside>
<div className="app-shell__column">
<header className="app-header">
<div className="app-header__bar mobile-only">
<NavLink to="/" className="app-logo">Tsumugu</NavLink>
<button type="button" className="quiet" onClick={logout}>Abmelden</button>
</div>
<header className="app-header mobile-only">
<NavLink to="/" className="app-logo" aria-label="Tsumugu">
<Mark size={28} />
<span>Tsumugu</span>
</NavLink>
<form className="search" onSubmit={onSearch}>
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Suchen"
aria-label="Suchen"
/>
<button type="submit">Suchen</button>
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Suchen" aria-label="Suchen" />
</form>
</header>
<div className="app-main">
<Outlet />
</div>
<nav className="bottom-nav" aria-label="Hauptnavigation">
{[...WORK, ADMIN[0]].map((item) => (
{WORK.map((item) => (
<NavLink key={item.to} to={item.to} end={item.end} className={({ isActive }) => `nav-item${isActive ? " active" : ""}`}>
<NavIcon name={item.icon} />
<span>{item.label}</span>
<span>{item.short}</span>
</NavLink>
))}
<button type="button" className={`nav-item${more ? " active" : ""}`} onClick={() => setMore(true)}>
<NavIcon name="more" />
<span>Mehr</span>
</button>
</nav>
{more ? (
<div className="modal-overlay" onClick={(event) => { if (event.target === event.currentTarget) setMore(false); }}>
<div className="sheet" role="dialog" aria-modal="true" aria-label="Weitere Ziele">
<header className="modal__bar">
<h2>Mehr</h2>
<button type="button" className="quiet" onClick={() => setMore(false)}>Schließen</button>
</header>
<div className="menu-list">
<NavLink to="/settings" onClick={() => setMore(false)}>Verwaltung</NavLink>
<NavLink to="/search" onClick={() => setMore(false)}>Suche</NavLink>
<button type="button" className="quiet" onClick={logout}>Abmelden</button>
</div>
</div>
</div>
) : null}
</div>
</div>
);
}
function NavIcon({ name }) {
const common = { width: 20, height: 20, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true };
if (name === "home") {
return <svg {...common}><path d="M4 10.5 12 4l8 6.5V20a1 1 0 0 1-1 1h-5v-6H10v6H5a1 1 0 0 1-1-1z" /></svg>;
}
if (name === "folder") {
return <svg {...common}><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /></svg>;
}
if (name === "layers") {
return <svg {...common}><path d="m12 3 9 5-9 5-9-5z" /><path d="m3 12 9 5 9-5" /><path d="m3 17 9 5 9-5" /></svg>;
}
if (name === "sources") {
return <svg {...common}><path d="M4 7h16" /><path d="M4 12h10" /><path d="M4 17h16" /><path d="M18 10v4" /></svg>;
}
if (name === "users") {
return <svg {...common}><circle cx="12" cy="8" r="3" /><path d="M5 19c1.2-2.4 3.4-3.5 7-3.5s5.8 1.1 7 3.5" /></svg>;
}
if (name === "check") {
return <svg {...common}><path d="M8 12h8" /><path d="M8 7h8" /><path d="M8 17h5" /><path d="M4 7.5 5.2 9 8 6" /></svg>;
}
if (name === "logout") {
return <svg {...common}><path d="M9 6H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h4" /><path d="M14 16l4-4-4-4" /><path d="M18 12H9" /></svg>;
}
return <svg {...common}><path d="M4 8h16M4 12h16M4 16h10" /></svg>;
}
+93 -19
View File
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import workerSrc from "pdfjs-dist/build/pdf.worker.min.mjs?url";
import { api, fetchFile, fetchPaperless } from "../api.js";
import { Modal } from "./Modal.jsx";
import { ErrorNote } from "./widgets.jsx";
@@ -180,7 +181,7 @@ export function Placements({ items }) {
{items.map((item, index) => (
<span key={item.case_id}>
{index ? <span aria-hidden="true"> · </span> : null}
<Link to={item.href} aria-current={item.current ? "true" : undefined}>{item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "")}</Link>
<Link to={item.href} aria-current={item.current ? "true" : undefined}>{item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / ")}</Link>
</span>
))}
{current ? <span className="muted"> · aktueller Handlungskontext</span> : <span className="muted"> · Handlungskontext direkt, solange keine Akte gewählt ist</span>}
@@ -196,7 +197,7 @@ export function ObjectMenu({ view, onView, children }) {
}
return (
<>
<button type="button" className="quiet" onClick={() => setOpen(true)}>Aktionen</button>
<button type="button" className="icon-button" aria-label="Aktionen" onClick={() => setOpen(true)}>⋯</button>
<Modal open={open} title="Aktionen" onClose={() => setOpen(false)}>
<div className="menu-list" onClick={() => setOpen(false)}>
<button type="button" className={view === "course" ? "" : "quiet"} onClick={() => choose("course")}>Fachlicher Verlauf</button>
@@ -211,7 +212,7 @@ export function ObjectMenu({ view, onView, children }) {
export function WorkSwitch({ view, onView }) {
return (
<div className="order-bar" role="tablist" aria-label="Arbeitsfläche">
<div className="surface-tabs" role="tablist" aria-label="Arbeitsfläche">
<button type="button" role="tab" aria-selected={view === "contents"} className={view === "contents" ? "" : "quiet"} onClick={() => onView("contents")}>Inhalte</button>
<button type="button" role="tab" aria-selected={view === "work"} className={view === "work" ? "" : "quiet"} onClick={() => onView("work")}>Aufgaben und Fristen</button>
{view !== "contents" && view !== "work" ? (
@@ -234,6 +235,39 @@ function blurb(element) {
return element.summary || element.excerpt || "";
}
function PdfThumb({ url, title }) {
const canvasRef = useRef(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let alive = true;
let doc;
(async () => {
try {
const pdfjs = await import("pdfjs-dist");
pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
const bytes = await fetch(url).then((response) => response.arrayBuffer());
doc = await pdfjs.getDocument({ data: bytes }).promise;
const pdfPage = await doc.getPage(1);
if (!alive || !canvasRef.current) return;
const base = pdfPage.getViewport({ scale: 1 });
const viewport = pdfPage.getViewport({ scale: 148 / base.width });
const canvas = canvasRef.current;
canvas.width = viewport.width;
canvas.height = viewport.height;
await pdfPage.render({ canvasContext: canvas.getContext("2d"), viewport }).promise;
} catch {
if (alive) setFailed(true);
}
})();
return () => {
alive = false;
doc?.destroy?.();
};
}, [url]);
if (failed) return <span className="thumb thumb--empty">Vorschau nicht verfügbar</span>;
return <canvas ref={canvasRef} className="thumb thumb--pdf" aria-label={`Vorschau ${title}`} />;
}
function Thumb({ element, context }) {
const [url, setUrl] = useState("");
const [media, setMedia] = useState("");
@@ -260,12 +294,30 @@ function Thumb({ element, context }) {
}, [element.id, element.preview?.available, element.preview?.source, context?.kind, context?.id]);
if (element.kind === "note") return <span className="thumb thumb--note">Notiz</span>;
if (url && media === "image") return <img className="thumb" alt="" src={url} />;
if (url && media === "pdf") return <iframe className="thumb thumb--pdf" title={`Vorschau ${element.title}`} src={url} />;
if (url && media === "pdf") return <PdfThumb url={url} title={element.title} />;
if (failed) return <span className="thumb thumb--empty">Vorschau nicht verfügbar</span>;
if (element.preview?.available) return <span className="thumb thumb--empty">Vorschau wird geladen</span>;
return <span className="thumb thumb--empty">Keine Vorschau</span>;
}
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,
@@ -276,6 +328,9 @@ export function ContentBoard({
onChange,
itemHref,
onlyChapter = "",
selectedId = "",
onOpen,
listTitle = "",
}) {
const source = bindings || record?.bindings || [];
const chapters = record?.chapters || [];
@@ -288,7 +343,8 @@ export function ContentBoard({
const custom = record?.content_order === "position";
const direction = record?.content_order_dir === "desc" ? "desc" : "asc";
const sections = sectionsOf(chapters, source);
const visibleSections = onlyChapter ? sections.filter((section) => section.id !== "loose") : sections;
const visibleSections = onlyChapter ? sections.filter((section) => section.id === onlyChapter) : sections;
const shownCount = onlyChapter ? (visibleSections[0]?.items.length || 0) : source.length;
const canSort = sortable && record?.rights?.edit;
const canMoveChapters = Boolean(canSort && chapters.length > 1);
const orderPath = `/api/v1/${containerKind === "case" ? "cases" : "matters"}/${containerId}`;
@@ -605,17 +661,23 @@ export function ContentBoard({
return (
<div className="contents" ref={rootRef}>
{canSort ? (
<OrderChoice
mode={custom ? "position" : "date"}
direction={direction}
disabled={pending}
allowPosition
onChange={saveMode}
/>
) : sortable ? (
<p className="muted">{custom ? "Eigene Reihenfolge" : `Fachliches Datum, ${direction === "desc" ? "absteigend" : "aufsteigend"}`}</p>
) : null}
<div className="content-toolbar">
<div>
<h2>{onlyChapter ? (visibleSections[0]?.title || listTitle || "Kapitel") : (listTitle || "Inhalte")}</h2>
<p className="muted">{shownCount} {shownCount === 1 ? "Eintrag" : "Einträge"}</p>
</div>
{canSort ? (
<OrderChoice
mode={custom ? "position" : "date"}
direction={direction}
disabled={pending}
allowPosition
onChange={saveMode}
/>
) : sortable ? (
<p className="muted">{custom ? "Eigene Reihenfolge" : `Fachliches Datum, ${direction === "desc" ? "absteigend" : "aufsteigend"}`}</p>
) : null}
</div>
{pending ? <p className="muted">Ordnung wird gespeichert …</p> : null}
<ErrorNote error={error} />
{source.length || chapters.length ? (
@@ -637,7 +699,7 @@ export function ContentBoard({
data-chapter={section.id === "loose" ? undefined : section.id}
>
{insertBefore ? <div className="insert-line" aria-hidden="true" /> : null}
{section.title ? (
{section.title && !onlyChapter ? (
<div
className={movable ? "chapter-head is-movable" : "chapter-head"}
draggable={movable && !pending}
@@ -692,7 +754,7 @@ export function ContentBoard({
const href = itemHref(binding);
const text = blurb(element);
return (
<li key={binding.id} data-binding={binding.id} className={draggingId === binding.id ? "preview-row is-dragging" : "preview-row"}>
<li key={binding.id} data-binding={binding.id} className={`preview-row${draggingId === binding.id ? " is-dragging" : ""}${selectedId === binding.id ? " is-selected" : ""}`}>
{indicator?.sectionId === section.id && indicator?.kind !== "chapter" && indicator.index === index ? <div className="insert-line" /> : null}
{canSort && custom ? (
<button
@@ -714,11 +776,23 @@ export function ContentBoard({
</button>
) : null}
<Thumb element={element} context={context} />
<Link className="preview-row__main" to={href}>
<Link
className="preview-row__main"
to={href}
aria-current={selectedId === binding.id ? "true" : undefined}
onClick={(event) => {
if (!onOpen || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
event.preventDefault();
onOpen(binding);
}}
>
<strong>{element.title}</strong>
<span className="preview-row__meta">{formatDate(fachDate(element))} · {sourceLabel(element)}</span>
{text ? <span className="preview-row__text">{text}</span> : null}
{binding.origin ? <span className="preview-row__origin">{binding.origin}{binding.shared ? " · weitere Einbindung" : ""}</span> : null}
{!onlyChapter && !binding.origin && binding.chapter_id ? (
<span className="preview-row__origin">Kapitel {(chapters.find((chapter) => chapter.id === binding.chapter_id)?.title) || ""}</span>
) : null}
</Link>
{(canSort && custom) || (canSort && chapters.length) ? (
<div className="preview-row__actions">
+40
View File
@@ -0,0 +1,40 @@
const common = {
width: 22,
height: 22,
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: 1.8,
strokeLinecap: "round",
strokeLinejoin: "round",
"aria-hidden": true,
};
export function NavIcon({ name }) {
if (name === "home") return <svg {...common}><path d="M4 10.5 12 4l8 6.5V20a1 1 0 0 1-1 1h-5v-6H10v6H5a1 1 0 0 1-1-1z" /></svg>;
if (name === "folder") return <svg {...common}><path d="M3 7.5A2 2 0 0 1 5 5.5h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /></svg>;
if (name === "layers") return <svg {...common}><path d="m12 3 9 5-9 5-9-5z" /><path d="m3 12 9 5 9-5" /></svg>;
if (name === "check") return <svg {...common}><rect x="4" y="4" width="16" height="16" rx="2" /><path d="m8 12 2.5 2.5L16 9" /></svg>;
if (name === "gear") return <svg {...common}><circle cx="12" cy="12" r="3" /><path d="M12 3.5v2.2M12 18.3v2.2M3.5 12h2.2M18.3 12h2.2M6 6l1.6 1.6M16.4 16.4 18 18M18 6l-1.6 1.6M7.6 16.4 6 18" /></svg>;
if (name === "search") return <svg {...common}><circle cx="11" cy="11" r="6" /><path d="m16 16 4 4" /></svg>;
if (name === "more") return <svg {...common}><circle cx="6" cy="12" r="1.2" fill="currentColor" /><circle cx="12" cy="12" r="1.2" fill="currentColor" /><circle cx="18" cy="12" r="1.2" fill="currentColor" /></svg>;
if (name === "logout") return <svg {...common}><path d="M9 6H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h4" /><path d="M14 16l4-4-4-4" /><path d="M18 12H9" /></svg>;
if (name === "menu") return <svg {...common}><path d="M4 7h16M4 12h16M4 17h16" /></svg>;
if (name === "close") return <svg {...common}><path d="M6 6l12 12M18 6 6 18" /></svg>;
if (name === "plus") return <svg {...common}><path d="M12 5v14M5 12h14" /></svg>;
if (name === "link") return <svg {...common}><path d="M10 13a5 5 0 0 0 7.1.1l1.4-1.5a5 5 0 0 0-7.1-7.1L10 6" /><path d="M14 11a5 5 0 0 0-7.1-.1L5.5 12.4a5 5 0 0 0 7.1 7.1L14 18" /></svg>;
return <svg {...common}><circle cx="12" cy="12" r="8" /></svg>;
}
import { ENSO_PATH } from "../enso-path.js";
export function Mark({ size = 36 }) {
return (
<svg className="mark" width={size} height={size} viewBox="0 0 64 64" aria-hidden="true">
<path fill="currentColor" d={ENSO_PATH} />
<path fill="currentColor" opacity="0.72" d="M37.2 25.2h11.2v13.2h-1.8V27.4H38.6z" />
<path fill="currentColor" d="M22.8 29.2h8.8l1.7 2.2h10.2V44H22.8z" />
<path fill="currentColor" opacity="0.45" d="M26.2 34.2h6.4v1.3h-6.4zm0 2.8h4.5v1.3h-4.5z" />
</svg>
);
}
+201
View File
@@ -0,0 +1,201 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { NavIcon } from "./icons.jsx";
export function useWorkspaceLayout() {
const [width, setWidth] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
const [structureOpen, setStructureOpen] = useState(false);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
return { width, structureOpen, setStructureOpen };
}
export function Workspace({ width, structureOpen, setStructureOpen, hasEntry, nav, reader, listRef, children }) {
const phone = width < 760;
const navColumn = width >= 1500;
const split = width >= 1180 && hasEntry;
const showNav = phone ? structureOpen && !hasEntry : navColumn || structureOpen;
const showList = phone ? !structureOpen && !hasEntry : !(hasEntry && width < 1180);
const showReader = hasEntry && (phone ? !structureOpen : true);
const overlay = showNav && !phone && !navColumn;
useEffect(() => {
document.body.classList.toggle("is-phone-reading", phone && hasEntry && !structureOpen);
return () => document.body.classList.remove("is-phone-reading");
}, [phone, hasEntry, structureOpen]);
const classes = ["workspace"];
if (phone && structureOpen && !hasEntry) classes.push("is-structure");
else if (!showNav || overlay) classes.push("is-nav-hidden");
if (split && showList && showReader) classes.push("is-split");
if (!showList && showReader) classes.push("is-reader-focus");
return (
<div className={classes.join(" ")}>
{showNav ? <div className={overlay ? "workspace-nav is-overlay" : "workspace-nav"}>{nav}</div> : null}
{overlay ? (
<button type="button" className="workspace-scrim" aria-label="Struktur schließen" onClick={() => setStructureOpen(false)} />
) : null}
{showList ? (
<div className="workspace-main" ref={listRef}>
{children}
</div>
) : null}
{showReader ? <div className="workspace-reader">{reader}</div> : null}
</div>
);
}
function TreeNodes({ nodes, onNavigate }) {
if (!nodes?.length) return null;
return (
<ul className="nav-tree">
{nodes.map((node) => (
<li key={node.id}>
{node.href ? (
<Link
className={node.current ? "nav-tree__link is-current" : "nav-tree__link"}
to={node.href}
aria-current={node.current ? "page" : undefined}
title={node.title}
onClick={onNavigate}
>
<NavIcon name={node.kind === "Querverweis" ? "link" : node.kind === "Akte" || node.kind === "Unterakte" ? "folder" : "layers"} />
<span>
<span className="nav-tree__kind">{node.kind}</span>
<span className="nav-tree__title">{node.title}</span>
</span>
</Link>
) : (
<span className="nav-tree__link is-current">
<NavIcon name="layers" />
<span>
<span className="nav-tree__kind">{node.kind}</span>
<span className="nav-tree__title">{node.title}</span>
</span>
</span>
)}
{node.children?.length ? <TreeNodes nodes={node.children} onNavigate={onNavigate} /> : null}
</li>
))}
</ul>
);
}
export function StructureNavigator({
contexts = [],
contextValue = "",
onContext,
nodes = [],
chapters = [],
chapterId = "",
allCount = 0,
overview = null,
chapterHeading,
onChapter,
onAddChapter,
canAddChapter = false,
onMoveChapter,
canReorder = false,
links = [],
onNavigate,
onClose,
}) {
return (
<nav className="structure" aria-label="Struktur">
<div className="structure__bar">
<h2>Struktur</h2>
{onClose ? (
<button type="button" className="icon-button" aria-label="Struktur schließen" onClick={onClose}>
<NavIcon name="close" />
</button>
) : null}
</div>
<label className="context-select">
Aktenkontext
<select
aria-label="Aktenkontext"
value={contextValue}
onChange={(event) => onContext?.(event.target.value)}
disabled={!onContext || contexts.length < 2}
>
{contexts.length ? contexts.map((item) => (
<option key={item.id} value={item.id}>{item.label}</option>
)) : <option value="">Ohne Akte</option>}
</select>
</label>
<TreeNodes nodes={nodes} onNavigate={onNavigate} />
<div className="structure__chapters">
<h3>{chapterHeading}</h3>
{overview ? (
<button type="button" className={overview.active ? "chapter-link is-current" : "chapter-link"} onClick={overview.onSelect}>
<span>Überblick</span>
<span className="count">{overview.count}</span>
</button>
) : null}
<button type="button" className={!chapterId && !overview?.active ? "chapter-link is-current" : "chapter-link"} onClick={() => onChapter("")}>
<span>Alle Inhalte</span>
<span className="count">{allCount}</span>
</button>
<ul className="chapter-links">
{chapters.map((chapter, index) => (
<li key={chapter.id}>
<button
type="button"
className={chapterId === chapter.id ? "chapter-link is-current" : "chapter-link"}
onClick={() => onChapter(chapter.id)}
>
<span>{chapter.title}</span>
<span className="count">{chapter.count}</span>
</button>
{canReorder && chapterId === chapter.id ? (
<span className="chapter-link__move">
<button type="button" aria-label={`${chapter.title} nach oben`} disabled={index === 0} onClick={() => onMoveChapter(chapter.id, -1)}>Nach oben</button>
<button type="button" aria-label={`${chapter.title} nach unten`} disabled={index === chapters.length - 1} onClick={() => onMoveChapter(chapter.id, 1)}>Nach unten</button>
</span>
) : null}
</li>
))}
</ul>
{canAddChapter ? (
<button type="button" className="quiet chapter-add" onClick={onAddChapter}>
<NavIcon name="plus" /> Kapitel
</button>
) : null}
</div>
{links.length ? (
<div className="structure__links">
<h3>Weitere Zuordnungen</h3>
<ul className="nav-tree">
{links.map((item) => (
<li key={item.id}>
<Link className="nav-tree__link" to={item.href} onClick={onNavigate}>
<NavIcon name="link" />
<span>
<span className="nav-tree__kind">{item.kind}</span>
<span className="nav-tree__title">{item.title}</span>
</span>
</Link>
</li>
))}
</ul>
</div>
) : null}
</nav>
);
}
export function rememberScroll(node, key) {
if (node && key) sessionStorage.setItem(key, String(node.scrollTop));
}
export function restoreScroll(node, key) {
if (!node || !key) return;
const saved = sessionStorage.getItem(key);
if (saved) node.scrollTop = Number(saved);
}