Skip to content

Build your personal knowledge base with Trilium Notes

feat(mind-map): pick a node's link in the dialog every other link is picked in

Elian Doran67f840a0f24f
diff --git a/apps/client/src/widgets/dialogs/add_link.tsx b/apps/client/src/widgets/dialogs/add_link.tsx
index 552ea07c0c..ead35263dd 100644
--- a/apps/client/src/widgets/dialogs/add_link.tsx
+++ b/apps/client/src/widgets/dialogs/add_link.tsx
@@ -36,6 +36,15 @@ function findAnchorIds(content: string): string[] {
export interface AddLinkOpts {
text: string;
hasSelection: boolean;
+ /**
+ * Pick what the link points at and nothing else.
+ *
+ * For a caller that carries no text of its own to dress — a mind map node reads as its own
+ * topic — there is no title to write and no reference-or-hyperlink to choose between, and the
+ * anchor within a note is left out too: what it appends is a link only a rich text can follow.
+ * `linkTitle` is handed over all the same, so a caller minding it need not be told twice.
+ */
+ targetOnly?: boolean;
addLink(notePath: string, linkTitle: string | null, externalLink?: boolean): Promise<void>;
}
@@ -198,7 +207,7 @@ export default function AddLinkDialog() {
/>
</FormGroup>
- {bookmarks.length > 0 && (
+ {bookmarks.length > 0 && !opts?.targetOnly && (
<FormGroup label={t("add_link.anchor")} name="anchor">
<select
className="form-select"
@@ -213,7 +222,7 @@ export default function AddLinkDialog() {
</FormGroup>
)}
- {!opts?.hasSelection && (
+ {!opts?.hasSelection && !opts?.targetOnly && (
<div className="add-link-title-settings">
{(linkType !== "external-link") && (
<>
diff --git a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.css b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.css
index 08876637aa..6773e32e39 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.css
+++ b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.css
@@ -189,11 +189,10 @@
* or an address is as long as it is, and cutting it short is kinder than letting it push the panel
* wider than the map can spare.
*/
-.mind-map-node-panel .mind-map-node-link button {
+.mind-map-node-panel button.mind-map-node-link {
display: flex;
align-items: center;
gap: 6px;
- width: 100%;
text-align: start;
.mind-map-node-link-label {
@@ -211,16 +210,6 @@
}
}
-/* The field is the whole of the menu, its suggestions falling under it as they do anywhere else. */
-.mind-map-node-link-picker {
- padding: 8px;
-
- /* The wrapper Algolia puts around the field takes no width of its own. */
- .algolia-autocomplete {
- flex: 1;
- }
-}
-
/* The sizes share the width of the panel evenly, rather than each taking its label's width. */
.mind-map-node-panel .btn-group {
width: 100%;
diff --git a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.spec.tsx b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.spec.tsx
index 8fdab885d0..94c651bfe0 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.spec.tsx
@@ -1,10 +1,12 @@
import type { MindElixirInstance, NodeObj } from "mind-elixir";
import { render } from "preact";
import { act } from "preact/test-utils";
-import { describe, expect, it, vi } from "vitest";
+import { describe, expect, it, onTestFinished, vi } from "vitest";
+import appContext from "../../../components/app_context";
import { buildNotes } from "../../../test/easy-froca";
import { renderInto } from "../../../test/render";
+import type { AddLinkOpts } from "../../dialogs/add_link";
import { uploadNodeImage } from "./images";
import NodePanel, { applyTagTexts, DEFAULT_FONT_SIZE, gatherTags, getCommonValue, MIXED, NODE_BACKGROUND_COLORS, NODE_COLORS, withIconAt } from "./NodePanel";
@@ -140,6 +142,16 @@ function chooseImage(container: HTMLElement, file: File) {
input.dispatchEvent(new Event("change", { bubbles: true }));
}
+/** The field saying what the selection is linked to, which is what opens the dialog. */
+function linkField(container: HTMLElement) {
+ return section(container, LINK).querySelector<HTMLButtonElement>("button.mind-map-node-link");
+}
+
+/** What the field says the selection points at, read off the label rather than the whole button. */
+function linkLabel(field: HTMLElement | null) {
+ return field?.querySelector(".mind-map-node-link-label")?.textContent;
+}
+
/** The button beside the link field dropping what the selection points at, if it is offered at all. */
function unlinkButton(container: HTMLElement) {
return section(container, LINK).querySelector<HTMLButtonElement>(".bx-unlink");
@@ -713,8 +725,7 @@ describe("NodePanel", () => {
it("says what the selection is linked to, and what it would take to link it", async () => {
const [ noteId ] = buildNotes([ { title: "Linked note", "#iconClass": "bx bx-cube" } ]);
const linkFace = (nodes: NodeObj[]) =>
- renderInto(<NodePanel mind={buildMind(nodes).mind} noteId="mapNote" nodes={nodes} />)
- .querySelector<HTMLElement>(`.mind-map-node-panel-section:nth-child(${LINK + 1}) button`);
+ linkField(renderInto(<NodePanel mind={buildMind(nodes).mind} noteId="mapNote" nodes={nodes} />));
// Nothing yet, and a selection that disagrees, each say so in their own words.
expect(linkFace([buildNode()])?.querySelector(".mind-map-node-link-empty")).toBeTruthy();
@@ -724,13 +735,60 @@ describe("NodePanel", () => {
])?.querySelector(".mind-map-node-link-mixed")).toBeTruthy();
// An address reads as the host it points at, its whole self being far too long for the panel.
- expect(linkFace([buildNode({ hyperLink: "https://example.com/a/long/page?q=1" })])?.textContent)
+ expect(linkLabel(linkFace([buildNode({ hyperLink: "https://example.com/a/long/page?q=1" })])))
.toBe("example.com");
// A note reads as it is named and dressed now, rather than as the address it is stored as.
const note = linkFace([buildNode({ hyperLink: `#root/${noteId}` })]);
expect(note?.querySelector(".bx-cube")).toBeTruthy();
- await vi.waitFor(() => expect(note?.textContent).toBe("Linked note"));
+ await vi.waitFor(() => expect(linkLabel(note)).toBe("Linked note"));
+ });
+
+ it("picks a link through the add-link dialog, asked for the target alone", async () => {
+ const nodes = [buildNode({ id: "a" }), buildNode({ id: "b" })];
+ const { mind, reshapeNode } = buildMind(nodes);
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
+ onTestFinished(() => triggerCommand.mockRestore());
+
+ const container = renderInto(<NodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
+ linkField(container)?.click();
+
+ // A node reads as its own topic, so the dialog is asked for what is pointed at and nothing
+ // else — no title beside it, and nothing to open the field on for a node linked to nothing.
+ expect(triggerCommand).toHaveBeenCalledWith("showAddLinkDialog",
+ expect.objectContaining({ targetOnly: true, hasSelection: false, text: "" }));
+
+ // What comes back is stored the way the map stores it: a note as an in-app address, an
+ // address as one we could follow. Every node the panel was handed takes it.
+ const opts = triggerCommand.mock.calls[0][1] as AddLinkOpts;
+ await opts.addLink("root/abc123", "Linked note");
+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { hyperLink: "#root/abc123" });
+ expect(reshapeNode).toHaveBeenNthCalledWith(2, mind.currentNodes[1], { hyperLink: "#root/abc123" });
+
+ reshapeNode.mockClear();
+ await opts.addLink("example.com", "example.com", true);
+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { hyperLink: "https://example.com" });
+
+ // Nothing we could store, nothing written: the selection keeps the link it had.
+ reshapeNode.mockClear();
+ await opts.addLink("javascript:alert(1)", "", true);
+ expect(reshapeNode).not.toHaveBeenCalled();
+ });
+
+ it("opens the dialog on the address a node already carries, a note having none to type", () => {
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
+ onTestFinished(() => triggerCommand.mockRestore());
+
+ const openOn = (link: string) => {
+ const nodes = [buildNode({ hyperLink: link })];
+ linkField(renderInto(<NodePanel mind={buildMind(nodes).mind} noteId="mapNote" nodes={nodes} />))?.click();
+ return (triggerCommand.mock.lastCall?.[1] as AddLinkOpts).text;
+ };
+
+ // An address is what someone typed, so it is handed back to be edited; the address a note is
+ // stored as is not, and the dialog opens on the notes last visited instead.
+ expect(openOn("https://example.com/page")).toBe("https://example.com/page");
+ expect(openOn("#root/abc123")).toBe("");
});
it("unlinks the selection from the button beside the field, which is only there to be unlinked", () => {
diff --git a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.tsx b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.tsx
index c84ab28b97..7e2794c958 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.tsx
+++ b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.tsx
@@ -4,21 +4,20 @@ import { parseMindMapNoteLink } from "@triliumnext/commons";
import { Dropdown as BootstrapDropdown } from "bootstrap";
import type { MindElixirInstance, NodeObj, TagObj } from "mind-elixir";
import { ComponentChildren } from "preact";
-import { useEffect, useRef, useState } from "preact/hooks";
+import { useRef, useState } from "preact/hooks";
+import appContext from "../../../components/app_context";
import { t } from "../../../services/i18n";
-import note_autocomplete from "../../../services/note_autocomplete";
import tree from "../../../services/tree";
import ValuesInput from "../../attribute_widgets/values_input";
import ActionButton from "../../react/ActionButton";
+import Button from "../../react/Button";
import ColorPicker, { DEFAULT_COLOR_PALETTE } from "../../react/ColorPicker";
import Dropdown from "../../react/Dropdown";
import { FormFileUploadActionButton } from "../../react/FormFileUpload";
import { useNote, useNoteIcon, useNoteTitle } from "../../react/hooks";
import Icon from "../../react/Icon";
import IconPicker from "../../react/IconPicker";
-import NoteAutocomplete from "../../react/NoteAutocomplete";
-import { refToJQuerySelector } from "../../react/react_utils";
import SegmentedChoice from "../../react/SegmentedChoice";
import TabStrip, { type TabStripTabDefinition } from "../../react/TabStrip";
import { fitNodeImage, getNodeImageShape, nearestNodeImageWidth, NODE_IMAGE_SHAPES, NODE_IMAGE_WIDTHS, type NodeImage as NodeImageData, type NodeImageShape, shapeNodeImage, uploadNodeImage } from "./images";
@@ -96,18 +95,19 @@ export default function NodePanel({ mind, noteId, nodes, readOnly }: NodePanelPr
}
/**
- * Writes a memo to the nodes the panel was handed rather than to the live selection: a memo is
- * written as the field is left, and what a user leaves it with is often the very click that
- * selects something else. The nodes are looked up again all the same, the elements a patch is
- * applied to having to be the ones on the map.
+ * Applies a patch to the nodes the panel was handed rather than to the live selection, for the
+ * fields whose value lands after the panel has had its say: a memo is written as the field is
+ * left, and what a user leaves it with is often the very click that selects something else,
+ * while a link comes back from a dialog opened over the map. The nodes are looked up again all
+ * the same, the elements a patch is applied to having to be the ones on the map.
*/
- function writeMemo(memo: string) {
+ function patchGivenNodes(patch: Partial<NodeObj>) {
for (const node of nodes) {
try {
- void mind.reshapeNode(mind.findEle(node.id), { memo } as Partial<NodeObj>);
+ void mind.reshapeNode(mind.findEle(node.id), patch);
} catch (e) {
// The node is no longer on the map, or is folded away inside one that is closed.
- console.warn("Could not write the memo of a mind map node:", e);
+ console.warn("Could not change a mind map node:", e);
}
}
}
@@ -244,7 +244,7 @@ export default function NodePanel({ mind, noteId, nodes, readOnly }: NodePanelPr
// A node carries one link, so what is picked takes the place of what was there.
// Clearing blanks the property, Mind Elixir only ever assigning the ones it is
// given (see the colors above).
- onChange={(link) => patchSelectedNodes({ hyperLink: link ?? "" })}
+ onChange={(link) => patchGivenNodes({ hyperLink: link ?? "" })}
/>
</PanelSection>
@@ -280,7 +280,7 @@ export default function NodePanel({ mind, noteId, nodes, readOnly }: NodePanelPr
selectionKey={nodes.map((node) => node.id).join(" ")}
memo={memo !== MIXED ? memo : null}
readOnly={readOnly || memo === MIXED}
- onCommit={writeMemo}
+ onCommit={(memo) => patchGivenNodes({ memo } as Partial<NodeObj>)}
/>
</div>
)}
@@ -578,76 +578,45 @@ function buildImageShapeOptions() {
return NODE_IMAGE_SHAPES.map((shape) => ({ value: shape, icon: icons[shape], title: titles[shape] }));
}
-/** Kept still, so that the autocomplete is not built anew every time the panel renders. */
-const LINK_AUTOCOMPLETE_OPTIONS = { allowExternalLinks: true };
-
/**
* The link a node carries: a note, or a page outside Trilium — one field, a node carrying one link.
*
- * The picker sits in a menu rather than in the panel itself: it is the field a note is picked
- * through everywhere else in Trilium, and it wants more room than a panel this narrow can give it.
- * Unlinking stands beside the field rather than at the foot of that menu, as it does for the picture
- * above: dropping a link is not one more note to pick from, and offered among them it read as one —
- * besides taking a menu opened on something else entirely to reach.
+ * What the field opens is the add-link dialog every other link in Trilium is picked through, asked
+ * for the target alone (`targetOnly` among its options): a node reads as its own topic, so there is
+ * no title to write beside it. A dialog rather than a menu hung off the field, which is where the
+ * picker used to sit — the panel stands in the corner of the map, and a menu anchored there had a
+ * strip of screen to search a whole tree in, growing and shrinking under the pointer as the results
+ * came in.
+ *
+ * Unlinking stands beside the field rather than inside what it opens, as it does for the picture
+ * above: dropping a link is not one more note to pick from.
*/
function NodeLink({ currentValue, indeterminate, onChange }: {
currentValue: string | null;
indeterminate: boolean;
onChange(link: string | null): void;
}) {
- const dropdownRef = useRef<BootstrapDropdown>(null);
- const inputRef = useRef<HTMLInputElement>(null);
- const pickerRef = useRef<HTMLDivElement>(null);
- const [ pickerShown, setPickerShown ] = useState(false);
-
- // Opened on the notes last visited, which are the likeliest thing to be linking to and what the
- // add-link dialog opens on as well. Once the picker is up, so that there is a field to fill.
- useEffect(() => {
- if (!pickerShown || !inputRef.current) return;
- const $input = refToJQuerySelector(inputRef);
- note_autocomplete.showRecentNotes($input);
- $input.trigger("focus");
- }, [ pickerShown ]);
-
- function commit(link: string | null) {
- onChange(link);
- dropdownRef.current?.hide();
- }
-
return (
<div className="mind-map-node-link-row">
- <Dropdown
+ <Button
className="mind-map-node-link"
text={<NodeLinkFace link={currentValue} indeterminate={indeterminate} />}
title={t("mind-map.choose-link")}
- dropdownRef={dropdownRef}
- dropdownContainerStyle={{ width: "360px" }}
- // The suggestions land inside the menu, so picking one is not the click outside that
- // would take the menu down before the pick is made.
- dropdownOptions={{ autoClose: "outside" }}
- // The panel scrolls, and the picker is wider than the panel is; hand the menu to the
- // page instead of leaving it to be clipped.
- portalToBody
- onShown={() => setPickerShown(true)}
- onHidden={() => setPickerShown(false)}
- >
- {pickerShown && (
- <div className="mind-map-node-link-picker" ref={pickerRef}>
- <NoteAutocomplete
- inputRef={inputRef}
- container={pickerRef}
- placeholder={t("mind-map.link-placeholder")}
- opts={LINK_AUTOCOMPLETE_OPTIONS}
- // Only a pick is worth taking: the field is also cleared as one types, and
- // the way back to no link at all is the button beside the menu.
- onChange={(suggestion) => {
- const link = linkFromSuggestion(suggestion);
- if (link) commit(link);
- }}
- />
- </div>
- )}
- </Dropdown>
+ onClick={() => void appContext.triggerCommand("showAddLinkDialog", {
+ // An address is handed back for editing as it stands; a note is not — what is
+ // stored for one is a path rather than anything anyone typed, and the dialog
+ // opens on the notes last visited instead.
+ text: (currentValue && !parseMindMapNoteLink(currentValue)) ? currentValue : "",
+ hasSelection: false,
+ targetOnly: true,
+ async addLink(target, _linkTitle, externalLink) {
+ // Only a target we can store is worth taking, as it was when the field was
+ // picked through directly.
+ const link = linkFromSuggestion(externalLink ? { externalLink: target } : { notePath: target });
+ if (link) onChange(link);
+ }
+ })}
+ />
{/* Only where there is a link to drop — as with the picture, what acts on one is there
once there is something for it to act on. */}