Skip to content

Free open-source image editor for the browser

Crop, rotate, and flip (#5)

Rodrigo Belfiore16f90e2bf3a7
diff --git a/README.md b/README.md
index 708a9b5..3c83390 100644
--- a/README.md
+++ b/README.md
@@ -2,11 +2,19 @@
**An open-source image editor for the browser, built with [vgpu.sh](https://vgpu.sh)**
-Open a photo, adjust light and color, export the result. Edits are non-destructive and rendering runs on your GPU through WebGPU. Everything stays on your machine: no account, no upload.
+Non-destructive editing, rendered on your GPU. Everything stays on your machine: no account, no upload.
-Needs a WebGPU-capable browser: Chrome or Edge stable, Safari 26+.
+## Features
-## Run
+- Light and color adjustments, tone curves, and Camera Raw XMP import.
+- Crop, rotate, straighten, and flip, with undo/redo.
+- Before/after comparison, RGB histograms, and clipping overlays.
+- Pan and zoom, including Space + drag while cropping.
+- PNG and JPEG export.
+
+Requires a WebGPU-capable browser.
+
+## Development
```sh
bun install
@@ -16,81 +24,21 @@ bun dev
```sh
bun run check # format + lint
bun run build # typecheck + bundle
-bun run test # fast integration tests; no browser or GPU
+bun run test # browser-free integration tests
bun run test:browser # pixels, UI, and codecs; requires Chromium + WebGPU
```
-## License
-
-[MIT](LICENSE)
-
-## Browser controls
+## Scripting
-`window.openlight` is available after the app mounts, including production builds.
-`createControls(gpu, workspace)` exposes the same commands without React. Each
-document owns a vanilla Zustand scene store, an in-memory history, and image
-resources. The scene contains canvas dimensions, a source ID, adjustments, and a
-tone curve. Files and GPU targets stay outside scene snapshots. The workspace
-currently opens one document at a time and replaces it when another image opens.
-React hooks and context bind these instances to the UI; the renderer subscribes to its
-explicit document.
+`window.openlight` exposes the editor commands in the browser. `createControls(gpu, workspace)` provides the same API without React.
```js
-await openlight.openFiles([
- new File([imageBytes], "photo.png", { type: "image/png" }),
- new File([xmpText], "photo.xmp"),
-]);
-openlight.setAdjustments({ exposure: 1, saturation: -25 });
-openlight.setAdjustments({ highlights: -50, shadows: 50, whites: 10, blacks: -10 });
+await openlight.openFiles([imageFile, xmpFile]);
+openlight.setAdjustments({ exposure: 1, shadows: 25 });
openlight.undo();
-openlight.redo();
-const state = openlight.getState();
+const image = await openlight.exportImage();
```
-`openFiles` is shared by the app-wide drop handler, image picker, and browser
-automation. Each batch opens the first recognized image, then applies all settings
-files in their input order. Additional images are ignored without decoding them.
-Camera Raw settings accept `.xmp` and `.xml` files containing the Camera Raw namespace.
-Settings alone apply to the current image. Unsupported files and settings without
-a loaded image are ignored; a failed image load skips that batch's settings.
-Batches run sequentially, including calls through `openFile`, `loadImage`, and
-`importXmp`, so settings cannot spill onto an image from a later batch.
-
-`app/loaders/registry.ts` owns matching and batch ordering. Each loader declares
-`kind`, `accepts`, and `load`; register loaders in `app/controls.ts`. The workspace
-owns document replacement. Image decoding and XMP import remain separate from
-scene state and history.
-
-`beginEdit()`, `commitEdit()`, and `cancelEdit()` group synchronous editing commands.
-Sliders and curve drags use the same grouping. Each text-field commit and XMP
-import is one edit. Undo and redo restore content; a new edit discards redo.
-History retains at most 100 small immutable scene snapshots in memory, sharing
-unchanged data and excluding binary resources. It resets with a new document.
-Undo/redo buttons and Ctrl/Cmd+Z, Ctrl/Cmd+Shift+Z, and Ctrl/Cmd+Y are available;
-text inputs keep native text undo. History is not persisted across reloads.
-
-`setAdjustments` merges a partial update. Exposure accepts -5 to 5; other
-adjustments accept -100 to 100. Loading another image resets adjustments.
-The four tone controls follow Camera Raw XMP's units and direction. Each effect
-is owned by its matching WGSL file in `src/lib/adjustments/`.
-Whites and blacks move their endpoints along monotone cubic curves in perceptual
-space, leaving middle gray fixed. At full strength the endpoint moves by 0.1.
-Highlights and shadows use pointwise curves fitted against Lightroom exports;
-they do not yet model Lightroom's spatial processing.
-State includes the file name, document ID, canvas size, adjustments, tone curve,
-and undo/redo counts. Loading commands resolve when their batch finishes; image
-decoding failures appear in the editor. The renderer updates when the scene changes.
-
-## Preview aids
+## License
-Click the split-view icon to compare the original on the left with the edit on the
-right. Drag the vertical divider, use arrow keys, or double-click it to recenter.
-Hold backslash for the full original; releasing restores the previous view.
-Text fields keep normal keyboard input. The histogram's left and right triangles
-toggle clipping overlays: blue for pixels with all sRGB channels at or below zero,
-red for any channel at or above one. Transparent pixels are excluded.
-These controls affect only the canvas; histograms and exports keep the edited result.
-Preview settings reset when another image opens and never enter undo history.
-Scripts can use `openlight.setPreview({ comparison: "split", split: 0.5 })` and
-`openlight.setPreview({ shadows: true, highlights: true })`. Comparison accepts
-`"edited"`, `"original"`, or `"split"`; the split position is a fraction from 0 to 1.
+[MIT](LICENSE)
diff --git a/src/app/controls.ts b/src/app/controls.ts
index 1794edc..7a1ac97 100644
--- a/src/app/controls.ts
+++ b/src/app/controls.ts
@@ -1,6 +1,4 @@
import type { Gpu } from "vgpu";
-import type { Preview } from "@/app/document";
-import { setAdjustments, setToneCurve } from "@/app/document/edits";
import {
type ExportOptions,
exportImage,
@@ -8,9 +6,15 @@ import {
import { createCameraRawXmpLoader } from "@/app/loaders/camera-raw-xmp";
import { createImageLoader } from "@/app/loaders/image";
import { createLoaderRegistry } from "@/app/loaders/registry";
-import { type Adjustments, defaultAdjustments } from "@/app/scene";
import type { Workspace } from "@/app/workspace";
-import { defaultCurve, type ToneCurve } from "@/features/tone-curves/curve";
+import type { Preview } from "@/lib/editor/document";
+import { setAdjustments, setToneCurve } from "@/lib/editor/document/edits";
+import {
+ type Adjustments,
+ defaultAdjustments,
+ type Scene,
+} from "@/lib/editor/scene";
+import { defaultCurve, type ToneCurve } from "@/lib/tone-curves/curve";
/** Imperative commands bound to an explicit workspace, usable without React. */
export function createControls(gpu: Gpu, workspace: Workspace) {
@@ -20,6 +24,7 @@ export function createControls(gpu: Gpu, workspace: Workspace) {
[xmp, image],
() => workspace.state.getState().status === "ready",
);
+
return {
openFiles: files.openFiles,
openFile: (file: File) => files.openFiles([file]),
@@ -29,6 +34,10 @@ export function createControls(gpu: Gpu, workspace: Workspace) {
setAdjustments(workspace.getDocument(), change),
setToneCurve: (curve?: ToneCurve) =>
setToneCurve(workspace.getDocument(), curve),
+ editScene(change: Partial<Scene>) {
+ const document = workspace.getDocument();
+ document.edit({ ...document.scene.getState(), ...change });
+ },
setPreview: (change: Partial<Preview>) =>
workspace.getDocument().preview.setState(change),
beginEdit: () => workspace.getDocument().history.begin(),
@@ -41,22 +50,19 @@ export function createControls(gpu: Gpu, workspace: Workspace) {
getState() {
const { file, document } = workspace.state.getState();
const scene = document?.scene.getState();
- return {
+ return structuredClone({
file,
- preview: document && { ...document.preview.getState() },
+ preview: document?.preview.getState(),
documentId: document?.id,
- size: scene && [...scene.size],
- adjustments: { ...(scene?.adjustments ?? defaultAdjustments) },
- toneCurve: (scene?.toneCurve ?? defaultCurve).map((point) => ({
- ...point,
- })),
- history: {
- ...(document?.history.status.getState() ?? {
- undoCount: 0,
- redoCount: 0,
- }),
+ size: scene?.frame.size,
+ frame: scene?.frame,
+ adjustments: scene?.adjustments ?? defaultAdjustments,
+ toneCurve: scene?.toneCurve ?? defaultCurve,
+ history: document?.history.status.getState() ?? {
+ undoCount: 0,
+ redoCount: 0,
},
- };
+ });
},
};
}
diff --git a/src/app/document/provider.tsx b/src/app/document/provider.tsx
deleted file mode 100644
index 7b4a71b..0000000
--- a/src/app/document/provider.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { createContext, useContext } from "react";
-import { useStore } from "zustand";
-import type { Scene } from "@/app/scene";
-import type { EditorDocument } from "./index";
-
-export const DocumentProvider = createContext<EditorDocument | null>(null);
-
-export function useDocument() {
- const document = useContext(DocumentProvider);
- if (!document) {
- throw new Error("useDocument requires DocumentProvider.");
- }
- return document;
-}
-
-export function useScene<T>(selector: (scene: Scene) => T) {
- return useStore(useDocument().scene, selector);
-}
diff --git a/src/app/editor/canvas.tsx b/src/app/editor/canvas.tsx
new file mode 100644
index 0000000..bb15618
--- /dev/null
+++ b/src/app/editor/canvas.tsx
@@ -0,0 +1,13 @@
+import { Image } from "@/components/editor/image";
+import { useScene } from "@/components/editor/session";
+import { EditorViewport } from "@/components/editor/viewport";
+import { ComparisonDivider } from "./comparison-divider";
+
+export function EditorCanvas() {
+ const size = useScene((scene) => scene.frame.size);
+ return (
+ <EditorViewport size={size} overlay={<ComparisonDivider />}>
+ <Image original="originalImage" />
+ </EditorViewport>
+ );
+}
diff --git a/src/app/editor/comparison-divider.tsx b/src/app/editor/comparison-divider.tsx
index b00f13e..39d06cd 100644
--- a/src/app/editor/comparison-divider.tsx
+++ b/src/app/editor/comparison-divider.tsx
@@ -1,6 +1,6 @@
import type { PointerEvent } from "react";
import { useStore } from "zustand";
-import { useDocument } from "@/app/document/provider";
+import { useDocument } from "@/components/editor/session";
export function ComparisonDivider() {
const { preview } = useDocument();
diff --git a/src/app/editor/export/export-button.tsx b/src/app/editor/export/export-button.tsx
index 20582e6..c88ba1a 100644
--- a/src/app/editor/export/export-button.tsx
+++ b/src/app/editor/export/export-button.tsx
@@ -7,7 +7,7 @@ export function ExportButton() {
return (
<div className="ml-auto">
<Button
- className="flex h-8 items-center gap-2 rounded-md px-3 py-0 text-xs"
+ className="flex items-center gap-2"
onClick={() => dialog.current?.showModal()}
>
<svg
@@ -27,7 +27,7 @@ export function ExportButton() {
<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-neutral-800 p-0 text-neutral-100 shadow-2xl backdrop:bg-black/50 backdrop:backdrop-blur-sm"
+ 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>
diff --git a/src/app/editor/export/export-image.ts b/src/app/editor/export/export-image.ts
index 834e3df..078d79a 100644
--- a/src/app/editor/export/export-image.ts
+++ b/src/app/editor/export/export-image.ts
@@ -1,12 +1,13 @@
import { frame, type Gpu, surface } from "vgpu";
-import type { EditorDocument } from "@/app/document";
-import { createRenderer } from "@/app/editor/renderer/renderer";
+import type { EditorDocument } from "@/lib/editor/document";
+import { createRenderer } from "@/lib/editor/renderer";
+import { createDisplay } from "@/lib/image-display";
export type ExportOptions =
| { format: "png" }
| { format: "jpeg"; quality: number };
-/** Renders a snapshot of the current edits at the original image dimensions. */
+/** Renders a snapshot of the current edits at the document dimensions. */
export async function exportImage(
gpu: Gpu,
document: EditorDocument,
@@ -28,14 +29,17 @@ export async function exportImage(
let output: ReturnType<typeof surface> | undefined;
let renderer: ReturnType<typeof createRenderer> | undefined;
try {
- const [width, height] = scene.size;
+ 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, image);
renderer.update(scene);
- const draw = renderer.draw;
+ const draw = createDisplay(gpu);
+ const texture = renderer.outputImage();
const destination = output;
- frame(gpu, (frame) => draw(frame, destination, { zoom: 1, pan: [0, 0] }));
+ frame(gpu, (frame) =>
+ draw(frame, destination, texture, { view: { zoom: 1, pan: [0, 0] } }),
+ );
// Source work is submitted before yielding; the canvas owns the export pixels.
const blob = await canvas.convertToBlob({
type: `image/${options.format}`,
diff --git a/src/app/editor/export/export-settings.tsx b/src/app/editor/export/export-settings.tsx
index 620c814..10fad06 100644
--- a/src/app/editor/export/export-settings.tsx
+++ b/src/app/editor/export/export-settings.tsx
@@ -1,7 +1,7 @@
import { useRef, useState } from "react";
import { useGpu } from "vgpu-react";
-import { useDocument } from "@/app/document/provider";
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";
@@ -101,7 +101,7 @@ export function ExportSettings({ onClose }: { onClose: () => void }) {
</p>
)}
</div>
- <footer className="flex justify-end gap-2 bg-neutral-900/40 px-4 py-3">
+ <footer className="flex justify-end gap-2 bg-panel p-3">
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
diff --git a/src/app/editor/history.tsx b/src/app/editor/history.tsx
index 66ad4da..e851f60 100644
--- a/src/app/editor/history.tsx
+++ b/src/app/editor/history.tsx
@@ -1,38 +1,18 @@
-import { useEffect } from "react";
import { useStore } from "zustand";
-import { useDocument } from "@/app/document/provider";
+import { useDocument } from "@/components/editor/session";
+import { Icon } from "@/components/icons/icon";
import Button from "@/components/ui/button";
+import { useShortcuts } from "@/hooks/use-shortcuts";
export function HistoryControls() {
const { history } = useDocument();
const { undoCount, redoCount } = useStore(history.status);
- useEffect(() => {
- function keyDown(event: KeyboardEvent) {
- const target = event.target;
- if (
- target instanceof HTMLElement &&
- (target.isContentEditable ||
- target.closest('input:not([type="range"]), textarea, select'))
- ) {
- return;
- }
- if (!(event.metaKey || event.ctrlKey) || event.altKey) {
- return;
- }
- const key = event.key.toLowerCase();
- if (key !== "z" && key !== "y") {
- return;
- }
- event.preventDefault();
- if (key === "y" || event.shiftKey) {
- history.redo();
- } else {
- history.undo();
- }
- }
- window.addEventListener("keydown", keyDown);
- return () => window.removeEventListener("keydown", keyDown);
- }, [history]);
+ useShortcuts({
+ "mod+z": history.undo,
+ "mod+shift+z": history.redo,
+ "mod+y": history.redo,
+ "mod+shift+y": history.redo,
+ });
return (
<fieldset aria-label="History" className="flex items-center gap-0.5">
<Button
@@ -43,18 +23,9 @@ export function HistoryControls() {
disabled={!undoCount}
onClick={history.undo}
>
- <svg
- aria-hidden="true"
- viewBox="0 0 20 20"
- className="size-4"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
+ <Icon viewBox="0 0 20 20" className="size-4">
<path d="m7 4-4 4 4 4M3 8h8a5 5 0 0 1 0 10" />
- </svg>
+ </Icon>
</Button>
<Button
variant="ghost"
@@ -64,18 +35,9 @@ export function HistoryControls() {
disabled={!redoCount}
onClick={history.redo}
>
- <svg
- aria-hidden="true"
- viewBox="0 0 20 20"
- className="size-4"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
+ <Icon viewBox="0 0 20 20" className="size-4">
<path d="m13 4 4 4-4 4m4-4H9a5 5 0 0 0 0 10" />
- </svg>
+ </Icon>
</Button>
</fieldset>
);
diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsx
index d9b7520..897e1df 100644
--- a/src/app/editor/index.tsx
+++ b/src/app/editor/index.tsx
@@ -1,36 +1,36 @@
-import { Canvas } from "vgpu-react";
-import { DocumentProvider } from "@/app/document/provider";
+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 ResizablePanel from "@/components/ui/resizable-panel";
import Spinner from "@/components/ui/spinner";
-import { usePanZoom } from "@/hooks/use-pan-zoom";
-import type { Target } from "@/lib/decode";
-import { ComparisonDivider } from "./comparison-divider";
-import { CanvasRenderer } from "./renderer";
-import { RendererProvider } from "./renderer/provider";
+import { CropButton } from "@/features/crop/button";
+import { CropEditor } from "@/features/crop/view";
+import { EditorCanvas } from "./canvas";
import { Sidebar } from "./sidebar";
-type WorkspaceProps = { image: Target };
-
-function ImageCanvas({ image }: WorkspaceProps) {
- const { ref, view, handlers } = usePanZoom(image.size);
+function AdjustmentEditor({ children }: { children: ReactNode }) {
+ return (
+ <RendererProvider>
+ <EditorCanvas />
+ <Sidebar>{children}</Sidebar>
+ </RendererProvider>
+ );
+}
+function DocumentEditor() {
+ const [cropping, setCropping] = useState(false);
+ if (cropping) {
+ return <CropEditor onClose={() => setCropping(false)} />;
+ }
return (
- <div
- className="relative grid min-h-0 min-w-0 flex-1 overflow-hidden cursor-grab touch-none place-items-center active:cursor-grabbing"
- ref={ref}
- {...handlers}
- >
- <Canvas className="size-full min-h-0">
- <CanvasRenderer view={view} />
- </Canvas>
- <ComparisonDivider />
- </div>
+ <AdjustmentEditor>
+ <CropButton onClick={() => setCropping(true)} />
+ </AdjustmentEditor>
);
}
type EditorProps = { state: ReturnType<Workspace["state"]["getState"]> };
-
function LoadingStatus({ state }: EditorProps) {
if (state.status !== "error") {
return <Spinner />;
@@ -41,19 +41,11 @@ function LoadingStatus({ state }: EditorProps) {
</p>
);
}
-
function EditorContent({ state }: EditorProps) {
if (state.status === "ready") {
- const { document } = state;
- const image = document.resources.get(
- document.scene.getState().source,
- ).image;
return (
- <DocumentProvider value={document}>
- <RendererProvider source={image}>
- <ImageCanvas image={image} />
- <Sidebar />
- </RendererProvider>
+ <DocumentProvider key={state.document.id} value={state.document}>
+ <DocumentEditor />
</DocumentProvider>
);
}
@@ -66,7 +58,6 @@ function EditorContent({ state }: EditorProps) {
</>
);
}
-
export default function Editor({ state }: EditorProps) {
return (
<main className="flex h-dvh flex-col md:flex-row">
diff --git a/src/app/editor/renderer/index.tsx b/src/app/editor/renderer/index.tsx
deleted file mode 100644
index 3c24270..0000000
--- a/src/app/editor/renderer/index.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { useEffect } from "react";
-import { useCanvas, useFrame } from "vgpu-react";
-import { useStore } from "zustand";
-import { useDocument } from "@/app/document/provider";
-import type { View } from "@/hooks/use-pan-zoom";
-import { useRenderer } from "./provider";
-
-type CanvasRendererProps = { view: View };
-
-export function CanvasRenderer({ view }: CanvasRendererProps) {
- const renderer = useRenderer();
- const preview = useStore(useDocument().preview);
- const canvas = useCanvas();
- const draw = useFrame((frame) => renderer.draw(frame, canvas, view, preview));
- useEffect(() => {
- const unsubscribe = renderer.subscribe(draw);
- const observer = new ResizeObserver(draw);
- if (canvas.canvas instanceof HTMLCanvasElement) {
- observer.observe(canvas.canvas);
- }
- return () => {
- unsubscribe();
- observer.disconnect();
- };
- }, [renderer, canvas, draw]);
- useEffect(() => draw(), [draw, view, preview]);
- return null;
-}
diff --git a/src/app/editor/renderer/renderer.ts b/src/app/editor/renderer/renderer.ts
deleted file mode 100644
index c06fb1a..0000000
--- a/src/app/editor/renderer/renderer.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import {
- effect,
- type Frame,
- frame,
- type Gpu,
- sampler,
- type Target,
-} from "vgpu";
-import type { Preview } from "@/app/document";
-import type { Scene } from "@/app/scene";
-import { createToneCurves } from "@/features/tone-curves/pass";
-import type { View } from "@/hooks/use-pan-zoom";
-import { createAdjustments } from "@/lib/adjustments";
-import shader from "./renderer.wgsl";
-
-/** Owns scene passes and intermediate textures for one decoded source. */
-export function createRenderer(gpu: Gpu, source: Target) {
- const adjust = createAdjustments(gpu, source);
- const adjusted = adjust.output;
- const toneCurves = createToneCurves(gpu, adjusted);
- const display = effect(gpu, shader, {
- set: {
- sourceSampler: sampler(gpu, { magFilter: "linear", minFilter: "linear" }),
- },
- });
-
- const listeners = new Set<() => void>();
- let rendered = false;
- let output = adjusted;
- return {
- inputImage: () => adjusted,
- outputImage: () => output,
- subscribe(listener: () => void) {
- listeners.add(listener);
- if (rendered) {
- listener();
- }
- return () => {
- listeners.delete(listener);
- };
- },
- update(scene: Scene) {
- frame(gpu, (frame) => {
- adjust.render(frame, scene.adjustments);
- output = toneCurves.render(frame, scene.toneCurve);
- });
- rendered = true;
- for (const listener of listeners) {
- listener();
- }
- },
- draw(
- frame: Frame,
- canvas: Target & { dpr: number },
- view: View,
- preview?: Preview,
- ) {
- if (!rendered) {
- return;
- }
- const image = preview?.comparison === "original" ? source : output;
- frame.pass(
- canvas,
- display.set({
- source: image.color,
- original: source.color,
- params: {
- size: canvas.size,
- sourceSize: image.size,
- pan: view.pan.map((p) => p * canvas.dpr),
- zoom: view.zoom,
- split: preview?.comparison === "split" ? preview.split : -1,
- shadows: Number(preview?.shadows ?? false),
- highlights: Number(preview?.highlights ?? false),
- },
- }),
- );
- },
- dispose() {
- listeners.clear();
- adjust.dispose();
- toneCurves.dispose();
- },
- };
-}
diff --git a/src/app/editor/renderer/renderer.wgsl b/src/app/editor/renderer/renderer.wgsl
deleted file mode 100644
index bf2f6ee..0000000
--- a/src/app/editor/renderer/renderer.wgsl
+++ /dev/null
@@ -1,39 +0,0 @@
-import { display, rec2020ToSrgb } from "../../../lib/color.wgsl";
-
-struct Params {
- size: vec2f,
- sourceSize: vec2f,
- pan: vec2f,
- zoom: f32,
- split: f32,
- shadows: u32,
- highlights: u32,
-}
-@group(0) @binding(0) var<uniform> params: Params;
-@group(0) @binding(1) var source: texture_2d<f32>;
-@group(0) @binding(2) var sourceSampler: sampler;
-@group(0) @binding(3) var original: texture_2d<f32>;
-
-const background = vec3f(0.09);
-
-@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
- // Zoom 1 fits the image (contain, capped at 1:1), scaled about the center, then shifted by pan.
- let scale = min(min(params.size.x / params.sourceSize.x, params.size.y / params.sourceSize.y), 1.0) * params.zoom;
- let p = ((uv - 0.5) * params.size - params.pan) / (params.sourceSize * scale) + 0.5;
- let inside = all(p >= vec2f(0.0)) && all(p <= vec2f(1.0));
- var sample = textureSampleLevel(source, sourceSampler, p, 0.0);
- if (uv.x < params.split) {
- sample = textureSampleLevel(original, sourceSampler, p, 0.0);
- }
- let rgb = rec2020ToSrgb * sample.rgb;
- var color = display(sample.rgb);
- if (sample.a > 0.0) {
- if (params.shadows != 0u && all(rgb <= vec3f(0.0))) {
- color = vec3f(0.0, 0.0, 1.0);
- }
- if (params.highlights != 0u && any(rgb >= vec3f(1.0))) {
- color = vec3f(1.0, 0.0, 0.0);
- }
- }
- return vec4f(select(background, color, inside), 1.0);
-}
diff --git a/src/app/editor/sidebar/adjustment-controls.tsx b/src/app/editor/sidebar/adjustment-controls.tsx
index 8db523e..84d946d 100644
--- a/src/app/editor/sidebar/adjustment-controls.tsx
+++ b/src/app/editor/sidebar/adjustment-controls.tsx
@@ -1,12 +1,12 @@
import type { ComponentProps } from "react";
-import { setAdjustments } from "@/app/document/edits";
-import { useDocument, useScene } from "@/app/document/provider";
+import { useDocument, useScene } from "@/components/editor/session";
+import { Slider } from "@/components/ui/slider";
+import { setAdjustments } from "@/lib/editor/document/edits";
import {
type Adjustments,
adjustmentLimits,
defaultAdjustments,
-} from "@/app/scene";
-import { Slider } from "@/components/ui/slider";
+} from "@/lib/editor/scene";
const stops = {
incrementalTemperature: ["#4a6fc3", "#c3b84a"],
diff --git a/src/app/editor/sidebar/clipping-controls.tsx b/src/app/editor/sidebar/clipping-controls.tsx
index 7bcbea3..fdf4872 100644
--- a/src/app/editor/sidebar/clipping-controls.tsx
+++ b/src/app/editor/sidebar/clipping-controls.tsx
@@ -1,5 +1,5 @@
import { useStore } from "zustand";
-import { useDocument } from "@/app/document/provider";
+import { useDocument } from "@/components/editor/session";
import Button from "@/components/ui/button";
export function ClippingControls() {
diff --git a/src/app/editor/sidebar/comparison-control.tsx b/src/app/editor/sidebar/comparison-control.tsx
index 67a3fe5..60b607c 100644
--- a/src/app/editor/sidebar/comparison-control.tsx
+++ b/src/app/editor/sidebar/comparison-control.tsx
@@ -1,8 +1,8 @@
import { useEffect } from "react";
import { useStore } from "zustand";
-import type { Preview } from "@/app/document";
-import { useDocument } from "@/app/document/provider";
+import { useDocument } from "@/components/editor/session";
import Button from "@/components/ui/button";
+import type { Preview } from "@/lib/editor/document";
export function ComparisonControl() {
const { preview } = useDocument();
diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/sidebar/index.tsx
index c8a76bb..eb22ba3 100644
--- a/src/app/editor/sidebar/index.tsx
+++ b/src/app/editor/sidebar/index.tsx
@@ -1,15 +1,18 @@
-import { useEffect, useMemo } from "react";
+import { type ReactNode, useEffect, useMemo } from "react";
import { useGpu } from "vgpu-react";
-import { setToneCurve } from "@/app/document/edits";
-import { useDocument, useScene } from "@/app/document/provider";
import { ExportButton } from "@/app/editor/export/export-button";
import { HistoryControls } from "@/app/editor/history";
-import { useRenderer } from "@/app/editor/renderer/provider";
-import ResizablePanel from "@/components/ui/resizable-panel";
+import { useRenderer } from "@/components/editor/pipeline";
+import {
+ EditorPanel,
+ useDocument,
+ useScene,
+} from "@/components/editor/session";
import { Histogram } from "@/features/histogram";
import { createHistogram } from "@/features/histogram/histogram";
import { ToneCurves } from "@/features/tone-curves/tone-curves";
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";
@@ -44,14 +47,15 @@ function ToneCurvesPanel({
);
}
-export function Sidebar() {
+export function Sidebar({ children }: { children?: ReactNode }) {
const gpu = useGpu();
- const gesture = useEditGesture(useDocument().history);
+ const document = useDocument();
+ const gesture = useEditGesture(document.history);
const renderer = useRenderer();
const histogram = useMemo(() => createHistogram(gpu), [gpu]);
useEffect(() => () => histogram.dispose(), [histogram]);
return (
- <ResizablePanel>
+ <EditorPanel>
<div className="flex h-full flex-col divide-y divide-black">
<div
{...gesture}
@@ -72,12 +76,13 @@ export function Sidebar() {
<AdjustmentControls />
<ToneCurvesPanel histogram={histogram} />
</div>
- <div className="flex shrink-0 items-center gap-2 bg-neutral-900 px-2 py-1.5">
+ <div className="flex shrink-0 items-center gap-2 bg-panel p-3">
<HistoryControls />
<ComparisonControl />
+ {children}
<ExportButton />
</div>
</div>
- </ResizablePanel>
+ </EditorPanel>
);
}
diff --git a/src/app/loaders/camera-raw-xmp.ts b/src/app/loaders/camera-raw-xmp.ts
index 890a757..cf94a38 100644
--- a/src/app/loaders/camera-raw-xmp.ts
+++ b/src/app/loaders/camera-raw-xmp.ts
@@ -1,11 +1,11 @@
-import { setAdjustments } from "@/app/document/edits";
-import type { Adjustments } from "@/app/scene";
import type { Workspace } from "@/app/workspace";
import {
type CameraRawXmp,
isCameraRawXmp,
readCameraRawXmp,
} from "@/features/camera-raw-xmp/xmp";
+import { setAdjustments } from "@/lib/editor/document/edits";
+import type { Adjustments } from "@/lib/editor/scene";
import type { FileLoader } from "./registry";
function toAdjustments(xmp: CameraRawXmp): Partial<Adjustments> {
diff --git a/src/app/loaders/image.ts b/src/app/loaders/image.ts
index 93d5035..42cb048 100644
--- a/src/app/loaders/image.ts
+++ b/src/app/loaders/image.ts
@@ -1,10 +1,11 @@
import type { Gpu } from "vgpu";
-import { createDocument } from "@/app/document";
-import { createResources } from "@/app/document/resources";
-import { defaultAdjustments } from "@/app/scene";
import type { Workspace } from "@/app/workspace";
-import { defaultCurve } from "@/features/tone-curves/curve";
import decode, { canDecode } from "@/lib/decode";
+import { createDocument } from "@/lib/editor/document";
+import { createResources } from "@/lib/editor/document/resources";
+import { defaultAdjustments } from "@/lib/editor/scene";
+import { imageFrame } from "@/lib/image-frame/geometry";
+import { defaultCurve } from "@/lib/tone-curves/curve";
import type { FileLoader } from "./registry";
export function createImageLoader(gpu: Gpu, workspace: Workspace): FileLoader {
@@ -21,7 +22,7 @@ export function createImageLoader(gpu: Gpu, workspace: Workspace): FileLoader {
const source = resources.add(file, image);
return createDocument(
{
- size: [image.size[0], image.size[1]],
+ frame: imageFrame(image.size),
source,
adjustments: { ...defaultAdjustments },
toneCurve: defaultCurve,
diff --git a/src/app/workspace/index.ts b/src/app/workspace/index.ts
index 580cb88..c2c88c1 100644
--- a/src/app/workspace/index.ts
+++ b/src/app/workspace/index.ts
@@ -1,5 +1,5 @@
import { createStore } from "zustand/vanilla";
-import type { EditorDocument } from "@/app/document";
+import type { EditorDocument } from "@/lib/editor/document";
type WorkspaceState =
| { status: "empty"; file?: undefined; document?: undefined }
diff --git a/src/components/editor/image.tsx b/src/components/editor/image.tsx
new file mode 100644
index 0000000..1324881
--- /dev/null
+++ b/src/components/editor/image.tsx
@@ -0,0 +1,50 @@
+import { useEffect, useMemo } from "react";
+import { useCanvas, useFrame, useGpu } from "vgpu-react";
+import { useStore } from "zustand";
+import { fitScale } from "@/hooks/use-pan-zoom";
+import { createDisplay } from "@/lib/image-display";
+import type { ImageFrame } from "@/lib/image-frame/geometry";
+import { useRenderer } from "./pipeline";
+import { useDocument } from "./session";
+import { useViewport } from "./viewport";
+
+type Output = "fullImage" | "inputImage" | "outputImage" | "originalImage";
+
+/** Mount a pipeline output; a supplied frame places the full source behind it. */
+export function Image({
+ image = "outputImage",
+ geometry,
+ original,
+}: {
+ image?: Output;
+ geometry?: ImageFrame;
+ original?: Output;
+}) {
+ const gpu = useGpu();
+ const canvas = useCanvas();
+ const camera = useViewport();
+ const preview = useStore(useDocument().preview);
+ const renderer = useRenderer();
+ const display = useMemo(() => createDisplay(gpu), [gpu]);
+ const render = useFrame((frame) => {
+ const before = original && renderer[original]();
+ const source =
+ preview.comparison === "original" && before ? before : renderer[image]();
+ const size = geometry?.size ?? source.size;
+ const view = {
+ ...camera.view,
+ zoom: camera.scale / (fitScale(size, camera.viewport) || 1),
+ };
+ display(frame, canvas, source, {
+ view,
+ viewport: camera.viewport,
+ frame: geometry,
+ original: before,
+ split: preview.comparison === "split" ? preview.split : -1,
+ clipping: preview,
+ });
+ });
+ useEffect(() => renderer.subscribe(render), [renderer, render]);
+ useEffect(() => render(), [render, camera, preview, geometry]);
+ return null;
+}
diff --git a/src/app/editor/renderer/provider.tsx b/src/components/editor/pipeline.tsx
similarity index 63%
rename from src/app/editor/renderer/provider.tsx
rename to src/components/editor/pipeline.tsx
index 4f55474..b91a2a7 100644
--- a/src/app/editor/renderer/provider.tsx
+++ b/src/components/editor/pipeline.tsx
@@ -5,11 +5,9 @@ import {
useEffect,
useMemo,
} from "react";
-import type { Target } from "vgpu";
import { useGpu } from "vgpu-react";
-import { useDocument } from "@/app/document/provider";
-import type { Scene } from "@/app/scene";
-import { createRenderer } from "./renderer";
+import { useDocument, useScene } from "@/components/editor/session";
+import { createRenderer } from "@/lib/editor/renderer";
const RendererContext = createContext<ReturnType<typeof createRenderer> | null>(
null,
@@ -23,18 +21,18 @@ export function useRenderer() {
return renderer;
}
-type RendererProviderProps = { source: Target; children: ReactNode };
+type RendererProviderProps = { children: ReactNode };
-export function RendererProvider({ source, children }: RendererProviderProps) {
+export function RendererProvider({ children }: RendererProviderProps) {
const gpu = useGpu();
const document = useDocument();
+ const sourceId = useScene((scene) => scene.source);
+ const source = document.resources.get(sourceId).image;
const renderer = useMemo(() => createRenderer(gpu, source), [gpu, source]);
useEffect(() => {
- const render = (scene: Scene) => {
- renderer.update(scene);
- };
+ const render = () => renderer.update(document.scene.getState());
const unsubscribe = document.scene.subscribe(render);
- render(document.scene.getState());
+ render();
return () => {
unsubscribe();
renderer.dispose();
diff --git a/src/components/editor/session.tsx b/src/components/editor/session.tsx
new file mode 100644
index 0000000..9d2f341
--- /dev/null
+++ b/src/components/editor/session.tsx
@@ -0,0 +1,60 @@
+import {
+ createContext,
+ type ReactNode,
+ useContext,
+ useMemo,
+ useState,
+} from "react";
+import { useStore } from "zustand";
+import ResizablePanel from "@/components/ui/resizable-panel";
+import { createCamera } from "@/hooks/use-pan-zoom";
+import type { EditorDocument } from "@/lib/editor/document";
+import type { Scene } from "@/lib/editor/scene";
+
+const Session = createContext<{
+ document: EditorDocument;
+ camera: ReturnType<typeof createCamera>;
+ width: number;
+ onWidthChange: (width: number) => void;
+} | null>(null);
+
+export function useEditorSession() {
+ const session = useContext(Session);
+ if (!session) {
+ throw new Error("An editor session is required.");
+ }
+ return session;
+}
+export function useDocument() {
+ return useEditorSession().document;
+}
+export function useScene<T>(selector: (scene: Scene) => T) {
+ return useStore(useDocument().scene, selector);
+}
+
+/** Preserve document UI state while independent tools mount and unmount. */
+export function DocumentProvider({
+ value,
+ children,
+}: {
+ value: EditorDocument;
+ children: ReactNode;
+}) {
+ const size = useStore(value.scene, (scene) => scene.frame.size);
+ const camera = useMemo(createCamera, [size[0], size[1]]);
+ const [width, onWidthChange] = useState(288);
+ return (
+ <Session value={{ document: value, camera, width, onWidthChange }}>
+ {children}
+ </Session>
+ );
+}
+
+export function EditorPanel({ children }: { children: ReactNode }) {
+ const { width, onWidthChange } = useEditorSession();
+ return (
+ <ResizablePanel width={width} onWidthChange={onWidthChange}>
+ {children}
+ </ResizablePanel>
+ );
+}
diff --git a/src/components/editor/viewport.tsx b/src/components/editor/viewport.tsx
new file mode 100644
index 0000000..c226b54
--- /dev/null
+++ b/src/components/editor/viewport.tsx
@@ -0,0 +1,49 @@
+import { createContext, type ReactNode, useContext } from "react";
+import { Canvas } from "vgpu-react";
+import { usePanZoom } from "@/hooks/use-pan-zoom";
+import type { Point } from "@/lib/image-frame/geometry";
+import { useEditorSession } from "./session";
+
+const Viewport = createContext<ReturnType<typeof usePanZoom> | null>(null);
+export function useViewport() {
+ const viewport = useContext(Viewport);
+ if (!viewport) {
+ throw new Error("An editor viewport is required.");
+ }
+ return viewport;
+}
+
+export function EditorViewport({
+ size,
+ constrain = true,
+ children,
+ overlay,
+}: {
+ size: Point;
+ constrain?: boolean;
+ children: ReactNode;
+ overlay?: ReactNode;
+}) {
+ const { camera } = useEditorSession();
+ const viewport = usePanZoom(camera, size, { constrain });
+ return (
+ <section
+ className="relative min-h-0 min-w-0 flex-1 overflow-hidden p-6"
+ aria-label="Image canvas"
+ >
+ <Viewport value={viewport}>
+ <div
+ ref={viewport.ref}
+ {...viewport.handlers}
+ data-pan-mode={viewport.panMode}
+ className="relative size-full cursor-grab touch-none active:cursor-grabbing data-[pan-mode=true]:[&_*]:cursor-grab! data-[pan-mode=true]:active:[&_*]:cursor-grabbing!"
+ >
+ <Canvas className="absolute -inset-6 size-[calc(100%+3rem)]">
+ {children}
+ </Canvas>
+ </div>
+ {overlay}
+ </Viewport>
+ </section>
+ );
+}
diff --git a/src/components/icons/crop.tsx b/src/components/icons/crop.tsx
new file mode 100644
index 0000000..30c2717
--- /dev/null
+++ b/src/components/icons/crop.tsx
@@ -0,0 +1,9 @@
+import { Icon, type IconProps } from "./icon";
+
+export function CropIcon(props: IconProps) {
+ return (
+ <Icon viewBox="0 0 20 20" {...props}>
+ <path d="M5 2v13h13M2 5h13v13" />
+ </Icon>
+ );
+}
diff --git a/src/components/icons/flip.tsx b/src/components/icons/flip.tsx
new file mode 100644
index 0000000..c5c51b4
--- /dev/null
+++ b/src/components/icons/flip.tsx
@@ -0,0 +1,11 @@
+import { Icon, type IconProps } from "./icon";
+
+export function FlipIcon(props: IconProps) {
+ return (
+ <Icon {...props}>
+ <path d="m15 5 6 7-6 7Z" />
+ <path d="M9 5 3 12l6 7Z" fill="currentColor" stroke="none" />
+ <path d="M12 3v18" strokeDasharray="0.1 3.5" />
+ </Icon>
+ );
+}
diff --git a/src/components/icons/icon.tsx b/src/components/icons/icon.tsx
new file mode 100644
index 0000000..f47e12c
--- /dev/null
+++ b/src/components/icons/icon.tsx
@@ -0,0 +1,18 @@
+import type { SVGProps } from "react";
+
+export type IconProps = SVGProps<SVGSVGElement>;
+export function Icon(props: IconProps) {
+ return (
+ <svg
+ aria-hidden="true"
+ viewBox="0 0 24 24"
+ className="size-5"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ {...props}
+ />
+ );
+}
diff --git a/src/components/icons/rotate-cursor.svg b/src/components/icons/rotate-cursor.svg
new file mode 100644
index 0000000..a706c0e
--- /dev/null
+++ b/src/components/icons/rotate-cursor.svg
@@ -0,0 +1,7 @@
+<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
+ <defs>
+ <path id="turn" d="M5 17A9 9 0 0 1 17 5M2 14l3 3 3-3M14 2l3 3-3 3" transform="rotate(-45 12 12)"/>
+ </defs>
+ <use href="#turn" stroke="#171717" stroke-width="3.5"/>
+ <use href="#turn" stroke="#fafafa" stroke-width="2"/>
+</svg>
diff --git a/src/components/icons/rotate.tsx b/src/components/icons/rotate.tsx
new file mode 100644
index 0000000..63e9f23
--- /dev/null
+++ b/src/components/icons/rotate.tsx
@@ -0,0 +1,11 @@
+import { Icon, type IconProps } from "./icon";
+
+export function RotateIcon(props: IconProps) {
+ return (
+ <Icon {...props}>
+ <path d="M4 12a8 8 0 0 1 14-5" />
+ <path d="M20 3v6h-6z" fill="currentColor" stroke="none" />
+ <path d="M4 12a8 8 0 0 0 16 0" strokeDasharray="0.1 3.5" />
+ </Icon>
+ );
+}
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 16cd452..89f3745 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -3,7 +3,7 @@ import { cn } from "cn";
import type { ComponentProps } from "react";
const button = cva(
- "cursor-pointer rounded-lg border px-3 py-2 transition-colors focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-neutral-400",
+ "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",
{
variants: {
variant: {
diff --git a/src/components/ui/resizable-panel.tsx b/src/components/ui/resizable-panel.tsx
index 930562e..76bf17e 100644
--- a/src/components/ui/resizable-panel.tsx
+++ b/src/components/ui/resizable-panel.tsx
@@ -1,15 +1,17 @@
import { cn } from "cn";
-import { type ComponentProps, type PointerEvent, useState } from "react";
+import type { ComponentProps, PointerEvent } from "react";
type ResizablePanelProps = ComponentProps<"aside"> & {
width?: number;
+ onWidthChange?: (width: number) => void;
min?: number;
max?: number;
};
/** Bottom half on mobile; right-side panel with a draggable left edge on desktop. */
export default function ResizablePanel({
- width: initial = 288,
+ width = 288,
+ onWidthChange,
min = 240,
max = 400,
className,
@@ -17,15 +19,14 @@ export default function ResizablePanel({
children,
...props
}: ResizablePanelProps) {
- const [width, setWidth] = useState(initial);
const resize = (event: PointerEvent) =>
event.buttons === 1 &&
- setWidth((width) => Math.min(max, Math.max(min, width - event.movementX)));
+ onWidthChange?.(Math.min(max, Math.max(min, width - event.movementX)));
return (
<aside
className={cn(
- "relative h-1/2 shrink-0 bg-neutral-800 shadow-ridge max-md:w-full! max-md:border-t max-md:border-neutral-600 md:h-auto",
+ "relative h-1/2 shrink-0 bg-panel shadow-ridge max-md:w-full! max-md:border-t max-md:border-neutral-600 md:h-auto",
className,
)}
style={{ width, ...style }}
diff --git a/src/components/ui/slider.tsx b/src/components/ui/slider.tsx
index 00ae6ae..971cf31 100644
--- a/src/components/ui/slider.tsx
+++ b/src/components/ui/slider.tsx
@@ -13,9 +13,6 @@ type SliderProps = {
stops?: string[];
};
-const track =
- "col-span-2 my-1 h-[4px] appearance-none rounded-full bg-neutral-900 shadow-groove outline-none focus-visible:ring-1 focus-visible:ring-neutral-100/50 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:size-3 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-neutral-100 [&::-webkit-slider-thumb]:ring-1 [&::-webkit-slider-thumb]:ring-neutral-800 [&::-moz-range-thumb]:size-2.5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-neutral-100 [&::-moz-range-thumb]:ring-1 [&::-moz-range-thumb]:ring-neutral-800";
-
/** Labeled slider paired with a scrubbable numeric field. */
export function Slider({
label,
@@ -35,27 +32,33 @@ export function Slider({
return (
<div className="grid grid-cols-[1fr_auto] items-center gap-y-0.5 text-neutral-400 text-sm">
<span>{label}</span>
- <ScrubInput
- aria-label={label}
- max={max}
- min={min}
- onChange={onChange}
- step={step}
- value={value}
- variant="text"
- />
- <input
- aria-label={label}
- className={track}
- max={max}
- min={min}
- onChange={(event) => onChange(event.currentTarget.valueAsNumber)}
- onDoubleClick={reset}
- step={step}
+ <div className="relative z-10">
+ <ScrubInput
+ aria-label={label}
+ max={max}
+ min={min}
+ onChange={onChange}
+ step={step}
+ value={value}
+ variant="text"
+ />
+ </div>
+ <div
+ className="relative col-span-2 my-1 h-1 min-w-11 rounded-full bg-neutral-900 shadow-groove"
style={gradient}
- type="range"
- value={value}
- />
+ >
+ <input
+ aria-label={label}
+ className="absolute top-1/2 h-11 w-full -translate-y-1/2 touch-pan-y appearance-none bg-transparent outline-none focus-visible:ring-1 focus-visible:ring-neutral-100/50 [&::-webkit-slider-runnable-track]:bg-transparent [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:size-3 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-neutral-100 [&::-webkit-slider-thumb]:ring-1 [&::-webkit-slider-thumb]:ring-neutral-800 [&::-moz-range-track]:bg-transparent [&::-moz-range-thumb]:size-2.5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-neutral-100 [&::-moz-range-thumb]:ring-1 [&::-moz-range-thumb]:ring-neutral-800"
+ max={max}
+ min={min}
+ onChange={(event) => onChange(event.currentTarget.valueAsNumber)}
+ onDoubleClick={reset}
+ step={step}
+ type="range"
+ value={value}
+ />
+ </div>
</div>
);
}
diff --git a/src/features/crop/button.tsx b/src/features/crop/button.tsx
new file mode 100644
index 0000000..715fe35
--- /dev/null
+++ b/src/features/crop/button.tsx
@@ -0,0 +1,18 @@
+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/geometry.ts b/src/features/crop/geometry.ts
new file mode 100644
index 0000000..42145fe
--- /dev/null
+++ b/src/features/crop/geometry.ts
@@ -0,0 +1,140 @@
+import {
+ type ImageFrame,
+ type Point,
+ sourceOffset,
+} from "@/lib/image-frame/geometry";
+import { clamp } from "@/lib/math";
+
+function radius(frame: ImageFrame): Point {
+ const x = sourceOffset(frame, frame.size[0] / 2, 0);
+ const y = sourceOffset(frame, 0, frame.size[1] / 2);
+ return [Math.abs(x[0]) + Math.abs(y[0]), Math.abs(x[1]) + Math.abs(y[1])];
+}
+
+/** Translation slides independently along source edges. */
+export function move(
+ frame: ImageFrame,
+ dx: number,
+ dy: number,
+ source: Point,
+): ImageFrame {
+ const offset = sourceOffset(frame, dx, dy);
+ const half = radius(frame);
+ return {
+ ...frame,
+ center: [
+ clamp(frame.center[0] + offset[0], half[0], source[0] - half[0]),
+ clamp(frame.center[1] + offset[1], half[1], source[1] - half[1]),
+ ],
+ };
+}
+
+/** Anchor the opposite source edge or corner, stopping the gesture at the first bound. */
+export function resize(
+ frame: ImageFrame,
+ handle: string,
+ dx: number,
+ dy: number,
+ ratio: number | null,
+ source: Point,
+): ImageFrame {
+ const sx = Number(handle.includes("e")) - Number(handle.includes("w"));
+ const sy = Number(handle.includes("s")) - Number(handle.includes("n"));
+ const xWeight = Math.abs(sx);
+ const yWeight = Math.abs(sy);
+ const width = frame.size[0] + sx * dx;
+ const height = frame.size[1] + sy * dy;
+ const w = ratio
+ ? Math.max(
+ 1,
+ ratio,
+ ((width * ratio * xWeight + height * yWeight) * ratio) /
+ (ratio * ratio * xWeight + yWeight),
+ )
+ : Math.max(1, width);
+ const h = ratio ? w / ratio : Math.max(1, height);
+ const offset = sourceOffset(
+ frame,
+ ((w - frame.size[0]) * sx) / 2,
+ ((h - frame.size[1]) * sy) / 2,
+ );
+ const before = radius(frame);
+ const after = radius({ ...frame, size: [w, h] });
+ let fraction = 1;
+ for (const axis of [0, 1]) {
+ for (const sign of [-1, 1]) {
+ const start = frame.center[axis] + sign * before[axis];
+ const end = frame.center[axis] + offset[axis] + sign * after[axis];
+ if (end < -1e-7 || end > source[axis] + 1e-7) {
+ fraction = Math.min(
+ fraction,
+ clamp((clamp(end, 0, source[axis]) - start) / (end - start)),
+ );
+ }
+ }
+ }
+ const blend = (a: number, b: number) => a + (b - a) * fraction;
+ return {
+ ...frame,
+ size: [blend(frame.size[0], w), blend(frame.size[1], h)],
+ center: [
+ frame.center[0] + offset[0] * fraction,
+ frame.center[1] + offset[1] * fraction,
+ ],
+ };
+}
+
+/** Magnify around the current source center only as much as coverage requires. */
+export function rotate(
+ frame: ImageFrame,
+ angle: number,
+ source: Point,
+): ImageFrame {
+ const next: ImageFrame = {
+ ...frame,
+ angle,
+ scale: [Math.sign(frame.scale[0]), Math.sign(frame.scale[1])],
+ };
+ const half = radius(next);
+ const scale = Math.min(
+ 1,
+ ...source.map(
+ (size, axis) =>
+ Math.min(frame.center[axis], size - frame.center[axis]) / half[axis],
+ ),
+ );
+ return { ...next, scale: [next.scale[0] * scale, next.scale[1] * scale] };
+}
+
+export function turn(frame: ImageFrame, direction: number): ImageFrame {
+ return {
+ ...frame,
+ rotation: (frame.rotation + direction * 90 + 360) % 360,
+ size: [frame.size[1], frame.size[0]],
+ scale: [frame.scale[1], frame.scale[0]],
+ };
+}
+
+export function flip(frame: ImageFrame, axis: number): ImageFrame {
+ const [x, y] = frame.scale;
+ return { ...frame, scale: axis === 0 ? [-x, y] : [x, -y] };
+}
+
+export function fitRatio(frame: ImageFrame, ratio: number): ImageFrame {
+ const width = Math.max(
+ 1,
+ ratio,
+ Math.min(frame.size[0], frame.size[1] * ratio),
+ );
+ // Keep one output pixel per axis without expanding source coverage.
+ const scale = Math.min(
+ 1,
+ frame.size[0] / width,
+ (frame.size[1] * ratio) / width,
+ );
+ return {
+ ...frame,
+ size: [width, width / ratio],
+ scale: [frame.scale[0] * scale, frame.scale[1] * scale],
+ };
+}
diff --git a/src/features/crop/overlay.tsx b/src/features/crop/overlay.tsx
new file mode 100644
index 0000000..ab32f2c
--- /dev/null
+++ b/src/features/crop/overlay.tsx
@@ -0,0 +1,164 @@
+import { type PointerEvent, useRef } from "react";
+import { useViewport } from "@/components/editor/viewport";
+import rotateCursor from "@/components/icons/rotate-cursor.svg?raw";
+import type { ImageFrame, Point } from "@/lib/image-frame/geometry";
+import { clamp } from "@/lib/math";
+import { move, resize, rotate } from "./geometry";
+
+const handles = [
+ ["n", "top", 50, 0, "ns-resize"],
+ ["e", "right", 100, 50, "ew-resize"],
+ ["s", "bottom", 50, 100, "ns-resize"],
+ ["w", "left", 0, 50, "ew-resize"],
+ ["nw", "top left", 0, 0, "nwse-resize"],
+ ["ne", "top right", 100, 0, "nesw-resize"],
+ ["sw", "bottom left", 0, 100, "nesw-resize"],
+ ["se", "bottom right", 100, 100, "nwse-resize"],
+] as const;
+const arrows: Record<string, Point> = {
+ ArrowLeft: [-1, 0],
+ ArrowRight: [1, 0],
+ ArrowUp: [0, -1],
+ ArrowDown: [0, 1],
+};
+
+export function CropOverlay({
+ frame,
+ source,
+ ratio,
+ onChange,
+}: {
+ frame: ImageFrame;
+ source: Point;
+ ratio: number | null;
+ onChange: (frame: ImageFrame) => void;
+}) {
+ const camera = useViewport();
+ const selection = useRef<HTMLDivElement>(null);
+ const style = {
+ width: frame.size[0] * camera.scale,
+ height: frame.size[1] * camera.scale,
+ marginLeft: camera.view.pan[0],
+ marginTop: camera.view.pan[1],
+ };
+ function hit(event: PointerEvent) {
+ const box = selection.current?.getBoundingClientRect();
+ if (!box || !(event.target instanceof Element)) {
+ return null;
+ }
+ const handle =
+ event.target.closest<HTMLElement>("[data-handle]")?.dataset.handle;
+ return { box, handle: handle ?? "rotate" };
+ }
+ function change(handle: string, dx: number, dy: number) {
+ onChange(
+ handle === "move"
+ ? move(frame, -dx, -dy, source)
+ : resize(frame, handle, dx * 2, dy * 2, ratio, source),
+ );
+ }
+ function start(event: PointerEvent<HTMLDivElement>) {
+ const target = hit(event);
+ if (event.button !== 0 || !event.isPrimary || !target?.handle) {
+ return;
+ }
+ const { handle, box } = target;
+ event.preventDefault();
+ event.stopPropagation();
+ const element = event.currentTarget;
+ element.setPointerCapture(event.pointerId);
+ if (event.target instanceof HTMLElement) {
+ event.target.closest("button")?.focus();
+ }
+ const { clientX: x, clientY: y, pointerId } = event;
+ const bearing = (px: number, py: number) =>
+ Math.atan2(py - box.y - box.height / 2, px - box.x - box.width / 2);
+ element.onpointermove = (pointer) => {
+ if (pointer.pointerId !== pointerId) {
+ return;
+ }
+ if (handle !== "rotate") {
+ change(
+ handle,
+ (pointer.clientX - x) / camera.scale,
+ (pointer.clientY - y) / camera.scale,
+ );
+ return;
+ }
+ const delta = bearing(pointer.clientX, pointer.clientY) - bearing(x, y);
+ const angle =
+ frame.angle +
+ (Math.atan2(Math.sin(delta), Math.cos(delta)) * 180) / Math.PI;
+ onChange(
+ rotate(frame, clamp(Math.round(angle * 10) / 10, -45, 45), source),
+ );
+ };
+ element.onlostpointercapture = () => {
+ element.onpointermove = null;
+ };
+ }
+ return (
+ <div
+ className="absolute -inset-6 touch-none"
+ onPointerDown={start}
+ onPointerMove={(event) => {
+ const target = hit(event);
+ if (target?.handle !== "rotate") {
+ event.currentTarget.style.cursor = "inherit";
+ return;
+ }
+ const { box } = target;
+ const angle = Math.atan2(
+ box.y + box.height / 2 - event.clientY,
+ box.x + box.width / 2 - event.clientX,
+ );
+ const svg = rotateCursor.replace(
+ 'transform="',
+ `transform="rotate(${Math.round((angle * 180) / Math.PI)} 12 12) `,
+ );
+ event.currentTarget.style.cursor = `url("data:image/svg+xml,${encodeURIComponent(svg)}") 12 12, crosshair`;
+ }}
+ >
+ <div
+ ref={selection}
+ role="application"
+ aria-label="Crop selection"
+ data-handle="move"
+ style={style}
+ className="absolute top-1/2 left-1/2 -translate-1/2 cursor-grab border border-white bg-[linear-gradient(to_right,#fff3_1px,transparent_1px),linear-gradient(to_bottom,#fff3_1px,transparent_1px)] bg-size-[33.333%_33.333%] shadow-[0_0_0_9999px_#0009] active:cursor-grabbing"
+ onKeyDown={(event) => {
+ const delta = arrows[event.key];
+ if (!delta || !(event.target instanceof HTMLElement)) {
+ return;
+ }
+ event.preventDefault();
+ const step = event.shiftKey ? 0.05 : 0.005;
+ change(
+ event.target.dataset.handle ?? "move",
+ delta[0] * source[0] * step,
+ delta[1] * source[1] * step,
+ );
+ }}
+ >
+ <button
+ type="button"
+ aria-label="Move crop"
+ className="absolute inset-0 cursor-[inherit] focus-visible:outline-2 focus-visible:outline-white"
+ />
+
+ {handles.map(([handle, label, left, top, cursor]) => (
+ <button
+ key={handle}
+ type="button"
+ data-handle={handle}
+ aria-label={`Resize crop ${label}`}
+ className="group absolute flex size-11 min-h-11 min-w-11 -translate-1/2 items-center justify-center outline-none data-[handle=n]:w-full data-[handle=s]:w-full data-[handle=e]:h-full data-[handle=w]:h-full"
+ style={{ left: `${left}%`, top: `${top}%`, cursor }}
+ >
+ <span className="pointer-events-none size-2.5 border border-neutral-900 bg-white group-focus-visible:ring-2 group-focus-visible:ring-neutral-400/50" />
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/src/features/crop/view.tsx b/src/features/crop/view.tsx
new file mode 100644
index 0000000..7dc8bfa
--- /dev/null
+++ b/src/features/crop/view.tsx
@@ -0,0 +1,192 @@
+import { useState } from "react";
+import { Image } from "@/components/editor/image";
+import { RendererProvider } from "@/components/editor/pipeline";
+import {
+ EditorPanel,
+ useDocument,
+ useEditorSession,
+} from "@/components/editor/session";
+import { EditorViewport } from "@/components/editor/viewport";
+import { FlipIcon } from "@/components/icons/flip";
+import { RotateIcon } from "@/components/icons/rotate";
+import Button from "@/components/ui/button";
+import { Field } from "@/components/ui/field";
+import { Slider } from "@/components/ui/slider";
+import { useShortcuts } from "@/hooks/use-shortcuts";
+import { imageFrame, type Point } from "@/lib/image-frame/geometry";
+import { fitRatio, flip, rotate, turn } from "./geometry";
+import { CropOverlay } from "./overlay";
+
+const actions = [
+ { label: "Rotate counterclockwise", turn: -1, transform: "scaleX(-1)" },
+ { label: "Rotate clockwise", turn: 1, transform: "" },
+ { label: "Flip horizontal", flip: 0, transform: "" },
+ { label: "Flip vertical", flip: 1, transform: "rotate(90deg)" },
+] as const;
+
+export function CropEditor({ onClose }: { onClose: () => void }) {
+ const document = useDocument();
+ const { camera } = useEditorSession();
+ const [frame, setFrame] = useState(() => document.scene.getState().frame);
+ const [reference, setReference] = useState(frame.size);
+ const [ratio, setRatio] = useState<number | null>(
+ frame.size[0] / frame.size[1],
+ );
+ const sourceId = document.scene.getState().source;
+ const [width, height] = document.resources.get(sourceId).image.size;
+ const source: Point = [width, height];
+ function fitView() {
+ camera.setState(camera.getInitialState(), true);
+ }
+ function reset() {
+ setFrame(imageFrame(source));
+ setReference(source);
+ setRatio(source[0] / source[1]);
+ fitView();
+ }
+ function apply() {
+ document.history.commit();
+ document.edit({ ...document.scene.getState(), frame });
+ fitView();
+ onClose();
+ }
+ useShortcuts({ enter: apply, escape: onClose }, { inputs: true });
+ const original =
+ frame.rotation % 180 ? source[1] / source[0] : source[0] / source[1];
+ const ratios = {
+ Original: original,
+ Square: 1,
+ "4:3": 4 / 3,
+ "3:2": 3 / 2,
+ "16:9": 16 / 9,
+ "4:5": 4 / 5,
+ "9:16": 9 / 16,
+ "3:4": 3 / 4,
+ "2:3": 2 / 3,
+ "5:4": 5 / 4,
+ };
+ const custom = ratio !== null && !Object.values(ratios).includes(ratio);
+ function changeRatio(value: string) {
+ const ratio = Number(value) || null;
+ setRatio(ratio);
+ if (ratio) {
+ setFrame(fitRatio(frame, ratio));
+ }
+ }
+
+ function applyAction(action: (typeof actions)[number]) {
+ if ("turn" in action) {
+ setFrame(turn(frame, action.turn));
+ setReference([reference[1], reference[0]]);
+ setRatio(ratio && 1 / ratio);
+ } else {
+ setFrame(flip(frame, action.flip));
+ }
+ }
+ return (
+ <RendererProvider>
+ <EditorViewport size={reference} constrain={false}>
+ <Image image="fullImage" geometry={frame} />
+ <CropOverlay
+ frame={frame}
+ source={source}
+ ratio={ratio}
+ onChange={setFrame}
+ />
+ </EditorViewport>
+ <EditorPanel>
+ <section
+ aria-label="Crop tool"
+ className="flex h-full flex-col bg-panel"
+ onKeyDown={(event) => {
+ if (
+ event.key === "Enter" &&
+ event.target instanceof Element &&
+ event.target.closest("button")
+ ) {
+ event.stopPropagation();
+ }
+ }}
+ >
+ <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">
+ <select
+ aria-label="Aspect ratio"
+ value={ratio ?? "free"}
+ className="w-full cursor-pointer bg-transparent px-1 text-neutral-100 outline-none [color-scheme:dark]"
+ onChange={(event) => changeRatio(event.currentTarget.value)}
+ >
+ <option value="free">Free</option>
+ {custom && <option value={ratio}>Current</option>}
+ {Object.entries(ratios).map(([label, value]) => (
+ <option key={label} value={value}>
+ {label}
+ </option>
+ ))}
+ </select>
+ </Field>
+ </label>
+ <section
+ aria-label="Rotate and flip image"
+ className="grid grid-cols-4 items-center gap-2"
+ >
+ <h3 className="col-span-3 text-xs font-medium text-neutral-400">
+ Rotate & flip
+ </h3>
+ <Button
+ variant="ghost"
+ className="justify-self-end px-2 py-1"
+ onClick={reset}
+ >
+ Reset
+ </Button>
+
+ {actions.map((action) => {
+ const Icon = "turn" in action ? RotateIcon : FlipIcon;
+
+ return (
+ <Button
+ key={action.label}
+ variant="ghost"
+ aria-label={action.label}
+ title={action.label}
+ className="flex h-9 items-center justify-center gap-1 rounded-md px-1"
+ onClick={() => applyAction(action)}
+ >
+ <Icon style={{ transform: action.transform }} />
+ {"turn" in action && <span className="text-xs">90°</span>}
+ </Button>
+ );
+ })}
+ </section>
+ <Slider
+ label="Rotation"
+ min={-45}
+ max={45}
+ step={0.1}
+ value={frame.angle}
+ defaultValue={0}
+ onChange={(angle) => setFrame(rotate(frame, angle, source))}
+ />
+ <p className="text-xs text-neutral-500">
+ Drag edges or corners to crop, inside to move, outside to rotate.
+ Space + drag to pan; Ctrl/⌘ + scroll to zoom.
+ </p>
+ <p className="text-xs tabular-nums text-neutral-400">
+ {frame.size.map(Math.round).join(" × ")} px
+ </p>
+ </div>
+ <div className="flex justify-end gap-2 border-t border-black p-3">
+ <Button variant="ghost" className="px-3" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button onClick={apply}>Apply crop</Button>
+ </div>
+ </section>
+ </EditorPanel>
+ </RendererProvider>
+ );
+}
diff --git a/src/features/tone-curves/graph.tsx b/src/features/tone-curves/graph.tsx
index f12eb39..4ced426 100644
--- a/src/features/tone-curves/graph.tsx
+++ b/src/features/tone-curves/graph.tsx
@@ -12,7 +12,7 @@ import {
removeCurvePoint,
sampleCurve,
type ToneCurve,
-} from "./curve";
+} from "@/lib/tone-curves/curve";
function gridLines(spacing: number) {
return Array.from({ length: 256 / spacing - 1 }, (_, index) => {
diff --git a/src/features/tone-curves/tone-curves.tsx b/src/features/tone-curves/tone-curves.tsx
index 2497d8e..123830c 100644
--- a/src/features/tone-curves/tone-curves.tsx
+++ b/src/features/tone-curves/tone-curves.tsx
@@ -1,5 +1,6 @@
import type { ReactNode } from "react";
-import { defaultCurve, type ToneCurve } from "./curve";
+import Button from "@/components/ui/button";
+import { defaultCurve, type ToneCurve } from "@/lib/tone-curves/curve";
import { Graph } from "./graph";
type ToneCurvesProps = {
@@ -13,26 +14,14 @@ export function ToneCurves({ points, onChange, children }: ToneCurvesProps) {
<section aria-label="Curves" className="space-y-2.5 p-4 shadow-ridge">
<div className="flex items-center justify-between">
<h2 className="text-sm text-neutral-400">Curves</h2>
- <button
+ <Button
+ variant="ghost"
aria-label="Reset curve"
- className="flex size-5 cursor-pointer items-center justify-center rounded text-neutral-500 transition-colors hover:bg-white/5 hover:text-neutral-300 focus-visible:outline-1 focus-visible:outline-neutral-400"
+ className="px-2 py-1 text-xs"
onClick={() => onChange(defaultCurve)}
- title="Reset curve"
- type="button"
>
- <svg
- aria-hidden="true"
- className="size-3.5"
- fill="none"
- stroke="currentColor"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth="1.5"
- viewBox="0 0 24 24"
- >
- <path d="M3 10a9 9 0 1 1 2.6 8.4M3 4v6h6" />
- </svg>
- </button>
+ Reset
+ </Button>
</div>
<div className="px-0.5">
<div className="relative aspect-square rounded border border-black bg-neutral-900 shadow-groove">
diff --git a/src/hooks/use-pan-zoom.ts b/src/hooks/use-pan-zoom.ts
index 92637b6..ef3d5a9 100644
--- a/src/hooks/use-pan-zoom.ts
+++ b/src/hooks/use-pan-zoom.ts
@@ -2,15 +2,21 @@ import {
type PointerEvent,
useCallback,
useEffect,
+ useLayoutEffect,
useRef,
useState,
} from "react";
+import { useStore } from "zustand";
+import { createStore } from "zustand/vanilla";
+import type { View } from "@/lib/image-display";
+
type Size = readonly [number, number, ...unknown[]];
type Point = readonly [number, number];
-export type View = { zoom: number; pan: Point };
const fit: View = { zoom: 1, pan: [0, 0] };
+export const createCamera = () => createStore<View>(() => fit);
+export type Camera = ReturnType<typeof createCamera>;
const maxZoom = 8;
function measureGesture(points: Iterable<Point>) {
@@ -21,9 +27,13 @@ function measureGesture(points: Iterable<Point>) {
};
}
+function pan(view: View, x: number, y: number): View {
+ return { ...view, pan: [view.pan[0] + x, view.pan[1] + y] };
+}
+
/** Keeps the content point under `focal` fixed while changing zoom. */
-function zoomAt(view: View, focal: Point, zoom: number): View {
- const ratio = Math.min(Math.max(zoom, 1), maxZoom) / view.zoom;
+function zoomAt(view: View, focal: Point, zoom: number, minimum = 1): View {
+ const ratio = Math.min(Math.max(zoom, minimum), maxZoom) / view.zoom;
return {
...view,
zoom: view.zoom * ratio,
@@ -34,14 +44,17 @@ function zoomAt(view: View, focal: Point, zoom: number): View {
};
}
+export function fitScale(content: Size, viewport: Size) {
+ return Math.min(
+ viewport[0] / content[0],
+ viewport[1] / content[1],
+ 2 / devicePixelRatio,
+ );
+}
+
/** Axes smaller than the viewport stay centered; larger ones cannot pan past their edge. */
function clamp(view: View, content: Size, viewport: Size): View {
- const scale =
- Math.min(
- viewport[0] / content[0],
- viewport[1] / content[1],
- 1 / devicePixelRatio,
- ) * view.zoom;
+ const scale = fitScale(content, viewport) * view.zoom;
const axis = (i: 0 | 1) => {
const room = Math.max(0, (content[i] * scale - viewport[i]) / 2);
return Math.min(room, Math.max(-room, view.pan[i]));
@@ -54,31 +67,88 @@ function clamp(view: View, content: Size, viewport: Size): View {
/**
* Pan and zoom over `content` inside the element given `ref`.
- * Zoom 1 is the initial fit: contain, but no larger than real size. `pan` is in CSS px from the viewport center.
+ * Zoom 1 is the initial fit: contain, but capped at 200%. `pan` is in CSS px from the viewport center.
* Wheel/drag pans, ctrl/cmd+wheel zooms at the cursor, two pointers pinch and pan, double-click resets.
*/
-export function usePanZoom(content?: Size) {
+export function usePanZoom(
+ state: Camera,
+ content: Size,
+ { constrain = true } = {},
+) {
const ref = useRef<HTMLDivElement>(null);
const pointers = useRef(new Map<number, Point>());
- const [view, setView] = useState(fit);
+ const boundedDrag = useRef(true);
+ const fitZoom = useRef(1);
+ const view = useStore(state);
+ const [viewport, setViewport] = useState<Point>([0, 0]);
+ const [panMode, setPanMode] = useState(false);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ const { signal } = controller;
+ function keyDown(event: KeyboardEvent) {
+ if (
+ event.code !== "Space" ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.altKey
+ ) {
+ return;
+ }
+ const target = event.target;
+ if (
+ target instanceof HTMLElement &&
+ (target.isContentEditable ||
+ target.closest(
+ 'input:not([type="range"]), textarea, select, dialog, [role="dialog"]',
+ ))
+ ) {
+ return;
+ }
+ event.preventDefault();
+ setPanMode(true);
+ }
+ function keyUp(event: KeyboardEvent) {
+ if (event.code === "Space") {
+ setPanMode(false);
+ }
+ }
+ function blur() {
+ setPanMode(false);
+ pointers.current.clear();
+ }
+ window.addEventListener("keydown", keyDown, { signal });
+ window.addEventListener("keyup", keyUp, { signal });
+ window.addEventListener("blur", blur, { signal });
+ return () => controller.abort();
+ }, []);
const update = useCallback(
- (next: (view: View) => View) => {
+ (next: (view: View) => View, bounded = constrain) => {
const element = ref.current;
- if (element && content) {
+ if (element) {
const viewport: Size = [element.clientWidth, element.clientHeight];
- setView((view) => clamp(next(view), content, viewport));
+ state.setState((view) => {
+ const result = next(view);
+ return bounded ? clamp(result, content, viewport) : result;
+ }, true);
}
},
- [content],
+ [state, content, constrain],
);
- useEffect(() => {
+ useLayoutEffect(() => update((view) => view), [update, viewport]);
+
+ useLayoutEffect(() => {
const element = ref.current;
if (!element) {
return;
}
- const observer = new ResizeObserver(() => update((view) => view));
+ const measure = () => {
+ setViewport([element.clientWidth, element.clientHeight]);
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
observer.observe(element);
const wheel = (event: WheelEvent) => {
event.preventDefault();
@@ -89,12 +159,14 @@ export function usePanZoom(content?: Size) {
];
update((view) => {
if (event.ctrlKey || event.metaKey) {
- return zoomAt(view, focal, view.zoom * Math.exp(-event.deltaY / 100));
+ return zoomAt(
+ view,
+ focal,
+ view.zoom * Math.exp(-event.deltaY / 100),
+ constrain ? 1 : fitZoom.current * 0.1,
+ );
}
- return {
- ...view,
- pan: [view.pan[0] - event.deltaX, view.pan[1] - event.deltaY],
- };
+ return pan(view, -event.deltaX, -event.deltaY);
});
};
element.addEventListener("wheel", wheel, { passive: false });
@@ -102,18 +174,33 @@ export function usePanZoom(content?: Size) {
observer.disconnect();
element.removeEventListener("wheel", wheel);
};
- }, [update]);
+ }, [update, constrain]);
const release = (event: PointerEvent<HTMLElement>) =>
pointers.current.delete(event.pointerId);
+ const resetView = (next = fit) => {
+ fitZoom.current = next.zoom;
+ state.setState(next, true);
+ };
+ function startDrag(event: PointerEvent<HTMLElement>) {
+ if (event.button !== 0 || pointers.current.size === 2) {
+ return;
+ }
+ if (pointers.current.size === 0) {
+ boundedDrag.current = constrain && !panMode;
+ }
+ pointers.current.set(event.pointerId, [event.clientX, event.clientY]);
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }
const handlers = {
- onPointerDown: (event: PointerEvent<HTMLElement>) => {
- if (event.button !== 0 || pointers.current.size === 2) {
- return;
+ onPointerDownCapture: (event: PointerEvent<HTMLElement>) => {
+ if (panMode && event.button === 0) {
+ event.preventDefault();
+ event.stopPropagation();
+ startDrag(event);
}
- pointers.current.set(event.pointerId, [event.clientX, event.clientY]);
- event.currentTarget.setPointerCapture(event.pointerId);
},
+ onPointerDown: startDrag,
onPointerMove: (event: PointerEvent<HTMLElement>) => {
const points = pointers.current;
if (!points.has(event.pointerId)) {
@@ -131,21 +218,32 @@ export function usePanZoom(content?: Size) {
const ratio =
previous.distance > 0 ? next.distance / previous.distance : 1;
update((view) => {
- const zoomed = zoomAt(view, focal, view.zoom * ratio);
- return {
- ...zoomed,
- pan: [
- zoomed.pan[0] + next.center[0] - previous.center[0],
- zoomed.pan[1] + next.center[1] - previous.center[1],
- ],
- };
- });
+ const zoomed = zoomAt(
+ view,
+ focal,
+ view.zoom * ratio,
+ constrain ? 1 : fitZoom.current * 0.1,
+ );
+ return pan(
+ zoomed,
+ next.center[0] - previous.center[0],
+ next.center[1] - previous.center[1],
+ );
+ }, boundedDrag.current);
},
onPointerUp: release,
onPointerCancel: release,
onLostPointerCapture: release,
- onDoubleClick: () => setView(fit),
+ onDoubleClick: () => resetView(),
};
- return { ref, view, handlers };
+ return {
+ ref,
+ view,
+ viewport,
+ handlers,
+ resetView,
+ panMode,
+ scale: fitScale(content, viewport) * view.zoom,
+ };
}
diff --git a/src/hooks/use-shortcuts.ts b/src/hooks/use-shortcuts.ts
new file mode 100644
index 0000000..1f05e27
--- /dev/null
+++ b/src/hooks/use-shortcuts.ts
@@ -0,0 +1,35 @@
+import { useEffect, useEffectEvent } from "react";
+
+/** View-scoped keyboard actions. Text fields opt in explicitly. */
+export function useShortcuts(
+ actions: Record<string, () => void>,
+ { inputs = false } = {},
+) {
+ const invoke = useEffectEvent((event: KeyboardEvent) => {
+ const modifier = event.ctrlKey || event.metaKey ? "mod+" : "";
+ const shift = modifier && event.shiftKey ? "shift+" : "";
+ if ((event.repeat && !modifier) || event.isComposing || event.altKey) {
+ return;
+ }
+ const target = event.target;
+ if (
+ !inputs &&
+ target instanceof HTMLElement &&
+ (target.isContentEditable ||
+ target.closest(
+ 'input:not([type="range"]), textarea, select, dialog, [role="dialog"]',
+ ))
+ ) {
+ return;
+ }
+ const action = actions[`${modifier}${shift}${event.key.toLowerCase()}`];
+ if (action) {
+ event.preventDefault();
+ action();
+ }
+ });
+ useEffect(() => {
+ window.addEventListener("keydown", invoke);
+ return () => window.removeEventListener("keydown", invoke);
+ }, []);
+}
diff --git a/src/index.css b/src/index.css
index 675e3dc..28ee5c6 100644
--- a/src/index.css
+++ b/src/index.css
@@ -1,6 +1,7 @@
@import "tailwindcss";
@theme {
+ --color-panel: var(--color-neutral-800);
--font-sans: "Geist Variable", system-ui, sans-serif;
}
diff --git a/src/app/document/edits.ts b/src/lib/editor/document/edits.ts
similarity index 88%
rename from src/app/document/edits.ts
rename to src/lib/editor/document/edits.ts
index 551e3d3..1d75274 100644
--- a/src/app/document/edits.ts
+++ b/src/lib/editor/document/edits.ts
@@ -1,9 +1,9 @@
-import { type Adjustments, adjustmentLimits } from "@/app/scene";
+import { type Adjustments, adjustmentLimits } from "@/lib/editor/scene";
import {
defaultCurve,
type ToneCurve,
validateCurve,
-} from "@/features/tone-curves/curve";
+} from "@/lib/tone-curves/curve";
import type { EditorDocument } from "./index";
export function setAdjustments(
diff --git a/src/app/document/index.ts b/src/lib/editor/document/index.ts
similarity index 88%
rename from src/app/document/index.ts
rename to src/lib/editor/document/index.ts
index 1b6de6c..afd9704 100644
--- a/src/app/document/index.ts
+++ b/src/lib/editor/document/index.ts
@@ -1,7 +1,8 @@
import { createStore } from "zustand/vanilla";
import { shallow } from "zustand/vanilla/shallow";
-import type { Scene } from "@/app/scene";
+import type { Scene } from "@/lib/editor/scene";
import { createHistory } from "@/lib/history";
+import { frameValues, validateFrame } from "@/lib/image-frame/geometry";
import { createResources } from "./resources";
export type Preview = {
@@ -14,7 +15,7 @@ export type Preview = {
function equal(a: Scene, b: Scene) {
return (
a.source === b.source &&
- shallow(a.size, b.size) &&
+ shallow(frameValues(a.frame), frameValues(b.frame)) &&
shallow(a.adjustments, b.adjustments) &&
a.toneCurve.length === b.toneCurve.length &&
a.toneCurve.every((point, i) => shallow(point, b.toneCurve[i]))
@@ -52,6 +53,7 @@ export function createDocument(initial: Scene, resources = createResources()) {
if (closed) {
throw new Error("Document is closed.");
}
+ validateFrame(next.frame);
update(next);
},
dispose() {
diff --git a/src/app/document/resources.ts b/src/lib/editor/document/resources.ts
similarity index 100%
rename from src/app/document/resources.ts
rename to src/lib/editor/document/resources.ts
diff --git a/src/lib/editor/renderer.ts b/src/lib/editor/renderer.ts
new file mode 100644
index 0000000..3b5e0b2
--- /dev/null
+++ b/src/lib/editor/renderer.ts
@@ -0,0 +1,56 @@
+import { frame, type Gpu, type Target } from "vgpu";
+import { createAdjustments } from "@/lib/adjustments";
+import type { Scene } from "@/lib/editor/scene";
+import { createImageFrame } from "@/lib/image-frame";
+import { createToneCurves } from "@/lib/tone-curves";
+
+/** Owns scene passes and intermediate textures for one decoded source. */
+export function createRenderer(gpu: Gpu, source: Target) {
+ const adjust = createAdjustments(gpu, source);
+ const adjusted = adjust.output;
+ const toneCurves = createToneCurves(gpu, adjusted);
+
+ const transform = createImageFrame(gpu);
+ let original = source;
+ let input = adjusted;
+ let fullImage = adjusted;
+ const listeners = new Set<() => void>();
+ let rendered = false;
+ let output = adjusted;
+ return {
+ originalImage: () => original,
+ inputImage: () => input,
+ fullImage: () => fullImage,
+ outputImage: () => output,
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ if (rendered) {
+ listener();
+ }
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ update(scene: Scene) {
+ frame(gpu, (frame) => {
+ adjust.render(frame, scene.adjustments);
+ fullImage = toneCurves.render(frame, scene.toneCurve);
+ [original, input, output] = transform.render(
+ frame,
+ [source, adjusted, fullImage],
+ scene.frame,
+ );
+ });
+ rendered = true;
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ dispose() {
+ listeners.clear();
+ adjust.dispose();
+ toneCurves.dispose();
+ transform.dispose();
+ },
+ };
+}
diff --git a/src/app/scene/index.ts b/src/lib/editor/scene.ts
similarity index 83%
rename from src/app/scene/index.ts
rename to src/lib/editor/scene.ts
index 2fb8ecd..e6e41fd 100644
--- a/src/app/scene/index.ts
+++ b/src/lib/editor/scene.ts
@@ -1,5 +1,6 @@
-import type { ToneCurve } from "@/features/tone-curves/curve";
import type { Adjustments } from "@/lib/adjustments";
+import type { ImageFrame } from "@/lib/image-frame/geometry";
+import type { ToneCurve } from "@/lib/tone-curves/curve";
export type { Adjustments } from "@/lib/adjustments";
@@ -31,7 +32,7 @@ export const adjustmentLimits: Adjustments = {
/** Serializable document content. Image bytes and GPU resources live elsewhere. */
export type Scene = {
- readonly size: readonly [number, number];
+ readonly frame: ImageFrame;
readonly source: string;
readonly adjustments: Readonly<Adjustments>;
readonly toneCurve: ToneCurve;
diff --git a/src/lib/image-display/display.wgsl b/src/lib/image-display/display.wgsl
new file mode 100644
index 0000000..853e89c
--- /dev/null
+++ b/src/lib/image-display/display.wgsl
@@ -0,0 +1,30 @@
+import { display, rec2020ToSrgb } from "../color.wgsl";
+
+export struct View {
+ size: vec2f,
+ fitSize: vec2f,
+ imageSize: vec2f,
+ pan: vec2f,
+ zoom: f32,
+ shadows: u32,
+ highlights: u32,
+}
+export const background = vec3f(0.09);
+
+export fn imagePoint(view: View, uv: vec2f) -> vec2f {
+ let scale = min(min(view.fitSize.x / view.imageSize.x, view.fitSize.y / view.imageSize.y), 2.0) * view.zoom;
+ return ((uv - 0.5) * view.size - view.pan) / (view.imageSize * scale) + 0.5;
+}
+export fn previewColor(sample: vec4f, view: View) -> vec3f {
+ let rgb = rec2020ToSrgb * sample.rgb;
+ var color = display(sample.rgb);
+ if (sample.a > 0.0) {
+ if (view.shadows != 0u && all(rgb <= vec3f(0.0))) {
+ color = vec3f(0.0, 0.0, 1.0);
+ }
+ if (view.highlights != 0u && any(rgb >= vec3f(1.0))) {
+ color = vec3f(1.0, 0.0, 0.0);
+ }
+ }
+ return mix(background, color, sample.a);
+}
diff --git a/src/lib/image-display/image.wgsl b/src/lib/image-display/image.wgsl
new file mode 100644
index 0000000..7e81e70
--- /dev/null
+++ b/src/lib/image-display/image.wgsl
@@ -0,0 +1,18 @@
+import { View, imagePoint, previewColor, background } from "./display.wgsl";
+import { Transform, sourcePoint } from "../image-frame/transform.wgsl";
+
+@group(0) @binding(0) var<uniform> view: View;
+@group(0) @binding(1) var source: texture_2d<f32>;
+@group(0) @binding(2) var sourceSampler: sampler;
+@group(0) @binding(3) var<uniform> transform: Transform;
+@group(0) @binding(4) var original: texture_2d<f32>;
+@group(0) @binding(5) var<uniform> split: f32;
+
+@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
+ let p = sourcePoint(transform, imagePoint(view, uv));
+ let edited = textureSampleLevel(source, sourceSampler, p, 0.0);
+ let before = textureSampleLevel(original, sourceSampler, p, 0.0);
+ let color = previewColor(select(edited, before, uv.x < split), view);
+ let inside = all(p >= vec2f(0.0)) && all(p <= vec2f(1.0));
+ return vec4f(select(background, color, inside), 1.0);
+}
diff --git a/src/lib/image-display/index.ts b/src/lib/image-display/index.ts
new file mode 100644
index 0000000..9d498be
--- /dev/null
+++ b/src/lib/image-display/index.ts
@@ -0,0 +1,55 @@
+import { effect, type Frame, type Gpu, sampler, type Target } from "vgpu";
+import {
+ frameTransform,
+ type ImageFrame,
+ imageFrame,
+} from "@/lib/image-frame/geometry";
+import shader from "./image.wgsl";
+
+export type View = { zoom: number; pan: readonly [number, number] };
+export type Clipping = { shadows: boolean; highlights: boolean };
+type DisplayOptions = {
+ view: View;
+ viewport?: readonly number[];
+ frame?: ImageFrame;
+ original?: Target;
+ split?: number;
+ clipping?: Clipping;
+};
+
+/** Display any transformed image with optional comparison and clipping indicators. */
+export function createDisplay(gpu: Gpu) {
+ const draw = effect(gpu, shader, {
+ set: {
+ sourceSampler: sampler(gpu, { magFilter: "linear", minFilter: "linear" }),
+ },
+ });
+ return (
+ frame: Frame,
+ canvas: Target & { dpr: number },
+ image: Target,
+ options: DisplayOptions,
+ ) => {
+ const geometry = options.frame ?? imageFrame(image.size);
+ const viewport =
+ options.viewport ?? canvas.size.map((value) => value / canvas.dpr);
+ frame.pass(
+ canvas,
+ draw.set({
+ source: image.color,
+ original: (options.original ?? image).color,
+ transform: frameTransform(geometry, image.size),
+ split: options.split ?? -1,
+ view: {
+ size: canvas.size,
+ fitSize: viewport.map((value) => value * canvas.dpr),
+ imageSize: geometry.size,
+ pan: options.view.pan.map((value) => value * canvas.dpr),
+ zoom: options.view.zoom,
+ shadows: Number(options.clipping?.shadows ?? false),
+ highlights: Number(options.clipping?.highlights ?? false),
+ },
+ }),
+ );
+ };
+}
diff --git a/src/lib/image-frame/frame.wgsl b/src/lib/image-frame/frame.wgsl
new file mode 100644
index 0000000..07e6581
--- /dev/null
+++ b/src/lib/image-frame/frame.wgsl
@@ -0,0 +1,13 @@
+import { Transform, sourcePoint } from "./transform.wgsl";
+
+@group(0) @binding(0) var<uniform> transform: Transform;
+@group(0) @binding(1) var source: texture_2d<f32>;
+@group(0) @binding(2) var sourceSampler: sampler;
+
+@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
+ let p = sourcePoint(transform, uv);
+ if (any(p < vec2f(0.0)) || any(p > vec2f(1.0))) {
+ return vec4f(0.0);
+ }
+ return textureSampleLevel(source, sourceSampler, p, 0.0);
+}
diff --git a/src/lib/image-frame/geometry.ts b/src/lib/image-frame/geometry.ts
new file mode 100644
index 0000000..fed440f
--- /dev/null
+++ b/src/lib/image-frame/geometry.ts
@@ -0,0 +1,66 @@
+export type Point = readonly [number, number];
+export type ImageFrame = {
+ center: Point;
+ size: Point;
+ rotation: number;
+ angle: number;
+ scale: Point;
+};
+
+/** Source pixels under the output center, output dimensions, and signed source scale. */
+export function imageFrame(size: readonly number[]): ImageFrame {
+ return {
+ center: [size[0] / 2, size[1] / 2],
+ size: [size[0], size[1]],
+ rotation: 0,
+ angle: 0,
+ scale: [1, 1],
+ };
+}
+
+export function frameValues(frame: ImageFrame) {
+ return [
+ ...frame.center,
+ ...frame.size,
+ ...frame.scale,
+ frame.rotation,
+ frame.angle,
+ ];
+}
+
+export function validateFrame(frame: ImageFrame) {
+ if (
+ !frameValues(frame).every(Number.isFinite) ||
+ frame.size.some((value) => value < 1) ||
+ frame.scale.some((value) => value === 0)
+ ) {
+ throw new Error("Invalid image frame.");
+ }
+}
+
+export function sourceOffset(frame: ImageFrame, x: number, y: number): Point {
+ const angle = (-(frame.rotation + frame.angle) * Math.PI) / 180;
+ const dx = x * frame.scale[0];
+ const dy = y * frame.scale[1];
+ return [
+ Math.cos(angle) * dx - Math.sin(angle) * dy,
+ Math.sin(angle) * dx + Math.cos(angle) * dy,
+ ];
+}
+
+/** Affine UV mapping used by image display and resampling, independent of editing tools. */
+export function frameTransform(
+ frame: ImageFrame,
+ sourceSize: readonly number[],
+) {
+ const xAxis = sourceOffset(frame, frame.size[0], 0).map(
+ (value, axis) => value / sourceSize[axis],
+ );
+ const yAxis = sourceOffset(frame, 0, frame.size[1]).map(
+ (value, axis) => value / sourceSize[axis],
+ );
+ const origin = frame.center.map(
+ (value, axis) => value / sourceSize[axis] - (xAxis[axis] + yAxis[axis]) / 2,
+ );
+ return { origin, xAxis, yAxis };
+}
diff --git a/src/lib/image-frame/index.ts b/src/lib/image-frame/index.ts
new file mode 100644
index 0000000..d80c3f6
--- /dev/null
+++ b/src/lib/image-frame/index.ts
@@ -0,0 +1,63 @@
+import {
+ effect,
+ type Frame,
+ type Gpu,
+ sampler,
+ type Target,
+ target,
+} from "vgpu";
+import shader from "./frame.wgsl";
+import {
+ frameTransform,
+ frameValues,
+ type ImageFrame,
+ imageFrame,
+} from "./geometry";
+
+/** Transforms image outputs; equal inputs share a target and identity preserves the source. */
+export function createImageFrame(gpu: Gpu) {
+ const apply = effect(gpu, shader, {
+ set: {
+ sourceSampler: sampler(gpu, { magFilter: "linear", minFilter: "linear" }),
+ },
+ });
+ const outputs = new Map<Target, Target>();
+ return {
+ render(frame: Frame, sources: Target[], geometry: ImageFrame) {
+ const initial = frameValues(imageFrame(sources[0].size));
+ if (frameValues(geometry).every((value, i) => value === initial[i])) {
+ return sources;
+ }
+ const rendered = new Set<Target>();
+ return sources.map((source) => {
+ const size: [number, number] = [
+ Math.round(geometry.size[0]),
+ Math.round(geometry.size[1]),
+ ];
+ let output = outputs.get(source);
+ if (!output) {
+ output = target(gpu, { size, format: source.format });
+ outputs.set(source, output);
+ }
+ output.resize(size);
+ if (!rendered.has(source)) {
+ frame.pass(
+ output,
+ apply.set({
+ source: source.color,
+ transform: frameTransform(geometry, source.size),
+ }),
+ );
+ }
+ rendered.add(source);
+ return output;
+ });
+ },
+ dispose() {
+ for (const output of outputs.values()) {
+ output.color.dispose();
+ }
+ outputs.clear();
+ },
+ };
+}
diff --git a/src/lib/image-frame/transform.wgsl b/src/lib/image-frame/transform.wgsl
new file mode 100644
index 0000000..3a90c4c
--- /dev/null
+++ b/src/lib/image-frame/transform.wgsl
@@ -0,0 +1,8 @@
+export struct Transform {
+ origin: vec2f,
+ xAxis: vec2f,
+ yAxis: vec2f,
+}
+export fn sourcePoint(transform: Transform, uv: vec2f) -> vec2f {
+ return transform.origin + uv.x * transform.xAxis + uv.y * transform.yAxis;
+}
diff --git a/src/features/tone-curves/curve.ts b/src/lib/tone-curves/curve.ts
similarity index 100%
rename from src/features/tone-curves/curve.ts
rename to src/lib/tone-curves/curve.ts
diff --git a/src/features/tone-curves/curves.wgsl b/src/lib/tone-curves/curves.wgsl
similarity index 100%
rename from src/features/tone-curves/curves.wgsl
rename to src/lib/tone-curves/curves.wgsl
diff --git a/src/features/tone-curves/pass.ts b/src/lib/tone-curves/index.ts
similarity index 100%
rename from src/features/tone-curves/pass.ts
rename to src/lib/tone-curves/index.ts
diff --git a/tests/crop.test.ts b/tests/crop.test.ts
new file mode 100644
index 0000000..b2f6785
--- /dev/null
+++ b/tests/crop.test.ts
@@ -0,0 +1,109 @@
+import { expect, test } from "bun:test";
+import {
+ fitRatio,
+ flip,
+ move,
+ resize,
+ rotate,
+ turn,
+} from "@/features/crop/geometry";
+import {
+ frameTransform,
+ type ImageFrame,
+ imageFrame,
+ type Point,
+ validateFrame,
+} from "@/lib/image-frame/geometry";
+
+const source: Point = [1200, 800];
+function sample(frame: ImageFrame, x: number, y: number) {
+ const { origin, xAxis, yAxis } = frameTransform(frame, source);
+ return origin.map((value, axis) => value + x * xAxis[axis] + y * yAxis[axis]);
+}
+function expectCovered(frame: ImageFrame) {
+ for (const x of [0, 1]) {
+ for (const y of [0, 1]) {
+ for (const value of sample(frame, x, y)) {
+ expect(value).toBeGreaterThanOrEqual(-1e-9);
+ expect(value).toBeLessThanOrEqual(1 + 1e-9);
+ }
+ }
+ }
+}
+
+test("crop preserves source coverage, opposite anchors, flips, and sliding along edges", () => {
+ const edge: ImageFrame = {
+ ...imageFrame(source),
+ center: [900, 400],
+ size: [600, 400],
+ };
+ expect(move(edge, 120, 80, source).center).toEqual([900, 480]);
+ const minimum = resize(imageFrame(source), "se", -1200, -800, null, source);
+ for (const ratio of [16 / 9, 9 / 16, 4 / 3, 3 / 4, 1]) {
+ const next = fitRatio(minimum, ratio);
+ expect(() => validateFrame(next)).not.toThrow();
+ expect(next.size[0] / next.size[1]).toBeCloseTo(ratio, 10);
+ expect(next.center).toEqual(minimum.center);
+ expectCovered(next);
+ }
+ for (const rotation of [0, 90, 180, 270]) {
+ for (const angle of [-45, -30, 0, 30, 45]) {
+ const before = rotate(
+ { ...edge, center: [480, 360], rotation },
+ angle,
+ source,
+ );
+ for (const axis of [0, 1]) {
+ const flipped = flip(before, axis);
+ expectCovered(flipped);
+ for (const x of [0, 0.3, 1]) {
+ for (const y of [0, 0.7, 1]) {
+ const expected = sample(
+ before,
+ axis === 0 ? 1 - x : x,
+ axis === 1 ? 1 - y : y,
+ );
+ for (const [i, value] of sample(flipped, x, y).entries()) {
+ expect(value).toBeCloseTo(expected[i], 10);
+ }
+ }
+ }
+ for (const direction of [-1, 1]) {
+ const turned = turn(flipped, direction);
+ expectCovered(turned);
+ expect(turn(turned, -direction)).toEqual(flipped);
+ }
+ for (const [handle, x, y] of [
+ ["nw", 1, 1],
+ ["ne", 0, 1],
+ ["sw", 1, 0],
+ ["se", 0, 0],
+ ["n", 0.5, 1],
+ ["s", 0.5, 0],
+ ["w", 1, 0.5],
+ ["e", 0, 0.5],
+ ] as const) {
+ for (const delta of [-1200, 1200]) {
+ for (const ratio of [before.size[0] / before.size[1], null]) {
+ const next = resize(flipped, handle, delta, delta, ratio, source);
+ expectCovered(next);
+ if (ratio)
+ expect(next.size[0] / next.size[1]).toBeCloseTo(ratio, 8);
+ if (!ratio && x === 0.5)
+ expect(next.size[0]).toBe(flipped.size[0]);
+ if (!ratio && y === 0.5)
+ expect(next.size[1]).toBe(flipped.size[1]);
+ const anchor = sample(flipped, x, y);
+ for (const [i, value] of sample(next, x, y).entries()) {
+ expect(value).toBeCloseTo(anchor[i], 8);
+ }
+ expect(next.scale).toBe(flipped.scale);
+ expectCovered(move(next, delta, delta, source));
+ expectCovered(rotate(next, -angle, source));
+ }
+ }
+ }
+ }
+ }
+ }
+});
diff --git a/tests/curves.test.ts b/tests/curves.test.ts
index e924842..bbdd5a9 100644
--- a/tests/curves.test.ts
+++ b/tests/curves.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from "bun:test";
-import { sampleCurve } from "@/features/tone-curves/curve";
import { interpolatePchip } from "@/lib/math";
+import { sampleCurve } from "@/lib/tone-curves/curve";
test("curves interpolate smoothly through their handles without overshoot", () => {
const identity = [
diff --git a/tests/documents.test.ts b/tests/documents.test.ts
index 9daf648..44ff4ae 100644
--- a/tests/documents.test.ts
+++ b/tests/documents.test.ts
@@ -1,15 +1,16 @@
import { expect, test } from "bun:test";
import { init, target } from "vgpu/mock";
-import { createDocument } from "@/app/document";
-import { setAdjustments, setToneCurve } from "@/app/document/edits";
-import { createResources } from "@/app/document/resources";
-import { defaultAdjustments } from "@/app/scene";
import { createWorkspace } from "@/app/workspace";
-import { defaultCurve } from "@/features/tone-curves/curve";
+import { createDocument } from "@/lib/editor/document";
+import { setAdjustments, setToneCurve } from "@/lib/editor/document/edits";
+import { createResources } from "@/lib/editor/document/resources";
+import { defaultAdjustments } from "@/lib/editor/scene";
+import { imageFrame } from "@/lib/image-frame/geometry";
+import { defaultCurve } from "@/lib/tone-curves/curve";
function document() {
return createDocument({
- size: [32, 32],
+ frame: imageFrame([32, 32]),
source: "image-1",
adjustments: { ...defaultAdjustments },
toneCurve: defaultCurve,
@@ -132,6 +133,18 @@ test("documents edit independently without React, retain bounded history, and re
}
expect(() => resources.get(source)).toThrow("unavailable");
expect(resources.get(replacement)).toBeDefined();
+ const frame = doc.scene.getState().frame;
+ for (const invalid of [
+ { ...frame, size: [0, 1] as const },
+ { ...frame, scale: [0, 1] as const },
+ { ...frame, angle: Number.NaN },
+ ]) {
+ expect(() => doc.edit({ ...doc.scene.getState(), frame: invalid })).toThrow(
+ "Invalid image frame",
+ );
+ }
+ expect(doc.scene.getState().frame).toBe(frame);
+
doc.dispose();
expect(() => resources.get(replacement)).toThrow("unavailable");
gpu.dispose();
diff --git a/tests/editing.e2e.ts b/tests/editing.e2e.ts
index d719aea..c9e40ed 100644
--- a/tests/editing.e2e.ts
+++ b/tests/editing.e2e.ts
@@ -1,11 +1,48 @@
import { readFile } from "node:fs/promises";
+import type { Locator, Page } from "@playwright/test";
+import { type ImageFrame, imageFrame } from "@/lib/image-frame/geometry";
import { interpolatePchip } from "@/lib/math";
import { expect, test } from "./fixtures";
-import { readImage, readPreview } from "./images";
+import { readImage, readPixel, readPreview } from "./images";
+
+async function box(locator: Locator) {
+ const bounds = await locator.boundingBox();
+ if (!bounds) throw new Error(`Missing bounds for ${locator}`);
+ return bounds;
+}
+
+function expectCentered(
+ actual: { x: number; y: number; width: number; height: number },
+ expected: typeof actual,
+) {
+ expect(actual.x + actual.width / 2).toBeCloseTo(
+ expected.x + expected.width / 2,
+ 0,
+ );
+ expect(actual.y + actual.height / 2).toBeCloseTo(
+ expected.y + expected.height / 2,
+ 0,
+ );
+}
+
+async function drag(page: Page, from: number[], to: number[], steps = 8) {
+ await page.mouse.move(from[0], from[1]);
+ await page.mouse.down();
+ await page.mouse.move(to[0], to[1], { steps });
+ await page.mouse.up();
+}
+
+async function zoom(page: Page, factor: number) {
+ await page.keyboard.down("Control");
+ await page.mouse.wheel(0, -Math.log(factor) * 100);
+ await page.keyboard.up("Control");
+}
test("edit a photo, inspect the preview and histograms, undo changes, and export", async ({
page,
+ browser,
}) => {
+ const state = () => page.evaluate(() => window.openlight.getState());
await page.goto("/");
await expect(page.getByRole("button", { name: "Open image" })).toBeVisible();
await page
@@ -22,9 +59,66 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
await expect(output).toHaveAttribute("points", /,\d{1,2}\./);
const original = await canvas.screenshot();
const histogram = await output.getAttribute("points");
- const initial = await page.evaluate(() => window.openlight.getState());
+ const initial = await state();
expect((await readImage(page)).center).toEqual([128, 128, 128, 255]);
+ await test.step("zoomed rendering reaches the edges of the editor viewport", async () => {
+ const viewport = await page
+ .getByRole("region", { name: "Image canvas" })
+ .boundingBox();
+ if (!viewport) throw new Error("Missing editor viewport.");
+ expect(await canvas.boundingBox()).toEqual(viewport);
+ await canvas.hover();
+ await zoom(page, 2);
+ const edge = {
+ x: viewport.x + viewport.width / 2,
+ y: viewport.y + 4,
+ width: 1,
+ height: 1,
+ };
+ await expect
+ .poll(async () => await readPixel(page, edge))
+ .toEqual([128, 128, 128, 255]);
+ await canvas.dblclick();
+ await expect.poll(() => canvas.screenshot()).toEqual(original);
+ });
+
+ await test.step("Space panning continues smoothly after releasing the key mid-drag", async () => {
+ const viewport = await canvas.boundingBox();
+ if (!viewport) throw new Error("Missing canvas.");
+ const scale = Math.min(
+ (viewport.width - 48) / 1200,
+ (viewport.height - 48) / 800,
+ 2,
+ );
+ const sample = {
+ x: viewport.x + viewport.width / 2 + (430 - 600) * scale,
+ y: viewport.y + viewport.height / 2 + (150 - 400) * scale,
+ width: 1,
+ height: 1,
+ };
+ expect(await readPixel(page, sample)).toEqual([48, 80, 128, 255]);
+ await canvas.hover();
+ await page.keyboard.down("Space");
+ await page.mouse.down();
+ await page.mouse.move(
+ viewport.x + viewport.width / 2 + 100,
+ viewport.y + viewport.height / 2,
+ );
+ await page.keyboard.up("Space");
+ await page.mouse.move(
+ viewport.x + viewport.width / 2 + 101,
+ viewport.y + viewport.height / 2,
+ );
+ await page.mouse.up();
+ await expect
+ .poll(async () => await readPixel(page, { ...sample, x: sample.x + 101 }))
+ .toEqual([48, 80, 128, 255]);
+ expect(await state()).toEqual(initial);
+ await canvas.dblclick();
+ await expect.poll(() => canvas.screenshot()).toEqual(original);
+ });
+
await test.step("exposure moves the preview and RGB histogram, then resets", async () => {
const exposure = page.getByRole("slider", {
name: "Exposure",
@@ -34,29 +128,18 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
await page.keyboard.down("ArrowRight");
await page.keyboard.press("ArrowRight");
await page.keyboard.up("ArrowRight");
- expect(
- (await page.evaluate(() => window.openlight.getState())).history
- .undoCount,
- ).toBe(1);
+ expect((await state()).history.undoCount).toBe(1);
await page.getByRole("button", { name: "Undo", exact: true }).click();
await expect(exposure).toHaveValue("0");
const bounds = await exposure.boundingBox();
if (!bounds) throw new Error("Exposure slider is missing.");
- await page.mouse.move(
- bounds.x + bounds.width / 2,
- bounds.y + bounds.height / 2,
- );
- await page.mouse.down();
- await page.mouse.move(
- bounds.x + bounds.width * 0.6,
- bounds.y + bounds.height / 2,
- { steps: 8 },
+ await drag(
+ page,
+ [bounds.x + bounds.width / 2, bounds.y + bounds.height / 2],
+ [bounds.x + bounds.width * 0.6, bounds.y + bounds.height / 2],
+ 8,
);
- await page.mouse.up();
- expect(
- (await page.evaluate(() => window.openlight.getState())).history
- .undoCount,
- ).toBe(1);
+ expect((await state()).history.undoCount).toBe(1);
await expect.poll(() => canvas.screenshot()).not.toEqual(original);
await expect(output).not.toHaveAttribute("points", histogram ?? "");
expect((await readImage(page)).center[0]).toBeGreaterThan(160);
@@ -88,8 +171,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
name: "Show clipped highlights",
});
const edited = await readImage(page);
- const history = (await page.evaluate(() => window.openlight.getState()))
- .history;
+ const history = (await state()).history;
const bins = await output.getAttribute("points");
await before.focus();
await page.keyboard.down("Backslash");
@@ -161,9 +243,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
.poll(async () => (await readPreview(page)).center)
.toEqual([128, 128, 128, 255]);
expect(await readImage(page)).toEqual(edited);
- expect(
- (await page.evaluate(() => window.openlight.getState())).history,
- ).toEqual(history);
+ expect((await state()).history).toEqual(history);
await expect(output).toHaveAttribute("points", bins ?? "");
await page.evaluate(() =>
window.openlight.setPreview({
@@ -232,22 +312,14 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
);
const bounds = await graph.boundingBox();
if (!bounds) throw new Error("Curve graph is missing.");
- await page.mouse.move(
- bounds.x + bounds.width / 2,
- bounds.y + bounds.height / 2,
- );
- await page.mouse.down();
- await page.mouse.move(
- bounds.x + bounds.width / 2,
- bounds.y + bounds.height / 4,
- { steps: 8 },
+ await drag(
+ page,
+ [bounds.x + bounds.width / 2, bounds.y + bounds.height / 2],
+ [bounds.x + bounds.width / 2, bounds.y + bounds.height / 4],
+ 8,
);
- await page.mouse.up();
await expect(graph.locator("circle")).toHaveCount(3);
- expect(
- (await page.evaluate(() => window.openlight.getState())).history
- .undoCount,
- ).toBe(before + 1);
+ expect((await state()).history.undoCount).toBe(before + 1);
await expect(input).toHaveAttribute("points", inputBefore ?? "");
const curved = await readImage(page);
const curve = await page.evaluate(
@@ -274,17 +346,12 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
{ from: [0, 1], to: [0, 0.75], sample: "corner", expected: 64 },
{ from: [1, 0], to: [0.1, 0], sample: "center", expected: 255 },
] as const) {
- await page.mouse.move(
- bounds.x + from[0] * bounds.width,
- bounds.y + from[1] * bounds.height,
- );
- await page.mouse.down();
- await page.mouse.move(
- bounds.x + to[0] * bounds.width,
- bounds.y + to[1] * bounds.height,
- { steps: 5 },
+ await drag(
+ page,
+ [bounds.x + from[0] * bounds.width, bounds.y + from[1] * bounds.height],
+ [bounds.x + to[0] * bounds.width, bounds.y + to[1] * bounds.height],
+ 5,
);
- await page.mouse.up();
expect(
Math.abs((await readImage(page))[sample][0] - expected),
).toBeLessThan(2);
@@ -297,6 +364,440 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
}
});
+ const open = page.getByRole("button", { name: "Crop and rotate" });
+ 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" });
+ const move = page.getByRole("button", { name: "Move crop" });
+ const reset = panel.getByRole("button", { name: "Reset", exact: true });
+ const aspect = panel.getByRole("combobox", { name: "Aspect ratio" });
+ const rotation = panel.getByRole("slider", { name: "Rotation", exact: true });
+ async function setFrame(change: Partial<ImageFrame> = {}) {
+ const frame = { ...imageFrame([1200, 800]), ...change };
+ await page.evaluate(
+ (frame) => window.openlight.editScene({ frame }),
+ frame,
+ );
+ }
+
+ async function expectImage(size: number[], corner: number) {
+ expect(await readImage(page)).toEqual({
+ size,
+ center: [128, 128, 128, 255],
+ corner: [corner, corner, corner, 255],
+ });
+ }
+
+ await test.step("Enter activates focused crop panel buttons", async () => {
+ const before = await state();
+ await open.click();
+ await aspect.selectOption({ label: "Square" });
+ await panel
+ .getByRole("button", { name: "Cancel", exact: true })
+ .press("Enter");
+ await expect(panel).toBeHidden();
+ expect((await state()).frame).toEqual(before.frame);
+ expect((await state()).history).toEqual(before.history);
+ await open.click();
+ await panel
+ .getByRole("button", { name: "Rotate clockwise" })
+ .press("Enter");
+ await expect(panel).toBeVisible();
+ expect((await state()).frame).toEqual(before.frame);
+ await reset.press("Enter");
+ await panel.getByRole("button", { name: "Apply crop" }).press("Enter");
+ await expect(panel).toBeHidden();
+ expect((await state()).frame).toEqual(before.frame);
+ expect((await state()).history).toEqual(before.history);
+ });
+
+ await test.step("locked crop corners resize continuously when the drag changes direction", async () => {
+ await setFrame({ size: [600, 400] });
+ await open.click();
+ const grip = await box(corner);
+ const x = grip.x + grip.width / 2;
+ const y = grip.y + grip.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x - 30, y + 19, { steps: 6 });
+ const before = await box(selection);
+ await page.mouse.move(x - 30, y + 21);
+ const after = await box(selection);
+ expect(Math.abs(after.width - before.width)).toBeLessThan(6);
+ expectCentered(after, before);
+ await page.keyboard.press("Escape");
+ await page.mouse.up();
+ await page.keyboard.press("c");
+ const reopened = await box(selection);
+ await page.mouse.move(x - 40, y - 40);
+ expect(await box(selection)).toEqual(reopened);
+ await page.keyboard.press("Escape");
+ await setFrame();
+ });
+
+ await test.step("44px edge targets resize along one axis and preserve locked ratios", async () => {
+ for (const locked of [false, true]) {
+ for (const [label, sx, sy] of [
+ ["top", 0, -1],
+ ["right", 1, 0],
+ ["bottom", 0, 1],
+ ["left", -1, 0],
+ ] as const) {
+ await setFrame({ size: [300, 200] });
+ await open.click();
+ if (!locked) await aspect.selectOption({ label: "Free" });
+ const bounds = await box(selection);
+ const edge = page.getByRole("button", {
+ name: `Resize crop ${label}`,
+ exact: true,
+ });
+ const target = await box(edge);
+ expect(sx ? target.width : target.height).toBe(44);
+ const grip = await box(corner);
+ expect([grip.width, grip.height]).toEqual([44, 44]);
+ const x =
+ bounds.x + bounds.width * (sx ? (sx + 1) / 2 : 0.35) + sx * 20;
+ const y =
+ bounds.y + bounds.height * (sy ? (sy + 1) / 2 : 0.35) + sy * 20;
+ await drag(
+ page,
+ [x, y],
+ [x - sx * 30 + Math.abs(sy) * 15, y - sy * 30 + Math.abs(sx) * 15],
+ );
+ const resized = await box(selection);
+ const widthChange = sx ? 60 : Number(locked) * 90;
+ const heightChange = sy ? 60 : Number(locked) * 40;
+ expect(resized.width).toBeCloseTo(bounds.width - widthChange, 0);
+ expect(resized.height).toBeCloseTo(bounds.height - heightChange, 0);
+ expectCentered(resized, bounds);
+ await panel.getByRole("button", { name: "Apply crop" }).click();
+ const frame = (await state()).frame;
+ if (!frame) throw new Error("Missing cropped frame");
+ const exported = await readImage(page);
+ expect(exported.size).toEqual(frame.size.map(Math.round));
+ expect(exported.center).toEqual([128, 128, 128, 255]);
+ }
+ }
+ await setFrame();
+ });
+
+ await test.step("crop drafts cancel, apply once, rotate and straighten without losing the source", async () => {
+ const before = await state();
+ await expect(output).toHaveAttribute("points", histogram ?? "");
+ await open.click();
+ await expect(aspect).toHaveValue("1.5");
+ await aspect.selectOption({ label: "Square" });
+ const bounds = await box(selection);
+ await drag(
+ page,
+ [bounds.x + bounds.width, bounds.y + bounds.height],
+ [bounds.x + bounds.width * 0.8, bounds.y + bounds.height * 0.8],
+ );
+ const beforeZoom = await box(selection);
+ expect(beforeZoom.width).toBeLessThan(bounds.width);
+ expect(beforeZoom.width).toBeCloseTo(beforeZoom.height, 4);
+ expectCentered(beforeZoom, bounds);
+ await corner.hover();
+ await zoom(page, Math.exp(0.4));
+ await expect
+ .poll(async () => (await box(selection)).width)
+ .toBeGreaterThan(beforeZoom.width * 1.4);
+ const zoomed = await box(selection);
+ const grip = await box(corner);
+ await drag(
+ page,
+ [grip.x + grip.width / 2, grip.y + grip.height / 2],
+ [grip.x + grip.width / 2 - 20, grip.y + grip.height / 2 - 20],
+ 4,
+ );
+ const resized = await box(selection);
+ expect(resized.width).toBeCloseTo(zoomed.width - 40, 0);
+ const beforePan = await box(selection);
+ expectCentered(beforePan, zoomed);
+ await page.mouse.wheel(30, 20);
+ await expect
+ .poll(async () => (await box(selection)).x)
+ .not.toBe(beforePan.x);
+ expect((await box(selection)).width).toBe(resized.width);
+ await move.press("Shift+ArrowRight");
+ for (const gap of [20, 24]) {
+ const frame = await box(selection);
+ const x = frame.x + frame.width + gap;
+ const y = frame.y + frame.height / 2;
+ await page.mouse.move(x, y);
+ expect(
+ await page.evaluate(
+ ({ x, y }) => {
+ const element = document.elementFromPoint(x, y);
+ return element && getComputedStyle(element).cursor;
+ },
+ { x, y },
+ ),
+ ).toContain(gap < 22 ? "ew-resize" : "url(");
+ await page.mouse.down();
+ await page.mouse.move(
+ x,
+ y + (frame.width / 2 + gap) * Math.tan(Math.PI / 6),
+ { steps: 8 },
+ );
+ await page.mouse.up();
+ const angle = await rotation.inputValue();
+ expect(Number(angle)).toBeCloseTo(gap < 22 ? 0 : 30, 0);
+ expect(await box(selection)).toEqual(frame);
+ await page.mouse.move(x + 20, y);
+ await expect(rotation).toHaveValue(angle);
+ }
+ expect((await readImage(page)).size).toEqual([1200, 800]);
+ await page.keyboard.press("Escape");
+ expect((await state()).frame).toEqual(before.frame);
+ expect((await state()).history).toEqual(before.history);
+ await open.focus();
+ await page.keyboard.press("c");
+ await aspect.selectOption({ label: "Square" });
+ await corner.press("Enter");
+ await expect(panel).toBeHidden();
+ await expectImage([800, 800], 128);
+ await expect(output).not.toHaveAttribute("points", histogram ?? "");
+ expect((await state()).history.undoCount).toBe(
+ before.history.undoCount + 1,
+ );
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ expect((await readImage(page)).size).toEqual([1200, 800]);
+ await page.getByRole("button", { name: "Redo", exact: true }).click();
+ expect((await readImage(page)).size).toEqual([800, 800]);
+ await open.click();
+ await reset.click();
+ await panel
+ .getByRole("button", { name: "Rotate counterclockwise" })
+ .click();
+ await corner.press("Enter");
+ await expectImage([800, 1200], 224);
+ await open.click();
+ await panel.getByRole("button", { name: "Rotate clockwise" }).click();
+ await panel.getByRole("button", { name: "Rotate clockwise" }).click();
+ await panel.getByRole("button", { name: "Apply crop" }).click();
+ await expectImage([800, 1200], 32);
+ await open.click();
+ await reset.click();
+ const angle = panel.getByRole("textbox", {
+ name: "Rotation",
+ exact: true,
+ });
+ await angle.fill("30");
+ await angle.press("Enter");
+ await expect(panel).toBeHidden();
+ await expectImage([1200, 800], 32);
+ await open.click();
+ await reset.click();
+ await panel.getByRole("button", { name: "Apply crop" }).click();
+ await expect.poll(() => canvas.screenshot()).toEqual(original);
+ });
+
+ await test.step("flip controls mirror pixels, preserve framing, and support undo", async () => {
+ for (const [axis, value] of [
+ ["horizontal", 224],
+ ["vertical", 224],
+ ["horizontal", 32],
+ ["vertical", 0],
+ ] as const) {
+ const pixel = [value, value, value, 255];
+ await open.click();
+ const bounds = await box(selection);
+ await page.getByRole("button", { name: `Flip ${axis}` }).click();
+ expect(await box(selection)).toEqual(bounds);
+ const corner = {
+ x: bounds.x + 10,
+ y: bounds.y + 10,
+ };
+ await expect
+ .poll(async () => await readPixel(page, corner))
+ .toEqual(pixel);
+ await page.getByRole("button", { name: "Apply crop" }).click();
+ expect((await readImage(page)).corner).toEqual(pixel);
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ await page.getByRole("button", { name: "Redo", exact: true }).click();
+ expect((await readImage(page)).corner).toEqual(pixel);
+ }
+ });
+
+ await test.step("cropping preserves framing, moves the image, and rotates around the crop center", async () => {
+ const sidebar = page.getByRole("complementary");
+ const sidebarBefore = await box(sidebar);
+ await drag(
+ page,
+ [sidebarBefore.x - 2, sidebarBefore.y + 40],
+ [sidebarBefore.x - 82, sidebarBefore.y + 40],
+ );
+ const resizedSidebar = await box(sidebar);
+ expect(resizedSidebar.width).toBe(sidebarBefore.width + 80);
+ await setFrame({ center: [360, 200], size: [240, 240] });
+ const viewport = await box(canvas);
+ await open.click();
+ expect(await box(sidebar)).toEqual(resizedSidebar);
+ const bounds = await box(selection);
+ // A 240px crop starts at 200%, centered exactly where it was before opening the tool.
+ expect(bounds.width).toBeCloseTo(480, 0);
+ expect(bounds.height).toBeCloseTo(480, 0);
+ expect(bounds.x).toBeCloseTo(viewport.x + (viewport.width - 480) / 2, 0);
+ expect(bounds.y).toBeCloseTo(viewport.y + (viewport.height - 480) / 2, 0);
+ const sample = {
+ x: bounds.x + 40,
+ y: bounds.y + bounds.height / 2,
+ };
+ expect(await readPixel(page, sample)).toEqual([48, 80, 128, 255]);
+ const x = bounds.x + bounds.width / 2;
+ const y = bounds.y + bounds.height / 2;
+ const beforePan = await state();
+ for (const [startX, startY] of [
+ [x, y],
+ [bounds.x, bounds.y],
+ [bounds.x + bounds.width, y],
+ [bounds.x + bounds.width + 12, y],
+ [bounds.x + bounds.width + 60, y],
+ ]) {
+ await page.mouse.move(startX, startY);
+ await page.keyboard.down("Space");
+ await expect(
+ page.getByRole("button", { name: "Resize crop top left" }),
+ ).toHaveCSS("cursor", "grab");
+ await page.mouse.down();
+ await page.mouse.move(startX + 40, startY + 20, { steps: 4 });
+ await page.mouse.up();
+ await page.keyboard.up("Space");
+ expect(await box(selection)).toEqual({
+ ...bounds,
+ x: bounds.x + 40,
+ y: bounds.y + 20,
+ });
+ expect(await state()).toEqual(beforePan);
+ expect(
+ await readPixel(page, {
+ ...sample,
+ x: sample.x + 40,
+ y: sample.y + 20,
+ }),
+ ).toEqual([48, 80, 128, 255]);
+ await page.keyboard.down("Space");
+ await page.mouse.down();
+ await page.mouse.move(startX, startY, { steps: 4 });
+ await page.mouse.up();
+ await page.keyboard.up("Space");
+ }
+ await page.mouse.move(x, y);
+ await expect(move).toHaveCSS("cursor", "grab");
+ await page.mouse.down();
+ await expect(move).toHaveCSS("cursor", "grabbing");
+ await page.mouse.move(x + 80, y + 30, { steps: 8 });
+ await page.mouse.up();
+ expect(await box(selection)).toEqual(bounds);
+ expect(await readPixel(page, sample)).toEqual([128, 128, 128, 255]);
+ await drag(
+ page,
+ [bounds.x + bounds.width + 60, y],
+ [
+ bounds.x + bounds.width + 60,
+ y + (bounds.width / 2 + 60) * Math.tan(Math.PI / 6),
+ ],
+ 8,
+ );
+ expect(await box(selection)).toEqual(bounds);
+ expect(Number(await rotation.inputValue())).toBeCloseTo(30, 0);
+ const center = { x, y };
+ expect(await readPixel(page, center)).toEqual([48, 80, 128, 255]);
+ await page.keyboard.press("Enter");
+ expect(await box(sidebar)).toEqual(resizedSidebar);
+ expect((await readImage(page)).center).toEqual([48, 80, 128, 255]);
+ await canvas.hover();
+ await zoom(page, 2.5);
+ await page.mouse.wheel(30, 20);
+ const before = await readPixel(page, center);
+ await open.click();
+ const zoomed = await box(selection);
+ expect(zoomed.width).toBeCloseTo(1200, 0);
+ expect(zoomed.x).toBeCloseTo(
+ viewport.x + (viewport.width - 1200) / 2 - 30,
+ 0,
+ );
+ expect(zoomed.y).toBeCloseTo(
+ viewport.y + (viewport.height - 1200) / 2 - 20,
+ 0,
+ );
+ expect(await readPixel(page, center)).toEqual(before);
+ await drag(page, [x, y], [x + 80, y + 30], 8);
+ await page.keyboard.press("Enter");
+ await open.click();
+ expect(await box(selection)).toEqual(bounds);
+ await page.keyboard.press("Escape");
+ expect(await box(sidebar)).toEqual(resizedSidebar);
+ await drag(
+ page,
+ [resizedSidebar.x - 2, resizedSidebar.y + 40],
+ [sidebarBefore.x - 2, sidebarBefore.y + 40],
+ );
+ await setFrame();
+ });
+
+ await test.step("straightened crops leave empty space outside the source and reset restores geometry and camera", async () => {
+ await setFrame({ size: [600, 400], angle: 30 });
+ await open.click();
+ await move.hover();
+ await zoom(page, 0.5);
+ const bounds = await box(selection);
+ const outside = {
+ x: bounds.x - bounds.width * 0.46,
+ y: bounds.y - bounds.height * 0.46,
+ };
+ const pixel = async () => await readPixel(page, outside);
+ await expect.poll(pixel).toEqual([9, 9, 9, 255]);
+ await zoom(page, 0.5);
+ const smaller = await box(selection);
+ // Known light patch rotated beyond the original source rectangle.
+ const revealed = {
+ x: smaller.x + smaller.width * 1.535,
+ y: smaller.y + smaller.height * 0.542,
+ };
+ await expect
+ .poll(async () => await readPixel(page, revealed))
+ .toEqual([90, 90, 90, 255]);
+ await reset.click();
+ await expect.poll(pixel).toEqual([0, 0, 0, 255]);
+ const fitted = await box(selection);
+ const viewport = await box(canvas);
+ const fit = Math.min(
+ (viewport.width - 48) / 1200,
+ (viewport.height - 48) / 800,
+ 2,
+ );
+ expect(fitted.width).toBeCloseTo(1200 * fit, 0);
+ expect(fitted.height).toBeCloseTo(800 * fit, 0);
+ expectCentered(fitted, viewport);
+ await page.getByRole("button", { name: "Rotate clockwise" }).click();
+ await move.hover();
+ await zoom(page, Math.exp(0.8));
+ await page.mouse.wheel(60, 40);
+ await reset.click();
+ expect(await box(selection)).toEqual(fitted);
+ await expect(
+ page.getByRole("slider", { name: "Rotation", exact: true }),
+ ).toHaveValue("0");
+ await expect(aspect).toHaveValue("1.5");
+ await aspect.selectOption({ label: "Square" });
+ const fixed = await box(selection);
+ for (const direction of [
+ "ArrowLeft",
+ "ArrowRight",
+ "ArrowUp",
+ "ArrowDown",
+ ]) {
+ for (let i = 0; i < 20; i++) await move.press(`Shift+${direction}`);
+ const actual = await box(selection);
+ expect(actual.x).toBeCloseTo(fixed.x, 0);
+ expect(actual.y).toBeCloseTo(fixed.y, 0);
+ }
+ await page.keyboard.press("Escape");
+ await setFrame();
+ });
+
await test.step("export retains edits and original dimensions independently of viewport zoom", async () => {
await page.evaluate(() => {
window.openlight.beginEdit();
@@ -319,9 +820,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
expect(expected.center[0]).toBeLessThan(255);
expect(expected.corner).toEqual([0, 0, 0, 255]);
await canvas.hover();
- await page.keyboard.down("Control");
- await page.mouse.wheel(0, -100);
- await page.keyboard.up("Control");
+ 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[] = [];
@@ -360,4 +859,53 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
});
+
+ await test.step("mobile slider targets accept taps above and below the visible track", async () => {
+ const context = await browser.newContext({
+ viewport: { width: 390, height: 844 },
+ isMobile: true,
+ hasTouch: true,
+ deviceScaleFactor: 2,
+ });
+ try {
+ const mobile = await context.newPage();
+ await mobile.goto(page.url());
+ await mobile
+ .locator('input[type="file"]')
+ .setInputFiles("tests/fixtures/photo.svg");
+ const exposure = mobile.getByRole("slider", {
+ name: "Exposure",
+ exact: true,
+ });
+ await exposure.scrollIntoViewIfNeeded();
+ for (const slider of await mobile.getByRole("slider").all()) {
+ const bounds = await box(slider);
+ expect(bounds.width).toBeGreaterThanOrEqual(44);
+ expect(bounds.height).toBeGreaterThanOrEqual(44);
+ const track = await box(slider.locator(".."));
+ expect(track.height).toBe(4);
+ expectCentered(bounds, track);
+ }
+ const bounds = await box(exposure);
+ await mobile.touchscreen.tap(bounds.x + bounds.width - 2, bounds.y + 16);
+ await expect(exposure).toHaveValue("5");
+ expect((await readImage(mobile)).center).toEqual([255, 255, 255, 255]);
+ await mobile.touchscreen.tap(bounds.x + 2, bounds.y + bounds.height - 3);
+ await expect(exposure).toHaveValue("-5");
+ const undo = mobile.getByRole("button", { name: "Undo", exact: true });
+ await undo.tap();
+ await expect(exposure).toHaveValue("5");
+ await undo.tap();
+ await expect(exposure).toHaveValue("0");
+ expect((await readImage(mobile)).center).toEqual([128, 128, 128, 255]);
+ const field = mobile.getByRole("textbox", {
+ name: "Exposure",
+ exact: true,
+ });
+ await field.tap();
+ await expect(field).toBeFocused();
+ } finally {
+ await context.close();
+ }
+ });
});
diff --git a/tests/images.ts b/tests/images.ts
index d592511..f756c94 100644
--- a/tests/images.ts
+++ b/tests/images.ts
@@ -60,3 +60,10 @@ export async function readPreview(page: Page) {
[...bytes],
);
}
+
+export async function readPixel(page: Page, point: { x: number; y: number }) {
+ const bytes = await page.screenshot({
+ clip: { ...point, width: 1, height: 1 },
+ });
+ return (await readImage(page, bytes)).center;
+}
diff --git a/tests/loaders.e2e.ts b/tests/loaders.e2e.ts
index 002296a..079b1d6 100644
--- a/tests/loaders.e2e.ts
+++ b/tests/loaders.e2e.ts
@@ -38,10 +38,23 @@ test("decode an image, apply XMP, recover from failure, and replace a document d
const expected = await readImage(page);
expect(expected.center[0]).toBeLessThan(baseline.center[0]);
const before = await page.evaluate(() => window.openlight.getState());
+ await page.evaluate(() => {
+ const frame = window.openlight.getState().frame;
+ if (!frame) throw new Error("Missing loaded frame");
+ frame.angle = 30;
+ Reflect.set(frame.center, 0, 0);
+ });
+ expect(
+ (await page.evaluate(() => window.openlight.getState())).frame,
+ ).toEqual(before.frame);
await page.evaluate(() => window.openlight.undo());
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("combobox", { name: "Aspect ratio" })
+ .selectOption({ label: "Square" });
const exported = await page.evaluate(async () => {
const api = window.openlight;
const convert = OffscreenCanvas.prototype.convertToBlob;
@@ -71,6 +84,8 @@ test("decode an image, apply XMP, recover from failure, and replace a document d
});
expect(await readImage(page, new Uint8Array(exported))).toEqual(expected);
const replaced = await page.evaluate(() => window.openlight.getState());
+ await expect(page.getByRole("region", { name: "Crop tool" })).toBeHidden();
+ expect(replaced.frame?.size).toEqual([32, 32]);
expect(replaced.documentId).not.toBe(before.documentId);
expect(replaced.history).toEqual({ undoCount: 0, redoCount: 0 });
expect(replaced.adjustments.exposure).toBe(0);
diff --git a/tests/loaders.test.ts b/tests/loaders.test.ts
index a68da67..e2a06ee 100644
--- a/tests/loaders.test.ts
+++ b/tests/loaders.test.ts
@@ -1,11 +1,12 @@
import { expect, test } from "bun:test";
-import { createDocument } from "@/app/document";
-import { setAdjustments } from "@/app/document/edits";
import { createCameraRawXmpLoader } from "@/app/loaders/camera-raw-xmp";
import { createLoaderRegistry, type FileLoader } from "@/app/loaders/registry";
-import { defaultAdjustments } from "@/app/scene";
import { createWorkspace } from "@/app/workspace";
-import { defaultCurve } from "@/features/tone-curves/curve";
+import { createDocument } from "@/lib/editor/document";
+import { setAdjustments } from "@/lib/editor/document/edits";
+import { defaultAdjustments } from "@/lib/editor/scene";
+import { imageFrame } from "@/lib/image-frame/geometry";
+import { defaultCurve } from "@/lib/tone-curves/curve";
function settings(attributes: string, name = "photo.xmp") {
return new File(
@@ -26,7 +27,7 @@ test("file batches preserve ordering, group imports, recover from failures, and
workspace.open(file.name, async () => {
if (file.name === "broken.png") throw new Error("Decode failed");
return createDocument({
- size: [32, 32],
+ frame: imageFrame([32, 32]),
source: file.name,
adjustments: { ...defaultAdjustments },
toneCurve: defaultCurve,
diff --git a/tests/renderer.test.ts b/tests/renderer.test.ts
index 8467d71..f499ca6 100644
--- a/tests/renderer.test.ts
+++ b/tests/renderer.test.ts
@@ -5,18 +5,20 @@ import {
init,
target,
} from "vgpu/mock";
-import { createDocument } from "@/app/document";
-import { setAdjustments, setToneCurve } from "@/app/document/edits";
-import { createRenderer } from "@/app/editor/renderer/renderer";
-import { defaultAdjustments } from "@/app/scene";
-import { defaultCurve } from "@/features/tone-curves/curve";
+import { createDocument } from "@/lib/editor/document";
+import { setAdjustments, setToneCurve } from "@/lib/editor/document/edits";
+import { createRenderer } from "@/lib/editor/renderer";
+import { defaultAdjustments } from "@/lib/editor/scene";
+import { createDisplay } from "@/lib/image-display";
+import { imageFrame } from "@/lib/image-frame/geometry";
+import { defaultCurve } from "@/lib/tone-curves/curve";
test("rendering follows grouped edits and undo, reuses pipelines, and releases owned targets", async () => {
const gpu = await init();
const source = target(gpu, { size: [32, 16], format: "rgba16float" });
const canvas = Object.assign(target(gpu, { size: [64, 32] }), { dpr: 2 });
const document = createDocument({
- size: [32, 16],
+ frame: imageFrame([32, 16]),
source: "photo",
adjustments: { ...defaultAdjustments },
toneCurve: defaultCurve,
@@ -25,12 +27,14 @@ test("rendering follows grouped edits and undo, reuses pipelines, and releases o
const notify = mock(() => {});
const detach = renderer.subscribe(notify);
const unsubscribe = document.scene.subscribe(renderer.update);
+ const display = createDisplay(gpu);
const draw = () =>
frame(gpu, (frame) =>
- renderer.draw(frame, canvas, { pan: [4, 8], zoom: 2 }),
+ display(frame, canvas, renderer.outputImage(), {
+ view: { pan: [4, 8], zoom: 2 },
+ }),
);
try {
- draw();
expect(notify).not.toHaveBeenCalled();
renderer.update(document.scene.getState());
const adjusted = renderer.inputImage();
@@ -79,7 +83,21 @@ test("rendering follows grouped edits and undo, reuses pipelines, and releases o
detach();
setAdjustments(document, { exposure: -1 });
expect(notify).toHaveBeenCalledTimes(8);
+ document.edit({
+ ...document.scene.getState(),
+ frame: {
+ ...document.scene.getState().frame,
+ size: [16, 8],
+ angle: 10,
+ },
+ });
+ const croppedInput = renderer.inputImage();
+ const croppedOutput = renderer.outputImage();
+ expect(croppedOutput.size).toEqual([16, 8]);
+ expect(croppedInput.size).toEqual([16, 8]);
renderer.dispose();
+ expect(() => croppedInput.color.view).toThrow("destroyed");
+ expect(() => croppedOutput.color.view).toThrow("destroyed");
expect(() => adjusted.color.view).toThrow("destroyed");
expect(() => curved.color.view).toThrow("destroyed");
expect(() => source.color.view).not.toThrow();