feat(workspace): trash for notes

Deleting a note (or its folder) moves it to the trash instead of erasing
it. Trashed notes leave the tree, search, export and stats and are hidden
from everyone they were shared with; the owner sees them read-only with a
restore banner. New endpoints list, restore, purge and empty the trash;
restoring recreates a deleted folder. Sidebar entry and mobile menu item
with counter, list view with two-tap permanent delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sandrodachandClaude Opus 5.5 committed 2026-10-29 07:57:42 +01:00
1 parent 344f5e4ab2
commit f69f74fdc7
15 files changed
+649 -40

No files matched your search

+4 -1
View File
@@ -104,7 +104,10 @@ Schreibzugriffe von Lesern auf Listen oder deren Aufgaben liefern `403` („Kein
| GET | `/workspace/tags`, `/workspace/tags/{tag}` | Tag-Übersicht und -Details |
| PUT | `/workspace/tags/{tag}/note` | Tag-Seite speichern (`content`) |
| GET/POST | `/documents` | Notizen auflisten; anlegen (`title`, `icon`, `folderPath`, `blocks`, `tags`, `isPinned`) |
| GET/PUT/DELETE | `/documents/{id}` | Abruf; Ändern von `title`, `icon`, `folderPath`, `isPinned` (Blöcke → `400`, sie laufen über `/docs/{id}/sync`); Löschen |
| GET/PUT/DELETE | `/documents/{id}` | Abruf; Ändern von `title`, `icon`, `folderPath`, `isPinned` (Blöcke → `400`, sie laufen über `/docs/{id}/sync`); Löschen = in den Papierkorb (Eigentümer) bzw. Freigabe verlassen (andere) |
| GET/DELETE | `/documents/trash` | Papierkorb auflisten (`id`, `title`, `icon`, `folderPath`, `deletedAt`, `isOwner`) bzw. leeren |
| POST | `/documents/{id}/restore` | Aus dem Papierkorb zurückholen (fehlender Ordner wird neu angelegt) |
| DELETE | `/documents/{id}/permanent` | Notiz im Papierkorb endgültig löschen |
| PUT | `/documents/{id}/move` | Ordner wechseln (`folderPath`) |
| POST | `/documents/{id}/blocks/{blockId}/enhanced-task` | Aus einem Block eine verknüpfte Aufgabe machen (`content`, `checked`) |
| GET/POST/DELETE | `/documents/{id}/shares[/{userId}]` | Notiz-Freigaben (`userId`/`email`/`teamId`, `permission`: `read`/`write`) |
+1 -1
View File
@@ -29,7 +29,7 @@ Eine Aufgabe ist ein `thought` mit `status='kept'` oder `status='converted' AND
### Workspace
| Tabelle | Zweck |
|---|---|
| `documents` | Notizen: `title`, `icon`, `folder_path`, `tags` (JSON), `is_archived`, `markdown_cache`, `shared_folder_id`, `sub_folder_path`, `head_seq` (letzte Log-Position), `title_version`, `log_floor` (bis hierhin ist das Log verdichtet), Altspalten `content`, `blocks_json` |
| `documents` | Notizen: `title`, `icon`, `folder_path`, `tags` (JSON), `is_archived` (1 = im Papierkorb), `archived_at`, `archived_by` (wer gelöscht hat), `markdown_cache`, `shared_folder_id`, `sub_folder_path`, `head_seq` (letzte Log-Position), `title_version`, `log_floor` (bis hierhin ist das Log verdichtet), Altspalten `content`, `blocks_json` |
| `blocks` | Outliner-Blöcke als Baum: `document_id`, `parent_id` (`''` = oberste Ebene), `order_key` (Sortierschlüssel unter Geschwistern), `type`, `content`, `checked`, `collapsed`, `lang`, `version` (Textversion), `conflict_of`/`conflict_author` (Konfliktkopien), `updated_by`, `deleted` (Grabstein) und `deleted_at` (Zeitpunkt des Löschens, für das Aufräumen). `level`/`position` sind Altspalten und werden nicht mehr gepflegt; Ebene und Reihenfolge berechnet der Server beim Lesen aus dem Baum. |
| `doc_ops` | Änderungs-Log je Notiz: `seq` (fortlaufend pro Notiz), `op_id`, `user_id`, `client_id`, `kind`, `block_id`, `payload` (Effekt als JSON), `created_at`. Abspielen aller Einträge ab einem Snapshot ergibt den Stand. Wird verdichtet (siehe unten). |
| `doc_op_results` | Ergebnis je Client-Operation (`op_id` eindeutig) für idempotente Wiederholungen; wird nach 90 Tagen gelöscht |
+7
View File
@@ -41,6 +41,13 @@ Code: [WorkspaceView.tsx](../../frontend/src/features/workspace/WorkspaceView.ts
- **To-Do-Rollup:** Die Ansicht „To-Dos“ sammelt alle `todo`-Blöcke aller Notizen, filterbar nach Ordner. Abhaken im Rollup ändert den Block in der Notiz.
- **Enhanced Tasks:** Ein `todo`-Block lässt sich als verknüpfte Aufgabe führen (`/documents/{id}/blocks/{blockId}/enhanced-task`); Erledigt-Status bleibt zwischen Notiz und Aufgabenansicht synchron.
## Papierkorb
- Löschen (einzeln oder mit dem Ordner) verschiebt eigene Notizen in den Papierkorb (`is_archived = 1`). Wer eine geteilte Notiz löscht, die ihm nicht gehört, verlässt nur die Freigabe.
- Notizen im Papierkorb fehlen im Baum, in Suche, Export und Statistik und sind für alle Empfänger unsichtbar (`DocRole` = keine Rolle). Eigentümer und Löschende sehen sie schreibgeschützt mit Hinweisleiste und „Wiederherstellen“; Umbenennen, Verschieben und Teilen werden abgelehnt.
- Eintrag „Papierkorb“ mit Zähler unten in der Ordnerleiste und im mobilen Menü. Die Liste zeigt Ordner und Löschzeitpunkt; „Endgültig löschen“ und „Papierkorb leeren“ brauchen einen zweiten Tipp.
- Wiederherstellen legt einen inzwischen gelöschten Ordner neu an; existiert ein geteilter Ordner nicht mehr, landet die Notiz auf der Hauptebene. Freigaben bleiben erhalten. Der Papierkorb leert sich nicht von selbst.
## Freigabe
- Einzelne Notizen und ganze **geteilte Ordner** lassen sich an Benutzer oder Gruppen geben. Empfänger haben **nur Leserechte**; nur der Eigentümer schreibt ([sharing-and-permissions.md](../sharing-and-permissions.md), [FLAW-17](../flaws.md)).
+3
View File
@@ -240,6 +240,9 @@ export const HelpView: React.FC<HelpViewProps> = ({ onBack }) => {
<li>
<strong className="text-main">Ansicht „Tags & Filter“:</strong> Im oberen Workspace-Reiter findest du die Tag-Übersicht. Hier siehst du alle verwendeten Hashtags, kannst Fundstellen aus allen Dokumenten gebündelt durchsuchen und sogar eigene freie Notizen auf Tag-Seiten hinterlegen.
</li>
<li>
<strong className="text-main">Papierkorb:</strong> Gelöschte Notizen (auch aus gelöschten Ordnern) landen im „Papierkorb“ unten in der Ordnerleiste bzw. im mobilen Menü. Dort kannst du sie schreibgeschützt ansehen, wiederherstellen oder endgültig löschen. Solange eine Notiz im Papierkorb liegt, sehen sie auch die Personen nicht, mit denen sie geteilt war.
</li>
</ul>
</div>
),
@@ -3,6 +3,7 @@ import {
Pin,
Users,
Trash2,
RotateCcw,
Download,
FileText,
Loader2,
@@ -36,6 +37,7 @@ export interface DocumentEditorProps {
initialFocusedBlockId?: string | null;
onDocMetadataChange: (updated: Document) => void;
onDeleteDoc: (docId: string) => void;
onRestoreDoc?: (docId: string) => void;
onOpenShareModal: (doc: Document) => void;
onSelectTag: (tag: string) => void;
onWikiLinkClick?: (pageTitle: string) => void;
@@ -179,6 +181,7 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
initialFocusedBlockId,
onDocMetadataChange,
onDeleteDoc,
onRestoreDoc,
onOpenShareModal,
onSelectTag,
onWikiLinkClick,
@@ -244,7 +247,9 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
}, [title, doc?.title, blocks, zoomedBlockId]);
// Owner and editors may edit; the role comes from the server via the sync engine
const inTrash = Boolean(doc?.isArchived);
const canEdit = useMemo(() => {
if (doc?.isArchived) return false;
if (engineState?.role) return engineState.role === 'owner' || engineState.role === 'editor';
if (!doc) return false;
return Boolean(doc.isOwner || doc.permission === 'owner' || doc.permission === 'write');
@@ -770,7 +775,7 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
{/* Who else has this note open */}
<PresenceAvatars people={otherPeople} avatars={avatarsById} />
{/* Sharing Section */}
{doc && (() => {
{doc && !inTrash && (() => {
const isOwner = doc.isOwner !== false && (doc.userId === currentUser?.id || !doc.userId || currentUser?.role === 'admin');
const sharesCount = doc.sharedWith?.length || 0;
const isShared = sharesCount > 0 || !isOwner || Boolean(doc.sharedFolderId);
@@ -814,7 +819,7 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
);
})()}
<button
{!inTrash && <button
type="button"
onClick={handleTogglePin}
className={`btn-icon ${
@@ -825,7 +830,7 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
title={doc?.isPinned ? 'Anheftung lösen' : 'Notiz anheften'}
>
<Pin className="w-3.5 h-3.5" />
</button>
</button>}
<button
type="button"
@@ -849,8 +854,26 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
</div>
</div>
{/* In the trash: read-only with a way back */}
{inTrash && (
<div className="flex flex-wrap items-center gap-2 px-4 sm:px-6 py-2 bg-status-err/10 border-b border-status-err/25 text-status-err text-xs">
<Trash2 className="w-3.5 h-3.5 shrink-0" />
<span className="flex-1 min-w-0">Diese Notiz liegt im Papierkorb und ist schreibgeschützt.</span>
{onRestoreDoc && (
<button
type="button"
onClick={() => onRestoreDoc(docId)}
className="btn-action h-11 sm:h-7 px-3 text-xs text-main inline-flex items-center gap-1.5"
>
<RotateCcw className="w-3.5 h-3.5 text-accent" />
Wiederherstellen
</button>
)}
</div>
)}
{/* Read-only notification banner */}
{!canEdit && (
{!canEdit && !inTrash && (
<div className="flex items-center gap-2 px-4 sm:px-6 py-2 bg-status-warn/10 border-b border-status-warn/25 text-status-warn text-xs">
<Lock className="w-3.5 h-3.5 shrink-0" />
<span>Dieses Dokument wurde schreibgeschützt mit dir geteilt (Nur Lesen).</span>
@@ -0,0 +1,141 @@
import React, { useState } from 'react';
import { ArrowLeft, Folder, RotateCcw, Trash2 } from 'lucide-react';
import { TrashedDocument } from '../../lib/types';
import { CountBadge } from '../../components/CountBadge';
interface TrashViewProps {
items: TrashedDocument[];
onOpen: (docId: string) => void;
onRestore: (docId: string) => Promise<void>;
onPurge: (docId: string) => Promise<void>;
onEmpty: () => Promise<void>;
onBackMobile: () => void;
}
const formatDeletedAt = (iso: string) => {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
return d.toLocaleString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
};
// Deleted notes: open read-only, restore, or delete for good. Deleting for good always takes a second
// tap on the same button ("Wirklich löschen?"), which works the same with mouse and touch.
export const TrashView: React.FC<TrashViewProps> = ({ items, onOpen, onRestore, onPurge, onEmpty, onBackMobile }) => {
const [confirmId, setConfirmId] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const run = async (id: string, action: () => Promise<void>) => {
setBusyId(id);
setError(null);
try {
await action();
setConfirmId(null);
} catch (err: any) {
setError(err.message || 'Aktion fehlgeschlagen');
} finally {
setBusyId(null);
}
};
return (
<div className="flex-1 overflow-y-auto p-4 sm:p-6 lg:p-8 bg-canvas">
<div className="w-full max-w-3xl space-y-4">
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={onBackMobile}
className="lg:hidden btn-action h-11 w-11 flex items-center justify-center"
aria-label="Zurück zu den Notizen"
>
<ArrowLeft className="w-4 h-4" />
</button>
<Trash2 className="w-5 h-5 text-accent" />
<h1 className="text-xl font-bold text-main">Papierkorb</h1>
<CountBadge count={items.length} />
{items.length > 0 && (
<button
type="button"
disabled={busyId !== null}
onClick={() =>
confirmId === '__all__' ? run('__all__', onEmpty) : setConfirmId('__all__')
}
className={`ml-auto h-11 sm:h-8 px-3 text-xs font-semibold rounded-btn border transition-colors disabled:opacity-50 ${
confirmId === '__all__'
? 'bg-status-err/20 text-status-err border-status-err'
: 'btn-action text-status-err border-status-err/40'
}`}
>
{confirmId === '__all__' ? `Wirklich ${items.length} endgültig löschen?` : 'Papierkorb leeren'}
</button>
)}
</div>
<p className="text-xs text-muted">
Gelöschte Notizen bleiben hier, bis du sie wiederherstellst oder endgültig löschst. Für alle, mit denen sie geteilt
waren, sind sie bis dahin ausgeblendet.
</p>
{error && <p className="text-xs text-status-err">{error}</p>}
{items.length === 0 ? (
<div className="p-8 text-center text-sm text-faint border border-dashed border-border rounded-card">
Der Papierkorb ist leer.
</div>
) : (
<ul className="space-y-2">
{items.map((t) => (
<li
key={t.id}
className="p-3 bg-panel border border-border rounded-card flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3"
>
<button
type="button"
onClick={() => onOpen(t.id)}
className="flex items-center gap-2.5 flex-1 min-w-0 text-left cursor-pointer group"
title="Schreibgeschützt ansehen"
>
<span className="text-lg shrink-0">{t.icon || '📝'}</span>
<span className="min-w-0">
<span className="block text-sm font-semibold text-main truncate group-hover:text-accent">
{t.title || 'Unbenannte Notiz'}
</span>
<span className="flex flex-wrap items-center gap-x-2 text-[11px] text-muted">
<span className="inline-flex items-center gap-1 min-w-0">
<Folder className="w-3 h-3 shrink-0" />
<span className="truncate">{t.folderPath || 'Hauptebene'}</span>
</span>
<span>gelöscht {formatDeletedAt(t.deletedAt)}</span>
</span>
</span>
</button>
<div className="grid grid-cols-2 sm:flex gap-2 shrink-0">
<button
type="button"
disabled={busyId !== null}
onClick={() => run(t.id, () => onRestore(t.id))}
className="btn-action h-11 sm:h-8 px-3 text-xs inline-flex items-center justify-center gap-1.5 disabled:opacity-50"
>
<RotateCcw className="w-3.5 h-3.5 text-accent" />
Wiederherstellen
</button>
<button
type="button"
disabled={busyId !== null}
onClick={() => (confirmId === t.id ? run(t.id, () => onPurge(t.id)) : setConfirmId(t.id))}
className={`h-11 sm:h-8 px-3 text-xs rounded-btn border inline-flex items-center justify-center gap-1.5 transition-colors disabled:opacity-50 ${
confirmId === t.id
? 'bg-status-err/20 text-status-err border-status-err font-semibold'
: 'btn-action text-status-err border-status-err/40'
}`}
>
<Trash2 className="w-3.5 h-3.5" />
{confirmId === t.id ? 'Wirklich löschen?' : 'Endgültig löschen'}
</button>
</div>
</li>
))}
</ul>
)}
</div>
</div>
);
};
@@ -36,6 +36,7 @@ import {
TagDetails,
TagSummary,
Team,
TrashedDocument,
UnifiedShare,
User,
} from '../../lib/types';
@@ -53,6 +54,8 @@ import { FormSheet } from '../../components/FormSheet';
import { sendDocOps } from '../../lib/docSync/oneoff';
import { useMobileActions } from '../../context/MobileActionContext';
import { DocumentEditor, DocSaveStatus } from './DocumentEditor';
import { TrashView } from './TrashView';
import { CountBadge } from '../../components/CountBadge';
import { extractHashtags } from '../../lib/hashtags';
interface WorkspaceViewProps {
@@ -63,7 +66,7 @@ interface WorkspaceViewProps {
onOpenTask?: (taskId: string) => void;
}
type WorkspaceSubView = 'editor' | 'tag_detail' | 'todos' | 'tags';
type WorkspaceSubView = 'editor' | 'tag_detail' | 'todos' | 'tags' | 'trash';
interface FolderTreeNode {
name: string;
@@ -307,6 +310,15 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
const [targetBlockId, setTargetBlockId] = useState<string | null>(initialBlockId || null);
const [newlyCreatedDocId, setNewlyCreatedDocId] = useState<string | null>(null);
const [subView, setSubView] = useState<WorkspaceSubView>('editor');
const [trash, setTrash] = useState<TrashedDocument[]>([]);
// Bumped after a restore so the open editor reloads the note without the trash banner
const [editorNonce, setEditorNonce] = useState(0);
const reloadTrash = useCallback(() => {
api.getTrash().then(setTrash).catch(() => {});
}, []);
useEffect(() => {
reloadTrash();
}, [reloadTrash]);
const [selectedTag, setSelectedTag] = useState<string | null>(null);
const [tagDetails, setTagDetails] = useState<TagDetails | null>(null);
const [tagNoteDraft, setTagNoteDraft] = useState<string>('');
@@ -466,14 +478,16 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
const delId = msg.payload.id as string;
setDocs((prev) => prev.filter((d) => d.id !== delId));
setSelectedDocId((prev) => (prev === delId ? null : prev));
reloadTrash();
} else if (msg.event === 'WORKSPACE_FOLDERS_UPDATED') {
api.getFolders().then(setFolders).catch(() => {});
api.getSharedFolders().then(setSharedFolders).catch(() => {});
api.getDocuments().then(setDocs).catch(() => {});
reloadTrash();
}
});
return unsub;
}, [currentUser]);
}, [currentUser, reloadTrash]);
const handleCreateDocument = useCallback(
async (folderPath = '') => {
@@ -524,6 +538,12 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
setMobileShowDetail(true);
}, []);
const openTrash = useCallback(() => {
reloadTrash();
setSubView('trash');
setMobileShowDetail(true);
}, [reloadTrash]);
// Register mobile FAB actions
useEffect(() => {
setPrimaryAction(() => handleCreateDocument(''));
@@ -545,6 +565,13 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
icon: <FolderPlus className="w-4 h-4" />,
onClick: () => setShowNewFolderModal(true),
},
{
id: 'trash',
label: 'Papierkorb',
icon: <Trash2 className="w-4 h-4" />,
badge: trash.length,
onClick: openTrash,
},
],
},
]);
@@ -552,7 +579,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
setGroups([]);
setPrimaryAction(undefined);
};
}, [handleCreateDocument, setGroups, setPrimaryAction]);
}, [handleCreateDocument, setGroups, setPrimaryAction, trash.length, openTrash]);
const handleDeleteDocument = useCallback(
async (docId: string) => {
@@ -567,13 +594,47 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
});
setMobileShowDetail(false);
onStatsChange();
reloadTrash();
} catch {
// ignore
}
},
[onStatsChange, selectedDocId]
[onStatsChange, selectedDocId, reloadTrash]
);
const handleOpenTrashedDoc = (docId: string) => {
setSelectedDocId(docId);
setTargetBlockId(null);
setNewlyCreatedDocId(null);
setSubView('editor');
setMobileShowDetail(true);
};
const handleRestoreDocument = useCallback(
async (docId: string) => {
await api.restoreDocument(docId);
const [freshDocs, freshFolders] = await Promise.all([api.getDocuments(), api.getFolders()]);
setDocs(freshDocs);
setFolders(freshFolders);
setEditorNonce((n) => n + 1);
reloadTrash();
onStatsChange();
},
[reloadTrash, onStatsChange]
);
const handlePurgeDocument = async (docId: string) => {
await api.purgeDocument(docId);
if (selectedDocId === docId) setSelectedDocId(null);
reloadTrash();
};
const handleEmptyTrash = async () => {
await api.emptyTrash();
if (selectedDocId && trash.some((t) => t.id === selectedDocId)) setSelectedDocId(null);
reloadTrash();
};
const handleDocMetadataChange = useCallback((updated: Document) => {
setDocs((prev) => prev.map((d) => (d.id === updated.id ? { ...d, ...updated } : d)));
}, []);
@@ -615,6 +676,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
}
}
onStatsChange();
reloadTrash();
} catch {
// ignore
}
@@ -1257,7 +1319,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
{/* LEFT MASTER SIDEBAR */}
<aside
className={`${
subView !== 'editor' || isSidebarCollapsed
(subView !== 'editor' && subView !== 'trash') || isSidebarCollapsed
? 'hidden'
: mobileShowDetail
? 'hidden lg:flex'
@@ -1469,6 +1531,23 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
</div>
)}
</div>
{/* Trash at the bottom of the tree */}
<div className="p-2 border-t border-border shrink-0">
<button
type="button"
onClick={openTrash}
className={`w-full flex items-center gap-2 px-2 h-11 sm:h-8 rounded-btn text-xs border transition-colors cursor-pointer ${
subView === 'trash'
? 'bg-panel-elevated text-main font-semibold border-border/80'
: 'border-transparent text-muted hover:text-main hover:bg-panel-elevated'
}`}
>
<Trash2 className="w-3.5 h-3.5" />
<span className="flex-1 text-left">Papierkorb</span>
<CountBadge count={trash.length} />
</button>
</div>
</aside>
{/* RIGHT DETAIL AREA (STRICTLY ISOLATED BY KEY) */}
@@ -1477,9 +1556,21 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
subView !== 'editor' || mobileShowDetail || isSidebarCollapsed ? 'flex' : 'hidden lg:flex'
} flex-1 flex-col min-w-0 h-full overflow-hidden bg-canvas`}
>
{subView === 'editor' && selectedDocId ? (
{subView === 'trash' ? (
<TrashView
items={trash}
onOpen={handleOpenTrashedDoc}
onRestore={handleRestoreDocument}
onPurge={handlePurgeDocument}
onEmpty={handleEmptyTrash}
onBackMobile={() => {
setSubView('editor');
setMobileShowDetail(false);
}}
/>
) : subView === 'editor' && selectedDocId ? (
<DocumentEditor
key={selectedDocId}
key={`${selectedDocId}:${editorNonce}`}
docId={selectedDocId}
currentUser={currentUser}
initialDoc={selectedDocObj}
@@ -1488,6 +1579,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
initialFocusedBlockId={targetBlockId}
onDocMetadataChange={handleDocMetadataChange}
onDeleteDoc={handleDeleteDocument}
onRestoreDoc={handleRestoreDocument}
onOpenShareModal={openDocShareModal}
onSelectTag={handleSelectTag}
onWikiLinkClick={handleWikiLinkClick}
+18
View File
@@ -3,6 +3,7 @@ import {
AuthStatus,
DashboardStats,
Document,
TrashedDocument,
DocumentBlock,
DocShare,
KanbanColumn,
@@ -647,10 +648,27 @@ export const api = {
});
},
/** Moves the note to the trash (owner) or leaves a shared note (others). */
async deleteDocument(id: string): Promise<void> {
await request(`/api/v1/documents/${id}`, { method: 'DELETE' });
},
async getTrash(): Promise<TrashedDocument[]> {
return request<TrashedDocument[]>('/api/v1/documents/trash');
},
async restoreDocument(id: string): Promise<void> {
await request(`/api/v1/documents/${id}/restore`, { method: 'POST' });
},
async purgeDocument(id: string): Promise<void> {
await request(`/api/v1/documents/${id}/permanent`, { method: 'DELETE' });
},
async emptyTrash(): Promise<{ deleted: number }> {
return request<{ deleted: number }>('/api/v1/documents/trash', { method: 'DELETE' });
},
async moveDocument(id: string, folderPath: string): Promise<Document> {
const d = await request<Document>(`/api/v1/documents/${id}/move`, {
method: 'PUT',
+10
View File
@@ -232,6 +232,16 @@ export interface DocShare {
createdAt: string;
}
/** A note in the trash (GET /documents/trash). */
export interface TrashedDocument {
id: string;
title: string;
icon: string;
folderPath: string;
deletedAt: string;
isOwner: boolean;
}
export interface Document {
id: string;
userId: string;
+53
View File
@@ -173,6 +173,10 @@ func (s *Server) Router() http.Handler {
r.Put("/api/v1/documents/{id}", s.handleUpdateDocument)
r.Put("/api/v1/documents/{id}/move", s.handleMoveDocument)
r.Delete("/api/v1/documents/{id}", s.handleDeleteDocument)
r.Get("/api/v1/documents/trash", s.handleGetTrash)
r.Delete("/api/v1/documents/trash", s.handleEmptyTrash)
r.Post("/api/v1/documents/{id}/restore", s.handleRestoreDocument)
r.Delete("/api/v1/documents/{id}/permanent", s.handlePurgeDocument)
r.Post("/api/v1/documents/{id}/blocks/{blockId}/enhanced-task", s.handleCreateEnhancedTask)
// Collaborative note editing (operation log)
@@ -1163,6 +1167,55 @@ func (s *Server) handleDeleteDocument(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"deleted": true})
}
func (s *Server) handleGetTrash(w http.ResponseWriter, r *http.Request) {
items, err := s.store.GetTrash(auth.GetUserID(r.Context()))
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, items)
}
func (s *Server) handleRestoreDocument(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
if err := s.store.RestoreDocument(userID, docID); err != nil {
writeTrashError(w, err)
return
}
// Everyone with access reloads their tree, so the note is back for shared users as well
authorized, _ := s.store.GetAuthorizedDocUsers(docID)
for _, uid := range append(authorized, userID) {
s.wsHub.BroadcastToUser(uid, "WORKSPACE_FOLDERS_UPDATED", map[string]string{"restored": docID})
}
writeJSON(w, http.StatusOK, map[string]bool{"restored": true})
}
func (s *Server) handlePurgeDocument(w http.ResponseWriter, r *http.Request) {
if err := s.store.PurgeDocument(auth.GetUserID(r.Context()), chi.URLParam(r, "id")); err != nil {
writeTrashError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]bool{"deleted": true})
}
func (s *Server) handleEmptyTrash(w http.ResponseWriter, r *http.Request) {
ids, err := s.store.EmptyTrash(auth.GetUserID(r.Context()))
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]int{"deleted": len(ids)})
}
func writeTrashError(w http.ResponseWriter, err error) {
if errors.Is(err, storage.ErrNotInTrash) {
writeError(w, http.StatusNotFound, err.Error())
return
}
writeError(w, http.StatusInternalServerError, err.Error())
}
func (s *Server) handleCreateEnhancedTask(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
+11 -3
View File
@@ -549,14 +549,22 @@ func (s *Store) DocRole(userID, docID string) string {
if userID == "" {
return ""
}
var ownerID, sharedFolderID, folderOwner string
var ownerID, sharedFolderID, folderOwner, archivedBy string
var archived bool
err := s.db.QueryRow(
`SELECT d.user_id, d.shared_folder_id, COALESCE(wsf.owner_id, '')
`SELECT d.user_id, d.shared_folder_id, COALESCE(wsf.owner_id, ''), d.is_archived, d.archived_by
FROM documents d LEFT JOIN workspace_shared_folders wsf ON wsf.id = d.shared_folder_id
WHERE d.id = ?`, docID).Scan(&ownerID, &sharedFolderID, &folderOwner)
WHERE d.id = ?`, docID).Scan(&ownerID, &sharedFolderID, &folderOwner, &archived, &archivedBy)
if err != nil {
return ""
}
if archived {
// In the trash: read-only for the owner and whoever trashed it, hidden from everyone else
if ownerID == userID || archivedBy == userID {
return DocRoleViewer
}
return ""
}
if ownerID == userID {
return DocRoleOwner
}
+24 -17
View File
@@ -379,6 +379,8 @@ func (s *Store) migrate() error {
// Idempotent column migrations for existing databases
columnMigrations := []string{
"ALTER TABLE documents ADD COLUMN archived_at TEXT NOT NULL DEFAULT '';",
"ALTER TABLE documents ADD COLUMN archived_by TEXT NOT NULL DEFAULT '';",
"ALTER TABLE users ADD COLUMN username TEXT NOT NULL DEFAULT '';",
"CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);",
"ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'member';",
@@ -1979,13 +1981,16 @@ func (s *Store) GetDocumentByID(userID, docID string) (*domain.Document, error)
d.shared_folder_id, d.sub_folder_path
FROM documents d
LEFT JOIN doc_pins p ON p.doc_id = d.id AND p.user_id = ?
WHERE d.id = ? AND d.user_id = ?`,
userID, docID, userID,
WHERE d.id = ? AND (d.user_id = ? OR (d.is_archived = 1 AND d.archived_by = ?))`,
userID, docID, userID, userID,
)
doc, err := s.scanDocumentWithBlocks(row)
if err == nil {
doc.Permission = "owner"
doc.IsOwner = true
doc.IsOwner = doc.UserID == userID
if doc.IsArchived {
doc.Permission = "read" // read-only while in the trash
}
resolveDocumentPath(userID, doc, mounts, names, userFolders)
if shares, err := s.GetDocShares(doc.ID); err == nil {
doc.SharedWith = shares
@@ -2022,7 +2027,7 @@ func (s *Store) GetDocumentByID(userID, docID string) (*domain.Document, error)
OR (wfs2.target_type = 'team' AND wfs2.target_id IN (SELECT team_id FROM team_members WHERE user_id = ?))
) wfs ON d.shared_folder_id = wfs.folder_id
LEFT JOIN doc_pins p ON p.doc_id = d.id AND p.user_id = ?
WHERE d.id = ? AND (s.user_id = ? OR dts.doc_id IS NOT NULL OR wsf.owner_id = ? OR wfs.folder_id IS NOT NULL)
WHERE d.id = ? AND d.is_archived = 0 AND (s.user_id = ? OR dts.doc_id IS NOT NULL OR wsf.owner_id = ? OR wfs.folder_id IS NOT NULL)
LIMIT 1`,
userID, userID, userID, userID, userID, userID, docID, userID, userID,
)
@@ -2060,6 +2065,9 @@ func (s *Store) UpdateDocument(userID, docID string, title, icon, folderPath *st
if err != nil {
return nil, err
}
if doc.IsArchived {
return nil, ErrDocInTrash
}
// Pins and folder placement are personal; title and icon need edit rights. The content (blocks) is
// only changed through the operation log (POST /docs/{id}/sync).
@@ -2121,11 +2129,10 @@ func (s *Store) DeleteDocument(userID, docID string) error {
_, _ = s.db.Exec(`DELETE FROM doc_user_folders WHERE user_id = ? AND doc_id = ?`, userID, docID)
return s.DeleteDocShare(userID, docID, userID)
}
_, _ = s.db.Exec(`DELETE FROM blocks WHERE document_id = ?`, docID)
_, _ = s.db.Exec(`DELETE FROM block_tags WHERE document_id = ?`, docID)
_, _ = s.db.Exec(`DELETE FROM doc_user_folders WHERE doc_id = ?`, docID)
_, err = s.db.Exec(`DELETE FROM documents WHERE id = ?`, docID)
return err
if doc.IsArchived {
return s.hardDeleteDocument(docID)
}
return s.trashDocument(userID, docID)
}
func (s *Store) reindexAllDocBlockTags() error {
@@ -2596,15 +2603,9 @@ func (s *Store) DeleteFolder(userID, folderPath string) ([]string, error) {
}
_ = rows.Close()
// Delete documents from SQLite, blocks, pins, shares, tags, user_folders
// The notes of the folder go to the trash; restoring one creates its folder again
for _, id := range deletedDocIDs {
_, _ = s.db.Exec(`DELETE FROM blocks WHERE document_id = ?`, id)
_, _ = s.db.Exec(`DELETE FROM block_tags WHERE document_id = ?`, id)
_, _ = s.db.Exec(`DELETE FROM doc_pins WHERE doc_id = ?`, id)
_, _ = s.db.Exec(`DELETE FROM doc_shares WHERE doc_id = ?`, id)
_, _ = s.db.Exec(`DELETE FROM doc_team_shares WHERE doc_id = ?`, id)
_, _ = s.db.Exec(`DELETE FROM doc_user_folders WHERE doc_id = ?`, id)
_, _ = s.db.Exec(`DELETE FROM documents WHERE id = ?`, id)
_ = s.trashDocument(userID, id)
}
// Also clear any personal folder placements for shared notes in this folder
@@ -2619,6 +2620,9 @@ func (s *Store) MoveDocument(userID, docID, targetFolderPath string) (*domain.Do
if err != nil {
return nil, err
}
if doc.IsArchived {
return nil, ErrDocInTrash
}
cleanTarget := filepath.ToSlash(filepath.Clean(strings.TrimSpace(targetFolderPath)))
if cleanTarget == "." {
@@ -3376,6 +3380,9 @@ func (s *Store) CreateDocShare(currentUserID, docID, targetUserIdentifier, permi
if err != nil {
return nil, err
}
if doc.IsArchived {
return nil, ErrDocInTrash
}
if !doc.IsOwner {
return nil, fmt.Errorf("nur der Eigentümer kann Freigaben verwalten")
}
+9 -7
View File
@@ -429,14 +429,16 @@ func TestFolderManagementAndDeletion(t *testing.T) {
t.Fatalf("expected 2 deleted docs, got %d (%v)", len(deletedDocs), deletedDocs)
}
// Verify docs are gone from DB
_, err = store.GetDocumentByID(user.ID, doc1.ID)
if err == nil {
t.Fatalf("expected doc1 to be deleted")
// The notes are in the trash now, no longer in the tree
trash, _ := store.GetTrash(user.ID)
if len(trash) != 2 {
t.Fatalf("expected doc1 and doc2 in the trash, got %v", trash)
}
docs, _ := store.GetDocuments(user.ID)
for _, d := range docs {
if d.ID == doc1.ID || d.ID == doc2.ID {
t.Fatalf("trashed note %s still in the tree", d.ID)
}
_, err = store.GetDocumentByID(user.ID, doc2.ID)
if err == nil {
t.Fatalf("expected doc2 to be deleted")
}
}
+149
View File
@@ -0,0 +1,149 @@
package storage
import (
"database/sql"
"errors"
"github.com/sandrodach/mindsift/internal/domain"
)
// Deleted notes go to a trash first (documents.is_archived = 1). Trashed notes vanish from the tree,
// search, export, stats and for everyone they were shared with; their owner can still read them,
// restore them or delete them for good. archived_by records who trashed the note (the owner, or the
// owner of the shared folder it lived in), so that person sees it in their trash as well.
// ErrNotInTrash is returned when restoring or purging a note that is not in the user's trash.
var ErrNotInTrash = errors.New("Notiz nicht im Papierkorb")
// ErrDocInTrash refuses changes to a trashed note; it has to be restored first.
var ErrDocInTrash = errors.New("Die Notiz liegt im Papierkorb. Stelle sie zuerst wieder her.")
// TrashedDocument is one entry of the trash list.
type TrashedDocument struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
FolderPath string `json:"folderPath"`
DeletedAt string `json:"deletedAt"`
IsOwner bool `json:"isOwner"`
}
const trashScope = `is_archived = 1 AND (user_id = ? OR archived_by = ?)`
func (s *Store) trashDocument(userID, docID string) error {
_, err := s.db.Exec(`UPDATE documents SET is_archived = 1, archived_at = ?, archived_by = ? WHERE id = ?`,
domain.NowISO(), userID, docID)
if err == nil {
_, _ = s.db.Exec(`DELETE FROM doc_pins WHERE doc_id = ?`, docID)
}
return err
}
// GetTrash lists the notes in the user's trash, newest deletion first.
func (s *Store) GetTrash(userID string) ([]TrashedDocument, error) {
rows, err := s.db.Query(`SELECT d.id, d.title, d.icon, d.folder_path, d.shared_folder_id, d.sub_folder_path, d.archived_at, d.user_id,
COALESCE(wsf.name, '')
FROM documents d LEFT JOIN workspace_shared_folders wsf ON wsf.id = d.shared_folder_id
WHERE d.`+trashScope+` ORDER BY d.archived_at DESC`, userID, userID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []TrashedDocument{}
for rows.Next() {
var t TrashedDocument
var sharedFolderID, subPath, ownerID, folderName string
if err := rows.Scan(&t.ID, &t.Title, &t.Icon, &t.FolderPath, &sharedFolderID, &subPath, &t.DeletedAt, &ownerID, &folderName); err != nil {
continue
}
if sharedFolderID != "" {
t.FolderPath = folderName
if subPath != "" {
t.FolderPath += "/" + subPath
}
}
t.IsOwner = ownerID == userID
out = append(out, t)
}
return out, nil
}
func (s *Store) trashedDocOwner(userID, docID string) (string, error) {
var owner string
err := s.db.QueryRow(`SELECT user_id FROM documents WHERE id = ? AND `+trashScope, docID, userID, userID).Scan(&owner)
if err == sql.ErrNoRows {
return "", ErrNotInTrash
}
return owner, err
}
// RestoreDocument takes a note out of the trash. Its folder is created again if it was deleted in the
// meantime; a shared folder that no longer exists puts the note back into the owner's top level.
func (s *Store) RestoreDocument(userID, docID string) error {
owner, err := s.trashedDocOwner(userID, docID)
if err != nil {
return err
}
var folderPath, sharedFolderID string
_ = s.db.QueryRow(`SELECT folder_path, shared_folder_id FROM documents WHERE id = ?`, docID).Scan(&folderPath, &sharedFolderID)
if sharedFolderID != "" {
var exists int
_ = s.db.QueryRow(`SELECT COUNT(*) FROM workspace_shared_folders WHERE id = ?`, sharedFolderID).Scan(&exists)
if exists == 0 {
_, _ = s.db.Exec(`UPDATE documents SET shared_folder_id = '', sub_folder_path = '', folder_path = '' WHERE id = ?`, docID)
}
} else if folderPath != "" {
_, _ = s.CreateFolder(owner, folderPath)
}
_, err = s.db.Exec(`UPDATE documents SET is_archived = 0, archived_at = '', archived_by = '' WHERE id = ?`, docID)
return err
}
// PurgeDocument deletes a trashed note for good.
func (s *Store) PurgeDocument(userID, docID string) error {
if _, err := s.trashedDocOwner(userID, docID); err != nil {
return err
}
return s.hardDeleteDocument(docID)
}
// EmptyTrash deletes every note in the user's trash for good and returns their IDs.
func (s *Store) EmptyTrash(userID string) ([]string, error) {
items, err := s.GetTrash(userID)
if err != nil {
return nil, err
}
ids := make([]string, 0, len(items))
for _, t := range items {
if err := s.hardDeleteDocument(t.ID); err != nil {
return ids, err
}
ids = append(ids, t.ID)
}
return ids, nil
}
func (s *Store) hardDeleteDocument(docID string) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for _, q := range []string{
// Tasks created from blocks of this note keep existing without the link
`UPDATE thoughts SET converted_type = '', converted_ref_id = '' WHERE converted_type = 'document_block'
AND substr(converted_ref_id, 1, instr(converted_ref_id, ':') - 1) = ?`,
`DELETE FROM blocks WHERE document_id = ?`,
`DELETE FROM block_tags WHERE document_id = ?`,
`DELETE FROM doc_pins WHERE doc_id = ?`,
`DELETE FROM doc_shares WHERE doc_id = ?`,
`DELETE FROM doc_team_shares WHERE doc_id = ?`,
`DELETE FROM doc_user_folders WHERE doc_id = ?`,
`DELETE FROM documents WHERE id = ?`,
} {
if _, err := tx.Exec(q, docID); err != nil {
return err
}
}
return tx.Commit()
}
+93
View File
@@ -0,0 +1,93 @@
package storage
import (
"path/filepath"
"testing"
"github.com/sandrodach/mindsift/internal/domain"
)
func TestTrashHidesRestoresAndPurgesNotes(t *testing.T) {
store, err := NewStore(filepath.Join(t.TempDir(), "trash.db"))
if err != nil {
t.Fatalf("NewStore: %v", err)
}
defer store.Close()
openSharing(t, store)
anna, _ := store.CreateUser("anna@example.com", "hash", "Anna", "member")
ben, _ := store.CreateUser("ben@example.com", "hash", "Ben", "member")
blocks := []domain.DocumentBlock{{ID: "b1", Type: "bullet", Content: "Zebrastreifen", Level: 0}}
doc, _ := store.CreateDocument(anna.ID, "", "Verkehr", "🚦", "Projekte/Stadt", blocks, nil, false)
_, _ = store.CreateFolder(anna.ID, "Projekte/Stadt")
if _, err := store.CreateDocShare(anna.ID, doc.ID, ben.ID, "write"); err != nil {
t.Fatalf("share: %v", err)
}
if err := store.DeleteDocument(anna.ID, doc.ID); err != nil {
t.Fatalf("trash: %v", err)
}
visible := func(uid string) bool {
docs, _ := store.GetDocuments(uid)
for _, d := range docs {
if d.ID == doc.ID {
return true
}
}
return false
}
if visible(anna.ID) || visible(ben.ID) {
t.Errorf("trashed note must leave the tree of owner and shared users")
}
if res, _ := store.SearchGlobal(anna.ID, "Zebrastreifen"); len(res.Documents) != 0 {
t.Errorf("trashed note must not be found: %+v", res.Documents)
}
if store.DocRole(anna.ID, doc.ID) != DocRoleViewer || store.DocRole(ben.ID, doc.ID) != "" {
t.Errorf("trash is read-only for the owner and hidden from others")
}
if got, err := store.GetDocumentByID(anna.ID, doc.ID); err != nil || !got.IsArchived || got.Permission != "read" {
t.Errorf("owner reads the trashed note read-only: %+v %v", got, err)
}
if _, err := store.GetDocumentByID(ben.ID, doc.ID); err == nil {
t.Errorf("shared user must not open a trashed note")
}
title := "Neu"
if _, err := store.UpdateDocument(anna.ID, doc.ID, &title, nil, nil, nil); err == nil {
t.Errorf("trashed note must not be renamed")
}
trash, _ := store.GetTrash(anna.ID)
if len(trash) != 1 || trash[0].FolderPath != "Projekte/Stadt" || trash[0].DeletedAt == "" {
t.Fatalf("trash list wrong: %+v", trash)
}
if err := store.RestoreDocument(ben.ID, doc.ID); err == nil {
t.Errorf("only the owner may restore")
}
// The folder was deleted meanwhile; restoring creates it again
_, _ = store.db.Exec(`DELETE FROM workspace_folders WHERE user_id = ?`, anna.ID)
if err := store.RestoreDocument(anna.ID, doc.ID); err != nil {
t.Fatalf("restore: %v", err)
}
if !visible(anna.ID) || !visible(ben.ID) || store.DocRole(ben.ID, doc.ID) != DocRoleEditor {
t.Errorf("restored note is back for everyone, shares intact")
}
if folders, _ := store.GetFolders(anna.ID); len(folders) == 0 {
t.Errorf("folder should be created again on restore")
}
// Deleting a folder moves its notes to the trash; emptying deletes them for good
if _, err := store.DeleteFolder(anna.ID, "Projekte"); err != nil {
t.Fatalf("DeleteFolder: %v", err)
}
if trash, _ := store.GetTrash(anna.ID); len(trash) != 1 {
t.Fatalf("folder deletion should trash the note, got %+v", trash)
}
if ids, err := store.EmptyTrash(anna.ID); err != nil || len(ids) != 1 {
t.Fatalf("EmptyTrash: %v %v", ids, err)
}
var docs, shares int
_ = store.db.QueryRow(`SELECT COUNT(*) FROM documents WHERE id = ?`, doc.ID).Scan(&docs)
_ = store.db.QueryRow(`SELECT COUNT(*) FROM doc_shares WHERE doc_id = ?`, doc.ID).Scan(&shares)
if docs+shares != 0 {
t.Errorf("purge must remove the note and its shares")
}
}