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
feat(mind-map): let a node link to a note or a page
Elian Doran5e740786e276
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 2b12429b75..938fe7fca7 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3534,6 +3534,13 @@"icon": "Icon","choose-icon": "Choose an icon","clear-icon": "Remove the icon",+ "node-link": "Link",+ "add-link": "Add a link",+ "choose-link": "Link this node to a note or a page",+ "link-placeholder": "Search notes or paste a URL",+ "clear-link": "Remove the link",+ "link-mixed": "Different links",+ "links-differ": "The selected nodes don't carry the same link.","tags": "Tags","tags-placeholder": "Type a tag and press Enter","tags-differ": "The selected nodes don't carry the same tags, so these can only be read.",diff --git a/apps/client/src/widgets/type_widgets/MindMap.tsx b/apps/client/src/widgets/type_widgets/MindMap.tsxindex 2d060d7c73..c2194447d2 100644--- a/apps/client/src/widgets/type_widgets/MindMap.tsx+++ b/apps/client/src/widgets/type_widgets/MindMap.tsx@@ -16,6 +16,7 @@ import { useColorScheme, useEditorSpacedUpdate, useEffectiveReadOnly, useSyncedRimport { refToJQuerySelector } from "../react/react_utils";import { renderMindMapPreviewSvg } from "./helpers/mind_map_export";import { renderIconClasses } from "./helpers/mind_map_icons";+import { renderNodeLinks } from "./helpers/mind_map_links";import MindMapNodePanel from "./MindMapNodePanel";import { TypeWidgetProps } from "./type_widget";@@ -276,12 +277,16 @@ function MindElixir({ children, containerRef: externalContainerRef, containerPro}, [ onChange ]);// Node icons are rendered as text by Mind Elixir, while ours are icon classes, so they are- // dressed again after every layout — which is what follows any change to a node.+ // dressed again after every layout — which is what follows any change to a node. The links a+ // node carries are hardened in the same pass and for the same reason: Mind Elixir builds their+ // anchors anew from the node's own data (see renderNodeLinks).useEffect(() => {const mind = apiRef.current;if (!mind) return;- const renderIcons = () => {+ const dressNodes = () => {+ renderNodeLinks(mind.nodes);+// An icon takes far less room than the class it arrived as, so the node it sits on// narrows the moment it is dressed — after the branches have been measured against the// wider one, leaving them reaching past it. Measure again, but only where something@@ -291,10 +296,10 @@ function MindElixir({ children, containerRef: externalContainerRef, containerPro}};- renderIcons();- mind.bus.addListener("linkDiv", renderIcons);+ dressNodes();+ mind.bus.addListener("linkDiv", dressNodes);- return () => mind.bus.removeListener("linkDiv", renderIcons);+ return () => mind.bus.removeListener("linkDiv", dressNodes);}, [ instanceVersion ]);// Selection listener. The events only carry the nodes that were added to or removed from thediff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css b/apps/client/src/widgets/type_widgets/MindMapNodePanel.cssindex ba18e95e4a..599b17c97d 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.css@@ -39,6 +39,43 @@--note-icon-container-padding-size: 4px;}+/*+ * The link takes the width of the panel and says what it points at, however long that runs: a title+ * 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 {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 100%;+ text-align: start;++ .mind-map-node-link-label {+ flex: 1;+ /* Without it a flex item refuses to shrink past its content, and there is nothing to cut. */+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ /* A link there is not yet is an invitation rather than a value. */+ .mind-map-node-link-empty {+ opacity: .7;+ }+}++/* 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/MindMapNodePanel.spec.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsxindex ab13dd08ca..bab92f289b 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx@@ -1,6 +1,7 @@import type { MindElixirInstance, NodeObj } from "mind-elixir";import { describe, expect, it, vi } from "vitest";+import { buildNotes } from "../../test/easy-froca";import { renderInto } from "../../test/render";import MindMapNodePanel, { applyTagTexts, DEFAULT_FONT_SIZE, gatherTags, getCommonValue, MIXED, NODE_BACKGROUND_COLORS, NODE_COLORS } from "./MindMapNodePanel";@@ -27,7 +28,8 @@ const TEXT = 1;const BACKGROUND = 2;const BRANCH = 3;const ICON = 4;-const TAGS = 5;+const LINK = 5;+const TAGS = 6;function section(container: HTMLElement, index: number) {const sections = container.querySelectorAll<HTMLElement>(".mind-map-node-panel-section");@@ -245,6 +247,29 @@ describe("MindMapNodePanel", () => {])?.className).toContain("bx bx-empty");});+ 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(<MindMapNodePanel mind={buildMind(nodes).mind} nodes={nodes} />)+ .querySelector<HTMLElement>(`.mind-map-node-panel-section:nth-child(${LINK + 1}) button`);++ // Nothing yet, and a selection that disagrees, each say so in their own words.+ expect(linkFace([buildNode()])?.querySelector(".mind-map-node-link-empty")).toBeTruthy();+ expect(linkFace([+ buildNode({ id: "a", hyperLink: "https://example.com" }),+ buildNode({ id: "b" })+ ])?.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)+ .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"));+ });+it("edits the tags of a single node, keeping the styling of the ones that stay", () => {const styled = { text: "urgent", style: { color: "red" } };const nodes = [buildNode({ tags: [styled, "later"] })];diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsxindex 26dbc831b2..6778a62ab7 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx@@ -3,14 +3,22 @@ import "./MindMapNodePanel.css";import { Dropdown as BootstrapDropdown } from "bootstrap";import type { MindElixirInstance, NodeObj, TagObj } from "mind-elixir";import { ComponentChildren } from "preact";-import { useRef, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";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 ColorPicker, { DEFAULT_COLOR_PALETTE } from "../react/ColorPicker";import Dropdown from "../react/Dropdown";+import { FormListItem } from "../react/FormList";+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 { describeExternalLink, getLinkedNotePath, linkFromSuggestion } from "./helpers/mind_map_links";/*** The hues offered by the panel: as many of the shared palette as fit on a single row next to the@@ -41,6 +49,7 @@ export default function MindMapNodePanel({ mind, nodes }: MindMapNodePanelProps)const backgroundColor = getCommonValue(nodes, (node) => node.style?.background);const branchColor = getCommonValue(nodes, (node) => node.branchColor);const icon = getCommonValue(nodes, (node) => node.icons?.[0]);+ const link = getCommonValue(nodes, (node) => node.hyperLink);const tags = gatherTags(nodes);/**@@ -105,6 +114,20 @@ export default function MindMapNodePanel({ mind, nodes }: MindMapNodePanelProps)/></PanelSection>+ <PanelSection+ label={t("mind-map.node-link")}+ title={link === MIXED ? t("mind-map.links-differ") : undefined}+ >+ <NodeLink+ currentValue={link !== MIXED ? link : null}+ indeterminate={link === MIXED}+ // 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 ?? "" })}+ />+ </PanelSection>+<PanelSectionlabel={t("mind-map.tags")}title={tags.readOnly ? t("mind-map.tags-differ") : undefined}@@ -236,6 +259,112 @@ function NodeIcon({ currentValue, onSelect, onClear }: {);}+/** 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.+ */+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 (+ <Dropdown+ 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 one offered below.+ onChange={(suggestion) => {+ const link = linkFromSuggestion(suggestion);+ if (link) commit(link);+ }}+ />++ {(currentValue || indeterminate) && (+ <FormListItem+ icon="bx bx-unlink"+ onClick={() => commit(null)}+ >{t("mind-map.clear-link")}</FormListItem>+ )}+ </div>+ )}+ </Dropdown>+ );+}++/** What the button says the selection is linked to. */+function NodeLinkFace({ link, indeterminate }: { link: string | null, indeterminate: boolean }) {+ if (indeterminate) {+ return <><Icon icon="bx bx-link" /><span className="mind-map-node-link-label mind-map-node-link-mixed">{t("mind-map.link-mixed")}</span></>;+ }++ const notePath = getLinkedNotePath(link);+ if (notePath) {+ return <LinkedNoteFace notePath={notePath} />;+ }++ if (link) {+ return <><Icon icon="bx bx-link-external" /><span className="mind-map-node-link-label">{describeExternalLink(link)}</span></>;+ }++ return <><Icon icon="bx bx-link" /><span className="mind-map-node-link-label mind-map-node-link-empty">{t("mind-map.add-link")}</span></>;+}++/** A linked note as it is named and dressed now, rather than as it was when it was linked. */+function LinkedNoteFace({ notePath }: { notePath: string }) {+ const { noteId, parentNoteId } = tree.getNoteIdAndParentIdFromUrl(notePath);+ const note = useNote(noteId);+ const title = useNoteTitle(noteId, parentNoteId);+ const icon = useNoteIcon(note);++ // The title is read asynchronously; until it lands, what is already known of the note stands in+ // for it, rather than the address the panel would otherwise have to show.+ return <><Icon icon={icon} /><span className="mind-map-node-link-label">{title ?? note?.title ?? ""}</span></>;+}+function PanelSection({ label, title, children }: { label: string, title?: string, children: ComponentChildren }) {return (<div className="mind-map-node-panel-section" title={title}>diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_links.spec.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_links.spec.tsnew file mode 100644index 0000000000..19a40220df--- /dev/null+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_links.spec.ts@@ -0,0 +1,111 @@+import type { Suggestion } from "../../../services/note_autocomplete";+import { describe, expect, it } from "vitest";++import { describeExternalLink, getLinkedNotePath, getNodeLinkHref, linkFromSuggestion, renderNodeLinks } from "./mind_map_links";++/** Builds the anchor Mind Elixir gives a node that carries a link. */+function buildNodes(...links: string[]) {+ const nodes = document.createElement("div");+ for (const link of links) {+ const anchor = document.createElement("a");+ anchor.className = "hyper-link";+ anchor.target = "_blank";+ anchor.innerText = "🔗";+ anchor.setAttribute("href", link);+ nodes.appendChild(anchor);+ }+ return nodes;+}++function anchors(nodes: HTMLElement) {+ return Array.from(nodes.querySelectorAll("a"));+}++describe("getLinkedNotePath", () => {+ it("tells a link to a note from one pointing outside Trilium", () => {+ expect(getLinkedNotePath("#root/abc123")).toBe("root/abc123");+ expect(getLinkedNotePath("#root/parent/abc123")).toBe("root/parent/abc123");+ expect(getLinkedNotePath("#root")).toBe("root");++ for (const link of [ null, undefined, "", "https://example.com", "#rootless/abc", "root/abc123" ]) {+ expect(getLinkedNotePath(link)).toBeNull();+ }+ });+});++describe("linkFromSuggestion", () => {+ it("stores a note as an in-app address and an external link as one we could follow", () => {+ expect(linkFromSuggestion({ notePath: "root/abc123" } as Suggestion)).toBe("#root/abc123");+ expect(linkFromSuggestion({ externalLink: "https://example.com/page" } as Suggestion))+ .toBe("https://example.com/page");+ // A bare host gets the scheme an address bar would give it.+ expect(linkFromSuggestion({ externalLink: "example.com" } as Suggestion)).toBe("https://example.com");++ // Nothing to store: no pick, a pick that is neither, or an address we may not follow.+ expect(linkFromSuggestion(null)).toBeNull();+ expect(linkFromSuggestion({ action: "search-notes" } as Suggestion)).toBeNull();+ expect(linkFromSuggestion({ externalLink: "javascript:alert(1)" } as Suggestion)).toBeNull();+ });+});++describe("getNodeLinkHref", () => {+ it("follows notes and addresses, and refuses what Trilium would not open", () => {+ expect(getNodeLinkHref("#root/abc123")).toBe("#root/abc123");+ expect(getNodeLinkHref("https://example.com")).toBe("https://example.com");+ expect(getNodeLinkHref("example.com")).toBe("https://example.com");+ // Schemes Trilium opens are kept as they stand, so a map made elsewhere keeps its links.+ expect(getNodeLinkHref("mailto:[email protected]")).toBe("mailto:[email protected]");+ expect(getNodeLinkHref("file:///home/note.pdf")).toBe("file:///home/note.pdf");++ for (const link of [ null, "", "javascript:alert(1)", "data:text/html,<script>alert(1)</script>", "about:blank" ]) {+ expect(getNodeLinkHref(link)).toBeNull();+ }+ });+});++describe("describeExternalLink", () => {+ it("reads an address as its host, and anything else as it stands", () => {+ expect(describeExternalLink("https://example.com/some/page?q=1")).toBe("example.com");+ expect(describeExternalLink("example.com")).toBe("example.com");+ expect(describeExternalLink("mailto:[email protected]")).toBe("mailto:[email protected]");+ });+});++describe("renderNodeLinks", () => {+ it("opens a note where the map is, and an address in a tab of its own", () => {+ const nodes = buildNodes("#root/abc123", "https://example.com");++ renderNodeLinks(nodes);++ const [ note, page ] = anchors(nodes);+ expect(note.getAttribute("href")).toBe("#root/abc123");+ expect(note.getAttribute("target")).toBeNull();+ expect(note.rel).toBe("noopener noreferrer");+ // Nothing worth saying about a note that its title would not say better.+ expect(note.getAttribute("title")).toBeNull();++ expect(page.getAttribute("target")).toBe("_blank");+ expect(page.title).toBe("https://example.com");+ });++ it("renders an address it may not follow inert, keeping the node's link visible", () => {+ const nodes = buildNodes("javascript:alert(1)");++ renderNodeLinks(nodes);++ const [ hostile ] = anchors(nodes);+ expect(hostile.getAttribute("href")).toBe("about:blank");+ expect(hostile.textContent).toBe("🔗");+ // Applied again after every layout, so it has to hold up on what it left behind.+ renderNodeLinks(nodes);+ expect(hostile.getAttribute("href")).toBe("about:blank");+ });++ it("gives a bare host the scheme it needs, without touching what the node stores", () => {+ const nodes = buildNodes("example.com");++ renderNodeLinks(nodes);++ expect(anchors(nodes)[0].getAttribute("href")).toBe("https://example.com");+ });+});diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_links.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_links.tsnew file mode 100644index 0000000000..e061e1390c--- /dev/null+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_links.ts@@ -0,0 +1,90 @@+import { ALLOWED_PROTOCOLS } from "@triliumnext/commons";++import type { Suggestion } from "../../../services/note_autocomplete";+import { normalizeExternalUrl } from "../../../utils/url";++/**+ * The link a node carries is Mind Elixir's own `NodeObj.hyperLink`: one string per node, which its+ * topic renderer puts straight into an anchor.+ *+ * A link to a note is therefore written the way a note link is written everywhere else in Trilium,+ * as the in-app address `#root/…`. The delegated handler in `link.ts` picks a click up off any+ * anchor on the page, so a note opens with nothing else to wire up. Anything else is an address+ * outside Trilium.+ */++/** The note path a link points at, or `null` where it points somewhere else entirely. */+export function getLinkedNotePath(link: string | null | undefined): string | null {+ return (link && /^#root(\/|$)/.test(link)) ? link.slice(1) : null;+}++/** The link to store for what was picked in the note autocomplete, or `null` if nothing was. */+export function linkFromSuggestion(suggestion: Suggestion | null | undefined): string | null {+ if (suggestion?.notePath) {+ return `#${suggestion.notePath}`;+ }++ // The autocomplete hands over what was typed; an address is only stored once it is one we could+ // follow, and a bare host gets the scheme an address bar would give it.+ return (suggestion?.externalLink ? normalizeExternalUrl(suggestion.externalLink) : null);+}++/** The address a link may be followed to, or `null` where it may not be followed at all. */+export function getNodeLinkHref(link: string | null | undefined): string | null {+ if (!link) {+ return null;+ }++ if (getLinkedNotePath(link)) {+ return link;+ }++ const url = normalizeExternalUrl(link);+ if (url) {+ return url;+ }++ // A scheme Trilium knows how to open is kept as it stands, so a map made elsewhere keeps its+ // `mailto:` and `file:` links. `data:` is left out: `goToLinkExt` refuses it anyway, and it+ // would still be live in an exported map opened outside Trilium.+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(link)?.[1].toLowerCase();+ return (scheme && scheme !== "data" && ALLOWED_PROTOCOLS.includes(scheme)) ? link : null;+}++/** What an external link reads as where there is only room for a few words: the host it points at. */+export function describeExternalLink(link: string): string {+ const url = normalizeExternalUrl(link);+ return (url ? new URL(url).host || link : link);+}++/**+ * Dresses the anchors Mind Elixir builds for the links a map's nodes carry.+ *+ * It puts the stored value into `href` as it stands and opens every link in a tab of its own, which+ * for a note means leaving the map behind for no reason; and a map that arrived by import or sync+ * can carry an address that should not be followed at all. Since the anchor is built anew from the+ * node's own data, this is applied again after every layout.+ *+ * @param container the element holding the rendered nodes.+ */+export function renderNodeLinks(container: HTMLElement) {+ for (const anchor of container.querySelectorAll<HTMLAnchorElement>("a.hyper-link")) {+ const link = anchor.getAttribute("href") ?? "";+ const href = getNodeLinkHref(link);++ // An address we may not follow is rendered inert rather than dropped, so that the node goes+ // on saying it carries a link — as the share view does with a hostile scheme.+ anchor.setAttribute("href", href ?? "about:blank");+ anchor.rel = "noopener noreferrer";++ if (getLinkedNotePath(link)) {+ // A note opens where the map is, as it does from anywhere else; `_blank` would force a+ // tab of its own (see `goToLinkExt`), leaving the map for a click that meant to follow+ // a thought.+ anchor.removeAttribute("target");+ anchor.removeAttribute("title");+ } else {+ anchor.title = href ?? link;+ }+ }+}