Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into feature/relation_map_improvements

Elian Doran31c0c06b7e45
diff --cc apps/client/src/translations/en/translation.json
index 22bca1996e,9638b9e732..1449496bc2
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@@ -1218,23 -1203,9 +1203,11 @@@
"opening_api_docs_message": "Opening API docs...",
"sql_console_saved_message": "SQL Console note has been saved into {{note_path}}"
},
- "copy_image_reference_button": {
- "button_title": "Copy image reference to the clipboard, can be pasted into a text note."
- },
- "hide_floating_buttons_button": {
- "button_title": "Hide buttons"
- },
- "show_floating_buttons_button": {
- "button_title": "Show buttons"
- },
- "svg_export_button": {
- "button_title": "Export diagram as SVG"
- },
"relation_map_buttons": {
"create_child_note_title": "Create child note and add it to map",
- "create_child_note_text": "Add note"
+ "create_child_note_text": "Add note",
+ "create_child_note_cancel_title": "Cancel adding the note",
+ "create_child_note_cancel_text": "Cancel"
},
"image_navigation": {
"previous": "Previous image: {{- title}}",
diff --cc apps/client/src/widgets/EmbeddedNotePane.tsx
index 3fb44f6de4,d58c26502b..f4eca7a7b1
--- a/apps/client/src/widgets/EmbeddedNotePane.tsx
+++ b/apps/client/src/widgets/EmbeddedNotePane.tsx
@@@ -12,14 -11,11 +12,14 @@@ import NoteColorPicker from "../menus/c
import linkContextMenu from "../menus/link_context_menu";
import { t } from "../services/i18n";
import link from "../services/link";
- import { isMobile } from "../services/utils";
-import { randomString } from "../services/utils";
++import { isMobile, randomString } from "../services/utils";
+import TitleRow from "./layout/TitleRow";
import ActionButton from "./react/ActionButton";
import Dropdown, { DropdownPanel } from "./react/Dropdown";
import { FormListItem } from "./react/FormList";
- import { useLegacyComponentElement, useNoteColorClass, useNoteContext } from "./react/hooks";
-import { useDetachedNoteContext, useNoteContext } from "./react/hooks";
++import { useDetachedNoteContext, useLegacyComponentElement, useNoteColorClass, useNoteContext } from "./react/hooks";
+import Modal from "./react/Modal";
+import OverlayPanel, { OverlayPanelBody } from "./react/OverlayPanel";
import { NoteContextContext, ParentComponent } from "./react/react_utils";
/*
diff --cc apps/client/src/widgets/type_widgets/relation_map/NotePane.spec.tsx
index 36afa272d7,0000000000..b5ce920297
mode 100644,000000..100644
--- a/apps/client/src/widgets/type_widgets/relation_map/NotePane.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/NotePane.spec.tsx
@@@ -1,200 -1,0 +1,203 @@@
+import { render } from "preact";
+import { useRef, useState } from "preact/hooks";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import appContext from "../../../components/app_context";
+import Component from "../../../components/component";
+import server from "../../../services/server";
+import { buildNote } from "../../../test/easy-froca";
+import { useNoteContext, useTriliumEvent } from "../../react/hooks";
+import { ParentComponent } from "../../react/react_utils";
+import type RelationMapApi from "./api";
+import NotePane, { type NotePaneHandle, type PaneSelection } from "./NotePane";
+
+/** Stub for the note's editor, listening for `beforeNoteContextRemove` as the real editor does. */
+const editorAskedToSave = vi.fn();
+vi.mock("../../NoteDetail", () => ({
+ default: () => {
+ const { note } = useNoteContext();
+ useTriliumEvent("beforeNoteContextRemove", editorAskedToSave);
+ return <div className="note-detail-stub">{note?.title}</div>;
+ }
+}));
+
+const confirmDelete = vi.fn();
+vi.mock("../../../services/dialog", async (importOriginal) => ({
+ default: {
+ ...((await importOriginal<{ default: object }>()).default),
+ confirmDeleteNoteBoxWithNote: (...args: unknown[]) => confirmDelete(...args)
+ }
+}));
+
+// Promoted text fields request autocomplete values from the server.
+server.get = (async () => []) as unknown as typeof server.get;
+
+interface MountOptions {
+ noteIdsOnMap?: string[];
+ isReadOnly?: boolean;
+ selection?: PaneSelection | null;
+}
+
+describe("relation map NotePane", () => {
+ let container: HTMLElement | undefined;
+ let mapComponent: Component | undefined;
+ let handle: { current: NotePaneHandle | null } = { current: null };
+ const removeItem = vi.fn();
+ const mapApi = { branchIdFor: () => "branch", removeItem } as unknown as RelationMapApi;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ (appContext as unknown as { tabManager: unknown }).tabManager = {
+ getActiveContext: () => undefined,
- getActiveContextNotePath: () => undefined
++ getActiveContextNotePath: () => undefined,
++ registerDetachedContext: () => undefined,
++ unregisterDetachedContext: () => undefined
+ };
+ buildNote({
+ id: "root", title: "root", children: [
+ { id: "mapnote", title: "Map", children: [
+ { id: "first", title: "First" },
+ { id: "second", title: "Second" }
+ ] }
+ ]
+ });
+ editorAskedToSave.mockClear();
+ removeItem.mockClear();
+ confirmDelete.mockReset();
+ });
+
+ afterEach(() => {
+ if (container) {
- render(null, container);
++ const mounted = container;
++ act(() => render(null, mounted));
+ container.remove();
+ container = undefined;
+ }
+ mapComponent = undefined;
+ (appContext as unknown as { tabManager: unknown }).tabManager = undefined;
+ });
+
+ /** Stub for `RelationMap`, which owns the selection and the list of notes on the map. */
+ function Harness({ noteIdsOnMap, isReadOnly, initialSelection }: {
+ noteIdsOnMap: string[]; isReadOnly: boolean; initialSelection: PaneSelection | null;
+ }) {
+ const [ selection, setSelection ] = useState(initialSelection);
+ const paneRef = useRef<NotePaneHandle>(null);
+ handle = paneRef;
+ const mapApiRef = useRef(mapApi);
+ return <NotePane
+ paneRef={paneRef} noteIdsOnMap={noteIdsOnMap} mapApiRef={mapApiRef}
+ isReadOnly={isReadOnly} selection={selection} onSelect={setSelection}
+ />;
+ }
+
+ /** Mounts the pane afresh, with the map's selection set to `selection`. */
+ async function mount(options: MountOptions = {}) {
+ if (container) render(null, container);
+ await update(options);
+ }
+
+ /** Re-renders with new props, keeping the selection the pane has now. */
+ async function update({ noteIdsOnMap = [ "first", "second" ], isReadOnly = false, selection = { noteId: "first" } }: MountOptions = {}) {
+ mapComponent ??= new Component();
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={mapComponent as Component}>
+ <Harness noteIdsOnMap={noteIdsOnMap} isReadOnly={isReadOnly} initialSelection={selection} />
+ </ParentComponent.Provider>,
+ container as HTMLElement
+ );
+ });
+ await settle();
+ }
+
+ async function settle() {
+ await act(async () => {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve));
+ });
+ }
+
+ const pane = () => container?.querySelector(".relation-map-note-pane") ?? null;
+ const title = () => pane()?.querySelector<HTMLInputElement>(".title-row input")?.value;
+
+ it("shows the selected note, and closes from its button after asking the editor to save", async () => {
+ await mount();
+
+ expect(title()).toBe("First");
+ expect(pane()?.querySelector(".note-detail-stub")?.textContent).toBe("First");
+
+ const close = pane()?.querySelector<HTMLButtonElement>(".tn-overlay-panel-close");
+ expect(close).toBeTruthy();
+ await act(async () => close?.click());
+
+ expect(editorAskedToSave).toHaveBeenCalledTimes(1);
+ expect(pane()).toBeNull();
+ });
+
+ it("closes on Escape and through the handle the map holds", async () => {
+ await mount();
+ await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });
+ expect(pane()).toBeNull();
+
+ await mount({ selection: { noteId: "second" } });
+ expect(title()).toBe("Second");
+ await act(async () => handle.current?.close());
+ expect(editorAskedToSave).toHaveBeenCalled();
+ expect(pane()).toBeNull();
+ });
+
+ it("stays closed for a note that is not on the map, and closes once its note leaves it", async () => {
+ await mount({ noteIdsOnMap: [ "second" ] });
+ expect(pane()).toBeNull();
+
+ await mount({ selection: { noteId: "second" } });
+ expect(title()).toBe("Second");
+
+ await update({ noteIdsOnMap: [ "first" ] });
+ expect(pane()).toBeNull();
+ });
+
+ it("switches to a note on the map when a link to it is followed inside the pane", async () => {
+ await mount();
+
+ const anchor = document.createElement("a");
+ anchor.setAttribute("href", "#root/mapnote/second");
+ pane()?.querySelector(".relation-map-note-pane-body")?.appendChild(anchor);
+ await act(async () => anchor.click());
+ await settle();
+
+ expect(title()).toBe("Second");
+ });
+
+ it("removes the note from the map once confirmed, and offers no edits on a read-only map", async () => {
+ confirmDelete.mockResolvedValue({ confirmed: true, isDeleteNoteChecked: false });
+ await mount();
+
+ const remove = pane()?.querySelector<HTMLButtonElement>(".tn-embedded-note-remove");
+ expect(remove).toBeTruthy();
+ await act(async () => remove?.click());
+ await settle();
+ expect(removeItem).toHaveBeenCalledWith("first", false);
+
+ await mount({ isReadOnly: true });
+ expect(pane()).toBeTruthy();
+ expect(pane()?.querySelector(".tn-embedded-note-remove")).toBeNull();
+ expect(pane()?.querySelector(".tn-embedded-note-color")).toBeNull();
+ });
+
+ it("keeps wheel and double clicks inside the pane from reaching the map", async () => {
+ const reached = vi.fn();
+ container?.addEventListener("wheel", reached);
+ container?.addEventListener("dblclick", reached);
+ await mount();
+
+ const body = pane()?.querySelector(".relation-map-note-pane-body");
+ expect(body).toBeTruthy();
+ body?.dispatchEvent(new WheelEvent("wheel", { bubbles: true }));
+ body?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+
+ expect(reached).not.toHaveBeenCalled();
+ });
+});
diff --cc apps/client/src/widgets/type_widgets/relation_map/NotePane.tsx
index a107173738,0000000000..28e40a49f6
mode 100644,000000..100644
--- a/apps/client/src/widgets/type_widgets/relation_map/NotePane.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/NotePane.tsx
@@@ -1,139 -1,0 +1,137 @@@
+import "./NotePane.css";
+
+import { RefObject } from "preact";
+import { useCallback, useEffect, useImperativeHandle, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import { isMobile } from "../../../services/utils";
+import { announceEmbeddedNoteClosing, EmbeddedNoteActions, EmbeddedNoteScope, EmbeddedNoteSurface, NoteColorAction, OpenNoteActions, SelectTitleOnFirstOpen, useEmbeddedNoteContext } from "../../EmbeddedNotePane";
+import NoteDetail from "../../NoteDetail";
+import PromotedAttributes from "../../PromotedAttributes";
+import ActionButton from "../../react/ActionButton";
+import { useNote } from "../../react/hooks";
+import RelationMapApi from "./api";
+import { confirmRemoveFromMap } from "./context_menu";
+
+/** The note shown in the pane. `RelationMap` owns it, so it can open the pane on a note it created. */
+export interface PaneSelection {
+ noteId: string;
+ /** The note was just created; the pane opens with its default title selected. */
+ isNew?: boolean;
+}
+
+export interface NotePaneHandle {
+ /** Closes the pane, giving the note's editor the chance to save first. */
+ close(): void;
+}
+
+/**
+ * Panel at the trailing edge of a relation map that shows the selected note's title, promoted
+ * attributes and content for editing.
+ */
+export default function NotePane({ paneRef, noteIdsOnMap, mapApiRef, isReadOnly, selection, onSelect }: {
+ paneRef: RefObject<NotePaneHandle | null>;
+ /** IDs of the notes on the map. The pane closes when its note is not among them, and a link in
+ * the pane switches the pane only to a note among them. */
+ noteIdsOnMap: string[];
+ mapApiRef: RefObject<RelationMapApi | null>;
+ /** Hides the color and remove buttons, leaving only the buttons that open the note. */
+ isReadOnly: boolean;
+ /** The note the pane shows, or `null` while the pane is closed. */
+ selection: PaneSelection | null;
+ onSelect(selection: PaneSelection | null): void;
+}) {
+ const note = useNote(selection?.noteId, true);
+ const [ maximized, setMaximized ] = useState(false);
- const { noteContext, component: paneComponent } = useEmbeddedNoteContext(note ?? undefined, PANE_NTX_ID_PREFIX);
++ const { noteContext, component: paneComponent, ntxId } = useEmbeddedNoteContext(note ?? undefined, PANE_NTX_ID_PREFIX);
+
+ const closePane = useCallback(() => {
- if (noteContext.ntxId) {
- void announceEmbeddedNoteClosing(paneComponent, noteContext.ntxId);
- }
++ void announceEmbeddedNoteClosing(paneComponent, ntxId);
+ onSelect(null);
- }, [ paneComponent, noteContext, onSelect ]);
++ }, [ paneComponent, ntxId, onSelect ]);
+ useImperativeHandle<NotePaneHandle | null, NotePaneHandle | null>(paneRef, () => ({ close: closePane }), [ closePane ]);
+
+ const followLink = useCallback((noteId: string) => {
+ if (!noteIdsOnMap.includes(noteId)) return false;
+ onSelect({ noteId });
+ return true;
+ }, [ noteIdsOnMap, onSelect ]);
+
+ // Resets the maximized state when the pane closes, so the pane reopens at its normal width.
+ useEffect(() => {
+ if (!selection) setMaximized(false);
+ }, [ selection ]);
+
+ // Closes the pane when its note is removed from the map or deleted.
+ const isOnMap = !!selection && noteIdsOnMap.includes(selection.noteId);
+ useEffect(() => {
+ if (selection && (!isOnMap || note === null)) {
+ closePane();
+ }
+ }, [ selection, isOnMap, note, closePane ]);
+
+ // On mobile, the `Modal` handles Escape itself.
+ useEffect(() => {
+ if (!selection || isMobile()) return;
+
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === "Escape") closePane();
+ };
+ // Capture phase, because `OverlayPanel` stops key presses inside it from bubbling.
+ window.addEventListener("keydown", onKeyDown, true);
+ return () => window.removeEventListener("keydown", onKeyDown, true);
+ }, [ selection?.noteId, closePane ]);
+
+ if (!note || !isOnMap) return null;
+
+ return (
+ // Stops wheel, double-click and touch events in the pane from reaching `panzoom`, which
+ // listens on the whole map.
+ <div
+ className="relation-map-note-pane-host"
+ onWheel={stopPropagation}
+ onDblClick={stopPropagation}
+ onTouchStart={stopPropagation}
+ >
+ <EmbeddedNoteScope component={paneComponent} noteContext={noteContext}>
+ <EmbeddedNoteSurface
+ note={note}
+ panelClassName="relation-map-note-pane"
+ sheetClassName="relation-map-note-sheet"
+ bodyClassName="relation-map-note-pane-body"
+ closeText={t("relation_map.close_note_pane")}
+ maximize={{
+ maximized,
+ onChange: setMaximized,
+ expandText: t("relation_map.expand_note_pane"),
+ restoreText: t("relation_map.restore_note_pane")
+ }}
+ onClose={closePane}
+ onFollowLink={followLink}
+ >
+ <EmbeddedNoteActions>
+ <OpenNoteActions note={note} />
+ {!isReadOnly && <>
+ <NoteColorAction note={note} title={t("relation_map.note_color")} />
+ <ActionButton
+ className="tn-embedded-note-remove"
+ icon="bx bx-trash"
+ text={t("relation_map.remove_from_map")}
+ onClick={() => void confirmRemoveFromMap(note, mapApiRef)}
+ />
+ </>}
+ </EmbeddedNoteActions>
+ <PromotedAttributes />
+ <NoteDetail />
+ </EmbeddedNoteSurface>
+ {selection?.isNew && <SelectTitleOnFirstOpen />}
+ </EmbeddedNoteScope>
+ </div>
+ );
+}
+
+const PANE_NTX_ID_PREFIX = "_relation-map-note-pane";
+
+function stopPropagation(e: Event) {
+ e.stopPropagation();
+}