Skip to content

Build your personal knowledge base with Trilium Notes

client/deleted notes dialog: restore notes without a parent to inbox

Adorian Doranc8d860297856
diff --git a/apps/client/src/stylesheets/theme-next/dialogs.css b/apps/client/src/stylesheets/theme-next/dialogs.css
index 56720fc50a..3562a0d77b 100644
--- a/apps/client/src/stylesheets/theme-next/dialogs.css
+++ b/apps/client/src/stylesheets/theme-next/dialogs.css
@@ -262,13 +262,6 @@ div.tn-tool-dialog {
text-decoration: underline;
}
-/* Undelete affordance disabled because the note has no surviving parent to restore into. */
-.recent-changes-content ul li .undelete-disabled {
- opacity: 0.5;
- cursor: help;
- text-decoration: underline dotted;
-}
-
/* Item title for deleted notes */
.recent-changes-dialog-view-mode-all-changes ul li.deleted-note .note-title {
text-decoration: line-through;
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 9a0e6d5ff6..72a46ff361 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -426,8 +426,8 @@
"no_deleted_notes_message": "No deleted notes.",
"undelete_link": "undelete",
"confirm_undelete": "Do you want to undelete this note and its sub-notes?",
- "cannot_undelete": "This note can't be restored because its parent has also been deleted. Restore the parent first.",
- "undelete_failed": "The note could not be restored — it may have been permanently erased or its parent is no longer available."
+ "confirm_undelete_to_default_location": "The parent of this note no longer exists, so it can't be restored to its original location. Restore it to the default location for new notes instead?",
+ "undelete_failed": "The note could not be restored — it may have been permanently erased."
},
"revisions": {
"note_revisions": "Note Revisions",
diff --git a/apps/client/src/widgets/dialogs/recent_changes.tsx b/apps/client/src/widgets/dialogs/recent_changes.tsx
index 2f466068c5..bb62b28cc7 100644
--- a/apps/client/src/widgets/dialogs/recent_changes.tsx
+++ b/apps/client/src/widgets/dialogs/recent_changes.tsx
@@ -1,5 +1,6 @@
import { Dispatch, StateUpdater, useEffect, useState } from "preact/hooks";
import appContext from "../../components/app_context";
+import dateNoteService from "../../services/date_notes";
import dialog from "../../services/dialog";
import { t } from "../../services/i18n";
import server from "../../services/server";
@@ -149,22 +150,43 @@ function DeletedNoteLink({ change, setShown }: { change: RecentChangeRow, setSho
`data-note-deleted` tells the tooltip to resolve it via the deleted-content route. */}
<span className="note-title" data-href={`#${change.noteId}?`} data-note-deleted>{change.current_title}</span>
&nbsp;
- {/* A note can only be restored if it still has a surviving (undeleted) parent to reattach to.
- When it doesn't (its parent is itself deleted or erased) the undelete link is disabled. */}
- ({change.canBeUndeleted
- ? <a href="javascript:" onClick={() => undeleteNote(change, setShown)}>{t("recent_changes.undelete_link")}</a>
- : <span className="undelete-disabled" title={t("recent_changes.cannot_undelete")}>{t("recent_changes.undelete_link")}</span>})
+ (<a href="javascript:" onClick={() => undeleteNote(change, setShown)}>{t("recent_changes.undelete_link")}</a>)
</>
);
}
+/**
+ * Restores a deleted note. When its original parent is gone (deleted or erased) there is no location
+ * to put it back into, so — after telling the user — the note is restored into the default new-note
+ * location (the inbox) instead. On success the dialog closes and the restored note is opened.
+ */
async function undeleteNote(change: RecentChangeRow, setShown: Dispatch<StateUpdater<boolean>>) {
- if (!await dialog.confirm(t("recent_changes.confirm_undelete"))) {
+ const hasOriginalLocation = !!change.canBeUndeleted;
+
+ const confirmed = await dialog.confirm(hasOriginalLocation
+ ? t("recent_changes.confirm_undelete")
+ : t("recent_changes.confirm_undelete_to_default_location"));
+
+ if (!confirmed) {
return;
}
- // The note may fail to restore if it was erased since the dialog opened, so act on the reported result.
- const { undeleted } = await server.put<{ undeleted: boolean }>(`notes/${change.noteId}/undelete`);
+ let fallbackParentNoteId: string | undefined;
+
+ if (!hasOriginalLocation) {
+ const inboxNote = await dateNoteService.getInboxNote();
+
+ if (!inboxNote) {
+ toast.showError(t("recent_changes.undelete_failed"));
+ return;
+ }
+
+ fallbackParentNoteId = inboxNote.noteId;
+ }
+
+ // The note may still fail to restore if it was erased since the dialog opened, so act on the reported result.
+ const { undeleted } = await server.put<UndeleteResponse>(`notes/${change.noteId}/undelete`, { fallbackParentNoteId });
+
if (!undeleted) {
toast.showError(t("recent_changes.undelete_failed"));
return;
@@ -175,6 +197,11 @@ async function undeleteNote(change: RecentChangeRow, setShown: Dispatch<StateUpd
appContext.tabManager.getActiveContext()?.setNote(change.noteId);
}
+interface UndeleteResponse {
+ undeleted: boolean;
+ restoredToFallbackParent: boolean;
+}
+
function groupByDate(rows: RecentChangeRow[]) {
const groupedByDate = new Map<string, RecentChangeRow[]>();
diff --git a/packages/trilium-core/src/routes/api/notes.spec.ts b/packages/trilium-core/src/routes/api/notes.spec.ts
index 3ee712a1bb..0065414bc7 100644
--- a/packages/trilium-core/src/routes/api/notes.spec.ts
+++ b/packages/trilium-core/src/routes/api/notes.spec.ts
@@ -141,6 +141,63 @@ describe("Notes API (core)", () => {
expect(noteIsDeleted(child.noteId)).toBe(1);
});
+ it("restores an orphaned note under the fallback parent when one is given", async () => {
+ const parent = await createTextNote(api, { title: "Doomed parent" });
+ const child = await createTextNote(api, { parentNoteId: parent.noteId, title: "Rehomed child" });
+ const newHome = await createTextNote(api, { title: "Inbox stand-in" });
+
+ // Deleting the parent orphans the child: its only original location is gone.
+ const del = await api.delete(`/api/notes/${parent.noteId}`, {
+ query: { taskId: "test-fallback-delete", last: "true" }
+ });
+ expect(del.status).toBe(204);
+ expect(noteIsDeleted(child.noteId)).toBe(1);
+
+ const undel = await api.put<{ undeleted: boolean; restoredToFallbackParent: boolean }>(
+ `/api/notes/${child.noteId}/undelete`,
+ { body: { fallbackParentNoteId: newHome.noteId } }
+ );
+
+ expect(undel.status).toBe(200);
+ expect(undel.body.undeleted).toBe(true);
+ expect(undel.body.restoredToFallbackParent).toBe(true);
+
+ // The child is alive again under its new home; the original parent stays deleted.
+ expect(noteIsDeleted(child.noteId)).toBe(0);
+ expect(noteIsDeleted(parent.noteId)).toBe(1);
+ expect(becca.getNote(child.noteId)?.getParentNotes().map((note) => note.noteId))
+ .toContain(newHome.noteId);
+ });
+
+ it("re-links an inbox-restored orphan under its original parent when that parent is later restored", async () => {
+ const parent = await createTextNote(api, { title: "Parent restored later" });
+ const child = await createTextNote(api, { parentNoteId: parent.noteId, title: "Orphan rehomed" });
+ const inbox = await createTextNote(api, { title: "Inbox stand-in 2" });
+
+ // Deleting the parent orphans the child.
+ await api.delete(`/api/notes/${parent.noteId}`, {
+ query: { taskId: "test-relink-delete", last: "true" }
+ });
+
+ // The user restores just the child, into the inbox.
+ const undelChild = await api.put<{ restoredToFallbackParent: boolean }>(
+ `/api/notes/${child.noteId}/undelete`,
+ { body: { fallbackParentNoteId: inbox.noteId } }
+ );
+ expect(undelChild.body.restoredToFallbackParent).toBe(true);
+
+ // Later, the user restores the whole parent.
+ const undelParent = await api.put<{ undeleted: boolean }>(`/api/notes/${parent.noteId}/undelete`);
+ expect(undelParent.body.undeleted).toBe(true);
+ expect(noteIsDeleted(parent.noteId)).toBe(0);
+
+ // The child is the SAME note (not a copy), now cloned under both its new home and its
+ // original parent — so restoring the parent brings back a complete subtree.
+ const parentIds = becca.getNote(child.noteId)?.getParentNotes().map((note) => note.noteId);
+ expect(parentIds).toContain(inbox.noteId);
+ expect(parentIds).toContain(parent.noteId);
+ });
+
it("reports failure (instead of crashing) when undeleting an already-erased note", async () => {
const { noteId } = await createTextNote(api, { title: "Erase then undelete" });
const del = await api.delete(`/api/notes/${noteId}`, {
diff --git a/packages/trilium-core/src/routes/api/notes.ts b/packages/trilium-core/src/routes/api/notes.ts
index b881c1eed8..429ec7da0f 100644
--- a/packages/trilium-core/src/routes/api/notes.ts
+++ b/packages/trilium-core/src/routes/api/notes.ts
@@ -201,14 +201,22 @@ function deleteNote(req: Request<{ noteId: string }>) {
function undeleteNote(req: Request<{ noteId: string }>) {
const taskContext = TaskContext.getInstance(randomString(10), "undeleteNotes", null);
- // Report whether the note was actually restored: it may fail silently if the note was already
- // erased or its parent is no longer available, so the client can give feedback instead of
- // navigating to a note that was never brought back.
- const undeleted = noteService.undeleteNote(req.params.noteId, taskContext);
+ // A note whose original parent is gone can only be restored by giving it a new home. The caller
+ // opts into that by naming a fallback parent (the client uses the inbox / default new-note
+ // location, after telling the user the original location no longer exists).
+ const { fallbackParentNoteId } = req.body ?? {};
+
+ if (fallbackParentNoteId !== undefined && typeof fallbackParentNoteId !== "string") {
+ throw new ValidationError("'fallbackParentNoteId' must be a note id.");
+ }
+
+ // Report whether the note was actually restored (and where): it may fail if the note was already
+ // erased, so the client can give feedback instead of navigating to a note that was never brought back.
+ const result = noteService.undeleteNote(req.params.noteId, taskContext, { fallbackParentNoteId });
taskContext.taskSucceeded(null);
- return { undeleted };
+ return result;
}
function sortChildNotes(req: Request<{ noteId: string }>) {
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index ae1cc76dea..fdc05a3ecb 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -1098,39 +1098,86 @@ function updateNoteData(noteId: string, content: string, attachments: Attachment
}
}
+export interface UndeleteNoteOptions {
+ /**
+ * When the note's original parent no longer survives (it is itself deleted, or has been erased),
+ * reattach the note under this note instead — typically the inbox / default new-note location.
+ * Without it, such a note cannot be restored at all.
+ */
+ fallbackParentNoteId?: string;
+}
+
+export interface UndeleteNoteResult {
+ /** Whether the note (and its deleted subtree) was actually restored. */
+ undeleted: boolean;
+ /** True when the original location was gone and the note was reattached under the fallback parent. */
+ restoredToFallbackParent: boolean;
+}
+
/**
* Attempts to restore a soft-deleted note (and the deleted subtree below it, sharing its deleteId).
*
- * @returns `true` if the note was restored, `false` if it could not be — because it has already been
- * erased, is not actually deleted, or has no surviving (undeleted) parent to reattach to.
+ * Normally the note is reattached to whichever of its original parents is still alive. If none is —
+ * because the parent was itself deleted or already erased — the note is an orphan: it can only be
+ * restored by giving it a new home, via {@link UndeleteNoteOptions.fallbackParentNoteId}.
*/
-function undeleteNote(noteId: string, taskContext: TaskContext<"undeleteNotes">): boolean {
+function undeleteNote(
+ noteId: string,
+ taskContext: TaskContext<"undeleteNotes">,
+ opts: UndeleteNoteOptions = {}
+): UndeleteNoteResult {
+ const failed: UndeleteNoteResult = { undeleted: false, restoredToFallbackParent: false };
+
// Use getRowOrNull: the note may have been erased (e.g. by the erasure scheduler or another client)
// between the caller observing it and this call, in which case its row no longer exists.
const noteRow = getSql().getRowOrNull<NoteRow>("SELECT * FROM notes WHERE noteId = ?", [noteId]);
if (!noteRow) {
getLog().info(`Note '${noteId}' no longer exists (has been erased) and thus cannot be undeleted.`);
- return false;
+ return failed;
}
if (!noteRow.isDeleted || !noteRow.deleteId) {
getLog().error(`Note '${noteId}' is not deleted and thus cannot be undeleted.`);
- return false;
+ return failed;
}
- const undeletedParentBranchIds = getUndeletedParentBranchIds(noteId, noteRow.deleteId);
+ const deleteId = noteRow.deleteId;
+ const undeletedParentBranchIds = getUndeletedParentBranchIds(noteId, deleteId);
+
+ if (undeletedParentBranchIds.length > 0) {
+ for (const parentBranchId of undeletedParentBranchIds) {
+ undeleteBranch(parentBranchId, deleteId, taskContext);
+ }
+
+ return { undeleted: true, restoredToFallbackParent: false };
+ }
- if (undeletedParentBranchIds.length === 0) {
- // cannot undelete if there's no undeleted parent (its parent is itself still deleted or erased)
- return false;
+ // The note is an orphan: none of its original parents survive.
+ if (!opts.fallbackParentNoteId) {
+ return failed;
}
- for (const parentBranchId of undeletedParentBranchIds) {
- undeleteBranch(parentBranchId, noteRow.deleteId, taskContext);
+ const fallbackParent = becca.getNote(opts.fallbackParentNoteId);
+
+ if (!fallbackParent) {
+ getLog().error(`Fallback parent '${opts.fallbackParentNoteId}' for undeleting note '${noteId}' was not found.`);
+ return failed;
}
- return true;
+ // A fresh branch gives the orphan a new home. Constructing it also materialises the note's becca
+ // skeleton (see BBranch.childNote), which restoreNoteAndDescendants then fills in from the row.
+ new BBranch({
+ noteId,
+ parentNoteId: fallbackParent.noteId,
+ prefix: null
+ } as BranchRow).save();
+
+ taskContext.increaseProgressCount();
+
+ restoreNoteAndDescendants(noteRow, deleteId, taskContext);
+
+ return { undeleted: true, restoredToFallbackParent: true };
}
function undeleteBranch(branchId: string, deleteId: string, taskContext: TaskContext<"undeleteNotes">) {
@@ -1152,56 +1199,66 @@ function undeleteBranch(branchId: string, deleteId: string, taskContext: TaskCon
taskContext.increaseProgressCount();
if (noteRow.isDeleted && noteRow.deleteId === deleteId) {
- // becca entity was already created as skeleton in "new Branch()" above
- const noteEntity = becca.getNote(noteRow.noteId);
- if (!noteEntity) {
- throw new Error("Unable to find the just restored branch.");
- }
+ restoreNoteAndDescendants(noteRow, deleteId, taskContext);
+ }
+}
- noteEntity.updateFromRow(noteRow);
- noteEntity.save();
-
- const attributeRows = sql.getRows<AttributeRow>(
- `
- SELECT * FROM attributes
- WHERE isDeleted = 1
- AND deleteId = ?
- AND (noteId = ?
- OR (type = 'relation' AND value = ?))`,
- [deleteId, noteRow.noteId, noteRow.noteId]
- );
+/**
+ * Restores a deleted note's row, attributes and attachments, then recurses into the branches of the
+ * subtree deleted alongside it. The note's becca skeleton must already exist — it is created as a
+ * side effect of saving a branch that points at it (see BBranch.childNote).
+ */
+function restoreNoteAndDescendants(noteRow: NoteRow, deleteId: string, taskContext: TaskContext<"undeleteNotes">) {
+ const sql = getSql();
+ const noteEntity = becca.getNote(noteRow.noteId);
- for (const attributeRow of attributeRows) {
- // relation might point to a note which hasn't been undeleted yet and would thus throw up
- new BAttribute(attributeRow).save({ skipValidation: true });
- }
+ if (!noteEntity) {
+ throw new Error("Unable to find the just restored note.");
+ }
- const attachmentRows = sql.getRows<AttachmentRow>(
- `
- SELECT * FROM attachments
+ noteEntity.updateFromRow(noteRow);
+ noteEntity.save();
+
+ const attributeRows = sql.getRows<AttributeRow>(
+ `
+ SELECT * FROM attributes
WHERE isDeleted = 1
AND deleteId = ?
- AND ownerId = ?`,
- [deleteId, noteRow.noteId]
- );
+ AND (noteId = ?
+ OR (type = 'relation' AND value = ?))`,
+ [deleteId, noteRow.noteId, noteRow.noteId]
+ );
- for (const attachmentRow of attachmentRows) {
- new BAttachment(attachmentRow).save();
- }
+ for (const attributeRow of attributeRows) {
+ // relation might point to a note which hasn't been undeleted yet and would thus throw up
+ new BAttribute(attributeRow).save({ skipValidation: true });
+ }
- const childBranchIds = sql.getColumn<string>(
- `
- SELECT branches.branchId
- FROM branches
- WHERE branches.isDeleted = 1
- AND branches.deleteId = ?
- AND branches.parentNoteId = ?`,
- [deleteId, noteRow.noteId]
- );
+ const attachmentRows = sql.getRows<AttachmentRow>(
+ `
+ SELECT * FROM attachments
+ WHERE isDeleted = 1
+ AND deleteId = ?
+ AND ownerId = ?`,
+ [deleteId, noteRow.noteId]
+ );
- for (const childBranchId of childBranchIds) {
- undeleteBranch(childBranchId, deleteId, taskContext);
- }
+ for (const attachmentRow of attachmentRows) {
+ new BAttachment(attachmentRow).save();
+ }
+
+ const childBranchIds = sql.getColumn<string>(
+ `
+ SELECT branches.branchId
+ FROM branches
+ WHERE branches.isDeleted = 1
+ AND branches.deleteId = ?
+ AND branches.parentNoteId = ?`,
+ [deleteId, noteRow.noteId]
+ );
+
+ for (const childBranchId of childBranchIds) {
+ undeleteBranch(childBranchId, deleteId, taskContext);
}
}