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: display image stats
Adorian Doran10b05b6d2def
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 1c46addcee..993e928b09 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2917,6 +2917,27 @@"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.","compress_title": "Compress images",+ "compress_summary_reading": "Reading…",+ "compress_summary_failed": "Could not read what is here.",+ "compress_summary_scope_one": "{{title}}, {{count}} descendant note",+ "compress_summary_scope_other": "{{title}}, {{count}} descendant notes",+ "compress_summary_none": "No images.",+ "compress_summary_total_one": "{{count}} image occupying {{size}}.",+ "compress_summary_total_other": "{{count}} images occupying {{size}}.",+ "compress_summary_format_one": "{{count}} {{format}} file ({{size}})",+ "compress_summary_format_other": "{{count}} {{format}} files ({{size}})",+ "compress_summary_oversized_one": "{{count}} image above {{bound}} pixels",+ "compress_summary_oversized_other": "{{count}} images above {{bound}} pixels",+ "compress_summary_compressible_one": "{{count}} compressible image",+ "compress_summary_compressible_other": "{{count}} compressible images",+ "compress_summary_unreadable_one": "{{count}} image could not be read",+ "compress_summary_unreadable_other": "{{count}} images could not be read",+ "compress_format_unknown": "Unrecognized",+ "compress_info_file": "{{format}} file, {{size}}",+ "compress_info_pixels": "{{width}}x{{height}} pixels",+ "compress_info_bits": "{{bits}} bits per pixel",+ "compress_info_transparency": "transparency used",+ "compress_info_quality": "quality {{quality}}","compress_quality_value": "{{quality}}%","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.",diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex 2b7cc7d265..dcc72a0082 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -1943,3 +1943,20 @@ export function useDelayedVisibility(active: boolean, { graceMs = 150, minVisiblreturn phase;}++/**+ * Trails `value` by `delay`, so a field being typed in does not fire a request per keystroke.+ *+ * For a reading that costs the server real work and is only worth taking once the user has stopped+ * changing what it is a reading of.+ */+export function useDebouncedValue<T>(value: T, delay: number): T {+ const [ settled, setSettled ] = useState(value);++ useEffect(() => {+ const timer = setTimeout(() => setSettled(value), delay);+ return () => clearTimeout(timer);+ }, [ value, delay ]);++ return settled;+}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsxindex 5e7c3f0367..bb10896c2e 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx@@ -16,7 +16,7 @@ import DonutChart, { type DonutRing } from "../../../../react/charts/DonutChart"import ContextualHelp from "../../../../react/ContextualHelp";import FormTextBox from "../../../../react/FormTextBox";import FormToggle from "../../../../react/FormToggle";-import { useTriliumOptionJson } from "../../../../react/hooks";+import { useDebouncedValue, useTriliumOptionJson } from "../../../../react/hooks";import Modal from "../../../../react/Modal";import {CLEANUP_ITEMS,@@ -372,15 +372,3 @@ const DONUT_THICKNESS = 40;/** Long enough to type a two-digit retention through without measuring the database twice. */const ESTIMATE_DEBOUNCE_MS = 500;--/** Trails `value` by `delay`, so a field being typed in does not fire a measurement per keystroke. */-function useDebouncedValue<T>(value: T, delay: number): T {- const [ settled, setSettled ] = useState(value);-- useEffect(() => {- const timer = setTimeout(() => setSettled(value), delay);- return () => clearTimeout(timer);- }, [ value, delay ]);-- return settled;-}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 2eaff290c4..7d14c2283f 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@@ -24,6 +24,10 @@ function resultOf(count: number, originalSize: number, newSize: number) {const mocks = vi.hoisted(() => ({storedOption: "{}",+ /** URLs the summary asked for, in order, so a re-reading can be told from a first reading. */+ read: [] as string[],+ inventory: {} as Record<string, unknown>,+ info: {} as Record<string, unknown>,save: vi.fn(async () => {}),postWithTimeout: vi.fn<(...args: unknown[]) => Promise<unknown>>(async () => EMPTY_RESULT),showMessage: vi.fn<(message: string, timeout?: number) => void>(),@@ -40,7 +44,17 @@ vi.mock("../../../../../services/options", () => ({vi.mock("../../../../../services/server", () => ({default: {- get: async () => [],+ // The summary reads one of these before the dialog can draw anything. Everything else the+ // app loads on the way past — the keyboard actions among them — expects a list.+ get: async (url: string) => {+ if (!url.includes("image-info") && !url.includes("image-inventory")) {+ return [];+ }++ mocks.read.push(url);++ return url.includes("image-info") ? mocks.info : mocks.inventory;+ },postWithTimeout: (url: string, _timeoutMs: number, body?: object) => mocks.postWithTimeout(url, body)}}));@@ -94,10 +108,21 @@ import {/** A note holding whatever it holds; the collection case, where every setting is in play. */const NOTE_TARGET: ImageCompressionTarget = { type: "note", noteId: "n1" };-/** One image apiece, which is what carrying a mime means. */-const JPEG_IMAGE_TARGET: ImageCompressionTarget = { type: "attachment", attachmentId: "a1", mime: "image/jpeg" };+/**+ * One image apiece. Carrying a mime is what marks a target as a single image; which format it is+ * comes from the reading, so these deliberately carry the non-standard mime Trilium itself writes+ * for a JPEG — nothing may depend on it being a real one.+ */+const JPEG_IMAGE_TARGET: ImageCompressionTarget = { type: "attachment", attachmentId: "a1", mime: "image/jpg" };const PNG_IMAGE_TARGET: ImageCompressionTarget = { type: "attachment", attachmentId: "a1", mime: "image/png" };+/** Opens a single-image dialog on an image the reading will report as the given format. */+async function openImageDialog(format: string, compressible = true) {+ mocks.info = { ...mocks.info, format, compressible };++ return openDialog(format === "jpg" ? JPEG_IMAGE_TARGET : PNG_IMAGE_TARGET);+}+function rows(within: ParentNode = document.body) {return Array.from(within.querySelectorAll<HTMLElement>(".image-compression-section"));}@@ -144,6 +169,9 @@ const compressButton = () => buttons()[1];*/async function openDialog(target: ImageCompressionTarget = NOTE_TARGET) {const closed = showImageCompressionDialog(target);+ // Two turns: the summary's reading is requested by an effect on mount and applied when it+ // resolves, and a macrotask turn drains the microtasks between them.+ await settle();await settle();return { closed };}@@ -196,6 +224,28 @@ async function setAndDispatch(field: HTMLInputElement | null | undefined, value:beforeEach(() => {mocks.storedOption = "{}";+ mocks.read = [];+ mocks.inventory = {+ title: "Holiday", noteCount: 1,+ total: { count: 4, size: 4000 },+ compressible: { count: 3, size: 3000 },+ oversized: { count: 1, size: 1000 },+ formats: [+ { format: "jpg", count: 2, size: 2000 },+ { format: "png", count: 1, size: 1000 },+ // Counted and listed, but nothing here can act on it — so it earns no setting.+ { format: "webp", count: 1, size: 1000 }+ ],+ compressibleFormats: [ "jpg", "png" ],+ maxWidthHeight: DEFAULT_MAX_WIDTH_HEIGHT,+ unreadable: 0+ };+ mocks.info = {+ entityType: "attachment", entityId: "a1", title: "shot.png",+ mime: "image/png", format: "png", detectedMime: "image/png",+ size: 2048, width: 1920, height: 1080,+ bitDepth: 8, channels: 4, hasAlpha: true, indexed: false, quality: null, compressible: true+ };vi.clearAllMocks();mocks.postWithTimeout.mockResolvedValue(EMPTY_RESULT);});@@ -401,9 +451,183 @@ describe("showImageCompressionDialog", () => {});});+describe("offering only what there are images for", () => {+ it("drops the JPEG choice for a note holding none", async () => {+ mocks.inventory = { ...mocks.inventory, compressibleFormats: [ "png" ] };++ await openDialog();++ expect(titles()).not.toContain("space_usage.compress_jpeg_handling");+ expect(titles()).toContain("space_usage.compress_png_handling");+ });++ it("drops the PNG choice for a note holding none", async () => {+ mocks.inventory = { ...mocks.inventory, compressibleFormats: [ "jpg" ] };++ await openDialog();++ expect(titles()).toContain("space_usage.compress_jpeg_handling");+ expect(titles()).not.toContain("space_usage.compress_png_handling");+ });++ it("drops every setting, resizing included, when nothing there can be compressed", async () => {+ // Four images, none of them a format a run could act on.+ mocks.inventory = { ...mocks.inventory, compressibleFormats: [] };++ await openDialog();++ expect(titles()).toEqual([ "space_usage.compress_process_child_notes" ]);+ expect(compressButton()?.disabled).toBe(true);+ });++ it("keeps the reach on offer, so a note can still be looked into", async () => {+ mocks.inventory = { ...mocks.inventory, compressibleFormats: [] };++ await openDialog();++ // The one setting that can change the answer: what is not here may be below.+ expect(cards()).toHaveLength(1);+ expect(titlesOf(cards()[0])).toEqual([ "space_usage.compress_process_child_notes" ]);+ });++ it("brings the settings back once descending finds something", async () => {+ mocks.inventory = { ...mocks.inventory, compressibleFormats: [] };+ await openDialog();+ expect(compressButton()?.disabled).toBe(true);++ mocks.inventory = { ...mocks.inventory, compressibleFormats: [ "jpg" ] };+ // With nothing on offer, the reach is the only switch there is.+ await toggle(toggles()[0]);+ await settle();+ await settle();++ expect(titles()).toContain("space_usage.compress_jpeg_handling");+ expect(compressButton()?.disabled).toBe(false);+ });++});++describe("the reading above the settings", () => {+ const summaryLines = () => Array.from(+ document.body.querySelectorAll<HTMLElement>(".image-compression-summary > *")+ ).map((line) => line.textContent);++ it("names the note and says what its images amount to", async () => {+ await openDialog();++ expect(summaryLines()).toEqual([+ "Holiday",+ 'space_usage.compress_summary_total {"count":4,"size":"3.91 KiB"}',+ // One clause per format, then the two figures the settings above are about.+ 'space_usage.compress_summary_format {"count":2,"format":"JPEG","size":"1.95 KiB"}, '+ + 'space_usage.compress_summary_format {"count":1,"format":"PNG","size":"1000 B"}, '+ + 'space_usage.compress_summary_format {"count":1,"format":"WEBP","size":"1000 B"}, '+ + 'space_usage.compress_summary_oversized {"count":1,"bound":1920}, '+ + 'space_usage.compress_summary_compressible {"count":3}.'+ ]);+ });++ it("says how far past the note it reached, once it reached anywhere", async () => {+ mocks.inventory = { ...mocks.inventory, noteCount: 21 };+ mocks.storedOption = JSON.stringify({ processChildNotes: true });++ await openDialog();++ // Twenty-one notes visited is the note itself plus twenty below it.+ expect(summaryLines()[0]).toBe('space_usage.compress_summary_scope {"title":"Holiday","count":20}');+ });++ it("names the note alone when descending reached no further", async () => {+ mocks.storedOption = JSON.stringify({ processChildNotes: true });++ await openDialog();++ expect(summaryLines()[0]).toBe("Holiday");+ });++ it("says so plainly when there is nothing to compress", async () => {+ mocks.inventory = {+ ...mocks.inventory,+ total: { count: 0, size: 0 }, compressible: { count: 0, size: 0 },+ oversized: { count: 0, size: 0 }, formats: [], compressibleFormats: []+ };++ await openDialog();++ // A breakdown of nothing would be a row of zeroes rather than an answer.+ expect(summaryLines()).toEqual([ "Holiday", "space_usage.compress_summary_none" ]);+ });++ it("mentions what it could not read, and only then", async () => {+ mocks.inventory = { ...mocks.inventory, unreadable: 2 };++ await openDialog();++ expect(summaryLines()[2]).toContain('space_usage.compress_summary_unreadable {"count":2}');+ });++ it("re-reads when the reach changes, since that is part of what the figures mean", async () => {+ await openDialog();+ expect(mocks.read).toEqual([ `notes/n1/image-inventory?recursive=false&maxWidthHeight=${DEFAULT_MAX_WIDTH_HEIGHT}` ]);++ await toggle(toggles()[1]);+ await settle();++ expect(mocks.read).toContain(`notes/n1/image-inventory?recursive=true&maxWidthHeight=${DEFAULT_MAX_WIDTH_HEIGHT}`);+ });++ it("re-reads when the bound changes, but only once the typing has stopped", async () => {+ await openDialog();+ await type(numberField(), "800");++ // The keystroke itself asks for nothing: a four-digit bound would otherwise cost four+ // readings of the note on its way to the one the user meant.+ expect(mocks.read).toHaveLength(1);++ await vi.waitFor(+ () => expect(mocks.read).toContain("notes/n1/image-inventory?recursive=false&maxWidthHeight=800"),+ { timeout: 3000 }+ );+ });++ it("reads nothing about a subtree for a single image, and describes the image instead", async () => {+ await openDialog(PNG_IMAGE_TARGET);++ expect(mocks.read).toEqual([ "attachments/a1/image-info" ]);+ expect(summaryLines()).toEqual([+ "shot.png",+ // Type and size read as one line rather than two.+ 'space_usage.compress_info_file {"format":"PNG","size":"2 KiB"}',+ 'space_usage.compress_info_pixels {"width":1920,"height":1080}, '+ + 'space_usage.compress_info_bits {"bits":32}, '+ + "space_usage.compress_info_transparency"+ ]);+ });++ it("leaves out what the header did not state", async () => {+ mocks.info = {+ ...mocks.info, format: "gif", width: 100, height: 50,+ bitDepth: null, channels: null, hasAlpha: null, quality: null+ };++ await openDialog({ type: "attachment", attachmentId: "a1", mime: "image/gif" });++ // A size it could read, and nothing guessed at for the rest.+ expect(summaryLines()[2]).toBe('space_usage.compress_info_pixels {"width":100,"height":50}');+ });++ it("says a JPEG has been squeezed already, which is what decides whether to squeeze it more", async () => {+ mocks.info = { ...mocks.info, format: "jpg", channels: 3, hasAlpha: false, quality: 62 };++ await openDialog(JPEG_IMAGE_TARGET);++ expect(summaryLines()[2]).toContain('space_usage.compress_info_quality {"quality":62}');+ });+});+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);+ await openImageDialog("jpg");// 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.@@ -417,7 +641,7 @@ describe("a single image rather than a note's collection", () => {});it("offers the PNG choice for a PNG, and its conversion quality when converting", async () => {- await openDialog(PNG_IMAGE_TARGET);+ await openImageDialog("png");expect(titles()).toEqual(["space_usage.compress_resize",@@ -430,6 +654,7 @@ describe("a single image rather than a note's collection", () => {});it("treats an image note as one image, the same as an attachment", async () => {+ mocks.info = { ...mocks.info, format: "png", compressible: true };await openDialog({ type: "note", noteId: "n1", mime: "image/png" });expect(titles()).not.toContain("space_usage.compress_jpeg_handling");@@ -437,21 +662,19 @@ describe("a single image rather than a note's collection", () => {});it("says why it has nothing to offer for a format it cannot compress", async () => {+ mocks.info = { ...mocks.info, format: "gif", compressible: false };await openDialog({ type: "attachment", attachmentId: "a1", mime: "image/gif" });- expect(titles()).toEqual([- "space_usage.compress_resize",- "space_usage.compress_max_dimensions"- ]);+ // Not even resizing: it acts on the same two formats as everything else, so a GIF is out+ // of its reach too and a row offering it would be a control that does nothing.+ expect(titles()).toEqual([]);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 openImageDialog("jpg");await toggle(toggles()[0]);await chooseJpeg("keep");@@ -495,6 +718,7 @@ describe("running the compression", () => {});it("sends nothing about subtrees to the attachment endpoint, which has no use for it", async () => {+ mocks.info = { ...mocks.info, format: "jpg" };const { closed } = await openDialog(JPEG_IMAGE_TARGET);await click(compressButton());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 f01a47bcae..f5a9dae57f 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,7 +11,6 @@ import { Card } from "../../../../react/Card";import { useTriliumOptionJson } from "../../../../react/hooks";import Modal from "../../../../react/Modal";import {- compressibleFormatsOf,compressionResultMessage,IMAGE_COMPRESSION_TOAST_ID,type ImageCompressionTarget,@@ -30,6 +29,11 @@ import {ResizeImageSection,UnsupportedFormatNotice} from "./image_compression_sections";+import {+ ImageCompressionSummary,+ readableFormats,+ useCompressionReading+} from "./image_compression_summary";/*** Opens the image compression dialog for one note or one attachment, and resolves once the run it@@ -77,10 +81,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);+ // Nothing is offered until the reading says there is something for it to act on: a format with+ // no images of it behind it is a setting with nothing to apply it to, and a run configured+ // entirely out of such settings would visit every image and change none of them.+ const reading = useCompressionReading(target, options);+ const formats = readableFormats(target, reading);async function runPendingCompression() {const settings = pending.current;@@ -127,9 +132,10 @@ function ImageCompressionDialog({ target, onFinished }: {<Buttontext={t("space_usage.compress_run")}kind="primary"- // 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)}+ // Nothing asked of anything actually here would visit every image and change+ // none of them: a run that provably does nothing is not one to offer. Also+ // covers the reading still being in flight, when nothing is yet known.+ disabled={!hasWorkToDo(options, formats)}onClick={() => {pending.current = options;setShown(false);@@ -138,14 +144,25 @@ function ImageCompressionDialog({ target, onFinished }: {</>}stackable>- <Card className="image-compression-settings">- <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>+ <ImageCompressionSummary reading={reading} recursive={options.processChildNotes} />++ {/* Only what there are images for. Scaling goes with them: it acts on the same formats+ and nothing else, so with none of them present it has nothing to scale either. */}+ {formats.length > 0 && (+ <Card className="image-compression-settings">+ <ResizeImageSection {...sectionProps} />+ {formats.includes("jpg") && <JpegHandlingSection {...sectionProps} />}+ {formats.includes("png") && <PngHandlingSection {...sectionProps} />}+ </Card>+ )}++ {/* Said only of one named image, whose format is the whole reason there is nothing to+ offer. For a note the reading above has already listed what it holds. */}+ {isSingleImage(target) && reading.info && formats.length === 0 && (+ <Card className="image-compression-settings">+ <UnsupportedFormatNotice />+ </Card>+ )}{/* A card of its own: everything above says *how* to compress, this says how far therun reaches. Absent for a single image, which has no subtree to reach into. */}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 92aaa690e2..c86559a521 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@@ -17,30 +17,13 @@ export type ImageCompressionTarget =| { 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.+ * Whether the dialog is configuring one named image rather than whatever a note happens to hold.*- * 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.+ * The mime is read only for this — as a marker that the target *is* one image. What format that+ * image actually is comes from its content, never from here: an image note Trilium saved itself+ * carries `image/jpg`, which is not a real mime type at all.*/-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;}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 05b8377ce1..ee793c1c27 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,4 @@-import { IMAGE_JPEG_HANDLINGS, IMAGE_PNG_HANDLINGS, type ImageJpegHandling, type ImagePngHandling } from "@triliumnext/commons";--import { compressibleFormatsOf, type ImageCompressionTarget } from "./image_compression_operation";+import { IMAGE_JPEG_HANDLINGS, IMAGE_PNG_HANDLINGS, type ImageCompressibleFormat, type ImageJpegHandling, type ImagePngHandling } from "@triliumnext/commons";/*** What the image compression tool is set to do. Persisted as JSON in the `imageCompressionToolOptions`@@ -27,17 +25,16 @@ export interface ImageCompressionToolOptions {}/**- * 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.+ * Whether the settings amount to anything, given the formats actually there to be acted on. Asking+ * for PNGs to be optimized says nothing about a note holding only JPEGs, and nothing asked of a+ * format that is not present is work.*- * Without this, a run would be offered that visits every image and changes none of them.+ * An empty list is therefore never work — which covers a reading still in flight as well as one+ * that found nothing, and in neither case is there a run worth offering yet.*/-export function hasWorkToDo(options: ImageCompressionToolOptions, target: ImageCompressionTarget): boolean {- const formats = compressibleFormatsOf(target);-+export function hasWorkToDo(options: ImageCompressionToolOptions, formats: ImageCompressibleFormat[]): boolean {return (options.resize && formats.length > 0)- || (formats.includes("jpeg") && options.jpegHandling !== "keep")+ || (formats.includes("jpg") && options.jpegHandling !== "keep")|| (formats.includes("png") && options.pngHandling !== "keep");}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_summary.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_summary.cssnew file mode 100644index 0000000000..23c452f95f--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_summary.css@@ -0,0 +1,24 @@+/* Sits above the cards as a reading rather than a control, so it carries no card frame of its own —+ only the spacing that keeps it from reading as part of the first one. */+.image-compression-summary {+ display: flex;+ flex-direction: column;+ gap: 2px;++ /* A fit-content dialog takes its width from the longest unbroken line in it, and the breakdown+ sentence would otherwise be that line. Containment says the part that is true — this block's+ width does not depend on what is written in it — so the dialog is sized by the rows that+ should size it, and the sentence wraps to whatever width that leaves. */+ contain: inline-size;+}++/* The name of what is about to be acted on: the one line that has to be read before the rest. */+.image-compression-summary-title {+ font-weight: 600;+ overflow-wrap: anywhere;+}++.image-compression-summary-detail {+ 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_summary.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_summary.tsxnew file mode 100644index 0000000000..9e29f9b72d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/image_compression_summary.tsx@@ -0,0 +1,214 @@+import "./image_compression_summary.css";++import {+ IMAGE_COMPRESSIBLE_FORMATS,+ type ImageCompressibleFormat,+ type ImageInfoResponse,+ type ImageInventoryResponse+} from "@triliumnext/commons";++import { t } from "../../../../../services/i18n";+import { formatSize } from "../../../../../services/utils";+import { useDebouncedValue } from "../../../../react/hooks";+import { type ImageCompressionTarget, isSingleImage } from "./image_compression_operation";+import type { ImageCompressionToolOptions } from "./image_compression_options";+import { useSpaceUsageFetch } from "./use_space_usage_fetch";++/**+ * What the dialog is about to act on, read before it acts and before it offers anything: the note+ * and what its images weigh, or the one image and what it is.+ *+ * A reading rather than a prediction — it says what is there, never what compressing would save.+ * The figures that depend on the settings (what counts as oversized, how far the run reaches) are+ * re-read as those settings change, so nothing on screen describes a run other than the one the+ * buttons would start.+ */+export interface CompressionReading {+ /** Present for a single image, and only then. */+ info: ImageInfoResponse | null;+ /** Present for a note, and only then. */+ inventory: ImageInventoryResponse | null;+ /** The reading did not arrive; nothing is known and nothing should be offered. */+ failed: boolean;+}++/**+ * Takes the one reading the dialog is built on. Which endpoint depends on the target, but the fetch+ * itself does not, so it is made unconditionally and sorted out afterwards.+ *+ * The bound trails the field being typed in: a number entered digit by digit should cost one+ * reading of the note rather than one per keystroke.+ */+export function useCompressionReading(+ target: ImageCompressionTarget,+ options: ImageCompressionToolOptions+): CompressionReading {+ const settledBound = useDebouncedValue(options.maxWidthHeight, READING_DEBOUNCE_MS);+ const single = isSingleImage(target);+ const { data, failed } = useSpaceUsageFetch<ImageInfoResponse | ImageInventoryResponse>(+ single ? imageInfoUrl(target) : inventoryUrl(target, options.processChildNotes, settledBound)+ );++ return {+ info: single ? data as ImageInfoResponse | null : null,+ inventory: single ? null : data as ImageInventoryResponse | null,+ failed+ };+}++/**+ * Which formats there are actually images of to act on — the whole basis of what is offered.+ *+ * Read from the content in both cases, never from the mime an entity is filed under. Those+ * disagree often enough to matter: an image note Trilium saved itself carries `image/jpg`, which is+ * not a real mime type at all, and a dialog trusting it would tell the user their JPEG was a format+ * it could not compress.+ */+export function readableFormats(target: ImageCompressionTarget, reading: CompressionReading): ImageCompressibleFormat[] {+ if (isSingleImage(target)) {+ const format = reading.info?.format;++ return reading.info?.compressible && isCompressible(format) ? [ format ] : [];+ }++ return reading.inventory?.compressibleFormats ?? [];+}++function isCompressible(format: string | undefined): format is ImageCompressibleFormat {+ return (IMAGE_COMPRESSIBLE_FORMATS as readonly string[]).includes(format ?? "");+}++function imageInfoUrl(target: ImageCompressionTarget): string {+ return target.type === "note"+ ? `notes/${target.noteId}/image-info`+ : `attachments/${target.attachmentId}/image-info`;+}++function inventoryUrl(target: ImageCompressionTarget, recursive: boolean, maxWidthHeight: number): string {+ const noteId = target.type === "note" ? target.noteId : "";++ return `notes/${noteId}/image-inventory?recursive=${recursive}&maxWidthHeight=${maxWidthHeight}`;+}++/** Renders the reading; taking it is the dialog's, since what it offers depends on the answer. */+export function ImageCompressionSummary({ reading, recursive }: {+ reading: CompressionReading;+ recursive: boolean;+}) {+ const { info, inventory, failed } = reading;++ if (info) {+ return (+ <div className="image-compression-summary">+ <div className="image-compression-summary-title">{info.title}</div>+ <div>+ {t("space_usage.compress_info_file", {+ format: formatLabel(info.format), size: formatSize(info.size)+ })}+ </div>+ <div className="image-compression-summary-detail">{describeImage(info)}</div>+ </div>+ );+ }++ if (!inventory) {+ return <SummaryPlaceholder failed={failed} />;+ }++ return (+ <div className="image-compression-summary">+ <div className="image-compression-summary-title">{describeScope(inventory, recursive)}</div>+ {inventory.total.count === 0+ ? <div>{t("space_usage.compress_summary_none")}</div>+ : <>+ <div>+ {t("space_usage.compress_summary_total", {+ count: inventory.total.count, size: formatSize(inventory.total.size)+ })}+ </div>+ <div className="image-compression-summary-detail">{describeBreakdown(inventory)}</div>+ </>}+ </div>+ );+}++/** Says which reading is still coming, or that it did not arrive; never a figure standing in. */+function SummaryPlaceholder({ failed }: { failed: boolean }) {+ return (+ <div className="image-compression-summary">+ <div className="image-compression-summary-detail">+ {t(failed ? "space_usage.compress_summary_failed" : "space_usage.compress_summary_reading")}+ </div>+ </div>+ );+}++/** The note, and how far past it the reading went — said only when it went anywhere. */+function describeScope(data: ImageInventoryResponse, recursive: boolean): string {+ const descendants = data.noteCount - 1;++ return recursive && descendants > 0+ ? t("space_usage.compress_summary_scope", { title: data.title, count: descendants })+ : data.title;+}++/**+ * The breakdown, as one sentence of clauses: what each format weighs, then the two figures the+ * settings above are about. Clauses that would say nothing are left out rather than printed as+ * zeroes — an unreadable image is worth mentioning, none of them is not.+ */+function describeBreakdown(data: ImageInventoryResponse): string {+ const clauses = data.formats.map((entry) => t("space_usage.compress_summary_format", {+ count: entry.count, format: formatLabel(entry.format), size: formatSize(entry.size)+ }));++ clauses.push(t("space_usage.compress_summary_oversized", {+ count: data.oversized.count, bound: data.maxWidthHeight+ }));+ clauses.push(t("space_usage.compress_summary_compressible", { count: data.compressible.count }));++ if (data.unreadable > 0) {+ clauses.push(t("space_usage.compress_summary_unreadable", { count: data.unreadable }));+ }++ return `${clauses.join(", ")}.`;+}++/**+ * What the image is, in the terms that decide what compressing it can do: its size, how its pixels+ * are stored, whether it carries transparency, and — for a JPEG — how hard it has been squeezed+ * already. Anything the header did not state is left out rather than guessed at.+ */+function describeImage(data: ImageInfoResponse): string {+ const clauses: string[] = [];++ if (data.width !== null && data.height !== null) {+ clauses.push(t("space_usage.compress_info_pixels", { width: data.width, height: data.height }));+ }++ if (data.bitDepth !== null && data.channels !== null) {+ clauses.push(t("space_usage.compress_info_bits", { bits: data.bitDepth * data.channels }));+ }++ if (data.hasAlpha) {+ clauses.push(t("space_usage.compress_info_transparency"));+ }++ if (data.quality !== null) {+ clauses.push(t("space_usage.compress_info_quality", { quality: data.quality }));+ }++ return clauses.join(", ");+}++/** How a format is named to a reader, rather than the extension the bytes were identified by. */+function formatLabel(format: string): string {+ if (format === "jpg") {+ return "JPEG";+ }++ return format === "unknown" ? t("space_usage.compress_format_unknown") : format.toUpperCase();+}++/** Long enough to type a four-digit bound through without re-reading the note between digits. */+const READING_DEBOUNCE_MS = 500;diff --git a/apps/server/src/services/image_inventory.spec.ts b/apps/server/src/services/image_inventory.spec.tsindex c54ee78739..39a1bfece7 100644--- a/apps/server/src/services/image_inventory.spec.ts+++ b/apps/server/src/services/image_inventory.spec.ts@@ -119,6 +119,30 @@ describe("image inventory (GET /api/notes/:noteId/image-inventory)", () => {expect(res.body.total.count).toBe(3);expect(res.body.compressible).toEqual({ count: 1, size: widePng.byteLength });expect(res.body.formats.map((entry) => entry.format).sort()).toEqual([ "gif", "png", "svg" ]);+ // What a caller offers settings for: only formats it could actually apply them to.+ expect(res.body.compressibleFormats).toEqual([ "png" ]);+ });++ it("names a format as compressible only where an image of it could actually be acted on", async () => {+ const { noteId } = await createTextNote(api);+ await addAttachment(noteId, "a.jpg", wideJpeg, "image/jpeg");+ // The one PNG here is the picture the note regenerates on save, which a run leaves alone —+ // so a PNG is present, and yet there is nothing a PNG setting could be applied to.+ await addAttachment(noteId, "spreadsheet-export.png", widePng);+ setNoteType(noteId, "spreadsheet");++ const res = await inventoryOf(noteId);++ expect(res.body.formats.map((entry) => entry.format).sort()).toEqual([ "jpg", "png" ]);+ expect(res.body.compressibleFormats).toEqual([ "jpg" ]);+ });++ it("orders the compressible formats as it orders the rest, heaviest first", async () => {+ const { noteId } = await createTextNote(api);+ await addAttachment(noteId, "small.png", smallPng);+ await addAttachment(noteId, "big.jpg", wideJpeg, "image/jpeg");++ expect((await inventoryOf(noteId)).body.compressibleFormats).toEqual([ "jpg", "png" ]);});describe("what counts as oversized", () => {diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 5483fd110a..6da0691661 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -308,6 +308,8 @@ export type ImageJpegHandling = (typeof IMAGE_JPEG_HANDLINGS)[number];*/export const IMAGE_COMPRESSIBLE_FORMATS = [ "jpg", "png" ] as const;+export type ImageCompressibleFormat = (typeof IMAGE_COMPRESSIBLE_FORMATS)[number];+/*** What one image is, read from its own bytes.*@@ -361,6 +363,10 @@ export interface ImageInventoryFormat extends ImageInventoryTally {* so the two never describe different sets — see `getNoteImageInventory`.*/export interface ImageInventoryResponse {+ /** The note the reading was taken on, so a caller need not look it up to name it. */+ title: string;+ /** How many notes it covered: the note alone, or it and its descendants when descending. */+ noteCount: number;/** Every image found, whatever its format. */total: ImageInventoryTally;/**@@ -372,6 +378,14 @@ export interface ImageInventoryResponse {oversized: ImageInventoryTally;/** Every format found, heaviest first. */formats: ImageInventoryFormat[];+ /**+ * The formats among which at least one image could actually be compressed, in the same order.+ *+ * Narrower than filtering {@link formats} by what the encoder supports: a note whose only PNG is+ * the picture it regenerates on save holds a PNG that nothing will act on, and offering to+ * configure one would be offering a setting with nothing to apply it to.+ */+ compressibleFormats: ImageCompressibleFormat[];/** What {@link oversized} was measured against. */maxWidthHeight: number;/** Images whose content could not be read — protected, with no session open. Counted nowhere else. */diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex eae54f0e7c..5cdc9641fa 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -169,11 +169,17 @@ export interface CompressionTarget {* and does not resolve search notes — the run follows the tree, not what a query happens to match.*/export function collectNoteTargets(note: BNote, recursive: boolean): CompressionTarget[] {- if (!recursive) {- return ownTargetsOf(note);- }+ return collectNoteImages(note, recursive).targets;+}++/**+ * The same images, with the notes they were gathered from — for a caller that has to say how far+ * the reading reached. One walk answers both; asking the subtree twice would not.+ */+export function collectNoteImages(note: BNote, recursive: boolean): { notes: BNote[]; targets: CompressionTarget[] } {+ const notes = recursive ? note.getSubtree().notes : [ note ];- return note.getSubtree().notes.flatMap(ownTargetsOf);+ return { notes, targets: notes.flatMap(ownTargetsOf) };}/**diff --git a/packages/trilium-core/src/services/image_inventory.ts b/packages/trilium-core/src/services/image_inventory.tsindex 186e8429ad..ab9df7742f 100644--- a/packages/trilium-core/src/services/image_inventory.ts+++ b/packages/trilium-core/src/services/image_inventory.ts@@ -12,6 +12,7 @@import {IMAGE_COMPRESSIBLE_FORMATS,+ type ImageCompressibleFormat,type ImageInventoryFormat,type ImageInventoryResponse,type ImageInventoryTally@@ -20,7 +21,7 @@ import {import becca from "../becca/becca.js";import { NotFoundError } from "../errors.js";import {- collectNoteTargets,+ collectNoteImages,type CompressionTarget,resolveMaxWidthHeight,resolveRecursive@@ -42,12 +43,13 @@ export function getNoteImageInventory(noteId: string, options: ImageInventoryOpt}const maxWidthHeight = resolveMaxWidthHeight(options.maxWidthHeight);- const targets = collectNoteTargets(note, resolveRecursive(options));+ const { notes, targets } = collectNoteImages(note, resolveRecursive(options));const total = emptyTally();const compressible = emptyTally();const oversized = emptyTally();const formats = new Map<string, ImageInventoryFormat>();+ const reachable = new Set<string>();let unreadable = 0;for (const target of targets) {@@ -71,18 +73,26 @@ export function getNoteImageInventory(noteId: string, options: ImageInventoryOpt}add(compressible, size);+ reachable.add(format);if (width !== null && height !== null && Math.max(width, height) > maxWidthHeight) {add(oversized, size);}}+ // Heaviest first: what a note's images weigh is the reason to be looking at all.+ const ordered = [ ...formats.values() ].sort((a, b) => b.size - a.size);+return {+ title: note.title,+ noteCount: notes.length,total,compressible,oversized,- // Heaviest first: what a note's images weigh is the reason to be looking at all.- formats: [ ...formats.values() ].sort((a, b) => b.size - a.size),+ formats: ordered,+ compressibleFormats: ordered+ .map((entry) => entry.format)+ .filter((format): format is ImageCompressibleFormat => reachable.has(format)),maxWidthHeight,unreadable};