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 adding existing notes to the board by using a picker
Adorian Doranfd9f253e628d
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 5a853c8042..1ea590bd6e 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -26,6 +26,7 @@ import type { InfoProps } from "../widgets/dialogs/info.jsx";import type { MarkdownImportOpts } from "../widgets/dialogs/markdown_import.jsx";import { ChooseNoteTypeCallback } from "../widgets/dialogs/note_type_chooser.jsx";import type { PrintPreviewData } from "../widgets/dialogs/print_preview.jsx";+import type { NotePickerDialogOptions } from "../widgets/dialogs/note_picker.js";import type { PromptDialogOptions } from "../widgets/dialogs/prompt.js";import type NoteTreeWidget from "../widgets/note_tree.js";import type { RightPaneTabId } from "../widgets/sidebar/RightPaneTabs.jsx";@@ -150,6 +151,7 @@ export type CommandMappings = {isNewNote?: boolean;};showPromptDialog: PromptDialogOptions;+ showNotePickerDialog: NotePickerDialogOptions;showInfoDialog: InfoProps;showConfirmDialog: ConfirmWithMessageOptions;showRecentChanges: CommandData & { ancestorNoteId: string };diff --git a/apps/client/src/layouts/layout_commons.tsx b/apps/client/src/layouts/layout_commons.tsxindex 37e460b016..efa949cbcd 100644--- a/apps/client/src/layouts/layout_commons.tsx+++ b/apps/client/src/layouts/layout_commons.tsx@@ -19,6 +19,7 @@ export function applyModals(rootContainer: RootContainer) {.child(<LazyDialog triggerEvents={["editBranchPrefix"]} loader={() => import("../widgets/dialogs/branch_prefix.js")} />).child(<LazyDialog triggerEvents={["sortChildNotes"]} loader={() => import("../widgets/dialogs/sort_child_notes.js")} />).child(<LazyDialog triggerEvents={["showIncludeNoteDialog"]} loader={() => import("../widgets/dialogs/include_note.js")} />)+ .child(<LazyDialog triggerEvents={["showNotePickerDialog"]} loader={() => import("../widgets/dialogs/note_picker.js")} />).child(<LazyDialog triggerEvents={["chooseNoteType"]} loader={() => import("../widgets/dialogs/note_type_chooser.js")} />).child(<LazyDialog triggerEvents={["jumpToNote", "commandPalette"]} loader={() => import("../widgets/dialogs/jump_to_note.js")} />).child(<LazyDialog triggerEvents={["showAddLinkDialog"]} loader={() => import("../widgets/dialogs/add_link.js")} />)diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.tsindex dc1f28823e..bb24dbfea3 100644--- a/apps/client/src/services/dialog.ts+++ b/apps/client/src/services/dialog.ts@@ -1,3 +1,4 @@+import type { NotePickerDialogOptions } from "../widgets/dialogs/note_picker.js";import { Modal } from "bootstrap";import appContext from "../components/app_context.js";@@ -222,12 +223,19 @@ async function confirmDeleteNoteBoxWithNote(title: string, deletionTarget?: Notereturn new Promise<ConfirmDialogResult | undefined>((res) => appContext.triggerCommand("showConfirmDeleteNoteBoxWithNoteDialog", { ...options, title, callback: res, deletionTarget }));}+/** Asks for a note, resolving to its id or to null where the reader picked none. */+export async function chooseNote(props: Omit<NotePickerDialogOptions, "callback"> = {}) {+ return new Promise<string | null>((res) =>+ appContext.triggerCommand("showNotePickerDialog", { ...props, callback: res }));+}+export async function prompt(props: PromptDialogOptions) {return new Promise<string | null>((res) => appContext.triggerCommand("showPromptDialog", { ...props, callback: res }));}export default {info,+ chooseNote,confirm,confirmDeleteNoteBoxWithNote,promptdiff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex fbd3887e9a..698a8bbfa0 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1360,6 +1360,11 @@"too-many-notes_other": "There are {{count}} notes here. Showing them all may slow things down.","show-anyway": "Show map"},+ "note_picker": {+ "title": "Choose a note",+ "label": "Note",+ "ok": "Choose"+ },"note_paths": {"title": "Note Paths","clone_button": "Clone note to new location...",@@ -3351,6 +3356,10 @@"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.","new-item": "New item","new-item-placeholder": "Enter note title...",+ "add-existing-item": "Add existing note...",+ "add-existing-item-title": "Add an existing note to the board",+ "add-existing-item-ok": "Add to column",+ "existing-item-conflict": "This note already belongs to another board that groups by “{{label}}”. Adding it here will move it to a different column on the original board as well. Add it anyway?","add-column": "Add Column","add-column-placeholder": "Enter column name...","edit-note-title": "Click to edit note title",diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 09a841cfae..4f73ec6a8a 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -1,7 +1,9 @@import { beforeEach, describe, expect, it, vi } from "vitest";import FAttribute from "../../../entities/fattribute";+import branches from "../../../services/branches";import { executeBulkActions } from "../../../services/bulk_action";+import dialog from "../../../services/dialog";import FNote from "../../../entities/fnote";import froca from "../../../services/froca";import noteAttributeCache from "../../../services/note_attribute_cache";@@ -20,6 +22,14 @@ function failNextBulkAction() {vi.mocked(executeBulkActions).mockRejectedValueOnce(new Error("offline"));}+vi.mock("../../../services/branches", () => ({+ default: { cloneNoteToParentNote: vi.fn(async () => {}) }+}));++vi.mock("../../../services/dialog", () => ({+ default: { confirm: vi.fn(async () => true) }+}));+vi.mock("../../../services/i18n", () => ({// i18next is never initialised under test, so the real `t` yields nothing and the alias would// silently vanish from the definitions asserted below rather than being checked.@@ -280,6 +290,79 @@ describe("BoardApi column mutations", () => {* `_template_board` no longer defines the status label, so a board created afterwards has no* definition at all until the board view writes one from the columns it resolved.*/+describe("BoardApi.addExistingItem", () => {+ let put: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ put = vi.spyOn(server, "put").mockResolvedValue(undefined);+ vi.mocked(branches.cloneNoteToParentNote).mockClear();+ vi.mocked(dialog.confirm).mockClear().mockResolvedValue(true);+ });++ /**+ * A board holding `insider` a level down, alongside an unrelated `outsider`.+ *+ * The ids are generated rather than fixed: `buildNote` appends to the note attribute cache+ * under the id given, so one reused across tests carries the previous test's attributes.+ */+ function createBoardWith(outsiderAttributes: Record<string, string> = {}) {+ const board = buildNote({+ title: "Board",+ children: [+ { title: "Branch", children: [ { title: "Insider", "#status": "To Do" } ] }+ ]+ });+ const outsider = buildNote({ title: "Outsider", ...outsiderAttributes });+ const branch = froca.getNoteFromCache(board.getChildNoteIds()[0]);++ return {+ api: createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ], board).api,+ boardId: board.noteId,+ insiderId: branch?.getChildNoteIds()[0] ?? "",+ outsiderId: outsider.noteId+ };+ }++ it("clones a note from outside the board, then files it in the column", async () => {+ const { api, boardId, outsiderId } = createBoardWith();++ expect(await api.addExistingItem("To Do", outsiderId)).toBe(true);+ expect(branches.cloneNoteToParentNote).toHaveBeenCalledWith(outsiderId, boardId);++ const [ url, body ] = put.mock.calls.at(-1) ?? [];+ expect(url).toBe(`notes/${outsiderId}/set-attribute`);+ expect(body).toMatchObject({ type: "label", name: "status", value: "To Do" });+ });++ // The board shows its whole subtree, so a grandchild is already on it.+ it("only changes the column of a note already under the board", async () => {+ const { api, insiderId } = createBoardWith();++ expect(await api.addExistingItem("To Do", insiderId)).toBe(true);+ expect(branches.cloneNoteToParentNote).not.toHaveBeenCalled();+ });++ it("warns before taking a note that carries the grouping label from elsewhere", async () => {+ const { api, outsiderId } = createBoardWith({ "#status": "Done" });++ expect(await api.addExistingItem("To Do", outsiderId)).toBe(true);+ expect(dialog.confirm).toHaveBeenCalledTimes(1);++ vi.mocked(dialog.confirm).mockResolvedValue(false);+ vi.mocked(branches.cloneNoteToParentNote).mockClear();++ expect(await api.addExistingItem("To Do", outsiderId)).toBe(false);+ expect(branches.cloneNoteToParentNote).not.toHaveBeenCalled();+ });++ it("does not warn for a note that carries no value of its own", async () => {+ const { api, outsiderId } = createBoardWith();++ await api.addExistingItem("To Do", outsiderId);+ expect(dialog.confirm).not.toHaveBeenCalled();+ });+});+describe("BoardApi.syncColumnsToDefinition", () => {let put: ReturnType<typeof vi.spyOn>;diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 306741df8b..255e79f231 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -5,6 +5,7 @@ import FNote from "../../../entities/fnote";import attributes from "../../../services/attributes";import branches from "../../../services/branches";import { executeBulkActions } from "../../../services/bulk_action";+import dialog from "../../../services/dialog";import froca from "../../../services/froca";import { t } from "../../../services/i18n";import note_create from "../../../services/note_create";@@ -55,6 +56,41 @@ export default class BoardApi {}}+ /**+ * Puts a note that already exists into a column, cloning it onto the board unless it is already+ * somewhere beneath it.+ *+ * A note that already carries a value for the label the board groups by is on some other board+ * grouped the same way, or is about to look like it: the value is the note's, not the board's,+ * so writing ours moves it there too. Worth knowing but not worth refusing, since a note+ * tracked on two boards is a fair thing to want.+ *+ * @returns whether the note was added, `false` when the user backed out.+ */+ async addExistingItem(column: string, noteId: string) {+ const note = await froca.getNote(noteId, true);+ if (!note) return false;++ const isAlreadyOnBoard = note.hasAncestor(this.parentNote.noteId);+ const currentValue = this.isRelationMode+ ? note.getRelationValue(this.statusAttribute)+ : note.getLabelValue(this.statusAttribute);++ if (!isAlreadyOnBoard && currentValue) {+ const confirmed = await dialog.confirm(t("board_view.existing-item-conflict", {+ label: this.statusAttribute+ }));+ if (!confirmed) return false;+ }++ if (!isAlreadyOnBoard) {+ await branches.cloneNoteToParentNote(noteId, this.parentNote.noteId);+ }++ await this.changeColumn(noteId, column);+ return true;+ }+async changeColumn(noteId: string, newColumn: string) {if (this.isRelationMode) {await attributes.setRelation(noteId, this.statusAttribute, newColumn);diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 1fd7243ab8..64039cf677 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -71,7 +71,7 @@ export default function Column({color,archived,onEditTitle: () => setColumnNameToEdit(column),- onNewNote: () => setIsCreatingNewItem(true)+ onNewItem: () => setIsCreatingNewItem(true)});}, [ api, column, color, archived, setColumnNameToEdit ]);diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsindex 7cbd632669..91f5bb1f87 100644--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -3,6 +3,7 @@ import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";import contextMenu, { ContextMenuEvent } from "../../../menus/context_menu";+import dialog from "../../../services/dialog";import BoardApi from "./api";import { openColumnContextMenu } from "./context_menu";@@ -21,7 +22,10 @@ describe("Board column context menu", () => {function openMenu(api: BoardApi,column: { color?: string, archived?: boolean } = {},- callbacks: { onEditTitle?: () => void, onNewNote?: () => void } = {}+ callbacks: {+ onEditTitle?: () => void,+ onNewItem?: () => void+ } = {}) {const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});const event = {@@ -35,7 +39,7 @@ describe("Board column context menu", () => {value: "To Do",...column,onEditTitle: callbacks.onEditTitle ?? (() => {}),- onNewNote: callbacks.onNewNote ?? (() => {})+ onNewItem: callbacks.onNewItem ?? (() => {})});// The spy outlives one call, so it is the menu just opened that is read back.@@ -93,17 +97,43 @@ describe("Board column context menu", () => {it("orders the entries, keeping the safe way out ahead of deleting", () => {const titled = openMenu({} as BoardApi).filter(item => item && "uiIcon" in item);expect(titled.map(item => "uiIcon" in item ? item.uiIcon : undefined))- .toEqual([ "bx bx-edit-alt", "bx bx-plus", "bx bx-archive", "bx bx-trash" ]);+ .toEqual([+ "bx bx-edit-alt", "bx bx-plus", "bx bx-link", "bx bx-archive", "bx bx-trash"+ ]);});it("opens the column's new-item editor, the same one its button opens", () => {- const onNewNote = vi.fn();- const entry = openMenu({} as BoardApi, {}, { onNewNote })+ const onNewItem = vi.fn();+ const entry = openMenu({} as BoardApi, {}, { onNewItem }).find(item => item && "uiIcon" in item && item.uiIcon === "bx bx-plus");if (!entry || !("handler" in entry)) throw new Error("expected a new-item entry");entry.handler?.(entry, {} as never);- expect(onNewNote).toHaveBeenCalled();+ expect(onNewItem).toHaveBeenCalled();+ });++ it("asks for a note, then adds the one chosen to the column", async () => {+ const api = { addExistingItem: vi.fn(async () => true) } as unknown as BoardApi;+ vi.spyOn(dialog, "chooseNote").mockResolvedValue("pickedNote");++ const entry = openMenu(api)+ .find(item => item && "uiIcon" in item && item.uiIcon === "bx bx-link");+ if (!entry || !("handler" in entry)) throw new Error("expected an add-existing entry");++ await entry.handler?.(entry, {} as never);+ expect(api.addExistingItem).toHaveBeenCalledWith("To Do", "pickedNote");+ });++ it("adds nothing when no note is chosen", async () => {+ const api = { addExistingItem: vi.fn(async () => true) } as unknown as BoardApi;+ vi.spyOn(dialog, "chooseNote").mockResolvedValue(null);++ const entry = openMenu(api)+ .find(item => item && "uiIcon" in item && item.uiIcon === "bx bx-link");+ if (!entry || !("handler" in entry)) throw new Error("expected an add-existing entry");++ await entry.handler?.(entry, {} as never);+ expect(api.addExistingItem).not.toHaveBeenCalled();});it("shows the column's own colour as the selected one", async () => {diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.tsindex 702285e2c2..9a13f99531 100644--- a/apps/client/src/widgets/collections/board/context_menu.ts+++ b/apps/client/src/widgets/collections/board/context_menu.ts@@ -18,7 +18,7 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:/** Puts the title into its inline editor, the menu being the only way there besides F2. */onEditTitle: () => void;/** Opens the column's own new-item editor, the same one its button opens. */- onNewNote: () => void;+ onNewItem: () => void;}) {event.preventDefault();event.stopPropagation();@@ -36,7 +36,20 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:{title: t("board_view.new-item"),uiIcon: "bx bx-plus",- handler: column.onNewNote+ handler: column.onNewItem+ },+ {+ title: t("board_view.add-existing-item"),+ uiIcon: "bx bx-link",+ async handler() {+ const noteId = await dialog.chooseNote({+ title: t("board_view.add-existing-item-title"),+ okLabel: t("board_view.add-existing-item-ok")+ });+ if (noteId) {+ await api.addExistingItem(column.value, noteId);+ }+ }},{ kind: "separator" },column.archiveddiff --git a/apps/client/src/widgets/dialogs/note_picker.tsx b/apps/client/src/widgets/dialogs/note_picker.tsxnew file mode 100644index 0000000000..26f56f6010--- /dev/null+++ b/apps/client/src/widgets/dialogs/note_picker.tsx@@ -0,0 +1,83 @@+import { useRef, useState } from "preact/hooks";++import { t } from "../../services/i18n";+import { Suggestion, triggerRecentNotes } from "../../services/note_autocomplete";+import tree from "../../services/tree";+import Button from "../react/Button";+import FormGroup from "../react/FormGroup";+import { useTriliumEvent } from "../react/hooks";+import Modal from "../react/Modal";+import NoteAutocomplete from "../react/NoteAutocomplete";++export interface NotePickerDialogOptions {+ /** Names what the note is wanted for; the stock title only asks for one. */+ title?: string;+ /** What the search box is labelled with. */+ message?: string;+ /** What accepting is called, for a caller that can name the act more plainly than "OK". */+ okLabel?: string;+ callback?: (noteId: string | null) => void;+}++/**+ * Asks for one note from anywhere in the document, reported to the caller as a note id.+ *+ * The picking is the autocomplete's, which is what every other note field in the app is built on;+ * this only wraps it in something a caller with no field of its own can open, such as a context+ * menu. Reach it through `dialog.chooseNote()` rather than the command, which is what turns the+ * answer into a promise.+ */+export default function NotePickerDialog() {+ const opts = useRef<NotePickerDialogOptions>();+ const inputRef = useRef<HTMLInputElement>(null);+ const [ suggestion, setSuggestion ] = useState<Suggestion | null>(null);+ const [ shown, setShown ] = useState(false);+ // Held apart from the suggestion because the answer is reported once the modal is out of the+ // way, by when dismissing it has already cleared what was picked.+ const pickedNoteId = useRef<string | null>(null);++ useTriliumEvent("showNotePickerDialog", (newOpts) => {+ opts.current = newOpts;+ setSuggestion(null);+ setShown(true);+ });++ return (+ <Modal+ className="note-picker-dialog"+ title={opts.current?.title ?? t("note_picker.title")}+ size="lg"+ zIndex={2000}+ onShown={() => triggerRecentNotes(inputRef.current)}+ onSubmit={() => {+ pickedNoteId.current = tree.getNoteIdFromUrl(suggestion?.notePath);+ setShown(false);+ }}+ onHidden={() => {+ setShown(false);+ opts.current?.callback?.(pickedNoteId.current);+ pickedNoteId.current = null;+ opts.current = undefined;+ }}+ footer={<>+ <Button text={t("modal.cancel")} onClick={() => setShown(false)} />+ <Button+ text={opts.current?.okLabel ?? t("note_picker.ok")}+ keyboardShortcut="Enter"+ kind="primary"+ disabled={!suggestion?.notePath}+ />+ </>}+ show={shown}+ stackable+ >+ <FormGroup name="note-picker-note" label={opts.current?.message ?? t("note_picker.label")}>+ <NoteAutocomplete+ inputRef={inputRef}+ onChange={setSuggestion}+ opts={{ hideAllButtons: true }}+ />+ </FormGroup>+ </Modal>+ );+}