Skip to content

Free open-source image editor for the browser

Editor modes, export mode with live preview, and zoom control (#18)

Rodrigo Belfiorefccc4caba12a
diff --git a/AGENTS.md b/AGENTS.md
index 961ceca..c876681 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -31,7 +31,7 @@ Prefer named exports (`export function`) and named imports. Use default exports
The `src/` root holds entrypoints, ambient types, and global styles. Import across folders through the `@/` alias (`@/hooks/use-pointer`); relative paths stay inside a folder. Source modules belong to these folders:
-- `app/`: application shell, app-wide state, and composition. It may import every folder below; no folder imports it.
+- `app/`: application shell, app-wide state, and composition. It may import every folder below; no folder imports it. `app/editor/modes.tsx` registers the editor modes: each mode is a `Panel` rendered into the shared panel over the shared canvas, or a `View` that brings its own viewport, like Crop.
- `features/`: removable product capabilities. A feature owns its UI, state, and behavior; removing its folder and `app/` composition leaves the rest working. Features never import each other.
- `components/`: generic React presentation grouped by role, such as `ui/` and `layout/`. It contains no product workflows.
- `hooks/`: generic React hooks without OpenLight business logic.
diff --git a/API.md b/API.md
index c364709..6fd1aa0 100644
--- a/API.md
+++ b/API.md
@@ -76,10 +76,15 @@ Each edit creates an undo step unless a group is open. Preview changes are outsi
## Export
-`exportImage(options)` returns `Promise<File>` containing the edited image at the document's dimensions. Preview settings do not affect export.
+`exportImage(options)` returns `Promise<File>` containing the edited image, named after the source file. Preview settings do not affect export.
-- `exportImage()` or `exportImage({ format: "png" })` exports PNG.
-- `exportImage({ format: "jpeg", quality: 90 })` exports JPEG. Quality must be between 1 and 100.
+| Option | Values | Default |
+| --- | --- | --- |
+| `format` | `"png"`, `"jpeg"`, `"webp"` | `"png"` |
+| `quality` | 1 to 100 for JPEG and WebP; PNG ignores it | 80 |
+| `longEdge` | Longest output side in pixels, from 1 to the document's longest side | The document size |
+
+The image renders at the document dimensions and downsamples to `longEdge` with high-quality smoothing. Invalid values throw, as does a format the browser cannot encode.
## State
diff --git a/CONTEXT.md b/CONTEXT.md
index 1779a5d..b3801ee 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -20,3 +20,7 @@ One reversible change to document content. A continuous slider or curve drag is
**Workspace**:
The application's open-document session. It currently contains at most one document, replaced when another image is opened.
+
+**Mode**:
+One of the editor's task areas: Adjust, Layers, Retouch, Crop, or Export. Switching modes changes the visible tools and panel, not the document.
+_Avoid_: Tab, page, persona, tool
diff --git a/README.md b/README.md
index 9875cdb..b4c4f28 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ Image processing runs locally with WebGPU. Built with TypeScript and React.
- Camera Raw XMP import
- TIFF import at 16-bit and floating-point precision, decoded on the GPU
- Camera RAW and DNG import through LibRaw, with absolute white balance and As Shot reset
-- PNG and JPEG export
+- PNG, JPEG, and WebP export with resizing, a live preview, and file size
Requires a WebGPU-capable browser.
diff --git a/src/app/editor/actions.tsx b/src/app/editor/actions.tsx
new file mode 100644
index 0000000..06c07be
--- /dev/null
+++ b/src/app/editor/actions.tsx
@@ -0,0 +1,12 @@
+import { ComparisonControl } from "./comparison-control";
+import { HistoryControls } from "./history";
+
+/** Document actions shared by mode panels. */
+export function EditorActions() {
+ return (
+ <div className="flex shrink-0 items-center gap-2 bg-panel p-3">
+ <HistoryControls />
+ <ComparisonControl />
+ </div>
+ );
+}
diff --git a/src/app/editor/sidebar/adjustment-controls.tsx b/src/app/editor/adjust/adjustment-controls.tsx
similarity index 100%
rename from src/app/editor/sidebar/adjustment-controls.tsx
rename to src/app/editor/adjust/adjustment-controls.tsx
diff --git a/src/app/editor/sidebar/clipping-controls.tsx b/src/app/editor/adjust/clipping-controls.tsx
similarity index 100%
rename from src/app/editor/sidebar/clipping-controls.tsx
rename to src/app/editor/adjust/clipping-controls.tsx
diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/adjust/index.tsx
similarity index 78%
rename from src/app/editor/sidebar/index.tsx
rename to src/app/editor/adjust/index.tsx
index 2eb48df..18089c0 100644
--- a/src/app/editor/sidebar/index.tsx
+++ b/src/app/editor/adjust/index.tsx
@@ -1,10 +1,9 @@
-import { type ReactNode, useEffect, useMemo } from "react";
+import { useEffect, useMemo } from "react";
import { useGpu } from "vgpu-react";
-import { ExportButton } from "@/app/editor/export/export-button";
-import { HistoryControls } from "@/app/editor/history";
+import { EditorActions } from "@/app/editor/actions";
import { useRenderer } from "@/components/editor/pipeline";
import {
- EditorPanel,
+ PanelContent,
useDocument,
useScene,
} from "@/components/editor/session";
@@ -15,7 +14,6 @@ import { useEditGesture } from "@/hooks/use-edit-gesture";
import { setToneCurve } from "@/lib/editor/document/edits";
import AdjustmentControls from "./adjustment-controls";
import { ClippingControls } from "./clipping-controls";
-import { ComparisonControl } from "./comparison-control";
const histogramColors = ["#f25445", "#6bd175", "#5c8ffa"] as const;
const curveHistogramColors = ["#a3a3a3"] as const;
@@ -47,7 +45,7 @@ function ToneCurvesPanel({
);
}
-export function Sidebar({ children }: { children?: ReactNode }) {
+export function AdjustPanel() {
const gpu = useGpu();
const document = useDocument();
const gesture = useEditGesture(document.history);
@@ -55,8 +53,8 @@ export function Sidebar({ children }: { children?: ReactNode }) {
const histogram = useMemo(() => createHistogram(gpu), [gpu]);
useEffect(() => () => histogram.dispose(), [histogram]);
return (
- <EditorPanel>
- <div className="flex h-full flex-col divide-y divide-black">
+ <PanelContent>
+ <div className="flex min-h-0 flex-1 flex-col divide-y divide-black">
<div
{...gesture}
className="min-h-0 flex-1 divide-y divide-black overflow-y-auto"
@@ -77,13 +75,8 @@ export function Sidebar({ children }: { children?: ReactNode }) {
curves={<ToneCurvesPanel histogram={histogram} />}
/>
</div>
- <div className="flex shrink-0 items-center gap-2 bg-panel p-3">
- <HistoryControls />
- <ComparisonControl />
- {children}
- <ExportButton />
- </div>
+ <EditorActions />
</div>
- </EditorPanel>
+ </PanelContent>
);
}
diff --git a/src/app/editor/sidebar/comparison-control.tsx b/src/app/editor/comparison-control.tsx
similarity index 100%
rename from src/app/editor/sidebar/comparison-control.tsx
rename to src/app/editor/comparison-control.tsx
diff --git a/src/app/editor/export/export-button.tsx b/src/app/editor/export/export-button.tsx
deleted file mode 100644
index c88ba1a..0000000
--- a/src/app/editor/export/export-button.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useRef } from "react";
-import Button from "@/components/ui/button";
-import { ExportSettings } from "./export-settings";
-
-export function ExportButton() {
- const dialog = useRef<HTMLDialogElement>(null);
- return (
- <div className="ml-auto">
- <Button
- className="flex items-center gap-2"
- onClick={() => dialog.current?.showModal()}
- >
- <svg
- aria-hidden="true"
- viewBox="0 0 20 20"
- className="size-3.5"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <path d="M10 2v10m-4-4 4 4 4-4M3 12v5h14v-5" />
- </svg>
- Export
- </Button>
- <dialog
- ref={dialog}
- aria-label="Export image"
- className="m-auto w-[360px] max-w-[calc(100%-2rem)] overflow-hidden rounded-xl border border-black bg-panel p-0 text-neutral-100 shadow-2xl backdrop:bg-black/50 backdrop:backdrop-blur-sm"
- >
- <ExportSettings onClose={() => dialog.current?.close()} />
- </dialog>
- </div>
- );
-}
diff --git a/src/app/editor/export/export-image.ts b/src/app/editor/export/export-image.ts
index 7f72500..80b6385 100644
--- a/src/app/editor/export/export-image.ts
+++ b/src/app/editor/export/export-image.ts
@@ -1,54 +1,126 @@
-import { frame, type Gpu, surface } from "vgpu";
+import { frame, type Gpu, surface, type Target } from "vgpu";
import type { EditorDocument } from "@/lib/editor/document";
import { createRenderer } from "@/lib/editor/renderer";
import { createDisplay } from "@/lib/image-display";
+import type { Point } from "@/lib/image-frame/geometry";
-export type ExportOptions =
- | { format: "png" }
- | { format: "jpeg"; quality: number };
+const encodings = {
+ png: { type: "image/png", extension: "png" },
+ jpeg: { type: "image/jpeg", extension: "jpg" },
+ webp: { type: "image/webp", extension: "webp" },
+};
-/** Renders a snapshot of the current edits at the document dimensions. */
-export async function exportImage(
+export type ExportFormat = keyof typeof encodings;
+
+export type ExportOptions = {
+ format?: ExportFormat;
+ /** 1 to 100 for JPEG and WebP; PNG ignores it. */
+ quality?: number;
+ /** Longest output side in pixels, up to the document's. */
+ longEdge?: number;
+};
+
+/** Whole-pixel output dimensions with the longest side scaled to `longEdge`. */
+export function exportSize(
+ [width, height]: Point,
+ longEdge = Math.max(width, height),
+): Point {
+ const scale = longEdge / Math.max(width, height);
+ return [
+ Math.max(1, Math.round(width * scale)),
+ Math.max(1, Math.round(height * scale)),
+ ];
+}
+
+const displays = new WeakMap<Gpu, ReturnType<typeof createDisplay>>();
+
+/** One display pipeline per GPU, shared by exports and size estimates. */
+function displayFor(gpu: Gpu) {
+ let display = displays.get(gpu);
+ if (!display) {
+ display = createDisplay(gpu);
+ displays.set(gpu, display);
+ }
+ return display;
+}
+
+/** Takes the rendered pixels as a bitmap; drawing the GPU canvas itself would wait for a frame that never comes off-screen. */
+function resample(source: OffscreenCanvas, [width, height]: Point) {
+ const bitmap = source.transferToImageBitmap();
+ const canvas = new OffscreenCanvas(width, height);
+ const context = canvas.getContext("2d");
+ if (!context) {
+ bitmap.close();
+ throw new Error("Couldn't resize the image.");
+ }
+ context.imageSmoothingQuality = "high";
+ context.drawImage(bitmap, 0, 0, width, height);
+ bitmap.close();
+ return canvas;
+}
+
+/** Encodes a rendered image, downsampled to `longEdge` with high-quality smoothing. */
+export async function encodeImage(
gpu: Gpu,
- document: EditorDocument,
- options: ExportOptions = { format: "png" },
+ image: Target,
+ { format = "png", quality = 80, longEdge }: ExportOptions = {},
) {
- if (options.format !== "png" && options.format !== "jpeg") {
- throw new Error("Choose PNG or JPEG.");
+ if (!(format in encodings)) {
+ throw new Error("Choose PNG, JPEG, or WebP.");
+ }
+ if (!Number.isFinite(quality) || quality < 1 || quality > 100) {
+ throw new Error("Quality must be between 1 and 100.");
}
+ const size = exportSize(image.size);
+ const maxEdge = Math.max(...size);
if (
- options.format === "jpeg" &&
- (!Number.isFinite(options.quality) ||
- options.quality < 1 ||
- options.quality > 100)
+ longEdge !== undefined &&
+ (!Number.isInteger(longEdge) || longEdge < 1 || longEdge > maxEdge)
) {
- throw new Error("JPEG quality must be between 1 and 100.");
+ throw new Error(`Long edge must be between 1 and ${maxEdge} pixels.`);
}
+ const canvas = new OffscreenCanvas(size[0], size[1]);
+ const output = surface(gpu, canvas, { size, dpr: 1 });
+ try {
+ const draw = displayFor(gpu);
+ frame(gpu, (frame) =>
+ draw(frame, output, image, { view: { zoom: 1, pan: [0, 0] } }),
+ );
+ const target = exportSize(size, longEdge);
+ const resized = target[0] !== size[0] || target[1] !== size[1];
+ const encoding = encodings[format];
+ // Finish the draw before the 2D canvas reads it; otherwise Chrome waits a full second for the sync.
+ await gpu.gpu.queue.onSubmittedWorkDone();
+ const blob = await (resized
+ ? resample(canvas, target)
+ : canvas
+ ).convertToBlob({ type: encoding.type, quality: quality / 100 });
+ if (blob.type !== encoding.type) {
+ throw new Error(`This browser can't encode ${format.toUpperCase()}.`);
+ }
+ return blob;
+ } finally {
+ output.dispose();
+ }
+}
+
+/** Renders a snapshot of the current edits, named after the source file. */
+export async function exportImage(
+ gpu: Gpu,
+ document: EditorDocument,
+ options: ExportOptions = {},
+) {
const scene = document.scene.getState();
const source = document.resources.get(scene.source);
- let output: ReturnType<typeof surface> | undefined;
- let renderer: ReturnType<typeof createRenderer> | undefined;
+ const renderer = createRenderer(gpu, source);
try {
- const [width, height] = scene.frame.size.map(Math.round);
- const canvas = new OffscreenCanvas(width, height);
- output = surface(gpu, canvas, { size: [width, height], dpr: 1 });
- renderer = createRenderer(gpu, source);
await renderer.update(scene);
- const draw = createDisplay(gpu);
- const texture = renderer.outputImage();
- const destination = output;
- frame(gpu, (frame) =>
- draw(frame, destination, texture, { view: { zoom: 1, pan: [0, 0] } }),
- );
- // The renderer retains the source until the canvas finishes encoding.
- const blob = await canvas.convertToBlob({
- type: `image/${options.format}`,
- quality: options.format === "jpeg" ? options.quality / 100 : undefined,
- });
- const extension = options.format === "jpeg" ? "jpg" : "png";
- return new File([blob], `export.${extension}`, { type: blob.type });
+ // The renderer retains the source until encoding finishes.
+ const blob = await encodeImage(gpu, renderer.outputImage(), options);
+ const name = source.file.name.replace(/\.[^.]*$/, "") || "export";
+ const { extension } = encodings[options.format ?? "png"];
+ return new File([blob], `${name}.${extension}`, { type: blob.type });
} finally {
- renderer?.dispose();
- output?.dispose();
+ renderer.dispose();
}
}
diff --git a/src/app/editor/export/export-settings.tsx b/src/app/editor/export/export-settings.tsx
deleted file mode 100644
index 10fad06..0000000
--- a/src/app/editor/export/export-settings.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-import { useRef, useState } from "react";
-import { useGpu } from "vgpu-react";
-import { exportImage } from "@/app/editor/export/export-image";
-import { useDocument } from "@/components/editor/session";
-import Button from "@/components/ui/button";
-import { Slider } from "@/components/ui/slider";
-
-const formats = [
- { value: "png", description: "Lossless detail" },
- { value: "jpeg", description: "Smaller files" },
-] as const;
-
-export function ExportSettings({ onClose }: { onClose: () => void }) {
- const gpu = useGpu();
- const editorDocument = useDocument();
- const [format, setFormat] = useState<"png" | "jpeg">("png");
- const [quality, setQuality] = useState(90);
- const [error, setError] = useState("");
- const exporting = useRef(false);
- const save = async () => {
- if (exporting.current) {
- return;
- }
- exporting.current = true;
- setError("");
- try {
- const options = format === "png" ? { format } : { format, quality };
- const file = await exportImage(gpu, editorDocument, options);
- const url = URL.createObjectURL(file);
- const link = document.createElement("a");
- link.href = url;
- link.download = file.name;
- link.click();
- setTimeout(() => URL.revokeObjectURL(url), 1000);
- onClose();
- } catch (error) {
- setError(
- error instanceof Error ? error.message : "Couldn't export image.",
- );
- } finally {
- exporting.current = false;
- }
- };
- return (
- <div className="divide-y divide-black shadow-ridge">
- <header className="px-4 py-3">
- <h2 className="font-medium">Export image</h2>
- <p className="mt-1 text-xs text-neutral-400">
- Full resolution. All your edits included.
- </p>
- </header>
- <div className="space-y-4 p-4">
- <fieldset>
- <legend className="mb-2 text-xs text-neutral-400">Format</legend>
- <div className="grid grid-cols-2 gap-2">
- {formats.map(({ value, description }) => (
- <label key={value} className="cursor-pointer">
- <input
- className="peer sr-only"
- type="radio"
- name="export-format"
- value={value}
- checked={format === value}
- onChange={() => setFormat(value)}
- />
- <span className="flex flex-col gap-1 rounded-lg border border-transparent px-3 py-2 text-neutral-400 hover:bg-neutral-700/30 peer-checked:border-neutral-500 peer-checked:bg-neutral-700 peer-checked:text-neutral-100 peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-neutral-400">
- <span className="text-sm font-medium uppercase">{value}</span>
- <span className="text-xs text-neutral-400">
- {description}
- </span>
- </span>
- </label>
- ))}
- </div>
- </fieldset>
- <div className="min-h-16">
- {format === "jpeg" && (
- <>
- <Slider
- label="Quality"
- value={quality}
- onChange={setQuality}
- min={1}
- max={100}
- />
- <p className="mt-2 text-xs text-neutral-500">
- Lower quality makes a smaller file.
- </p>
- </>
- )}
- {format === "png" && (
- <p className="text-xs leading-relaxed text-neutral-400">
- Preserves every detail without compression loss. Best for keeping
- a finished edit.
- </p>
- )}
- </div>
- {error && (
- <p className="text-sm text-red-400" role="alert">
- {error}
- </p>
- )}
- </div>
- <footer className="flex justify-end gap-2 bg-panel p-3">
- <Button variant="ghost" onClick={onClose}>
- Cancel
- </Button>
- <Button onClick={save}>Save image</Button>
- </footer>
- </div>
- );
-}
diff --git a/src/app/editor/export/index.tsx b/src/app/editor/export/index.tsx
new file mode 100644
index 0000000..5d4e0cc
--- /dev/null
+++ b/src/app/editor/export/index.tsx
@@ -0,0 +1,251 @@
+import { cn } from "cn";
+import { type ReactNode, useMemo, useRef, useState } from "react";
+import { useGpu } from "vgpu-react";
+import { Image } from "@/components/editor/image";
+import {
+ PanelContent,
+ useDocument,
+ useScene,
+} from "@/components/editor/session";
+import { EditorViewport } from "@/components/editor/viewport";
+import Button from "@/components/ui/button";
+import { Field } from "@/components/ui/field";
+import { ScrubInput } from "@/components/ui/scrub-input";
+import { Slider } from "@/components/ui/slider";
+import Spinner from "@/components/ui/spinner";
+import type { Point } from "@/lib/image-frame/geometry";
+import { type ExportFormat, exportImage, exportSize } from "./export-image";
+import { useEncodedPreview } from "./preview";
+
+type Format = {
+ id: ExportFormat;
+ label: string;
+ description: string;
+ lossy: boolean;
+};
+
+const formats: Format[] = [
+ {
+ id: "jpeg",
+ label: "JPEG",
+ description: "Small files, opens anywhere.",
+ lossy: true,
+ },
+ {
+ id: "png",
+ label: "PNG",
+ description: "Lossless, largest files.",
+ lossy: false,
+ },
+ {
+ id: "webp",
+ label: "WebP",
+ description: "Smaller than JPEG, less widely supported.",
+ lossy: true,
+ },
+];
+
+const kilobytes = new Intl.NumberFormat(undefined, {
+ style: "unit",
+ unit: "kilobyte",
+ maximumFractionDigits: 0,
+});
+const megabytes = new Intl.NumberFormat(undefined, {
+ style: "unit",
+ unit: "megabyte",
+ maximumFractionDigits: 1,
+});
+
+function formatBytes(bytes: number) {
+ if (bytes < 1_000_000) {
+ return kilobytes.format(bytes / 1000);
+ }
+ return megabytes.format(bytes / 1_000_000);
+}
+
+function FormatSelect({
+ value,
+ onChange,
+}: {
+ value: Format;
+ onChange: (format: Format) => void;
+}) {
+ return (
+ <div className="space-y-2">
+ <label className="flex items-center justify-between text-neutral-400 text-sm">
+ Format
+ <Field className="relative w-28">
+ <select
+ aria-label="Format"
+ value={value.id}
+ className="w-full cursor-pointer bg-transparent px-1 text-neutral-100 outline-none [color-scheme:dark]"
+ onChange={(event) =>
+ onChange(formats[event.currentTarget.selectedIndex])
+ }
+ >
+ {formats.map((format) => (
+ <option key={format.id} value={format.id}>
+ {format.label}
+ </option>
+ ))}
+ </select>
+ </Field>
+ </label>
+ <p className="text-neutral-500 text-xs">{value.description}</p>
+ </div>
+ );
+}
+
+/** Width, height, and scale edit one long edge; extra rows share the grid. */
+function SizeFields({
+ size,
+ longEdge,
+ onChange,
+ children,
+}: {
+ size: Point;
+ longEdge: number;
+ onChange: (longEdge: number) => void;
+ children: ReactNode;
+}) {
+ const [fullWidth, fullHeight] = exportSize(size);
+ const maxEdge = Math.max(fullWidth, fullHeight);
+ const [width, height] = exportSize(size, longEdge);
+ const scale = Math.round((100 * longEdge) / maxEdge);
+ const scaleTo = (fraction: number) =>
+ onChange(Math.max(1, Math.round(maxEdge * fraction)));
+ return (
+ <div className="grid grid-cols-[auto_1fr_1.5rem] items-center gap-x-3 gap-y-2 text-neutral-400 text-sm">
+ <span>Width</span>
+ <div className="justify-self-end">
+ <ScrubInput
+ aria-label="Width"
+ value={width}
+ min={1}
+ max={fullWidth}
+ onChange={(value) => scaleTo(value / fullWidth)}
+ />
+ </div>
+ <span className="text-neutral-500 text-xs">px</span>
+ <span>Height</span>
+ <div className="justify-self-end">
+ <ScrubInput
+ aria-label="Height"
+ value={height}
+ min={1}
+ max={fullHeight}
+ onChange={(value) => scaleTo(value / fullHeight)}
+ />
+ </div>
+ <span className="text-neutral-500 text-xs">px</span>
+ <span>Scale</span>
+ <div className="justify-self-end">
+ <ScrubInput
+ aria-label="Scale"
+ value={scale}
+ min={1}
+ max={100}
+ onChange={(value) => scaleTo(value / 100)}
+ />
+ </div>
+ <span className="text-neutral-500 text-xs">%</span>
+ {children}
+ </div>
+ );
+}
+
+function LoadingOverlay() {
+ return (
+ <div className="pointer-events-none absolute inset-0 grid place-items-center">
+ <Spinner className="size-8 border-neutral-500 border-t-white" />
+ </div>
+ );
+}
+
+/** Shows the encoded file on the canvas; a spinner marks results from earlier settings as loading. */
+export function ExportMode() {
+ const gpu = useGpu();
+ const editorDocument = useDocument();
+ const size = useScene((scene) => scene.frame.size);
+ const maxEdge = Math.max(...exportSize(size));
+ const [format, setFormat] = useState(formats[0]);
+ const [quality, setQuality] = useState(80);
+ const [longEdge, setLongEdge] = useState(maxEdge);
+ const [error, setError] = useState("");
+ const exporting = useRef(false);
+ // A crop after choosing a size keeps the choice within the new document.
+ const edge = Math.min(longEdge, maxEdge);
+ const options = { format: format.id, quality, longEdge: edge };
+ const output = useMemo(() => exportSize(size, edge), [size, edge]);
+ const { encoded, pending } = useEncodedPreview(options);
+ const save = async () => {
+ if (exporting.current) {
+ return;
+ }
+ exporting.current = true;
+ setError("");
+ try {
+ const file = await exportImage(gpu, editorDocument, options);
+ const url = URL.createObjectURL(file);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = file.name;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ } catch (error) {
+ setError(
+ error instanceof Error ? error.message : "Couldn't export image.",
+ );
+ } finally {
+ exporting.current = false;
+ }
+ };
+ return (
+ <>
+ <EditorViewport
+ size={encoded?.image.size ?? output}
+ overlay={pending && <LoadingOverlay />}
+ >
+ {encoded && <Image image={encoded.image} />}
+ </EditorViewport>
+ <PanelContent>
+ <section
+ aria-label="Export settings"
+ className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto p-4"
+ >
+ <FormatSelect value={format} onChange={setFormat} />
+ {format.lossy && (
+ <Slider
+ label="Quality"
+ value={quality}
+ onChange={setQuality}
+ min={1}
+ max={100}
+ defaultValue={80}
+ />
+ )}
+ <SizeFields size={size} longEdge={edge} onChange={setLongEdge}>
+ <span>File size</span>
+ <span
+ className={cn(
+ "col-span-2 flex items-center justify-end gap-1.5 text-neutral-100 tabular-nums",
+ pending && "text-neutral-500",
+ )}
+ >
+ {encoded ? formatBytes(encoded.bytes) : "…"}
+ {pending && <Spinner className="size-3" />}
+ </span>
+ </SizeFields>
+ <Button className="w-full py-2" onClick={save}>
+ Save image
+ </Button>
+ {error && (
+ <p className="text-red-400 text-sm" role="alert">
+ {error}
+ </p>
+ )}
+ </section>
+ </PanelContent>
+ </>
+ );
+}
diff --git a/src/app/editor/export/preview.tsx b/src/app/editor/export/preview.tsx
new file mode 100644
index 0000000..f88b70e
--- /dev/null
+++ b/src/app/editor/export/preview.tsx
@@ -0,0 +1,66 @@
+import { useEffect, useRef, useState } from "react";
+import type { Target } from "vgpu";
+import { useGpu } from "vgpu-react";
+import { useRenderer } from "@/components/editor/pipeline";
+import linearize from "@/lib/decode/linearize";
+import { type ExportOptions, encodeImage } from "./export-image";
+
+/** Quiet time after a change before encoding; typical encodes take tens of milliseconds. */
+const settleDelay = 150;
+
+type Encoded = { key: string; bytes: number; image: Target };
+
+/**
+ * Encodes the preview output once settings settle and decodes the file back into a target.
+ * Encodes run one at a time: a change during one waits for it and runs once more.
+ * The last result stays available while the current settings are still pending.
+ */
+export function useEncodedPreview({
+ format,
+ quality,
+ longEdge,
+}: ExportOptions) {
+ const gpu = useGpu();
+ const renderer = useRenderer();
+ const [revision, setRevision] = useState(0);
+ useEffect(
+ () => renderer.subscribe(() => setRevision((count) => count + 1)),
+ [renderer],
+ );
+ const key = `${format} ${quality} ${longEdge} ${revision}`;
+ const [encoded, setEncoded] = useState<Encoded>();
+ const queue = useRef(Promise.resolve());
+ useEffect(() => {
+ let active = true;
+ const timer = setTimeout(() => {
+ queue.current = queue.current.then(async () => {
+ if (!active) {
+ return;
+ }
+ try {
+ const blob = await encodeImage(gpu, renderer.outputImage(), {
+ format,
+ quality,
+ longEdge,
+ });
+ const bitmap = await createImageBitmap(blob);
+ if (!active) {
+ bitmap.close();
+ return;
+ }
+ setEncoded({ key, bytes: blob.size, image: linearize(gpu, bitmap) });
+ } catch {
+ if (active) {
+ setEncoded(undefined);
+ }
+ }
+ });
+ }, settleDelay);
+ return () => {
+ active = false;
+ clearTimeout(timer);
+ };
+ }, [gpu, renderer, key, format, quality, longEdge]);
+ useEffect(() => () => encoded?.image.color.dispose(), [encoded]);
+ return { encoded, pending: encoded?.key !== key };
+}
diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsx
index 897e1df..4cd55d7 100644
--- a/src/app/editor/index.tsx
+++ b/src/app/editor/index.tsx
@@ -1,32 +1,32 @@
-import { type ReactNode, useState } from "react";
import type { Workspace } from "@/app/workspace";
import { RendererProvider } from "@/components/editor/pipeline";
-import { DocumentProvider } from "@/components/editor/session";
+import { DocumentProvider, EditorPanel } from "@/components/editor/session";
import ResizablePanel from "@/components/ui/resizable-panel";
import Spinner from "@/components/ui/spinner";
-import { CropButton } from "@/features/crop/button";
-import { CropEditor } from "@/features/crop/view";
import { EditorCanvas } from "./canvas";
-import { Sidebar } from "./sidebar";
+import { ModeRail } from "./mode-rail";
+import { ModeProvider, useMode } from "./modes";
-function AdjustmentEditor({ children }: { children: ReactNode }) {
+function ModeView() {
+ const { mode } = useMode();
+ if ("View" in mode) {
+ return <mode.View />;
+ }
return (
- <RendererProvider>
+ <>
<EditorCanvas />
- <Sidebar>{children}</Sidebar>
- </RendererProvider>
+ <mode.Panel />
+ </>
);
}
function DocumentEditor() {
- const [cropping, setCropping] = useState(false);
- if (cropping) {
- return <CropEditor onClose={() => setCropping(false)} />;
- }
return (
- <AdjustmentEditor>
- <CropButton onClick={() => setCropping(true)} />
- </AdjustmentEditor>
+ <ModeProvider>
+ <ModeView />
+ <EditorPanel />
+ <ModeRail />
+ </ModeProvider>
);
}
@@ -45,7 +45,9 @@ function EditorContent({ state }: EditorProps) {
if (state.status === "ready") {
return (
<DocumentProvider key={state.document.id} value={state.document}>
- <DocumentEditor />
+ <RendererProvider>
+ <DocumentEditor />
+ </RendererProvider>
</DocumentProvider>
);
}
diff --git a/src/app/editor/mode-rail.tsx b/src/app/editor/mode-rail.tsx
new file mode 100644
index 0000000..3301cce
--- /dev/null
+++ b/src/app/editor/mode-rail.tsx
@@ -0,0 +1,44 @@
+import { Tab, TabList } from "@/components/ui/tabs";
+import { useShortcuts } from "@/hooks/use-shortcuts";
+import { type Mode, modes, useMode } from "./modes";
+
+function ModeTab({ entry }: { entry: Mode }) {
+ const { mode, setMode } = useMode();
+ return (
+ <Tab
+ selected={entry === mode}
+ title={`${entry.label} (${entry.key.toUpperCase()})`}
+ onClick={() => setMode(entry)}
+ className="flex min-w-16 flex-1 flex-col items-center gap-0.5 rounded-md px-0 py-1.5 md:min-w-0 md:flex-none md:py-2"
+ >
+ <entry.Icon className="size-5" />
+ {entry.label}
+ </Tab>
+ );
+}
+
+/** A column at the window's right edge on desktop, a scrollable bar below the panel on mobile. Letter shortcuts work anywhere. */
+export function ModeRail() {
+ const { setMode } = useMode();
+ useShortcuts(
+ Object.fromEntries(
+ modes.map((entry) => [entry.key, () => setMode(entry)] as const),
+ ),
+ );
+ const editing = modes.filter((entry) => entry.group === "edit");
+ const output = modes.filter((entry) => entry.group === "output");
+ return (
+ <TabList
+ aria-label="Editor mode"
+ className="shrink-0 overflow-auto border-black border-t bg-panel p-2 shadow-ridge md:w-17.5 md:flex-col md:border-t-0 md:border-l"
+ >
+ {editing.map((entry) => (
+ <ModeTab key={entry.id} entry={entry} />
+ ))}
+ <div className="my-1 w-px shrink-0 bg-black md:my-0 md:w-auto md:flex-1 md:bg-transparent" />
+ {output.map((entry) => (
+ <ModeTab key={entry.id} entry={entry} />
+ ))}
+ </TabList>
+ );
+}
diff --git a/src/app/editor/modes.tsx b/src/app/editor/modes.tsx
new file mode 100644
index 0000000..08065ac
--- /dev/null
+++ b/src/app/editor/modes.tsx
@@ -0,0 +1,98 @@
+import { createContext, type ReactNode, useContext, useState } from "react";
+import { PanelContent } from "@/components/editor/session";
+import { AdjustIcon } from "@/components/icons/adjust";
+import { CropIcon } from "@/components/icons/crop";
+import { ExportIcon } from "@/components/icons/export";
+import { LayersIcon } from "@/components/icons/layers";
+import { RetouchIcon } from "@/components/icons/retouch";
+import { CropEditor } from "@/features/crop/view";
+import { EditorActions } from "./actions";
+import { AdjustPanel } from "./adjust";
+import { ExportMode } from "./export";
+
+const ModeContext = createContext<{
+ mode: Mode;
+ setMode: (mode: Mode) => void;
+} | null>(null);
+
+export function useMode() {
+ const context = useContext(ModeContext);
+ if (!context) {
+ throw new Error("A mode provider is required.");
+ }
+ return context;
+}
+
+function PlaceholderPanel() {
+ return (
+ <PanelContent>
+ <div className="flex min-h-0 flex-1 flex-col divide-y divide-black">
+ <p className="grid flex-1 place-items-center text-neutral-500 text-sm">
+ Coming soon
+ </p>
+ <EditorActions />
+ </div>
+ </PanelContent>
+ );
+}
+
+const adjust = {
+ id: "adjust",
+ label: "Adjust",
+ key: "a",
+ Icon: AdjustIcon,
+ group: "edit",
+ Panel: AdjustPanel,
+} as const;
+
+function CropMode() {
+ const { setMode } = useMode();
+ return <CropEditor onClose={() => setMode(adjust)} />;
+}
+
+/**
+ * A mode edits over the shared canvas through a Panel, or brings its own View when it needs another viewport.
+ * Output modes sit at the end of the rail, apart from editing modes.
+ */
+export const modes = [
+ adjust,
+ {
+ id: "layers",
+ label: "Layers",
+ key: "l",
+ Icon: LayersIcon,
+ group: "edit",
+ Panel: PlaceholderPanel,
+ },
+ {
+ id: "retouch",
+ label: "Retouch",
+ key: "r",
+ Icon: RetouchIcon,
+ group: "edit",
+ Panel: PlaceholderPanel,
+ },
+ {
+ id: "crop",
+ label: "Crop",
+ key: "c",
+ Icon: CropIcon,
+ group: "edit",
+ View: CropMode,
+ },
+ {
+ id: "export",
+ label: "Export",
+ key: "e",
+ Icon: ExportIcon,
+ group: "output",
+ View: ExportMode,
+ },
+] as const;
+
+export type Mode = (typeof modes)[number];
+
+export function ModeProvider({ children }: { children: ReactNode }) {
+ const [mode, setMode] = useState<Mode>(adjust);
+ return <ModeContext value={{ mode, setMode }}>{children}</ModeContext>;
+}
diff --git a/src/components/editor/image.tsx b/src/components/editor/image.tsx
index 1324881..8eb7498 100644
--- a/src/components/editor/image.tsx
+++ b/src/components/editor/image.tsx
@@ -1,4 +1,5 @@
import { useEffect, useMemo } from "react";
+import type { Target } from "vgpu";
import { useCanvas, useFrame, useGpu } from "vgpu-react";
import { useStore } from "zustand";
import { fitScale } from "@/hooks/use-pan-zoom";
@@ -10,13 +11,14 @@ import { useViewport } from "./viewport";
type Output = "fullImage" | "inputImage" | "outputImage" | "originalImage";
-/** Mount a pipeline output; a supplied frame places the full source behind it. */
+/** Mount a pipeline output or any target; a supplied frame places the full source behind it. */
export function Image({
image = "outputImage",
geometry,
original,
}: {
- image?: Output;
+ /** A renderer output, or a target such as an export preview. */
+ image?: Output | Target;
geometry?: ImageFrame;
original?: Output;
}) {
@@ -28,8 +30,9 @@ export function Image({
const display = useMemo(() => createDisplay(gpu), [gpu]);
const render = useFrame((frame) => {
const before = original && renderer[original]();
+ const target = typeof image === "string" ? renderer[image]() : image;
const source =
- preview.comparison === "original" && before ? before : renderer[image]();
+ preview.comparison === "original" && before ? before : target;
const size = geometry?.size ?? source.size;
const view = {
...camera.view,
@@ -45,6 +48,6 @@ export function Image({
});
});
useEffect(() => renderer.subscribe(render), [renderer, render]);
- useEffect(() => render(), [render, camera, preview, geometry]);
+ useEffect(() => render(), [render, camera, preview, geometry, image]);
return null;
}
diff --git a/src/components/editor/session.tsx b/src/components/editor/session.tsx
index 9d2f341..cff4161 100644
--- a/src/components/editor/session.tsx
+++ b/src/components/editor/session.tsx
@@ -5,6 +5,7 @@ import {
useMemo,
useState,
} from "react";
+import { createPortal } from "react-dom";
import { useStore } from "zustand";
import ResizablePanel from "@/components/ui/resizable-panel";
import { createCamera } from "@/hooks/use-pan-zoom";
@@ -16,6 +17,8 @@ const Session = createContext<{
camera: ReturnType<typeof createCamera>;
width: number;
onWidthChange: (width: number) => void;
+ panel: HTMLElement | null;
+ panelRef: (panel: HTMLElement | null) => void;
} | null>(null);
export function useEditorSession() {
@@ -43,18 +46,28 @@ export function DocumentProvider({
const size = useStore(value.scene, (scene) => scene.frame.size);
const camera = useMemo(createCamera, [size[0], size[1]]);
const [width, onWidthChange] = useState(288);
+ const [panel, panelRef] = useState<HTMLElement | null>(null);
return (
- <Session value={{ document: value, camera, width, onWidthChange }}>
+ <Session
+ value={{ document: value, camera, width, onWidthChange, panel, panelRef }}
+ >
{children}
</Session>
);
}
-export function EditorPanel({ children }: { children: ReactNode }) {
- const { width, onWidthChange } = useEditorSession();
+/** The resizable panel; the active tool fills it through PanelContent. */
+export function EditorPanel() {
+ const { width, onWidthChange, panelRef } = useEditorSession();
return (
<ResizablePanel width={width} onWidthChange={onWidthChange}>
- {children}
+ <div ref={panelRef} className="flex h-full flex-col" />
</ResizablePanel>
);
}
+
+/** A tool's panel content, rendered into the EditorPanel. */
+export function PanelContent({ children }: { children: ReactNode }) {
+ const { panel } = useEditorSession();
+ return panel && createPortal(children, panel);
+}
diff --git a/src/components/editor/viewport.tsx b/src/components/editor/viewport.tsx
index c226b54..c469e6f 100644
--- a/src/components/editor/viewport.tsx
+++ b/src/components/editor/viewport.tsx
@@ -1,5 +1,7 @@
import { createContext, type ReactNode, useContext } from "react";
import { Canvas } from "vgpu-react";
+import { Icon } from "@/components/icons/icon";
+import Button from "@/components/ui/button";
import { usePanZoom } from "@/hooks/use-pan-zoom";
import type { Point } from "@/lib/image-frame/geometry";
import { useEditorSession } from "./session";
@@ -13,6 +15,46 @@ export function useViewport() {
return viewport;
}
+/** Zoom as Photoshop counts it: 100% shows one image pixel per device pixel. */
+function ZoomControl() {
+ const { scale, zoomBy, resetView } = useViewport();
+ const percent = Math.round(scale * devicePixelRatio * 100);
+ return (
+ <div className="absolute right-3 bottom-3">
+ <div className="flex items-center rounded-full bg-neutral-900/65 p-0.5 shadow-md backdrop-blur-sm">
+ <Button
+ variant="ghost"
+ aria-label="Zoom out"
+ className="flex size-6 items-center justify-center rounded-full p-0"
+ onClick={() => zoomBy(1 / 1.25)}
+ >
+ <Icon viewBox="0 0 20 20" className="size-3.5">
+ <path d="M5 10h10" />
+ </Icon>
+ </Button>
+ <Button
+ variant="ghost"
+ title="Fit to view"
+ className="min-w-14 rounded-full px-1 py-0.5 text-neutral-200 tabular-nums"
+ onClick={() => resetView()}
+ >
+ {percent}%
+ </Button>
+ <Button
+ variant="ghost"
+ aria-label="Zoom in"
+ className="flex size-6 items-center justify-center rounded-full p-0"
+ onClick={() => zoomBy(1.25)}
+ >
+ <Icon viewBox="0 0 20 20" className="size-3.5">
+ <path d="M10 5v10M5 10h10" />
+ </Icon>
+ </Button>
+ </div>
+ </div>
+ );
+}
+
export function EditorViewport({
size,
constrain = true,
@@ -43,6 +85,7 @@ export function EditorViewport({
</Canvas>
</div>
{overlay}
+ <ZoomControl />
</Viewport>
</section>
);
diff --git a/src/components/icons/adjust.tsx b/src/components/icons/adjust.tsx
new file mode 100644
index 0000000..ea4cb1c
--- /dev/null
+++ b/src/components/icons/adjust.tsx
@@ -0,0 +1,9 @@
+import { Icon, type IconProps } from "./icon";
+
+export function AdjustIcon(props: IconProps) {
+ return (
+ <Icon viewBox="0 0 20 20" {...props}>
+ <path d="M3 5h7M14 5h3M12 3v4M3 10h3M10 10h7M8 8v4M3 15h8M15 15h2M13 13v4" />
+ </Icon>
+ );
+}
diff --git a/src/components/icons/export.tsx b/src/components/icons/export.tsx
new file mode 100644
index 0000000..f252c71
--- /dev/null
+++ b/src/components/icons/export.tsx
@@ -0,0 +1,9 @@
+import { Icon, type IconProps } from "./icon";
+
+export function ExportIcon(props: IconProps) {
+ return (
+ <Icon viewBox="0 0 20 20" {...props}>
+ <path d="M10 2v10m-4-4 4 4 4-4M3 12v5h14v-5" />
+ </Icon>
+ );
+}
diff --git a/src/components/icons/layers.tsx b/src/components/icons/layers.tsx
new file mode 100644
index 0000000..6b5aedd
--- /dev/null
+++ b/src/components/icons/layers.tsx
@@ -0,0 +1,10 @@
+import { Icon, type IconProps } from "./icon";
+
+export function LayersIcon(props: IconProps) {
+ return (
+ <Icon viewBox="0 0 20 20" {...props}>
+ <path d="m10 2 7 4-7 4-7-4z" />
+ <path d="m3 10 7 4 7-4M3 14l7 4 7-4" />
+ </Icon>
+ );
+}
diff --git a/src/components/icons/retouch.tsx b/src/components/icons/retouch.tsx
new file mode 100644
index 0000000..a6aaea5
--- /dev/null
+++ b/src/components/icons/retouch.tsx
@@ -0,0 +1,12 @@
+import { Icon, type IconProps } from "./icon";
+
+export function RetouchIcon(props: IconProps) {
+ return (
+ <Icon viewBox="0 0 20 20" {...props}>
+ <g transform="rotate(45 10 10)">
+ <rect x="6" y="2" width="8" height="16" rx="4" />
+ <path d="M6 7h8M6 13h8M8.5 10h.01M11.5 10h.01" />
+ </g>
+ </Icon>
+ );
+}
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 89f3745..78d33b4 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -3,14 +3,14 @@ import { cn } from "cn";
import type { ComponentProps } from "react";
const button = cva(
- "cursor-pointer rounded-lg border px-4 py-1.5 text-xs transition-colors focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-neutral-400",
+ "cursor-pointer rounded-md px-4 py-1.5 text-xs transition-colors focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-neutral-400",
{
variants: {
variant: {
default:
- "border-black bg-neutral-700 text-neutral-100 shadow-ridge hover:bg-neutral-600 active:bg-neutral-700 active:shadow-groove",
+ "bg-neutral-700 text-neutral-100 shadow-ridge hover:bg-neutral-600 active:bg-neutral-700 active:shadow-groove",
ghost:
- "border-transparent text-neutral-400 hover:bg-neutral-700/50 hover:text-neutral-100 active:bg-neutral-700",
+ "text-neutral-400 hover:bg-neutral-700/50 hover:text-neutral-100 active:bg-neutral-700",
},
},
defaultVariants: { variant: "default" },
diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsx
new file mode 100644
index 0000000..b174f6d
--- /dev/null
+++ b/src/components/ui/tabs.tsx
@@ -0,0 +1,59 @@
+import { cn } from "cn";
+import type { ComponentProps, KeyboardEvent } from "react";
+import Button from "./button";
+
+const steps: Record<string, number> = {
+ ArrowRight: 1,
+ ArrowDown: 1,
+ ArrowLeft: -1,
+ ArrowUp: -1,
+};
+
+/** Arrow keys in any direction move between the tabs inside. Orientation comes from className. */
+export function TabList({ className, ...props }: ComponentProps<"div">) {
+ function selectNeighbor(event: KeyboardEvent<HTMLDivElement>) {
+ const step = steps[event.key];
+ if (!step) {
+ return;
+ }
+ event.preventDefault();
+ const tabs = [
+ ...event.currentTarget.querySelectorAll<HTMLElement>('[role="tab"]'),
+ ];
+ const index = tabs.findIndex(
+ (tab) => tab.getAttribute("aria-selected") === "true",
+ );
+ const next = tabs.at((index + step) % tabs.length);
+ next?.focus();
+ next?.click();
+ }
+ return (
+ <div
+ role="tablist"
+ onKeyDown={selectNeighbor}
+ className={cn("flex gap-1", className)}
+ {...props}
+ />
+ );
+}
+
+/** Only the selected tab is in the tab order; arrow keys reach the rest. */
+export function Tab({
+ selected,
+ className,
+ ...props
+}: ComponentProps<typeof Button> & { selected: boolean }) {
+ return (
+ <Button
+ variant="ghost"
+ role="tab"
+ aria-selected={selected}
+ tabIndex={selected ? 0 : -1}
+ className={cn(
+ "aria-selected:bg-neutral-700 aria-selected:text-neutral-100 aria-selected:shadow-ridge",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
diff --git a/src/features/crop/button.tsx b/src/features/crop/button.tsx
deleted file mode 100644
index 715fe35..0000000
--- a/src/features/crop/button.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { CropIcon } from "@/components/icons/crop";
-import Button from "@/components/ui/button";
-import { useShortcuts } from "@/hooks/use-shortcuts";
-
-export function CropButton({ onClick }: { onClick: () => void }) {
- useShortcuts({ c: onClick });
- return (
- <Button
- variant="ghost"
- aria-label="Crop and rotate"
- title="Crop and rotate (C)"
- className="flex size-8 items-center justify-center rounded-md p-0"
- onClick={onClick}
- >
- <CropIcon className="size-4" />
- </Button>
- );
-}
diff --git a/src/features/crop/view.tsx b/src/features/crop/view.tsx
index 7dc8bfa..3325198 100644
--- a/src/features/crop/view.tsx
+++ b/src/features/crop/view.tsx
@@ -1,8 +1,7 @@
import { useState } from "react";
import { Image } from "@/components/editor/image";
-import { RendererProvider } from "@/components/editor/pipeline";
import {
- EditorPanel,
+ PanelContent,
useDocument,
useEditorSession,
} from "@/components/editor/session";
@@ -84,7 +83,7 @@ export function CropEditor({ onClose }: { onClose: () => void }) {
}
}
return (
- <RendererProvider>
+ <>
<EditorViewport size={reference} constrain={false}>
<Image image="fullImage" geometry={frame} />
<CropOverlay
@@ -94,10 +93,10 @@ export function CropEditor({ onClose }: { onClose: () => void }) {
onChange={setFrame}
/>
</EditorViewport>
- <EditorPanel>
+ <PanelContent>
<section
aria-label="Crop tool"
- className="flex h-full flex-col bg-panel"
+ className="flex min-h-0 flex-1 flex-col bg-panel"
onKeyDown={(event) => {
if (
event.key === "Enter" &&
@@ -109,7 +108,6 @@ export function CropEditor({ onClose }: { onClose: () => void }) {
}}
>
<div className="flex-1 space-y-5 overflow-y-auto p-4">
- <h2 className="text-sm text-neutral-100">Crop & rotate</h2>
<label className="flex items-center justify-between text-sm text-neutral-400">
Aspect ratio
<Field className="relative w-24">
@@ -186,7 +184,7 @@ export function CropEditor({ onClose }: { onClose: () => void }) {
<Button onClick={apply}>Apply crop</Button>
</div>
</section>
- </EditorPanel>
- </RendererProvider>
+ </PanelContent>
+ </>
);
}
diff --git a/src/hooks/use-pan-zoom.ts b/src/hooks/use-pan-zoom.ts
index ef3d5a9..48d1aec 100644
--- a/src/hooks/use-pan-zoom.ts
+++ b/src/hooks/use-pan-zoom.ts
@@ -182,6 +182,15 @@ export function usePanZoom(
fitZoom.current = next.zoom;
state.setState(next, true);
};
+ const zoomBy = (factor: number) =>
+ update((view) =>
+ zoomAt(
+ view,
+ [0, 0],
+ view.zoom * factor,
+ constrain ? 1 : fitZoom.current * 0.1,
+ ),
+ );
function startDrag(event: PointerEvent<HTMLElement>) {
if (event.button !== 0 || pointers.current.size === 2) {
return;
@@ -243,6 +252,7 @@ export function usePanZoom(
viewport,
handlers,
resetView,
+ zoomBy,
panMode,
scale: fitScale(content, viewport) * view.zoom,
};
diff --git a/tests/editing.e2e.ts b/tests/editing.e2e.ts
index f50aa40..ab95dce 100644
--- a/tests/editing.e2e.ts
+++ b/tests/editing.e2e.ts
@@ -438,7 +438,27 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
}
});
- const open = page.getByRole("button", { name: "Crop and rotate" });
+ await test.step("mode bar switches panels by click, arrow keys, and letters", async () => {
+ const modes = page.getByRole("tablist", { name: "Editor mode" });
+ const selected = modes.getByRole("tab", { selected: true });
+ await expect(selected).toHaveText("Adjust");
+ await modes.getByRole("tab", { name: "Layers" }).click();
+ await expect(selected).toHaveText("Layers");
+ await expect(page.getByText("Coming soon")).toBeVisible();
+ await page.keyboard.press("ArrowRight");
+ await expect(selected).toHaveText("Retouch");
+ await expect(selected).toBeFocused();
+ await page.keyboard.press("ArrowLeft");
+ await page.keyboard.press("ArrowLeft");
+ await expect(selected).toHaveText("Adjust");
+ await page.keyboard.press("l");
+ await expect(selected).toHaveText("Layers");
+ await page.keyboard.press("a");
+ await expect(selected).toHaveText("Adjust");
+ await expect(page.getByRole("slider", { name: "Exposure" })).toBeVisible();
+ });
+
+ const open = page.getByRole("tab", { name: "Crop" });
const panel = page.getByRole("region", { name: "Crop tool" });
const selection = page.getByRole("application", { name: "Crop selection" });
const corner = page.getByRole("button", { name: "Resize crop bottom right" });
@@ -899,43 +919,56 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
expect(expected.corner[3]).toBe(255);
await canvas.hover();
await zoom(page, Math.E);
- const trigger = page.getByRole("button", { name: "Export", exact: true });
- const dialog = page.getByRole("dialog", { name: "Export image" });
- const sizes: number[] = [];
- for (const quality of [null, 20, 95]) {
- await trigger.click();
- if (quality !== null) {
- await dialog.getByText("Smaller files", { exact: true }).click();
- const field = dialog.getByRole("textbox", { name: "Quality" });
- await field.fill(String(quality));
- await field.press("Enter");
- }
+ const panel = page.getByRole("region", { name: "Export settings" });
+ await page.getByRole("tab", { name: "Export" }).click();
+ const quality = panel.getByRole("textbox", { name: "Quality" });
+ async function save(name: string) {
const pending = page.waitForEvent("download");
- await dialog.getByRole("button", { name: "Save image" }).click();
+ await panel.getByRole("button", { name: "Save image" }).click();
const download = await pending;
- expect(download.suggestedFilename()).toBe(
- quality === null ? "export.png" : "export.jpg",
- );
+ expect(download.suggestedFilename()).toBe(name);
const path = await download.path();
if (!path) throw new Error("Missing image download.");
- const bytes = await readFile(path);
+ return readFile(path);
+ }
+ const format = panel.getByRole("combobox", { name: "Format" });
+ await format.selectOption("png");
+ await expect(panel.getByRole("textbox", { name: "Width" })).toHaveValue(
+ "1200",
+ );
+ await expect(panel.getByText(/kB|MB/)).toBeVisible();
+ expect(await readImage(page, await save("photo.png"))).toEqual(expected);
+ await format.selectOption("jpeg");
+ await expect(format).toHaveValue("jpeg");
+ await quality.fill("20");
+ await quality.press("Enter");
+ const small = await save("photo.jpg");
+ await quality.fill("95");
+ await quality.press("Enter");
+ const large = await save("photo.jpg");
+ for (const bytes of [small, large]) {
const actual = await readImage(page, bytes);
expect(actual.size).toEqual([1200, 800]);
expect(
Math.abs(actual.center[0] - expected.center[0]),
).toBeLessThanOrEqual(3);
- if (quality === null) expect(actual).toEqual(expected);
- else sizes.push(bytes.length);
- await expect(dialog).toBeHidden();
- await expect(trigger).toBeFocused();
}
- expect(sizes[1]).toBeGreaterThan(sizes[0]);
- await trigger.click();
- await expect(dialog.getByRole("slider", { name: "Quality" })).toHaveValue(
- "95",
+ expect(large.length).toBeGreaterThan(small.length);
+ await format.selectOption("webp");
+ const width = panel.getByRole("textbox", { name: "Width" });
+ await width.fill("600");
+ await width.press("Enter");
+ await expect(panel.getByRole("textbox", { name: "Height" })).toHaveValue(
+ "400",
);
- await page.keyboard.press("Escape");
- await expect(dialog).toBeHidden();
+ const resized = await readImage(page, await save("photo.webp"));
+ expect(resized.size).toEqual([600, 400]);
+ expect(
+ Math.abs(resized.center[0] - expected.center[0]),
+ ).toBeLessThanOrEqual(3);
+ await expect(quality).toHaveValue("95");
+ await page.keyboard.press("a");
+ await expect(panel).toBeHidden();
});
await test.step("mobile slider targets accept taps above and below the visible track", async () => {
diff --git a/tests/loaders.e2e.ts b/tests/loaders.e2e.ts
index 079b1d6..ea1959d 100644
--- a/tests/loaders.e2e.ts
+++ b/tests/loaders.e2e.ts
@@ -51,7 +51,7 @@ test("decode an image, apply XMP, recover from failure, and replace a document d
expect(await readImage(page)).toEqual(baseline);
await page.evaluate(() => window.openlight.redo());
expect(await readImage(page)).toEqual(expected);
- await page.getByRole("button", { name: "Crop and rotate" }).click();
+ await page.getByRole("tab", { name: "Crop" }).click();
await page
.getByRole("combobox", { name: "Aspect ratio" })
.selectOption({ label: "Square" });