Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): offer to delete the note taken off a map, and say what that costs

Elian Doran07c3f89fa4e2
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index 95ad3d8cc1..e3cde2e1e7 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -392,9 +392,6 @@ export type CommandMappings = {
zoomReset: CommandData;
copyWithoutFormatting: CommandData;
- // Geomap
- deleteFromMap: { noteId: string };
-
toggleZenMode: CommandData;
updateAttributeList: CommandData & { attributes: Attribute[] };
diff --git a/apps/client/src/services/dialog.spec.ts b/apps/client/src/services/dialog.spec.ts
index 14c3606dcb..d129370950 100644
--- a/apps/client/src/services/dialog.spec.ts
+++ b/apps/client/src/services/dialog.spec.ts
@@ -462,6 +462,20 @@ describe("dialog service", () => {
expect(typeof data.callback).toBe("function");
});
+ /**
+ * The note and the placement it is being removed from, and nothing more: what ticking "Also
+ * delete the note" would cost is the dialog's to work out from those two, not the caller's
+ * to describe (see note_deletion.ts).
+ */
+ it("confirmDeleteNoteBoxWithNote carries the note and branch the dialog judges by", async () => {
+ triggerCommand.mockImplementation((_name, data: any) => data.callback({ confirmed: true, isDeleteNoteChecked: true }));
+
+ await dialogService.confirmDeleteNoteBoxWithNote("My note", { noteId: "n1", branchId: "b1" });
+
+ const [, data] = triggerCommand.mock.calls[0];
+ expect(data.deletionTarget).toEqual({ noteId: "n1", branchId: "b1" });
+ });
+
it("prompt triggers showPromptDialog with merged props and resolves with the callback value", async () => {
triggerCommand.mockImplementation((_name, data: any) => data.callback("typed text"));
diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.ts
index 773ff9ec85..dc1f28823e 100644
--- a/apps/client/src/services/dialog.ts
+++ b/apps/client/src/services/dialog.ts
@@ -1,11 +1,12 @@
import { Modal } from "bootstrap";
import appContext from "../components/app_context.js";
-import type { ConfirmDialogOptions, ConfirmDialogResult, ConfirmWithMessageOptions, MessageType } from "../widgets/dialogs/confirm.js";
+import type { ConfirmDeleteNoteBoxOptions, ConfirmDialogOptions, ConfirmDialogResult, ConfirmWithMessageOptions, MessageType } from "../widgets/dialogs/confirm.js";
import { InfoExtraProps } from "../widgets/dialogs/info.jsx";
import type { PromptDialogOptions } from "../widgets/dialogs/prompt.js";
import { focusSavedElement, saveFocusedElement } from "./focus.js";
import keyboardActionsService from "./keyboard_actions.js";
+import type { NoteDeletionTarget } from "./note_deletion.js";
/**
* @param declaredZIndex the z-index the dialog defines for itself, if any (see {@link raiseAboveStackedPopup}).
@@ -202,8 +203,23 @@ async function confirm(message: MessageType) {
);
}
-async function confirmDeleteNoteBoxWithNote(title: string) {
- return new Promise<ConfirmDialogResult | undefined>((res) => appContext.triggerCommand("showConfirmDeleteNoteBoxWithNoteDialog", { title, callback: res }));
+/**
+ * Asks whether a note should be taken off whatever is showing it, offering to delete the note along
+ * with it.
+ *
+ * Hand it the target and the dialog works out for itself what accepting that offer would cost — the
+ * note deleted outright, or merely one of its places removed — and says so under the checkbox. What
+ * comes back says only whether the reader agreed and whether they ticked the box; carrying it out is
+ * the caller's, through `deleteNoteOrBranch` in note_deletion.ts with the same target.
+ *
+ * @param title the note's title, which the stock question names.
+ * @param deletionTarget the note and the placement it is being removed from. See
+ * {@link NoteDeletionTarget}.
+ * @param options the question to ask in place of the stock one, and whether removing the note from
+ * here deletes it whether the reader likes it or not.
+ */
+async function confirmDeleteNoteBoxWithNote(title: string, deletionTarget?: NoteDeletionTarget, options?: ConfirmDeleteNoteBoxOptions) {
+ return new Promise<ConfirmDialogResult | undefined>((res) => appContext.triggerCommand("showConfirmDeleteNoteBoxWithNoteDialog", { ...options, title, callback: res, deletionTarget }));
}
export async function prompt(props: PromptDialogOptions) {
diff --git a/apps/client/src/services/note_deletion.spec.ts b/apps/client/src/services/note_deletion.spec.ts
new file mode 100644
index 0000000000..724d11d64a
--- /dev/null
+++ b/apps/client/src/services/note_deletion.spec.ts
@@ -0,0 +1,138 @@
+/**
+ * What "also delete the note" costs the tree, which is not one thing.
+ *
+ * A view that lists notes holds two kinds and looks like it holds one: the notes filed under it,
+ * which hang from a branch of its own, and the notes it merely names. Deleting is the removal of one
+ * placement for the first — which the note may well outlive — and the removal of the note itself for
+ * the second. What is checked here is that the same rule decides both the sentence shown to the
+ * reader and the request that follows, so the two can never disagree.
+ */
+import { describe, expect, it, vi } from "vitest";
+
+import froca from "./froca";
+import { buildNote } from "../test/easy-froca";
+import { deleteNoteOrBranch, deletesNote, describeNoteDeletion, planNoteDeletion } from "./note_deletion";
+import server from "./server";
+
+// t() returns the key and the values it was given, so the assertions below are on which sentence is
+// shown and what it was told to count rather than on its English wording.
+vi.mock("./i18n", () => ({
+ t: (key: string, values?: object) => (values ? `${key}:${JSON.stringify(values)}` : key)
+}));
+
+/**
+ * A note hanging under the given parents, the first of which is the view asking about it. `buildNote`
+ * only makes the one branch, so the rest are added the way froca adds a clone.
+ */
+function noteUnder(...parentNoteIds: string[]) {
+ const [ first, ...rest ] = parentNoteIds;
+ buildNote({ id: first, title: first, children: [ { id: "subject", title: "Subject" } ] });
+ const note = froca.notes["subject"];
+
+ for (const parentNoteId of rest) {
+ note.addParent(parentNoteId, `${parentNoteId}_subject`, false);
+ }
+
+ return note;
+}
+
+describe("planNoteDeletion", () => {
+ it("keeps the branch the view files the note under, and counts every place it hangs", () => {
+ noteUnder("theview", "elsewhere");
+
+ expect(planNoteDeletion("subject", "theview_subject"))
+ .toEqual({ branchId: "theview_subject", places: 2 });
+ });
+
+ /**
+ * A note the view merely names — dragged onto a relation map, say — hangs from nothing of the
+ * view's, so there is no placement to remove and only the note itself can go.
+ */
+ it("names no branch where the view files the note nowhere", () => {
+ noteUnder("elsewhere");
+
+ expect(planNoteDeletion("subject", null)).toEqual({ branchId: null, places: 1 });
+ expect(planNoteDeletion("subject")).toEqual({ branchId: null, places: 1 });
+ });
+
+ /** A branch the note does not hang from is no placement of ours either, however it got here. */
+ it("refuses a branch that is not one of the note's own", () => {
+ noteUnder("theview");
+
+ expect(planNoteDeletion("subject", "someone_elses_branch"))
+ .toEqual({ branchId: null, places: 1 });
+ });
+
+ it("plans nothing destructive for a note froca has never heard of", () => {
+ expect(planNoteDeletion("missing", "missing_branch")).toEqual({ branchId: null, places: 0 });
+ });
+});
+
+describe("deletesNote", () => {
+ it("answers whether the note would survive the plan being carried out", () => {
+ // Its only place is the view's, so deleting that branch deletes the note with it.
+ expect(deletesNote({ branchId: "theview_subject", places: 1 })).toBe(true);
+ // It hangs elsewhere too, so the note outlives the branch.
+ expect(deletesNote({ branchId: "theview_subject", places: 2 })).toBe(false);
+ // Nothing of the view's to delete, so the note itself goes however many places it has.
+ expect(deletesNote({ branchId: null, places: 1 })).toBe(true);
+ expect(deletesNote({ branchId: null, places: 3 })).toBe(true);
+ });
+});
+
+describe("describeNoteDeletion", () => {
+ it("says the note survives, and how many clones keep it standing", () => {
+ expect(describeNoteDeletion({ branchId: "theview_subject", places: 3 }))
+ .toBe(`confirm.delete_note_keeps_note:${JSON.stringify({ count: 2 })}`);
+ });
+
+ it("says the note itself goes where the view holds the only place it hangs", () => {
+ expect(describeNoteDeletion({ branchId: "theview_subject", places: 1 }))
+ .toBe("confirm.delete_note_deletes_note");
+ });
+
+ /** Merely named by the view, and hanging in one place, which the deletion takes. */
+ it("says the note itself goes where the view files it nowhere", () => {
+ expect(describeNoteDeletion({ branchId: null, places: 1 }))
+ .toBe("confirm.delete_note_deletes_note");
+ });
+
+ /**
+ * The costly reading, and the one the relation map used to take without saying so: the note is
+ * not the view's to unfile, so deleting it takes every clone of it anywhere in the tree.
+ */
+ it("counts the places that would go with a note the view files nowhere", () => {
+ expect(describeNoteDeletion({ branchId: null, places: 4 }))
+ .toBe(`confirm.delete_note_deletes_clones:${JSON.stringify({ places: 4 })}`);
+ });
+});
+
+describe("deleteNoteOrBranch", () => {
+ it("deletes the branch the view files the note under, leaving its other places alone", async () => {
+ noteUnder("theview", "elsewhere");
+ const remove = vi.spyOn(server, "remove").mockResolvedValue(undefined);
+
+ try {
+ await deleteNoteOrBranch("subject", "theview_subject");
+
+ const [ url ] = remove.mock.calls[0];
+ expect(url).toMatch(/^branches\/theview_subject\?/);
+ expect(url).toContain("last=true");
+ } finally {
+ remove.mockRestore();
+ }
+ });
+
+ it("deletes the note itself where the view files it nowhere", async () => {
+ noteUnder("elsewhere");
+ const remove = vi.spyOn(server, "remove").mockResolvedValue(undefined);
+
+ try {
+ await deleteNoteOrBranch("subject", null);
+
+ expect(remove.mock.calls[0][0]).toMatch(/^notes\/subject\?/);
+ } finally {
+ remove.mockRestore();
+ }
+ });
+});
diff --git a/apps/client/src/services/note_deletion.ts b/apps/client/src/services/note_deletion.ts
new file mode 100644
index 0000000000..1c703b788e
--- /dev/null
+++ b/apps/client/src/services/note_deletion.ts
@@ -0,0 +1,95 @@
+import froca from "./froca.js";
+import { t } from "./i18n.js";
+import server from "./server.js";
+import utils from "./utils.js";
+
+/**
+ * What deleting a note from somewhere that shows it would cost the tree.
+ *
+ * A view that lists notes holds two kinds of them and usually looks like it holds one: notes filed
+ * under it, which hang from a branch of its own, and notes it merely names — dragged onto a relation
+ * map, say. Deleting is not one act for the two. For the first it is the removal of a single
+ * placement, which the note may well outlive elsewhere; for the second there is no placement of the
+ * view's to remove, so only the note itself can go, and it goes from every place it hangs.
+ *
+ * Which is why this is worked out before the reader is asked rather than after they have answered:
+ * a checkbox reading "Also delete the note" means quite different things in the two cases, and
+ * nothing on the box says which.
+ */
+export interface NoteDeletionPlan {
+ /** The branch that would be deleted, or `null` where the note itself is what goes. */
+ branchId: string | null;
+ /** How many places the note has in the tree, all told. */
+ places: number;
+}
+
+/**
+ * A note as it stands in the view asking about it: which note, and which of its placements the view
+ * is removing it from. Enough for {@link planNoteDeletion} to answer everything else, so a view that
+ * wants the offer made need know nothing about what the offer costs.
+ */
+export interface NoteDeletionTarget {
+ noteId: string;
+ /** The note's branch under the view, where the view files it, and `null` where it does not. */
+ branchId?: string | null;
+}
+
+/**
+ * Works out what deleting the given note would mean, where `branchId` is the placement the caller is
+ * removing it from.
+ *
+ * A branch the note does not actually hang from — none was given, or the view names a note it does
+ * not file — leaves nothing of the caller's to delete, so the note itself is what the plan deletes.
+ */
+export function planNoteDeletion(noteId: string, branchId?: string | null): NoteDeletionPlan {
+ const parentBranchIds = froca.getNoteFromCache(noteId)?.getParentBranchIds() ?? [];
+
+ return {
+ branchId: branchId && parentBranchIds.includes(branchId) ? branchId : null,
+ places: parentBranchIds.length
+ };
+}
+
+/** Whether carrying out the plan would take the note out of the tree, or leave it standing elsewhere. */
+export function deletesNote({ branchId, places }: NoteDeletionPlan) {
+ // No branch of the caller's to delete means the note itself goes, wherever it happened to hang;
+ // and a branch that is the note's only one takes the note with it when it goes.
+ return !branchId || places <= 1;
+}
+
+/**
+ * What carrying out the plan would cost, in a sentence to be shown before it is carried out.
+ *
+ * Named in the app's own terms rather than the calling view's — a clone is what the reader is told a
+ * note in several places is everywhere else (see the delete-notes dialog) — so the same sentence
+ * serves whichever view is doing the asking.
+ */
+export function describeNoteDeletion(plan: NoteDeletionPlan) {
+ if (!deletesNote(plan)) {
+ return t("confirm.delete_note_keeps_note", { count: plan.places - 1 });
+ }
+
+ // Counted rather than pluralised: this reading is only reached above one, and a `count` would
+ // have i18next ask translators for a singular that is never shown.
+ if (!plan.branchId && plan.places > 1) {
+ return t("confirm.delete_note_deletes_clones", { places: plan.places });
+ }
+
+ return t("confirm.delete_note_deletes_note");
+}
+
+/**
+ * Carries out {@link planNoteDeletion} — the branch where the caller has one, the note itself where
+ * it has not.
+ *
+ * The branch road serves both outcomes, deleting the last branch of a note being what deletes the
+ * note; what it does not do is take the note's other places down with it, which is the road
+ * `branches.deleteNotes` only takes when the reader ticks "delete all clones".
+ */
+export async function deleteNoteOrBranch(noteId: string, branchId?: string | null) {
+ const { branchId: branchToDelete } = planNoteDeletion(noteId, branchId);
+ const taskId = utils.randomString(10);
+ const target = branchToDelete ? `branches/${branchToDelete}` : `notes/${noteId}`;
+
+ await server.remove(`${target}?taskId=${taskId}&last=true`);
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index a69c296736..99f772d032 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -111,7 +111,11 @@
"cancel": "Cancel",
"ok": "OK",
"are_you_sure_remove_note": "Are you sure you want to remove the note \"{{title}}\" from relation map? ",
- "if_you_dont_check": "If you don't check this, the note will be only removed from the relation map.",
+ "if_you_dont_check": "The note itself is kept; only its place here is removed.",
+ "delete_note_keeps_note_one": "The note has {{count}} other clone, so the note itself is kept.",
+ "delete_note_keeps_note_other": "The note has {{count}} other clones, so the note itself is kept.",
+ "delete_note_deletes_note": "This is the note's only place in the tree, so the note itself will be deleted. This can be undone in recent changes.",
+ "delete_note_deletes_clones": "The note will be deleted from all {{places}} places it appears in. This can be undone in recent changes.",
"also_delete_note": "Also delete the note"
},
"delete_notes": {
@@ -1001,7 +1005,8 @@
"list": "List",
"today": "Today",
"pin_date": "Pin the current date so the calendar always opens on this interval instead of today",
- "unpin_date": "Unpin the date so the calendar opens on today's date again"
+ "unpin_date": "Unpin the date so the calendar opens on today's date again",
+ "close_details": "Close event details"
},
"close_pane_button": {
"close_this_pane": "Close this pane"
@@ -2794,6 +2799,9 @@
"open-location": "Open location",
"move-marker": "Move to another location",
"remove-from-map": "Remove from map",
+ "remove-from-map-confirmation": "Are you sure you want to remove the note \"{{title}}\" from the map?",
+ "delete-note": "Delete note",
+ "delete-note-confirmation": "Are you sure you want to delete the note \"{{title}}\"? A track is drawn from its own note, so it cannot be taken off the map on its own.",
"add-note": "Add a marker at this location"
},
"help-button": {
diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx b/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx
index 3d5f037b9f..c5bef6601a 100644
--- a/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx
@@ -67,12 +67,14 @@ function fakeMap(markerUnderPointer?: FNote, trackUnderPointer?: FNote) {
/** Opens the menu over the given map and hands back the items it was shown with. */
async function openMenu(map: ReturnType<typeof fakeMap>, { isReadOnly = false, onRelocate = vi.fn(), onCreateNote = vi.fn() } = {}) {
+ const parentNote = buildNote({ title: "The map" });
+
// Settled before the map is clicked: the listener the menu opens from is bound in an effect, and
// effects do not run within the render itself.
await act(async () => {
renderInto(
<ParentMap.Provider value={map as never}>
- <ContextMenus isReadOnly={isReadOnly} onRelocate={onRelocate} onCreateNote={onCreateNote} />
+ <ContextMenus parentNote={parentNote} isReadOnly={isReadOnly} onRelocate={onRelocate} onCreateNote={onCreateNote} />
</ParentMap.Provider>
);
});
@@ -132,14 +134,27 @@ describe("ContextMenus", () => {
expect(onCreateNote).toHaveBeenCalledWith(expect.objectContaining({ latlng: { lat: 1, lng: 2 } }));
});
- it("opens the note of a GPX track that was clicked, not the map's own menu", async () => {
+ /**
+ * And named for what taking it off would do, which is delete the note: a track's line is drawn
+ * from its own file rather than from a location written on it, so "remove from map" would be a
+ * promise the map cannot keep.
+ */
+ it("opens the note of a GPX track that was clicked, offering to delete rather than unpin it", async () => {
const track = buildNote({ title: "A Sunday ride", mime: GPX_MIME });
const { items } = await openMenu(fakeMap(undefined, track));
- // The note's menu rather than the map's: a track is a note, so what it offers is what a
- // marker offers, and never the offer to add a note where the click landed.
+ // The note's menu rather than the map's: never the offer to add a note where the click landed.
expect(items).not.toContainEqual(expect.objectContaining({ title: "geo-map-context.add-note" }));
+ expect(items).toContainEqual(expect.objectContaining({ title: "geo-map-context.delete-note" }));
+ expect(items).not.toContainEqual(expect.objectContaining({ title: "geo-map-context.remove-from-map" }));
+ });
+
+ it("offers a marker the plain removal, the note being able to outlive its pin", async () => {
+ const marker = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const { items } = await openMenu(fakeMap(marker));
+
expect(items).toContainEqual(expect.objectContaining({ title: "geo-map-context.remove-from-map" }));
+ expect(items).not.toContainEqual(expect.objectContaining({ title: "geo-map-context.delete-note" }));
});
/**
diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.ts b/apps/client/src/widgets/collections/geomap/ContextMenus.ts
index b6ec2da3ec..243edb987f 100644
--- a/apps/client/src/widgets/collections/geomap/ContextMenus.ts
+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.ts
@@ -1,7 +1,8 @@
import { MapMouseEvent } from "maplibre-gl";
import { useCallback, useContext, useEffect } from "preact/hooks";
-import appContext, { type CommandMappings } from "../../../components/app_context.js";
+import { type CommandMappings } from "../../../components/app_context.js";
+import FNote from "../../../entities/fnote.js";
import contextMenu, { type MenuItem } from "../../../menus/context_menu.js";
import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker.jsx";
import linkContextMenu from "../../../menus/link_context_menu.js";
@@ -9,11 +10,14 @@ import { copyTextWithToast } from "../../../services/clipboard_ext.js";
import froca from "../../../services/froca.js";
import { t } from "../../../services/i18n.js";
import link from "../../../services/link.js";
+import { removeFromMap } from "./api.js";
import { GPX_MIME, trackHitLayers } from "./GpxTrack.js";
import { type GeoMouseEvent, ParentMap, toGeoMouseEvent } from "./map.js";
import { formatLocation, MARKER_LAYER } from "./Markers.js";
interface ContextMenusProps {
+ /** The map's own note, which is how the tree is told what the map holds a note by. */
+ parentNote: FNote;
isReadOnly: boolean;
/**
* Arms this map for the marker of the given note to be put somewhere else, the next click on the
@@ -30,7 +34,7 @@ interface ContextMenusProps {
onCreateNote: (e: GeoMouseEvent) => void;
}
-export default function ContextMenus({ isReadOnly, onRelocate, onCreateNote }: ContextMenusProps) {
+export default function ContextMenus({ parentNote, isReadOnly, onRelocate, onCreateNote }: ContextMenusProps) {
const map = useContext(ParentMap);
const onContextMenu = useCallback((e: GeoMouseEvent) => {
@@ -44,12 +48,12 @@ export default function ContextMenus({ isReadOnly, onRelocate, onCreateNote }: C
if (features.length > 0) {
// Marker or track context menu.
- openContextMenu(features[0].properties.id, e, !isReadOnly, onRelocate);
+ openContextMenu(features[0].properties.id, e, { isEditable: !isReadOnly, onRelocate, parentNote });
} else {
// Empty area context menu.
openMapContextMenu(e, !isReadOnly, onCreateNote);
}
- }, [ map, isReadOnly, onRelocate, onCreateNote ]);
+ }, [ map, isReadOnly, onRelocate, onCreateNote, parentNote ]);
useEffect(() => {
if (!onContextMenu || !map) return;
@@ -65,7 +69,11 @@ export default function ContextMenus({ isReadOnly, onRelocate, onCreateNote }: C
return null;
}
-export function openContextMenu(noteId: string, e: GeoMouseEvent, isEditable: boolean, onRelocate: (noteId: string) => void) {
+export function openContextMenu(noteId: string, e: GeoMouseEvent, { isEditable, onRelocate, parentNote }: {
+ isEditable: boolean;
+ onRelocate: (noteId: string) => void;
+ parentNote: FNote;
+}) {
let items: MenuItem<keyof CommandMappings>[] = [
...buildGeoLocationItem(e),
{ kind: "separator" },
@@ -73,11 +81,22 @@ export function openContextMenu(noteId: string, e: GeoMouseEvent, isEditable: bo
];
if (isEditable) {
+ const note = froca.getNoteFromCache(noteId);
+
items = [
...items,
{ kind: "separator" },
...buildRelocateItem(noteId, onRelocate),
- { title: t("geo-map-context.remove-from-map"), command: "deleteFromMap", uiIcon: "bx bx-trash" },
+ {
+ // A track is named for what removing it does, which is delete the note: its line is
+ // drawn from the note's own file rather than from a location written on it, so there
+ // is no taking it off the map and keeping it (see removeFromMap).
+ title: t(note?.mime === GPX_MIME ? "geo-map-context.delete-note" : "geo-map-context.remove-from-map"),
+ // Called rather than commanded: what was a broadcast command every open map heard
+ // would now put a dialog up on each of them in turn.
+ handler: () => note && void removeFromMap(note, parentNote),
+ uiIcon: "bx bx-trash"
+ },
{ kind: "separator"},
{
kind: "custom",
@@ -90,15 +109,8 @@ export function openContextMenu(noteId: string, e: GeoMouseEvent, isEditable: bo
x: e.originalEvent.pageX,
y: e.originalEvent.pageY,
items,
- selectMenuItemHandler: ({ command }) => {
- if (command === "deleteFromMap") {
- appContext.triggerCommand(command, { noteId });
- return;
- }
-
- // Pass the events to the link context menu
- linkContextMenu.handleLinkContextMenuItem(command, e, noteId);
- }
+ // Pass the events to the link context menu, everything this menu adds handling itself.
+ selectMenuItemHandler: ({ command }) => linkContextMenu.handleLinkContextMenuItem(command, e, noteId)
});
}
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
index 33feb3d831..8ab900a1d7 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
@@ -51,6 +51,18 @@ vi.mock("../../NoteDetail", () => ({
}
}));
+/**
+ * Whether the reader agreed to the note being taken off the map, and whether it should go from the
+ * tree with it. What the dialog itself makes of that is its own spec's business (see confirm.spec).
+ */
+const confirmDelete = vi.fn();
+vi.mock("../../../services/dialog", async (importOriginal) => ({
+ default: {
+ ...((await importOriginal<{ default: object }>()).default),
+ confirmDeleteNoteBoxWithNote: (...args: unknown[]) => confirmDelete(...args)
+ }
+}));
+
/** What the pane puts on the clipboard, the writing of it being the browser's business. */
const copied = vi.fn();
vi.mock("../../../services/clipboard_ext", async (importOriginal) => ({
@@ -146,6 +158,9 @@ describe("DetailPane", () => {
};
editorAskedToSave.mockClear();
onRelocate.mockClear();
+ // Nothing is taken off the map unless a test says the reader agreed to it.
+ confirmDelete.mockReset();
+ confirmDelete.mockResolvedValue(false);
});
afterEach(() => {
@@ -173,6 +188,7 @@ describe("DetailPane", () => {
const [ selection, setSelection ] = useState<PaneSelection | null>(initialSelection ?? null);
return <DetailPane
notes={notes}
+ parentNote={froca.notes["root"] ?? buildNote({ id: "root", title: "root" })}
placing={placing}
isReadOnly={isReadOnly}
selection={selection}
@@ -922,13 +938,14 @@ describe("DetailPane", () => {
}
/**
- * Only the note's location goes — the note itself stays where it is in the tree — and the
- * pane goes with it, there being no marker left for it to stand for.
+ * Asked first, and only then does the note's location go — the note itself staying where it
+ * is in the tree — the pane going with the marker, there being nothing left to stand for.
*/
- it("clears the note's location and stands down", async () => {
+ it("clears the note's location and stands down, the reader having agreed", async () => {
const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
const map = fakeMap();
const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ confirmDelete.mockResolvedValue({ confirmed: true, isDeleteNoteChecked: false });
try {
await mount([ note ], map);
@@ -947,6 +964,27 @@ describe("DetailPane", () => {
}
});
+ /** Turned down at the dialog, the marker stays exactly where it was. */
+ it("leaves the marker alone where the reader changed their mind", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ confirmDelete.mockResolvedValue(false);
+
+ try {
+ await mount([ note ], map);
+ map.setUnderPointer([ markerFeature(note) ]);
+ await act(async () => map.click());
+
+ await act(async () => { removeButton()?.click(); });
+
+ expect(setLabel).not.toHaveBeenCalled();
+ expect(pane()).toBeTruthy();
+ } finally {
+ setLabel.mockRestore();
+ }
+ });
+
it("is not offered at all on a map that cannot be edited", async () => {
const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
const map = fakeMap();
@@ -960,6 +998,30 @@ describe("DetailPane", () => {
expect(container?.querySelector(".geo-detail-pane-actions button.bx-log-in")).toBeTruthy();
expect(removeButton()).toBeNull();
});
+
+ /**
+ * A track's line is drawn from its own file rather than from a location written on it, so
+ * there is no taking it off the map and keeping it. The button is named for what it really
+ * does, and the dialog is told there is nothing to offer a choice about.
+ */
+ it("asks about a GPX track as a deletion, there being nothing else it could be", async () => {
+ buildNote({ id: "root", title: "root", children: [ { id: "hikegone", title: "A hike", mime: GPX_MIME } ] });
+ const note = froca.notes["hikegone"];
+ const map = fakeMap();
+
+ await mount([ note ], map);
+ map.setUnderPointer([ trackFeature(note) ]);
+ await act(async () => map.click());
+ await settle();
+
+ await act(async () => { removeButton()?.click(); });
+
+ expect(confirmDelete).toHaveBeenCalledWith(
+ note.title,
+ { noteId: note.noteId, branchId: "root_hikegone" },
+ expect.objectContaining({ mustDeleteNote: true })
+ );
+ });
});
it("keeps clicks and key presses from reaching the map underneath", async () => {
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
index ab4ae3dab0..b4434ca4ee 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
@@ -22,7 +22,7 @@ import { FormListItem } from "../../react/FormList";
import { useLegacyComponentElement, useNoteColorClass, useNoteContext, useNoteLabel, useStaticTooltip } from "../../react/hooks";
import OverlayPanel, { OverlayPanelBody } from "../../react/OverlayPanel";
import { NoteContextContext, ParentComponent } from "../../react/react_utils";
-import { moveMarker } from "./api";
+import { removeFromMap } from "./api";
import { GPX_MIME, trackHitLayers, trackSourceId } from "./GpxTrack";
import { ParentMap } from "./map";
import { formatLocation, LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";
@@ -61,8 +61,10 @@ export type PaneFocus =
* pane outside it would leave the screen. It reads as a dock because the map keeps out of its way
* (see {@link paneOffset}).
*/
-export default function DetailPane({ notes, placing, isReadOnly, selection, onSelect, onRelocate }: {
+export default function DetailPane({ notes, parentNote, placing, isReadOnly, selection, onSelect, onRelocate }: {
notes: FNote[];
+ /** The map's own note, which is how the tree is told what the map holds a note by. */
+ parentNote: FNote;
/** A marker is being placed, which is what the next click on the map is for. */
placing: boolean;
/** The map may not be edited, which leaves the pane the ways of opening a note and no more. */
@@ -240,7 +242,7 @@ export default function DetailPane({ notes, placing, isReadOnly, selection, onSe
// TitleRow), and answers to the pane's own component rather than the map's (see below).
<ParentComponent.Provider value={paneComponent}>
<NoteContextContext.Provider value={noteContext}>
- <MarkerDetails note={note} isReadOnly={isReadOnly} onClose={closePane} onRelocate={relocate} onFollowLink={followLink} />
+ <MarkerDetails note={note} parentNote={parentNote} isReadOnly={isReadOnly} onClose={closePane} onRelocate={relocate} onFollowLink={followLink} />
{selection?.isNew && <SelectTitleOnFirstOpen />}
</NoteContextContext.Provider>
</ParentComponent.Provider>
@@ -388,8 +390,9 @@ function trackFitPadding(map: MapLibreGLMap) {
}
/** The pane itself, for a marker there is one to draw. */
-function MarkerDetails({ note, isReadOnly, onClose, onRelocate, onFollowLink }: {
+function MarkerDetails({ note, parentNote, isReadOnly, onClose, onRelocate, onFollowLink }: {
note: FNote;
+ parentNote: FNote;
isReadOnly: boolean;
onClose(): void;
onRelocate(): void;
@@ -458,7 +461,7 @@ function MarkerDetails({ note, isReadOnly, onClose, onRelocate, onFollowLink }:
<OverlayPanelBody className="geo-detail-pane-body">
<MarkerLocation note={note} />
- <MarkerActions note={note} isReadOnly={isReadOnly} onRelocate={onRelocate} />
+ <MarkerActions note={note} parentNote={parentNote} isReadOnly={isReadOnly} onRelocate={onRelocate} />
{/* Whatever fields the note's own definitions ask for, ahead of the note as the quick
editor puts them — a marker is often a note whose type says less about it than
@@ -551,7 +554,7 @@ function usePaneNoteContext(note: FNote | undefined) {
* and the pane took that click over — offering it here would put a modal back over the pane that
* replaced it.
*/
-function MarkerActions({ note, isReadOnly, onRelocate }: { note: FNote; isReadOnly: boolean; onRelocate(): void }) {
+function MarkerActions({ note, parentNote, isReadOnly, onRelocate }: { note: FNote; parentNote: FNote; isReadOnly: boolean; onRelocate(): void }) {
const [ location ] = useNoteLabel(note, LOCATION_ATTRIBUTE);
const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;
// A path rather than an id: a note may hang in several places, and each of these opens a path.
@@ -644,13 +647,14 @@ function MarkerActions({ note, isReadOnly, onRelocate }: { note: FNote; isReadOn
<ActionButton
className="geo-detail-pane-remove"
icon="bx bx-trash"
- text={t("geo-map-context.remove-from-map")}
- // Only the location goes; the note stays in the tree. Nothing closes the pane
- // afterwards because the effect above already stands it down.
- //
- // Called rather than commanded: `deleteFromMap` is broadcast, so every open geo
- // map would take the same note off in turn.
- onClick={() => void moveMarker(note.noteId, null)}
+ // Named for what it does to a track, which is delete the note: a track's line is
+ // drawn from the note's own file, so there is no taking it off the map and
+ // keeping it (see removeFromMap). The right-click menu names it the same way.
+ text={t(note.mime === GPX_MIME ? "geo-map-context.delete-note" : "geo-map-context.remove-from-map")}
+ // Whether the note goes with its marker is asked before anything happens, the
+ // two being different wishes. Nothing closes the pane afterwards because the
+ // effect above already stands it down, either way round.
+ onClick={() => void removeFromMap(note, parentNote)}
/>
</>}
</div>
diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.ts
index 3fde07aa83..107b4409bc 100644
--- a/apps/client/src/widgets/collections/geomap/api.ts
+++ b/apps/client/src/widgets/collections/geomap/api.ts
@@ -1,7 +1,10 @@
import FNote from "../../../entities/fnote";
import attributes from "../../../services/attributes";
+import dialog from "../../../services/dialog";
import { t } from "../../../services/i18n";
import note_create from "../../../services/note_create";
+import { deleteNoteOrBranch } from "../../../services/note_deletion";
+import { GPX_MIME } from "./GpxTrack";
import type { GeoMouseEvent } from "./map";
import { LOCATION_ATTRIBUTE } from "./Markers";
@@ -13,6 +16,46 @@ export async function moveMarker(noteId: string, latLng: { lat: number; lng: num
await attributes.setLabel(noteId, LOCATION_ATTRIBUTE, value);
}
+/**
+ * Takes a note off the map, having asked first, and offers to delete it while it is at it.
+ *
+ * The offer is the point. A marker put down by mistake used to leave a note behind that the map no
+ * longer showed and the reader had to go hunting for in the tree — taking a note off the map and
+ * getting rid of it are different wishes, and only one of them was granted. What deleting would
+ * actually cost is the dialog's to work out and to say (see confirmDeleteNoteBoxWithNote); all this
+ * has to know is which branch the map holds the note by.
+ *
+ * A track is the exception, and is deleted or left alone: its line is drawn from the note's own file
+ * rather than from a location written on it, so there is no taking it off the map and keeping it —
+ * the note is the track. That is also why it is not offered under the same name (see ContextMenus).
+ */
+export async function removeFromMap(note: FNote, mapNote: FNote) {
+ const isTrack = note.mime === GPX_MIME;
+ // The map's own branch for the note, which is how a note the map merely shows — cloned in from
+ // elsewhere, and clone-able out again — is told from one that lives here and nowhere else.
+ const branchId = note.parentToBranch[mapNote.noteId] ?? null;
+
+ const result = await dialog.confirmDeleteNoteBoxWithNote(
+ note.title,
+ { noteId: note.noteId, branchId },
+ {
+ message: t(isTrack ? "geo-map-context.delete-note-confirmation" : "geo-map-context.remove-from-map-confirmation",
+ { title: note.title }),
+ mustDeleteNote: isTrack
+ }
+ );
+
+ if (typeof result !== "object" || !result.confirmed) {
+ return;
+ }
+
+ if (result.isDeleteNoteChecked) {
+ await deleteNoteOrBranch(note.noteId, branchId);
+ } else {
+ await moveMarker(note.noteId, null);
+ }
+}
+
/**
* Creates a note where the click landed, and hands it back for the pane to open on.
*
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index 8a22cd9573..605ca5d74b 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -11,7 +11,7 @@ import server from "../../../services/server";
import toast from "../../../services/toast";
import CollectionProperties from "../../note_bars/CollectionProperties";
import ActionButton from "../../react/ActionButton";
-import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate, useTriliumEvent } from "../../react/hooks";
+import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate } from "../../react/hooks";
import { ViewModeProps } from "../interface";
import { createNewNote, importGpxTrack, moveMarker } from "./api";
import ContextMenus from "./ContextMenus";
@@ -172,10 +172,6 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
};
}, [ placement ]);
- useTriliumEvent("deleteFromMap", ({ noteId }) => {
- moveMarker(noteId, null);
- });
-
const onClick = useCallback(async (e: GeoMouseEvent) => {
if (!placement) return;
@@ -257,8 +253,8 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
being moved wearing its own pin, a note to be created wearing the pin it will be
given (see api.ts). */}
{placement && <GhostPin note={placement.mode === "move" ? notes.find((n) => n.noteId === placement.noteId) : undefined} />}
- <DetailPane notes={notes} placing={!!placement} isReadOnly={isReadOnly} selection={selection} onSelect={setSelection} onRelocate={startMarkerRelocation} />
- <ContextMenus isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} onCreateNote={createNoteAt} />
+ <DetailPane notes={notes} parentNote={note} placing={!!placement} isReadOnly={isReadOnly} selection={selection} onSelect={setSelection} onRelocate={startMarkerRelocation} />
+ <ContextMenus parentNote={note} isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} onCreateNote={createNoteAt} />
{/* The pane above is what a click on a marker opens now, so the markers no longer
open the note themselves — the two would otherwise both answer the same click,
raising the quick editor over the pane that had just opened behind it. */}
diff --git a/apps/client/src/widgets/dialogs/confirm.css b/apps/client/src/widgets/dialogs/confirm.css
new file mode 100644
index 0000000000..cea0e72e47
--- /dev/null
+++ b/apps/client/src/widgets/dialogs/confirm.css
@@ -0,0 +1,11 @@
+.modal.confirm-dialog {
+ .confirm-delete-note-outcome {
+ color: var(--muted-text-color);
+ margin-block: 4px 0;
+ font-size: 0.9em;
+
+ /* Held at the height of a line so that ticking the box swaps the wording rather than
+ resizing the dialog under the pointer that ticked it. */
+ min-height: 1.35em;
+ }
+}
diff --git a/apps/client/src/widgets/dialogs/confirm.spec.tsx b/apps/client/src/widgets/dialogs/confirm.spec.tsx
new file mode 100644
index 0000000000..d471ab4e9d
--- /dev/null
+++ b/apps/client/src/widgets/dialogs/confirm.spec.tsx
@@ -0,0 +1,142 @@
+/**
+ * The confirmation that offers to delete the note as well as take it off whatever is showing it.
+ *
+ * What matters here is the offer's honesty. The dialog is handed only the note and the branch the
+ * view files it under, and works out for itself what ticking the box would cost — a caller that had
+ * to answer that for itself would be a caller that could get it wrong. And a tick must not survive
+ * into the next thing the dialog is asked about, it being mounted once for the whole session (see
+ * LazyDialog in layout_commons).
+ */
+import { act } from "preact/test-utils";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../components/component";
+import froca from "../../services/froca";
+import { buildNote } from "../../test/easy-froca";
+import { renderInto } from "../../test/render";
+import { ParentComponent } from "../react/react_utils";
+import ConfirmDialog from "./confirm";
+
+vi.mock("../../services/i18n", () => ({
+ t: (key: string, values?: object) => (values ? `${key}:${JSON.stringify(values)}` : key)
+}));
+
+describe("ConfirmDialog", () => {
+ let host: Component;
+ let container: HTMLElement;
+
+ beforeEach(() => {
+ host = new Component();
+ container = renderInto(
+ <ParentComponent.Provider value={host}>
+ <ConfirmDialog />
+ </ParentComponent.Provider>
+ );
+ });
+
+ /**
+ * A note filed under the given view and cloned into as many other places as asked for, which is
+ * the whole of what decides the sentence the dialog shows.
+ */
+ function buildSubject(noteId: string, viewNoteId: string, otherPlaces = 0) {
+ buildNote({ id: viewNoteId, title: viewNoteId, children: [ { id: noteId, title: "A note" } ] });
+
+ for (let i = 0; i < otherPlaces; i++) {
+ froca.notes[noteId].addParent(`other${i}`, `other${i}_${noteId}`, false);
+ }
+ }
+
+ /** Asks to remove a note, as the relation map's own "Remove note" asks. */
+ async function askAboutNote(deletionTarget?: { noteId: string; branchId?: string | null }) {
+ await act(async () => {
+ void host.handleEventInChildren("showConfirmDeleteNoteBoxWithNoteDialog", {
+ title: "A note",
+ callback: () => {},
+ deletionTarget
+ });
+ });
+ }
+
+ function checkbox() {
+ return container.querySelector<HTMLInputElement>("input[type=checkbox]");
+ }
+
+ function outcome() {
+ return container.querySelector(".confirm-delete-note-outcome")?.textContent;
+ }
+
+ async function tick(checked: boolean) {
+ const input = checkbox();
+ if (!input) throw new Error("The dialog offered no checkbox to tick.");
+ await act(async () => {
+ input.checked = checked;
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ }
+
+ /**
+ * The note hangs nowhere else, so ticking would take it out of the tree — which the dialog works
+ * out from the branch alone, nobody having told it so.
+ */
+ it("says what leaving the box alone means, and what ticking it would cost", async () => {
+ buildSubject("lonely", "theview");
+ await askAboutNote({ noteId: "lonely", branchId: "theview_lonely" });
+
+ expect(outcome()).toBe("confirm.if_you_dont_check");
+
+ await tick(true);
+ expect(outcome()).toBe("confirm.delete_note_deletes_note");
+
+ // Both ways round: unticking says the harmless thing again.
+ await tick(false);
+ expect(outcome()).toBe("confirm.if_you_dont_check");
+ });
+
+ /** The same tick on a note that hangs elsewhere too costs it only this one placement. */
+ it("says the note is kept where the branch is one of several it hangs from", async () => {
+ buildSubject("cloned", "theview", 2);
+ await askAboutNote({ noteId: "cloned", branchId: "theview_cloned" });
+
+ await tick(true);
+ expect(outcome()).toBe(`confirm.delete_note_keeps_note:${JSON.stringify({ count: 2 })}`);
+ });
+
+ /**
+ * The dialog is mounted once and lives for the session, so its state is not swept away between
+ * openings the way an unmounted component's would be. A tick left standing was a destructive
+ * default carried over to another note, and to whichever part of the app asked next.
+ */
+ it("does not carry a tick over into the next note it is asked about", async () => {
+ buildSubject("first", "theview");
+ await askAboutNote({ noteId: "first", branchId: "theview_first" });
+ await tick(true);
+ expect(checkbox()?.checked).toBe(true);
+
+ buildSubject("second", "theview");
+ await askAboutNote({ noteId: "second", branchId: "theview_second" });
+
+ expect(checkbox()?.checked).toBe(false);
+ expect(outcome()).toBe("confirm.if_you_dont_check");
+ });
+
+ /** A caller that names no note gets the box bare, as it was before the dialog could tell. */
+ it("offers the box without a verdict where it was told nothing to judge", async () => {
+ await askAboutNote();
+
+ await tick(true);
+ expect(checkbox()).toBeTruthy();
+ expect(outcome()).toBe("");
+ });
+
+ it("offers nothing to tick when it is only being asked to confirm", async () => {
+ await act(async () => {
+ void host.handleEventInChildren("showConfirmDialog", {
+ message: "Sure?",
+ callback: () => {}
+ });
+ });
+
+ expect(checkbox()).toBeNull();
+ expect(container.querySelector(".confirm-delete-note-outcome")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/dialogs/confirm.tsx b/apps/client/src/widgets/dialogs/confirm.tsx
index b1d6cfb5a1..4a1d96190f 100644
--- a/apps/client/src/widgets/dialogs/confirm.tsx
+++ b/apps/client/src/widgets/dialogs/confirm.tsx
@@ -1,7 +1,10 @@
+import "./confirm.css";
+
import Modal from "../react/Modal";
import Button from "../react/Button";
import { t } from "../../services/i18n";
-import { useRef, useState } from "preact/hooks";
+import { describeNoteDeletion, type NoteDeletionTarget, planNoteDeletion } from "../../services/note_deletion";
+import { useMemo, useRef, useState } from "preact/hooks";
import FormCheckbox from "../react/FormCheckbox";
import { useTriliumEvent } from "../react/hooks";
import { isValidElement, type VNode } from "preact";
@@ -12,6 +15,8 @@ interface ConfirmDialogProps {
message?: MessageType;
callback?: ConfirmDialogCallback;
isConfirmDeleteNoteBox?: boolean;
+ deletionTarget?: NoteDeletionTarget;
+ mustDeleteNote?: boolean;
}
export default function ConfirmDialog() {
@@ -20,18 +25,38 @@ export default function ConfirmDialog() {
const [ shown, setShown ] = useState(false);
const okButtonRef = useRef<HTMLButtonElement>(null);
- function showDialog(title: string | null, message: MessageType, callback: ConfirmDialogCallback, isConfirmDeleteNoteBox: boolean) {
+ // What ticking the box would cost, worked out here rather than by whoever opened the dialog: the
+ // question is the same wherever it is asked from, and a caller that had to answer it for itself
+ // would be a caller that could get it wrong.
+ const deleteNoteDescription = useMemo(() => {
+ const { noteId, branchId } = opts?.deletionTarget ?? {};
+ return noteId ? describeNoteDeletion(planNoteDeletion(noteId, branchId)) : undefined;
+ }, [ opts?.deletionTarget ]);
+
+ // Removing the note from where it is shown may leave nothing to decide: a view whose note *is*
+ // what it draws (a GPX track on a geo map) cannot take it off and keep it, so the box would be
+ // one the reader had to tick to get anywhere. The outcome is still shown, being the whole of
+ // 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
+ isConfirmDeleteNoteBox,
+ deletionTarget,
+ mustDeleteNote
});
+ // 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.
+ setIsDeleteNoteChecked(false);
setShown(true);
}
useTriliumEvent("showConfirmDialog", ({ message, callback }) => showDialog(null, message, callback, false));
- useTriliumEvent("showConfirmDeleteNoteBoxWithNoteDialog", ({ title, callback }) => showDialog(title, t("confirm.are_you_sure_remove_note", { title: title }), callback, true));
+ useTriliumEvent("showConfirmDeleteNoteBoxWithNoteDialog", ({ title, message, callback, deletionTarget, mustDeleteNote }) => showDialog(title, message ?? t("confirm.are_you_sure_remove_note", { title: title }), callback, true, deletionTarget, mustDeleteNote));
return (
<Modal
@@ -44,7 +69,7 @@ export default function ConfirmDialog() {
onHidden={() => {
opts?.callback?.({
confirmed: false,
- isDeleteNoteChecked
+ isDeleteNoteChecked: deleteNote
});
setShown(false);
}}
@@ -53,7 +78,7 @@ export default function ConfirmDialog() {
<Button buttonRef={okButtonRef} text={t("confirm.ok")} onClick={() => {
opts?.callback?.({
confirmed: true,
- isDeleteNoteChecked
+ isDeleteNoteChecked: deleteNote
});
setShown(false);
}} />
@@ -66,13 +91,24 @@ export default function ConfirmDialog() {
: <RawHtmlBlock html={opts?.message} />
}
- {opts?.isConfirmDeleteNoteBox && (
- <FormCheckbox
- name="confirm-dialog-delete-note"
- label={t("confirm.also_delete_note")}
- hint={t("confirm.if_you_dont_check")}
- currentValue={isDeleteNoteChecked} onChange={setIsDeleteNoteChecked} />
- )}
+ {opts?.isConfirmDeleteNoteBox && (<>
+ {!opts.mustDeleteNote && (
+ <FormCheckbox
+ name="confirm-dialog-delete-note"
+ label={t("confirm.also_delete_note")}
+ currentValue={isDeleteNoteChecked} onChange={setIsDeleteNoteChecked} />
+ )}
+
+ {/* What the answer means, written out rather than hidden in a tooltip on the box's
+ label: the two answers do quite different things to the tree, and which one a
+ tick would be is not something the reader should have to hover to find out. The
+ line is there in both states so ticking the box does not shift the dialog. */}
+ <p className="confirm-delete-note-outcome">
+ {deleteNote
+ ? deleteNoteDescription
+ : t("confirm.if_you_dont_check")}
+ </p>
+ </>)}
</Modal>
);
}
@@ -91,8 +127,35 @@ export interface ConfirmWithMessageOptions {
callback: ConfirmDialogCallback;
}
-// For "showConfirmDialog"
-export interface ConfirmWithTitleOptions {
+/**
+ * How a view asking to remove a note wants the question put, over and above the note itself.
+ *
+ * Both are things only the caller can know — where the note is being removed *from*, and whether
+ * removing it there can mean anything other than deleting it.
+ */
+export interface ConfirmDeleteNoteBoxOptions {
+ /**
+ * The question, where the stock one does not fit. It names where the note is being removed from,
+ * which is the one thing about this dialog only the caller can say.
+ */
+ message?: MessageType;
+ /**
+ * Removing the note from where it is shown necessarily deletes it, so there is nothing to offer
+ * a choice about: the checkbox is left out and the answer comes back as though it were ticked.
+ * For a view whose note *is* what it draws — a GPX track on a geo map, whose line is drawn from
+ * the note's own file — there is no taking it off and keeping it.
+ */
+ mustDeleteNote?: boolean;
+}
+
+// For "showConfirmDeleteNoteBoxWithNoteDialog"
+export interface ConfirmWithTitleOptions extends ConfirmDeleteNoteBoxOptions {
title: string;
callback: ConfirmDialogCallback;
+ /**
+ * The note being removed, and the placement it is being removed from. Given it, the dialog says
+ * for itself what ticking "Also delete the note" would cost (see {@link NoteDeletionTarget});
+ * without it the box is offered bare, as it was before it could tell.
+ */
+ deletionTarget?: NoteDeletionTarget;
}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/api.spec.ts b/apps/client/src/widgets/type_widgets/relation_map/api.spec.ts
new file mode 100644
index 0000000000..7ca502905b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/api.spec.ts
@@ -0,0 +1,68 @@
+/**
+ * Which of the map's notes it actually files, which is the one thing about deleting them that is the
+ * map's own business — what follows from the answer is the app's (see services/note_deletion.ts).
+ *
+ * A map holds two kinds of note and looks like it holds one: the notes it made itself hang under it
+ * in the tree, while the notes dragged onto it live wherever they lived and are merely named in the
+ * map's content.
+ */
+import { describe, expect, it, vi } from "vitest";
+
+import froca from "../../../services/froca";
+import * as noteDeletion from "../../../services/note_deletion";
+import { buildNote } from "../../../test/easy-froca";
+import RelationMapApi, { MapData } from "./api";
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+/** A map holding the given note, whose content changes this reports rather than saves. */
+function mapOf(noteId: string) {
+ const data: MapData = { notes: [ { noteId, x: 0, y: 0 } ], transform: { x: 0, y: 0, scale: 1 } };
+ return { api: new RelationMapApi(froca.notes["themap"], data, () => {}), data };
+}
+
+describe("RelationMapApi", () => {
+ it("names the branch of a note it made, and none for a note dragged onto it", () => {
+ buildNote({ id: "themap", title: "The map", children: [ { id: "made", title: "Made here" } ] });
+ buildNote({ id: "elsewhere", title: "Elsewhere", children: [ { id: "dragged", title: "Dragged on" } ] });
+ const { api } = mapOf("made");
+
+ expect(api.branchIdFor("made")).toBe("themap_made");
+ expect(api.branchIdFor("dragged")).toBeNull();
+ // Nor for a note that has since gone from froca entirely.
+ expect(api.branchIdFor("vanished")).toBeNull();
+ });
+
+ describe("removeItem", () => {
+ it("hands the note and the map's branch for it to the app's own deletion", async () => {
+ buildNote({ id: "themap", title: "The map", children: [ { id: "made", title: "Made here" } ] });
+ const deletion = vi.spyOn(noteDeletion, "deleteNoteOrBranch").mockResolvedValue(undefined);
+ const { api, data } = mapOf("made");
+
+ try {
+ await api.removeItem("made", true);
+
+ expect(deletion).toHaveBeenCalledWith("made", "themap_made");
+ // And off the map itself, which is the half that happens either way.
+ expect(data.notes).toEqual([]);
+ } finally {
+ deletion.mockRestore();
+ }
+ });
+
+ it("touches the tree not at all where the note is only being taken off the map", async () => {
+ buildNote({ id: "themap", title: "The map", children: [ { id: "made", title: "Made here" } ] });
+ const deletion = vi.spyOn(noteDeletion, "deleteNoteOrBranch").mockResolvedValue(undefined);
+ const { api, data } = mapOf("made");
+
+ try {
+ await api.removeItem("made", false);
+
+ expect(deletion).not.toHaveBeenCalled();
+ expect(data.notes).toEqual([]);
+ } finally {
+ deletion.mockRestore();
+ }
+ });
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/relation_map/api.ts b/apps/client/src/widgets/type_widgets/relation_map/api.ts
index dec79bfa8a..8962991365 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/api.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/api.ts
@@ -1,6 +1,8 @@
import { Connection } from "jsplumb";
import FNote from "../../../entities/fnote";
+import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
+import { deleteNoteOrBranch } from "../../../services/note_deletion";
import server from "../../../services/server";
import utils from "../../../services/utils";
import { RelationMapRelation } from "@triliumnext/commons";
@@ -31,11 +33,26 @@ export default class RelationMapApi {
private data: MapData;
private relations: ClientRelation[];
private onDataChange: (refreshUi: boolean) => void;
+ private mapNote: FNote;
constructor(note: FNote, initialMapData: MapData, onDataChange: (newData: MapData, refreshUi: boolean) => void) {
this.data = initialMapData;
this.onDataChange = (refreshUi) => onDataChange({ ...this.data }, refreshUi);
this.relations = [];
+ this.mapNote = note;
+ }
+
+ /**
+ * The given note's branch under this map, where the map is one of the places it hangs.
+ *
+ * A map holds notes of two kinds and only looks like it holds one: the notes it made itself hang
+ * under it in the tree (see `useNoteCreation` in RelationMap.tsx), while the notes dragged onto
+ * it live wherever they lived and are merely named in the map's content. So there is a branch of
+ * ours to remove for the first and none at all for the second, which is the whole difference
+ * between removing a placement and deleting a note.
+ */
+ branchIdFor(noteId: string) {
+ return froca.getNoteFromCache(noteId)?.parentToBranch[this.mapNote.noteId] ?? null;
}
loadRelations(relations: ClientRelation[]) {
@@ -47,11 +64,17 @@ export default class RelationMapApi {
this.onDataChange(true);
}
- async removeItem(noteId: string, deleteNoteToo: boolean) {
- console.log("Remove ", noteId, deleteNoteToo);
- if (deleteNoteToo) {
- const taskId = utils.randomString(10);
- await server.remove(`notes/${noteId}?taskId=${taskId}&last=true`);
+ /**
+ * Takes the note off the map, and out of the tree as well where asked.
+ *
+ * Which of the two deletions that second half is — the map's placement of the note, or the note
+ * itself — is `deleteFromTree`'s business no more than it is the reader's: the branch decides it
+ * (see {@link branchIdFor}), and `deleteNoteOrBranch` reads the same branch the dialog read when
+ * it told the reader what ticking the box would cost.
+ */
+ async removeItem(noteId: string, deleteFromTree: boolean) {
+ if (deleteFromTree) {
+ await deleteNoteOrBranch(noteId, this.branchIdFor(noteId));
}
if (this.data) {
diff --git a/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts b/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
index 896b2c171c..35710451b0 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
@@ -47,7 +47,14 @@ export function buildNoteContextMenuHandler(note: FNote | null | undefined, mapA
uiIcon: "bx bx-trash",
handler: async () => {
if (!note) return;
- const result = await dialog.confirmDeleteNoteBoxWithNote(note.title);
+
+ // The branch is all the dialog is told: from it, it works out for itself
+ // whether ticking the box would delete the note or merely unfile it here,
+ // and says so (see confirmDeleteNoteBoxWithNote).
+ const result = await dialog.confirmDeleteNoteBoxWithNote(note.title, {
+ noteId: note.noteId,
+ branchId: mapApiRef.current?.branchIdFor(note.noteId)
+ });
if (typeof result !== "object" || !result.confirmed) return;
mapApiRef.current?.removeItem(note.noteId, result.isDeleteNoteChecked);