Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/collections/board: allow the notes of a column to be deleted
Adorian Doran23a120f03849
diff --git a/apps/client/src/services/dialog.spec.ts b/apps/client/src/services/dialog.spec.tsindex 502edf505e..d9b389bdaf 100644--- a/apps/client/src/services/dialog.spec.ts+++ b/apps/client/src/services/dialog.spec.ts@@ -487,6 +487,19 @@ describe("dialog service", () => {await expect(dialogService.confirm("sure?")).resolves.toBe(false);});+ it("confirmWithNoteDeletion carries the caller's box and answers with the whole result", async () => {+ const callbackResult = { confirmed: true, isDeleteNoteChecked: true };+ triggerCommand.mockImplementation((_name, data: any) => data.callback(callbackResult));++ await expect(dialogService.confirmWithNoteDeletion("Delete it?", "Also delete 2 notes"))+ .resolves.toBe(callbackResult);++ const [name, data] = triggerCommand.mock.calls[0];+ expect(name).toBe("showConfirmDialog");+ expect(data.message).toBe("Delete it?");+ expect(data.checkboxLabel).toBe("Also delete 2 notes");+ });+it("confirmDeleteNoteBoxWithNote triggers the delete-box command and resolves with the callback value", async () => {const callbackResult = { confirmed: true, isDeleteNoteChecked: true };triggerCommand.mockImplementation((_name, data: any) => data.callback(callbackResult));diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.tsindex d9b5118e5d..f1cf23f3d4 100644--- a/apps/client/src/services/dialog.ts+++ b/apps/client/src/services/dialog.ts@@ -209,6 +209,23 @@ async function confirm(message: MessageType) {);}+/**+ * Asks a yes/no question that also offers to delete the notes it is about.+ *+ * The offer is worded by the caller, and left out entirely where `checkboxLabel` is absent.+ *+ * @returns the answer and whether the box was ticked, or `false` where the reader backed out.+ */+async function confirmWithNoteDeletion(message: MessageType, checkboxLabel?: string) {+ return new Promise<ConfirmDialogResult | undefined>((res) =>+ appContext.triggerCommand("showConfirmDialog", <ConfirmWithMessageOptions>{+ message,+ checkboxLabel,+ callback: res+ })+ );+}+/*** Asks whether a note should be taken off whatever is showing it, offering to delete the note along* with it.@@ -255,6 +272,7 @@ export default {info,chooseNote,confirm,+ confirmWithNoteDeletion,confirmDeleteNoteBoxWithNote,pickSingleItem,promptdiff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a9b49a3a0d..95cf71aa3e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3477,6 +3477,8 @@"card-count-with-archived_other": "{{count}} active cards, {{archived}} archived","card-count-over-limit": "The card limit set for this column is exceeded!","delete-column-confirmation": "Are you sure you want to delete this column? The corresponding attribute will be deleted in the notes under this column as well.",+ "delete-column-notes_one": "Also delete the note in this column",+ "delete-column-notes_other": "Also delete the {{count}} notes in this column","new-item": "New card","new-item-placeholder": "Enter card title...","add-new-item": "Add new card",diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 5fb7edee5f..450d9529ca 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -58,7 +58,13 @@ vi.mock("../../../services/note_create", () => ({}));vi.mock("../../../services/dialog", () => ({- default: { confirm: vi.fn(async () => true) }+ default: {+ confirm: vi.fn(async () => true),+ confirmWithNoteDeletion: vi.fn(async () => ({+ confirmed: true,+ isDeleteNoteChecked: false+ }))+ }}));vi.mock("../../../services/i18n", () => ({@@ -97,15 +103,15 @@ function createApi(return { api, board, saved, editing, pendingRenames: pending.renames };}-describe("BoardApi filtering", () => {- /** Cards named by their note id, which is all the operations under test read them for. */- function cards(columns: Record<string, string[]>): ColumnMap {- return new Map(Object.entries(columns).map(([ column, ids ]) => [- column,- ids.map((noteId) => ({ note: { noteId }, branch: { branchId: `b_${noteId}` } }))- ])) as unknown as ColumnMap;- }+/** Cards named by their note id, which is all the operations under test read them for. */+function cards(columns: Record<string, string[]>): ColumnMap {+ return new Map(Object.entries(columns).map(([ column, ids ]) => [+ column,+ ids.map((noteId) => ({ note: { noteId }, branch: { branchId: `b_${noteId}` } }))+ ])) as unknown as ColumnMap;+}+describe("BoardApi filtering", () => {it("stores a submitted filter query and clears it for an empty one", () => {const { api, saved } = createApi({ filterQuery: undefined }, []);@@ -1530,14 +1536,15 @@ describe("removing a column with the question put first", () => {{ columns: [ { value: "To Do" }, { value: "Done" } ] },[ "To Do", "Done" ]);- const confirm = vi.spyOn(dialog, "confirm").mockResolvedValue(false);+ const confirm = vi.spyOn(dialog, "confirmWithNoteDeletion").mockResolvedValue(false);const error = vi.spyOn(toast, "showError").mockReturnValue(undefined);expect(await api.confirmAndRemoveColumn("Done")).toBe(false);- expect(confirm).toHaveBeenCalled();+ // An empty column has no notes to offer, so the box is left out.+ expect(confirm).toHaveBeenCalledWith("board_view.delete-column-confirmation", undefined);expect(saved).toEqual([]);- confirm.mockResolvedValue(true);+ confirm.mockResolvedValue({ confirmed: true, isDeleteNoteChecked: false });expect(await api.confirmAndRemoveColumn("Done")).toBe(true);expect(saved.at(-1)?.columns?.map(column => column.value)).toEqual([ "To Do" ]);expect(error).not.toHaveBeenCalled();@@ -1547,6 +1554,40 @@ describe("removing a column with the question put first", () => {expect(await api.confirmAndRemoveColumn("To Do")).toBe(false);expect(error).toHaveBeenCalledWith("board_view.save-error");});++ /**+ * The column's own cards are what the offer covers, so taking it deletes the notes instead of+ * stripping the grouping value and leaving them on the board.+ */+ it("deletes the notes in the column when the offer is taken", async () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do" }, { value: "Done" } ] },+ [ "To Do", "Done" ], undefined, "status", cards({ Done: [ "one", "two" ] }));+ const confirm = vi.spyOn(dialog, "confirmWithNoteDeletion")+ .mockResolvedValue({ confirmed: true, isDeleteNoteChecked: true });++ expect(await api.confirmAndRemoveColumn("Done")).toBe(true);++ expect(confirm).toHaveBeenCalledWith(+ "board_view.delete-column-confirmation", "board_view.delete-column-notes");+ expect(executeBulkActions).toHaveBeenCalledWith(+ [ "one", "two" ], [ { name: "deleteNote" } ], { silent: true });+ expect(saved.at(-1)?.columns?.map(column => column.value)).toEqual([ "To Do" ]);+ });++ /** Left untaken, the cards stay on the board without the value that put them in the column. */+ it("strips the grouping value when the offer is left untaken", async () => {+ const { api } = createApi(+ { columns: [ { value: "Done" } ] },+ [ "Done" ], undefined, "status", cards({ Done: [ "one" ] }));+ vi.spyOn(dialog, "confirmWithNoteDeletion")+ .mockResolvedValue({ confirmed: true, isDeleteNoteChecked: false });++ expect(await api.confirmAndRemoveColumn("Done")).toBe(true);++ expect(executeBulkActions).toHaveBeenCalledWith(+ [ "one" ], [ { name: "deleteLabel", labelName: "status" } ], { silent: true });+ });});describe("duplicating a card", () => {diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 0a1940c048..dda4c5f5fb 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -506,12 +506,18 @@ export default class BoardApi {* @returns whether the column went, for a caller with something to do afterwards.*/async confirmAndRemoveColumn(column: string) {- if (!await dialog.confirm(t("board_view.delete-column-confirmation"))) {+ // Counted off the map `removeColumn` acts on, so a filter hiding part of the column does+ // not make the offer read as covering fewer notes than it takes.+ const cards = (this.allByColumn ?? this.byColumn)?.get(column)?.length ?? 0;+ const answer = await dialog.confirmWithNoteDeletion(+ t("board_view.delete-column-confirmation"),+ cards ? t("board_view.delete-column-notes", { count: cards }) : undefined);+ if (!answer || !answer.confirmed) {return false;}try {- await this.removeColumn(column);+ await this.removeColumn(column, answer.isDeleteNoteChecked);return true;} catch (e) {console.error("Failed to delete the board column:", e);@@ -520,15 +526,23 @@ export default class BoardApi {}}- async removeColumn(column: string) {- // Remove the value from the notes. Read off the unfiltered map where there is one, so the- // value also comes off the cards an active filter is not showing.+ /**+ * Takes a column off the board.+ *+ * @param deleteNotes whether its cards are deleted, rather than kept on the board with the+ * grouping value taken off them.+ */+ async removeColumn(column: string, deleteNotes = false) {+ // Read off the unfiltered map where there is one, so the cards an active filter is not+ // showing are covered too.const items = (this.allByColumn ?? this.byColumn)?.get(column);const noteIds = items?.map(item => item.note.noteId) || [];- const action: BulkAction = this.isRelationMode- ? { name: "deleteRelation", relationName: this.statusAttribute }- : { name: "deleteLabel", labelName: this.statusAttribute };+ const action: BulkAction = deleteNotes+ ? { name: "deleteNote" }+ : this.isRelationMode+ ? { name: "deleteRelation", relationName: this.statusAttribute }+ : { name: "deleteLabel", labelName: this.statusAttribute };await this.retiredWhile(column, undefined,() => executeBulkActions(noteIds, [ action ], { silent: true }));diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.tsindex 69f75fbcd1..0068f0780f 100644--- a/apps/client/src/widgets/collections/board/keyboard.ts+++ b/apps/client/src/widgets/collections/board/keyboard.ts@@ -335,9 +335,9 @@ export function useBoardKeyboard({if (e.key === "Delete" && spot.kind === "header" && !e.shiftKey) {take(e);- // Where focus goes once the column is gone, taken up only if it does go. Shift is left- // unanswered here: escalating a column would take every note in it, which nothing else- // on the board offers.+ // Where focus goes once the column is gone, taken up only if it does go. Shift is+ // left unanswered here: the confirmation is where the notes in the column are asked+ // about, so there is nothing for a modifier to say.const neighbour = columns[spot.column + 1] ?? columns[spot.column - 1];api.confirmAndRemoveColumn(columns[spot.column]).then((removed) => {if (removed && neighbour !== undefined) {diff --git a/apps/client/src/widgets/dialogs/confirm.css b/apps/client/src/widgets/dialogs/confirm.cssindex cea0e72e47..f45b3610c2 100644--- a/apps/client/src/widgets/dialogs/confirm.css+++ b/apps/client/src/widgets/dialogs/confirm.css@@ -1,4 +1,8 @@.modal.confirm-dialog {+ .form-checkbox {+ margin-top: 12px;+ }+.confirm-delete-note-outcome {color: var(--muted-text-color);margin-block: 4px 0;diff --git a/apps/client/src/widgets/dialogs/confirm.spec.tsx b/apps/client/src/widgets/dialogs/confirm.spec.tsxindex d471ab4e9d..8ba53bbac5 100644--- a/apps/client/src/widgets/dialogs/confirm.spec.tsx+++ b/apps/client/src/widgets/dialogs/confirm.spec.tsx@@ -139,4 +139,30 @@ describe("ConfirmDialog", () => {expect(checkbox()).toBeNull();expect(container.querySelector(".confirm-delete-note-outcome")).toBeNull();});++ /**+ * A caller removing something of its own — a board column, say — offers to delete the notes+ * that go with it in its own words. The verdict the note box carries is not shown, the notes+ * being the caller's to count rather than this dialog's to look up.+ */+ it("offers the caller's own box, and answers with what was done to it", async () => {+ const answers: { confirmed: boolean, isDeleteNoteChecked: boolean }[] = [];+ await act(async () => {+ void host.handleEventInChildren("showConfirmDialog", {+ message: "Delete the column?",+ checkboxLabel: "Also delete the 2 notes in it",+ callback: (answer) => answer && answers.push(answer)+ });+ });++ expect(checkbox()?.parentElement?.textContent).toContain("Also delete the 2 notes in it");+ expect(container.querySelector(".confirm-delete-note-outcome")).toBeNull();++ await tick(true);+ await act(async () => {+ container.querySelectorAll<HTMLButtonElement>(".modal-footer button")[1]?.click();+ });++ expect(answers.at(-1)).toEqual({ confirmed: true, isDeleteNoteChecked: true });+ });});diff --git a/apps/client/src/widgets/dialogs/confirm.tsx b/apps/client/src/widgets/dialogs/confirm.tsxindex 4a1d96190f..954bf59c16 100644--- a/apps/client/src/widgets/dialogs/confirm.tsx+++ b/apps/client/src/widgets/dialogs/confirm.tsx@@ -17,6 +17,7 @@ interface ConfirmDialogProps {isConfirmDeleteNoteBox?: boolean;deletionTarget?: NoteDeletionTarget;mustDeleteNote?: boolean;+ checkboxLabel?: string;}export default function ConfirmDialog() {@@ -39,15 +40,8 @@ export default function ConfirmDialog() {// what the dialog has to say then.const deleteNote = opts?.mustDeleteNote || isDeleteNoteChecked;- function showDialog(title: string | null, message: MessageType, callback: ConfirmDialogCallback, isConfirmDeleteNoteBox: boolean, deletionTarget?: NoteDeletionTarget, mustDeleteNote?: boolean) {- setOpts({- title: title ?? undefined,- message,- callback,- isConfirmDeleteNoteBox,- deletionTarget,- mustDeleteNote- });+ function showDialog(props: ConfirmDialogProps) {+ setOpts(props);// The dialog is mounted once and lives for the session (see LazyDialog), so a box left// ticked would still be ticked the next time it is asked about — a destructive default// carried over to another note, and to whichever part of the app asks next.@@ -55,8 +49,17 @@ export default function ConfirmDialog() {setShown(true);}- useTriliumEvent("showConfirmDialog", ({ message, callback }) => showDialog(null, message, callback, false));- useTriliumEvent("showConfirmDeleteNoteBoxWithNoteDialog", ({ title, message, callback, deletionTarget, mustDeleteNote }) => showDialog(title, message ?? t("confirm.are_you_sure_remove_note", { title: title }), callback, true, deletionTarget, mustDeleteNote));+ useTriliumEvent("showConfirmDialog", ({ message, callback, checkboxLabel }) =>+ showDialog({ message, callback, checkboxLabel }));+ useTriliumEvent("showConfirmDeleteNoteBoxWithNoteDialog", ({ title, message, callback, deletionTarget, mustDeleteNote }) =>+ showDialog({+ title,+ message: message ?? t("confirm.are_you_sure_remove_note", { title: title }),+ callback,+ isConfirmDeleteNoteBox: true,+ deletionTarget,+ mustDeleteNote+ }));return (<Modal@@ -91,6 +94,15 @@ export default function ConfirmDialog() {: <RawHtmlBlock html={opts?.message} />}+ {/* The caller words the offer itself: what is being removed, and how many notes go+ with it, is the caller's to describe. */}+ {opts?.checkboxLabel && (+ <FormCheckbox+ name="confirm-dialog-checkbox"+ label={opts.checkboxLabel}+ currentValue={isDeleteNoteChecked} onChange={setIsDeleteNoteChecked} />+ )}+{opts?.isConfirmDeleteNoteBox && (<>{!opts.mustDeleteNote && (<FormCheckbox@@ -125,6 +137,11 @@ export interface ConfirmDialogOptions {export interface ConfirmWithMessageOptions {message: MessageType;callback: ConfirmDialogCallback;+ /**+ * Wording for a checkbox offering to delete the notes the question is about, left out where+ * there is nothing to offer. Its state comes back as `isDeleteNoteChecked`.+ */+ checkboxLabel?: string;}/**