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): give a node a memo
Elian Doranfa45a0b3f9aa
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 1229f1bcda..fdb4aa9701 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3552,6 +3552,8 @@"clear-link": "Remove the link","link-mixed": "Different links","links-differ": "The selected nodes don't carry the same link.",+ "memo": "Memo",+ "memos-differ": "The selected nodes carry different memos, so this one can only be read.","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/react/CKEditor.tsx b/apps/client/src/widgets/react/CKEditor.tsxindex 14aca18e9a..1e97a2c8b1 100644--- a/apps/client/src/widgets/react/CKEditor.tsx+++ b/apps/client/src/widgets/react/CKEditor.tsx@@ -43,6 +43,9 @@ interface CKEditorOpts {export default function CKEditor({ apiRef, currentValue, editor, config, disableNewlines, disableSpellcheck, onChange, onClick, onInitialized, ...restProps }: CKEditorOpts) {const editorContainerRef = useRef<HTMLDivElement>(null);const textEditorRef = useRef<CKTextEditor>(null);+ /** The value as it stands now, for the building of the editor to end on rather than begin with. */+ const currentValueRef = useRef(currentValue);+ currentValueRef.current = currentValue;useImperativeHandle(apiRef, () => {return {focus() {@@ -105,8 +108,16 @@ export default function CKEditor({ apiRef, currentValue, editor, config, disableuseEffect(() => {if (!editorContainerRef.current) return;+ let unmounted = false;editor.create(editorContainerRef.current, config).then((textEditor) => {+ // Gone before it was ready: build no further, and take with it what it has put on the+ // page, or the next editor would find it there and take it for its own content.+ if (unmounted) {+ void textEditor.destroy();+ return;+ }+textEditorRef.current = textEditor;if (disableNewlines) {@@ -134,12 +145,24 @@ export default function CKEditor({ apiRef, currentValue, editor, config, disable});}- if (currentValue) {- textEditor.setData(currentValue);- }+ // Read as the editor is ready rather than as it was asked for: building one takes a+ // while, and a value handed over in the meantime would otherwise be passed over — the+ // effect watching it having had no editor to give it to, and this one holding the value+ // as it stood when the building began.+ //+ // Set even when there is nothing to set: an editor built upon an element takes what+ // that element holds as its content, so anything left there — by an editor that stood+ // here before this one — would otherwise become the content of this one.+ textEditor.setData(currentValueRef.current ?? "");onInitialized?.(textEditor);});++ return () => {+ unmounted = true;+ void textEditorRef.current?.destroy();+ textEditorRef.current = null;+ };}, []);useEffect(() => {diff --git a/apps/client/src/widgets/type_widgets/MindMapNodeMemo.css b/apps/client/src/widgets/type_widgets/MindMapNodeMemo.cssnew file mode 100644index 0000000000..529b4e6f38--- /dev/null+++ b/apps/client/src/widgets/type_widgets/MindMapNodeMemo.css@@ -0,0 +1,23 @@+/*+ * The memo is a field like the others around it, framed and scrolling once what is written outgrows+ * the room the panel has: the editor inside it brings neither.+ */+.mind-map-node-panel .mind-map-node-memo {+ max-height: 160px;+ overflow: auto;+ padding: 4px 8px;+ border: 1px solid var(--main-border-color);+ border-radius: 6px;+ background: var(--input-background-color);++ &:focus-within {+ outline: 2px solid var(--input-focus-outline-color);+ }++ /* The editor is the field's own surface; a frame of its own would draw a second one within it. */+ .ck.ck-editor__editable {+ border: none;+ box-shadow: none;+ background: transparent;+ }+}diff --git a/apps/client/src/widgets/type_widgets/MindMapNodeMemo.spec.ts b/apps/client/src/widgets/type_widgets/MindMapNodeMemo.spec.tsnew file mode 100644index 0000000000..0299fac232--- /dev/null+++ b/apps/client/src/widgets/type_widgets/MindMapNodeMemo.spec.ts@@ -0,0 +1,29 @@+import type { NodeObj } from "mind-elixir";+import { describe, expect, it } from "vitest";++import { getNodeMemo, toMemoHtml } from "./MindMapNodeMemo";++function buildNode(node: Partial<NodeObj> = {}): NodeObj {+ return { id: "n1", topic: "Node", ...node };+}++describe("the memo of a node", () => {+ it("is read from the field the node menu wrote, which Mind Elixir has no say over", () => {+ // Its own `note` field is a different one, never written here: reading that instead would+ // leave every memo written before this panel unseen.+ expect(getNodeMemo(buildNode({ memo: "Ask about this" } as Partial<NodeObj>))).toBe("Ask about this");+ expect(getNodeMemo(buildNode({ note: "elsewhere" } as Partial<NodeObj>))).toBeUndefined();+ expect(getNodeMemo(buildNode())).toBeUndefined();+ });++ it("survives being taken into an editor, however it was written", () => {+ // Written through the textarea this replaces, a memo is plain text: read as HTML, a `<`+ // would swallow what follows it and the memo would come back shorter than it went in.+ expect(toMemoHtml("2 < 3 & counting")).toBe("<p>2 < 3 & counting</p>");+ expect(toMemoHtml("first\nsecond")).toBe("<p>first</p><p>second</p>");+ // Written through the editor, it is HTML already and is handed over as it stands.+ expect(toMemoHtml("<p>Ask <strong>about</strong> this</p>")).toBe("<p>Ask <strong>about</strong> this</p>");+ expect(toMemoHtml(null)).toBe("");+ expect(toMemoHtml("")).toBe("");+ });+});diff --git a/apps/client/src/widgets/type_widgets/MindMapNodeMemo.tsx b/apps/client/src/widgets/type_widgets/MindMapNodeMemo.tsxnew file mode 100644index 0000000000..92535df6b6--- /dev/null+++ b/apps/client/src/widgets/type_widgets/MindMapNodeMemo.tsx@@ -0,0 +1,137 @@+import "./MindMapNodeMemo.css";++import { AttributeEditor, CHAT_INPUT_PLUGINS, type CKTextEditor, type EditorConfig } from "@triliumnext/ckeditor5";+import type { NodeObj } from "mind-elixir";+import { useEffect, useLayoutEffect, useRef } from "preact/hooks";++import { escapeHtml } from "../../services/utils";+import CKEditor, { type CKEditorApi } from "../react/CKEditor";++/**+ * The memo a node carries: text kept about it, which the map itself never shows.+ *+ * Written as the field is left rather than as it is typed, which is what the textarea it replaces+ * did: a memo is written a paragraph at a time, and taking every keystroke would mean a copy of the+ * whole map in the undo stack for each of them.+ */+export default function MindMapNodeMemo({ selectionKey, memo, readOnly, onCommit }: {+ /**+ * What the panel currently stands for. The field is one editor for however many nodes are+ * selected over its lifetime, so it is told when that changes: the memo shown is the memo of+ * whatever is selected now, and what was typed for what came before belongs to those nodes.+ */+ selectionKey: string;+ memo: string | null;+ readOnly: boolean;+ onCommit(html: string): void;+}) {+ const apiRef = useRef<CKEditorApi>();+ const editorRef = useRef<CKTextEditor>(null);+ const html = toMemoHtml(memo);+ // Both are stamped with the selection they belong to: what the field was handed, and what it+ // holds now. The editor reports a change for a memo handed to it as readily as for one typed,+ // so without the stamp the memo of a node just selected passes for something typed for the one+ // just left — and is written over it.+ const shown = useRef({ key: selectionKey, html });+ const typed = useRef(shown.current);+ // The selection as it stands while the editor is reporting, which is a render behind the refs.+ const currentKey = useRef(selectionKey);+ currentKey.current = selectionKey;++ function commit(key: string) {+ if (readOnly || typed.current.key !== key || typed.current.html === shown.current.html) return;+ shown.current = typed.current;+ onCommit(typed.current.html);+ }++ /*+ * Taken up as the selection changes, and written back before it does.+ *+ * A layout effect rather than a plain one: its cleanup then runs within the same commit, ahead+ * of the editor being handed the new memo — which is a plain effect of the field below, and+ * would otherwise land first and take what was typed with it.+ */+ useLayoutEffect(() => {+ shown.current = { key: selectionKey, html };+ typed.current = shown.current;+ // Said outright rather than left to the field to notice: it sets what it is given only when+ // that differs from what it was given last, and two nodes carrying the same memo — no memo+ // at all, most of the time — are the same value. Whatever was typed for the node just left+ // would then simply stay on the page as the memo of the one just selected.+ apiRef.current?.setText(html);++ return () => commit(selectionKey);+ }, [ selectionKey ]);++ useEffect(() => {+ const editor = editorRef.current;+ if (!editor) return;++ if (readOnly) {+ editor.enableReadOnlyMode(MEMO_READ_ONLY_LOCK);+ } else {+ editor.disableReadOnlyMode(MEMO_READ_ONLY_LOCK);+ }+ }, [ readOnly ]);++ return (+ <CKEditor+ apiRef={apiRef}+ className="mind-map-node-memo"+ editor={AttributeEditor}+ config={MEMO_EDITOR_CONFIG}+ currentValue={html}+ onChange={(html) => (typed.current = { key: currentKey.current, html: html ?? "" })}+ onInitialized={(editor) => {+ editorRef.current = editor;+ if (readOnly) {+ editor.enableReadOnlyMode(MEMO_READ_ONLY_LOCK);+ }++ // The editor's own account of being left: a `blur` of the box it writes into does+ // not reach the element around it, so there is nothing there to listen for.+ editor.ui.focusTracker.on("change:isFocused", (_event, _name, isFocused) => {+ if (!isFocused) commit(currentKey.current);+ });+ }}+ />+ );+}++/** Kept still, so that the editor is not configured anew every time the panel renders. */+const MEMO_EDITOR_CONFIG: EditorConfig = {+ // The markdown autoformatting the chat box has — quotes, code, lists, links — and no toolbar.+ extraPlugins: CHAT_INPUT_PLUGINS,+ toolbar: { items: [] },+ licenseKey: "GPL",+ language: "en"+};++/** Held while the selection disagrees, there being no one memo to write over the others. */+const MEMO_READ_ONLY_LOCK = "mind-map-node-memo";++/**+ * A node's memo: what the node menu Trilium used to carry wrote into `nodeObj.memo`, from a plain+ * textarea, and what maps made since then hold.+ *+ * Mind Elixir neither declares the field nor renders it — it survives only because everything but a+ * node's parent is serialized — and the `note` it does declare is a different field the menu never+ * wrote. Keeping to `memo` is what keeps those memos the ones being read and written here.+ */+export function getNodeMemo(node: NodeObj) {+ return (node as NodeObj & { memo?: string }).memo;+}++/**+ * The memo as the editor takes it.+ *+ * A memo written through the old textarea is plain text, so one carrying no markup at all is+ * escaped into paragraphs rather than read as HTML — otherwise a `<` someone typed would swallow+ * what follows it, and the memo would come back shorter than it was written.+ */+export function toMemoHtml(memo: string | null | undefined) {+ if (!memo) return "";+ if (/<[a-z][\s\S]*>/i.test(memo)) return memo;++ return memo.split(/\r?\n/).map((line) => `<p>${escapeHtml(line)}</p>`).join("");+}diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsxindex 04965a9b53..5d0433cf1c 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx@@ -1,4 +1,6 @@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 { buildNotes } from "../../test/easy-froca";@@ -13,6 +15,45 @@ vi.mock("./helpers/mind_map_images", async (importOriginal) => ({uploadNodeImage: vi.fn()}));+// The memo field is a CKEditor, which wants a browser to build itself in; what it is handed and+// what it gives back is checked around it instead (see `toMemoHtml` below). The stand-in reports+// what it was last handed, so that a test can speak for the editor — the real one reports a change+// for a memo handed to it as readily as for one typed.+let memoEditor: MemoEditorProps = { className: "" };+/** What the stand-in is showing, which outlives the props it was last handed. */+let shownMemoText: string | undefined;+vi.mock("../react/CKEditor", async () => {+ const { useEffect, useImperativeHandle } = await import("preact/hooks");++ return {+ default: (props: MemoEditorProps) => {+ memoEditor = props;+ // What the real one shows: the value it was last told to show, whether it noticed the+ // change itself or was told outright.+ useImperativeHandle(props.apiRef ?? { current: undefined as { setText(text: string): void } | undefined }, () => ({+ setText(text: string) {+ shownMemoText = text;+ props.onChange?.(text);+ }+ }), []);+ // As the real one does: it takes a value it is handed only when that differs from the+ // one before it, and reports the change from an effect — where its own `setData` is made.+ useEffect(() => {+ shownMemoText = props.currentValue ?? "";+ props.onChange?.(props.currentValue ?? "");+ }, [ props.currentValue ]);+ return <div className={props.className} data-current-value={props.currentValue} />;+ }+ };+});++interface MemoEditorProps {+ className: string;+ currentValue?: string;+ apiRef?: { current: { setText(text: string): void } | undefined };+ onChange?: (html: string) => void;+}+function buildNode(node: Partial<NodeObj> = {}): NodeObj {return { id: "n1", topic: "Node", ...node };}@@ -23,8 +64,11 @@ function buildNode(node: Partial<NodeObj> = {}): NodeObj {*/function buildMind(nodes: NodeObj[]) {const reshapeNode = vi.fn();+ const topics = nodes.map((nodeObj) => ({ nodeObj }));const mind = {- currentNodes: nodes.map((nodeObj) => ({ nodeObj })),+ currentNodes: topics,+ // Looked up by the memo, which writes to the nodes it was given rather than to the selection.+ findEle: (id: string) => topics.find(({ nodeObj }) => nodeObj.id === id),reshapeNode} as unknown as MindElixirInstance;return { mind, reshapeNode };@@ -184,6 +228,98 @@ describe("withIconAt", () => {});});+describe("the memo field of the panel", () => {+ /** What the field is currently showing, the editor itself standing in for the real one. */+ function shownMemo(container: HTMLElement) {+ return container.querySelector(".mind-map-node-memo")?.getAttribute("data-current-value");+ }++ /** Writes into the field, as someone typing does: what it shows is what it then reports. */+ async function typeMemo(html: string) {+ await act(async () => {+ shownMemoText = html;+ memoEditor.onChange?.(html);+ });+ }++ it("shows the memo of whatever is selected now, not of what was selected before", async () => {+ // One field serves every selection it outlives, so the memo it shows has to follow the+ // selection — otherwise the memo of the node left behind is what is read, and written over.+ const withMemo = buildNode({ id: "a", memo: "<p>About A</p>" } as Partial<NodeObj>);+ const without = buildNode({ id: "b" });+ let container: HTMLElement | undefined;++ await act(async () => {+ container = renderInto(<MindMapNodePanel mind={buildMind([withMemo]).mind} noteId="map" nodes={[withMemo]} />);+ });+ if (!container) throw new Error("render produced no container");+ const panel = container;+ expect(shownMemo(panel)).toBe("<p>About A</p>");++ // Rendered into the same container, so the panel is updated rather than built anew.+ await act(async () => {+ render(<MindMapNodePanel mind={buildMind([without]).mind} noteId="map" nodes={[without]} />, panel);+ });+ expect(shownMemo(panel)).toBe("");++ await act(async () => {+ render(<MindMapNodePanel mind={buildMind([withMemo]).mind} noteId="map" nodes={[withMemo]} />, panel);+ });+ expect(shownMemo(panel)).toBe("<p>About A</p>");+ });++ it("clears what was typed when the node selected next carries the same memo — none, usually", async () => {+ // The field takes a value it is handed only when it differs from the one before it, and two+ // nodes with no memo hand it the same nothing. Left to that, what was typed for the node+ // just left stays on the page as the memo of the one just selected.+ const first = buildNode({ id: "a" });+ const second = buildNode({ id: "b" });+ let container: HTMLElement | undefined;++ await act(async () => {+ container = renderInto(<MindMapNodePanel mind={buildMind([first]).mind} noteId="map" nodes={[first]} />);+ });+ if (!container) throw new Error("render produced no container");+ const panel = container;++ await typeMemo("<p>Typed for A</p>");+ expect(shownMemoText).toBe("<p>Typed for A</p>");++ await act(async () => {+ render(<MindMapNodePanel mind={buildMind([second]).mind} noteId="map" nodes={[second]} />, panel);+ });+ expect(shownMemoText).toBe("");+ });++ it("writes what was typed to the node it was typed for, and the memo it is handed to none", async () => {+ const first = buildNode({ id: "a", memo: "<p>About A</p>" } as Partial<NodeObj>);+ const second = buildNode({ id: "b", memo: "<p>About B</p>" } as Partial<NodeObj>);+ const firstMind = buildMind([first]);+ let container: HTMLElement | undefined;++ await act(async () => {+ container = renderInto(<MindMapNodePanel mind={firstMind.mind} noteId="map" nodes={[first]} />);+ });+ if (!container) throw new Error("render produced no container");+ const panel = container;++ await typeMemo("<p>About A, at length</p>");++ // Selecting another node writes what was typed for the first back to the first...+ const secondMind = buildMind([second]);+ await act(async () => {+ render(<MindMapNodePanel mind={secondMind.mind} noteId="map" nodes={[second]} />, panel);+ });+ expect(firstMind.reshapeNode).toHaveBeenCalledWith(firstMind.mind.currentNodes[0], { memo: "<p>About A, at length</p>" });++ // ...and the memo the field is then handed is the second node's own, which it is not asked+ // to write anywhere — least of all over the node just left.+ await act(async () => memoEditor.onChange?.("<p>About B</p>"));+ expect(secondMind.reshapeNode).not.toHaveBeenCalled();+ expect(firstMind.reshapeNode).toHaveBeenCalledTimes(1);+ });+});+describe("applyTagTexts", () => {it("keeps a styled tag while its text stands, and plain text for the rest", () => {const styled = { text: "urgent", style: { color: "red" } };diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsxindex b534d4252f..3244482d69 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx@@ -21,6 +21,7 @@ import IconPicker from "../react/IconPicker";import NoteAutocomplete from "../react/NoteAutocomplete";import { refToJQuerySelector } from "../react/react_utils";import SegmentedChoice from "../react/SegmentedChoice";+import MindMapNodeMemo, { getNodeMemo } from "./MindMapNodeMemo";import { fitNodeImage, getNodeImageShape, nearestNodeImageWidth, NODE_IMAGE_SHAPES, NODE_IMAGE_WIDTHS, type NodeImage as NodeImageData, type NodeImageShape, shapeNodeImage, uploadNodeImage } from "./helpers/mind_map_images";import { describeExternalLink, linkFromSuggestion } from "./helpers/mind_map_links";@@ -60,6 +61,7 @@ export default function MindMapNodePanel({ mind, noteId, nodes }: MindMapNodePanconst imageShape = getCommonValue(nodes, (node) => node.image && getNodeImageShape(node.image)) as NodeImageShape | null | typeof MIXED;const link = getCommonValue(nodes, (node) => node.hyperLink);const tags = gatherTags(nodes);+ const memo = getCommonValue(nodes, getNodeMemo);/*** Applies a patch to every selected node. The selection is read back from the instance rather@@ -72,6 +74,23 @@ export default function MindMapNodePanel({ mind, noteId, nodes }: MindMapNodePan}}+ /**+ * 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.+ */+ function writeMemo(memo: string) {+ for (const node of nodes) {+ try {+ void mind.reshapeNode(mind.findEle(node.id), { memo } as Partial<NodeObj>);+ } 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);+ }+ }+ }+/** Stores a picture on the note and gives it to the selection, if it can be taken in at all. */async function takeInImage(file: File) {const image = await uploadNodeImage(noteId, file);@@ -201,6 +220,18 @@ export default function MindMapNodePanel({ mind, noteId, nodes }: MindMapNodePanonCommit={(texts) => patchSelectedNodes((node) => ({ tags: applyTagTexts(node.tags, texts) }))}/></PanelSection>++ <PanelSection+ label={t("mind-map.memo")}+ title={memo === MIXED ? t("mind-map.memos-differ") : undefined}+ >+ <MindMapNodeMemo+ selectionKey={nodes.map((node) => node.id).join(" ")}+ memo={memo !== MIXED ? memo : null}+ readOnly={memo === MIXED}+ onCommit={writeMemo}+ />+ </PanelSection></div>);}