Skip to content

Build your personal knowledge base with Trilium Notes

client: create a dialog for compressing images

Adorian Doran11f1deb00760
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 53514ad81b..33a172ef24 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2891,6 +2891,7 @@
"status_deleted": "{{size}} in deleted notes and attachments",
"status_deleted_hint": "Space still held by deleted notes and by deleted attachments (whose note may still exist); erasing them reclaims it",
"menu_show_details": "Show details",
+ "menu_compress_images": "Compress images",
"menu_erase_deleted": "Erase deleted data",
"erase_deleted_message": "Deleted data has been erased.",
"revisions_limit_required": "Excess snapshots can only be erased once a maximum number of revision snapshots per note is set. Without a limit, no snapshot counts as excess. Do you want to set the limit now?",
@@ -2914,7 +2915,15 @@
"cleanup_confirm_interrupted": "If something interrupts it, such as a crash, a restart or a power cut, nothing beyond the selected items is lost.",
"cleanup_confirm_compacting_title": "Compacting database is a slow operation",
"cleanup_confirm_compacting": "Compacting the database can take several minutes, depending on its size and on the performance of the machine running Trilium. Also, up to {{space}} of free disk space on the machine is temporarily needed (in the data directory and the system's temporary directory).",
- "cleanup_compact_notice": "This operation may take several minutes and Trilium will not respond until it completes."
+ "cleanup_compact_notice": "This operation may take several minutes and Trilium will not respond until it completes.",
+ "compress_title": "Compress images",
+ "compress_quality_value": "{{quality}}%",
+ "compress_convert_lossless": "Convert lossless images to lossy",
+ "compress_convert_lossless_help": "Re-encodes lossless images, such as PNG, as JPEG. This usually saves the most space, but the quality loss is permanent. Images with transparency are left as they are, since JPEG cannot store it.",
+ "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"
},
"note_language": {
"not_set": "No language set",
diff --git a/apps/client/src/widgets/react/Slider.tsx b/apps/client/src/widgets/react/Slider.tsx
index b341871e27..47cec16ec7 100644
--- a/apps/client/src/widgets/react/Slider.tsx
+++ b/apps/client/src/widgets/react/Slider.tsx
@@ -5,6 +5,7 @@ interface SliderProps {
max?: number;
step?: number;
title?: string;
+ disabled?: boolean;
}
export default function Slider({ onChange, value, min = 0, max = 100, ...restProps }: SliderProps) {
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.ts
index 7a21f6c421..e6f094c283 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,6 +18,7 @@ const mocks = vi.hoisted(() => ({
deleteNotes: vi.fn(async (..._args: unknown[]) => true),
downloadFileNote: vi.fn(),
showDetails: vi.fn(),
+ showCompressionDialog: vi.fn(async () => null),
contentChanged: vi.fn(),
post: vi.fn(async (..._args: unknown[]) => undefined),
showMessage: vi.fn(),
@@ -54,6 +55,12 @@ vi.mock("../../../../../services/server", () => ({
default: { post: (...args: unknown[]) => mocks.post(...args) }
}));
+// 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()
+}));
+
vi.mock("../../../../../services/toast", () => ({
default: { showMessage: (...args: unknown[]) => mocks.showMessage(...args) }
}));
@@ -87,6 +94,7 @@ import {
const QUICK_EDIT = "bx bx-edit";
const NEW_TAB = "bx bx-link-external";
const SHOW_DETAILS = "bx bx-detail";
+const COMPRESS_IMAGES = "bx bx-image";
const DOWNLOAD = "bx bx-download";
const EXPORT = "bx bx-export";
const DELETE = "bx bx-trash destructive-action-icon";
@@ -147,7 +155,7 @@ describe("openSpaceUsageContextMenu", () => {
expect(event.preventDefault).toHaveBeenCalled();
expect(event.stopPropagation).toHaveBeenCalled();
// No Download: a text note has no file to save.
- expect(icons()).toEqual([ QUICK_EDIT, NEW_TAB, SHOW_DETAILS, EXPORT, DELETE ]);
+ expect(icons()).toEqual([ QUICK_EDIT, NEW_TAB, SHOW_DETAILS, COMPRESS_IMAGES, EXPORT, DELETE ]);
invoke(QUICK_EDIT);
expect(mocks.triggerCommand)
@@ -160,6 +168,11 @@ 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();
+
invoke(EXPORT);
expect(mocks.triggerCommand).toHaveBeenLastCalledWith("showExportDialog", {
notePath: "root/p/n1",
@@ -210,7 +223,7 @@ describe("openSpaceUsageContextMenu", () => {
await openFor([ "root" ]);
// Not merely struck through: the root can never be deleted, so it is not offered.
- expect(icons()).toEqual([ QUICK_EDIT, NEW_TAB, SHOW_DETAILS, EXPORT ]);
+ expect(icons()).toEqual([ QUICK_EDIT, NEW_TAB, SHOW_DETAILS, COMPRESS_IMAGES, EXPORT ]);
expect(itemByIcon(EXPORT)?.enabled).toBe(false);
// Opening it is still fine.
expect(itemByIcon(QUICK_EDIT)?.enabled).toBeUndefined();
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.ts
index e782fc4867..f21ab9195b 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
@@ -12,6 +12,7 @@ import { downloadFileNote } from "../../../../../services/open";
import options from "../../../../../services/options";
import server from "../../../../../services/server";
import toast from "../../../../../services/toast";
+import { showImageCompressionDialog } from "./image_compression_dialog";
const ROOT_NOTE_ID = "root";
@@ -82,6 +83,12 @@ export async function openSpaceUsageContextMenu(
uiIcon: "bx bx-detail",
handler: () => onShowDetails(notePath)
},
+ {
+ 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()
+ },
{ kind: "separator" },
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.css
new file mode 100644
index 0000000000..8282a37582
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.css
@@ -0,0 +1,8 @@
+.modal.image-compression-dialog {
+ /* Sized by its content rather than to the floor the component sets: no row title wraps, so a
+ long one has to widen the dialog. Capped at the viewport, past which there is nowhere to grow. */
+ .modal-dialog {
+ width: fit-content;
+ max-width: 100%;
+ }
+}
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.tsx
new file mode 100644
index 0000000000..9506624a62
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.spec.tsx
@@ -0,0 +1,284 @@
+import type { ComponentChildren } from "preact";
+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(() => ({
+ // 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
+}));
+
+const mocks = vi.hoisted(() => ({
+ getInt: vi.fn<(name: string) => number | null>(),
+ storedOption: "{}",
+ save: vi.fn(async () => {})
+}));
+
+vi.mock("../../../../../services/options", () => ({
+ default: {
+ get: () => mocks.storedOption,
+ getInt: mocks.getInt,
+ save: mocks.save
+ }
+}));
+
+// 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.
+vi.mock("../../../../../services/i18n", () => ({
+ t: (key: string, params?: Record<string, unknown>) => (params ? `${key} ${JSON.stringify(params)}` : key),
+ translationsInitializedPromise: Promise.resolve(),
+ initLocale: async () => {},
+ getAvailableLocales: () => [],
+ getLocaleById: () => null,
+ getCurrentLanguage: () => "en"
+}));
+
+// The real modal reports its close once the animation is done; the stub reports it as soon as it is
+// told to hide, which is the signal the dialog's own flow keys off.
+vi.mock("../../../../react/Modal", () => ({
+ default: function ModalStub({ children, footer, show, onHidden }: {
+ children: ComponentChildren, footer: ComponentChildren, show: boolean, onHidden: () => void
+ }) {
+ useEffect(() => {
+ if (!show) {
+ onHidden();
+ }
+ // Keyed on the visibility alone: the dialog hands down a fresh closure each render, and
+ // following that identity would report the same close over and over.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [ show ]);
+
+ return show ? <div className="modal-stub">{children}<div className="footer-stub">{footer}</div></div> : null;
+ }
+}));
+
+import { showImageCompressionDialog } from "./image_compression_dialog";
+
+function rows() {
+ return Array.from(document.body.querySelectorAll<HTMLElement>(".image-compression-section"));
+}
+
+function titles() {
+ return rows().map((row) => row.querySelector(".image-compression-section-title")?.textContent);
+}
+
+const numberField = () => document.body.querySelector<HTMLInputElement>(".image-compression-section-number");
+const slider = () => document.body.querySelector<HTMLInputElement>(".slider");
+const qualityReading = () => document.body.querySelector(".image-compression-section-value")?.textContent ?? "";
+const toggles = () => Array.from(document.body.querySelectorAll<HTMLInputElement>(".switch-toggle"));
+const buttons = () => Array.from(document.body.querySelectorAll<HTMLButtonElement>(".footer-stub button"));
+const cancelButton = () => buttons()[0];
+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();
+ await settle();
+ return { closed };
+}
+
+function settle() {
+ return act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+}
+
+async function click(button: HTMLButtonElement | undefined) {
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+}
+
+/** Flips a switch, the way a click on it does. */
+async function toggle(input: HTMLInputElement | null | undefined) {
+ await act(async () => {
+ input?.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+/** Types into a field, the way the user does — the component reads the value off the element. */
+async function type(field: HTMLInputElement | null | undefined, value: string) {
+ await setAndDispatch(field, value, [ "input" ]);
+}
+
+/** Drags a range control: a real drag reports every step as an input and the release as a change. */
+async function drag(range: HTMLInputElement | null | undefined, value: string) {
+ await setAndDispatch(range, value, [ "input", "change" ]);
+}
+
+async function setAndDispatch(field: HTMLInputElement | null | undefined, value: string, events: string[]) {
+ await act(async () => {
+ if (field) {
+ field.value = value;
+ for (const event of events) {
+ field.dispatchEvent(new Event(event, { bubbles: true }));
+ }
+ }
+ });
+}
+
+beforeEach(() => {
+ mocks.storedOption = "{}";
+ vi.clearAllMocks();
+ mocks.getInt.mockImplementation((name) => (
+ name === "imageMaxWidthHeight" ? CONFIGURED_MAX_DIMENSIONS
+ : name === "imageJpegQuality" ? CONFIGURED_QUALITY
+ : null
+ ));
+});
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("showImageCompressionDialog", () => {
+ it("lists the four settings, in reading order", async () => {
+ await openDialog();
+
+ expect(titles()).toEqual([
+ "images.max_image_dimensions",
+ "images.jpeg_quality",
+ "space_usage.compress_convert_lossless",
+ "space_usage.compress_process_child_notes"
+ ]);
+ expect(rows().map(controlOf)).toEqual([ "number", "slider", "toggle", "toggle" ]);
+
+ // Both toggles turn on something with a consequence their label cannot carry — a permanent
+ // quality loss, and a reach past the note the run was invoked on — so each explains itself
+ // beside its title. The two numbered rows say all there is to say in their labels.
+ expect(rows().map((row) => !!row.querySelector(".image-compression-section-title .contextual-help")))
+ .toEqual([ false, false, true, true ]);
+ });
+
+ it("reads the quality out between its title and the slider", async () => {
+ await openDialog();
+
+ // A slider says which way it is going but never where it is, so the row reads
+ // title, value, control — the reading placed before the control it reads.
+ expect(Array.from(rows()[1].children).map((child) => child.classList[0])).toEqual([
+ "image-compression-section-title",
+ "image-compression-section-value",
+ "slider"
+ ]);
+ expect(qualityReading()).toContain(String(CONFIGURED_QUALITY));
+
+ await drag(slider(), "45");
+
+ expect(qualityReading()).toContain("45");
+ });
+
+ it("opens on the image options when the setting has never been written", async () => {
+ await openDialog();
+
+ // Neither number has a default of its own: an unconfigured tool compresses the way
+ // automatic compression is already set to.
+ 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 ]);
+ });
+
+ it("reads a stored answer back, and lets it override the image options", async () => {
+ mocks.storedOption = JSON.stringify({
+ maxWidthHeight: 800, quality: 35, convertLossless: true, processChildNotes: true
+ });
+
+ await openDialog();
+
+ expect(numberField()?.value).toBe("800");
+ expect(slider()?.value).toBe("35");
+ expect(toggles().map((input) => input.checked)).toEqual([ true, true ]);
+ });
+
+ it.each([
+ [ "out of range", { quality: 500 } ],
+ [ "fractional", { quality: 62.5 } ],
+ [ "of the wrong type", { quality: "high" } ]
+ ])("ignores a stored quality that is %s and falls back to the option", async (_label, stored) => {
+ mocks.storedOption = JSON.stringify(stored);
+
+ await openDialog();
+
+ expect(slider()?.value).toBe(String(CONFIGURED_QUALITY));
+ });
+
+ it("ignores a nonsensical stored dimension and falls back to the option", async () => {
+ mocks.storedOption = JSON.stringify({ maxWidthHeight: 0 });
+
+ await openDialog();
+
+ expect(numberField()?.value).toBe(String(CONFIGURED_MAX_DIMENSIONS));
+ });
+
+ it("writes every change straight back, so the next run opens where this one left off", async () => {
+ await openDialog();
+
+ await type(numberField(), "900");
+ await drag(slider(), "45");
+ await toggle(toggles()[0]);
+ await toggle(toggles()[1]);
+
+ // The last write carries the whole set, each change having been folded into the one before.
+ expect(mocks.save).toHaveBeenLastCalledWith("imageCompressionToolOptions", JSON.stringify({
+ maxWidthHeight: 900,
+ quality: 45,
+ convertLossless: true,
+ processChildNotes: true
+ }));
+ });
+
+ it("holds the dimension to at least one pixel, which is the least the server accepts", async () => {
+ await openDialog();
+
+ await type(numberField(), "0");
+
+ expect(numberField()?.value).toBe("1");
+ });
+
+ it("hands back what was asked for once it has closed", async () => {
+ const { closed } = await openDialog();
+
+ await toggle(toggles()[0]);
+ await click(compressButton());
+
+ await expect(closed).resolves.toEqual({
+ maxWidthHeight: CONFIGURED_MAX_DIMENSIONS,
+ quality: CONFIGURED_QUALITY,
+ convertLossless: true,
+ processChildNotes: false
+ });
+ // 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 () => {
+ const { closed } = await openDialog();
+
+ await toggle(toggles()[1]);
+ await click(cancelButton());
+
+ // 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.
+ await expect(closed).resolves.toBeNull();
+ expect(mocks.save).toHaveBeenCalledWith(
+ "imageCompressionToolOptions", expect.stringContaining('"processChildNotes":true'));
+ });
+});
+
+/** Which control a row carries, standing in for the setting it configures. */
+function controlOf(row: HTMLElement) {
+ if (row.querySelector(".image-compression-section-number")) {
+ return "number";
+ }
+ if (row.querySelector(".slider")) {
+ return "slider";
+ }
+
+ return row.querySelector(".switch-toggle") ? "toggle" : "none";
+}
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.tsx
new file mode 100644
index 0000000000..04d98f38c2
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_dialog.tsx
@@ -0,0 +1,92 @@
+import "./image_compression_dialog.css";
+
+import { render } from "preact";
+import { useState } from "preact/hooks";
+
+import { t } from "../../../../../services/i18n";
+import Button from "../../../../react/Button";
+import { Card } from "../../../../react/Card";
+import { useTriliumOptionJson } from "../../../../react/hooks";
+import Modal from "../../../../react/Modal";
+import {
+ type ImageCompressionToolOptions,
+ readImageCompressionOptions
+} from "./image_compression_options";
+import { ImageCompressionSections } 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.
+ *
+ * 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> {
+ return new Promise((resolve) => {
+ const host = document.body.appendChild(document.createElement("div"));
+
+ render(
+ <ImageCompressionDialog onFinished={(options) => {
+ resolve(options);
+ render(null, host);
+ host.remove();
+ }} />,
+ host
+ );
+ });
+}
+
+/**
+ * How the images a note holds 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 }) {
+ const [ shown, setShown ] = useState(true);
+ const [ stored, setStored ] = useTriliumOptionJson<Partial<ImageCompressionToolOptions>>("imageCompressionToolOptions");
+ const [ options, setOptions ] = useState<ImageCompressionToolOptions>(() => readImageCompressionOptions(stored));
+ const update = (patch: Partial<ImageCompressionToolOptions>) => {
+ const next = { ...options, ...patch };
+ setOptions(next);
+ void 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);
+
+ return (
+ <Modal
+ className="image-compression-dialog"
+ title={t("space_usage.compress_title")}
+ size="sm"
+ minWidth={COMPRESSION_DIALOG_MIN_WIDTH}
+ show={shown}
+ onHidden={() => onFinished(confirmed)}
+ footer={<>
+ <Button text={t("space_usage.compress_cancel")} onClick={() => setShown(false)} />
+ <Button
+ text={t("space_usage.compress_run")}
+ kind="primary"
+ onClick={() => {
+ setConfirmed(options);
+ setShown(false);
+ }}
+ />
+ </>}
+ stackable
+ >
+ <Card className="image-compression-settings">
+ <ImageCompressionSections options={options} onChange={update} />
+ </Card>
+ </Modal>
+ );
+}
+
+/**
+ * The width the dialog starts at, narrow on purpose: four 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";
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.ts
new file mode 100644
index 0000000000..3e8c590fbb
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_options.ts
@@ -0,0 +1,79 @@
+import optionService from "../../../../../services/options";
+
+/**
+ * What the image compression tool is set to do. Persisted as JSON in the `imageCompressionToolOptions`
+ * option, so the next run opens on the last answer rather than on a fresh set of defaults.
+ *
+ * The first three mirror the server's `ImageCompressionOptions`; {@link processChildNotes} is the
+ * tool's own, the endpoint acting on one note at a time.
+ */
+export interface ImageCompressionToolOptions {
+ /** Longest edge in pixels: a larger image is scaled down to fit, a smaller one left alone. */
+ 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.
+ */
+ convertLossless: boolean;
+ /** Whether the note's whole subtree is compressed, rather than the note on its own. */
+ processChildNotes: boolean;
+}
+
+/** The bounds the server validates against; the controls here never offer a value it would reject. */
+export const MIN_QUALITY = 10;
+export const MAX_QUALITY = 100;
+export const QUALITY_STEP = 5;
+export const DEFAULT_QUALITY = 75;
+export const MIN_MAX_WIDTH_HEIGHT = 1;
+
+/**
+ * Fills a stored setting out into the full set the dialog works with.
+ *
+ * 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.
+ */
+export function readImageCompressionOptions(
+ stored: Partial<ImageCompressionToolOptions> | null | undefined
+): ImageCompressionToolOptions {
+ return {
+ maxWidthHeight: isPositiveInteger(stored?.maxWidthHeight)
+ ? Number(stored?.maxWidthHeight)
+ : defaultMaxWidthHeight(),
+ quality: isQuality(stored?.quality) ? Number(stored?.quality) : defaultQuality(),
+ convertLossless: stored?.convertLossless === true,
+ processChildNotes: stored?.processChildNotes === true
+ };
+}
+
+/** Where the dimension field starts: whatever automatic compression resizes to. */
+export function defaultMaxWidthHeight(): number {
+ const configured = optionService.getInt("imageMaxWidthHeight");
+
+ return isPositiveInteger(configured) ? Number(configured) : FALLBACK_MAX_WIDTH_HEIGHT;
+}
+
+/** Where the quality slider starts: whatever automatic compression encodes at. */
+export function defaultQuality(): number {
+ const configured = optionService.getInt("imageJpegQuality");
+
+ return isQuality(configured) ? Number(configured) : DEFAULT_QUALITY;
+}
+
+/**
+ * Stands in when the image option itself is unreadable or nonsensical — the same figure it ships
+ * with, so the field opens on a bound that resizes something rather than on one that resizes nothing.
+ */
+const FALLBACK_MAX_WIDTH_HEIGHT = 2000;
+
+function isPositiveInteger(value: unknown): boolean {
+ return Number.isInteger(value) && Number(value) >= MIN_MAX_WIDTH_HEIGHT;
+}
+
+function isQuality(value: unknown): boolean {
+ return Number.isInteger(value) && Number(value) >= MIN_QUALITY && Number(value) <= MAX_QUALITY;
+}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.css
new file mode 100644
index 0000000000..c27768df28
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.css
@@ -0,0 +1,45 @@
+/* One row per setting: title on the leading edge, its control on the trailing one, so a stack of
+ them reads as a column of labels and a column of controls whichever card they were dropped into. */
+.image-compression-section {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+
+ /* Takes the slack, so every control sits at the trailing edge whatever the title — and never
+ gives any back: an unwrapped title is what widens the dialog holding it. */
+ .image-compression-section-title {
+ flex: 1 0 auto;
+ white-space: nowrap;
+ }
+
+ /* Where the slider currently is, which the slider itself cannot say. Fixed-width digits so the
+ row holds still as the value is dragged through. */
+ .image-compression-section-value {
+ flex: 0 0 auto;
+ color: var(--muted-text-color);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ }
+
+ /* Wide enough for a four-digit bound and its unit, and no wider: the pair sizes itself to its
+ content otherwise, which would let the unit's translation move the field. */
+ .tn-number-unit-pair {
+ flex: 0 0 auto;
+ width: 11em;
+ }
+
+ /* Right-aligned so the digits end where the toggles below them do. */
+ .image-compression-section-number {
+ text-align: right;
+ }
+
+ .slider {
+ flex: 0 0 auto;
+ width: 140px;
+ }
+
+ /* The switch brings its own label slot, unused here — the row's own title names the setting. */
+ .switch-widget {
+ flex: 0 0 auto;
+ }
+}
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.tsx
new file mode 100644
index 0000000000..6aa94c1962
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_sections.tsx
@@ -0,0 +1,118 @@
+import "./image_compression_sections.css";
+
+import { t } from "../../../../../services/i18n";
+import { CardSection } from "../../../../react/Card";
+import ContextualHelp from "../../../../react/ContextualHelp";
+import { FormTextBoxWithUnit } from "../../../../react/FormTextBox";
+import FormToggle from "../../../../react/FormToggle";
+import Slider from "../../../../react/Slider";
+import {
+ type ImageCompressionToolOptions,
+ MAX_QUALITY,
+ MIN_MAX_WIDTH_HEIGHT,
+ MIN_QUALITY,
+ QUALITY_STEP
+} 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.
+ *
+ * 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.
+ */
+export interface ImageCompressionSectionProps {
+ options: ImageCompressionToolOptions;
+ onChange(patch: Partial<ImageCompressionToolOptions>): void;
+ /** Greys the controls out, for a host that hangs the whole group off a switch of its own. */
+ 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 (
+ <CardSection className="image-compression-section">
+ <span className="image-compression-section-title">{t("images.max_image_dimensions")}</span>
+ <FormTextBoxWithUnit
+ className="image-compression-section-number"
+ type="number"
+ min={MIN_MAX_WIDTH_HEIGHT}
+ disabled={disabled}
+ unit={t("images.max_image_dimensions_unit")}
+ currentValue={String(options.maxWidthHeight)}
+ onChange={(value) => onChange({
+ maxWidthHeight: Math.max(parseInt(value, 10) || MIN_MAX_WIDTH_HEIGHT, MIN_MAX_WIDTH_HEIGHT)
+ })}
+ />
+ </CardSection>
+ );
+}
+
+/**
+ * The quality re-encoded images are written at. The figure sits between the title and the slider
+ * rather than inside the title: a slider says which way it is going but never where it is, and the
+ * reading belongs beside the control it reads.
+ */
+export function JpegQualitySection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+ return (
+ <CardSection className="image-compression-section">
+ <span className="image-compression-section-title">{t("images.jpeg_quality")}</span>
+ <span className="image-compression-section-value">{t("space_usage.compress_quality_value", { quality: options.quality })}</span>
+ <Slider
+ min={MIN_QUALITY}
+ max={MAX_QUALITY}
+ step={QUALITY_STEP}
+ disabled={disabled}
+ value={options.quality}
+ onChange={(value) => onChange({ quality: value })}
+ />
+ </CardSection>
+ );
+}
+
+/** Whether PNGs may be re-encoded as JPEG — the choice that actually costs quality. */
+export function ConvertLosslessSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+ return (
+ <CardSection className="image-compression-section">
+ <span className="image-compression-section-title">
+ {t("space_usage.compress_convert_lossless")}
+ <ContextualHelp helpMessage={t("space_usage.compress_convert_lossless_help")} />
+ </span>
+ <FormToggle
+ disabled={disabled}
+ currentValue={options.convertLossless}
+ onChange={(value) => onChange({ convertLossless: value })}
+ />
+ </CardSection>
+ );
+}
+
+/** Whether the run reaches past the note it was invoked on, into its whole subtree. */
+export function ProcessChildNotesSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+ return (
+ <CardSection className="image-compression-section">
+ <span className="image-compression-section-title">
+ {t("space_usage.compress_process_child_notes")}
+ <ContextualHelp helpMessage={t("space_usage.compress_process_child_notes_help")} />
+ </span>
+ <FormToggle
+ disabled={disabled}
+ currentValue={options.processChildNotes}
+ onChange={(value) => onChange({ processChildNotes: value })}
+ />
+ </CardSection>
+ );
+}
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index f7c3e86e3d..02c98f217d 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -85,6 +85,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
allowedHtmlTags: string;
/** JSON: what the Content Manager's cleanup tool was last set to erase — see `CleanupToolOptions`. */
cleanupToolOptions: string;
+ /** JSON: how the image compression tool was last set to compress — see `ImageCompressionToolOptions`. */
+ imageCompressionToolOptions: string;
documentId: string;
documentSecret: string;
passwordVerificationHash: string;
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index 4e590647f6..63047a2193 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -124,6 +124,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>([
"backgroundEffects",
"allowedHtmlTags",
"cleanupToolOptions",
+ "imageCompressionToolOptions",
"searchEnableFuzzyMatching",
"searchAutocompleteFuzzy",
"redirectBareDomain",
diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.ts
index 65e95ee5a8..0414d3204e 100644
--- a/packages/trilium-core/src/services/options_init.ts
+++ b/packages/trilium-core/src/services/options_init.ts
@@ -301,6 +301,11 @@ const defaultOptions: DefaultOption[] = [
// picks it, so an uninitialized setting has to mean "nothing selected".
{ name: "cleanupToolOptions", value: "{}", isSynced: true },
+ // Likewise empty: the compression tool fills its dimensions and quality in from the image
+ // options, so an uninitialized setting opens on those rather than on a second set of defaults
+ // that could disagree with them.
+ { name: "imageCompressionToolOptions", value: "{}", isSynced: true },
+
// Share settings
{ name: "redirectBareDomain", value: "false", isSynced: true },
{ name: "showLoginInShareTheme", value: "false", isSynced: true },