diff --git a/client/src/App.tsx b/client/src/App.tsx index 09b4998a..aec50dfc 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -38,6 +38,7 @@ const Base64Encoder = lazy(() => import("@/pages/tools/base64-encoder")); const CborEncoder = lazy(() => import("@/pages/tools/cbor-encoder")); const MarkdownToHtml = lazy(() => import("@/pages/tools/markdown-to-html")); const ImageMetadata = lazy(() => import("@/pages/tools/image-metadata")); +const ImageCompressor = lazy(() => import("@/pages/tools/image-compressor")); const UrlEncoder = lazy(() => import("@/pages/tools/url-encoder")); const JwtDecoder = lazy(() => import("@/pages/tools/jwt-decoder")); const TlsDecoder = lazy(() => import("@/pages/tools/tls-decoder")); @@ -179,6 +180,7 @@ function Router() { component={ColorPaletteGenerator} /> + diff --git a/client/src/components/image-compare.tsx b/client/src/components/image-compare.tsx new file mode 100644 index 00000000..d2ecf494 --- /dev/null +++ b/client/src/components/image-compare.tsx @@ -0,0 +1,340 @@ +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, + type PointerEvent as ReactPointerEvent, + type RefObject, +} from "react"; +import * as DialogPrimitive from "@radix-ui/react-dialog"; +import { ArrowLeftRight, Loader2, X } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { cn } from "@/lib/utils"; + +export const CHECKERBOARD = + "bg-[length:16px_16px] bg-[linear-gradient(45deg,#e2e8f0_25%,transparent_25%),linear-gradient(-45deg,#e2e8f0_25%,transparent_25%),linear-gradient(45deg,transparent_75%,#e2e8f0_75%),linear-gradient(-45deg,transparent_75%,#e2e8f0_75%)] bg-[position:0_0,0_8px,8px_-8px,-8px_0] dark:bg-[linear-gradient(45deg,#334155_25%,transparent_25%),linear-gradient(-45deg,#334155_25%,transparent_25%),linear-gradient(45deg,transparent_75%,#334155_75%),linear-gradient(-45deg,transparent_75%,#334155_75%)]"; + +export interface CompareSource { + id: string; + label: string; + /** Short secondary text, e.g. the file size. */ + detail?: string; + /** Undefined while the source is still being produced. */ + url?: string; +} + +type Zoom = "fit" | 1 | 2 | 4; + +const ZOOM_OPTIONS: Array<{ value: Zoom; label: string }> = [ + { value: "fit", label: "Fit" }, + { value: 1, label: "100%" }, + { value: 2, label: "200%" }, + { value: 4, label: "400%" }, +]; + +interface ImageCompareProps { + open: boolean; + onOpenChange: (open: boolean) => void; + sources: CompareSource[]; + leftId: string; + rightId: string; + onLeftChange: (id: string) => void; + onRightChange: (id: string) => void; + /** Pixel dimensions every source is displayed at. */ + width: number; + height: number; + /** Shown under the toolbar, e.g. formats the browser can't display. */ + note?: string; +} + +function ComparePane({ + side, + paneRef, + sources, + selectedId, + onSelect, + zoom, + displayWidth, + displayHeight, + onScroll, +}: { + side: "left" | "right"; + paneRef: RefObject; + sources: CompareSource[]; + selectedId: string; + onSelect: (id: string) => void; + zoom: Zoom; + displayWidth: number; + displayHeight: number; + onScroll: () => void; +}) { + const source = sources.find(candidate => candidate.id === selectedId); + const drag = useRef<{ + x: number; + y: number; + left: number; + top: number; + } | null>(null); + + const onPointerDown = (event: ReactPointerEvent) => { + const pane = paneRef.current; + if (!pane || zoom === "fit" || event.button !== 0) return; + drag.current = { + x: event.clientX, + y: event.clientY, + left: pane.scrollLeft, + top: pane.scrollTop, + }; + pane.setPointerCapture(event.pointerId); + }; + + const onPointerMove = (event: ReactPointerEvent) => { + const pane = paneRef.current; + if (!pane || !drag.current) return; + pane.scrollLeft = drag.current.left - (event.clientX - drag.current.x); + pane.scrollTop = drag.current.top - (event.clientY - drag.current.y); + }; + + const endDrag = () => { + drag.current = null; + }; + + return ( +
+
+ + {source?.detail ? ( + + {source.detail} + + ) : null} +
+
+ {source?.url ? ( +
+ {source.label} +
+ ) : ( +
+ + Encoding… +
+ )} +
+
+ ); +} + +export function ImageCompare({ + open, + onOpenChange, + sources, + leftId, + rightId, + onLeftChange, + onRightChange, + width, + height, + note, +}: ImageCompareProps) { + const [zoom, setZoom] = useState(1); + const [pixelRatio, setPixelRatio] = useState(1); + const leftRef = useRef(null); + const rightRef = useRef(null); + const syncing = useRef(false); + + useEffect(() => { + if (open) setPixelRatio(window.devicePixelRatio || 1); + }, [open]); + + // 100% means one image pixel per physical screen pixel. + const scale = zoom === "fit" ? 1 : zoom / pixelRatio; + const displayWidth = Math.max(1, Math.round(width * scale)); + const displayHeight = Math.max(1, Math.round(height * scale)); + + const syncFrom = useCallback((from: "left" | "right") => { + if (syncing.current) return; + const source = (from === "left" ? leftRef : rightRef).current; + const target = (from === "left" ? rightRef : leftRef).current; + if (!source || !target) return; + syncing.current = true; + target.scrollLeft = source.scrollLeft; + target.scrollTop = source.scrollTop; + requestAnimationFrame(() => { + syncing.current = false; + }); + }, []); + + // Start each zoom level centred on the image. + useLayoutEffect(() => { + if (!open) return undefined; + const frame = requestAnimationFrame(() => { + for (const pane of [leftRef.current, rightRef.current]) { + if (!pane) continue; + pane.scrollLeft = (pane.scrollWidth - pane.clientWidth) / 2; + pane.scrollTop = (pane.scrollHeight - pane.clientHeight) / 2; + } + }); + return () => cancelAnimationFrame(frame); + }, [open, zoom, displayWidth, displayHeight]); + + return ( + + + + +
+ + Compare quality + + + Two images shown side by side at the same size. Scrolling or + dragging one pans both. + +
+ {ZOOM_OPTIONS.map(option => ( + + ))} +
+ + + + +
+

+ {zoom === "fit" + ? "Scaled to fit the window. Choose 100% to judge quality." + : `${zoom * 100}%: each image pixel is ${zoom === 1 ? "one screen pixel" : `${zoom}×${zoom} screen pixels`}. Drag or scroll to pan both sides together.`}{" "} + {width} × {height}px. + {note ? ` ${note}` : ""} +

+
+ syncFrom("left")} + /> + syncFrom("right")} + /> +
+
+
+
+ ); +} diff --git a/client/src/data/tools.ts b/client/src/data/tools.ts index 9324e656..1def9641 100644 --- a/client/src/data/tools.ts +++ b/client/src/data/tools.ts @@ -30,6 +30,7 @@ import { Link, Layers, FileImage, + ImageDown, // Text tools FileText, @@ -5095,6 +5096,82 @@ export const toolsData: ToolData = { ], }, }, + { + name: "Image Compressor", + path: "/tools/image-compressor", + icon: ImageDown, + shortcut: "Ctrl+Shift+Alt+C", + metadata: { + title: + "Image Compressor - Compare AVIF, WebP, JPEG XL, JPEG & PNG Sizes", + description: + "Compress an image into AVIF, WebP, JPEG XL, JPEG, PNG, and QOI at once. Compare file sizes and previews, tune quality, and download the best format. Runs locally in your browser.", + keywords: [ + "image compressor", + "compress image", + "convert to webp", + "convert to avif", + "jpeg xl converter", + "png optimizer", + "mozjpeg", + "oxipng", + "image format comparison", + "reduce image size", + ], + }, + explanations: { + notice: { + type: "privacy", + title: "Private, Local Compression", + items: [ + "Every format is encoded on your device with WebAssembly codecs", + "Your image is never uploaded to a server", + "Output files don't keep the original metadata (EXIF, GPS, color profiles)", + ], + }, + sections: [ + { + title: "Which Format to Pick", + items: [ + { + label: "AVIF:", + text: "Usually the smallest for photos. Supported by all modern browsers, but slow to encode", + }, + { + label: "WebP:", + text: "A safe default for the web. Small files, transparency, and universal browser support", + }, + { + label: "JPEG XL:", + text: "Excellent compression and lossless mode, but only Safari displays it natively today", + }, + { + label: "JPEG:", + text: "Works everywhere. Good for photos without transparency (transparent areas become white)", + }, + { + label: "PNG:", + text: "Lossless. Best for screenshots, logos, and graphics with sharp edges or few colors", + }, + { + label: "QOI:", + text: "Very fast lossless format for tooling and games. Browsers can't display it", + }, + ], + }, + { + title: "Settings Explained", + items: [ + "Quality: lower values give smaller files with more visible artifacts. 60-80 is a good range for photos", + "Lossless: keeps every pixel exactly, at the cost of larger files", + "Effort / Speed: more effort makes smaller files but takes longer to encode", + "Chroma subsampling 4:2:0 halves color resolution, which is fine for photos but can blur colored text", + "Resize first: halving the dimensions cuts file size by roughly 75%", + ], + }, + ], + }, + }, { name: "QR Generator", path: "/tools/qr-generator", diff --git a/client/src/lib/image-compression.ts b/client/src/lib/image-compression.ts new file mode 100644 index 00000000..08089e80 --- /dev/null +++ b/client/src/lib/image-compression.ts @@ -0,0 +1,366 @@ +export type ImageFormatId = "qoi" | "jpeg" | "png" | "webp" | "jxl" | "avif"; + +export type FormatSetting = + | { + type: "range"; + key: string; + label: string; + min: number; + max: number; + step: number; + defaultValue: number; + /** Disable this control while the given boolean setting is on. */ + disabledWhen?: string; + } + | { + type: "boolean"; + key: string; + label: string; + defaultValue: boolean; + } + | { + type: "select"; + key: string; + label: string; + options: Array<{ value: string; label: string }>; + defaultValue: string; + }; + +export type FormatSettingValues = Record; + +export interface ImageFormat { + id: ImageFormatId; + label: string; + codec: string; + mime: string; + extension: string; + supportsAlpha: boolean; + settings: FormatSetting[]; +} + +/** Ordered roughly fastest-to-slowest so results fill in progressively. */ +export const IMAGE_FORMATS: ImageFormat[] = [ + { + id: "qoi", + label: "QOI", + codec: "QOI", + mime: "image/qoi", + extension: "qoi", + supportsAlpha: true, + settings: [], + }, + { + id: "jpeg", + label: "JPEG", + codec: "MozJPEG", + mime: "image/jpeg", + extension: "jpg", + supportsAlpha: false, + settings: [ + { + type: "range", + key: "quality", + label: "Quality", + min: 0, + max: 100, + step: 1, + defaultValue: 75, + }, + { + type: "boolean", + key: "progressive", + label: "Progressive", + defaultValue: true, + }, + { + type: "select", + key: "subsample", + label: "Chroma subsampling", + options: [ + { value: "420", label: "4:2:0 (smaller)" }, + { value: "444", label: "4:4:4 (sharper color)" }, + ], + defaultValue: "420", + }, + ], + }, + { + id: "png", + label: "PNG", + codec: "OxiPNG", + mime: "image/png", + extension: "png", + supportsAlpha: true, + settings: [ + { + type: "range", + key: "level", + label: "Optimization level", + min: 0, + max: 6, + step: 1, + defaultValue: 2, + }, + { + type: "boolean", + key: "interlace", + label: "Interlaced", + defaultValue: false, + }, + ], + }, + { + id: "webp", + label: "WebP", + codec: "libwebp", + mime: "image/webp", + extension: "webp", + supportsAlpha: true, + settings: [ + { + type: "boolean", + key: "lossless", + label: "Lossless", + defaultValue: false, + }, + { + type: "range", + key: "quality", + label: "Quality", + min: 0, + max: 100, + step: 1, + defaultValue: 75, + disabledWhen: "lossless", + }, + { + type: "range", + key: "effort", + label: "Effort", + min: 0, + max: 6, + step: 1, + defaultValue: 4, + }, + ], + }, + { + id: "jxl", + label: "JPEG XL", + codec: "libjxl", + mime: "image/jxl", + extension: "jxl", + supportsAlpha: true, + settings: [ + { + type: "boolean", + key: "lossless", + label: "Lossless", + defaultValue: false, + }, + { + type: "range", + key: "quality", + label: "Quality", + min: 0, + max: 100, + step: 1, + defaultValue: 75, + disabledWhen: "lossless", + }, + { + type: "range", + key: "effort", + label: "Effort", + min: 1, + max: 9, + step: 1, + defaultValue: 7, + }, + ], + }, + { + id: "avif", + label: "AVIF", + codec: "libavif", + mime: "image/avif", + extension: "avif", + supportsAlpha: true, + settings: [ + { + type: "boolean", + key: "lossless", + label: "Lossless", + defaultValue: false, + }, + { + type: "range", + key: "quality", + label: "Quality", + min: 0, + max: 100, + step: 1, + defaultValue: 50, + disabledWhen: "lossless", + }, + { + type: "range", + key: "speed", + label: "Speed (higher is faster, larger)", + min: 0, + max: 10, + step: 1, + defaultValue: 6, + }, + { + type: "select", + key: "subsample", + label: "Chroma subsampling", + options: [ + { value: "420", label: "4:2:0 (smaller)" }, + { value: "444", label: "4:4:4 (sharper color)" }, + ], + defaultValue: "420", + }, + ], + }, +]; + +function getImageFormat(id: ImageFormatId): ImageFormat { + const format = IMAGE_FORMATS.find(candidate => candidate.id === id); + if (!format) throw new Error(`Unknown image format: ${id}`); + return format; +} + +export function getDefaultSettings(id: ImageFormatId): FormatSettingValues { + return Object.fromEntries( + getImageFormat(id).settings.map(setting => [ + setting.key, + setting.defaultValue, + ]) + ); +} + +export function getAllDefaultSettings(): Record< + ImageFormatId, + FormatSettingValues +> { + return Object.fromEntries( + IMAGE_FORMATS.map(format => [format.id, getDefaultSettings(format.id)]) + ) as Record; +} + +function num(values: FormatSettingValues, key: string): number { + return Number(values[key]); +} + +function bool(values: FormatSettingValues, key: string): boolean { + return values[key] === true; +} + +/** + * Translate UI settings into the option object each jSquash codec expects. + * Missing values fall back to the format's defaults. + */ +export function buildEncodeOptions( + id: ImageFormatId, + settings: FormatSettingValues = {} +): Record { + const values = { ...getDefaultSettings(id), ...settings }; + + switch (id) { + case "qoi": + return {}; + case "jpeg": + return { + quality: num(values, "quality"), + progressive: bool(values, "progressive"), + baseline: !bool(values, "progressive"), + auto_subsample: false, + // MozJPEG: 2 = 2x2 subsampling (4:2:0), 1 = none (4:4:4) + chroma_subsample: values.subsample === "444" ? 1 : 2, + }; + case "png": + return { + level: num(values, "level"), + interlace: bool(values, "interlace"), + }; + case "webp": + return { + quality: bool(values, "lossless") ? 100 : num(values, "quality"), + method: num(values, "effort"), + lossless: bool(values, "lossless") ? 1 : 0, + exact: bool(values, "lossless") ? 1 : 0, + }; + case "jxl": + return { + quality: bool(values, "lossless") ? 100 : num(values, "quality"), + effort: num(values, "effort"), + lossless: bool(values, "lossless"), + }; + case "avif": + return { + quality: bool(values, "lossless") ? 100 : num(values, "quality"), + speed: num(values, "speed"), + lossless: bool(values, "lossless"), + // libavif: 1 = 4:2:0, 3 = 4:4:4 + subsample: values.subsample === "444" ? 3 : 1, + }; + default: + throw new Error(`Unknown image format: ${String(id)}`); + } +} + +export function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +/** Size of `size` relative to `original`, as a whole-number percentage. */ +export function percentOfOriginal(size: number, original: number): number { + if (original <= 0) return 0; + return Math.round((size / original) * 100); +} + +/** Scale dimensions to fit within maxWidth x maxHeight, never upscaling. */ +export function fitDimensions( + width: number, + height: number, + maxWidth?: number, + maxHeight?: number +): { width: number; height: number } { + const scale = Math.min( + 1, + maxWidth && maxWidth > 0 ? maxWidth / width : 1, + maxHeight && maxHeight > 0 ? maxHeight / height : 1 + ); + return { + width: Math.max(1, Math.round(width * scale)), + height: Math.max(1, Math.round(height * scale)), + }; +} + +export function outputFileName( + originalName: string, + format: ImageFormat +): string { + const base = originalName.replace(/\.[^./\\]+$/, "") || "image"; + return `${base}.${format.extension}`; +} + +/** Composite RGBA pixels onto an opaque background (for formats without alpha). */ +export function flattenAlpha( + data: Uint8ClampedArray, + background: [number, number, number] = [255, 255, 255] +): Uint8ClampedArray { + const out = new Uint8ClampedArray(data.length); + for (let i = 0; i < data.length; i += 4) { + const alpha = data[i + 3] / 255; + out[i] = data[i] * alpha + background[0] * (1 - alpha); + out[i + 1] = data[i + 1] * alpha + background[1] * (1 - alpha); + out[i + 2] = data[i + 2] * alpha + background[2] * (1 - alpha); + out[i + 3] = 255; + } + return out; +} diff --git a/client/src/lib/image-compression.worker.ts b/client/src/lib/image-compression.worker.ts new file mode 100644 index 00000000..895b0bf0 --- /dev/null +++ b/client/src/lib/image-compression.worker.ts @@ -0,0 +1,86 @@ +import { + buildEncodeOptions, + flattenAlpha, + type FormatSettingValues, + type ImageFormatId, +} from "./image-compression"; + +export interface EncodeRequest { + id: number; + formatId: ImageFormatId; + width: number; + height: number; + pixels: Uint8ClampedArray; + settings: FormatSettingValues; +} + +export type EncodeResponse = + | { id: number; ok: true; buffer: ArrayBuffer; durationMs: number } + | { id: number; ok: false; error: string }; + +async function encode( + formatId: ImageFormatId, + image: ImageData, + settings: FormatSettingValues +): Promise { + const options = buildEncodeOptions(formatId, settings); + switch (formatId) { + case "qoi": { + const { default: encodeQoi } = await import("@jsquash/qoi/encode.js"); + return encodeQoi(image); + } + case "jpeg": { + const { default: encodeJpeg } = await import("@jsquash/jpeg/encode.js"); + const opaque = new ImageData( + flattenAlpha(image.data), + image.width, + image.height + ); + return encodeJpeg(opaque, options); + } + case "png": { + const { default: optimise } = await import("@jsquash/oxipng/optimise.js"); + return optimise(image, options); + } + case "webp": { + const { default: encodeWebp } = await import("@jsquash/webp/encode.js"); + return encodeWebp(image, options); + } + case "jxl": { + const { default: encodeJxl } = await import("@jsquash/jxl/encode.js"); + return encodeJxl(image, options); + } + case "avif": { + const { default: encodeAvif } = await import("@jsquash/avif/encode.js"); + return encodeAvif(image, options); + } + default: + throw new Error(`Unknown image format: ${String(formatId)}`); + } +} + +self.onmessage = async (event: MessageEvent) => { + const { id, formatId, width, height, pixels, settings } = event.data; + const started = performance.now(); + try { + const buffer = await encode( + formatId, + new ImageData(pixels, width, height), + settings + ); + const response: EncodeResponse = { + id, + ok: true, + buffer, + durationMs: performance.now() - started, + }; + self.postMessage(response, { transfer: [buffer] }); + } catch (cause) { + const response: EncodeResponse = { + id, + ok: false, + error: cause instanceof Error ? cause.message : String(cause), + }; + self.postMessage(response); + } +}; diff --git a/client/src/pages/tools/image-compressor.tsx b/client/src/pages/tools/image-compressor.tsx new file mode 100644 index 00000000..0bdc56f7 --- /dev/null +++ b/client/src/pages/tools/image-compressor.tsx @@ -0,0 +1,993 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + ArrowDownWideNarrow, + Columns2, + ChevronDown, + Download, + Loader2, + Upload, +} from "lucide-react"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Slider } from "@/components/ui/slider"; +import { Switch } from "@/components/ui/switch"; +import { + ActionButtonGroup, + ClearButton, + DataButtonGroup, + ToolButtonGroup, +} from "@/components/ui/tool-button"; +import { SecurityBanner } from "@/components/ui/security-banner"; +import { ShortcutBadge } from "@/components/ui/shortcut-badge"; +import { ToolExplanations } from "@/components/tool-explanations"; +import { + CHECKERBOARD, + ImageCompare, + type CompareSource, +} from "@/components/image-compare"; +import { getToolByPath } from "@/data/tools"; +import { + IMAGE_FORMATS, + fitDimensions, + formatBytes, + getAllDefaultSettings, + outputFileName, + percentOfOriginal, + type FormatSetting, + type FormatSettingValues, + type ImageFormat, + type ImageFormatId, +} from "@/lib/image-compression"; +import type { + EncodeRequest, + EncodeResponse, +} from "@/lib/image-compression.worker"; +import { cn } from "@/lib/utils"; + +interface WorkingImage { + width: number; + height: number; + pixels: Uint8ClampedArray; +} + +type FormatResult = + | { status: "encoding" } + | { status: "error"; error: string } + | { + status: "done"; + blob: Blob; + url: string; + size: number; + durationMs: number; + previewFailed?: boolean; + }; + +const SETTINGS_DEBOUNCE_MS = 300; +const RESIZE_DEBOUNCE_MS = 400; + +function parseDimension(value: string): number | undefined { + const parsed = Number.parseInt(value, 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined; +} + +function rasterize( + bitmap: ImageBitmap, + maxWidth?: number, + maxHeight?: number +): WorkingImage { + const { width, height } = fitDimensions( + bitmap.width, + bitmap.height, + maxWidth, + maxHeight + ); + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + const context = canvas.getContext("2d", { willReadFrequently: true }); + if (!context) throw new Error("Canvas 2D context is not available"); + context.imageSmoothingEnabled = true; + context.imageSmoothingQuality = "high"; + context.drawImage(bitmap, 0, 0, width, height); + return { + width, + height, + pixels: context.getImageData(0, 0, width, height).data, + }; +} + +function SettingControl({ + formatId, + setting, + values, + onChange, +}: { + formatId: ImageFormatId; + setting: FormatSetting; + values: FormatSettingValues; + onChange: (key: string, value: number | boolean | string) => void; +}) { + const id = `${formatId}-${setting.key}`; + + if (setting.type === "boolean") { + return ( +
+ + onChange(setting.key, checked)} + data-testid={`setting-${id}`} + /> +
+ ); + } + + if (setting.type === "select") { + return ( +
+ + +
+ ); + } + + const disabled = + setting.disabledWhen !== undefined && values[setting.disabledWhen] === true; + const value = Number(values[setting.key]); + + return ( +
+
+ + + {value} + +
+ onChange(setting.key, next)} + data-testid={`setting-${id}`} + /> +
+ ); +} + +export default function ImageCompressor() { + const tool = getToolByPath("/tools/image-compressor"); + const [imageFile, setImageFile] = useState(null); + const [originalUrl, setOriginalUrl] = useState(null); + const [sourceSize, setSourceSize] = useState<{ + width: number; + height: number; + } | null>(null); + const [workingImage, setWorkingImage] = useState(null); + const [maxWidth, setMaxWidth] = useState(""); + const [maxHeight, setMaxHeight] = useState(""); + const [settings, setSettings] = useState(getAllDefaultSettings); + const [results, setResults] = useState< + Partial> + >({}); + const [openSettings, setOpenSettings] = useState< + Partial> + >({}); + const [sortBySize, setSortBySize] = useState(false); + const [compare, setCompare] = useState<{ + left: string; + right: string; + } | null>(null); + const [error, setError] = useState(null); + + const fileInputRef = useRef(null); + const bitmapRef = useRef(null); + const workingImageRef = useRef(null); + const settingsRef = useRef(settings); + const workerRef = useRef(null); + const pendingRef = useRef( + new Map< + number, + { resolve: (r: EncodeResponse) => void; reject: (e: Error) => void } + >() + ); + const requestIdRef = useRef(0); + const queueRef = useRef([]); + const runningRef = useRef(false); + const sessionRef = useRef(0); + const versionsRef = useRef>>({}); + const settingTimersRef = useRef< + Partial>> + >({}); + const urlsRef = useRef(new Set()); + + settingsRef.current = settings; + + const trackUrl = (url: string) => { + urlsRef.current.add(url); + return url; + }; + + const revokeUrl = (url: string) => { + URL.revokeObjectURL(url); + urlsRef.current.delete(url); + }; + + const getWorker = useCallback(() => { + if (!workerRef.current) { + const worker = new Worker( + new URL("../../lib/image-compression.worker.ts", import.meta.url), + { type: "module" } + ); + worker.onmessage = (event: MessageEvent) => { + const pending = pendingRef.current.get(event.data.id); + if (!pending) return; + pendingRef.current.delete(event.data.id); + pending.resolve(event.data); + }; + worker.onerror = event => { + const failure = new Error(event.message || "Encoder worker crashed"); + pendingRef.current.forEach(pending => pending.reject(failure)); + pendingRef.current.clear(); + worker.terminate(); + if (workerRef.current === worker) workerRef.current = null; + }; + workerRef.current = worker; + } + return workerRef.current; + }, []); + + const encodeInWorker = useCallback( + ( + formatId: ImageFormatId, + image: WorkingImage, + formatSettings: FormatSettingValues + ) => + new Promise((resolve, reject) => { + const id = ++requestIdRef.current; + pendingRef.current.set(id, { resolve, reject }); + const request: EncodeRequest = { + id, + formatId, + width: image.width, + height: image.height, + pixels: image.pixels, + settings: formatSettings, + }; + getWorker().postMessage(request); + }), + [getWorker] + ); + + const setResult = useCallback( + (formatId: ImageFormatId, result: FormatResult) => { + setResults(previous => { + const old = previous[formatId]; + if ( + old?.status === "done" && + (result.status !== "done" || old.url !== result.url) + ) { + revokeUrl(old.url); + } + return { ...previous, [formatId]: result }; + }); + }, + [] + ); + + const runQueue = useCallback(async () => { + if (runningRef.current) return; + runningRef.current = true; + const session = sessionRef.current; + + while (queueRef.current.length > 0) { + const formatId = queueRef.current.shift()!; + const image = workingImageRef.current; + if (!image) continue; + const version = versionsRef.current[formatId] ?? 0; + setResult(formatId, { status: "encoding" }); + + let response: EncodeResponse; + try { + response = await encodeInWorker( + formatId, + image, + settingsRef.current[formatId] + ); + } catch (cause) { + if (session !== sessionRef.current) return; + response = { + id: 0, + ok: false, + error: cause instanceof Error ? cause.message : String(cause), + }; + } + + if (session !== sessionRef.current) return; + if (version !== (versionsRef.current[formatId] ?? 0)) continue; + + const format = IMAGE_FORMATS.find(f => f.id === formatId)!; + if (response.ok) { + const blob = new Blob([response.buffer], { type: format.mime }); + setResult(formatId, { + status: "done", + blob, + url: trackUrl(URL.createObjectURL(blob)), + size: blob.size, + durationMs: response.durationMs, + }); + } else { + setResult(formatId, { status: "error", error: response.error }); + } + } + + runningRef.current = false; + }, [encodeInWorker, setResult]); + + const enqueue = useCallback( + (formatIds: ImageFormatId[]) => { + for (const formatId of formatIds) { + versionsRef.current[formatId] = + (versionsRef.current[formatId] ?? 0) + 1; + if (!queueRef.current.includes(formatId)) { + queueRef.current.push(formatId); + } + setResult(formatId, { status: "encoding" }); + } + void runQueue(); + }, + [runQueue, setResult] + ); + + /** Abandon all in-flight work: new session, fresh worker, empty queue. */ + const resetEncoding = useCallback(() => { + sessionRef.current += 1; + queueRef.current = []; + runningRef.current = false; + Object.values(settingTimersRef.current).forEach(timer => + clearTimeout(timer) + ); + settingTimersRef.current = {}; + workerRef.current?.terminate(); + workerRef.current = null; + const aborted = new Error("Encoding cancelled"); + pendingRef.current.forEach(pending => pending.reject(aborted)); + pendingRef.current.clear(); + setResults(previous => { + Object.values(previous).forEach(result => { + if (result?.status === "done") revokeUrl(result.url); + }); + return {}; + }); + }, []); + + // Re-rasterize when the image or resize bounds change, then encode everything. + useEffect(() => { + const bitmap = bitmapRef.current; + if (!bitmap || !imageFile) return undefined; + const timer = setTimeout( + () => { + try { + const image = rasterize( + bitmap, + parseDimension(maxWidth), + parseDimension(maxHeight) + ); + resetEncoding(); + workingImageRef.current = image; + setWorkingImage(image); + enqueue(IMAGE_FORMATS.map(format => format.id)); + } catch (cause) { + setError( + cause instanceof Error ? cause.message : "Could not read the image" + ); + } + }, + workingImageRef.current ? RESIZE_DEBOUNCE_MS : 0 + ); + return () => clearTimeout(timer); + }, [imageFile, sourceSize, maxWidth, maxHeight, enqueue, resetEncoding]); + + useEffect( + () => () => { + sessionRef.current += 1; + workerRef.current?.terminate(); + bitmapRef.current?.close(); + Object.values(settingTimersRef.current).forEach(timer => + clearTimeout(timer) + ); + urlsRef.current.forEach(url => URL.revokeObjectURL(url)); + urlsRef.current.clear(); + }, + [] + ); + + const clearImage = () => { + setCompare(null); + resetEncoding(); + bitmapRef.current?.close(); + bitmapRef.current = null; + workingImageRef.current = null; + if (originalUrl) revokeUrl(originalUrl); + setOriginalUrl(null); + setImageFile(null); + setSourceSize(null); + setWorkingImage(null); + setError(null); + }; + + const handleFile = async (file: File | undefined) => { + if (!file) return; + if (!file.type.startsWith("image/") && file.type !== "") { + setError("Please choose an image file."); + return; + } + clearImage(); + try { + const bitmap = await createImageBitmap(file); + bitmapRef.current = bitmap; + setOriginalUrl(trackUrl(URL.createObjectURL(file))); + setSourceSize({ width: bitmap.width, height: bitmap.height }); + setImageFile(file); + } catch { + setError( + "This browser could not decode the image. Try a JPEG, PNG, WebP, GIF, or AVIF file." + ); + } + }; + + const updateSetting = ( + formatId: ImageFormatId, + key: string, + value: number | boolean | string + ) => { + setSettings(previous => { + const next = { + ...previous, + [formatId]: { ...previous[formatId], [key]: value }, + }; + settingsRef.current = next; + return next; + }); + if (!workingImageRef.current) return; + clearTimeout(settingTimersRef.current[formatId]); + settingTimersRef.current[formatId] = setTimeout(() => { + delete settingTimersRef.current[formatId]; + enqueue([formatId]); + }, SETTINGS_DEBOUNCE_MS); + }; + + const resetSettings = (formatId: ImageFormatId) => { + const defaults = getAllDefaultSettings()[formatId]; + setSettings(previous => { + const next = { ...previous, [formatId]: defaults }; + settingsRef.current = next; + return next; + }); + if (workingImageRef.current) enqueue([formatId]); + }; + + const download = (format: ImageFormat, result: FormatResult) => { + if (result.status !== "done" || !imageFile) return; + const link = document.createElement("a"); + link.href = result.url; + link.download = outputFileName(imageFile.name, format); + document.body.appendChild(link); + link.click(); + link.remove(); + }; + + const smallestId = useMemo(() => { + let best: { id: ImageFormatId; size: number } | null = null; + for (const format of IMAGE_FORMATS) { + const result = results[format.id]; + if (result?.status === "done" && (!best || result.size < best.size)) { + best = { id: format.id, size: result.size }; + } + } + return best?.id ?? null; + }, [results]); + + const orderedFormats = useMemo(() => { + if (!sortBySize) return IMAGE_FORMATS; + const sizeOf = (id: ImageFormatId) => { + const result = results[id]; + return result?.status === "done" ? result.size : Number.POSITIVE_INFINITY; + }; + return [...IMAGE_FORMATS].sort((a, b) => sizeOf(a.id) - sizeOf(b.id)); + }, [results, sortBySize]); + + const compareSources = useMemo(() => { + if (!imageFile || !originalUrl) return []; + const resized = + workingImage && + sourceSize && + (workingImage.width !== sourceSize.width || + workingImage.height !== sourceSize.height); + const sources: CompareSource[] = [ + { + id: "original", + label: resized ? "Original (resized)" : "Original", + detail: formatBytes(imageFile.size), + url: originalUrl, + }, + ]; + for (const format of IMAGE_FORMATS) { + const result = results[format.id]; + if (result?.status === "done" && result.previewFailed) continue; + sources.push({ + id: format.id, + label: format.label, + detail: + result?.status === "done" + ? `${formatBytes(result.size)} · ${percentOfOriginal(result.size, imageFile.size)}%` + : undefined, + url: result?.status === "done" ? result.url : undefined, + }); + } + return sources; + }, [imageFile, originalUrl, results, sourceSize, workingImage]); + + const hiddenFromCompare = IMAGE_FORMATS.filter(format => { + const result = results[format.id]; + return result?.status === "done" && result.previewFailed; + }).map(format => format.label); + + const canCompare = (formatId: ImageFormatId) => { + const result = results[formatId]; + return result?.status === "done" && !result.previewFailed; + }; + + const openCompare = (right: string, left = "original") => + setCompare({ left, right }); + + const isEncoding = Object.values(results).some( + result => result?.status === "encoding" + ); + + const markPreviewFailed = (formatId: ImageFormatId) => + setResults(previous => { + const current = previous[formatId]; + if (current?.status !== "done") return previous; + return { + ...previous, + [formatId]: { ...current, previewFailed: true }, + }; + }); + + const renderPreview = (format: ImageFormat, result?: FormatResult) => { + if (result?.status === "done") { + if (result.previewFailed) { + return ( +

+ Your browser can't display {format.label} images. The file was + still created and can be downloaded. +

+ ); + } + return ( + {`${format.label} markPreviewFailed(format.id)} + /> + ); + } + if (result?.status === "error") { + return ( +

+ Encoding failed: {result.error} +

+ ); + } + return ( +
+ + Encoding… +
+ ); + }; + + const renderResultCard = (format: ImageFormat) => { + const result = results[format.id]; + const values = settings[format.id]; + const settingsOpen = openSettings[format.id] === true; + const percent = + result?.status === "done" && imageFile + ? percentOfOriginal(result.size, imageFile.size) + : null; + + return ( + + +
+
+ + {format.label} + {smallestId === format.id ? ( + + Smallest + + ) : null} + +

+ {format.codec} · .{format.extension} + {format.supportsAlpha ? "" : " · no transparency"} +

+
+
+ {result?.status === "done" ? ( + <> +
+ {formatBytes(result.size)} +
+
+ {percent}% of original · {Math.round(result.durationMs)} ms +
+ + ) : null} +
+
+
+ +
+ {renderPreview(format, result)} +
+ +
+ + + {format.settings.length > 0 ? ( + + ) : null} +
+ + {settingsOpen ? ( +
+ {format.settings.map(setting => ( + + updateSetting(format.id, key, value) + } + /> + ))} + +
+ ) : null} +
+
+ ); + }; + + return ( +
+
+

+ Image Compressor + {tool?.shortcut ? : null} +

+
+

+ Compress an image into multiple formats and compare sizes side by + side +

+ +
+
+ + {error ? ( + + + {error} + + + ) : null} + + + + + + {isEncoding ? ( + + + Encoding… + + ) : null} + + + + + + +
+ + + Choose an image + + + + + {imageFile ? ( +
+ + {imageFile.name} + + + {formatBytes(imageFile.size)} + + {sourceSize ? ( + + {sourceSize.width} × {sourceSize.height}px + + ) : null} + {imageFile.type ? {imageFile.type} : null} +
+ ) : null} +
+
+ + + + Resize (optional) + + +

+ Shrink the image to fit within these bounds before compressing. + Aspect ratio is kept and images are never enlarged. +

+
+
+ + setMaxWidth(event.target.value)} + data-testid="max-width-input" + /> +
+
+ + setMaxHeight(event.target.value)} + data-testid="max-height-input" + /> +
+
+ {workingImage && + sourceSize && + (workingImage.width !== sourceSize.width || + workingImage.height !== sourceSize.height) ? ( +

+ Output: {workingImage.width} × {workingImage.height}px +

+ ) : null} +
+
+
+ + {imageFile ? ( +
+ {orderedFormats.map(renderResultCard)} +
+ ) : null} + +

+ Compression runs on this device with WebAssembly encoders. Your image is + never uploaded. Output files do not keep the original metadata (EXIF, + GPS, color profiles). +

+ + {compare && workingImage ? ( + { + if (!open) setCompare(null); + }} + sources={compareSources} + leftId={compare.left} + rightId={compare.right} + onLeftChange={left => + setCompare(previous => previous && { ...previous, left }) + } + onRightChange={right => + setCompare(previous => previous && { ...previous, right }) + } + width={workingImage.width} + height={workingImage.height} + note={ + hiddenFromCompare.length + ? `${hiddenFromCompare.join(", ")} can't be shown because this browser can't display ${hiddenFromCompare.length === 1 ? "it" : "them"}.` + : undefined + } + /> + ) : null} + + +
+ ); +} diff --git a/client/src/pages/tools/image-metadata.tsx b/client/src/pages/tools/image-metadata.tsx index 1c3cdee1..7a0654d6 100644 --- a/client/src/pages/tools/image-metadata.tsx +++ b/client/src/pages/tools/image-metadata.tsx @@ -22,16 +22,11 @@ import { readC2paManifest, } from "@/lib/c2pa-metadata"; import { findImageAiIndicators } from "@/lib/image-ai-indicators"; +import { formatBytes } from "@/lib/image-compression"; import { extractPngTextMetadata } from "@/lib/png-text-metadata"; import { useToast } from "@/hooks/use-toast"; import type { ManifestStore } from "@contentauth/c2pa-web"; -function formatBytes(bytes: number): string { - if (bytes < 1024) return `${bytes} B`; - if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; - return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; -} - function stringifyMetadata(metadata: Record): string { return JSON.stringify( metadata, diff --git a/package-lock.json b/package-lock.json index 5ba6ae3c..5a4e701f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,12 @@ "@codemirror/view": "^6.38.1", "@contentauth/c2pa-web": "^0.15.4", "@eslint/js": "^9.33.0", + "@jsquash/avif": "^2.1.1", + "@jsquash/jpeg": "^1.6.0", + "@jsquash/jxl": "^1.3.0", + "@jsquash/oxipng": "^2.3.0", + "@jsquash/qoi": "^1.1.0", + "@jsquash/webp": "^1.5.0", "@peculiar/x509": "^2.0.0", "@playwright/test": "^1.57.0", "@radix-ui/react-alert-dialog": "^1.1.7", @@ -1722,6 +1728,54 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@jsquash/avif": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@jsquash/avif/-/avif-2.1.1.tgz", + "integrity": "sha512-LMRxd0fMgfCLtobDh0/sFYJMMiRJTNYSEEWvRDKXlAeZ08t3gI5V+1thIT0XjXJ+SVG7Zug9B0XPyx0Ti5VRNA==", + "license": "Apache-2.0", + "dependencies": { + "wasm-feature-detect": "^1.2.11" + } + }, + "node_modules/@jsquash/jpeg": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jsquash/jpeg/-/jpeg-1.6.0.tgz", + "integrity": "sha512-zwN46Awh1VM6gXlIcALwb5WzqK5H2e6+Awcs1QP8AvS8ohsK/sbE4esvmH4jhlhW7+CgiUUww66vg0aTnlSIMA==", + "license": "Apache-2.0" + }, + "node_modules/@jsquash/jxl": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@jsquash/jxl/-/jxl-1.3.0.tgz", + "integrity": "sha512-IVOPTneyOd9eBAuow+FnCYIP6wkIc7CjrCDnZGiqAPyJ63vMVxv3zoWiucGiZVh6u9vi/l40AkcS9QwkoVSAqA==", + "license": "Apache-2.0", + "dependencies": { + "wasm-feature-detect": "^1.5.1" + } + }, + "node_modules/@jsquash/oxipng": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@jsquash/oxipng/-/oxipng-2.3.0.tgz", + "integrity": "sha512-aQ8wiEp6ztlTMXc+RMt/CG8crU3mEHDU+h+JYkIi6ctMhlh8+Ltj5XwQFfBuyzKYrp8NxaFW80Dp824bqjr+zA==", + "license": "Apache-2.0", + "dependencies": { + "wasm-feature-detect": "^1.2.11" + } + }, + "node_modules/@jsquash/qoi": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@jsquash/qoi/-/qoi-1.1.0.tgz", + "integrity": "sha512-GV+Gy3zSMSEsjXjeiVO6vTPp4bTSKXVe4CjbHQFEu60edt09gl0cqEuEU5Sp0V5tXvU91sB5MW8tKZyDLEdWlQ==", + "license": "Apache-2.0" + }, + "node_modules/@jsquash/webp": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jsquash/webp/-/webp-1.5.0.tgz", + "integrity": "sha512-KggLoj2MnRSfIqTeKe1EmbljTX2vuV7mh79k89PCL1pyqiDULcPM1L47twxXt0hkb68F70bXiL31MxsuoZtKFw==", + "license": "Apache-2.0", + "dependencies": { + "wasm-feature-detect": "^1.2.11" + } + }, "node_modules/@lezer/common": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.2.3.tgz", @@ -10818,6 +10872,12 @@ "loose-envify": "^1.0.0" } }, + "node_modules/wasm-feature-detect": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/wasm-feature-detect/-/wasm-feature-detect-1.10.1.tgz", + "integrity": "sha512-+wz9+WpMKgQ7H1tm41nJbFwAvwX4DqY0jNY8Blw5Qe6hHg1yhCJ+AqU0R4lgX7p3pyo8irYIl1+mMNoBwSj2Zg==", + "license": "Apache-2.0" + }, "node_modules/webidl-conversions": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", diff --git a/package.json b/package.json index 4cd649f5..c784e495 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,12 @@ "@codemirror/view": "^6.38.1", "@contentauth/c2pa-web": "^0.15.4", "@eslint/js": "^9.33.0", + "@jsquash/avif": "^2.1.1", + "@jsquash/jpeg": "^1.6.0", + "@jsquash/jxl": "^1.3.0", + "@jsquash/oxipng": "^2.3.0", + "@jsquash/qoi": "^1.1.0", + "@jsquash/webp": "^1.5.0", "@peculiar/x509": "^2.0.0", "@playwright/test": "^1.57.0", "@radix-ui/react-alert-dialog": "^1.1.7", diff --git a/tests/e2e/tools/image-compressor.spec.ts b/tests/e2e/tools/image-compressor.spec.ts new file mode 100644 index 00000000..35cea36a --- /dev/null +++ b/tests/e2e/tools/image-compressor.spec.ts @@ -0,0 +1,183 @@ +import { test, expect, type Page } from "@playwright/test"; +import { setupJSErrorCollection, expectNoErrors } from "./utils"; + +const FORMATS = ["qoi", "jpeg", "png", "webp", "jxl", "avif"] as const; + +/** Render a gradient PNG in the browser so codecs have real pixels to work with. */ +async function makeTestPng( + page: Page, + width = 64, + height = 48 +): Promise { + const base64 = await page.evaluate( + ([w, h]) => { + const canvas = document.createElement("canvas"); + canvas.width = w; + canvas.height = h; + const context = canvas.getContext("2d")!; + const gradient = context.createLinearGradient(0, 0, w, h); + gradient.addColorStop(0, "#ff0080"); + gradient.addColorStop(1, "#00c8ff"); + context.fillStyle = gradient; + context.fillRect(0, 0, w, h); + context.clearRect(0, 0, 16, 16); + return canvas.toDataURL("image/png").split(",")[1]; + }, + [width, height] + ); + return Buffer.from(base64, "base64"); +} + +async function uploadTestImage(page: Page, width = 64, height = 48) { + await page.getByTestId("image-file-input").setInputFiles({ + name: "gradient.png", + mimeType: "image/png", + buffer: await makeTestPng(page, width, height), + }); +} + +async function waitForAllResults(page: Page) { + for (const format of FORMATS) { + await expect(page.getByTestId(`result-size-${format}`)).toBeVisible({ + timeout: 60_000, + }); + } +} + +test.describe("Image Compressor Tool", () => { + test.beforeEach(async ({ page }) => { + await setupJSErrorCollection(page); + await page.goto("/tools/image-compressor"); + }); + + test("encodes an uploaded image into every format", async ({ page }) => { + await uploadTestImage(page); + + await expect(page.getByText("gradient.png")).toBeVisible(); + await expect(page.getByText("64 × 48px")).toBeVisible(); + await waitForAllResults(page); + + for (const format of FORMATS) { + await expect(page.getByTestId(`result-size-${format}`)).toContainText( + /\d+(\.\d+)? (B|KB|MB)/ + ); + await expect(page.getByTestId(`download-${format}`)).toBeEnabled(); + } + await expect(page.locator('[data-testid^="smallest-"]')).toHaveCount(1); + await expect(page.getByTestId("preview-png")).toBeVisible(); + + await expectNoErrors(page); + }); + + test("downloads a format with the right file name", async ({ page }) => { + await uploadTestImage(page); + await expect(page.getByTestId("result-size-webp")).toBeVisible({ + timeout: 60_000, + }); + + const downloadPromise = page.waitForEvent("download"); + await page.getByTestId("download-webp").click(); + const download = await downloadPromise; + expect(download.suggestedFilename()).toBe("gradient.webp"); + }); + + test("re-encodes a format when its settings change", async ({ page }) => { + await uploadTestImage(page); + await waitForAllResults(page); + + const size = page.getByTestId("result-size-jpeg"); + const before = await size.textContent(); + + await page.getByTestId("settings-toggle-jpeg").click(); + const slider = page.getByTestId("setting-jpeg-quality"); + await slider.locator('[role="slider"]').focus(); + await page.keyboard.press("End"); + + await expect(size).not.toHaveText(before ?? "", { timeout: 30_000 }); + await expectNoErrors(page); + }); + + test("resizes before compressing", async ({ page }) => { + await uploadTestImage(page); + await page.getByTestId("max-width-input").fill("32"); + await expect(page.getByTestId("output-dimensions")).toHaveText( + "Output: 32 × 24px" + ); + await waitForAllResults(page); + }); + + test("clears the image and results", async ({ page }) => { + await uploadTestImage(page); + await expect(page.getByTestId("results-grid")).toBeVisible(); + + await page.getByTestId("clear-button").click(); + await page.getByTestId("button-clear-confirm").click(); + + await expect(page.getByTestId("results-grid")).toHaveCount(0); + await expect(page.getByText("gradient.png")).toHaveCount(0); + }); + + test("compares two images side by side at true size", async ({ page }) => { + await uploadTestImage(page); + await waitForAllResults(page); + + await page.getByTestId("compare-webp").click(); + const dialog = page.getByTestId("image-compare-dialog"); + await expect(dialog).toBeVisible(); + await expect(page.getByTestId("compare-select-left")).toContainText( + "Original" + ); + await expect(page.getByTestId("compare-select-right")).toContainText( + "WebP" + ); + + const ratio = await page.evaluate(() => window.devicePixelRatio); + const left = page.getByTestId("compare-image-left"); + const right = page.getByTestId("compare-image-right"); + await expect(left).toBeVisible(); + await expect(right).toBeVisible(); + for (const image of [left, right]) { + const box = await image.boundingBox(); + expect(box?.width).toBeCloseTo(64 / ratio, 0); + expect(box?.height).toBeCloseTo(48 / ratio, 0); + } + + await page.getByTestId("compare-zoom-200%").click(); + expect((await right.boundingBox())?.width).toBeCloseTo(128 / ratio, 0); + + await page.getByTestId("compare-swap").click(); + await expect(page.getByTestId("compare-select-left")).toContainText("WebP"); + await expect(page.getByTestId("compare-select-right")).toContainText( + "Original" + ); + + await page.getByTestId("compare-close").click(); + await expect(dialog).toHaveCount(0); + await expectNoErrors(page); + }); + + test("pans both comparison panes together", async ({ page }) => { + await uploadTestImage(page, 2400, 1800); + await expect(page.getByTestId("result-size-png")).toBeVisible({ + timeout: 60_000, + }); + + await page.getByTestId("compare-png").click(); + const leftViewport = page.getByTestId("compare-viewport-left"); + const rightViewport = page.getByTestId("compare-viewport-right"); + await expect(page.getByTestId("compare-image-right")).toBeVisible(); + + await leftViewport.evaluate(element => { + element.scrollLeft = 150; + element.scrollTop = 120; + }); + await expect + .poll(() => + rightViewport.evaluate(element => [ + Math.round(element.scrollLeft), + Math.round(element.scrollTop), + ]) + ) + .toEqual([150, 120]); + }); +}); diff --git a/tests/lib/image-compression.test.ts b/tests/lib/image-compression.test.ts new file mode 100644 index 00000000..079a5d99 --- /dev/null +++ b/tests/lib/image-compression.test.ts @@ -0,0 +1,163 @@ +import { describe, it, expect } from "vitest"; +import { + IMAGE_FORMATS, + buildEncodeOptions, + fitDimensions, + flattenAlpha, + formatBytes, + getAllDefaultSettings, + getDefaultSettings, + outputFileName, + percentOfOriginal, +} from "../../client/src/lib/image-compression"; + +describe("Image compression formats", () => { + it("defines every format with unique ids and extensions", () => { + const ids = IMAGE_FORMATS.map(format => format.id); + expect(ids).toEqual(["qoi", "jpeg", "png", "webp", "jxl", "avif"]); + expect(new Set(IMAGE_FORMATS.map(f => f.extension)).size).toBe(ids.length); + for (const format of IMAGE_FORMATS) { + expect(format.mime).toMatch(/^image\//); + } + }); + + it("has defaults that sit inside each range setting", () => { + for (const format of IMAGE_FORMATS) { + for (const setting of format.settings) { + if (setting.type === "range") { + expect(setting.defaultValue).toBeGreaterThanOrEqual(setting.min); + expect(setting.defaultValue).toBeLessThanOrEqual(setting.max); + } + if (setting.type === "select") { + expect(setting.options.map(o => o.value)).toContain( + setting.defaultValue + ); + } + if (setting.type === "range" && setting.disabledWhen) { + expect(format.settings.map(s => s.key)).toContain( + setting.disabledWhen + ); + } + } + } + }); + + it("builds defaults for all formats", () => { + const all = getAllDefaultSettings(); + expect(Object.keys(all)).toHaveLength(IMAGE_FORMATS.length); + expect(getDefaultSettings("jpeg")).toEqual({ + quality: 75, + progressive: true, + subsample: "420", + }); + expect(getDefaultSettings("qoi")).toEqual({}); + }); +}); + +describe("buildEncodeOptions", () => { + it("maps JPEG settings to MozJPEG options", () => { + expect(buildEncodeOptions("jpeg")).toEqual({ + quality: 75, + progressive: true, + baseline: false, + auto_subsample: false, + chroma_subsample: 2, + }); + expect( + buildEncodeOptions("jpeg", { progressive: false, subsample: "444" }) + ).toMatchObject({ + progressive: false, + baseline: true, + chroma_subsample: 1, + }); + }); + + it("maps WebP lossless to numeric libwebp flags", () => { + expect(buildEncodeOptions("webp", { lossless: true, quality: 40 })).toEqual( + { quality: 100, method: 4, lossless: 1, exact: 1 } + ); + expect(buildEncodeOptions("webp")).toMatchObject({ + quality: 75, + lossless: 0, + }); + }); + + it("maps AVIF and JPEG XL options", () => { + expect(buildEncodeOptions("avif", { subsample: "444" })).toEqual({ + quality: 50, + speed: 6, + lossless: false, + subsample: 3, + }); + expect(buildEncodeOptions("jxl", { lossless: true })).toEqual({ + quality: 100, + effort: 7, + lossless: true, + }); + }); + + it("maps PNG settings to OxiPNG options", () => { + expect(buildEncodeOptions("png", { level: 4, interlace: true })).toEqual({ + level: 4, + interlace: true, + }); + expect(buildEncodeOptions("qoi")).toEqual({}); + }); +}); + +describe("helpers", () => { + it("formats byte sizes", () => { + expect(formatBytes(512)).toBe("512 B"); + expect(formatBytes(2048)).toBe("2.0 KB"); + expect(formatBytes(3 * 1024 * 1024)).toBe("3.0 MB"); + }); + + it("computes percent of original", () => { + expect(percentOfOriginal(25, 100)).toBe(25); + expect(percentOfOriginal(150, 100)).toBe(150); + expect(percentOfOriginal(10, 0)).toBe(0); + }); + + it("fits dimensions without upscaling", () => { + expect(fitDimensions(4000, 3000, 1000)).toEqual({ + width: 1000, + height: 750, + }); + expect(fitDimensions(4000, 3000, 1000, 300)).toEqual({ + width: 400, + height: 300, + }); + expect(fitDimensions(100, 50, 1000, 1000)).toEqual({ + width: 100, + height: 50, + }); + expect(fitDimensions(100, 50)).toEqual({ width: 100, height: 50 }); + }); + + it("names output files with the format extension", () => { + const jpeg = IMAGE_FORMATS.find(f => f.id === "jpeg")!; + expect(outputFileName("holiday.photo.png", jpeg)).toBe("holiday.photo.jpg"); + expect(outputFileName("noext", jpeg)).toBe("noext.jpg"); + expect(outputFileName(".png", jpeg)).toBe("image.jpg"); + }); + + it("flattens transparent pixels onto white", () => { + const pixels = new Uint8ClampedArray([ + 0, + 0, + 0, + 0, // fully transparent + 255, + 0, + 0, + 255, // opaque red + 0, + 0, + 0, + 128, // half-transparent black + ]); + expect(Array.from(flattenAlpha(pixels))).toEqual([ + 255, 255, 255, 255, 255, 0, 0, 255, 127, 127, 127, 255, + ]); + }); +}); diff --git a/vite.config.ts b/vite.config.ts index 303602be..33caf670 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -63,6 +63,21 @@ export default defineConfig({ }, }, }, + optimizeDeps: { + // jSquash codecs locate their .wasm files relative to their own modules, + // which breaks if Vite pre-bundles them. + exclude: [ + "@jsquash/avif", + "@jsquash/jpeg", + "@jsquash/jxl", + "@jsquash/oxipng", + "@jsquash/qoi", + "@jsquash/webp", + ], + }, + worker: { + format: "es", + }, server: { fs: { strict: true,