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): open Trilium's own menu on a node
Elian Doran90fdd74253fd
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 52de998f33..fd0b325566 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3530,8 +3530,8 @@"cancelFocus": "Cancel Focus Mode","moveUp": "Move up","moveDown": "Move down",- "link": "Link",- "linkBidirectional": "Bidirectional Link",+ "draw-arrow": "Draw an arrow to…",+ "draw-arrow-bidirectional": "Draw a two-way arrow to…","clickTips": "Please click the target node","summary": "Summary","new-topic": "New topic",diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.css b/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.cssnew file mode 100644index 0000000000..f11a1e2df3--- /dev/null+++ b/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.css@@ -0,0 +1,23 @@+/*+ * What is asked of the user while an arrow waits for its far end: the one thing they are meant to+ * do next, said at the head of the map where the eye already is after a menu closes.+ *+ * On the same glass the bars stand on (see MapToolbar.css), a hand's width in from the top so that+ * it does not sit on the bar of direction buttons in the corner. It takes no clicks of its own —+ * the very next one belongs to the node being chosen, wherever that node happens to be.+ */+.mind-map-container .mind-map-overlay .mind-map-arrow-hint {+ position: absolute;+ top: var(--mind-map-inset-top);+ left: 50%;+ transform: translateX(-50%);+ padding: 6px 14px;+ max-width: calc(100% - var(--mind-map-inset) * 2);+ background: var(--menu-background-color);+ color: var(--menu-text-color);+ border: 1px solid var(--dropdown-border-color);+ border-radius: 8px;+ box-shadow: 0 2px 8px #0003;+ backdrop-filter: blur(10px);+ pointer-events: none;+}diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.spec.tsx b/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.spec.tsxnew file mode 100644index 0000000000..95bb24c4f6--- /dev/null+++ b/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.spec.tsx@@ -0,0 +1,156 @@+import i18next from "i18next";+import type { MindElixirInstance, NodeObj, Topic } from "mind-elixir";+import { act } from "preact/test-utils";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import contextMenu, { type ContextMenuOptions } from "../../../menus/context_menu";+import englishTranslation from "../../../translations/en/translation.json";+import { renderInto } from "../../../test/render";+import type { MindMapCommand } from "./context_menu";+import MapContextMenu from "./MapContextMenu";++vi.mock("../../../menus/context_menu", () => ({ default: { show: vi.fn() } }));++beforeAll(() => i18next.init({ lng: "en", resources: { en: { translation: englishTranslation } } }));+beforeEach(() => vi.mocked(contextMenu.show).mockClear());++const ROOT: NodeObj = { id: "root", topic: "Root" };++/**+ * A stand-in for the Mind Elixir instance exposing only what the menu touches: the map the far end+ * of an arrow is clicked on, the selection, and the drawing of the arrow itself.+ */+function buildMind() {+ const map = document.createElement("div");+ document.body.appendChild(map);++ const listeners = new Set<(e: MouseEvent) => void>();+ const mind = {+ map,+ currentNode: buildTopic("n1"),+ currentNodes: [],+ createArrow: vi.fn(),+ bus: {+ addListener: (_type: string, listener: (e: MouseEvent) => void) => listeners.add(listener),+ removeListener: (_type: string, listener: (e: MouseEvent) => void) => listeners.delete(listener)+ }+ } as unknown as MindElixirInstance;++ /** Right-clicks a node, as the map's own pointer handling reports it. */+ const rightClick = () => act(() => {+ for (const listener of listeners) listener(new MouseEvent("contextmenu"));+ });++ return { mind, map, rightClick };+}++/** A node as the map builds it, laid onto the map so a click on it can be seen. */+function buildTopic(id: string) {+ const topic = document.createElement("me-tpc");+ (topic as unknown as Topic).nodeObj = { id, topic: id, parent: ROOT };+ return topic as unknown as Topic;+}++/** What the last menu shown was told to do when the given entry was chosen. */+function choose(command: MindMapCommand) {+ const options = vi.mocked(contextMenu.show).mock.lastCall?.[0] as ContextMenuOptions<MindMapCommand>;+ act(() => options.selectMenuItemHandler({ title: "", command }, null as never));+}++/** Builds the menu and settles it, so that what it listens to is listened to before it speaks. */+function renderMenu(mind: MindElixirInstance) {+ let container: HTMLElement | undefined;+ act(() => { container = renderInto(<MapContextMenu mind={mind} />); });+ if (!container) throw new Error("the menu was not rendered");+ return container;+}++function hint(container: HTMLElement) {+ return container.querySelector(".mind-map-arrow-hint");+}++describe("MapContextMenu", () => {+ it("opens Trilium's own menu where the map says one was asked for", () => {+ const { mind, rightClick } = buildMind();+ renderMenu(mind);++ rightClick();++ const options = vi.mocked(contextMenu.show).mock.lastCall?.[0];+ expect(options?.items.length).toBeGreaterThan(0);+ });++ it("opens nothing where the right-click landed on no node", () => {+ const { mind, rightClick } = buildMind();+ (mind as { currentNode: Topic | null }).currentNode = null;+ renderMenu(mind);++ rightClick();++ expect(contextMenu.show).not.toHaveBeenCalled();+ });++ it("asks for the far end of an arrow, and draws it to the node clicked next", () => {+ const { mind, map, rightClick } = buildMind();+ const from = mind.currentNode;+ const to = buildTopic("n2");+ map.appendChild(to);+ const container = renderMenu(mind);++ rightClick();+ choose("drawArrowBidirectional");+ expect(hint(container)).not.toBeNull();++ act(() => to.dispatchEvent(new MouseEvent("click", { bubbles: true })));++ expect(mind.createArrow).toHaveBeenCalledWith(from, to, { bidirectional: true });+ expect(hint(container)).toBeNull();+ });++ it("draws a one-way arrow without asking for one back", () => {+ const { mind, map, rightClick } = buildMind();+ const to = buildTopic("n2");+ map.appendChild(to);+ renderMenu(mind);++ rightClick();+ choose("drawArrow");+ act(() => to.dispatchEvent(new MouseEvent("click", { bubbles: true })));++ expect(mind.createArrow).toHaveBeenCalledWith(mind.currentNode, to, undefined);+ });++ it("gives the arrow up on a click beside a node, and on Escape", () => {+ const { mind, map, rightClick } = buildMind();+ const container = renderMenu(mind);++ rightClick();+ choose("drawArrow");+ act(() => map.dispatchEvent(new MouseEvent("click", { bubbles: true })));+ expect(mind.createArrow).not.toHaveBeenCalled();+ expect(hint(container)).toBeNull();++ rightClick();+ choose("drawArrow");+ expect(hint(container)).not.toBeNull();+ act(() => { document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });++ expect(mind.createArrow).not.toHaveBeenCalled();+ expect(hint(container)).toBeNull();+ });++ it("draws no arrow from a node to itself", () => {+ const { mind, map, rightClick } = buildMind();+ const from = mind.currentNode;+ if (from) map.appendChild(from);+ const container = renderMenu(mind);++ rightClick();+ choose("drawArrow");+ act(() => from?.dispatchEvent(new MouseEvent("click", { bubbles: true })));++ expect(mind.createArrow).not.toHaveBeenCalled();+ // Given up all the same: the click was spent, and a hint left standing would be a lie.+ expect(hint(container)).toBeNull();+ });+});diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.tsx b/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.tsxnew file mode 100644index 0000000000..dcf1cbf5c4--- /dev/null+++ b/apps/client/src/widgets/type_widgets/mind_map/MapContextMenu.tsx@@ -0,0 +1,91 @@+import "./MapContextMenu.css";++import type { MindElixirInstance } from "mind-elixir";+import { useCallback, useEffect, useState } from "preact/hooks";++import contextMenu from "../../../menus/context_menu";+import { t } from "../../../services/i18n";+import { type ArrowRequest, buildNodeMenuItems, findArrowTarget, runNodeMenuCommand } from "./context_menu";++interface MapContextMenuProps {+ mind: MindElixirInstance;+}++/**+ * The menu a node is right-clicked for, and the one thing it asks for that a menu cannot finish on+ * its own: the far end of an arrow, which is chosen by clicking a second node.+ *+ * Mind Elixir draws a menu of its own, which is left out (`contextMenu: false`, see MindMap.tsx)+ * along with its two bars. What it never stopped doing is telling us that one was asked for — the+ * word comes from the map's pointer handling rather than from the menu — and it selects the node+ * under the pointer before saying so, so the selection is already the right one when it arrives.+ *+ * The component draws nothing but the hint over the map while an arrow is waiting for its far end.+ */+export default function MapContextMenu({ mind }: MapContextMenuProps) {+ const [ pendingArrow, setPendingArrow ] = useState<ArrowRequest | null>(null);++ useNodeMenu(mind, setPendingArrow);+ useArrowTarget(mind, pendingArrow, useCallback(() => setPendingArrow(null), []));++ return pendingArrow && <div className="mind-map-arrow-hint">{t("mind-map.clickTips")}</div>;+}++/** Opens Trilium's own menu wherever the map says one was asked for. */+function useNodeMenu(mind: MindElixirInstance, requestArrow: (request: ArrowRequest) => void) {+ useEffect(() => {+ const show = (e: MouseEvent) => {+ const node = mind.currentNode;+ if (!node) return;++ contextMenu.show({+ x: e.pageX,+ y: e.pageY,+ items: buildNodeMenuItems(node.nodeObj),+ selectMenuItemHandler: ({ command }) => runNodeMenuCommand(mind, command, requestArrow)+ });+ };++ mind.bus.addListener("showContextMenu", show);+ return () => mind.bus.removeListener("showContextMenu", show);+ }, [ mind, requestArrow ]);+}++/**+ * Waits for the node an arrow asked for should end at, and draws it there.+ *+ * A click anywhere else on the map gives the arrow up, as does Escape — the way out Mind Elixir's+ * own gesture went without, leaving the next click on the map to be spent on an arrow the user had+ * stopped wanting.+ */+function useArrowTarget(mind: MindElixirInstance, request: ArrowRequest | null, done: () => void) {+ useEffect(() => {+ if (!request) return;++ const onClick = (e: MouseEvent) => {+ e.preventDefault();++ const to = findArrowTarget(e.target);+ // Drawn to itself an arrow has nowhere to run, and the map draws nothing.+ if (to && to !== request.from) {+ mind.createArrow(request.from, to, request.bidirectional ? { bidirectional: true } : undefined);+ }+ done();+ };++ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key !== "Escape") return;+ // The map is listening for Escape as well, and has its own use for it.+ e.stopPropagation();+ done();+ };++ mind.map.addEventListener("click", onClick);+ document.addEventListener("keydown", onKeyDown, true);++ return () => {+ mind.map.removeEventListener("click", onClick);+ document.removeEventListener("keydown", onKeyDown, true);+ };+ }, [ mind, request, done ]);+}diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.spec.tsx b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.spec.tsxindex b03f291b1e..5bb4b3143a 100644--- a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.spec.tsx+++ b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.spec.tsx@@ -11,7 +11,7 @@ import MapToolbar, { DirectionToolbar } from "./MapToolbar";* range, the element that goes fullscreen, the map's own transform, the direction it is laid out* by, and the ways it is moved and relaid.*/-function buildMind({ scaleVal = 1, direction = 1 } = {}) {+function buildMind({ scaleVal = 1, direction = 1, isFocusMode = false } = {}) {const el = document.createElement("div");el.requestFullscreen = vi.fn(async () => {});document.body.appendChild(el);@@ -41,12 +41,18 @@ function buildMind({ scaleVal = 1, direction = 1 } = {}) {scaleMin: 0.2,scaleMax: 1.4,direction,+ isFocusMode,scale,toCenter: vi.fn(),move: vi.fn(),initLeft: relayOut(0),initRight: relayOut(1),initSide: relayOut(2),+ // As the map does: it is laid out afresh, showing all it has again.+ cancelFocus: vi.fn(() => {+ mind.isFocusMode = false;+ fire("linkDiv");+ }),bus: {fire,addListener: (type: string, listener: (...args: unknown[]) => void) => {@@ -111,6 +117,26 @@ describe("MapToolbar", () => {expect(buttons(container)[FULLSCREEN].className).toContain("bx-fullscreen");});+ it("keeps the way out of focus mode off the bar while there is nothing to leave", () => {+ const container = renderToolbar(buildMind());++ expect(buttons(container).some((button) => button.className.includes("bx-exit"))).toBe(false);+ });++ it("offers the way out of focus mode while the map is narrowed, and drops it once it is not", () => {+ const mind = buildMind({ isFocusMode: true });+ const container = renderToolbar(mind);++ // Leading the bar: it is the one thing there that undoes a state the map is being read in.+ expect(buttons(container)).toHaveLength(5);+ expect(buttons(container)[0].className).toContain("bx-exit");++ press(container, 0);++ expect(mind.cancelFocus).toHaveBeenCalled();+ expect(buttons(container)).toHaveLength(4);+ });+it("zooms by one step of the map's own sensitivity, in either direction", () => {const mind = buildMind();const container = renderToolbar(mind);diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsxindex 432b9161a9..f4867f3424 100644--- a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx+++ b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx@@ -24,6 +24,7 @@ interface MapToolbarProps {*/export default function MapToolbar({ mind }: MapToolbarProps) {const scale = useMapScale(mind);+ const isFocused = useMapFocus(mind);const [ isFullscreen, toggleFullscreen ] = useMapFullscreen(mind);const limits = { sensitivity: mind.scaleSensitivity, min: mind.scaleMin, max: mind.scaleMax };@@ -32,6 +33,18 @@ export default function MapToolbar({ mind }: MapToolbarProps) {return (<Toolbar className="mind-map-view-toolbar">+ {/* Leaving focus mode is about the map rather than about any one node, so it stands+ here rather than in the menu a node is right-clicked for — which is where Mind+ Elixir kept it, offered on every node whether the map was narrowed or not. It is+ only here while there is something to leave, the map otherwise showing all it has. */}+ {isFocused && (+ <ToolbarButton+ icon="bx bx-exit"+ text={t("mind-map.cancelFocus")}+ onClick={() => mind.cancelFocus()}+ />+ )}+<ToolbarButtonicon="bx bx-zoom-in"text={t("mind-map.zoom-in")}@@ -162,27 +175,41 @@ function useMapScale(mind: MindElixirInstance) {return scale;}+/** The way the map is laid out, followed as it changes. */+function useMapDirection(mind: MindElixirInstance) {+ return useMapState(mind, (mind) => mind.direction);+}++/** Whether the map is narrowed to one node's branch, followed as that comes and goes. */+function useMapFocus(mind: MindElixirInstance) {+ return useMapState(mind, (mind) => mind.isFocusMode);+}+/**- * The way the map is laid out, followed as it changes.+ * Follows something a map holds that it does not announce in its own right.*- * A map says so when it is laid out afresh, but not when it is first filled: content carrying a- * direction of its own is taken silently, and a map built and then filled would leave the bar- * showing the direction it was born with. What every layout of a map does say is that its branches- * have been drawn, which is asked after instead — it costs a read of a number, and it is the one- * word that comes however the direction was arrived at.+ * Neither the direction nor the focus is spoken of directly: content carrying a direction of its own+ * is taken silently as a map is filled, and narrowing a map says only that it has been laid out+ * afresh. What every one of them does say is that the branches have been drawn, which is asked after+ * instead — it costs a read of what is wanted, and it is the one word that comes however the map+ * arrived at it.*/-function useMapDirection(mind: MindElixirInstance) {- const [ direction, setDirection ] = useState(mind.direction);+function useMapState<T>(mind: MindElixirInstance, read: (mind: MindElixirInstance) => T) {+ const [ value, setValue ] = useState(() => read(mind));+ // Read afresh on every report rather than closed over, so that a listener bound once follows a+ // reader the component hands over anew on each render.+ const readRef = useRef(read);+ readRef.current = read;useEffect(() => {- const report = () => setDirection(mind.direction);+ const report = () => setValue(() => readRef.current(mind));report();mind.bus.addListener("linkDiv", report);return () => mind.bus.removeListener("linkDiv", report);}, [ mind ]);- return direction;+ return value;}/**diff --git a/apps/client/src/widgets/type_widgets/mind_map/MindMap.tsx b/apps/client/src/widgets/type_widgets/mind_map/MindMap.tsxindex 3a13160bee..59bb0109e0 100644--- a/apps/client/src/widgets/type_widgets/mind_map/MindMap.tsx+++ b/apps/client/src/widgets/type_widgets/mind_map/MindMap.tsx@@ -4,7 +4,6 @@ import "./MindMap.css";import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import { t } from "i18next";import { DARK_THEME, default as VanillaMindElixir, MindElixirData, MindElixirInstance, NodeObj, Operation, Theme, THEME as LIGHT_THEME } from "mind-elixir";-import type { LangPack } from "mind-elixir/i18n";import { ComponentChildren, HTMLAttributes, RefObject } from "preact";import { createPortal } from "preact/compat";import { useCallback, useEffect, useRef, useState } from "preact/hooks";@@ -18,6 +17,7 @@ import { TypeWidgetProps } from "../type_widget";import { renderMindMapPreviewSvg } from "./export";import { renderIconClasses } from "./icons";import { renderNodeLinks } from "./links";+import MapContextMenu from "./MapContextMenu";import MapToolbar, { DirectionToolbar } from "./MapToolbar";import NodePanel from "./NodePanel";@@ -82,23 +82,6 @@ interface MindElixirProps {onSelectionChange?: (selectedNodes: NodeObj[]) => void;}-function buildMindElixirLangPack(): LangPack {- return {- addChild: t("mind-map.addChild"),- addParent: t("mind-map.addParent"),- addSibling: t("mind-map.addSibling"),- removeNode: t("mind-map.removeNode"),- focus: t("mind-map.focus"),- cancelFocus: t("mind-map.cancelFocus"),- moveUp: t("mind-map.moveUp"),- moveDown: t("mind-map.moveDown"),- link: t("mind-map.link"),- linkBidirectional: t("mind-map.linkBidirectional"),- clickTips: t("mind-map.clickTips"),- summary: t("mind-map.summary")- };-}-export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {const apiRef = useRef<MindElixirInstance>(null);const containerRef = useRef<HTMLDivElement>(null);@@ -200,6 +183,11 @@ export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {<DirectionToolbar mind={mind} /><MapToolbar mind={mind} />+ {/* Only a map that can be edited is right-clicked at all: the event the menu is+ built from comes from Mind Elixir's pointer handling, which raises it for an+ editable map alone. Everything the menu holds edits the map in any case. */}+ {!isReadOnly && <MapContextMenu mind={mind} />}+{/* Offered on a read-only map as well: Mind Elixir still selects a node there, andthe panel then holds the memo alone — the one thing a node carries that the mapitself never draws, and which would otherwise be out of reach (see NodePanel). */}@@ -226,8 +214,9 @@ function MindElixir({ children, containerRef: externalContainerRef, containerProconst mind = new VanillaMindElixir({el: containerRef.current,editable,- contextMenu: { locale: buildMindElixirLangPack() },- // Both of the bars the library lays over a map are Trilium's instead (see MapToolbar).+ // Everything the library would lay over a map is Trilium's instead: the two bars of+ // buttons (see MapToolbar) and the menu a node is right-clicked for (see MapContextMenu).+ contextMenu: false,toolBar: false,// The name every node added to the map is born with, which Mind Elixir would otherwise// give in English. Read afresh on every build, which follows a change of locale.diff --git a/apps/client/src/widgets/type_widgets/mind_map/context_menu.spec.ts b/apps/client/src/widgets/type_widgets/mind_map/context_menu.spec.tsnew file mode 100644index 0000000000..2c2fe0a07e--- /dev/null+++ b/apps/client/src/widgets/type_widgets/mind_map/context_menu.spec.ts@@ -0,0 +1,156 @@+import i18next from "i18next";+import type { MindElixirInstance, NodeObj, Topic } from "mind-elixir";+import { beforeAll, describe, expect, it, vi } from "vitest";++import type { MenuCommandItem } from "../../../menus/context_menu";+import englishTranslation from "../../../translations/en/translation.json";+import { buildNodeMenuItems, findArrowTarget, type MindMapCommand, runNodeMenuCommand } from "./context_menu";++// The entries are named through i18next, which nothing else in the suite sets up.+beforeAll(() => i18next.init({ lng: "en", resources: { en: { translation: englishTranslation } } }));++const ROOT: NodeObj = { id: "root", topic: "Root" };+const CHILD: NodeObj = { id: "n1", topic: "Node", parent: ROOT };++/** The commands the menu offers for a node, in the order it offers them. */+function commandsFor(node: NodeObj) {+ return buildNodeMenuItems(node)+ .filter((item): item is MenuCommandItem<MindMapCommand> => "command" in item)+ .map((item) => item.command);+}++/**+ * A stand-in for the Mind Elixir instance exposing only what the menu touches: the selection, and+ * the calls each entry stands for.+ */+function buildMind(node: Topic | null = { nodeObj: CHILD } as Topic) {+ return {+ currentNode: node,+ currentNodes: node ? [ node ] : [],+ addChild: vi.fn(),+ insertSibling: vi.fn(),+ insertParent: vi.fn(),+ moveUpNode: vi.fn(),+ moveDownNode: vi.fn(),+ createSummary: vi.fn(),+ unselectNodes: vi.fn(),+ focusNode: vi.fn(),+ removeNodes: vi.fn()+ } as unknown as MindElixirInstance;+}++describe("buildNodeMenuItems", () => {+ it("offers everything the map's own menu did, bar what moved to the toolbar", () => {+ expect(commandsFor(CHILD)).toEqual([+ "addChild", "addSibling", "addParent",+ "moveUp", "moveDown",+ "drawArrow", "drawArrowBidirectional", "summary",+ "focus",+ "remove"+ ]);+ });++ it("leaves out what a root cannot take part in, rather than greying it", () => {+ expect(commandsFor(ROOT)).toEqual([ "addChild", "drawArrow", "drawArrowBidirectional", "summary" ]);+ expect(buildNodeMenuItems(ROOT).every((item) => !("enabled" in item && item.enabled === false))).toBe(true);+ });++ it("leaves no rule of separators over an empty group, nor one at either end", () => {+ for (const node of [ ROOT, CHILD ]) {+ const items = buildNodeMenuItems(node);+ const separators = items.map((item) => "kind" in item && item.kind === "separator");++ expect(separators[0]).toBe(false);+ expect(separators[separators.length - 1]).toBe(false);+ expect(separators.some((isSeparator, at) => isSeparator && separators[at + 1])).toBe(false);+ }+ });++ it("names every entry and gives it a mark", () => {+ for (const item of buildNodeMenuItems(CHILD)) {+ if (!("command" in item)) continue;+ expect(item.title).toBeTruthy();+ // A key that was never translated, rather than a name.+ expect(item.title).not.toContain("mind-map.");+ expect(item.uiIcon).toMatch(/^bx /);+ }+ });+});++describe("runNodeMenuCommand", () => {+ const requestArrow = vi.fn();++ it.each([+ [ "addChild", "addChild" ],+ [ "addParent", "insertParent" ],+ [ "moveUp", "moveUpNode" ],+ [ "moveDown", "moveDownNode" ],+ [ "focus", "focusNode" ],+ [ "remove", "removeNodes" ]+ ] as const)("carries out %s", (command, method) => {+ const mind = buildMind();+ runNodeMenuCommand(mind, command, requestArrow);+ expect(mind[method]).toHaveBeenCalled();+ });++ it("adds a sibling after the node rather than before it", () => {+ const mind = buildMind();+ runNodeMenuCommand(mind, "addSibling", requestArrow);+ expect(mind.insertSibling).toHaveBeenCalledWith("after");+ });++ it("lets go of the nodes a summary was drawn over, the summary opening for naming over them", () => {+ const mind = buildMind();+ runNodeMenuCommand(mind, "summary", requestArrow);+ expect(mind.createSummary).toHaveBeenCalled();+ expect(mind.unselectNodes).toHaveBeenCalledWith(mind.currentNodes);+ });++ it("asks for the far end of an arrow rather than drawing one, and says which kind", () => {+ const mind = buildMind();+ const asked = vi.fn();++ runNodeMenuCommand(mind, "drawArrow", asked);+ expect(asked).toHaveBeenCalledWith({ from: mind.currentNode, bidirectional: false });++ runNodeMenuCommand(mind, "drawArrowBidirectional", asked);+ expect(asked).toHaveBeenCalledWith({ from: mind.currentNode, bidirectional: true });+ });++ it("does nothing where there is no node under the menu, or no command", () => {+ const mind = buildMind(null);++ runNodeMenuCommand(mind, "focus", requestArrow);+ runNodeMenuCommand(mind, "drawArrow", requestArrow);+ runNodeMenuCommand(mind, undefined, requestArrow);++ expect(mind.focusNode).not.toHaveBeenCalled();+ expect(requestArrow).not.toHaveBeenCalled();+ });+});++describe("findArrowTarget", () => {+ /** A node as the map builds it: a topic carrying its object, with an icon inside it. */+ function buildTopic() {+ const topic = document.createElement("me-tpc");+ (topic as unknown as Topic).nodeObj = CHILD;+ topic.innerHTML = `<span class="mind-map-lead-icon bx bx-star"></span>Node`;+ return topic;+ }++ it("finds the node a click landed on", () => {+ const topic = buildTopic();+ expect(findArrowTarget(topic)).toBe(topic);+ });++ it("finds it through whatever the node holds, an icon of ours among them", () => {+ const topic = buildTopic();+ expect(findArrowTarget(topic.querySelector(".mind-map-lead-icon"))).toBe(topic);+ });++ it("finds nothing beside a node, or on a topic standing for none", () => {+ expect(findArrowTarget(document.createElement("div"))).toBeNull();+ expect(findArrowTarget(document.createElement("me-tpc"))).toBeNull();+ expect(findArrowTarget(null)).toBeNull();+ });+});diff --git a/apps/client/src/widgets/type_widgets/mind_map/context_menu.ts b/apps/client/src/widgets/type_widgets/mind_map/context_menu.tsnew file mode 100644index 0000000000..0d59119d64--- /dev/null+++ b/apps/client/src/widgets/type_widgets/mind_map/context_menu.ts@@ -0,0 +1,128 @@+import type { MindElixirInstance, NodeObj, Topic } from "mind-elixir";++import type { MenuItem } from "../../../menus/context_menu";+import { t } from "../../../services/i18n";++/** What the menu offers to do with the node it was opened on. */+export type MindMapCommand =+ | "addChild" | "addSibling" | "addParent"+ | "moveUp" | "moveDown"+ | "drawArrow" | "drawArrowBidirectional" | "summary"+ | "focus"+ | "remove";++/** An arrow the user has asked for and must now choose the far end of (see MapContextMenu). */+export interface ArrowRequest {+ from: Topic;+ bidirectional: boolean;+}++/**+ * What the menu holds for the node it was opened on, in groups: what is added beside it, where it+ * sits among its siblings, what is drawn from it, what the map is narrowed to, and — last, apart+ * from the rest — what removes it.+ *+ * Everything a root cannot take part in is left out rather than shown greyed, which is what Mind+ * Elixir's own menu did: six of its eleven entries greyed out on the very node a map opens with,+ * leaving a menu that was mostly unavailable on the node most likely to be asked.+ *+ * @param node the node the menu was opened on.+ */+export function buildNodeMenuItems(node: NodeObj): MenuItem<MindMapCommand>[] {+ // Filled in by Mind Elixir as it reads a map; the root is the one node left without one.+ const isRoot = !node.parent;++ const items: (MenuItem<MindMapCommand> | null)[] = [+ { title: t("mind-map.addChild"), command: "addChild", uiIcon: "bx bx-subdirectory-right", shortcut: "Tab" },+ !isRoot ? { title: t("mind-map.addSibling"), command: "addSibling", uiIcon: "bx bx-plus", shortcut: "Enter" } : null,+ !isRoot ? { title: t("mind-map.addParent"), command: "addParent", uiIcon: "bx bx-git-merge", shortcut: "Ctrl+Enter" } : null,++ !isRoot ? { kind: "separator" } : null,+ !isRoot ? { title: t("mind-map.moveUp"), command: "moveUp", uiIcon: "bx bx-chevron-up", shortcut: "PgUp" } : null,+ !isRoot ? { title: t("mind-map.moveDown"), command: "moveDown", uiIcon: "bx bx-chevron-down", shortcut: "PgDn" } : null,++ { kind: "separator" },+ { title: t("mind-map.draw-arrow"), command: "drawArrow", uiIcon: "bx bx-right-arrow-alt" },+ { title: t("mind-map.draw-arrow-bidirectional"), command: "drawArrowBidirectional", uiIcon: "bx bx-transfer-alt" },+ { title: t("mind-map.summary"), command: "summary", uiIcon: "bx bx-bracket" },++ // Narrowing the map to the root is what leaving focus mode does, so the root is not offered+ // it — and leaving is offered by the toolbar rather than here (see MapToolbar).+ !isRoot ? { kind: "separator" } : null,+ !isRoot ? { title: t("mind-map.focus"), command: "focus", uiIcon: "bx bx-crosshair" } : null,++ !isRoot ? { kind: "separator" } : null,+ !isRoot ? { title: t("mind-map.removeNode"), command: "remove", uiIcon: "bx bx-trash", shortcut: "Delete" } : null+ ];++ return items.filter((item) => item !== null);+}++/**+ * Carries out what was chosen, over the selection the map already holds — the node under the+ * pointer having been selected before the menu was asked for.+ *+ * @param mind the instance the menu was opened over.+ * @param command what was chosen; anything unknown is ignored.+ * @param requestArrow asked for the two ends of an arrow, which takes a further click on the map+ * and so cannot be finished here (see MapContextMenu).+ */+export function runNodeMenuCommand(+ mind: MindElixirInstance,+ command: MindMapCommand | undefined,+ requestArrow: (request: ArrowRequest) => void+) {+ const node = mind.currentNode;++ switch (command) {+ case "addChild":+ void mind.addChild();+ break;+ case "addSibling":+ void mind.insertSibling("after");+ break;+ case "addParent":+ void mind.insertParent();+ break;+ case "moveUp":+ void mind.moveUpNode();+ break;+ case "moveDown":+ void mind.moveDownNode();+ break;+ case "drawArrow":+ case "drawArrowBidirectional":+ if (node) requestArrow({ from: node, bidirectional: command === "drawArrowBidirectional" });+ break;+ case "summary":+ mind.createSummary();+ // The summary opens for naming the moment it is drawn, and the nodes it was drawn over+ // would otherwise stay selected under it — a Delete meant for the name taking them with it.+ mind.unselectNodes(mind.currentNodes);+ break;+ case "focus":+ if (node) mind.focusNode(node);+ break;+ case "remove":+ void mind.removeNodes(mind.currentNodes);+ break;+ }+}++/**+ * The node an arrow being drawn should end at, for a click landing anywhere within it — its text,+ * one of its icons, or the picture it carries.+ *+ * Mind Elixir's own menu read the element clicked and asked what its parent was, so a click on+ * anything a node holds — every icon we dress a node with among them (see icons.ts) — missed the+ * node and quietly dropped the arrow.+ *+ * @returns the node clicked, or `null` where the click landed beside one.+ */+export function findArrowTarget(target: EventTarget | null): Topic | null {+ if (!(target instanceof Element)) return null;++ const topic = target.closest("me-tpc");+ // A topic carries the node it stands for; anything else wearing the tag is not one to draw to.+ return topic && "nodeObj" in topic ? topic as Topic : null;+}