Skip to content

Build your personal knowledge base with Trilium Notes

feat(mind-map): let a node carry a picture

Elian Doran25443e5345fb
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 8309b91191..32ec6b3f9d 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3536,6 +3536,13 @@
"change-icon": "Change this icon",
"clear-icon": "Remove the icon",
"icons-differ": "The selected nodes don't carry the same icons, so these can only be read.",
+ "image": "Image",
+ "add-image": "Add an image",
+ "change-image": "Replace the image",
+ "remove-image": "Remove the image",
+ "image-mixed": "Different images",
+ "images-differ": "The selected nodes don't carry the same image.",
+ "image-upload-failed": "Cannot upload image \"{{name}}\".",
"node-link": "Link",
"add-link": "Add a link",
"choose-link": "Link this node to a note or a page",
diff --git a/apps/client/src/widgets/type_widgets/MindMap.tsx b/apps/client/src/widgets/type_widgets/MindMap.tsx
index c2194447d2..6d0ae5dd1f 100644
--- a/apps/client/src/widgets/type_widgets/MindMap.tsx
+++ b/apps/client/src/widgets/type_widgets/MindMap.tsx
@@ -191,7 +191,7 @@ export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {
}}
>
{!isReadOnly && selectedNodes.length > 0 && apiRef.current &&
- <MindMapNodePanel mind={apiRef.current} nodes={selectedNodes} />}
+ <MindMapNodePanel mind={apiRef.current} noteId={note.noteId} nodes={selectedNodes} />}
</MindElixir>
);
}
diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css b/apps/client/src/widgets/type_widgets/MindMapNodePanel.css
index 3561d222e9..8f129697dc 100644
--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css
+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.css
@@ -51,6 +51,46 @@
}
}
+/* The picture stands above the row of what can be done with it. */
+.mind-map-node-panel .mind-map-node-image {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+/*
+ * Shown as it will read on a node, only smaller — enough to tell which picture it is. Left to keep
+ * its proportions inside that, and read against the panel as it will be read against the map, so
+ * that a picture with transparent parts shows them as such rather than on a plate of its own.
+ */
+.mind-map-node-panel .mind-map-node-image-preview {
+ align-self: center;
+ max-width: 100%;
+ max-height: 90px;
+ object-fit: contain;
+ border-radius: 4px;
+}
+
+/* Where the selection carries different pictures, said in the room one would have taken. */
+.mind-map-node-panel .mind-map-node-image-mixed {
+ align-self: center;
+ padding: 12px 0;
+ font-size: .9em;
+ opacity: .7;
+}
+
+.mind-map-node-panel .mind-map-node-image-actions {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+
+ /* The sizes take what the buttons beside them leave, rather than the whole row (see below). */
+ .btn-group {
+ flex: 1;
+ width: auto;
+ }
+}
+
/*
* 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
diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx
index effe6d8cb5..02ee5dd623 100644
--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx
@@ -3,8 +3,16 @@ import { describe, expect, it, vi } from "vitest";
import { buildNotes } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
+import { uploadNodeImage } from "./helpers/mind_map_images";
import MindMapNodePanel, { applyTagTexts, DEFAULT_FONT_SIZE, gatherTags, getCommonValue, MIXED, NODE_BACKGROUND_COLORS, NODE_COLORS, withIconAt } from "./MindMapNodePanel";
+// Storing a picture is the one thing the panel does that leaves the browser; the rest of the module
+// (the sizes, the proportions) is the real one, being what the panel is checked against here.
+vi.mock("./helpers/mind_map_images", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./helpers/mind_map_images")>(),
+ uploadNodeImage: vi.fn()
+}));
+
function buildNode(node: Partial<NodeObj> = {}): NodeObj {
return { id: "n1", topic: "Node", ...node };
}
@@ -28,8 +36,9 @@ const TEXT = 1;
const BACKGROUND = 2;
const BRANCH = 3;
const ICON = 4;
-const LINK = 5;
-const TAGS = 6;
+const IMAGE = 5;
+const LINK = 6;
+const TAGS = 7;
function section(container: HTMLElement, index: number) {
const sections = container.querySelectorAll<HTMLElement>(".mind-map-node-panel-section");
@@ -58,6 +67,31 @@ function iconFaces(container: HTMLElement) {
[ ...button.classList ].filter((name) => name.startsWith("bx")).join(" "));
}
+function imagePreview(container: HTMLElement) {
+ return section(container, IMAGE).querySelector<HTMLImageElement>(".mind-map-node-image-preview");
+}
+
+function imageWidthButtons(container: HTMLElement) {
+ return Array.from(section(container, IMAGE).querySelectorAll<HTMLElement>(".btn-group .btn"));
+}
+
+function activeImageWidth(container: HTMLElement) {
+ return imageWidthButtons(container).findIndex((button) => button.classList.contains("active"));
+}
+
+/** The button of the picture row wearing the given icon, if it is offered at all. */
+function imageAction(container: HTMLElement, icon: string) {
+ return section(container, IMAGE).querySelector<HTMLElement>(`.mind-map-node-image-actions .${icon}`);
+}
+
+/** Hands a picture to the field behind the button, the way picking one from disk does. */
+function chooseImage(container: HTMLElement, file: File) {
+ const input = section(container, IMAGE).querySelector<HTMLInputElement>("input[type=file]");
+ if (!input) throw new Error("the picture row has no field to pick through");
+ Object.defineProperty(input, "files", { value: [ file ], configurable: true });
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+}
+
function sizeButtons(container: HTMLElement) {
return Array.from(section(container, SIZE).querySelectorAll<HTMLElement>(".btn"));
}
@@ -163,7 +197,7 @@ describe("MindMapNodePanel", () => {
const nodes = [buildNode()];
const { mind } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
for (const index of [TEXT, BACKGROUND, BRANCH]) {
// A row is the presets plus the clear and custom cells; more would wrap in the panel.
@@ -177,7 +211,7 @@ describe("MindMapNodePanel", () => {
const nodes = [buildNode({ id: "a" }), buildNode({ id: "b" })];
const { mind, reshapeNode } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
expect(sizeButtons(container)).toHaveLength(4);
expect(activeSize(container)).toBe(1);
@@ -197,11 +231,11 @@ describe("MindMapNodePanel", () => {
it("shows the size the selection already carries, and none when the nodes disagree", () => {
const large = { style: { fontSize: "24px" } };
const { mind } = buildMind([buildNode(large)]);
- expect(activeSize(renderInto(<MindMapNodePanel mind={mind} nodes={[buildNode(large)]} />))).toBe(2);
+ expect(activeSize(renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={[buildNode(large)]} />))).toBe(2);
const mixed = [buildNode({ id: "a", ...large }), buildNode({ id: "b", style: { fontSize: "32px" } })];
const mixedMind = buildMind(mixed);
- expect(activeSize(renderInto(<MindMapNodePanel mind={mixedMind.mind} nodes={mixed} />))).toBe(-1);
+ expect(activeSize(renderInto(<MindMapNodePanel mind={mixedMind.mind} noteId="mapNote" nodes={mixed} />))).toBe(-1);
});
it("shows the colors the selection already carries", () => {
@@ -211,7 +245,7 @@ describe("MindMapNodePanel", () => {
})];
const { mind } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
const selectedIn = (index: number) => presetCells(section(container, index))
.findIndex((cell) => cell.classList.contains("selected"));
@@ -228,7 +262,7 @@ describe("MindMapNodePanel", () => {
];
const { mind } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
const textCells = Array.from(section(container, TEXT).querySelectorAll(".color-cell"));
expect(textCells.some((cell) => cell.classList.contains("selected"))).toBe(false);
@@ -241,7 +275,7 @@ describe("MindMapNodePanel", () => {
const nodes = [buildNode({ id: "a" }), buildNode({ id: "b" })];
const { mind, reshapeNode } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
presetCells(section(container, TEXT))[3].click();
expect(reshapeNode).toHaveBeenCalledTimes(2);
@@ -264,12 +298,12 @@ describe("MindMapNodePanel", () => {
it("shows every icon the selection wears, and a button for one more", () => {
const nodes = [buildNode({ icons: ["bx bx-star", "bx bx-cube"] })];
- const container = renderInto(<MindMapNodePanel mind={buildMind(nodes).mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={buildMind(nodes).mind} noteId="mapNote" nodes={nodes} />);
// The icons themselves, then the button adding another.
expect(iconFaces(container)).toEqual(["bx bx-star", "bx bx-cube", "bx bx-plus"]);
// A node wearing none is the adding button alone, which is invitation enough.
- expect(iconFaces(renderInto(<MindMapNodePanel mind={buildMind([buildNode()]).mind} nodes={[buildNode()]} />)))
+ expect(iconFaces(renderInto(<MindMapNodePanel mind={buildMind([buildNode()]).mind} noteId="mapNote" nodes={[buildNode()]} />)))
.toEqual(["bx bx-plus"]);
});
@@ -279,17 +313,97 @@ describe("MindMapNodePanel", () => {
buildNode({ id: "b", icons: ["bx bx-cube"] })
];
- const container = renderInto(<MindMapNodePanel mind={buildMind(nodes).mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={buildMind(nodes).mind} noteId="mapNote" nodes={nodes} />);
// Everything they carry, and no way to add: a pick could only overwrite what each has.
expect(iconFaces(container)).toEqual(["bx bx-star", "bx bx-cube"]);
expect(iconButtons(container).every((button) => button.disabled)).toBe(true);
});
+ it("shows the picture the selection carries and what can be done with it, nothing more", () => {
+ const nodes = [buildNode({ image: { url: "api/attachments/att1/image/a.png", width: 240, height: 180 } })];
+
+ const container = renderInto(<MindMapNodePanel mind={buildMind(nodes).mind} noteId="mapNote" nodes={nodes} />);
+
+ expect(imagePreview(container)?.getAttribute("src")).toBe("api/attachments/att1/image/a.png");
+ expect(activeImageWidth(container)).toBe(1);
+ expect(imageAction(container, "bx-trash")).toBeTruthy();
+
+ // A node carrying none offers to take one in, and nothing else: there is no size to set and
+ // nothing to remove.
+ const empty = renderInto(<MindMapNodePanel mind={buildMind([buildNode()]).mind} noteId="mapNote" nodes={[buildNode()]} />);
+ expect(imagePreview(empty)).toBeNull();
+ expect(imageWidthButtons(empty)).toHaveLength(0);
+ expect(imageAction(empty, "bx-trash")).toBeNull();
+ expect(imageAction(empty, "bx-image-add")).toBeTruthy();
+ });
+
+ it("draws every selected node at the width it is asked for, each keeping its own proportions", () => {
+ const nodes = [
+ buildNode({ id: "a", image: { url: "a.png", width: 240, height: 180 } }),
+ buildNode({ id: "b", image: { url: "b.png", width: 240, height: 480 } })
+ ];
+ const { mind, reshapeNode } = buildMind(nodes);
+
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
+
+ imageWidthButtons(container)[2].click();
+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { image: { url: "a.png", width: 400, height: 300 } });
+ expect(reshapeNode).toHaveBeenNthCalledWith(2, mind.currentNodes[1], { image: { url: "b.png", width: 400, height: 800 } });
+
+ // Removing takes the picture off every selected node.
+ reshapeNode.mockClear();
+ imageAction(container, "bx-trash")?.click();
+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { image: undefined });
+ expect(reshapeNode).toHaveBeenNthCalledWith(2, mind.currentNodes[1], { image: undefined });
+ });
+
+ it("says as much where the selection carries different pictures", () => {
+ const nodes = [
+ buildNode({ id: "a", image: { url: "a.png", width: 240, height: 180 } }),
+ buildNode({ id: "b", image: { url: "b.png", width: 120, height: 90 } })
+ ];
+
+ const container = renderInto(<MindMapNodePanel mind={buildMind(nodes).mind} noteId="mapNote" nodes={nodes} />);
+
+ expect(imagePreview(container)).toBeNull();
+ expect(section(container, IMAGE).querySelector(".mind-map-node-image-mixed")).toBeTruthy();
+ // Neither the picture nor the width can be shown, but both can still be set for all of them.
+ expect(activeImageWidth(container)).toBe(-1);
+ expect(imageAction(container, "bx-trash")).toBeTruthy();
+ });
+
+ it("stores a chosen picture on the note and gives it to every selected node", async () => {
+ const image = { url: "api/attachments/att9/image/photo.png", width: 240, height: 160 };
+ vi.mocked(uploadNodeImage).mockResolvedValue(image);
+ const nodes = [buildNode({ id: "a" }), buildNode({ id: "b" })];
+ const { mind, reshapeNode } = buildMind(nodes);
+
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
+ chooseImage(container, new File([""], "photo.png", { type: "image/png" }));
+
+ await vi.waitFor(() => expect(reshapeNode).toHaveBeenCalledTimes(2));
+ expect(uploadNodeImage).toHaveBeenCalledWith("mapNote", expect.objectContaining({ name: "photo.png" }));
+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { image });
+ expect(reshapeNode).toHaveBeenNthCalledWith(2, mind.currentNodes[1], { image });
+ });
+
+ it("leaves the selection as it was when a picture cannot be stored", async () => {
+ vi.mocked(uploadNodeImage).mockResolvedValue(null);
+ const nodes = [buildNode()];
+ const { mind, reshapeNode } = buildMind(nodes);
+
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
+ chooseImage(container, new File([""], "photo.png", { type: "image/png" }));
+
+ await vi.waitFor(() => expect(uploadNodeImage).toHaveBeenCalled());
+ expect(reshapeNode).not.toHaveBeenCalled();
+ });
+
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} />)
+ renderInto(<MindMapNodePanel mind={buildMind(nodes).mind} noteId="mapNote" 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.
@@ -314,7 +428,7 @@ describe("MindMapNodePanel", () => {
const nodes = [buildNode({ tags: [styled, "later"] })];
const { mind, reshapeNode } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
expect(tagTexts(container)).toEqual(["urgent", "later"]);
@@ -332,7 +446,7 @@ describe("MindMapNodePanel", () => {
];
const { mind, reshapeNode } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
expect(tagTexts(container)).toEqual(["urgent"]);
expect(container.querySelector<HTMLInputElement>(".tn-field input")?.disabled).toBe(false);
@@ -350,7 +464,7 @@ describe("MindMapNodePanel", () => {
];
const { mind, reshapeNode } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
expect(tagTexts(container)).toEqual(["one", "shared", "two"]);
expect(container.querySelector<HTMLInputElement>(".tn-field input")?.disabled).toBe(true);
@@ -365,7 +479,7 @@ describe("MindMapNodePanel", () => {
const nodes = [buildNode()];
const { mind } = buildMind(nodes);
- const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
const panel = container.querySelector(".mind-map-node-panel");
for (const event of [
diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx
index 39c3e1cc89..1ea7fc6ae2 100644
--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx
+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx
@@ -9,8 +9,10 @@ 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 ColorPicker, { DEFAULT_COLOR_PALETTE } from "../react/ColorPicker";
import Dropdown from "../react/Dropdown";
+import { FormFileUploadActionButton } from "../react/FormFileUpload";
import { FormListItem } from "../react/FormList";
import { useNote, useNoteIcon, useNoteTitle } from "../react/hooks";
import Icon from "../react/Icon";
@@ -18,6 +20,7 @@ import IconPicker from "../react/IconPicker";
import NoteAutocomplete from "../react/NoteAutocomplete";
import { refToJQuerySelector } from "../react/react_utils";
import SegmentedChoice from "../react/SegmentedChoice";
+import { fitNodeImage, nearestNodeImageWidth, NODE_IMAGE_WIDTHS, uploadNodeImage } from "./helpers/mind_map_images";
import { describeExternalLink, getLinkedNotePath, linkFromSuggestion } from "./helpers/mind_map_links";
/**
@@ -35,6 +38,8 @@ export const NODE_BACKGROUND_COLORS = NODE_COLORS.map((color) => `${color}40`);
interface MindMapNodePanelProps {
mind: MindElixirInstance;
+ /** The note the map belongs to, which is where a picture put on a node is stored. */
+ noteId: string;
/** The currently selected nodes; the panel edits all of them at once. */
nodes: NodeObj[];
}
@@ -43,12 +48,14 @@ interface MindMapNodePanelProps {
* Floating panel displayed over a mind map while at least one node is selected, holding the
* formatting controls for the selection.
*/
-export default function MindMapNodePanel({ mind, nodes }: MindMapNodePanelProps) {
+export default function MindMapNodePanel({ mind, noteId, nodes }: MindMapNodePanelProps) {
const fontSize = getCommonValue(nodes, (node) => node.style?.fontSize);
const textColor = getCommonValue(nodes, (node) => node.style?.color);
const backgroundColor = getCommonValue(nodes, (node) => node.style?.background);
const branchColor = getCommonValue(nodes, (node) => node.branchColor);
const icons = gatherListValues(nodes, (node) => node.icons ?? []);
+ const image = getCommonValue(nodes, (node) => node.image?.url);
+ const imageWidth = getCommonValue(nodes, (node) => node.image && String(node.image.width));
const link = getCommonValue(nodes, (node) => node.hyperLink);
const tags = gatherTags(nodes);
@@ -63,6 +70,14 @@ export default function MindMapNodePanel({ mind, nodes }: MindMapNodePanelProps)
}
}
+ /** 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);
+ if (image) {
+ patchSelectedNodes({ image });
+ }
+ }
+
return (
<div
className="mind-map-node-panel"
@@ -115,6 +130,26 @@ export default function MindMapNodePanel({ mind, nodes }: MindMapNodePanelProps)
/>
</PanelSection>
+ <PanelSection
+ label={t("mind-map.image")}
+ title={image === MIXED ? t("mind-map.images-differ") : undefined}
+ >
+ <NodeImage
+ url={image !== MIXED ? image : null}
+ indeterminate={image === MIXED}
+ width={imageWidth !== MIXED && imageWidth ? Number(imageWidth) : null}
+ // A node carries one picture, so what is taken in takes the place of what was
+ // there, at the size it comes in at.
+ onPick={(file) => void takeInImage(file)}
+ // Derived per node: the nodes are set to the same width, but each keeps the
+ // proportions of the picture it carries.
+ onResize={(width) => patchSelectedNodes((node) => ({
+ image: node.image && fitNodeImage(node.image, width)
+ }))}
+ onRemove={() => patchSelectedNodes({ image: undefined })}
+ />
+ </PanelSection>
+
<PanelSection
label={t("mind-map.node-link")}
title={link === MIXED ? t("mind-map.links-differ") : undefined}
@@ -327,6 +362,69 @@ function NodeIcon({ face, title, disabled, onSelect, onRemove }: {
);
}
+/**
+ * The picture a node carries: what it looks like, how large it is drawn, and the way to another one
+ * or to none at all.
+ *
+ * A node holds one picture, so the button offering one stands alone until there is a picture to
+ * show, and turns into the way to replace it once there is — the same shape the icons row takes.
+ */
+function NodeImage({ url, indeterminate, width, onPick, onResize, onRemove }: {
+ url: string | null;
+ /** The selected nodes carry different pictures, so none of them can be shown. */
+ indeterminate: boolean;
+ /** The width they are drawn at, or `null` where the nodes disagree on one. */
+ width: number | null;
+ onPick(file: File): void;
+ onResize(width: number): void;
+ onRemove(): void;
+}) {
+ const hasImage = !!url || indeterminate;
+
+ return (
+ <div className="mind-map-node-image">
+ {indeterminate
+ ? <div className="mind-map-node-image-mixed">{t("mind-map.image-mixed")}</div>
+ : url && <img className="mind-map-node-image-preview" src={url} alt="" />}
+
+ <div className="mind-map-node-image-actions">
+ {hasImage && (
+ <SegmentedChoice
+ options={buildImageWidthOptions()}
+ // Nothing is highlighted where the nodes are drawn at different widths, or
+ // where a map made elsewhere carries a width of its own.
+ currentValue={width !== null ? String(nearestNodeImageWidth(width)) : ""}
+ onChange={(width) => onResize(Number(width))}
+ />
+ )}
+
+ <FormFileUploadActionButton
+ icon={hasImage ? "bx bx-repost" : "bx bx-image-add"}
+ text={hasImage ? t("mind-map.change-image") : t("mind-map.add-image")}
+ onChange={(files) => {
+ const file = files?.[0];
+ if (file) onPick(file);
+ }}
+ />
+
+ {hasImage && (
+ <ActionButton
+ icon="bx bx-trash"
+ text={t("mind-map.remove-image")}
+ onClick={onRemove}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** The widths a picture is drawn at, under the same labels the text sizes wear. */
+function buildImageWidthOptions() {
+ const labels = [ t("mind-map.font-size-small"), t("mind-map.font-size-medium"), t("mind-map.font-size-large") ];
+ return NODE_IMAGE_WIDTHS.map((width, index) => ({ value: String(width), label: labels[index] }));
+}
+
/** Kept still, so that the autocomplete is not built anew every time the panel renders. */
const LINK_AUTOCOMPLETE_OPTIONS = { allowExternalLinks: true };
diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_export.spec.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.spec.ts
index 7001b637a1..316b487b93 100644
--- a/apps/client/src/widgets/type_widgets/helpers/mind_map_export.spec.ts
+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.spec.ts
@@ -3,9 +3,9 @@
// breaks (NodeIterator mishandling — see sanitize_content.spec.ts). jsdom matches
// real-browser behavior.
import MindElixir, { type MindElixirData, type MindElixirInstance } from "mind-elixir";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
-import { postProcessExportedSvg, renderMindMapPreviewSvg } from "./mind_map_export";
+import { inlineExportedImages, postProcessExportedSvg, renderMindMapPreviewSvg } from "./mind_map_export";
// mind-elixir touches these browser APIs at construction time; jsdom lacks them.
window.matchMedia = window.matchMedia ?? ((query: string) => ({
@@ -134,6 +134,48 @@ describe("postProcessExportedSvg", () => {
});
});
+describe("inlineExportedImages", () => {
+ /** An export holding the pictures of three nodes, one of them already carried inside it. */
+ function buildExportWithImages() {
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="400px" height="300px">` +
+ `<svg x="100" y="100" overflow="visible">` +
+ `<image x="0" y="0" width="240px" height="180px" href="api/attachments/att1/image/a.png"/>` +
+ `<image x="0" y="0" width="120px" height="90px" href="https://elsewhere.example/b.png"/>` +
+ `<image x="0" y="0" width="60px" height="45px" href="data:image/webp;base64,already"/>` +
+ `</svg></svg>`;
+ }
+
+ function imageHrefs(svgText: string) {
+ const doc = new DOMParser().parseFromString(svgText, "image/svg+xml");
+ return Array.from(doc.querySelectorAll("image")).map((image) => image.getAttribute("href"));
+ }
+
+ it("carries in every picture it can load, at the width it is drawn at", async () => {
+ // The picture of another site cannot be read back, and one already carried is not fetched.
+ const load = vi.fn(async (url: string) => (url.startsWith("api/") ? "data:image/webp;base64,carried" : null));
+
+ const result = await inlineExportedImages(buildExportWithImages(), load);
+
+ expect(imageHrefs(result)).toEqual([
+ "data:image/webp;base64,carried",
+ "https://elsewhere.example/b.png",
+ "data:image/webp;base64,already"
+ ]);
+ expect(load.mock.calls).toEqual([
+ [ "api/attachments/att1/image/a.png", 240 ],
+ [ "https://elsewhere.example/b.png", 120 ]
+ ]);
+ });
+
+ it("hands back what it was given when there is nothing to carry in", async () => {
+ const load = vi.fn(async () => "data:image/webp;base64,carried");
+ const svgText = buildExportedSvg();
+
+ expect(await inlineExportedImages(svgText, load)).toBe(svgText);
+ expect(load).not.toHaveBeenCalled();
+ });
+});
+
describe("renderMindMapPreviewSvg", () => {
it("exports the map and injects the labels", async () => {
const mind = buildMind({ labels: [ "arrow label" ] });
diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts
index 7366737cf4..b2588ce8db 100644
--- a/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts
+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts
@@ -1,6 +1,7 @@
import type { MindElixirInstance } from "mind-elixir";
import { sanitizeNoteContentHtml } from "../../../services/sanitize_content";
+import { loadImageData } from "./mind_map_images";
const SVG_NS = "http://www.w3.org/2000/svg";
const XHTML_NS = "http://www.w3.org/1999/xhtml";
@@ -28,9 +29,54 @@ const XHTML_NS = "http://www.w3.org/1999/xhtml";
*/
export async function renderMindMapPreviewSvg(mind: MindElixirInstance): Promise<string> {
const svgText = await mind.exportSvg().text();
- return postProcessExportedSvg(mind, svgText);
+ return inlineExportedImages(postProcessExportedSvg(mind, svgText));
}
+/**
+ * Carries the pictures of the nodes into the SVG itself, as data of their own.
+ *
+ * The exporter points each of them at the address it was drawn from, and that address is of no use
+ * to whoever ends up holding the SVG: it is read as a picture — on a share page, in an included
+ * note, as the note's own image — and a picture drawn by the browser is not allowed to fetch
+ * anything from anywhere, whatever it points at. The same is true of the rasterizer the PNG export
+ * runs through, which would additionally be barred from reading back a canvas it had tainted.
+ *
+ * Each picture is redrawn to about the size it is shown at rather than carried at its full weight,
+ * since the SVG is written afresh on every save: a photograph on a node would otherwise be paid for,
+ * a third over again for being written as text, at every pause in the editing.
+ *
+ * @param svgText the exported SVG.
+ * @param load how a picture is fetched and redrawn; the caller's own in the tests.
+ * @returns the SVG with every picture it could take in carried inside it. One it could not — a map
+ * made elsewhere pointing at another site, a picture no longer there — is left pointing
+ * where it did, which is no worse than it was.
+ */
+export async function inlineExportedImages(svgText: string, load: ImageLoader = loadImageData): Promise<string> {
+ const doc = new DOMParser().parseFromString(svgText, "image/svg+xml");
+ const images = Array.from(doc.querySelectorAll("image"));
+
+ const loaded = await Promise.all(images.map((image) => {
+ const href = image.getAttribute("href") ?? "";
+ if (!href || href.startsWith("data:")) {
+ return null;
+ }
+ return load(href, Number.parseFloat(image.getAttribute("width") ?? "") || 0);
+ }));
+
+ let inlined = false;
+ for (const [ index, data ] of loaded.entries()) {
+ if (data) {
+ images[index].setAttribute("href", data);
+ inlined = true;
+ }
+ }
+
+ return inlined ? new XMLSerializer().serializeToString(doc) : svgText;
+}
+
+/** Fetches a picture and redraws it, given the width it is shown at. See {@link inlineExportedImages}. */
+export type ImageLoader = (url: string, displayWidth: number) => Promise<string | null>;
+
// The exporter emits exact-fit foreignObject boxes: the text's measured width in the
// page's font, to the third decimal, with `white-space: pre-wrap`. Any context that
// resolves fonts even fractionally wider — PNG rasterization at scale, an <img> on a
diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_images.spec.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_images.spec.ts
new file mode 100644
index 0000000000..61dfa2db6a
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_images.spec.ts
@@ -0,0 +1,136 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import server from "../../../services/server";
+import toast from "../../../services/toast";
+import { DEFAULT_NODE_IMAGE_WIDTH, fitNodeImage, loadImageData, measureImage, nearestNodeImageWidth, NODE_IMAGE_WIDTHS, uploadNodeImage } from "./mind_map_images";
+
+vi.mock("../../../services/server", () => ({ default: { upload: vi.fn() } }));
+vi.mock("../../../services/toast", () => ({ default: { showError: vi.fn() } }));
+
+/**
+ * Stands in for the browser's decoder, which no test environment carries: whatever is handed over
+ * is a picture of the given size, or not a picture at all.
+ */
+function stubDecoder(size: { width: number, height: number } | null) {
+ vi.stubGlobal("Image", class {
+
+ naturalWidth = size?.width ?? 0;
+ naturalHeight = size?.height ?? 0;
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+
+ set src(_value: string) {
+ queueMicrotask(() => (size ? this.onload?.() : this.onerror?.()));
+ }
+
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:picture");
+ vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
+ stubDecoder({ width: 800, height: 600 });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe("fitNodeImage", () => {
+ it("draws a picture at the width it is given, keeping its proportions", () => {
+ const image = { url: "a.png", width: 800, height: 600 };
+
+ expect(fitNodeImage(image, 240)).toEqual({ url: "a.png", width: 240, height: 180 });
+ // Whatever else the picture carries is kept, and a fractional height is rounded to a pixel.
+ expect(fitNodeImage({ ...image, height: 601, fit: "cover" }, 240))
+ .toEqual({ url: "a.png", width: 240, height: 180, fit: "cover" });
+ // A picture of no width at all — one a map made elsewhere may carry — is drawn square
+ // rather than not at all.
+ expect(fitNodeImage({ url: "a.png", width: 0, height: 0 }, 240))
+ .toEqual({ url: "a.png", width: 240, height: 240 });
+ });
+});
+
+describe("nearestNodeImageWidth", () => {
+ it("reads a width as the offered one it is closest to", () => {
+ for (const width of NODE_IMAGE_WIDTHS) {
+ expect(nearestNodeImageWidth(width)).toBe(width);
+ }
+ expect(nearestNodeImageWidth(60)).toBe(NODE_IMAGE_WIDTHS[0]);
+ expect(nearestNodeImageWidth(200)).toBe(NODE_IMAGE_WIDTHS[1]);
+ expect(nearestNodeImageWidth(4000)).toBe(NODE_IMAGE_WIDTHS[2]);
+ });
+});
+
+describe("uploadNodeImage", () => {
+ const file = new File([ "" ], "photo.png", { type: "image/png" });
+
+ it("stores the picture on the note and hands it back at a size a node can wear", async () => {
+ vi.mocked(server.upload).mockResolvedValue({ uploaded: true, url: "api/attachments/att1/image/photo.png" });
+
+ expect(await uploadNodeImage("mapNote", file)).toEqual({
+ url: "api/attachments/att1/image/photo.png",
+ width: DEFAULT_NODE_IMAGE_WIDTH,
+ height: DEFAULT_NODE_IMAGE_WIDTH * 600 / 800
+ });
+ expect(server.upload).toHaveBeenCalledWith("notes/mapNote/attachments/upload", file, undefined, "POST");
+ });
+
+ it("never draws a picture larger than it came", async () => {
+ stubDecoder({ width: 64, height: 32 });
+ vi.mocked(server.upload).mockResolvedValue({ uploaded: true, url: "api/attachments/att1/image/photo.png" });
+
+ expect(await uploadNodeImage("mapNote", file)).toMatchObject({ width: 64, height: 32 });
+ });
+
+ it("says what went wrong when the note will not take it, and gives the node nothing", async () => {
+ vi.mocked(server.upload).mockResolvedValue({ uploaded: false, message: "Too large." });
+ expect(await uploadNodeImage("mapNote", file)).toBeNull();
+ expect(vi.mocked(toast.showError).mock.calls[0][0]).toContain("Too large.");
+
+ vi.mocked(server.upload).mockRejectedValue(new Error("Offline."));
+ expect(await uploadNodeImage("mapNote", file)).toBeNull();
+ expect(vi.mocked(toast.showError).mock.calls[1][0]).toContain("Offline.");
+
+ // A file that is no picture is refused as well, whatever the note made of it.
+ stubDecoder(null);
+ vi.mocked(server.upload).mockResolvedValue({ uploaded: true, url: "api/attachments/att1/image/photo.png" });
+ expect(await uploadNodeImage("mapNote", file)).toBeNull();
+ });
+});
+
+describe("measureImage", () => {
+ it("reads the size a picture comes in, and nothing for what is not one", async () => {
+ expect(await measureImage(new Blob())).toEqual({ width: 800, height: 600 });
+
+ stubDecoder(null);
+ expect(await measureImage(new Blob())).toBeNull();
+ });
+});
+
+describe("loadImageData", () => {
+ it("fetches a picture once and carries it as data", async () => {
+ const fetchPicture = vi.fn(async () => new Response(new Blob([ "bytes" ], { type: "image/png" })));
+ vi.stubGlobal("fetch", fetchPicture);
+
+ const data = await loadImageData("api/attachments/att1/image/a.png", 240);
+ expect(data).toMatch(/^data:/);
+
+ // Asked for again at the same size, it is the one already fetched: the SVG holding it is
+ // written again at every pause in the editing.
+ expect(await loadImageData("api/attachments/att1/image/a.png", 240)).toBe(data);
+ expect(fetchPicture).toHaveBeenCalledTimes(1);
+ });
+
+ it("hands back nothing for a picture that cannot be fetched", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 404 })));
+ expect(await loadImageData("api/attachments/gone/image/a.png", 240)).toBeNull();
+
+ vi.stubGlobal("fetch", vi.fn(async () => {
+ throw new Error("Refused.");
+ }));
+ expect(await loadImageData("https://elsewhere.example/a.png", 240)).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_images.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_images.ts
new file mode 100644
index 0000000000..d14c8b5001
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_images.ts
@@ -0,0 +1,215 @@
+import type { NodeObj } from "mind-elixir";
+
+import { t } from "../../../services/i18n";
+import server from "../../../services/server";
+import toast from "../../../services/toast";
+
+/** The picture a node carries, as Mind Elixir holds it. */
+export type NodeImage = NonNullable<NodeObj["image"]>;
+
+/**
+ * The widths a node picture is offered at, in the order the panel lays them out. A picture is drawn
+ * at the size it is given rather than at the size it came in, so these are the whole of the choice:
+ * a map is read at a glance, and a picture large enough to be read at that glance while still
+ * leaving room for the branches around it lands well inside this range.
+ */
+export const NODE_IMAGE_WIDTHS = [ 120, 240, 400 ];
+
+/** What a picture is taken in at, unless it is smaller than that to begin with (see below). */
+export const DEFAULT_NODE_IMAGE_WIDTH = NODE_IMAGE_WIDTHS[1];
+
+/**
+ * Uploads a picture to the note the map belongs to and describes it as a node carries it.
+ *
+ * The picture is stored as an attachment of the note, the way every other note type stores the
+ * pictures written into it, and the node holds the address it is served back from — so the map's
+ * own content stays the small piece of JSON it is however many pictures it grows.
+ *
+ * @returns what to hand to a node, or `null` if the picture could not be taken in — a message
+ * having been shown for it, as it is the whole of what the caller asked for.
+ */
+export async function uploadNodeImage(noteId: string, file: File): Promise<NodeImage | null> {
+ const [ url, size ] = await Promise.all([ uploadImage(noteId, file), measureImage(file) ]);
+ if (!url || !size) {
+ // A file the browser will not read as a picture may have been stored all the same; nothing
+ // points at it, so the next save takes it as an orphan and schedules its erasure.
+ return null;
+ }
+
+ // Never larger than it came: a picture drawn past its own size is a blurred one, and the sizes
+ // below are there for whoever does want it larger than it is.
+ return fitNodeImage({ url, ...size }, Math.min(DEFAULT_NODE_IMAGE_WIDTH, size.width));
+}
+
+/** The address a picture is served back from once the note holds it, or `null` with a message shown. */
+async function uploadImage(noteId: string, file: File): Promise<string | null> {
+ let detail: string | undefined;
+
+ try {
+ const result = await server.upload(
+ `notes/${noteId}/attachments/upload`,
+ file, undefined, "POST"
+ ) as { uploaded?: boolean; url?: string; message?: string };
+
+ if (result?.uploaded && result.url) {
+ return result.url;
+ }
+ detail = result?.message;
+ } catch (e) {
+ detail = e instanceof Error ? e.message : undefined;
+ }
+
+ const message = t("mind-map.image-upload-failed", { name: file.name });
+ toast.showError(detail ? `${message} ${detail}` : message);
+ return null;
+}
+
+/**
+ * The size a picture comes in, or `null` if it cannot be read as a picture at all.
+ */
+export async function measureImage(file: Blob): Promise<{ width: number, height: number } | null> {
+ const image = await decodeImage(file);
+ if (!image?.naturalWidth || !image.naturalHeight) {
+ return null;
+ }
+ return { width: image.naturalWidth, height: image.naturalHeight };
+}
+
+/**
+ * A picture of the map, fetched from where a node points at it and redrawn at about the size it is
+ * shown at, as data that can be carried inside the exported SVG (see `mind_map_export`).
+ *
+ * What has been fetched once is kept: the SVG is written again at every pause in the editing, and
+ * an address names one picture for good — a picture put in the place of another is stored anew and
+ * gets an address of its own.
+ *
+ * @returns the picture as a `data:` URL, or `null` where it could not be fetched at all — a map
+ * made elsewhere may point at a site that will not hand it over.
+ */
+export function loadImageData(url: string, displayWidth: number): Promise<string | null> {
+ const width = Math.max(1, Math.round(displayWidth * IMAGE_EXPORT_SCALE));
+ const key = `${width}|${url}`;
+
+ let data = pictureData.get(key);
+ if (!data) {
+ data = fetchImageData(url, width);
+ pictureData.set(key, data);
+ }
+ return data;
+}
+
+/**
+ * How much larger than it is shown a picture is redrawn, so that it stays sharp on a dense display
+ * and in a PNG export, which rasterizes the SVG at a scale of its own.
+ */
+const IMAGE_EXPORT_SCALE = 2;
+
+/**
+ * What a redrawn picture is written as. WebP holds transparency, as PNG does, at a fraction of the
+ * weight; a browser that cannot write it falls back to PNG on its own.
+ */
+const IMAGE_EXPORT_TYPE = "image/webp";
+const IMAGE_EXPORT_QUALITY = 0.8;
+
+/** What has already been fetched, by address and by the width it was redrawn at. */
+const pictureData = new Map<string, Promise<string | null>>();
+
+async function fetchImageData(url: string, width: number): Promise<string | null> {
+ try {
+ const response = await fetch(url);
+ if (!response.ok) {
+ return null;
+ }
+
+ const blob = await response.blob();
+ // Where the browser will not redraw it, it is carried as it came: heavier, but there.
+ return await redrawImage(blob, width) ?? await readAsDataUrl(blob);
+ } catch (e) {
+ console.warn(`Could not read the picture at '${url}'`, e);
+ return null;
+ }
+}
+
+/** The picture redrawn at no more than the given width, or `null` if the browser would not draw it. */
+async function redrawImage(blob: Blob, width: number): Promise<string | null> {
+ const image = await decodeImage(blob);
+ if (!image?.naturalWidth || !image.naturalHeight) {
+ return null;
+ }
+
+ // Never larger than it came: that would cost more and show no more.
+ const drawnWidth = Math.min(width, image.naturalWidth);
+ const drawnHeight = Math.max(1, Math.round(drawnWidth * image.naturalHeight / image.naturalWidth));
+
+ try {
+ const canvas = document.createElement("canvas");
+ canvas.width = drawnWidth;
+ canvas.height = drawnHeight;
+
+ const context = canvas.getContext("2d");
+ if (!context) {
+ return null;
+ }
+ context.drawImage(image, 0, 0, drawnWidth, drawnHeight);
+
+ // A picture fetched from another site taints the canvas, and reading it back is refused.
+ return canvas.toDataURL(IMAGE_EXPORT_TYPE, IMAGE_EXPORT_QUALITY);
+ } catch (e) {
+ console.warn("Could not redraw a picture of the map", e);
+ return null;
+ }
+}
+
+/**
+ * Hands the picture to the browser to decode, `null` where it will not have it. Decoded through an
+ * `<img>` rather than through `createImageBitmap`, which several browsers refuse for SVG — a format
+ * a node takes as readily as any other.
+ */
+function decodeImage(blob: Blob): Promise<HTMLImageElement | null> {
+ return new Promise((resolve) => {
+ const url = URL.createObjectURL(blob);
+ const image = new Image();
+
+ const settle = (decoded: HTMLImageElement | null) => {
+ URL.revokeObjectURL(url);
+ resolve(decoded);
+ };
+
+ image.onload = () => settle(image);
+ image.onerror = () => settle(null);
+ image.src = url;
+ });
+}
+
+function readAsDataUrl(blob: Blob): Promise<string | null> {
+ return new Promise((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(typeof reader.result === "string" ? reader.result : null);
+ reader.onerror = () => resolve(null);
+ reader.readAsDataURL(blob);
+ });
+}
+
+/**
+ * The same picture drawn at the given width, as tall as its proportions ask for. A node holds the
+ * size it is drawn at rather than a scale, so every change of size goes through here.
+ */
+export function fitNodeImage(image: NodeImage, width: number): NodeImage {
+ const ratio = (image.width > 0 ? image.height / image.width : 1);
+ return {
+ ...image,
+ width: Math.max(1, Math.round(width)),
+ height: Math.max(1, Math.round(width * ratio))
+ };
+}
+
+/**
+ * The offered width a picture is closest to, which is the one the panel shows as its size. A picture
+ * is taken in at its own width where that is smaller than any of them (see {@link uploadNodeImage}),
+ * and a map made elsewhere carries whatever width it was made with, so what a node holds is not
+ * always one of them.
+ */
+export function nearestNodeImageWidth(width: number): number {
+ return NODE_IMAGE_WIDTHS.reduce((nearest, offered) =>
+ (Math.abs(offered - width) < Math.abs(nearest - width) ? offered : nearest));
+}