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: redo the dialog options
Adorian Doran6e0f3cd5bdce
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 271dcb49b7..1c46addcee 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2918,16 +2918,20 @@"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_reduce_resolution": "Reduce image resolution",- "compress_reduce_resolution_help": "Scales down images that are larger than the given size, keeping their proportions. Images that already fit are left untouched, so on its own this reaches only oversized images.",- "compress_reencode": "Re-encode lossy images",- "compress_reencode_help": "Recompresses images that are already lossy, such as JPEG, at the given quality, whatever their size. They lose a little more quality each time, and the loss is permanent. Lossless images, such as PNG, are not affected by this setting.",- "compress_png_handling": "PNG images",- "compress_png_handling_help": "Only one of these can happen to a given PNG. Keeping it leaves every pixel intact, so only resizing can shrink it. Optimizing reduces it to a palette of 256 colors and writes it back as a PNG: lossy and permanent, though images with few colors, such as screenshots and diagrams, usually look unchanged, and transparency is preserved. Converting to JPEG usually saves the most, but the image stops being a PNG; images with transparency cannot be converted, as JPEG cannot store it, and are optimized instead.",- "compress_png_keep": "Keep as they are",+ "compress_resize": "Resize image",+ "compress_resize_help": "Scales the image down if it is larger than the given size, keeping its proportions. An image that already fits is left untouched, so on its own this reaches only oversized images.",+ "compress_max_dimensions": "Reduce the image size to",+ "compress_jpeg_handling": "JPEG image",+ "compress_jpeg_handling_help": "Keeping it leaves the encoding alone; if it is resized it is written back at a near-lossless quality, so nothing is deliberately given up. Compressing re-encodes it at the given quality whatever its size, which loses a little more each time and cannot be undone.",+ "compress_jpeg_keep": "Keep as it is",+ "compress_jpeg_compress": "Compress",+ "compress_png_handling": "PNG image",+ "compress_png_handling_help": "Only one of these can happen to a PNG. Keeping it leaves every pixel intact, so only resizing can shrink it. Optimizing reduces it to a palette of 256 colors and writes it back as a PNG: lossy and permanent, though images with few colors, such as screenshots and diagrams, usually look unchanged, and transparency is preserved. Converting to JPEG usually saves the most, but the image stops being a PNG; an image with transparency cannot be converted, as JPEG cannot store it, and is optimized instead.",+ "compress_png_keep": "Keep as it is","compress_png_optimize": "Optimize","compress_png_jpeg": "Convert to JPEG","compress_quality": "Quality",+ "compress_unsupported_format": "This image is in a format that cannot be compressed. Only JPEG and PNG images can be.","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",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 a28a86e05e..a3a7e1bb50 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@@ -87,10 +87,14 @@ export async function openSpaceUsageContextMenu(title: t("space_usage.menu_compress_images"),uiIcon: "bx bx-image",handler: () => {+ // An image note *is* one image, so the dialog is told its type and offers only the+ // settings that could reach it; any other note is a collection of however many.+ const mime = note.type === "image" ? note.mime : undefined;+// 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 })+ void showImageCompressionDialog({ type: "note", noteId, mime }).then((result) => result?.compressedCount && onContentChanged());}},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.cssindex 8282a37582..0ad24e8817 100644--- 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@@ -5,4 +5,12 @@width: fit-content;max-width: 100%;}++ /* Two cards, held apart so the split between how the run compresses and how far it reaches+ reads as deliberate rather than as one list with a gap in it. */+ .modal-body {+ display: flex;+ flex-direction: column;+ gap: 16px;+ }}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 e26a283e38..fa869f5f3f 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@@ -93,21 +93,48 @@ vi.mock("../../../../react/Modal", () => ({import { showImageCompressionDialog } from "./image_compression_dialog";import { IMAGE_COMPRESSION_TOAST_ID, type ImageCompressionTarget } from "./image_compression_operation";+/** A note holding whatever it holds; the collection case, where every setting is in play. */const NOTE_TARGET: ImageCompressionTarget = { type: "note", noteId: "n1" };-const ATTACHMENT_TARGET: ImageCompressionTarget = { type: "attachment", attachmentId: "a1" };+/** One image apiece, which is what carrying a mime means. */+const JPEG_IMAGE_TARGET: ImageCompressionTarget = { type: "attachment", attachmentId: "a1", mime: "image/jpeg" };+const PNG_IMAGE_TARGET: ImageCompressionTarget = { type: "attachment", attachmentId: "a1", mime: "image/png" };-function rows() {- return Array.from(document.body.querySelectorAll<HTMLElement>(".image-compression-section"));+function rows(within: ParentNode = document.body) {+ return Array.from(within.querySelectorAll<HTMLElement>(".image-compression-section"));}-function titles() {- return rows().map((row) => row.querySelector(".image-compression-section-title")?.textContent);-}+const titles = () => titlesOf(document.body);+const titlesOf = (within: ParentNode) =>+ rows(within).map((row) => row.querySelector(".image-compression-section-title")?.textContent);+const cards = () => Array.from(document.body.querySelectorAll<HTMLElement>(".modal-stub .tn-card"));const numberField = () => document.body.querySelector<HTMLInputElement>(".image-compression-section-number");const slider = () => document.body.querySelector<HTMLInputElement>(".slider");+const qualityRows = () => rows().filter((row) => !!row.querySelector(".slider"));const qualityReading = () => document.body.querySelector(".image-compression-section-value")?.textContent ?? "";const toggles = () => Array.from(document.body.querySelectorAll<HTMLInputElement>(".switch-toggle"));+const hasHelp = (row: HTMLElement) => !!row.querySelector(".image-compression-section-title .contextual-help");++/** The buttons of one format's choice, the groups being in the order the card lists them. */+const choiceButtons = (group: number) =>+ Array.from(document.body.querySelectorAll<HTMLElement>(".image-compression-section-choice"))+ .map((element) => Array.from(element.querySelectorAll<HTMLButtonElement>("button")))[group] ?? [];++/** How many choice groups precede the PNG one, which is last and so counts from the end. */+const pngGroup = () => document.body.querySelectorAll(".image-compression-section-choice").length - 1;++const chosenOf = (group: number) =>+ choiceButtons(group).find((button) => button.classList.contains("active"))?.textContent?.trim();+const chosenJpeg = () => chosenOf(0);+const chosenPng = () => chosenOf(pngGroup());++async function chooseJpeg(handling: "keep" | "compress") {+ await click(choiceButtons(0)[[ "keep", "compress" ].indexOf(handling)]);+}++async function choosePng(handling: "keep" | "optimize" | "jpeg") {+ await click(choiceButtons(pngGroup())[[ "keep", "optimize", "jpeg" ].indexOf(handling)]);+}const buttons = () => Array.from(document.body.querySelectorAll<HTMLButtonElement>(".footer-stub button"));const cancelButton = () => buttons()[0];const compressButton = () => buttons()[1];@@ -184,31 +211,35 @@ afterEach(() => {});describe("showImageCompressionDialog", () => {- it("leads with each step, the bound nested under the one that measures against it", async () => {+ it("offers each kind of image its own choice, with what qualifies it nested beneath", async () => {await openDialog();expect(titles()).toEqual([- "space_usage.compress_reduce_resolution",- "images.max_image_dimensions",- // One switch per kind of image: recompressing the lossy ones, and letting the lossless- // ones stop being lossless. Neither implies the other.- "space_usage.compress_reencode",- // Straight after the step it governs rather than nested under it: scaling writes a- // JPEG back too, so it is in force for either.- "images.jpeg_quality",- // One exclusive choice, since only one of the three can happen to a given PNG.+ "space_usage.compress_resize",+ "space_usage.compress_max_dimensions",+ // One exclusive choice per kind of image, since only one thing can ever become of a+ // given image — and each brings the quality that governs it alone.+ "space_usage.compress_jpeg_handling",+ "space_usage.compress_quality","space_usage.compress_png_handling","space_usage.compress_process_child_notes"]);expect(rows().map(controlOf))- .toEqual([ "toggle", "number", "toggle", "slider", "choice", "toggle" ]);- expect(rows().map(isNested)).toEqual([ false, true, false, false, false, false ]);-- // Each switch turns on something with a consequence its label cannot carry — what is left- // untouched, a permanent quality loss, a reach past the note the run was invoked on — so- // each explains itself beside its title. The two figures say all there is to say already.- expect(rows().map((row) => !!row.querySelector(".image-compression-section-title .contextual-help")))- .toEqual([ true, false, true, false, true, true ]);+ .toEqual([ "toggle", "number", "choice", "slider", "choice", "toggle" ]);+ expect(rows().map(isNested)).toEqual([ false, true, false, true, false, false ]);++ // Every choice and switch carries a consequence its label cannot — what is left untouched,+ // a permanent loss of quality, a reach past the note the run was invoked on — so each+ // explains itself beside its title. The two figures say all there is to say already.+ expect(rows().map(hasHelp)).toEqual([ true, false, true, false, true, true ]);+ });++ it("puts the reach of the run in a card of its own, apart from how it compresses", async () => {+ await openDialog();++ // Everything in the first card says *how*; the second says how far.+ expect(cards()).toHaveLength(2);+ expect(titlesOf(cards()[1])).toEqual([ "space_usage.compress_process_child_notes" ]);});it("shows the bound only while there is a step that measures against it", async () => {@@ -216,57 +247,34 @@ describe("showImageCompressionDialog", () => {// Reading it off a switch that is off would present a figure still in force.await toggle(toggles()[0]);- expect(titles()).not.toContain("images.max_image_dimensions");expect(numberField()).toBeNull();await toggle(toggles()[0]);expect(numberField()?.value).toBe(String(CONFIGURED_MAX_DIMENSIONS));});- it("keeps the quality up whichever steps are on, being in force for all of them", async () => {+ it("shows each quality only while the choice it qualifies is the one taken", async () => {await openDialog();- await toggle(toggles()[0]);- await toggle(toggles()[1]);- await chooseHandling("keep");-- expect(titles()).toContain("images.jpeg_quality");- expect(slider()).not.toBeNull();- });+ // Opens on compressing JPEGs and optimizing PNGs, so one quality is in force and one is not.+ expect(qualityRows()).toHaveLength(1);- it("shows the conversion quality only while converting is the chosen handling", async () => {- await openDialog();+ await choosePng("jpeg");+ expect(qualityRows()).toHaveLength(2);- // Nested under the choice it qualifies, and under nothing else: it is the one setting that- // governs that handling alone.- expect(titles()).not.toContain("space_usage.compress_quality");-- await chooseHandling("jpeg");- expect(titles()).toContain("space_usage.compress_quality");- expect(rows().map(isNested)).toEqual([ false, true, false, false, false, true, false ]);+ await chooseJpeg("keep");+ expect(qualityRows()).toHaveLength(1);- await chooseHandling("optimize");- expect(titles()).not.toContain("space_usage.compress_quality");+ await choosePng("optimize");+ expect(qualityRows()).toHaveLength(0);});- it("drops the subtree row for an attachment, which has no subtree to reach into", async () => {- await openDialog(ATTACHMENT_TARGET);-- expect(titles()).toEqual([- "space_usage.compress_reduce_resolution",- "images.max_image_dimensions",- "space_usage.compress_reencode",- "images.jpeg_quality",- "space_usage.compress_png_handling"- ]);- });-- it("reads the quality out between its title and the slider", async () => {+ it("reads a 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()[3].children).map((child) => child.classList[0])).toEqual([+ expect(Array.from(qualityRows()[0].children).map((child) => child.classList[0])).toEqual(["image-compression-section-title","image-compression-section-value","slider"@@ -286,42 +294,37 @@ describe("showImageCompressionDialog", () => {expect(numberField()?.value).toBe(String(CONFIGURED_MAX_DIMENSIONS));expect(slider()?.value).toBe(String(CONFIGURED_QUALITY));- // Every step starts on — converting in particular, being where nearly all the saving- // comes from. 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.- expect(toggles().map((input) => input.checked)).toEqual([ true, true, false ]);- // PNGs start on being made smaller without ceasing to be PNGs, which is the least- // surprising thing to do by default.- expect(chosenHandling()).toBe("space_usage.compress_png_optimize");+ // A JPEG is compressed and a PNG is made smaller without ceasing to be one — the least+ // surprising thing to do to each. Reaching into the subtree is not assumed: that widens+ // what the run touches rather than how hard it compresses, and a child may be a clone.+ expect(chosenJpeg()).toBe("space_usage.compress_jpeg_compress");+ expect(chosenPng()).toBe("space_usage.compress_png_optimize");+ expect(toggles().map((input) => input.checked)).toEqual([ true, false ]);});- it("keeps a stored answer of off for a step, rather than reasserting the default", async () => {- mocks.storedOption = JSON.stringify({ reencode: false, pngHandling: "keep" });-- await openDialog();-- expect(toggles().map((input) => input.checked)).toEqual([ true, false, false ]);- expect(chosenHandling()).toBe("space_usage.compress_png_keep");- });-- it("falls back to optimizing on a stored handling it does not recognise", async () => {- mocks.storedOption = JSON.stringify({ pngHandling: "shrink" });+ it("keeps a stored answer, rather than reasserting the defaults over it", async () => {+ mocks.storedOption = JSON.stringify({+ maxWidthHeight: 800, quality: 35, jpegHandling: "keep", pngHandling: "keep",+ processChildNotes: true+ });await openDialog();- expect(chosenHandling()).toBe("space_usage.compress_png_optimize");+ expect(numberField()?.value).toBe("800");+ expect(chosenJpeg()).toBe("space_usage.compress_jpeg_keep");+ expect(chosenPng()).toBe("space_usage.compress_png_keep");+ expect(toggles().map((input) => input.checked)).toEqual([ true, true ]);});- it("reads a stored answer back, and lets it override the image options", async () => {- mocks.storedOption = JSON.stringify({- maxWidthHeight: 800, quality: 35, reencode: false, processChildNotes: true- });+ it.each([+ [ "an unknown JPEG handling", { jpegHandling: "squash" }, "space_usage.compress_jpeg_compress" ],+ [ "an unknown PNG handling", { pngHandling: "shrink" }, "space_usage.compress_png_optimize" ]+ ])("falls back to the default on %s", async (_label, stored, expected) => {+ mocks.storedOption = JSON.stringify(stored);await openDialog();- expect(numberField()?.value).toBe("800");- expect(slider()?.value).toBe("35");- expect(toggles().map((input) => input.checked)).toEqual([ true, false, true ]);+ expect([ chosenJpeg(), chosenPng() ]).toContain(expected);});it.each([@@ -349,15 +352,15 @@ describe("showImageCompressionDialog", () => {await type(numberField(), "900");await drag(slider(), "45");+ await chooseJpeg("keep");+ await choosePng("jpeg");await toggle(toggles()[1]);- await chooseHandling("jpeg");- await toggle(toggles()[2]);// The last write carries the whole set, each change having been folded into the one before.expect(mocks.save).toHaveBeenLastCalledWith("imageCompressionToolOptions", JSON.stringify({resize: true,maxWidthHeight: 900,- reencode: false,+ jpegHandling: "keep",pngHandling: "jpeg",quality: 45,conversionQuality: 85,@@ -365,19 +368,19 @@ describe("showImageCompressionDialog", () => {}));});- it("offers no run at all once every step is switched off", async () => {+ it("offers no run at all once nothing is asked of anything", async () => {await openDialog();await toggle(toggles()[0]);- await toggle(toggles()[1]);- await chooseHandling("keep");+ await chooseJpeg("keep");+ await choosePng("keep");// Every image would be visited and none of them changed; a button that provably does// nothing is not one to offer.expect(compressButton()?.disabled).toBe(true);// Any one of them is enough to make the run worth offering again.- await chooseHandling("optimize");+ await choosePng("optimize");expect(compressButton()?.disabled).toBe(false);});@@ -392,7 +395,7 @@ describe("showImageCompressionDialog", () => {it("hands back nothing when the user backs out, settings remembered all the same", async () => {const { closed } = await openDialog();- await toggle(toggles()[2]);+ await toggle(toggles()[1]);await click(cancelButton());// The answer is "no run", and nothing was asked of the server — but the settings are kept@@ -404,11 +407,72 @@ describe("showImageCompressionDialog", () => {});});+describe("a single image rather than a note's collection", () => {+ it("offers only the choice for its own format, and nothing about a subtree", async () => {+ await openDialog(JPEG_IMAGE_TARGET);++ // A lone JPEG can never be reached by anything the PNG choice says, so offering it would+ // be offering a setting that cannot apply. And one image has no subtree to descend into.+ expect(titles()).toEqual([+ "space_usage.compress_resize",+ "space_usage.compress_max_dimensions",+ "space_usage.compress_jpeg_handling",+ "space_usage.compress_quality"+ ]);+ expect(cards()).toHaveLength(1);+ });++ it("offers the PNG choice for a PNG, and its conversion quality when converting", async () => {+ await openDialog(PNG_IMAGE_TARGET);++ expect(titles()).toEqual([+ "space_usage.compress_resize",+ "space_usage.compress_max_dimensions",+ "space_usage.compress_png_handling"+ ]);++ await choosePng("jpeg");+ expect(titles()).toContain("space_usage.compress_quality");+ });++ it("treats an image note as one image, the same as an attachment", async () => {+ await openDialog({ type: "note", noteId: "n1", mime: "image/png" });++ expect(titles()).not.toContain("space_usage.compress_jpeg_handling");+ expect(titles()).not.toContain("space_usage.compress_process_child_notes");+ });++ it("says why it has nothing to offer for a format it cannot compress", async () => {+ await openDialog({ type: "attachment", attachmentId: "a1", mime: "image/gif" });++ expect(titles()).toEqual([+ "space_usage.compress_resize",+ "space_usage.compress_max_dimensions"+ ]);+ expect(document.body.querySelector(".image-compression-notice")?.textContent)+ .toBe("space_usage.compress_unsupported_format");++ // And nothing on offer could reach it, so there is no run to offer either.+ expect(compressButton()?.disabled).toBe(true);+ });++ it("offers no run for a lone JPEG once its own choice is the only one left off", async () => {+ await openDialog(JPEG_IMAGE_TARGET);++ await toggle(toggles()[0]);+ await chooseJpeg("keep");++ // The PNG setting is still stored as "optimize", but it could never reach this image, so+ // it must not count as work either.+ expect(compressButton()?.disabled).toBe(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()[2]);+ await toggle(toggles()[1]);await click(compressButton());await closed;@@ -416,7 +480,7 @@ describe("running the compression", () => {expect(postedBody()).toEqual({resize: true,maxWidthHeight: CONFIGURED_MAX_DIMENSIONS,- reencode: true,+ jpegHandling: "compress",pngHandling: "optimize",quality: CONFIGURED_QUALITY,conversionQuality: 85,@@ -424,19 +488,20 @@ describe("running the compression", () => {});});- it("sends a step that was switched off as switched off, rather than leaving it out", async () => {+ it("sends a choice that was narrowed as narrowed, rather than leaving it out", async () => {const { closed } = await openDialog();await toggle(toggles()[0]);+ await chooseJpeg("keep");await click(compressButton());await closed;- // The server defaults an omitted step to on, so silence would ask for the opposite.- expect(postedBody()).toMatchObject({ resize: false, reencode: true, pngHandling: "optimize" });+ // The server defaults an omitted setting to acting, so silence would ask for the opposite.+ expect(postedBody()).toMatchObject({ resize: false, jpegHandling: "keep", pngHandling: "optimize" });});it("sends nothing about subtrees to the attachment endpoint, which has no use for it", async () => {- const { closed } = await openDialog(ATTACHMENT_TARGET);+ const { closed } = await openDialog(JPEG_IMAGE_TARGET);await click(compressButton());await closed;@@ -511,21 +576,6 @@ describe("running the compression", () => {});});-/** The segmented choice buttons, in the order they are offered. */-const choiceButtons = () =>- Array.from(document.body.querySelectorAll<HTMLButtonElement>(".image-compression-section-choice button"));--/** The label of the choice currently highlighted. */-function chosenHandling() {- return choiceButtons().find((button) => button.classList.contains("active"))?.textContent?.trim();-}--/** Picks a handling by its position, the way a click on that button does. */-async function chooseHandling(handling: "keep" | "optimize" | "jpeg") {- const index = [ "keep", "optimize", "jpeg" ].indexOf(handling);- await click(choiceButtons()[index]);-}-/** Whether a row is drawn as qualifying the one above it rather than standing beside it. */function isNested(row: HTMLElement) {return row.classList.contains("image-compression-section-nested");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 5b54a46e92..f01a47bcae 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@@ -11,9 +11,11 @@ import { Card } from "../../../../react/Card";import { useTriliumOptionJson } from "../../../../react/hooks";import Modal from "../../../../react/Modal";import {+ compressibleFormatsOf,compressionResultMessage,IMAGE_COMPRESSION_TOAST_ID,type ImageCompressionTarget,+ isSingleImage,runImageCompression} from "./image_compression_operation";import {@@ -22,11 +24,11 @@ import {readImageCompressionOptions} from "./image_compression_options";import {- JpegQualitySection,+ JpegHandlingSection,PngHandlingSection,ProcessChildNotesSection,- ReduceResolutionSection,- ReencodeImagesSection+ ResizeImageSection,+ UnsupportedFormatNotice} from "./image_compression_sections";/**@@ -75,6 +77,11 @@ function ImageCompressionDialog({ target, onFinished }: {const pending = useRef<ImageCompressionToolOptions | null>(null);const sectionProps = { options, onChange: update };+ // A single image is offered only the settings that could reach it: the choice for its own+ // format and nothing about the other, since neither could ever act on it. A note is offered+ // both, holding whatever it holds.+ const formats = compressibleFormatsOf(target);+async function runPendingCompression() {const settings = pending.current;@@ -120,9 +127,9 @@ function ImageCompressionDialog({ target, onFinished }: {<Buttontext={t("space_usage.compress_run")}kind="primary"- // Neither step switched on would visit every image and change none of them:- // a run that provably does nothing is not one to offer.- disabled={!hasWorkToDo(options)}+ // Nothing asked of anything this target holds would visit every image and+ // change none of them: a run that provably does nothing is not one to offer.+ disabled={!hasWorkToDo(options, target)}onClick={() => {pending.current = options;setShown(false);@@ -132,16 +139,21 @@ function ImageCompressionDialog({ target, onFinished }: {stackable><Card className="image-compression-settings">- <ReduceResolutionSection {...sectionProps} />- <ReencodeImagesSection {...sectionProps} />- {/* Straight after the step it governs, rather than under it: scaling a JPEG has to- write one back too, so it is in force for either. */}- <JpegQualitySection {...sectionProps} />- {/* Last of the three, since converting brings a quality of its own nested beneath. */}- <PngHandlingSection {...sectionProps} />- {/* An attachment is one image; there is no subtree under it to reach into. */}- {target.type === "note" && <ProcessChildNotesSection {...sectionProps} />}+ <ResizeImageSection {...sectionProps} />+ {formats.includes("jpeg") && <JpegHandlingSection {...sectionProps} />}+ {formats.includes("png") && <PngHandlingSection {...sectionProps} />}+ {/* A single image of a format nothing here can act on: the dialog is open, and why+ it has nothing to offer is the one thing worth saying. */}+ {formats.length === 0 && <UnsupportedFormatNotice />}</Card>++ {/* A card of its own: everything above says *how* to compress, this says how far the+ run reaches. Absent for a single image, which has no subtree to reach into. */}+ {!isSingleImage(target) && (+ <Card className="image-compression-scope">+ <ProcessChildNotesSection {...sectionProps} />+ </Card>+ )}</Modal>);}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.tsindex 326a7f338f..92aaa690e2 100644--- 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.ts@@ -6,12 +6,44 @@ 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.+ * What a compression run acts on: a whole note — the images its attachments hold — or a single+ * image picked out on its own, which may be an image note or an image attachment.+ *+ * `mime` is what tells the two apart. Present, the target *is* one image of that type, and the+ * dialog can offer only the settings that could reach it; absent, the target is a note holding+ * however many images of whatever types, and every setting is in play.*/export type ImageCompressionTarget =- | { type: "note"; noteId: string }- | { type: "attachment"; attachmentId: string };+ | { type: "note"; noteId: string; mime?: string }+ | { type: "attachment"; attachmentId: string; mime: string };++/** The formats a run can act on at all, which is what the settings are ultimately about. */+export type CompressibleFormat = "jpeg" | "png";++/**+ * Which formats the settings could reach on this target: the one format of a single image, both for+ * a note holding a collection, and neither for a single image of a type nothing here can compress —+ * a GIF, a WebP, an SVG.+ *+ * A collection is answered with both without looking: what a note actually holds is not known until+ * the run visits it, and offering only what is there would mean measuring the note to open a dialog.+ */+export function compressibleFormatsOf(target: ImageCompressionTarget): CompressibleFormat[] {+ if (target.mime === undefined) {+ return [ "jpeg", "png" ];+ }++ if (target.mime === "image/jpeg") {+ return [ "jpeg" ];+ }++ return target.mime === "image/png" ? [ "png" ] : [];+}++/** Whether the dialog is configuring one named image rather than whatever a note happens to hold. */+export function isSingleImage(target: ImageCompressionTarget): boolean {+ return target.mime !== undefined;+}/** 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";@@ -35,7 +67,7 @@ export function runImageCompression(return server.postWithTimeout<ImageCompressionResponse>(url, COMPRESSION_TIMEOUT_MS, {resize: options.resize,maxWidthHeight: options.maxWidthHeight,- reencode: options.reencode,+ jpegHandling: options.jpegHandling,pngHandling: options.pngHandling,quality: options.quality,conversionQuality: options.conversionQuality,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 d0f0400a3d..0220a0156e 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@@ -1,6 +1,7 @@-import { IMAGE_PNG_HANDLINGS, type ImagePngHandling } from "@triliumnext/commons";+import { IMAGE_JPEG_HANDLINGS, IMAGE_PNG_HANDLINGS, type ImageJpegHandling, type ImagePngHandling } from "@triliumnext/commons";import optionService from "../../../../../services/options";+import { compressibleFormatsOf, type ImageCompressionTarget } from "./image_compression_operation";/*** What the image compression tool is set to do. Persisted as JSON in the `imageCompressionToolOptions`@@ -14,8 +15,8 @@ export interface ImageCompressionToolOptions {resize: boolean;/** Longest edge in pixels. Only consulted when {@link resize} is on. */maxWidthHeight: number;- /** Whether an already-lossy image (JPEG) is recompressed even when nothing needs scaling. */- reencode: boolean;+ /** What becomes of an already-lossy image (JPEG): left as encoded, or recompressed. */+ jpegHandling: ImageJpegHandling;/** What becomes of a lossless image (PNG): left alone, quantized in place, or converted. */pngHandling: ImagePngHandling;/** JPEG quality, {@link MIN_QUALITY} to {@link MAX_QUALITY}, for an already-lossy image. */@@ -27,11 +28,18 @@ export interface ImageCompressionToolOptions {}/**- * Whether the settings amount to anything at all. With nothing asked of either kind of image, every- * one of them would be visited and left exactly as it was, so the run is not one worth offering.+ * Whether the settings amount to anything at all. Only what the target can actually be reached by+ * counts: asking for PNGs to be optimized says nothing about a lone JPEG, and a format the run+ * cannot touch at all is not made reachable by any setting.+ *+ * Without this, a run would be offered that visits every image and changes none of them.*/-export function hasWorkToDo(options: ImageCompressionToolOptions): boolean {- return options.resize || options.reencode || options.pngHandling !== "keep";+export function hasWorkToDo(options: ImageCompressionToolOptions, target: ImageCompressionTarget): boolean {+ const formats = compressibleFormatsOf(target);++ return (options.resize && formats.length > 0)+ || (formats.includes("jpeg") && options.jpegHandling !== "keep")+ || (formats.includes("png") && options.pngHandling !== "keep");}/** The bounds the server validates against; the controls here never offer a value it would reject. */@@ -61,8 +69,8 @@ export function readImageCompressionOptions(maxWidthHeight: isPositiveInteger(stored?.maxWidthHeight)? Number(stored?.maxWidthHeight): defaultMaxWidthHeight(),- reencode: stored?.reencode ?? true,- pngHandling: readPngHandling(stored?.pngHandling),+ jpegHandling: readHandling(stored?.jpegHandling, IMAGE_JPEG_HANDLINGS, "compress"),+ pngHandling: readHandling(stored?.pngHandling, IMAGE_PNG_HANDLINGS, "optimize"),quality: isQuality(stored?.quality) ? Number(stored?.quality) : defaultQuality(),conversionQuality: isQuality(stored?.conversionQuality)? Number(stored?.conversionQuality)@@ -98,9 +106,9 @@ const FALLBACK_MAX_WIDTH_HEIGHT = 2000;*/export const DEFAULT_CONVERSION_QUALITY = 85;-/** Anything unrecognised falls back to optimizing, the choice that changes an image least. */-function readPngHandling(value: unknown): ImagePngHandling {- return IMAGE_PNG_HANDLINGS.includes(value as ImagePngHandling) ? value as ImagePngHandling : "optimize";+/** Anything unrecognised falls back to the default, rather than to whichever choice comes first. */+function readHandling<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {+ return allowed.includes(value as T) ? value as T : fallback;}function isPositiveInteger(value: unknown): boolean {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.cssindex d30c13d87a..1019a1ffd2 100644--- 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@@ -56,3 +56,13 @@.image-compression-section-nested .image-compression-section-title {color: var(--muted-text-color);}++/* Prose rather than a row of controls, so none of the row layout applies to it. A fit-content+ dialog takes its width from the longest unbroken line in it, and this sentence would otherwise+ be that line; containment says the part that is true — this row's width does not depend on what+ is written in it — so the dialog is sized by the rows that should size it. */+.image-compression-notice {+ contain: inline-size;+ color: var(--muted-text-color);+ font-size: 0.85em;+}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 dd4c644912..d3f690e609 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@@ -1,6 +1,6 @@import "./image_compression_sections.css";-import { IMAGE_PNG_HANDLINGS } from "@triliumnext/commons";+import { IMAGE_JPEG_HANDLINGS, IMAGE_PNG_HANDLINGS } from "@triliumnext/commons";import clsx from "clsx";import { t } from "../../../../../services/i18n";@@ -19,13 +19,13 @@ import {} from "./image_compression_options";/**- * 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.+ * The rows that configure an image compression run, each a `CardSection` of its own so a host shows+ * only the ones that mean anything where it stands — the dialog drops the subtree row for a single+ * image, and drops a format's row entirely when the image being compressed is not of that format.*- * A figure is nested under a switch only where it qualifies that switch alone — the bound under- * scaling, which is the only step that measures against it. The JPEG quality stands on its own,- * being in force for every step that writes a JPEG, which is all of them.+ * Each format is one exclusive choice rather than a set of switches, because only one thing can+ * ever become of a given image. What qualifies a choice is nested beneath it and appears only while+ * that choice is the one taken, so nothing on screen is a figure no longer in force.** 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.@@ -38,11 +38,11 @@ export interface ImageCompressionSectionProps {}/**- * Scaling oversized images down, with the bound they are scaled to. The bound appears only while- * the step is on: with it off nothing is measured against it, so a figure sitting there would read- * as one still in force.+ * Scaling an oversized image down, with the bound it is scaled to. The bound appears only while the+ * step is on: with it off nothing is measured against it, so a figure sitting there would read as+ * one still in force.*/-export function ReduceResolutionSection(props: ImageCompressionSectionProps) {+export function ResizeImageSection(props: ImageCompressionSectionProps) {const { options, onChange, disabled } = props;return (@@ -52,8 +52,8 @@ export function ReduceResolutionSection(props: ImageCompressionSectionProps) {subSections={[ <MaxImageDimensionsSection key="max-dimensions" {...props} /> ]}><span className="image-compression-section-title">- {t("space_usage.compress_reduce_resolution")}- <ContextualHelp helpMessage={t("space_usage.compress_reduce_resolution_help")} />+ {t("space_usage.compress_resize")}+ <ContextualHelp helpMessage={t("space_usage.compress_resize_help")} /></span><FormToggledisabled={disabled}@@ -64,11 +64,11 @@ export function ReduceResolutionSection(props: ImageCompressionSectionProps) {);}-/** The bound images are scaled down to fit. Labelled as the image settings label it. */+/** The bound an image is scaled down to fit. */export function MaxImageDimensionsSection({ options, onChange, disabled }: ImageCompressionSectionProps) {return (<CardSection className="image-compression-section image-compression-section-nested">- <span className="image-compression-section-title">{t("images.max_image_dimensions")}</span>+ <span className="image-compression-section-title">{t("space_usage.compress_max_dimensions")}</span><FormTextBoxWithUnitclassName="image-compression-section-number"type="number"@@ -85,36 +85,40 @@ export function MaxImageDimensionsSection({ options, onChange, disabled }: Image}/**- * Recompressing images that are already lossy, at whatever {@link JpegQualitySection} is set to.- * Says nothing about lossless ones — that is {@link ConvertLosslessSection}'s to answer.+ * What becomes of an already-lossy image. Recompressing brings its own quality with it, nested+ * underneath — it governs that choice and nothing else, an image merely being scaled going out at a+ * near-lossless quality of the server's own.*/-export function ReencodeImagesSection({ options, onChange, disabled }: ImageCompressionSectionProps) {+export function JpegHandlingSection(props: ImageCompressionSectionProps) {+ const { options, onChange } = props;+return (- <CardSection className="image-compression-section">- <span className="image-compression-section-title">- {t("space_usage.compress_reencode")}- <ContextualHelp helpMessage={t("space_usage.compress_reencode_help")} />- </span>- <FormToggle- disabled={disabled}- currentValue={options.reencode}- onChange={(value) => onChange({ reencode: value })}+ <CardSection+ className="image-compression-section"+ subSectionsVisible={options.jpegHandling === "compress"}+ subSections={[ <JpegQualitySection key="quality" {...props} /> ]}+ >+ <HandlingChoice+ {...props}+ title={t("space_usage.compress_jpeg_handling")}+ help={t("space_usage.compress_jpeg_handling_help")}+ values={IMAGE_JPEG_HANDLINGS}+ currentValue={options.jpegHandling}+ labelKey="compress_jpeg"+ onChoose={(jpegHandling) => onChange({ jpegHandling })}/></CardSection>);}/**- * What becomes of a PNG — one exclusive choice rather than a set of switches, because only one of- * the three can ever happen to a given image: it survives as it is, survives smaller, or stops- * being a PNG. Two toggles would claim they combine, and they do not.- *- * Converting brings its own quality with it, nested underneath: it is the only setting that- * qualifies this choice alone, and someone converting a pristine original may well want more- * quality here than they would spend recompressing an image that is already lossy.+ * What becomes of a lossless image — one exclusive choice, because only one of the three can ever+ * happen to it: it survives as it is, survives smaller, or stops being a PNG. Converting brings its+ * own quality with it, nested underneath, since someone converting a pristine original may well+ * want more quality there than they would spend recompressing something already lossy.*/export function PngHandlingSection(props: ImageCompressionSectionProps) {- const { options, onChange, disabled } = props;+ const { options, onChange } = props;return (<CardSection@@ -122,51 +126,37 @@ export function PngHandlingSection(props: ImageCompressionSectionProps) {subSectionsVisible={options.pngHandling === "jpeg"}subSections={[ <ConversionQualitySection key="conversion-quality" {...props} /> ]}>- <span className="image-compression-section-title">- {t("space_usage.compress_png_handling")}- <ContextualHelp helpMessage={t("space_usage.compress_png_handling_help")} />- </span>- <SegmentedChoice- className="image-compression-section-choice"- currentValue={disabled ? "" : options.pngHandling}- options={IMAGE_PNG_HANDLINGS.map((value) => ({- value,- label: t(`space_usage.compress_png_${value}`)- }))}- onChange={(value) => !disabled && onChange({ pngHandling: value })}+ <HandlingChoice+ {...props}+ title={t("space_usage.compress_png_handling")}+ help={t("space_usage.compress_png_handling_help")}+ values={IMAGE_PNG_HANDLINGS}+ currentValue={options.pngHandling}+ labelKey="compress_png"+ onChoose={(pngHandling) => onChange({ pngHandling })}/></CardSection>);}-/** The quality a converted PNG is written at, kept apart from the recompression quality above. */-export function ConversionQualitySection({ options, onChange, disabled }: ImageCompressionSectionProps) {+/** The quality an already-lossy image is recompressed at. */+export function JpegQualitySection({ options, onChange, disabled }: ImageCompressionSectionProps) {return (<QualitySlider- label={t("space_usage.compress_quality")}- value={options.conversionQuality}+ value={options.quality}disabled={disabled}- onChange={(value) => onChange({ conversionQuality: value })}- nested+ onChange={(quality) => onChange({ quality })}/>);}-/**- * The quality any JPEG is written at. A row in its own right rather than a qualifier of the- * re-encoding step, because it governs more than that step does: scaling a JPEG has to write one- * back whether or not re-encoding was asked for, so the quality is in force there too.- *- * 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) {+/** The quality a converted lossless image is written at, kept apart from the one above. */+export function ConversionQualitySection({ options, onChange, disabled }: ImageCompressionSectionProps) {return (<QualitySlider- label={t("images.jpeg_quality")}- value={options.quality}+ value={options.conversionQuality}disabled={disabled}- onChange={(value) => onChange({ quality: value })}+ onChange={(conversionQuality) => onChange({ conversionQuality })}/>);}@@ -189,21 +179,60 @@ export function ProcessChildNotesSection({ options, onChange, disabled }: ImageC}/**- * The row shared by both qualities: a title, the current figure, and the slider it reads.+ * Said in place of a format's choice when the image being compressed is of neither kind the run can+ * act on. Better than an empty card: the dialog opened, and the reason nothing is on offer is the+ * one thing it can usefully say.+ */+export function UnsupportedFormatNotice() {+ return (+ <CardSection className="image-compression-notice">+ {t("space_usage.compress_unsupported_format")}+ </CardSection>+ );+}++/** The title, help and buttons every format choice is made of. */+function HandlingChoice<T extends string>({ title, help, values, currentValue, labelKey, onChoose, disabled }: {+ title: string;+ help: string;+ values: readonly T[];+ currentValue: T;+ /** Prefix of the translation key naming each choice, completed with the value itself. */+ labelKey: string;+ onChoose: (value: T) => void;+} & ImageCompressionSectionProps) {+ return (+ <>+ <span className="image-compression-section-title">+ {title}+ <ContextualHelp helpMessage={help} />+ </span>+ <SegmentedChoice+ className="image-compression-section-choice"+ // A disabled group highlights nothing rather than showing a choice it will not take.+ currentValue={disabled ? "" : currentValue}+ options={values.map((value) => ({ value, label: t(`space_usage.${labelKey}_${value}`) }))}+ onChange={(value) => !disabled && onChoose(value)}+ />+ </>+ );+}++/**+ * The row both qualities are made of: a title, the current figure, and the slider it reads.** The figure sits between the two 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.+ * going but never where it is, and the reading belongs beside the control it reads. Always nested,+ * each quality qualifying exactly one choice above it.*/-function QualitySlider({ label, value, onChange, disabled, nested }: {- label: string;+function QualitySlider({ value, onChange, disabled }: {value: number;onChange: (value: number) => void;disabled?: boolean;- nested?: boolean;}) {return (- <CardSection className={clsx("image-compression-section", nested && "image-compression-section-nested")}>- <span className="image-compression-section-title">{label}</span>+ <CardSection className={clsx("image-compression-section", "image-compression-section-nested")}>+ <span className="image-compression-section-title">{t("space_usage.compress_quality")}</span><span className="image-compression-section-value">{t("space_usage.compress_quality_value", { quality: value })}</span>diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex 12f2ba39dc..01d8a67680 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -295,7 +295,7 @@ describe("compression parameters", () => {[ "a quality above the maximum", { quality: 101 } ],[ "a non-integer quality", { quality: 75.5 } ],[ "a non-boolean resize", { resize: "yes" } ],- [ "a non-boolean reencode", { reencode: "yes" } ],+ [ "an unknown jpegHandling", { jpegHandling: "loads" } ],[ "an unknown pngHandling", { pngHandling: "shrink" } ],[ "a conversion quality out of range", { conversionQuality: 5 } ]])("400s on %s", async (_label, body) => {@@ -310,7 +310,7 @@ describe("compression parameters", () => {const noteId = await createImageNote(smallPng);expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: [ 1, 2 ] })).status).toBe(400);- expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: "reencode" })).status).toBe(400);+ expect((await api.post(`/api/notes/${noteId}/compress-images`, { body: "jpegHandling" })).status).toBe(400);});it("treats a missing body as a request to compress without changing formats", async () => {@@ -329,7 +329,7 @@ describe("compression parameters", () => {const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {body: {- resize: false, reencode: false, pngHandling: "keep", maxWidthHeight: 10+ resize: false, jpegHandling: "keep", pngHandling: "keep", maxWidthHeight: 10}});@@ -340,8 +340,8 @@ describe("compression parameters", () => {});it.each([- [ "the lossy one", { reencode: true, pngHandling: "keep" }, "jpeg.jpg" ],- [ "the lossless one", { reencode: false, pngHandling: "jpeg" }, "png.png" ]+ [ "the lossy one", { jpegHandling: "compress", pngHandling: "keep" }, "jpeg.jpg" ],+ [ "the lossless one", { jpegHandling: "keep", pngHandling: "jpeg" }, "png.png" ]])("reaches only its own kind of image with %s switched on", async (_label, body, expected) => {const { noteId } = await createTextNote(api);await addAttachment(noteId, "png.png", noisyPng);diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.tsindex 5aa66fc321..49a94e7906 100644--- a/apps/server/src/services/image_provider.spec.ts+++ b/apps/server/src/services/image_provider.spec.ts@@ -259,7 +259,7 @@ describe('serverImageProvider.compressImage', () => {/** Every parameter is explicit, so nothing here depends on the stored options. */function request(overrides: Partial<ImageCompressionRequest> = {}): ImageCompressionRequest {return {- resize: true, maxWidthHeight: 2000, reencode: true, pngHandling: "optimize",+ resize: true, maxWidthHeight: 2000, jpegHandling: "compress", pngHandling: "optimize",quality: 75, conversionQuality: 85, ...overrides};}@@ -368,7 +368,7 @@ describe('serverImageProvider.compressImage', () => {it('never touches a JPEG, whichever handling is chosen', async () => {for (const pngHandling of [ 'keep', 'optimize', 'jpeg' ] as const) {const outcome = await serverImageProvider.compressImage(- noisyJpeg, request({ reencode: false, pngHandling }));+ noisyJpeg, request({ jpegHandling: "keep", pngHandling }));expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });}@@ -400,15 +400,24 @@ describe('serverImageProvider.compressImage', () => {expect(coarse.buffer.byteLength).toBeLessThan(fine.buffer.byteLength);});- it('writes a scaled JPEG at the recompression quality with every re-encoding step off', async () => {- // Scaling has to write a JPEG back whatever the settings say, so that quality governs- // this too — which is why it is not nested under the recompression step.- const off = { reencode: false, pngHandling: 'keep' as const, maxWidthHeight: 300 };- const coarse = await serverImageProvider.compressImage(noisyJpeg, request({ ...off, quality: 20 }));- const fine = await serverImageProvider.compressImage(noisyJpeg, request({ ...off, quality: 80 }));+ it('writes a scaled JPEG near-losslessly when its handling is "keep"', async () => {+ // Scaling has to write a JPEG back whatever the settings say, but "keep" is not a place+ // to quietly apply a quality nobody asked for — the slider is hidden under it in the+ // dialog, so it must not be in force either. Moving it changes nothing here.+ const kept = { jpegHandling: 'keep' as const, maxWidthHeight: 300 };+ const atLow = await serverImageProvider.compressImage(noisyJpeg, request({ ...kept, quality: 20 }));+ const atHigh = await serverImageProvider.compressImage(noisyJpeg, request({ ...kept, quality: 80 }));- if (!coarse.compressed || !fine.compressed) throw new Error('expected both to compress');- expect(coarse.buffer.byteLength).toBeLessThan(fine.buffer.byteLength);+ if (!atLow.compressed || !atHigh.compressed) throw new Error('expected both to compress');+ expect(atLow.buffer.byteLength).toBe(atHigh.buffer.byteLength);++ // And it comes out above what recompressing at a high quality would have chosen, so+ // "keep" gives up the scaling and nothing else.+ const compressed = await serverImageProvider.compressImage(+ noisyJpeg, request({ jpegHandling: 'compress', maxWidthHeight: 300, quality: 80 }));++ if (!compressed.compressed) throw new Error('expected it to compress');+ expect(atLow.buffer.byteLength).toBeGreaterThan(compressed.buffer.byteLength);});});@@ -418,7 +427,7 @@ describe('serverImageProvider.compressImage', () => {])('changes nothing about %s when every step is off', async (_label, getBuffer) => {const outcome = await serverImageProvider.compressImage(getBuffer(),- request({ resize: false, reencode: false, pngHandling: 'keep', maxWidthHeight: 10 })+ request({ resize: false, jpegHandling: "keep", pngHandling: 'keep', maxWidthHeight: 10 }));expect(outcome).toEqual({ compressed: false, reason: 'no-gain' });diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex c7feafaf95..1cfeba54c3 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -171,10 +171,10 @@ export const serverImageProvider: ImageProvider = {// covers both `optimize` and a transparent image that `jpeg` could not take.const quantize = isLossless && !toJpeg && request.pngHandling !== "keep";- // Whether re-encoding alone is worth doing to *this* image: a lossy source is recompressed- // if `reencode` says so, a lossless one when its handling asks for anything at all —- // rewriting a PNG as the same PNG at its own size gains nothing.- const worthReencoding = isLossless ? (toJpeg || quantize) : request.reencode;+ // Whether re-encoding alone is worth doing to *this* image, each kind answering for itself:+ // a lossy source when its handling asks for it, a lossless one when its handling asks for+ // anything at all — rewriting a PNG as the same PNG at its own size gains nothing.+ const worthReencoding = isLossless ? (toJpeg || quantize) : request.jpegHandling === "compress";if (!needsResize && !worthReencoding) {return { compressed: false, reason: "no-gain" };@@ -194,10 +194,7 @@ export const serverImageProvider: ImageProvider = {// Reached either by conversion, which has already established there is no transparency// to lose, or by a JPEG source, which never had any to begin with.image.background = 0xffffffff;- // Converting a pristine original and recompressing an already-lossy one are different- // trades, so each is written at its own quality.- const quality = isLossless ? request.conversionQuality : request.quality;- result = await image.getBuffer("image/jpeg", { quality });+ result = await image.getBuffer("image/jpeg", { quality: jpegQualityFor(request, isLossless) });} else if (quantize) {result = quantizePng(image, buffer.byteLength);} else {@@ -215,6 +212,29 @@ export const serverImageProvider: ImageProvider = {}};+/**+ * Which of the two qualities a JPEG about to be written is owed. Converting a pristine original and+ * recompressing an already-lossy one are different trades, so each has its own.+ *+ * The third case has neither: a JPEG that is only being scaled, its handling left on `keep`. It has+ * to be re-encoded all the same — there is no way to write scaled pixels without one — so it goes+ * out at {@link RESIZE_QUALITY}, high enough that "keep" is not quietly made to mean "degrade".+ */+function jpegQualityFor(request: ImageCompressionRequest, isLossless: boolean): number {+ if (isLossless) {+ return request.conversionQuality;+ }++ return request.jpegHandling === "compress" ? request.quality : RESIZE_QUALITY;+}++/**+ * What a JPEG is re-encoded at when nothing asked for it to be recompressed and only the scaling+ * forced a rewrite. Near enough to lossless that the loss is not the point of the operation, while+ * still far below the size a quality of 100 would produce for no visible return.+ */+const RESIZE_QUALITY = 92;+/*** Rewrites the image as a palette PNG, which is where a PNG's weight actually goes: the saving* comes from storing an index per pixel instead of 24-bit colour, not from discarding detail. Thediff --git a/apps/standalone/src/services/image_provider.spec.ts b/apps/standalone/src/services/image_provider.spec.tsindex 8d02a3de8c..5684a0197d 100644--- a/apps/standalone/src/services/image_provider.spec.ts+++ b/apps/standalone/src/services/image_provider.spec.ts@@ -85,8 +85,8 @@ describe("standaloneImageProvider.compressImage", () => {await expect(standaloneImageProvider.compressImage(buffer, {- resize: true, maxWidthHeight: 100, reencode: true, convertLossless: true,- optimizePNG: true, quality: 75+ resize: true, maxWidthHeight: 100, jpegHandling: "compress", pngHandling: "optimize",+ quality: 75, conversionQuality: 85})).resolves.toEqual({ compressed: false, reason: "unsupported-platform" });});diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 64cb954ec6..6168063bb3 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -296,6 +296,11 @@ export const IMAGE_PNG_HANDLINGS = [ "keep", "optimize", "jpeg" ] as const;export type ImagePngHandling = (typeof IMAGE_PNG_HANDLINGS)[number];+/** The two things that can become of an already-lossy image; see {@link ImageCompressionOptions}. */+export const IMAGE_JPEG_HANDLINGS = [ "keep", "compress" ] as const;++export type ImageJpegHandling = (typeof IMAGE_JPEG_HANDLINGS)[number];+export interface ImageCompressionOptions {/*** Whether an image larger than {@link maxWidthHeight} is scaled down to fit. On its own this@@ -308,14 +313,17 @@ export interface ImageCompressionOptions {/** Longest edge in pixels. Omitted, it falls back to the `imageMaxWidthHeight` option. */maxWidthHeight?: number;/**- * Whether an image that is *already* lossy — a JPEG — is recompressed at {@link quality} even- * when nothing needs scaling. It costs quality every time it runs, on an image that has already- * paid that cost once.+ * What is done with an image that is *already* lossy — a JPEG:+ *+ * - `keep` leaves its encoding alone. Scaling still has to write a JPEG back, but at a quality+ * high enough not to be a further deliberate degradation.+ * - `compress` recompresses it at {@link quality}, whatever its size. It costs quality every+ * time it runs, on an image that has already paid that cost once.*- * Says nothing about lossless sources, which is {@link convertLossless}'s to answer: the two- * are separate choices, and squeezing the JPEGs harder is no reason to stop a PNG being a PNG.+ * Says nothing about lossless sources, which is {@link pngHandling}'s to answer: squeezing the+ * JPEGs harder is no reason to stop a PNG being a PNG. Defaults to `compress`.*/- reencode?: boolean;+ jpegHandling?: ImageJpegHandling;/*** What is done with a lossless image — a PNG. Only ever one of the three, since a PNG either* survives as it is, survives smaller, or stops being a PNG:@@ -332,8 +340,9 @@ export interface ImageCompressionOptions {*/pngHandling?: ImagePngHandling;/**- * JPEG quality, 10 to 100, used when recompressing an image that is *already* lossy — and when- * scaling one, which has to write a JPEG back whatever {@link reencode} says.+ * JPEG quality, 10 to 100, used when recompressing an image that is *already* lossy — so only+ * where {@link jpegHandling} is `compress`. A JPEG merely being scaled is written back at a+ * near-lossless quality of the implementation's own instead, `keep` meaning what it says.** Omitted, it falls back to the `imageJpegQuality` option (75 by default).*/diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex 88ae7baba6..5cc75cd789 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -11,7 +11,7 @@* recompressed belongs to the platform's {@link ImageProvider}.*/-import { getImageAttachmentTitle, IMAGE_PNG_HANDLINGS, type ImageCompressionItem, type ImageCompressionOptions, type ImageCompressionResponse, type ImageCompressionSkipReason } from "@triliumnext/commons";+import { getImageAttachmentTitle, IMAGE_JPEG_HANDLINGS, IMAGE_PNG_HANDLINGS, type ImageCompressionItem, type ImageCompressionOptions, type ImageCompressionResponse, type ImageCompressionSkipReason } from "@triliumnext/commons";import becca from "../becca/becca.js";import type BAttachment from "../becca/entities/battachment.js";@@ -70,7 +70,7 @@ export async function compressAttachmentImage(attachmentId: string, options?: Im* failing the request — the caller did not choose that value and cannot fix it from here.*/export function resolveCompressionRequest(options: ImageCompressionOptions = {}): ImageCompressionRequest {- const { resize, maxWidthHeight, reencode, pngHandling, quality, conversionQuality } = options;+ const { resize, maxWidthHeight, jpegHandling, pngHandling, quality, conversionQuality } = options;if (maxWidthHeight !== undefined && (!Number.isInteger(maxWidthHeight) || maxWidthHeight < MIN_MAX_WIDTH_HEIGHT)) {throw new ValidationError(`maxWidthHeight must be an integer of ${MIN_MAX_WIDTH_HEIGHT} or above.`);@@ -79,11 +79,8 @@ export function resolveCompressionRequest(options: ImageCompressionOptions = {})requireQuality(quality, "quality");requireQuality(conversionQuality, "conversionQuality");requireBoolean(resize, "resize");- requireBoolean(reencode, "reencode");-- if (pngHandling !== undefined && !IMAGE_PNG_HANDLINGS.includes(pngHandling)) {- throw new ValidationError(`pngHandling must be one of: ${IMAGE_PNG_HANDLINGS.join(", ")}.`);- }+ requireOneOf(jpegHandling, IMAGE_JPEG_HANDLINGS, "jpegHandling");+ requireOneOf(pngHandling, IMAGE_PNG_HANDLINGS, "pngHandling");return {// Every step defaults to acting: a request that named none of them asked for the images to@@ -91,7 +88,7 @@ export function resolveCompressionRequest(options: ImageCompressionOptions = {})// being made smaller without ceasing to be one.resize: resize ?? true,maxWidthHeight: maxWidthHeight ?? optionService.getOptionInt("imageMaxWidthHeight"),- reencode: reencode ?? true,+ jpegHandling: jpegHandling ?? "compress",pngHandling: pngHandling ?? "optimize",quality: quality ?? defaultQuality(),conversionQuality: conversionQuality ?? DEFAULT_CONVERSION_QUALITY@@ -104,6 +101,12 @@ function requireBoolean(value: unknown, name: string) {}}+function requireOneOf<T extends string>(value: T | undefined, allowed: readonly T[], name: string) {+ if (value !== undefined && !allowed.includes(value)) {+ throw new ValidationError(`${name} must be one of: ${allowed.join(", ")}.`);+ }+}+function requireQuality(value: number | undefined, name: string) {if (value !== undefined && (!Number.isInteger(value) || value < MIN_QUALITY || value > MAX_QUALITY)) {throw new ValidationError(`${name} must be an integer between ${MIN_QUALITY} and ${MAX_QUALITY}.`);diff --git a/packages/trilium-core/src/services/image_provider.ts b/packages/trilium-core/src/services/image_provider.tsindex 7429d320a3..b9ae9ef6a1 100644--- a/packages/trilium-core/src/services/image_provider.ts+++ b/packages/trilium-core/src/services/image_provider.ts@@ -4,7 +4,7 @@* Standalone uses simple format detection without compression.*/-import type { ImageCompressionSkipReason, ImagePngHandling } from "@triliumnext/commons";+import type { ImageCompressionSkipReason, ImageJpegHandling, ImagePngHandling } from "@triliumnext/commons";export interface ImageFormat {ext: string;@@ -25,11 +25,11 @@ export interface ImageCompressionRequest {resize: boolean;/** Longest edge in pixels. Only consulted when {@link resize} is on. */maxWidthHeight: number;- /** Whether an already-lossy image (JPEG) is recompressed even when nothing needs scaling. */- reencode: boolean;+ /** What becomes of an already-lossy image (JPEG): left as encoded, or recompressed. */+ jpegHandling: ImageJpegHandling;/** What becomes of a lossless image (PNG): left alone, quantized in place, or converted. */pngHandling: ImagePngHandling;- /** JPEG quality, 10 to 100, for recompressing or scaling an already-lossy image. */+ /** JPEG quality, 10 to 100, for recompressing an already-lossy image. */quality: number;/** JPEG quality, 10 to 100, for converting a lossless image. */conversionQuality: number;