Skip to content

Build your personal knowledge base with Trilium Notes

feat(relation_map): name a relation in a popover beside it

Elian Doran7ec97cb984c1
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 0a45c517ae..b6b7b04808 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1697,6 +1697,10 @@
"rename_note": "Rename note",
"enter_new_title": "Enter new note title:",
"rename_relation": "Rename relation",
+ "rename": "Rename",
+ "new_relation": "New relation",
+ "create_relation": "Create relation",
+ "relation_name_placeholder": "Relation name",
"remove_relation": "Remove relation",
"confirm_remove_relation": "Are you sure you want to remove the relation?",
"specify_new_relation_name": "Specify new relation name (allowed characters: alphanumeric, colon and underscore):",
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
index f5559d512f..17752143ac 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
@@ -23,7 +23,8 @@ import { JsPlumb } from "./jsplumb";
import MapToolbar, { EditToolbar } from "./MapToolbar";
import { NoteBox } from "./NoteBox";
import setupOverlays, { uniDirectionalOverlays } from "./overlays";
-import { getMousePosition, getZoom, idToNoteId, noteIdToId, promptForRelationName } from "./utils";
+import RelationNamePopover, { type AskRelationName, useRelationNamePrompt } from "./RelationNamePopover";
+import { getMousePosition, getZoom, idToNoteId, noteIdToId } from "./utils";
interface Clipboard {
noteId: string;
@@ -118,7 +119,8 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
});
const dragProps = useNoteDragging({ containerRef, mapApiRef });
- const connectionCallback = useRelationCreation({ mapApiRef, jsPlumbApiRef: pbApiRef });
+ const relationNamePrompt = useRelationNamePrompt();
+ const connectionCallback = useRelationCreation({ mapApiRef, jsPlumbApiRef: pbApiRef, askRelationName: relationNamePrompt.ask });
const panZoom = usePanZoom({
ntxId,
@@ -176,6 +178,15 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
panZoom={panZoom}
onCommand={(command) => parentComponent?.triggerEvent(command, { ntxId })}
/>
+
+ {relationNamePrompt.request && (
+ <RelationNamePopover
+ key={relationNamePrompt.request.id}
+ connection={relationNamePrompt.request.connection}
+ defaultValue={relationNamePrompt.request.defaultValue}
+ onAnswer={relationNamePrompt.answer}
+ />
+ )}
</div>
);
}
@@ -403,18 +414,22 @@ function useNoteDragging({ containerRef, mapApiRef }: {
return dragProps;
}
-function useRelationCreation({ mapApiRef, jsPlumbApiRef }: { mapApiRef: RefObject<RelationMapApi>, jsPlumbApiRef: RefObject<jsPlumbInstance> }) {
+function useRelationCreation({ mapApiRef, jsPlumbApiRef, askRelationName }: {
+ mapApiRef: RefObject<RelationMapApi>,
+ jsPlumbApiRef: RefObject<jsPlumbInstance>,
+ askRelationName: AskRelationName
+}) {
const connectionCallback = useCallback(async (info: OnConnectionBindInfo, originalEvent: Event) => {
const connection = info.connection;
// Called whenever a connection is created, either initially or manually when added by the user.
- const handler = buildRelationContextMenuHandler(connection, mapApiRef);
+ const handler = buildRelationContextMenuHandler(connection, mapApiRef, askRelationName);
connection.bind("contextmenu", handler);
// if there's no event, then this has been triggered programmatically
if (!originalEvent || !mapApiRef.current) return;
- const name = await promptForRelationName();
+ const name = await askRelationName(connection);
// Delete the newly created connection if the dialog was dismissed.
if (!name || !name.trim()) {
@@ -429,7 +444,7 @@ function useRelationCreation({ mapApiRef, jsPlumbApiRef }: { mapApiRef: RefObjec
toast.showError(t("relation_map.connection_exists", { name }));
jsPlumbApiRef.current?.deleteConnection(connection);
}
- }, []);
+ }, [ askRelationName ]);
return connectionCallback;
}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.css b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.css
new file mode 100644
index 0000000000..995a16618f
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.css
@@ -0,0 +1,30 @@
+.relation-name-popover {
+ width: 300px;
+
+ .relation-name-header {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 9px;
+ border-bottom: 1px solid var(--main-border-color);
+ }
+
+ .relation-name-heading {
+ flex: 1;
+ min-width: 0;
+ padding: 6px 0;
+ font-weight: 600;
+ }
+
+ .relation-name-body {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding: 10px;
+ }
+
+ .relation-name-actions {
+ display: flex;
+ justify-content: flex-end;
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.spec.tsx
new file mode 100644
index 0000000000..45d3d7dc55
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.spec.tsx
@@ -0,0 +1,137 @@
+import type { Connection } from "jsplumb";
+import { act } from "preact/test-utils";
+import { describe, expect, it, vi } from "vitest";
+
+// The suggestions and their rows come from the attribute pane, whose module brings the whole pane.
+vi.mock("../../attribute_widgets/attribute_detail", () => ({
+ fetchAttributeNames: vi.fn(async (_type: string, query: string) =>
+ [ "author", "template" ].filter((name) => name.includes(query))),
+ AttributeNameSuggestion: ({ name }: { name: string }) => <span>{name}</span>
+}));
+
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
+import { renderInto } from "../../../test/render";
+import RelationNamePopover, { type AskRelationName, useRelationNamePrompt } from "./RelationNamePopover";
+
+describe("RelationNamePopover", () => {
+ it("keeps the name to the characters an attribute name allows, except while composing", async () => {
+ const { input } = await mount();
+
+ await type(input, "my relation!");
+ expect(input.value).toBe("myrelation");
+
+ await act(async () => { input.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true })); });
+ await type(input, "myrelation 关系");
+ expect(input.value).toBe("myrelation 关系");
+
+ await act(async () => { input.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); });
+ expect(input.value).toBe("myrelation关系");
+ });
+
+ it("answers the typed name on Enter, and nothing for a blank one", async () => {
+ const { input, onAnswer } = await mount();
+
+ await press(input, "Enter");
+ expect(onAnswer).not.toHaveBeenCalled();
+
+ await type(input, "author2");
+ await press(input, "Enter");
+ expect(onAnswer).toHaveBeenCalledWith("author2");
+ });
+
+ it("answers a picked suggestion straight away", async () => {
+ const { onAnswer } = await mount();
+
+ const rows = await settleDropdown();
+ expect(rows.map((row) => row.textContent)).toEqual([ "author", "template" ]);
+
+ await act(async () => (rows[1] as HTMLElement | undefined)?.click());
+ expect(onAnswer).toHaveBeenCalledWith("template");
+ });
+
+ it("cancels on Escape once the list is closed, and on a press outside", async () => {
+ const { input, onAnswer } = await mount();
+ await settleDropdown();
+
+ // The first Escape only closes the suggestions.
+ await press(input, "Escape");
+ expect(onAnswer).not.toHaveBeenCalled();
+ await press(input, "Escape");
+ expect(onAnswer).toHaveBeenCalledWith(null);
+
+ const outside = await mount();
+ await act(async () => { document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); });
+ expect(outside.onAnswer).toHaveBeenCalledWith(null);
+ });
+
+ it("opens on the current name when renaming", async () => {
+ const { input } = await mount("author");
+
+ expect(input.value).toBe("author");
+ expect(document.querySelector(".relation-name-heading")?.textContent).toBe("relation_map.rename_relation");
+ });
+});
+
+describe("useRelationNamePrompt", () => {
+ it("resolves a request with its answer, and a request replaced by a newer one with nothing", async () => {
+ let prompt: ReturnType<typeof useRelationNamePrompt> | undefined;
+ function Probe() {
+ prompt = useRelationNamePrompt();
+ return null;
+ }
+ await act(async () => { renderInto(<Probe />); });
+ const ask = prompt?.ask as AskRelationName;
+
+ const first = ask(fakeConnection());
+ const second = ask(fakeConnection(), "author");
+ await act(async () => undefined);
+ expect(await first).toBeNull();
+ expect(prompt?.request?.defaultValue).toBe("author");
+
+ await act(async () => prompt?.answer("editor"));
+ expect(await second).toBe("editor");
+ expect(prompt?.request).toBeUndefined();
+ });
+});
+
+async function mount(defaultValue = "") {
+ const onAnswer = vi.fn();
+ await act(async () => {
+ renderInto(
+ <RelationNamePopover connection={fakeConnection()} defaultValue={defaultValue} onAnswer={onAnswer} />);
+ });
+
+ const input = document.querySelector<HTMLInputElement>(".relation-name-popover input");
+ if (!input) throw new Error("the popover rendered no field");
+ return { input, onAnswer };
+}
+
+function fakeConnection() {
+ const canvas = document.createElement("div");
+ document.body.appendChild(canvas);
+ return { canvas } as unknown as Connection;
+}
+
+async function type(input: HTMLInputElement, value: string) {
+ await act(async () => {
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+async function press(input: HTMLInputElement, key: string) {
+ await act(async () => {
+ input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
+ });
+}
+
+/** Lets the debounced lookup run, then returns the rows of the list portaled to the body. */
+async function settleDropdown() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ });
+ return [ ...document.querySelectorAll(".form-autocomplete-dropdown li") ];
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx
new file mode 100644
index 0000000000..f7c4f5017c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx
@@ -0,0 +1,142 @@
+import "./RelationNamePopover.css";
+
+import type { Connection } from "jsplumb";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import utils from "../../../services/utils";
+import { AttributeNameSuggestion, fetchAttributeNames } from "../../attribute_widgets/attribute_detail";
+import ActionButton from "../../react/ActionButton";
+import Button from "../../react/Button";
+import FormAutocomplete from "../../react/FormAutocomplete";
+import Popover from "../../react/Popover";
+
+interface RelationNameRequest {
+ /** Tells requests apart, so a new one opens a fresh popover. */
+ id: number;
+ connection: Connection;
+ /** The name the field opens with: the current one when renaming, empty for a new relation. */
+ defaultValue: string;
+ resolve(name: string | null): void;
+}
+
+/**
+ * Asks for the name of the relation drawn by `connection`, next to the connection itself. Resolves
+ * with the name, or `null` when the request is canceled with Escape, the close button or a press
+ * outside the popover.
+ */
+export default function RelationNamePopover({ connection, defaultValue, onAnswer }: {
+ connection: Connection;
+ defaultValue: string;
+ onAnswer(name: string | null): void;
+}) {
+ const [ name, setName ] = useState(defaultValue);
+ const isComposing = useRef(false);
+ const isRename = !!defaultValue;
+
+ const suggestRelationNames = useCallback((query: string) => fetchAttributeNames("relation", query), []);
+ const renderRelationSuggestion = useCallback(
+ (suggestion: string) => <AttributeNameSuggestion type="relation" name={suggestion} />, []);
+ const cancel = useCallback(() => onAnswer(null), [ onAnswer ]);
+
+ // `FormAutocomplete` stops the propagation of an Escape that closes its list, so only an
+ // Escape with the list closed reaches the window.
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === "Escape") cancel();
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [ cancel ]);
+
+ return (
+ <Popover
+ className="relation-name-popover"
+ placement="bottom"
+ getAnchorRect={() => connectionAnchorRect(connection)}
+ onDismiss={cancel}
+ >
+ <div className="relation-name-header">
+ <span className="relation-name-heading">
+ {isRename ? t("relation_map.rename_relation") : t("relation_map.new_relation")}
+ </span>
+ <ActionButton icon="bx bx-x" text={t("modal.close")} onClick={cancel} />
+ </div>
+
+ <div className="relation-name-body">
+ <FormAutocomplete
+ autoFocus
+ currentValue={name}
+ placeholder={t("relation_map.relation_name_placeholder")}
+ source={suggestRelationNames}
+ renderItem={renderRelationSuggestion}
+ openOnFocus
+ // An input method's text is filtered once it is committed, not while composing.
+ onChange={(newValue) => setName(isComposing.current ? newValue : utils.filterAttributeName(newValue))}
+ onCompositionStart={() => isComposing.current = true}
+ onCompositionEnd={(e) => {
+ isComposing.current = false;
+ setName(utils.filterAttributeName(e.currentTarget.value));
+ }}
+ // A relation name already in use is a whole answer, so picking one confirms it.
+ onPick={onAnswer}
+ onKeyDown={(e) => {
+ // `FormAutocomplete` prevents the default of an Enter that picks a suggestion.
+ if (e.key === "Enter" && !e.defaultPrevented) {
+ e.preventDefault();
+ if (name.trim()) onAnswer(name);
+ }
+ }}
+ />
+
+ <div className="relation-name-actions">
+ <Button
+ kind="primary"
+ text={isRename ? t("relation_map.rename") : t("relation_map.create_relation")}
+ disabled={!name.trim()}
+ onClick={() => onAnswer(name)}
+ />
+ </div>
+ </div>
+ </Popover>
+ );
+}
+
+/** Asks for a relation name next to `connection`; see {@link useRelationNamePrompt}. */
+export type AskRelationName = (connection: Connection, defaultValue?: string) => Promise<string | null>;
+
+/**
+ * Holds the pending request for a relation name, for {@link RelationNamePopover} to answer. `ask`
+ * keeps its identity across renders, so a jsPlumb handler bound once can call it; a new request
+ * cancels the one still pending.
+ */
+export function useRelationNamePrompt() {
+ const [ request, setRequest ] = useState<RelationNameRequest>();
+ const requestRef = useRef(request);
+ requestRef.current = request;
+ const nextId = useRef(0);
+
+ const ask: AskRelationName = useCallback((connection, defaultValue = "") => new Promise<string | null>((resolve) => {
+ requestRef.current?.resolve(null);
+ requestRef.current = { id: nextId.current++, connection, defaultValue, resolve };
+ setRequest(requestRef.current);
+ }), []);
+
+ const answer = useCallback((name: string | null) => {
+ requestRef.current?.resolve(name);
+ requestRef.current = undefined;
+ setRequest(undefined);
+ }, []);
+
+ return { request, ask, answer };
+}
+
+/** The middle of the connection's drawing, read afresh so the popover follows the map's pan and zoom. */
+function connectionAnchorRect(connection: Connection) {
+ const rect = connection.canvas?.getBoundingClientRect();
+ if (!rect) {
+ return new DOMRect();
+ }
+
+ return new DOMRect(rect.left + rect.width / 2, rect.top + rect.height / 2, 0, 0);
+}
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 35710451b0..09e8146640 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
@@ -10,7 +10,7 @@ import toast from "../../../services/toast";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import RelationMapApi from "./api";
-import { promptForRelationName } from "./utils";
+import type { AskRelationName } from "./RelationNamePopover";
export function buildNoteContextMenuHandler(note: FNote | null | undefined, mapApiRef: RefObject<RelationMapApi>) {
return (e: MouseEvent) => {
@@ -69,7 +69,7 @@ export function buildNoteContextMenuHandler(note: FNote | null | undefined, mapA
};
}
-export function buildRelationContextMenuHandler(connection: Connection, mapApiRef: RefObject<RelationMapApi>) {
+export function buildRelationContextMenuHandler(connection: Connection, mapApiRef: RefObject<RelationMapApi>, askRelationName: AskRelationName) {
return (_, event: MouseEvent) => {
if (connection.getType().includes("link")) {
// don't create context menu if it's a link since there's nothing to do with link from relation map
@@ -90,7 +90,7 @@ export function buildRelationContextMenuHandler(connection: Connection, mapApiRe
selectMenuItemHandler: async ({ command }) => {
if (command === "rename") {
const currentName = mapApiRef.current?.getRelationName(connection) ?? "";
- const newName = await promptForRelationName(currentName);
+ const newName = await askRelationName(connection, currentName);
if (!newName?.trim() || newName === currentName) {
return;
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html
index 531ab95742..c2fdff6684 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html
@@ -27,15 +27,17 @@
note to the second one.</li>
<li>Drag over the same note to create a self-referencing relationship (represented
as a loop).</li>
- <li>Once dragged, enter the name of the relationship to create. To cancel,
- simply dismiss the dialog or press <kbd>Esc</kbd>.</li>
+ <li>Once dragged, a popover next to the relationship asks for its name. Type
+ a new name and press <kbd>Enter</kbd>, or pick a relation name already in
+ use from the suggestions. To cancel, press <kbd>Esc</kbd>, close the popover
+ or click elsewhere on the map.</li>
</ul>
</li>
<li>To open a note, either click on the note (opening it in the current view)
or use the right click menu to open in a new tab.</li>
<li>To edit the title of a note or to delete it (either from the map, or delete
it completely), right click the note.</li>
- <li>To delete a relationship, right click it and select the corresponding
+ <li>To rename or delete a relationship, right click it and select the corresponding
option.</li>
</ul>
<h2>Development process demo</h2>
diff --git a/docs/User Guide/User Guide/Note Types/Relation Map.md b/docs/User Guide/User Guide/Note Types/Relation Map.md
index ce15cbe374..5ba8831e48 100644
--- a/docs/User Guide/User Guide/Note Types/Relation Map.md
+++ b/docs/User Guide/User Guide/Note Types/Relation Map.md
@@ -12,10 +12,10 @@ Relation map is a type of note which visualizes notes and their [relations](..
* To create a relationship, hold the mouse on the box on the right of a note and then:
* Drag it over another note to create a relationship pointing from the first note to the second one.
* Drag over the same note to create a self-referencing relationship (represented as a loop).
- * Once dragged, enter the name of the relationship to create. To cancel, simply dismiss the dialog or press <kbd>Esc</kbd>.
+ * Once dragged, a popover next to the relationship asks for its name. Type a new name and press <kbd>Enter</kbd>, or pick a relation name already in use from the suggestions. To cancel, press <kbd>Esc</kbd>, close the popover or click elsewhere on the map.
* To open a note, either click on the note (opening it in the current view) or use the right click menu to open in a new tab.
* To edit the title of a note or to delete it (either from the map, or delete it completely), right click the note.
-* To delete a relationship, right click it and select the corresponding option.
+* To rename or delete a relationship, right click it and select the corresponding option.
## Development process demo