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
feat(image-compression): pick JPEG/PNG handling from a described dropdown
Elian Dorand120e075cc6a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b5a042b816..7a5ea64ed1 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3353,14 +3353,17 @@"compress_resize_help": "Reduces images that are larger than the chosen size. Images that already fit are left unchanged.","compress_max_dimensions": "Reduce the image size to","compress_jpeg_handling": "JPEG image",- "compress_jpeg_handling_help": "Keeping the image preserves its current quality. Compressing saves it again at a lower quality to reduce its size, which cannot be undone.","compress_jpeg_keep": "Keep as it is",+ "compress_jpeg_keep_description": "Preserves the current quality.","compress_jpeg_compress": "Compress",+ "compress_jpeg_compress_description": "Saves the image again at a lower quality to reduce its size. This cannot be undone.","compress_png_handling": "PNG image",- "compress_png_handling_help": "Keeping the image preserves it exactly. Optimizing reduces the number of colors, which is usually unnoticeable in screenshots and diagrams. Converting to JPEG saves the most space, but cannot be applied to images with transparency, which are optimized instead.","compress_png_keep": "Keep as it is",+ "compress_png_keep_description": "Preserves the image exactly.","compress_png_optimize": "Optimize",+ "compress_png_optimize_description": "Reduces the number of colors, which is usually unnoticeable in screenshots and diagrams.","compress_png_jpeg": "Convert to JPEG",+ "compress_png_jpeg_description": "Saves the most space. Images with transparency are optimized instead.","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",diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsxindex be040b64a9..ad6f581959 100644--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx@@ -153,25 +153,37 @@ const qualityReading = () => document.body.querySelector(".image-compression-secconst toggles = () => Array.from(document.body.querySelectorAll<HTMLInputElement>(".switch-toggle"));const hasHelp = (row: HTMLElement) => !!row.querySelector(".tn-card-option-title .contextual-help-icon");-/** 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] ?? [];+/** The menu toggle of each format's choice, in the order the card lists them. */+const choiceToggles = () =>+ Array.from(document.body.querySelectorAll<HTMLButtonElement>(".dropdown.image-compression-section-choice > button"));/** 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 pngGroup = () => choiceToggles().length - 1;-const chosenOf = (group: number) =>- choiceButtons(group).find((button) => button.classList.contains("active"))?.textContent?.trim();+const chosenOf = (group: number) => choiceToggles()[group]?.textContent?.trim();const chosenJpeg = () => chosenOf(0);const chosenPng = () => chosenOf(pngGroup());+/** The rows of the open choice menu. */+const choiceEntries = () =>+ Array.from(document.body.querySelectorAll<HTMLElement>(".image-compression-choice-menu li.dropdown-item"));++/** Opens one format's menu and runs its entry at `index`. */+async function chooseIn(group: number, index: number) {+ await click(choiceToggles()[group]);+ const entry = choiceEntries()[index];+ expect(entry).toBeDefined();+ await act(async () => {+ entry?.click();+ });+}+async function chooseJpeg(handling: "keep" | "compress") {- await click(choiceButtons(0)[[ "keep", "compress" ].indexOf(handling)]);+ await chooseIn(0, [ "keep", "compress" ].indexOf(handling));}async function choosePng(handling: "keep" | "optimize" | "jpeg") {- await click(choiceButtons(pngGroup())[[ "keep", "optimize", "jpeg" ].indexOf(handling)]);+ await chooseIn(pngGroup(), [ "keep", "optimize", "jpeg" ].indexOf(handling));}const buttons = () => Array.from(document.body.querySelectorAll<HTMLButtonElement>(".footer-stub button"));const cancelButton = () => buttons()[0];@@ -286,10 +298,20 @@ describe("showImageCompressionDialog", () => {.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 ]);+ // Switches explain themselves beside their title; a choice explains each entry in its menu.+ expect(rows().map(hasHelp)).toEqual([ true, false, false, false, false, true ]);+ });++ it("describes every entry of a format's menu and marks the current one", async () => {+ await openDialog();++ await click(choiceToggles()[pngGroup()]);+ expect(choiceEntries().map((entry) => entry.querySelector(".description")?.textContent)).toEqual([+ "space_usage.compress_png_keep_description",+ "space_usage.compress_png_optimize_description",+ "space_usage.compress_png_jpeg_description"+ ]);+ expect(choiceEntries().map((entry) => entry.getAttribute("aria-checked"))).toEqual([ "false", "true", "false" ]);});it("puts the reach of the run in a card of its own, apart from how it compresses", async () => {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.cssindex a2ff5a3186..afe7cfe583 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@@ -43,17 +43,15 @@width: 140px;}- /* Never wraps: the choices are read across, and a button folding onto a second line would- break the row into two heights. A long translation widens the dialog instead. */.image-compression-section-choice {flex: 0 0 auto;- white-space: nowrap;- /* Smaller than the label it answers: three of these across a row read as a control,- where at full size they compete with the title for it. */- font-size: 0.85em;}}+.image-compression-choice-menu {+ max-width: 22em;+}+/* Indented by the card itself; quieting the title is what marks it as qualifying the row aboverather than standing beside it. */.image-compression-section-nested .tn-card-option-title {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.tsxindex 27730e0d79..0b89548712 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@@ -6,9 +6,10 @@ import clsx from "clsx";import { t } from "../../../services/i18n";import { CardSection } from "../../react/Card";import ContextualHelp from "../../react/ContextualHelp";+import Dropdown from "../../react/Dropdown";+import { FormListItem } from "../../react/FormList";import { FormTextBoxWithUnit } from "../../react/FormTextBox";import FormToggle from "../../react/FormToggle";-import SegmentedChoice from "../../react/SegmentedChoice";import Slider from "../../react/Slider";import {type ImageCompressionToolOptions,@@ -127,7 +128,6 @@ export function JpegHandlingSection(props: ImageCompressionSectionProps) {<HandlingChoice{...props}title={t("space_usage.compress_jpeg_handling")}- help={t("space_usage.compress_jpeg_handling_help")}values={IMAGE_JPEG_HANDLINGS}currentValue={options.jpegHandling}description={props.descriptions?.jpegHandling}@@ -156,7 +156,6 @@ export function PngHandlingSection(props: ImageCompressionSectionProps) {<HandlingChoice{...props}title={t("space_usage.compress_png_handling")}- help={t("space_usage.compress_png_handling_help")}values={IMAGE_PNG_HANDLINGS}currentValue={options.pngHandling}description={props.descriptions?.pngHandling}@@ -250,29 +249,39 @@ function SectionLabel({ title, help, description }: { title: string; help?: stri);}-/** The title, help and buttons every format choice is made of. */-function HandlingChoice<T extends string>({ title, help, description, values, currentValue, labelKey, onChoose, disabled }: {+/** The title and the menu every format choice is made of, each entry saying what it does. */+function HandlingChoice<T extends string>({ title, 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. */+ /** Prefix of the translation keys naming and describing each choice, completed with the value. */labelKey: string;onChoose: (value: T) => void;} & ImageCompressionSectionProps) {return (<>- <SectionLabel title={title} help={help} description={description} />- <SegmentedChoice+ <SectionLabel title={title} description={description} />+ <DropdownclassName="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)}- // Three named choices are wider than a phone: the PNG row's ran 74px past its card.- collapseOnMobile- />+ dropdownContainerClassName="image-compression-choice-menu"+ text={t(`space_usage.${labelKey}_${currentValue}`)}+ disabled={disabled}+ placement="bottom-end"+ mobileBottomSheet+ >+ {values.map((value) => (+ <FormListItem+ key={value}+ checkable+ checked={value === currentValue}+ description={t(`space_usage.${labelKey}_${value}_description`)}+ onClick={() => onChoose(value)}+ >+ {t(`space_usage.${labelKey}_${value}`)}+ </FormListItem>+ ))}+ </Dropdown></>);}diff --git a/apps/client/src/widgets/type_widgets/options/media.spec.tsx b/apps/client/src/widgets/type_widgets/options/media.spec.tsxindex 7307a27115..0374531211 100644--- a/apps/client/src/widgets/type_widgets/options/media.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/media.spec.tsx@@ -145,13 +145,17 @@ function rowOrFail(title: string): HTMLElement {return found;}-/** Presses one of a row's choice buttons by its label. */+/** Opens a row's choice menu and runs the entry with the given label. */async function choose(title: string, label: string) {- const button = [ ...(row(title)?.querySelectorAll<HTMLElement>("button") ?? []) ]- .find((candidate) => candidate.textContent?.trim() === label);+ await act(async () => {+ rowOrFail(title).querySelector<HTMLButtonElement>(".dropdown > button")?.click();+ });+ const entry = [ ...document.body.querySelectorAll<HTMLElement>(".image-compression-choice-menu li.dropdown-item") ]+ .find((candidate) => candidate.textContent?.trim().startsWith(label));+ expect(entry).toBeDefined();await act(async () => {- button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ entry?.click();});}@@ -223,9 +227,8 @@ describe("the images card", () => {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.+ // A choice describes each entry in its menu rather than the row.expect(describes("space_usage.compress_png_handling")).toBeUndefined();- expect(row("space_usage.compress_png_handling")?.querySelector(".contextual-help-icon")).not.toBeNull();});it("writes each choice back to the option it stands for", async () => {