Skip to content

Build your personal knowledge base with Trilium Notes

client/image compression tool: make the new automatic compression configurable

Adorian Doran0478fe19ad87
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index fc0e0cbd85..0315ca17d4 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1816,6 +1816,7 @@
"download_images_automatically": "Download images automatically",
"download_images_description": "Download referenced online images from pasted HTML so they are available offline.",
"enable_image_compression": "Image compression",
+ "automatic_image_compression": "Automatically compress images",
"enable_image_compression_description": "Compress and resize images when they are uploaded or pasted.",
"max_image_dimensions": "Max image dimensions",
"max_image_dimensions_description": "Images exceeding this size will be resized automatically.",
diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_options.ts b/apps/client/src/widgets/dialogs/image_compression/image_compression_options.ts
index 797e7db5c8..05b1199474 100644
--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_options.ts
+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_options.ts
@@ -106,6 +106,20 @@ export const CONSERVATIVE_IMAGE_COMPRESSION_DEFAULTS: ImageCompressionDefaults =
pngHandling: "keep"
};
+/**
+ * What automatic compression falls back to, which is what it has always done: an arriving JPEG
+ * recompressed, an arriving PNG written back as a JPEG.
+ *
+ * Only ever reached by a stored option that cannot be read, since every one of these settings has
+ * a value from the moment the database is created. It is here so that the unreadable case answers
+ * the way the server answers it — the settings page and the upload path must not disagree about
+ * what an install with a corrupt option is doing.
+ */
+export const AUTOMATIC_IMAGE_COMPRESSION_DEFAULTS: ImageCompressionDefaults = {
+ jpegHandling: "compress",
+ pngHandling: "jpeg"
+};
+
/** The longest edge the first run offers to scale down to: the width of a Full HD screen. */
export const DEFAULT_MAX_WIDTH_HEIGHT = 1920;
diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_sections.css b/apps/client/src/widgets/dialogs/image_compression/image_compression_sections.css
index a35ba69089..7b16272fe4 100644
--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_sections.css
+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_sections.css
@@ -12,6 +12,26 @@
white-space: nowrap;
}
+ /* A described row: the title and its sentence stack, and the pair takes the slack the title
+ alone would have taken. Unlike the title it may shrink, since a sentence wraps where a label
+ does not — and it needs to, or a long description would push the control off the row. */
+ .image-compression-section-label {
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+
+ .image-compression-section-title {
+ white-space: normal;
+ }
+ }
+
+ .image-compression-section-description {
+ color: var(--muted-text-color);
+ font-size: 0.85em;
+ }
+
/* Where the slider currently is, which the slider itself cannot say. Fixed-width digits so the
row holds still as the value is dragged through. */
.image-compression-section-value {
diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_sections.tsx b/apps/client/src/widgets/dialogs/image_compression/image_compression_sections.tsx
index 5a747d990f..d4a5e50735 100644
--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_sections.tsx
+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_sections.tsx
@@ -35,8 +35,30 @@ export interface ImageCompressionSectionProps {
onChange(patch: Partial<ImageCompressionToolOptions>): void;
/** Greys the controls out, for a host that hangs the whole group off a switch of its own. */
disabled?: boolean;
+ /**
+ * A sentence under a row's title, for a host with room to explain rather than to be asked.
+ *
+ * Keyed by row rather than passed to one, because the group is wired once and handed down: a
+ * nested row is rendered by the row above it, and this is what lets a host still describe it.
+ *
+ * The settings page fills these in; the dialogs leave them out. A dialog is opened to do one
+ * thing and is read in a hurry, so what a row means lives behind its help mark and stays out of
+ * the way — where a settings page is read by someone deciding, and the prose is the point. Rows
+ * with nothing extra to say keep the mark alone.
+ */
+ descriptions?: Partial<Record<ImageCompressionSectionKey, string>>;
}
+/** The rows a host can describe, named after the setting each one carries. */
+export type ImageCompressionSectionKey =
+ | "resize"
+ | "maxWidthHeight"
+ | "jpegHandling"
+ | "pngHandling"
+ | "quality"
+ | "conversionQuality"
+ | "processChildNotes";
+
/**
* 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
@@ -51,10 +73,11 @@ export function ResizeImageSection(props: ImageCompressionSectionProps) {
subSectionsVisible={options.resize}
subSections={[ <MaxImageDimensionsSection key="max-dimensions" {...props} /> ]}
>
- <span className="image-compression-section-title">
- {t("space_usage.compress_resize")}
- <ContextualHelp helpMessage={t("space_usage.compress_resize_help")} />
- </span>
+ <SectionLabel
+ title={t("space_usage.compress_resize")}
+ help={t("space_usage.compress_resize_help")}
+ description={props.descriptions?.resize}
+ />
<FormToggle
disabled={disabled}
currentValue={options.resize}
@@ -65,10 +88,13 @@ export function ResizeImageSection(props: ImageCompressionSectionProps) {
}
/** The bound an image is scaled down to fit. */
-export function MaxImageDimensionsSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+export function MaxImageDimensionsSection({ options, onChange, disabled, descriptions }: ImageCompressionSectionProps) {
return (
<CardSection className="image-compression-section image-compression-section-nested">
- <span className="image-compression-section-title">{t("space_usage.compress_max_dimensions")}</span>
+ <SectionLabel
+ title={t("space_usage.compress_max_dimensions")}
+ description={descriptions?.maxWidthHeight}
+ />
<FormTextBoxWithUnit
className="image-compression-section-number"
type="number"
@@ -104,6 +130,7 @@ export function JpegHandlingSection(props: ImageCompressionSectionProps) {
help={t("space_usage.compress_jpeg_handling_help")}
values={IMAGE_JPEG_HANDLINGS}
currentValue={options.jpegHandling}
+ description={props.descriptions?.jpegHandling}
labelKey="compress_jpeg"
onChoose={(jpegHandling) => onChange({ jpegHandling })}
/>
@@ -132,6 +159,7 @@ export function PngHandlingSection(props: ImageCompressionSectionProps) {
help={t("space_usage.compress_png_handling_help")}
values={IMAGE_PNG_HANDLINGS}
currentValue={options.pngHandling}
+ description={props.descriptions?.pngHandling}
labelKey="compress_png"
onChoose={(pngHandling) => onChange({ pngHandling })}
/>
@@ -140,35 +168,38 @@ export function PngHandlingSection(props: ImageCompressionSectionProps) {
}
/** The quality an already-lossy image is recompressed at. */
-export function JpegQualitySection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+export function JpegQualitySection({ options, onChange, disabled, descriptions }: ImageCompressionSectionProps) {
return (
<QualitySlider
value={options.quality}
disabled={disabled}
+ description={descriptions?.quality}
onChange={(quality) => onChange({ quality })}
/>
);
}
/** The quality a converted lossless image is written at, kept apart from the one above. */
-export function ConversionQualitySection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+export function ConversionQualitySection({ options, onChange, disabled, descriptions }: ImageCompressionSectionProps) {
return (
<QualitySlider
value={options.conversionQuality}
disabled={disabled}
+ description={descriptions?.conversionQuality}
onChange={(conversionQuality) => onChange({ conversionQuality })}
/>
);
}
/** Whether the run reaches past the note it was invoked on, into its whole subtree. */
-export function ProcessChildNotesSection({ options, onChange, disabled }: ImageCompressionSectionProps) {
+export function ProcessChildNotesSection({ options, onChange, disabled, descriptions }: ImageCompressionSectionProps) {
return (
<CardSection className="image-compression-section">
- <span className="image-compression-section-title">
- {t("space_usage.compress_process_child_notes")}
- <ContextualHelp helpMessage={t("space_usage.compress_process_child_notes_help")} />
- </span>
+ <SectionLabel
+ title={t("space_usage.compress_process_child_notes")}
+ help={t("space_usage.compress_process_child_notes_help")}
+ description={descriptions?.processChildNotes}
+ />
<FormToggle
disabled={disabled}
currentValue={options.processChildNotes}
@@ -191,10 +222,39 @@ export function UnsupportedFormatNotice() {
);
}
+/**
+ * What a row is called, and — where the host gave one — what it means.
+ *
+ * Undescribed, this is the bare title span the rows have always been built from, so a dialog's
+ * markup is exactly what it was. A description wraps the pair in a column instead: the title keeps
+ * its own element, since the title is what the row's layout is measured against, and the sentence
+ * hangs beneath it where it can wrap.
+ */
+function SectionLabel({ title, help, description }: { title: string; help?: string; description?: string }) {
+ const label = (
+ <span className="image-compression-section-title">
+ {title}
+ {help && <ContextualHelp helpMessage={help} />}
+ </span>
+ );
+
+ if (!description) {
+ return label;
+ }
+
+ return (
+ <span className="image-compression-section-label">
+ {label}
+ <small className="image-compression-section-description">{description}</small>
+ </span>
+ );
+}
+
/** The title, help and buttons every format choice is made of. */
-function HandlingChoice<T extends string>({ title, help, values, currentValue, labelKey, onChoose, disabled }: {
+function HandlingChoice<T extends string>({ title, help, description, values, currentValue, labelKey, onChoose, disabled }: {
title: string;
help: string;
+ description?: string;
values: readonly T[];
currentValue: T;
/** Prefix of the translation key naming each choice, completed with the value itself. */
@@ -203,10 +263,7 @@ function HandlingChoice<T extends string>({ title, help, values, currentValue, l
} & ImageCompressionSectionProps) {
return (
<>
- <span className="image-compression-section-title">
- {title}
- <ContextualHelp helpMessage={help} />
- </span>
+ <SectionLabel title={title} help={help} description={description} />
<SegmentedChoice
className="image-compression-section-choice"
// A disabled group highlights nothing rather than showing a choice it will not take.
@@ -225,14 +282,15 @@ function HandlingChoice<T extends string>({ title, help, values, currentValue, l
* 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({ value, onChange, disabled }: {
+function QualitySlider({ value, onChange, disabled, description }: {
value: number;
onChange: (value: number) => void;
disabled?: boolean;
+ description?: string;
}) {
return (
<CardSection className={clsx("image-compression-section", "image-compression-section-nested")}>
- <span className="image-compression-section-title">{t("space_usage.compress_quality")}</span>
+ <SectionLabel title={t("space_usage.compress_quality")} description={description} />
<span className="image-compression-section-value">
{t("space_usage.compress_quality_value", { quality: value })}
</span>
diff --git a/apps/client/src/widgets/type_widgets/options/media.css b/apps/client/src/widgets/type_widgets/options/media.css
new file mode 100644
index 0000000000..2c0041debf
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/media.css
@@ -0,0 +1,11 @@
+/* A real card where the rest of the page is options sections. It keeps the card styling the theme
+ already gives every other one — the wrapper is here for the page's own spacing, so the card sits
+ where a section would rather than flush against the one above it. */
+.media-image-compression {
+ /* The choice buttons and their labels sit on one line in a dialog sized to its content; a
+ settings page is only as wide as its pane, and a narrow one has to be allowed to stack them
+ rather than push the card wider than the page. */
+ .image-compression-section {
+ flex-wrap: wrap;
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/options/media.spec.tsx b/apps/client/src/widgets/type_widgets/options/media.spec.tsx
new file mode 100644
index 0000000000..c1422a6005
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/media.spec.tsx
@@ -0,0 +1,173 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * The image compression card: the tool's own rows, driving the options that govern every image
+ * arriving in the database rather than a run the user is watching.
+ *
+ * What is worth holding here is the wiring, since the rows themselves are tested where they live —
+ * that each row reads and writes the option it stands for, that the group hangs off the switch
+ * above it, and that the sentences the settings carried before they became rows are still on the
+ * page.
+ */
+const mocks = vi.hoisted(() => ({
+ stored: {} as Record<string, string>,
+ saved: vi.fn<(name: string, value: string) => void>()
+}));
+
+// i18next is never initialised for these tests and answers `undefined` until it is, which would
+// make every assertion about a description true of any string at all.
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string, params?: Record<string, unknown>) => (params ? `${key} ${JSON.stringify(params)}` : key),
+ translationsInitializedPromise: Promise.resolve(),
+ initLocale: async () => {},
+ getAvailableLocales: () => [],
+ getLocaleById: () => null,
+ getCurrentLanguage: () => "en"
+}));
+
+// A stand-in options store: the page reads through these hooks and writes back through them, so
+// this is the whole of what the card touches. Partial-mocked, since sibling components below it
+// use other hooks from the same module.
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOption: (name: string) => [ mocks.stored[name], (value: string) => mocks.saved(name, value) ],
+ useTriliumOptionBool: (name: string) => [
+ mocks.stored[name] === "true",
+ (value: boolean) => mocks.saved(name, String(value))
+ ],
+ useTriliumOptionInt: (name: string) => [
+ parseInt(mocks.stored[name] ?? "", 10),
+ (value: number) => mocks.saved(name, String(value))
+ ],
+ useNoteContext: () => ({ note: undefined })
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+vi.mock("./components/RelatedSettings", () => ({ default: () => <div className="related-stub" /> }));
+
+import MediaSettings from "./media";
+
+/** What an untouched install has: everything on, PNGs converted, as automatic shrinking always did. */
+const DEFAULTS: Record<string, string> = {
+ compressImages: "true",
+ imageResize: "true",
+ imageMaxWidthHeight: "2000",
+ imageJpegHandling: "compress",
+ imagePngHandling: "jpeg",
+ imageJpegQuality: "75",
+ imageConversionQuality: "75",
+ downloadImagesAutomatically: "true"
+};
+
+let host: HTMLElement;
+
+function open(overrides: Record<string, string> = {}) {
+ mocks.stored = { ...DEFAULTS, ...overrides };
+
+ void act(() => {
+ render(<MediaSettings />, host);
+ });
+}
+
+/** The card's rows, in the order they are drawn, named by their titles. */
+function rowTitles(): (string | undefined)[] {
+ return [ ...host.querySelectorAll(".media-image-compression .image-compression-section") ]
+ .map((row) => row.querySelector(".image-compression-section-title")?.textContent ?? undefined);
+}
+
+function row(title: string): HTMLElement | undefined {
+ return [ ...host.querySelectorAll<HTMLElement>(".media-image-compression .image-compression-section") ]
+ .find((candidate) => candidate.querySelector(".image-compression-section-title")?.textContent === title);
+}
+
+/** Presses one of a row's choice buttons by its label. */
+async function choose(title: string, label: string) {
+ const button = [ ...(row(title)?.querySelectorAll<HTMLElement>("button") ?? []) ]
+ .find((candidate) => candidate.textContent?.trim() === label);
+
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+}
+
+beforeEach(() => {
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+describe("the image compression card", () => {
+ it("hangs the whole group off its switch, nesting what qualifies each choice", () => {
+ open();
+
+ // Every row the settings can offer, in order: the switch, scaling with its bound, then one
+ // exclusive choice per format, each followed by the quality that qualifies it.
+ expect(rowTitles()).toEqual([
+ "images.automatic_image_compression",
+ "space_usage.compress_resize",
+ "space_usage.compress_max_dimensions",
+ "space_usage.compress_jpeg_handling",
+ "space_usage.compress_quality",
+ "space_usage.compress_png_handling",
+ "space_usage.compress_quality"
+ ]);
+
+ // Switched off, the settings are not merely greyed out but gone: there is nothing for them
+ // to govern, and a bound sitting there would read as one still in force.
+ open({ compressImages: "false" });
+ expect(rowTitles()).toEqual([ "images.automatic_image_compression" ]);
+ });
+
+ it("drops a quality that no longer qualifies anything", () => {
+ open({ imageJpegHandling: "keep", imagePngHandling: "keep" });
+
+ // Neither format is being re-encoded, so neither quality is in force — and resizing is
+ // still on offer, being the one step that reaches an image whatever its encoding.
+ expect(rowTitles()).toEqual([
+ "images.automatic_image_compression",
+ "space_usage.compress_resize",
+ "space_usage.compress_max_dimensions",
+ "space_usage.compress_jpeg_handling",
+ "space_usage.compress_png_handling"
+ ]);
+
+ // And the bound goes with scaling, for the same reason.
+ open({ imageResize: "false" });
+ expect(rowTitles()).not.toContain("space_usage.compress_max_dimensions");
+ });
+
+ it("carries the sentences the settings had before they were rows", () => {
+ open();
+
+ const describes = (title: string) =>
+ row(title)?.querySelector(".image-compression-section-description")?.textContent;
+
+ expect(describes("images.automatic_image_compression")).toBe("images.enable_image_compression_description");
+ expect(describes("space_usage.compress_resize")).toBe("images.max_image_dimensions_description");
+ // Both qualities take the same advice, being the same scale read twice.
+ expect(describes("space_usage.compress_quality")).toBe("images.jpeg_quality_description");
+ // A row with nothing extra to say keeps its help mark alone rather than inventing prose.
+ expect(describes("space_usage.compress_png_handling")).toBeUndefined();
+ expect(row("space_usage.compress_png_handling")?.querySelector(".contextual-help")).not.toBeNull();
+ });
+
+ it("writes each choice back to the option it stands for", async () => {
+ open();
+
+ await choose("space_usage.compress_png_handling", "space_usage.compress_png_optimize");
+ expect(mocks.saved).toHaveBeenCalledWith("imagePngHandling", "optimize");
+
+ await choose("space_usage.compress_jpeg_handling", "space_usage.compress_jpeg_keep");
+ expect(mocks.saved).toHaveBeenCalledWith("imageJpegHandling", "keep");
+
+ // Each row writes its own and only its own: the settings are separate synced options, not
+ // one blob, so a client that has never heard of the newer ones still reads the older ones.
+ expect(mocks.saved.mock.calls.map(([ name ]) => name)).toEqual([ "imagePngHandling", "imageJpegHandling" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/media.tsx b/apps/client/src/widgets/type_widgets/options/media.tsx
index 5560559c80..682bee83ab 100644
--- a/apps/client/src/widgets/type_widgets/options/media.tsx
+++ b/apps/client/src/widgets/type_widgets/options/media.tsx
@@ -1,11 +1,26 @@
+import "./media.css";
+
+import type { ImageJpegHandling, ImagePngHandling } from "@triliumnext/commons";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import toast from "../../../services/toast";
import { isElectron } from "../../../services/utils";
-import { FormTextBoxWithUnit } from "../../react/FormTextBox";
-import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import {
+ AUTOMATIC_IMAGE_COMPRESSION_DEFAULTS,
+ type ImageCompressionToolOptions,
+ readImageCompressionOptions
+} from "../../dialogs/image_compression/image_compression_options";
+import {
+ type ImageCompressionSectionProps,
+ JpegHandlingSection,
+ PngHandlingSection,
+ ResizeImageSection
+} from "../../dialogs/image_compression/image_compression_sections";
+import { Card, CardSection } from "../../react/Card";
+import FormToggle from "../../react/FormToggle";
+import { useTriliumOption, useTriliumOptionBool, useTriliumOptionInt } from "../../react/hooks";
import Slider from "../../react/Slider";
import OptionsPageHeader from "./components/OptionsPageHeader";
import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";
@@ -17,6 +32,7 @@ export default function MediaSettings() {
<>
<OptionsPageHeader />
<ImageSettings />
+ <ImageCompressionSettings />
<OcrSettings />
</>
);
@@ -24,9 +40,6 @@ export default function MediaSettings() {
function ImageSettings() {
const [ downloadImagesAutomatically, setDownloadImagesAutomatically ] = useTriliumOptionBool("downloadImagesAutomatically");
- const [ compressImages, setCompressImages ] = useTriliumOptionBool("compressImages");
- const [ imageMaxWidthHeight, setImageMaxWidthHeight ] = useTriliumOption("imageMaxWidthHeight");
- const [ imageJpegQuality, setImageJpegQuality ] = useTriliumOption("imageJpegQuality");
return (
<OptionsSection title={t("images.images_section_title")}>
@@ -37,35 +50,105 @@ function ImageSettings() {
currentValue={downloadImagesAutomatically}
onChange={setDownloadImagesAutomatically}
/>
+ </OptionsSection>
+ );
+}
- <OptionsRowWithToggle
- name="image-compression-enabled"
- label={t("images.enable_image_compression")}
- description={t("images.enable_image_compression_description")}
- currentValue={compressImages}
- onChange={setCompressImages}
- />
-
- <OptionsRow name="image-max-width-height" label={t("images.max_image_dimensions")} description={t("images.max_image_dimensions_description")}>
- <FormTextBoxWithUnit
- type="number" min="1"
- disabled={!compressImages}
- unit={t("images.max_image_dimensions_unit")}
- currentValue={imageMaxWidthHeight} onChange={setImageMaxWidthHeight}
- />
- </OptionsRow>
+/**
+ * What happens to an image on its way in, configured with the same rows the compression tool is
+ * built from — because behind them it is now the same compression. The one thing said here that the
+ * tool never has to say is *when* any of it happens: on upload, on paste, on import.
+ *
+ * A real card rather than the options page's own section: these rows nest, a choice bringing its
+ * quality out from under it, and nesting is what a card section does. The descriptions are the ones
+ * the settings carried before they were rows — a settings page is read by someone deciding, where a
+ * dialog is read by someone who has already decided, so here the prose is on the page rather than
+ * behind the help marks the dialogs use.
+ */
+function ImageCompressionSettings() {
+ const [ compressImages, setCompressImages ] = useTriliumOptionBool("compressImages");
+ const [ options, update ] = useAutomaticCompressionOptions();
+ const sectionProps: ImageCompressionSectionProps = {
+ options,
+ onChange: update,
+ disabled: !compressImages,
+ descriptions: {
+ resize: t("images.max_image_dimensions_description"),
+ quality: t("images.jpeg_quality_description"),
+ conversionQuality: t("images.jpeg_quality_description")
+ }
+ };
- <OptionsRow name="image-jpeg-quality" label={`${t("images.jpeg_quality")} (${imageJpegQuality ?? 75}%)`} description={t("images.jpeg_quality_description")}>
- <Slider
- min={10} max={100} step={5}
- value={parseInt(imageJpegQuality ?? "75", 10)}
- onChange={(v) => setImageJpegQuality(String(v))}
- />
- </OptionsRow>
- </OptionsSection>
+ return (
+ <div className="options-section media-image-compression">
+ <Card heading={t("images.enable_image_compression")}>
+ <CardSection
+ className="image-compression-section"
+ subSectionsVisible={compressImages}
+ subSections={[
+ <ResizeImageSection key="resize" {...sectionProps} />,
+ <JpegHandlingSection key="jpeg" {...sectionProps} />,
+ <PngHandlingSection key="png" {...sectionProps} />
+ ]}
+ >
+ <span className="image-compression-section-label">
+ {/* Not the tool's own "Compress images": that is something the user does to
+ images already stored, where this is a standing instruction about every
+ image still to arrive. Saying which is which is the whole of the label. */}
+ <span className="image-compression-section-title">
+ {t("images.automatic_image_compression")}
+ </span>
+ <small className="image-compression-section-description">
+ {t("images.enable_image_compression_description")}
+ </small>
+ </span>
+ <FormToggle currentValue={compressImages} onChange={setCompressImages} />
+ </CardSection>
+ </Card>
+ </div>
);
}
+/**
+ * The image options, read and written as one set of compression settings.
+ *
+ * Each is its own synced option rather than a blob, as they always were — an install that has only
+ * ever had a bound and a quality keeps them, and a client too old to know the rest still reads the
+ * two it does. The adapter is what lets the tool's rows drive them: those rows speak in whole
+ * settings objects, and this turns a patch of one back into the writes it stands for.
+ */
+function useAutomaticCompressionOptions(): [ ImageCompressionToolOptions, (patch: Partial<ImageCompressionToolOptions>) => void ] {
+ const [ maxWidthHeight, setMaxWidthHeight ] = useTriliumOptionInt("imageMaxWidthHeight");
+ const [ quality, setQuality ] = useTriliumOptionInt("imageJpegQuality");
+ const [ conversionQuality, setConversionQuality ] = useTriliumOptionInt("imageConversionQuality");
+ const [ resize, setResize ] = useTriliumOptionBool("imageResize");
+ const [ jpegHandling, setJpegHandling ] = useTriliumOption("imageJpegHandling");
+ const [ pngHandling, setPngHandling ] = useTriliumOption("imagePngHandling");
+
+ const options = readImageCompressionOptions({
+ resize,
+ maxWidthHeight,
+ quality,
+ conversionQuality,
+ jpegHandling: jpegHandling as ImageJpegHandling,
+ pngHandling: pngHandling as ImagePngHandling,
+ // Automatic compression reaches every image that arrives; there is no subtree to choose,
+ // and no row here offers one. Held only because the rows share one settings type.
+ processChildNotes: false
+ }, AUTOMATIC_IMAGE_COMPRESSION_DEFAULTS);
+
+ // Each write is left to settle on its own: a row changes one setting, the option is saved, and
+ // nothing here waits on the round trip — the control already shows the new value.
+ return [ options, (patch) => {
+ if (patch.resize !== undefined) void setResize(patch.resize);
+ if (patch.maxWidthHeight !== undefined) void setMaxWidthHeight(patch.maxWidthHeight);
+ if (patch.quality !== undefined) void setQuality(patch.quality);
+ if (patch.conversionQuality !== undefined) void setConversionQuality(patch.conversionQuality);
+ if (patch.jpegHandling !== undefined) void setJpegHandling(patch.jpegHandling);
+ if (patch.pngHandling !== undefined) void setPngHandling(patch.pngHandling);
+ } ];
+}
+
function OcrSettings() {
const [ ocrAutoProcess, setOcrAutoProcess ] = useTriliumOptionBool("ocrAutoProcessImages");
const [ ocrMinConfidence, setOcrMinConfidence ] = useTriliumOption("ocrMinConfidence");