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
client/image compression tool: wire up the dialog to the API
Adorian Doran92e231a3820f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 33a172ef24..8ad73174d1 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2923,7 +2923,13 @@"compress_process_child_notes": "Process child notes as well","compress_process_child_notes_help": "Compresses the images of every note in the subtree, not just the selected one. Beware that a child note may be a clone, in which case its images are shared with the other notes it appears in.","compress_cancel": "Cancel",- "compress_run": "Compress images"+ "compress_run": "Compress images",+ "compress_running": "Compressing images…",+ "compress_result_one": "{{count}} image processed, reducing the size from {{before}} to {{after}}.",+ "compress_result_other": "{{count}} images processed, reducing the size from {{before}} to {{after}}.",+ "compress_result_no_gain_one": "{{count}} image processed, but it could not be made any smaller.",+ "compress_result_no_gain_other": "{{count}} images processed, but none of them could be made any smaller.",+ "compress_result_none": "There are no images to compress."},"note_language": {"not_set": "No language set",diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.tsindex e6f094c283..6aa2aee2b0 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts@@ -18,7 +18,8 @@ const mocks = vi.hoisted(() => ({deleteNotes: vi.fn(async (..._args: unknown[]) => true),downloadFileNote: vi.fn(),showDetails: vi.fn(),- showCompressionDialog: vi.fn(async () => null),+ // Answers like the real one: the run's report, or null when the user backed out or it failed.+ showCompressionDialog: vi.fn<(...args: unknown[]) => Promise<{ compressedCount: number } | null>>(async () => null),contentChanged: vi.fn(),post: vi.fn(async (..._args: unknown[]) => undefined),showMessage: vi.fn(),@@ -58,7 +59,7 @@ vi.mock("../../../../../services/server", () => ({// Stubbed rather than rendered: what belongs here is that the menu opens it, and the dialog's own// spec covers what it then does.vi.mock("./image_compression_dialog", () => ({- showImageCompressionDialog: () => mocks.showCompressionDialog()+ showImageCompressionDialog: (...args: unknown[]) => mocks.showCompressionDialog(...args)}));vi.mock("../../../../../services/toast", () => ({@@ -168,10 +169,8 @@ describe("openSpaceUsageContextMenu", () => {invoke(SHOW_DETAILS);expect(mocks.showDetails).toHaveBeenCalledWith([ "root", "p", "n1" ]);- // Only opens the dialog: nothing is compressed and nothing re-measured until the run itself- // is wired up, so there is no reading to invalidate either.invoke(COMPRESS_IMAGES);- expect(mocks.showCompressionDialog).toHaveBeenCalled();+ expect(mocks.showCompressionDialog).toHaveBeenCalledWith({ type: "note", noteId: "n1" });invoke(EXPORT);expect(mocks.triggerCommand).toHaveBeenLastCalledWith("showExportDialog", {@@ -202,6 +201,26 @@ describe("openSpaceUsageContextMenu", () => {expect(mocks.contentChanged).toHaveBeenCalledTimes(1);});+ it("asks for a fresh reading once images were actually replaced, and not otherwise", async () => {+ givenNote("n1");+ await openFor([ "root", "p", "n1" ]);++ // Compressing changes the size of the notes holding the images, which is what the views are+ // drawn from — so a run that replaced any of them has to say so.+ mocks.showCompressionDialog.mockResolvedValueOnce({ compressedCount: 2 });+ invoke(COMPRESS_IMAGES);+ await vi.waitFor(() => expect(mocks.contentChanged).toHaveBeenCalledTimes(1));++ // A run that compressed nothing, and a dialog backed out of or failed, all leave the+ // figures exactly as they were — so none of them is worth re-measuring the database for.+ mocks.showCompressionDialog.mockResolvedValueOnce({ compressedCount: 0 });+ invoke(COMPRESS_IMAGES);+ mocks.showCompressionDialog.mockResolvedValueOnce(null);+ invoke(COMPRESS_IMAGES);+ await vi.waitFor(() => expect(mocks.showCompressionDialog).toHaveBeenCalledTimes(3));+ expect(mocks.contentChanged).toHaveBeenCalledTimes(1);+ });+it("adds Download for file-bearing types, disabled when the content is away", async () => {givenNote("f1", "file");mocks.branchIds.set("p/f1", "b1");diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.tsindex f21ab9195b..a28a86e05e 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts@@ -86,8 +86,13 @@ export async function openSpaceUsageContextMenu({title: t("space_usage.menu_compress_images"),uiIcon: "bx bx-image",- // The dialog only collects the settings for now; nothing runs, and nothing re-measures.- handler: () => void showImageCompressionDialog()+ handler: () => {+ // Only once images were actually replaced: their notes just changed size, and the+ // views take a reading when asked rather than following the database. A run that+ // compressed nothing — or failed, which answers as no run — leaves them be.+ void showImageCompressionDialog({ type: "note", noteId })+ .then((result) => result?.compressedCount && onContentChanged());+ }},{ kind: "separator" },diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsxindex 9506624a62..7dd6ed2efa 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsx@@ -3,17 +3,37 @@ import { useEffect } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-const { CONFIGURED_MAX_DIMENSIONS, CONFIGURED_QUALITY } = vi.hoisted(() => ({+const { CONFIGURED_MAX_DIMENSIONS, CONFIGURED_QUALITY, EMPTY_RESULT } = vi.hoisted(() => ({// Deliberately unlike the shipped defaults, so a field falling back to the image option cannot// pass for one falling back to a constant of its own.CONFIGURED_MAX_DIMENSIONS: 1600,- CONFIGURED_QUALITY: 60+ CONFIGURED_QUALITY: 60,+ /** What a run reports when it found nothing; tests that care override it. */+ EMPTY_RESULT: {+ items: [], compressedCount: 0, skippedCount: 0, originalSize: 0, newSize: 0, savedSize: 0+ }}));+/** A report of `count` images compressed, weighing `originalSize` before and `newSize` after. */+function resultOf(count: number, originalSize: number, newSize: number) {+ return {+ items: Array.from({ length: count }, (_, index) => ({ entityId: `img${index}` })),+ compressedCount: count,+ skippedCount: 0,+ originalSize,+ newSize,+ savedSize: originalSize - newSize+ };+}+const mocks = vi.hoisted(() => ({getInt: vi.fn<(name: string) => number | null>(),storedOption: "{}",- save: vi.fn(async () => {})+ save: vi.fn(async () => {}),+ postWithTimeout: vi.fn<(...args: unknown[]) => Promise<unknown>>(async () => EMPTY_RESULT),+ showMessage: vi.fn<(message: string, timeout?: number) => void>(),+ showPersistent: vi.fn<(options: { id: string, message: string }) => void>(),+ closePersistent: vi.fn<(id: string) => void>()}));vi.mock("../../../../../services/options", () => ({@@ -24,6 +44,21 @@ vi.mock("../../../../../services/options", () => ({}}));+vi.mock("../../../../../services/server", () => ({+ default: {+ get: async () => [],+ postWithTimeout: (url: string, _timeoutMs: number, body?: object) => mocks.postWithTimeout(url, body)+ }+}));++vi.mock("../../../../../services/toast", () => ({+ default: {+ showMessage: mocks.showMessage,+ showPersistent: mocks.showPersistent,+ closePersistent: mocks.closePersistent+ }+}));+// The harness loads no translations, so the real `t` answers undefined for every key. Echoing the// key back instead lets each row be identified by the string it actually asked for, and lets the// quality reading be read as the value it interpolates.@@ -56,6 +91,10 @@ vi.mock("../../../../react/Modal", () => ({}));import { showImageCompressionDialog } from "./image_compression_dialog";+import { IMAGE_COMPRESSION_TOAST_ID, type ImageCompressionTarget } from "./image_compression_operation";++const NOTE_TARGET: ImageCompressionTarget = { type: "note", noteId: "n1" };+const ATTACHMENT_TARGET: ImageCompressionTarget = { type: "attachment", attachmentId: "a1" };function rows() {return Array.from(document.body.querySelectorAll<HTMLElement>(".image-compression-section"));@@ -77,12 +116,20 @@ const compressButton = () => buttons()[1];* Opens the dialog. The pending close is handed back wrapped: returned bare, awaiting this helper* would adopt it and wait for the dialog to be dismissed.*/-async function openDialog() {- const closed = showImageCompressionDialog();+async function openDialog(target: ImageCompressionTarget = NOTE_TARGET) {+ const closed = showImageCompressionDialog(target);await settle();return { closed };}+/** The body of the one request a run made, or `undefined` if it made none. */+function postedBody() {+ return mocks.postWithTimeout.mock.calls[0]?.[1] as Record<string, unknown> | undefined;+}++const postedUrl = () => mocks.postWithTimeout.mock.calls[0]?.[0];+const reportedMessage = () => mocks.showMessage.mock.calls[0]?.[0] ?? "";+function settle() {return act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });}@@ -124,6 +171,7 @@ async function setAndDispatch(field: HTMLInputElement | null | undefined, value:beforeEach(() => {mocks.storedOption = "{}";vi.clearAllMocks();+ mocks.postWithTimeout.mockResolvedValue(EMPTY_RESULT);mocks.getInt.mockImplementation((name) => (name === "imageMaxWidthHeight" ? CONFIGURED_MAX_DIMENSIONS: name === "imageJpegQuality" ? CONFIGURED_QUALITY@@ -154,6 +202,16 @@ describe("showImageCompressionDialog", () => {.toEqual([ false, false, true, true ]);});+ it("drops the subtree row for an attachment, which has no subtree to reach into", async () => {+ await openDialog(ATTACHMENT_TARGET);++ expect(titles()).toEqual([+ "images.max_image_dimensions",+ "images.jpeg_quality",+ "space_usage.compress_convert_lossless"+ ]);+ });+it("reads the quality out between its title and the slider", async () => {await openDialog();@@ -179,9 +237,18 @@ describe("showImageCompressionDialog", () => {expect(numberField()?.value).toBe(String(CONFIGURED_MAX_DIMENSIONS));expect(slider()?.value).toBe(String(CONFIGURED_QUALITY));- // Both toggles start off: a conversion that costs quality and a run that reaches beyond the- // note it was invoked on are things to be asked for, never assumed.- expect(toggles().map((input) => input.checked)).toEqual([ false, false ]);+ // Converting starts on — it is where nearly all the saving comes from, and someone reaching+ // for this tool is already accepting a loss of quality. Reaching into the subtree does not:+ // that widens what the run touches, and a descendant may be a clone.+ expect(toggles().map((input) => input.checked)).toEqual([ true, false ]);+ });++ it("keeps a stored answer of off for converting, rather than reasserting the default", async () => {+ mocks.storedOption = JSON.stringify({ convertLossless: false });++ await openDialog();++ expect(toggles()[0].checked).toBe(false);});it("reads a stored answer back, and lets it override the image options", async () => {@@ -228,7 +295,7 @@ describe("showImageCompressionDialog", () => {expect(mocks.save).toHaveBeenLastCalledWith("imageCompressionToolOptions", JSON.stringify({maxWidthHeight: 900,quality: 45,- convertLossless: true,+ convertLossless: false,processChildNotes: true}));});@@ -241,33 +308,111 @@ describe("showImageCompressionDialog", () => {expect(numberField()?.value).toBe("1");});- it("hands back what was asked for once it has closed", async () => {+ it("hands back nothing when the user backs out, settings remembered all the same", async () => {const { closed } = await openDialog();- await toggle(toggles()[0]);+ await toggle(toggles()[1]);+ await click(cancelButton());++ // The answer is "no run", and nothing was asked of the server — but the settings are kept+ // either way, so the next run opens where this one left off.+ await expect(closed).resolves.toBeNull();+ expect(mocks.postWithTimeout).not.toHaveBeenCalled();+ expect(mocks.save).toHaveBeenCalledWith(+ "imageCompressionToolOptions", expect.stringContaining('"processChildNotes":true'));+ });+});++describe("running the compression", () => {+ it("sends the settings to the note endpoint, the subtree choice among them", async () => {+ const { closed } = await openDialog();++ await toggle(toggles()[1]);await click(compressButton());+ await closed;- await expect(closed).resolves.toEqual({+ expect(postedUrl()).toBe("notes/n1/compress-images");+ expect(postedBody()).toEqual({maxWidthHeight: CONFIGURED_MAX_DIMENSIONS,quality: CONFIGURED_QUALITY,convertLossless: true,- processChildNotes: false+ recursive: true});- // Mounted on demand, and gone again with it: nothing is left in the page behind the dialog.- expect(rows()).toEqual([]);});- it("hands back nothing when the user backs out, settings remembered all the same", async () => {+ it("sends nothing about subtrees to the attachment endpoint, which has no use for it", async () => {+ const { closed } = await openDialog(ATTACHMENT_TARGET);++ await click(compressButton());+ await closed;++ expect(postedUrl()).toBe("attachments/a1/compress-image");+ expect(postedBody()).not.toHaveProperty("recursive");+ });++ it("holds a spinner up for the length of the run, and takes it down once it is over", async () => {+ let finish: (result: unknown) => void = () => {};+ mocks.postWithTimeout.mockReturnValueOnce(new Promise<unknown>((resolve) => { finish = resolve; }));+const { closed } = await openDialog();+ await click(compressButton());- await toggle(toggles()[1]);- await click(cancelButton());+ // The dialog is out of the way and the run is under way: nothing here can say how far along+ // it is, so the toast stays up rather than counting anything down.+ expect(mocks.showPersistent).toHaveBeenCalledWith(expect.objectContaining({+ id: IMAGE_COMPRESSION_TOAST_ID,+ message: "space_usage.compress_running",+ dismissible: false+ }));+ expect(mocks.closePersistent).not.toHaveBeenCalled();++ finish(resultOf(3, 100, 40));+ await closed;++ expect(mocks.closePersistent).toHaveBeenCalledWith(IMAGE_COMPRESSION_TOAST_ID);+ });++ it("reports what the run did, in real sizes", async () => {+ mocks.postWithTimeout.mockResolvedValueOnce(resultOf(10, 45 * 1024 * 1024, 7 * 1024 * 1024));- // The answer is "no run", but the settings are kept either way — the next run opens where- // this one left off whether or not it was carried through.+ const { closed } = await openDialog();+ await click(compressButton());+ const result = await closed;++ expect(reportedMessage()).toBe(+ 'space_usage.compress_result {"count":10,"before":"45 MiB","after":"7 MiB"}');+ // Handed back as well as reported, so a caller knows its own figures are now stale.+ expect(result?.compressedCount).toBe(10);+ });++ it.each([+ [ "found no images at all", EMPTY_RESULT, "space_usage.compress_result_none" ],+ // Quoting "from 45 MiB to 45 MiB" would read as a failure to report, where it is in fact a+ // complete answer: the images were already as small as these settings can make them.+ [ "made nothing smaller", resultOf(4, 900, 900), 'space_usage.compress_result_no_gain {"count":4}' ]+ ])("says so plainly when the run %s", async (_label, response, expected) => {+ mocks.postWithTimeout.mockResolvedValueOnce(response);++ const { closed } = await openDialog();+ await click(compressButton());+ await closed;++ expect(reportedMessage()).toBe(expected);+ });++ it("takes the spinner down and claims nothing when the run fails", async () => {+ mocks.postWithTimeout.mockRejectedValueOnce(new Error("boom"));++ const { closed } = await openDialog();+ await click(compressButton());++ // Answered as no run: the request layer already reported the failure, and nothing here can+ // say what it managed to change before it failed.await expect(closed).resolves.toBeNull();- expect(mocks.save).toHaveBeenCalledWith(- "imageCompressionToolOptions", expect.stringContaining('"processChildNotes":true'));+ expect(mocks.closePersistent).toHaveBeenCalledWith(IMAGE_COMPRESSION_TOAST_ID);+ expect(mocks.showMessage).not.toHaveBeenCalled();+ // Mounted on demand, and gone again with it, however the run ended.+ expect(rows()).toEqual([]);});});diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsxindex 04d98f38c2..18be0ef47e 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsx@@ -1,34 +1,47 @@import "./image_compression_dialog.css";+import type { ImageCompressionResponse } from "@triliumnext/commons";import { render } from "preact";-import { useState } from "preact/hooks";+import { useRef, useState } from "preact/hooks";import { t } from "../../../../../services/i18n";+import toast from "../../../../../services/toast";import Button from "../../../../react/Button";import { Card } from "../../../../react/Card";import { useTriliumOptionJson } from "../../../../react/hooks";import Modal from "../../../../react/Modal";+import {+ compressionResultMessage,+ IMAGE_COMPRESSION_TOAST_ID,+ type ImageCompressionTarget,+ runImageCompression+} from "./image_compression_operation";import {type ImageCompressionToolOptions,readImageCompressionOptions} from "./image_compression_options";-import { ImageCompressionSections } from "./image_compression_sections";+import {+ ConvertLosslessSection,+ JpegQualitySection,+ MaxImageDimensionsSection,+ ProcessChildNotesSection+} from "./image_compression_sections";/**- * Opens the image compression dialog, and resolves once it has closed: the settings the user- * confirmed, or `null` if they backed out. The run itself is the caller's to make — nothing here- * touches the database.+ * Opens the image compression dialog for one note or one attachment, and resolves once the run it+ * asked for has finished: the report of what was compressed, or `null` if the user backed out.+ * Callers await it to know when their own figures are stale.** Mounted on demand into a host of its own, as the cleanup dialog is: a dialog reached from a* context menu has no place sitting in the page that merely *could* open it.*/-export function showImageCompressionDialog(): Promise<ImageCompressionToolOptions | null> {+export function showImageCompressionDialog(target: ImageCompressionTarget): Promise<ImageCompressionResponse | null> {return new Promise((resolve) => {const host = document.body.appendChild(document.createElement("div"));render(- <ImageCompressionDialog onFinished={(options) => {- resolve(options);+ <ImageCompressionDialog target={target} onFinished={(result) => {+ resolve(result);render(null, host);host.remove();}} />,@@ -38,11 +51,14 @@ export function showImageCompressionDialog(): Promise<ImageCompressionToolOption}/**- * How the images a note holds are to be recompressed. Every setting is written straight back to the+ * How the target's images are to be recompressed. Every setting is written straight back to the* stored option as it changes, so the next run opens where this one left off whether or not it was* carried through — the same bargain the cleanup tool makes.*/-function ImageCompressionDialog({ onFinished }: { onFinished: (options: ImageCompressionToolOptions | null) => void }) {+function ImageCompressionDialog({ target, onFinished }: {+ target: ImageCompressionTarget,+ onFinished: (result: ImageCompressionResponse | null) => void+}) {const [ shown, setShown ] = useState(true);const [ stored, setStored ] = useTriliumOptionJson<Partial<ImageCompressionToolOptions>>("imageCompressionToolOptions");const [ options, setOptions ] = useState<ImageCompressionToolOptions>(() => readImageCompressionOptions(stored));@@ -52,9 +68,42 @@ function ImageCompressionDialog({ onFinished }: { onFinished: (options: ImageComvoid setStored(next);};- // What the dialog was closed *for*, held across the close: the answer is delivered once the- // dialog is out of the way, by which time the state it was configured from is on its way out too.- const [ confirmed, setConfirmed ] = useState<ImageCompressionToolOptions | null>(null);+ // What the run was asked to do, held across the close: the operation starts once the dialog is+ // out of the way, by which time the state it was configured from is on its way out too.+ const pending = useRef<ImageCompressionToolOptions | null>(null);+ const sectionProps = { options, onChange: update };++ async function runPendingCompression() {+ const settings = pending.current;++ if (!settings) {+ onFinished(null);+ return;+ }++ // Nothing here can say how far along it is — the images are compressed server-side and the+ // run reports only once — so a spinner rather than a bar, and nothing to cancel: the server+ // carries on whatever the client does.+ toast.showPersistent({+ id: IMAGE_COMPRESSION_TOAST_ID,+ icon: "bx bx-loader-circle bx-spin",+ message: t("space_usage.compress_running"),+ dismissible: false+ });++ let result: ImageCompressionResponse | null = null;++ try {+ result = await runImageCompression(target, settings);+ toast.showMessage(compressionResultMessage(result), COMPRESSION_DONE_TIMEOUT_MS);+ } catch {+ // Already reported by the request layer, and nothing here can say what the run managed+ // to change before it failed — so it is answered as no run rather than as an empty one.+ } finally {+ toast.closePersistent(IMAGE_COMPRESSION_TOAST_ID);+ onFinished(result);+ }+ }return (<Modal@@ -63,14 +112,14 @@ function ImageCompressionDialog({ onFinished }: { onFinished: (options: ImageComsize="sm"minWidth={COMPRESSION_DIALOG_MIN_WIDTH}show={shown}- onHidden={() => onFinished(confirmed)}+ onHidden={() => void runPendingCompression()}footer={<><Button text={t("space_usage.compress_cancel")} onClick={() => setShown(false)} /><Buttontext={t("space_usage.compress_run")}kind="primary"onClick={() => {- setConfirmed(options);+ pending.current = options;setShown(false);}}/>@@ -78,15 +127,25 @@ function ImageCompressionDialog({ onFinished }: { onFinished: (options: ImageComstackable><Card className="image-compression-settings">- <ImageCompressionSections options={options} onChange={update} />+ <MaxImageDimensionsSection {...sectionProps} />+ <JpegQualitySection {...sectionProps} />+ <ConvertLosslessSection {...sectionProps} />+ {/* An attachment is one image; there is no subtree under it to reach into. */}+ {target.type === "note" && <ProcessChildNotesSection {...sectionProps} />}</Card></Modal>);}/**- * The width the dialog starts at, narrow on purpose: four settings read top to bottom rather than+ * The width the dialog starts at, narrow on purpose: a few settings read top to bottom rather than* scanned across. A floor rather than a size — row titles never wrap, so a long translation widens* the dialog instead of folding onto a second line (see the sections' stylesheet).*/const COMPRESSION_DIALOG_MIN_WIDTH = "420px";++/**+ * Longer than the default couple of seconds: this reports on something that ran unattended and has+ * three figures worth reading, and it is the only account of a run the user will get.+ */+const COMPRESSION_DONE_TIMEOUT_MS = 15000;diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_operation.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_operation.tsnew file mode 100644index 0000000000..508d835e02--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_operation.ts@@ -0,0 +1,69 @@+import type { ImageCompressionResponse } from "@triliumnext/commons";++import { t } from "../../../../../services/i18n";+import server from "../../../../../services/server";+import { formatSize } from "../../../../../services/utils";+import type { ImageCompressionToolOptions } from "./image_compression_options";++/**+ * What a compression run acts on: a whole note — its own image, or the images its attachments hold+ * — or a single attachment picked out on its own.+ */+export type ImageCompressionTarget =+ | { type: "note"; noteId: string }+ | { type: "attachment"; attachmentId: string };++/** Shared by every stage of a run, so the message is swapped in place rather than stacked. */+export const IMAGE_COMPRESSION_TOAST_ID = "image-compression";++/**+ * Decoding and re-encoding is measured in seconds per image, and a subtree run can hold thousands+ * of them. The default minute would not stop the server working — it would only lose the answer and+ * report a failure for something that went on to succeed.+ */+const COMPRESSION_TIMEOUT_MS = 60 * 60 * 1000;++/** Compresses the target's images and reports what that did, image by image and in total. */+export function runImageCompression(+ target: ImageCompressionTarget,+ options: ImageCompressionToolOptions+): Promise<ImageCompressionResponse> {+ const url = target.type === "note"+ ? `notes/${target.noteId}/compress-images`+ : `attachments/${target.attachmentId}/compress-image`;++ return server.postWithTimeout<ImageCompressionResponse>(url, COMPRESSION_TIMEOUT_MS, {+ maxWidthHeight: options.maxWidthHeight,+ quality: options.quality,+ convertLossless: options.convertLossless,+ // Left out entirely for an attachment, which has no subtree to descend into — the endpoint+ // does not read it, and sending it would suggest it does.+ ...(target.type === "note" ? { recursive: options.processChildNotes } : {})+ });+}++/**+ * What the run is told to have done. Every image it visited is counted, skipped ones included, so+ * the count and the two sizes are all measured over the same set and read as one sentence.+ *+ * A run that saved nothing says so rather than quoting a size that did not move: "from 45 MiB to+ * 45 MiB" reads as a failure to report, where it is in fact a complete and correct answer — the+ * images were already as small as these settings can make them.+ */+export function compressionResultMessage(result: ImageCompressionResponse): string {+ const count = result.items.length;++ if (count === 0) {+ return t("space_usage.compress_result_none");+ }++ if (result.savedSize <= 0) {+ return t("space_usage.compress_result_no_gain", { count });+ }++ return t("space_usage.compress_result", {+ count,+ before: formatSize(result.originalSize),+ after: formatSize(result.newSize)+ });+}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.tsindex 3e8c590fbb..49317c7c67 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.ts@@ -12,10 +12,7 @@ export interface ImageCompressionToolOptions {maxWidthHeight: number;/** JPEG quality, {@link MIN_QUALITY} to {@link MAX_QUALITY}. */quality: number;- /**- * Whether a lossless source (PNG) may be re-encoded as JPEG. Off unless asked for: it trades- * away quality permanently, where scaling down alone does not.- */+ /** Whether a lossless source (PNG) may be re-encoded as JPEG. */convertLossless: boolean;/** Whether the note's whole subtree is compressed, rather than the note on its own. */processChildNotes: boolean;@@ -33,9 +30,13 @@ export const MIN_MAX_WIDTH_HEIGHT = 1;** The two numbers fall back to the image options rather than to constants of their own, so a tool* that has never been run opens on what automatic compression is already configured to do — the same- * fallbacks the server applies to a request that omits them. Neither toggle is ever assumed: a- * conversion that costs quality, and a run that reaches beyond the note it was invoked on, are both- * things to be asked for.+ * fallbacks the server applies to a request that omits them.+ *+ * Converting starts on: someone reaching for this tool has a note that has grown too heavy and is+ * already accepting a loss of quality to shrink it, and converting is where nearly all the saving+ * comes from — offering it off by default would mean most first runs reporting almost nothing.+ * Reaching into the subtree does not: that widens what the run touches rather than how hard it+ * compresses, and a descendant may be a clone shared with notes the user did not have in mind.*/export function readImageCompressionOptions(stored: Partial<ImageCompressionToolOptions> | null | undefined@@ -45,7 +46,7 @@ export function readImageCompressionOptions(? Number(stored?.maxWidthHeight): defaultMaxWidthHeight(),quality: isQuality(stored?.quality) ? Number(stored?.quality) : defaultQuality(),- convertLossless: stored?.convertLossless === true,+ convertLossless: stored?.convertLossless ?? true,processChildNotes: stored?.processChildNotes === true};}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsxindex 6aa94c1962..5de5a6c0bc 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsx@@ -15,9 +15,9 @@ import {} from "./image_compression_options";/**- * The rows that configure an image compression run, each a `CardSection` of its own so they can be- * dropped into any card — the compression dialog lists all four, and the cleanup tool will nest them- * under an item of its own.+ * The rows that configure an image compression run, each a `CardSection` of its own so a host picks+ * the ones that mean anything where it stands: the compression dialog drops the subtree row for an+ * attachment, which has no subtree, and the cleanup tool will drop it too, being database-wide.** Every row takes the whole settings object and reports a patch, rather than a value and a setter,* so a host wires the group once and adding a row later costs it nothing.@@ -29,18 +29,6 @@ export interface ImageCompressionSectionProps {disabled?: boolean;}-/** All four rows in their reading order, for the common case of wanting the lot. */-export function ImageCompressionSections(props: ImageCompressionSectionProps) {- return (- <>- <MaxImageDimensionsSection {...props} />- <JpegQualitySection {...props} />- <ConvertLosslessSection {...props} />- <ProcessChildNotesSection {...props} />- </>- );-}-/** The bound images are scaled down to fit. Labelled as the image settings label it. */export function MaxImageDimensionsSection({ options, onChange, disabled }: ImageCompressionSectionProps) {return (diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex 33c588d230..5cb4caa28c 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -127,7 +127,7 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>expect(res.body).toMatchObject({ items: [], compressedCount: 0, skippedCount: 0, savedSize: 0 });});- it("does not follow child notes, which may be clones shared with other notes", async () => {+ it("does not follow child notes unless asked to, they may be clones shared elsewhere", async () => {const { noteId } = await createTextNote(api);const childId = await createImageNote(noisyPng, noteId);@@ -139,6 +139,34 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>expect(readNote(childId).size).toBe(noisyPng.byteLength);});+ it("descends the whole subtree when asked, visiting a clone once however often it is placed", async () => {+ const { noteId } = await createTextNote(api);+ const ownAttachment = await addAttachment(noteId, "own.png", noisyPng);+ const childId = await createImageNote(noisyPng, noteId);+ const grandchildId = await createImageNote(noisyPng, childId);+ // The same note placed a second time inside the subtree: it holds one image, and the run+ // must not compress it twice (nor report it twice).+ await api.put(`/api/notes/${grandchildId}/clone-to-note/${noteId}`);++ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {+ body: { convertLossless: true, recursive: true }+ });++ expect(res.body.items.map((item) => item.entityId).sort())+ .toEqual([ ownAttachment, childId, grandchildId ].sort());+ expect(res.body.compressedCount).toBe(3);+ expect(readNote(childId).mime).toBe("image/jpeg");+ expect(readNote(grandchildId).mime).toBe("image/jpeg");+ });++ it("400s on a non-boolean recursive", async () => {+ const { noteId } = await createTextNote(api);++ const res = await api.post(`/api/notes/${noteId}/compress-images`, { body: { recursive: "deep" } });++ expect(res.status).toBe(400);+ });+it("skips the generated picture of a spreadsheet note, which is rebuilt on every save", async () => {const { noteId } = await createTextNote(api);const attachmentId = await addAttachment(noteId, "spreadsheet-export.png", noisyPng);diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex f696aa49b0..d40a81754e 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -307,6 +307,18 @@ export interface ImageCompressionOptions {* away quality permanently; with it off a PNG is only ever scaled down, never re-encoded.*/convertLossless?: boolean;+ /**+ * Whether the run visits the note's whole subtree rather than the note alone. Off by default,+ * and opt-in for a reason: a descendant may be a clone, so compressing it degrades an image+ * that other notes show too.+ *+ * Each note is visited once however many placements it has. Archived notes are included, the+ * hidden subtree is not, and a search note's results are left to whatever holds them — the run+ * follows the tree, not what a query happens to match.+ *+ * Only the note endpoint reads this; an attachment has no subtree to descend into.+ */+ recursive?: boolean;}/**diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex 047f265edc..dc532f74c0 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -38,7 +38,7 @@ export async function compressNoteImages(noteId: string, options?: ImageCompressthrow new NotFoundError(`Note '${noteId}' was not found.`);}- return compressTargets(collectNoteTargets(note), resolveCompressionRequest(options));+ return compressTargets(collectNoteTargets(note, resolveRecursive(options)), resolveCompressionRequest(options));}/** Compresses one image attachment, under exactly the rules a whole-note run would apply to it. */@@ -83,6 +83,19 @@ export function resolveCompressionRequest(options: ImageCompressionOptions = {})};}+/**+ * Whether the run descends into the note's subtree. Read apart from {@link resolveCompressionRequest}+ * because it says nothing about how an image is compressed, only about which images are visited —+ * so the provider never sees it. The attachment endpoint has no use for it and does not read it.+ */+export function resolveRecursive(options: ImageCompressionOptions = {}): boolean {+ if (options.recursive !== undefined && typeof options.recursive !== "boolean") {+ throw new ValidationError("recursive must be a boolean.");+ }++ return options.recursive === true;+}+function defaultQuality(): number {const configured = optionService.getOptionInt("imageJpegQuality", 0);@@ -108,14 +121,27 @@ interface CompressionTarget {}/**- * The images a note holds. An image note *is* its image, so it stands alone; for anything else the- * images are the attachments it owns — which is where a text note's pictures live, and where the- * weight the user is trying to shed actually sits.+ * The images the run will visit, in the order it visits them.*- * Child notes are deliberately not followed: a child can be a clone shared with other notes, and- * shrinking a note should not silently degrade an image somewhere else.+ * Child notes are followed only when asked for: a descendant can be a clone shared with other+ * notes, so reaching into the subtree degrades images the caller may not have had in mind.+ * `getSubtree` visits each note once however many placements it has, leaves the hidden subtree out+ * and does not resolve search notes — the run follows the tree, not what a query happens to match.+ */+function collectNoteTargets(note: BNote, recursive: boolean): CompressionTarget[] {+ if (!recursive) {+ return ownTargetsOf(note);+ }++ return note.getSubtree().notes.flatMap(ownTargetsOf);+}++/**+ * The images one note holds. An image note *is* its image, so it stands alone; for anything else+ * the images are the attachments it owns — which is where a text note's pictures live, and where+ * the weight the user is trying to shed actually sits.*/-function collectNoteTargets(note: BNote): CompressionTarget[] {+function ownTargetsOf(note: BNote): CompressionTarget[] {if (note.type === "image") {return [ noteTarget(note) ];}@@ -265,5 +291,6 @@ function summarize(items: ImageCompressionItem[]): ImageCompressionResponse {export default {compressNoteImages,compressAttachmentImage,- resolveCompressionRequest+ resolveCompressionRequest,+ resolveRecursive};