Skip to content

Build your personal knowledge base with Trilium Notes

feat(mind-map): let a node's picture be cut to a shape

Elian Doran7b6a8c08a13a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index c3a2a88dda..1229f1bcda 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3540,6 +3540,9 @@
"add-image": "Add an image",
"change-image": "Replace the image",
"remove-image": "Remove the image",
+ "image-shape-original": "Original",
+ "image-shape-square": "Square",
+ "image-shape-wide": "Wide",
"images-differ": "The selected nodes don't carry the same image. To replace the images anyway, remove them first.",
"image-upload-failed": "Cannot upload image \"{{name}}\".",
"node-link": "Link",
diff --git a/apps/client/src/widgets/react/SegmentedChoice.tsx b/apps/client/src/widgets/react/SegmentedChoice.tsx
index ea3adec395..dcbbc79a01 100644
--- a/apps/client/src/widgets/react/SegmentedChoice.tsx
+++ b/apps/client/src/widgets/react/SegmentedChoice.tsx
@@ -2,8 +2,18 @@ import clsx from "clsx";
import Button, { ButtonGroup } from "./Button";
+interface SegmentedChoiceOption<T extends string> {
+ value: T;
+ /** Left out where the option is shown as an icon alone, which then wants a {@link title}. */
+ label?: string;
+ /** An icon class without its `bx` prefix, e.g. `bx-square`. */
+ icon?: string;
+ /** What the option is called, for an option that shows as an icon alone. */
+ title?: string;
+}
+
interface SegmentedChoiceProps<T extends string> {
- options: { value: T, label: string }[];
+ options: SegmentedChoiceOption<T>[];
/**
* Kept a plain string rather than {@link T}: callers routinely hold the value as a raw option
* string, and a value outside the options simply highlights nothing.
@@ -20,10 +30,12 @@ interface SegmentedChoiceProps<T extends string> {
export default function SegmentedChoice<T extends string>({ options, currentValue, onChange, className }: SegmentedChoiceProps<T>) {
return (
<ButtonGroup size="sm" className={className}>
- {options.map(({ value, label }) => (
+ {options.map(({ value, label, icon, title }) => (
<Button
key={value}
- text={label}
+ text={label ?? ""}
+ icon={icon}
+ title={title}
size="small"
className={clsx(currentValue === value && "active")}
onClick={() => onChange(value)}
diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css b/apps/client/src/widgets/type_widgets/MindMapNodePanel.css
index 8e18d42f10..2d399dbfd9 100644
--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css
+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.css
@@ -51,7 +51,14 @@
}
}
+/* What is done with the picture stands on one line, the shapes it is cut to on the next. */
.mind-map-node-panel .mind-map-node-image {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.mind-map-node-panel .mind-map-node-image-actions {
display: flex;
align-items: center;
gap: 4px;
@@ -63,6 +70,22 @@
}
}
+/*
+ * A shape is drawn rather than named, and a drawing asks for no more room than itself: the row is
+ * as wide as the three of them, instead of each taking a third of the panel (see below).
+ *
+ * Written onto the group itself rather than as a descendant of the panel, so that it outweighs the
+ * rule below rather than merely disagreeing with it — that one is written last and would win.
+ */
+.mind-map-node-panel .mind-map-node-image-shapes.btn-group {
+ align-self: start;
+ width: auto;
+
+ .btn {
+ flex: 0 0 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 48ea69a413..04965a9b53 100644
--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx
@@ -68,13 +68,21 @@ function iconFaces(container: HTMLElement) {
}
function imageWidthButtons(container: HTMLElement) {
- return Array.from(section(container, IMAGE).querySelectorAll<HTMLElement>(".btn-group .btn"));
+ return Array.from(section(container, IMAGE).querySelectorAll<HTMLElement>(".mind-map-node-image-actions .btn"));
}
function activeImageWidth(container: HTMLElement) {
return imageWidthButtons(container).findIndex((button) => button.classList.contains("active"));
}
+function imageShapeButtons(container: HTMLElement) {
+ return Array.from(section(container, IMAGE).querySelectorAll<HTMLElement>(".mind-map-node-image-shapes .btn"));
+}
+
+function activeImageShape(container: HTMLElement) {
+ return imageShapeButtons(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<HTMLButtonElement>(`.mind-map-node-image .${icon}`);
@@ -355,6 +363,27 @@ describe("MindMapNodePanel", () => {
expect(reshapeNode).toHaveBeenNthCalledWith(2, mind.currentNodes[1], { image: undefined });
});
+ it("cuts every selected picture to the shape it is asked for, each at the width it is drawn at", async () => {
+ 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 { mind, reshapeNode } = buildMind(nodes);
+
+ const container = renderInto(<MindMapNodePanel mind={mind} noteId="mapNote" nodes={nodes} />);
+
+ // Both carry their own shape, which is the one shown; the widths they disagree on are not.
+ expect(imageShapeButtons(container)).toHaveLength(3);
+ expect(activeImageShape(container)).toBe(0);
+ expect(activeImageWidth(container)).toBe(-1);
+
+ imageShapeButtons(container)[1].click();
+
+ await vi.waitFor(() => expect(reshapeNode).toHaveBeenCalledTimes(2));
+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { image: { url: "a.png", width: 240, height: 240, fit: "cover" } });
+ expect(reshapeNode).toHaveBeenNthCalledWith(2, mind.currentNodes[1], { image: { url: "b.png", width: 120, height: 120, fit: "cover" } });
+ });
+
it("takes no picture in where the selection carries different ones", () => {
const nodes = [
buildNode({ id: "a", image: { url: "a.png", width: 240, height: 180 } }),
diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx
index d4fa874917..b534d4252f 100644
--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx
+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx
@@ -21,7 +21,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 { 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";
/**
@@ -57,6 +57,7 @@ export default function MindMapNodePanel({ mind, noteId, nodes }: MindMapNodePan
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 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);
@@ -79,6 +80,23 @@ export default function MindMapNodePanel({ mind, noteId, nodes }: MindMapNodePan
}
}
+ /**
+ * Draws the picture of every selected node in the given shape. Worked out before any node is
+ * touched — a picture returning to its own shape has to be read again for it, and a patch is
+ * applied as it is handed over.
+ */
+ async function shapeImages(shape: NodeImageShape) {
+ const shaped = new Map<string, NodeImageData>();
+
+ await Promise.all(mind.currentNodes.map(async ({ nodeObj }) => {
+ if (nodeObj.image) {
+ shaped.set(nodeObj.id, await shapeNodeImage(nodeObj.image, shape));
+ }
+ }));
+
+ patchSelectedNodes((node) => ({ image: shaped.get(node.id) ?? node.image }));
+ }
+
return (
<div
className="mind-map-node-panel"
@@ -139,6 +157,8 @@ export default function MindMapNodePanel({ mind, noteId, nodes }: MindMapNodePan
hasImage={!!image}
indeterminate={image === MIXED}
width={imageWidth !== MIXED && imageWidth ? Number(imageWidth) : null}
+ shape={imageShape !== MIXED ? imageShape : null}
+ onShape={(shape) => void shapeImages(shape)}
// 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)}
@@ -371,7 +391,7 @@ function NodeIcon({ face, title, disabled, onSelect, onRemove }: {
* carrying none offers the one button that takes a picture in, and every other is only there once
* there is something for it to act on.
*/
-function NodeImage({ hasImage, indeterminate, width, onPick, onResize, onRemove }: {
+function NodeImage({ hasImage, indeterminate, width, shape, onPick, onResize, onShape, onRemove }: {
/** Whether the selection carries a picture at all, which is what the row offers to do with. */
hasImage: boolean;
/**
@@ -382,37 +402,51 @@ function NodeImage({ hasImage, indeterminate, width, onPick, onResize, onRemove
indeterminate: boolean;
/** The width they are drawn at, or `null` where the nodes disagree on one. */
width: number | null;
+ /** The shape they are drawn in, or `null` where the nodes disagree on one. */
+ shape: NodeImageShape | null;
onPick(file: File): void;
onResize(width: number): void;
+ onShape(shape: NodeImageShape): void;
onRemove(): void;
}) {
return (
<div className="mind-map-node-image">
- {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))}
+ <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")}
+ disabled={indeterminate}
+ onChange={(files) => {
+ const file = files?.[0];
+ if (file) onPick(file);
+ }}
/>
- )}
- <FormFileUploadActionButton
- icon={hasImage ? "bx bx-repost" : "bx bx-image-add"}
- text={hasImage ? t("mind-map.change-image") : t("mind-map.add-image")}
- disabled={indeterminate}
- 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>
{hasImage && (
- <ActionButton
- icon="bx bx-trash"
- text={t("mind-map.remove-image")}
- onClick={onRemove}
+ <SegmentedChoice
+ className="mind-map-node-image-shapes"
+ options={buildImageShapeOptions()}
+ currentValue={shape ?? ""}
+ onChange={onShape}
/>
)}
</div>
@@ -425,6 +459,24 @@ function buildImageWidthOptions() {
return NODE_IMAGE_WIDTHS.map((width, index) => ({ value: String(width), label: labels[index] }));
}
+/**
+ * The shapes a picture is cut to, its own among them — each drawn as the shape it stands for, which
+ * says it more plainly than its name does and leaves the three of them room in a panel this narrow.
+ */
+function buildImageShapeOptions() {
+ const icons: Record<NodeImageShape, string> = {
+ original: "bx-image",
+ square: "bx-square",
+ wide: "bx-rectangle"
+ };
+ const titles: Record<NodeImageShape, string> = {
+ original: t("mind-map.image-shape-original"),
+ square: t("mind-map.image-shape-square"),
+ wide: t("mind-map.image-shape-wide")
+ };
+ return NODE_IMAGE_SHAPES.map((shape) => ({ value: shape, icon: icons[shape], title: titles[shape] }));
+}
+
/** Kept still, so that the autocomplete is not built anew every time the panel renders. */
const LINK_AUTOCOMPLETE_OPTIONS = { allowExternalLinks: true };
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 316b487b93..798289e064 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
@@ -123,6 +123,43 @@ describe("postProcessExportedSvg", () => {
}
});
+ it("tells each exported picture what to do with a box that is not its shape", () => {
+ // The exporter writes the box and the address alone, so a picture cut to a square on the
+ // map would be drawn whole and squashed into it here.
+ const mind = buildMind();
+ for (const objectFit of [ "cover", "contain", "" ]) {
+ const drawn = document.createElement("img");
+ drawn.style.objectFit = objectFit;
+ mind.nodes.appendChild(drawn);
+ }
+
+ const exportedSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="400px" height="300px">` +
+ `<svg x="100" y="100" overflow="visible">` +
+ `<image width="240px" height="240px" href="a.png"/>` +
+ `<image width="240px" height="240px" href="b.png"/>` +
+ `<image width="240px" height="180px" href="c.png"/>` +
+ `</svg></svg>`;
+ const result = postProcessExportedSvg(mind, exportedSvg);
+
+ const doc = new DOMParser().parseFromString(result, "image/svg+xml");
+ expect(Array.from(doc.querySelectorAll("image")).map((image) => image.getAttribute("preserveAspectRatio")))
+ // The last is drawn with no fit of its own, which stretches it to its box — the shape
+ // of the picture, as it happens, so nothing comes of it.
+ .toEqual([ "xMidYMid slice", "xMidYMid meet", "none" ]);
+ });
+
+ it("says nothing of the fit where the pictures of the map and of the export do not line up", () => {
+ const mind = buildMind();
+ mind.nodes.appendChild(document.createElement("img"));
+
+ const exportedSvg = `<svg xmlns="http://www.w3.org/2000/svg"><svg><image href="a.png"/>` +
+ `<image href="b.png"/></svg></svg>`;
+ const result = postProcessExportedSvg(mind, exportedSvg);
+
+ const doc = new DOMParser().parseFromString(result, "image/svg+xml");
+ expect(doc.querySelector("image")?.hasAttribute("preserveAspectRatio")).toBe(false);
+ });
+
it("adds no labels when the map has none, and returns unparseable input unchanged", () => {
const noLabels = postProcessExportedSvg(buildMind(), buildExportedSvg());
const doc = new DOMParser().parseFromString(noLabels, "image/svg+xml");
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 b2588ce8db..118b941dcd 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
@@ -117,6 +117,8 @@ export function postProcessExportedSvg(mind: MindElixirInstance, svgText: string
backTranslucentNodeBoxes(contentSvg, canvasColor);
}
+ carryImageFit(contentSvg, mind);
+
const labels = mind.nodes.querySelectorAll<HTMLElement>(".svg-label");
for (const label of Array.from(labels)) {
contentSvg.appendChild(doc.importNode(buildLabelForeignObject(label), true));
@@ -155,6 +157,39 @@ function backTranslucentNodeBoxes(contentSvg: Element, canvasColor: string) {
}
}
+/**
+ * Tells each exported picture what to do with a box that is not its shape.
+ *
+ * A node draws its picture with `object-fit`, which the exporter does not carry over: it writes the
+ * box and the address and nothing else, so a picture cut to a square on the map would be drawn
+ * whole and squashed into that square in the preview. The same instruction in SVG is
+ * `preserveAspectRatio`, set here from what each picture was drawn with.
+ *
+ * The exporter appends one `<image>` per `<img>` of the map, in the order it finds them, and emits
+ * no others — so the two line up. Where they do not, nothing is said rather than the wrong thing.
+ */
+function carryImageFit(contentSvg: Element, mind: MindElixirInstance) {
+ const drawn = Array.from(mind.nodes.querySelectorAll("img"));
+ const exported = Array.from(contentSvg.querySelectorAll("image"));
+ if (drawn.length !== exported.length) {
+ return;
+ }
+
+ for (const [ index, image ] of exported.entries()) {
+ // Unset, a picture is stretched to its box, which is what CSS does with `object-fit` unset
+ // — and what a box of the picture's own shape, the usual case, makes no difference to.
+ const fit = drawn[index].style.objectFit || "fill";
+ image.setAttribute("preserveAspectRatio", FIT_ALIGNMENTS[fit] ?? FIT_ALIGNMENTS.fill);
+ }
+}
+
+/** What each `object-fit` is called in SVG. */
+const FIT_ALIGNMENTS: Record<string, string> = {
+ fill: "none",
+ contain: "xMidYMid meet",
+ cover: "xMidYMid slice"
+};
+
/**
* The alpha of a fill the exporter took from a computed style, or `null` when it carries none.
* Computed sRGB colors are always serialized as `rgb()`/`rgba()`, so a translucent one arrives in
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
index 61dfa2db6a..cb9fc8fe86 100644
--- 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
@@ -2,7 +2,7 @@ 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";
+import { DEFAULT_NODE_IMAGE_WIDTH, fitNodeImage, getNodeImageShape, loadImageData, measureImage, nearestNodeImageWidth, NODE_IMAGE_WIDTHS, shapeNodeImage, uploadNodeImage } from "./mind_map_images";
vi.mock("../../../services/server", () => ({ default: { upload: vi.fn() } }));
vi.mock("../../../services/toast", () => ({ default: { showError: vi.fn() } }));
@@ -64,6 +64,41 @@ describe("nearestNodeImageWidth", () => {
});
});
+describe("shapeNodeImage", () => {
+ const image = { url: "a.png", width: 240, height: 180 };
+
+ it("cuts a picture to a shape it did not come in, and asks it to fill the box", async () => {
+ expect(await shapeNodeImage(image, "square")).toEqual({ url: "a.png", width: 240, height: 240, fit: "cover" });
+ expect(await shapeNodeImage(image, "wide")).toEqual({ url: "a.png", width: 240, height: 135, fit: "cover" });
+ });
+
+ it("reads the picture again to give it its own shape back, keeping the width it is drawn at", async () => {
+ // Cut to a square, a picture no longer says what it came in — so it is asked.
+ stubDecoder({ width: 800, height: 600 });
+ const square = await shapeNodeImage(image, "square");
+
+ expect(await shapeNodeImage(square, "original")).toEqual({ url: "a.png", width: 240, height: 180, fit: undefined });
+ });
+
+ it("leaves a picture as it stands where it can no longer be read", async () => {
+ stubDecoder(null);
+ const square = { url: "gone.png", width: 240, height: 240, fit: "cover" } as const;
+
+ expect(await shapeNodeImage(square, "original")).toBe(square);
+ });
+});
+
+describe("getNodeImageShape", () => {
+ it("reads the shape a picture is drawn in, its own being every other", () => {
+ expect(getNodeImageShape({ url: "a.png", width: 240, height: 240 })).toBe("square");
+ expect(getNodeImageShape({ url: "a.png", width: 240, height: 135 })).toBe("wide");
+ expect(getNodeImageShape({ url: "a.png", width: 240, height: 180 })).toBe("original");
+
+ // A height rounded to whole pixels still reads as the shape it was cut to.
+ expect(getNodeImageShape({ url: "a.png", width: 121, height: 68 })).toBe("wide");
+ });
+});
+
describe("uploadNodeImage", () => {
const file = new File([ "" ], "photo.png", { type: "image/png" });
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
index d14c8b5001..10d064c6be 100644
--- a/apps/client/src/widgets/type_widgets/helpers/mind_map_images.ts
+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_images.ts
@@ -67,12 +67,80 @@ async function uploadImage(noteId: string, file: File): Promise<string | 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;
+export async function measureImage(file: Blob): Promise<ImageSize | null> {
+ return sizeOf(await decodeImage(file));
+}
+
+/** The same, for a picture the note already holds, read from where a node points at it. */
+export async function measureImageAt(url: string): Promise<ImageSize | null> {
+ return sizeOf(await decodeImageAt(url));
+}
+
+export interface ImageSize {
+ width: number;
+ height: number;
+}
+
+/**
+ * The shapes a picture is offered in, in the order the panel lays them out.
+ *
+ * A picture is drawn in the box a node gives it, and the box need not be the shape the picture came
+ * in: a portrait and a landscape sitting side by side on two nodes read as a jumble, where the same
+ * two cut to a square read as a pair. What is asked of the picture where the two disagree is
+ * {@link NodeImage.fit} — cut to fill the box, which is what a shape is chosen for.
+ */
+export const NODE_IMAGE_SHAPES = [ "original", "square", "wide" ] as const;
+
+export type NodeImageShape = typeof NODE_IMAGE_SHAPES[number];
+
+/** How tall each shape stands for a width of one. "Original" is the picture's own, so it has none. */
+const NODE_IMAGE_SHAPE_RATIOS: Record<Exclude<NodeImageShape, "original">, number> = {
+ square: 1,
+ wide: 9 / 16
+};
+
+/**
+ * The same picture in the given shape, at the width it is already drawn at.
+ *
+ * Read back rather than remembered: a picture cut to a square no longer says what it came in, so
+ * returning it to its own shape means asking the picture itself again — it is a fetch the browser
+ * answers from what it already holds, the picture being on screen.
+ *
+ * @returns the picture as it is to be drawn, or as it stands where its own shape was asked for and
+ * it could no longer be read.
+ */
+export async function shapeNodeImage(image: NodeImage, shape: NodeImageShape): Promise<NodeImage> {
+ if (shape !== "original") {
+ return {
+ ...image,
+ height: Math.max(1, Math.round(image.width * NODE_IMAGE_SHAPE_RATIOS[shape])),
+ fit: "cover"
+ };
}
- return { width: image.naturalWidth, height: image.naturalHeight };
+
+ const size = await measureImageAt(image.url);
+ if (!size) {
+ return image;
+ }
+ return { ...fitNodeImage({ ...image, ...size }, image.width), fit: undefined };
+}
+
+/**
+ * The shape a picture is drawn in, as the panel shows it. A picture that came in one of these
+ * shapes and was never cut reads as that shape, which is what it is — nothing is asked of it, and
+ * choosing that shape leaves it as it is.
+ */
+export function getNodeImageShape(image: NodeImage): NodeImageShape {
+ const ratio = (image.width > 0 ? image.height / image.width : 1);
+
+ for (const [ shape, shapeRatio ] of Object.entries(NODE_IMAGE_SHAPE_RATIOS)) {
+ // Wide enough to take in the rounding of a height to whole pixels, and no wider.
+ if (Math.abs(ratio - shapeRatio) < 0.01) {
+ return shape as NodeImageShape;
+ }
+ }
+
+ return "original";
}
/**
@@ -160,24 +228,31 @@ async function redrawImage(blob: Blob, width: number): Promise<string | null> {
}
}
+/** The size of a decoded picture, or `null` for what could not be read as one. */
+function sizeOf(image: HTMLImageElement | null): ImageSize | null {
+ if (!image?.naturalWidth || !image.naturalHeight) {
+ return null;
+ }
+ return { width: image.naturalWidth, height: image.naturalHeight };
+}
+
+/** Hands the picture to the browser to decode, under an address of the moment. */
+function decodeImage(blob: Blob): Promise<HTMLImageElement | null> {
+ const url = URL.createObjectURL(blob);
+ return decodeImageAt(url).finally(() => URL.revokeObjectURL(url));
+}
+
/**
- * Hands the picture to the browser to decode, `null` where it will not have it. Decoded through an
+ * Decodes the picture at an address, `null` where the browser 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> {
+function decodeImageAt(src: string): 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;
+ image.onload = () => resolve(image);
+ image.onerror = () => resolve(null);
+ image.src = src;
});
}