Skip to content

Free open-source image editor for the browser

Separate documents and add history

Rodrigo6ef4c052fd23
diff --git a/AGENTS.md b/AGENTS.md
index ddff61a..ad46f3f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,21 +6,24 @@ Demonstrate a professional photo editor with little, readable code.
`src/main.tsx` owns runtime and provider composition.
+Write committed code, comments, documentation, and UI text in English. Research drafts may use another language while uncommitted.
+Use `CONTEXT.md` for document, scene, and image-source terminology.
+
## Size
Keep each file focused on one responsibility and one abstraction level. Entry points compose; providers, hooks, and domain modules own lifecycles and policy.
-Prefer the smallest complete implementation that preserves clear ownership. Evaluate simplicity across the whole feature, including lifecycle glue and consumers; moving lines into helpers is not a reduction.
-Start with a direct function and thin UI composition. Add a layer only when it hides a real responsibility or removes duplication; keep cohesive work together when splitting it would only add forwarding.
+Start with direct functions and thin UI composition. Add a layer only when it owns a distinct responsibility or removes duplication.
+Evaluate simplicity across the whole feature, including lifecycle code and consumers. Keep cohesive work together; moving lines into forwarding helpers is not a reduction.
Prefer direct vgpu operations. Add wrappers, validation, scheduling, or caching only for a current requirement.
One component per responsibility: when a component holds state or refs that only part of its markup uses, extract that part into its own component. Within a file, define a function above the function that uses it.
## Engine and React
-React owns UI composition, controls, and mounting engine outputs. Scene actions perform decoding and other processing imperatively. The engine owns GPU resources, rendering, and derived data such as histogram bins; frame data stays outside React state and props.
+React owns UI composition, controls, and mounting engine outputs. Commands perform decoding and other processing imperatively, with explicit workspace or document dependencies. The engine owns GPU resources, rendering, and derived data such as histogram bins; frame data stays outside React state and props.
-Providers expose stable engine instances and connect their lifetime to mounting and cleanup. The engine creates and disposes its resources. Canvas and histogram components attach their outputs through the provider.
+Hooks and providers connect stable imperative instances to mounting and cleanup. Each resource owner disposes what it creates. Canvas and histogram components attach engine outputs to the UI.
-The Zustand scene store owns document state. UI interactions and browser commands call the same actions; the renderer reads the scene directly.
+Each document owns a vanilla Zustand scene store, history, and image resources. The scene contains serializable data and refers to image sources by ID; files and GPU targets stay outside history. The workspace owns document replacement and loading state. UI interactions and browser commands use the same imperative edits; history groups them without knowing loaders or tools.
## Structure
@@ -57,11 +60,9 @@ All React bindings come from `vgpu-react`; everything else comes from `vgpu`.
## Testing
-Prefer a few broad end-to-end tests over many granular tests. A typical editing test loads a known image, applies several adjustments through the control API, and compares the final rendered or exported pixels with a reference, using a small tolerance when needed. Favor coverage of the complete processing chain over pinpointing failures by test name. Extend an existing workflow before adding a test; split when workflows are independent or execution becomes too long. Format-specific tests should load a real file of that format. Add narrow tests only when a broad workflow cannot meaningfully exercise the behavior.
-
-Maintain a browser-side control API for agents and browser tests. Expose stable, semantic commands for real workflows such as loading an image, changing an adjustment, and reading application state. Use DOM interaction only when the UI interaction itself is under test. Tests wait for visible results without adding production completion tracking.
+Prefer a few broad end-to-end tests over many granular tests. Keep one main editing session that opens a fixture, changes controls, checks the preview and histogram, edits curves, uses undo/redo, and exports. Extend that session with named steps instead of adding a test per control. Check actual pixels against known values, with a small tolerance when needed; changed state or a changed screenshot alone does not prove correct rendering. Keep independent loading and rendering checks separate, and load real files for format coverage. Use browser-free tests for invariants that the editing session cannot meaningfully exercise.
-Extend the control API whenever a feature adds a workflow that agents need to exercise. It may require an explicit test mode, but it must work in local browsers, CI, and remote browser sessions.
+Maintain a browser-side control API with semantic commands for loading, editing, and reading state. Extend it with new workflows; it must work in local browsers, CI, and remote sessions. Use DOM interaction when testing the UI itself. Wait for visible results without adding production completion tracking.
## Done
diff --git a/CONTEXT.md b/CONTEXT.md
new file mode 100644
index 0000000..1779a5d
--- /dev/null
+++ b/CONTEXT.md
@@ -0,0 +1,22 @@
+# OpenLight
+
+OpenLight edits documents containing image content and adjustments.
+
+## Language
+
+**Document**:
+An independent editing session with its own canvas and history. Opening an image creates a document containing that image.
+_Avoid_: Image, input file, scene
+
+**Scene**:
+The current content of a document, including its canvas dimensions, image references, and adjustments.
+_Avoid_: Open file, texture
+
+**Image source**:
+An image used as input to a document's composition. It is content within the document, not the document itself.
+
+**Edit**:
+One reversible change to document content. A continuous slider or curve drag is one edit, as is importing a set of adjustments.
+
+**Workspace**:
+The application's open-document session. It currently contains at most one document, replaced when another image is opened.
diff --git a/README.md b/README.md
index 6fe64a6..651c1da 100644
--- a/README.md
+++ b/README.md
@@ -25,11 +25,13 @@ bun run build # typecheck + bundle
## Browser controls
`window.openlight` is available after the app mounts, including production builds.
-The UI, renderer, and browser API share the Zustand scene store in
-`src/app/scene/index.ts`. The scene currently contains a source image and
-adjustments. `app/editor/renderer/renderer.ts` executes the adjustment and display passes imperatively through
-vgpu. `RendererProvider` owns the engine and frame loop; canvas and histogram
-components attach their outputs through `useRenderer`. The API exposes application commands and scene actions:
+`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.
```js
await openlight.openFiles([
@@ -38,7 +40,9 @@ await openlight.openFiles([
]);
openlight.setAdjustments({ exposure: 1, saturation: -25 });
openlight.setAdjustments({ highlights: -50, shadows: 50, whites: 10, blacks: -10 });
-const state = // Or read immediately: openlight.getState()
+openlight.undo();
+openlight.redo();
+const state = openlight.getState();
```
`openFiles` is shared by the app-wide drop handler, image picker, and browser
@@ -50,10 +54,18 @@ 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, batch ordering, and the single-document
-policy. Each loader declares `kind`, `accepts`, and `load`; register new loaders in
-`app/controls.ts`. Image decoding and XMP import live in their own loaders. The
-scene store owns document state and generic editing actions, without file loaders.
+`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.
@@ -63,5 +75,6 @@ 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 and adjustments. Loading commands resolve when their
-batch finishes; image decoding failures appear in the editor. The renderer runs every frame.
+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.
diff --git a/src/app/controls.ts b/src/app/controls.ts
index 0ac04a1..e5af013 100644
--- a/src/app/controls.ts
+++ b/src/app/controls.ts
@@ -1,50 +1,64 @@
-import { useEffect, useMemo } from "react";
-import { useGpu } from "vgpu-react";
+import type { Gpu } from "vgpu";
+import { setAdjustments, setToneCurve } from "@/app/document/edits";
import {
type ExportOptions,
exportImage,
} from "@/app/editor/export/export-image";
-import { cameraRawXmpLoader } from "@/app/loaders/camera-raw-xmp";
+import { createCameraRawXmpLoader } from "@/app/loaders/camera-raw-xmp";
import { createImageLoader } from "@/app/loaders/image";
import { createLoaderRegistry } from "@/app/loaders/registry";
-import { useScene } from "@/app/scene";
+import { type Adjustments, defaultAdjustments } from "@/app/scene";
+import type { Workspace } from "@/app/workspace";
+import { defaultCurve, type ToneCurve } from "@/features/tone-curves/curve";
-function getState() {
- const scene = useScene.getState();
+/** Imperative commands bound to an explicit workspace, usable without React. */
+export function createControls(gpu: Gpu, workspace: Workspace) {
+ const image = createImageLoader(gpu, workspace);
+ const xmp = createCameraRawXmpLoader(workspace);
+ const files = createLoaderRegistry(
+ [xmp, image],
+ () => workspace.state.getState().status === "ready",
+ );
return {
- file: scene.source?.file.name,
- adjustments: { ...scene.adjustments },
- toneCurve: scene.toneCurve.map((point) => ({ ...point })),
+ openFiles: files.openFiles,
+ openFile: (file: File) => files.openFiles([file]),
+ loadImage: (file: File) => files.loadFile(image, file),
+ importXmp: (file: File) => files.loadFile(xmp, file),
+ setAdjustments: (change: Partial<Adjustments>) =>
+ setAdjustments(workspace.getDocument(), change),
+ setToneCurve: (curve?: ToneCurve) =>
+ setToneCurve(workspace.getDocument(), curve),
+ beginEdit: () => workspace.getDocument().history.begin(),
+ commitEdit: () => workspace.getDocument().history.commit(),
+ cancelEdit: () => workspace.getDocument().history.cancel(),
+ undo: () => workspace.getDocument().history.undo(),
+ redo: () => workspace.getDocument().history.redo(),
+ exportImage: (options?: ExportOptions) =>
+ exportImage(gpu, workspace.getDocument(), options),
+ getState() {
+ const { file, document } = workspace.state.getState();
+ const scene = document?.scene.getState();
+ return {
+ file,
+ 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,
+ }),
+ },
+ };
+ },
};
}
declare global {
interface Window {
- openlight: ReturnType<typeof useControls>;
+ openlight: ReturnType<typeof createControls>;
}
}
-
-export function useControls() {
- const gpu = useGpu();
- const controls = useMemo(() => {
- const image = createImageLoader(gpu);
- const files = createLoaderRegistry([cameraRawXmpLoader, image]);
- return {
- openFiles: files.openFiles,
- openFile: (file: File) => files.openFiles([file]),
- loadImage: (file: File) => files.loadFile(image, file),
- importXmp: (file: File) => files.loadFile(cameraRawXmpLoader, file),
- setAdjustments: useScene.getState().setAdjustments,
- setToneCurve: useScene.getState().setToneCurve,
- exportImage: (options?: ExportOptions) => exportImage(gpu, options),
- getState,
- };
- }, [gpu]);
- useEffect(() => {
- window.openlight = controls;
- return () => {
- Reflect.deleteProperty(window, "openlight");
- };
- }, [controls]);
- return controls;
-}
diff --git a/src/app/document/edits.ts b/src/app/document/edits.ts
new file mode 100644
index 0000000..551e3d3
--- /dev/null
+++ b/src/app/document/edits.ts
@@ -0,0 +1,37 @@
+import { type Adjustments, adjustmentLimits } from "@/app/scene";
+import {
+ defaultCurve,
+ type ToneCurve,
+ validateCurve,
+} from "@/features/tone-curves/curve";
+import type { EditorDocument } from "./index";
+
+export function setAdjustments(
+ document: EditorDocument,
+ change: Partial<Adjustments>,
+) {
+ for (const [name, value] of Object.entries(change)) {
+ const limit = Reflect.get(adjustmentLimits, name);
+ if (
+ typeof limit !== "number" ||
+ typeof value !== "number" ||
+ !Number.isFinite(value) ||
+ Math.abs(value) > limit
+ ) {
+ throw new Error(`Invalid adjustment: ${name}.`);
+ }
+ }
+ const scene = document.scene.getState();
+ document.edit({ ...scene, adjustments: { ...scene.adjustments, ...change } });
+}
+
+export function setToneCurve(
+ document: EditorDocument,
+ points: ToneCurve = defaultCurve,
+) {
+ validateCurve(points);
+ document.edit({
+ ...document.scene.getState(),
+ toneCurve: points.map((point) => ({ ...point })),
+ });
+}
diff --git a/src/app/document/index.ts b/src/app/document/index.ts
new file mode 100644
index 0000000..e8fd5f4
--- /dev/null
+++ b/src/app/document/index.ts
@@ -0,0 +1,48 @@
+import { createStore } from "zustand/vanilla";
+import { shallow } from "zustand/vanilla/shallow";
+import type { Scene } from "@/app/scene";
+import { createHistory } from "@/lib/history";
+import { createResources } from "./resources";
+
+function equal(a: Scene, b: Scene) {
+ return (
+ a.source === b.source &&
+ shallow(a.size, b.size) &&
+ shallow(a.adjustments, b.adjustments) &&
+ a.toneCurve.length === b.toneCurve.length &&
+ a.toneCurve.every((point, i) => shallow(point, b.toneCurve[i]))
+ );
+}
+
+/** One independent editing session. No React, decoders, or file workflows. */
+export function createDocument(initial: Scene, resources = createResources()) {
+ const scene = createStore(() => initial);
+ const { update, ...history } = createHistory(scene, equal);
+ let closed = false;
+ return {
+ id: crypto.randomUUID(),
+ scene: {
+ getState: scene.getState,
+ getInitialState: scene.getInitialState,
+ subscribe: scene.subscribe,
+ },
+ history,
+ resources,
+ edit(next: Scene) {
+ if (closed) {
+ throw new Error("Document is closed.");
+ }
+ update(next);
+ },
+ dispose() {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ history.clear();
+ resources.dispose();
+ },
+ };
+}
+
+export type EditorDocument = ReturnType<typeof createDocument>;
diff --git a/src/app/document/provider.tsx b/src/app/document/provider.tsx
new file mode 100644
index 0000000..7b4a71b
--- /dev/null
+++ b/src/app/document/provider.tsx
@@ -0,0 +1,18 @@
+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/document/resources.ts b/src/app/document/resources.ts
new file mode 100644
index 0000000..46083a9
--- /dev/null
+++ b/src/app/document/resources.ts
@@ -0,0 +1,31 @@
+import type { Target } from "vgpu";
+
+/** Owns the document's image files and GPU targets, outside scene history. */
+export function createResources() {
+ const images = new Map<string, { file: File; image: Target }>();
+ let disposed = false;
+ return {
+ add(file: File, image: Target) {
+ if (disposed) {
+ throw new Error("Document is closed.");
+ }
+ const id = crypto.randomUUID();
+ images.set(id, { file, image });
+ return id;
+ },
+ get(id: string) {
+ const resource = images.get(id);
+ if (!resource) {
+ throw new Error("Image resource is unavailable.");
+ }
+ return resource;
+ },
+ dispose() {
+ disposed = true;
+ for (const { image } of images.values()) {
+ image.color.dispose();
+ }
+ images.clear();
+ },
+ };
+}
diff --git a/src/app/editor/export/export-image.ts b/src/app/editor/export/export-image.ts
index 29049c4..834e3df 100644
--- a/src/app/editor/export/export-image.ts
+++ b/src/app/editor/export/export-image.ts
@@ -1,6 +1,6 @@
import { frame, type Gpu, surface } from "vgpu";
+import type { EditorDocument } from "@/app/document";
import { createRenderer } from "@/app/editor/renderer/renderer";
-import { useScene } from "@/app/scene";
export type ExportOptions =
| { format: "png" }
@@ -9,6 +9,7 @@ export type ExportOptions =
/** Renders a snapshot of the current edits at the original image dimensions. */
export async function exportImage(
gpu: Gpu,
+ document: EditorDocument,
options: ExportOptions = { format: "png" },
) {
if (options.format !== "png" && options.format !== "jpeg") {
@@ -22,20 +23,20 @@ export async function exportImage(
) {
throw new Error("JPEG quality must be between 1 and 100.");
}
- const scene = useScene.getState();
- const source = scene.source;
- if (!source?.image) {
- throw new Error("Load an image before exporting.");
- }
- const [width, height] = source.image.size;
- const canvas = new OffscreenCanvas(width, height);
- const output = surface(gpu, canvas, { size: [width, height], dpr: 1 });
- const renderer = createRenderer(gpu, source.image);
+ const scene = document.scene.getState();
+ const { image } = document.resources.get(scene.source);
+ let output: ReturnType<typeof surface> | undefined;
+ let renderer: ReturnType<typeof createRenderer> | undefined;
try {
+ const [width, height] = scene.size;
+ const canvas = new OffscreenCanvas(width, height);
+ output = surface(gpu, canvas, { size: [width, height], dpr: 1 });
+ renderer = createRenderer(gpu, image);
renderer.update(scene);
- frame(gpu, (frame) =>
- renderer.draw(frame, output, { zoom: 1, pan: [0, 0] }),
- );
+ const draw = renderer.draw;
+ const destination = output;
+ frame(gpu, (frame) => draw(frame, destination, { 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}`,
quality: options.format === "jpeg" ? options.quality / 100 : undefined,
@@ -43,7 +44,7 @@ export async function exportImage(
const extension = options.format === "jpeg" ? "jpg" : "png";
return new File([blob], `export.${extension}`, { type: blob.type });
} finally {
- renderer.dispose();
- output.dispose();
+ renderer?.dispose();
+ output?.dispose();
}
}
diff --git a/src/app/editor/export/export-settings.tsx b/src/app/editor/export/export-settings.tsx
index 83a3ce6..620c814 100644
--- a/src/app/editor/export/export-settings.tsx
+++ b/src/app/editor/export/export-settings.tsx
@@ -1,5 +1,6 @@
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 Button from "@/components/ui/button";
import { Slider } from "@/components/ui/slider";
@@ -11,6 +12,7 @@ const formats = [
export function ExportSettings({ onClose }: { onClose: () => void }) {
const gpu = useGpu();
+ const editorDocument = useDocument();
const [format, setFormat] = useState<"png" | "jpeg">("png");
const [quality, setQuality] = useState(90);
const [error, setError] = useState("");
@@ -23,7 +25,7 @@ export function ExportSettings({ onClose }: { onClose: () => void }) {
setError("");
try {
const options = format === "png" ? { format } : { format, quality };
- const file = await exportImage(gpu, options);
+ const file = await exportImage(gpu, editorDocument, options);
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
diff --git a/src/app/editor/history.tsx b/src/app/editor/history.tsx
new file mode 100644
index 0000000..00f18de
--- /dev/null
+++ b/src/app/editor/history.tsx
@@ -0,0 +1,56 @@
+import { useEffect } from "react";
+import { useStore } from "zustand";
+import { useDocument } from "@/app/document/provider";
+import Button from "@/components/ui/button";
+
+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]);
+ return (
+ <div className="flex gap-2 px-4 pt-3">
+ <Button
+ variant="ghost"
+ className="disabled:pointer-events-none disabled:opacity-40"
+ disabled={!undoCount}
+ onClick={history.undo}
+ >
+ Undo
+ </Button>
+ <Button
+ variant="ghost"
+ className="disabled:pointer-events-none disabled:opacity-40"
+ disabled={!redoCount}
+ onClick={history.redo}
+ >
+ Redo
+ </Button>
+ </div>
+ );
+}
diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsx
index 6f7ef67..90bb635 100644
--- a/src/app/editor/index.tsx
+++ b/src/app/editor/index.tsx
@@ -1,5 +1,6 @@
import { Canvas } from "vgpu-react";
-import type { Source } from "@/app/scene";
+import { DocumentProvider } from "@/app/document/provider";
+import type { Workspace } from "@/app/workspace";
import ResizablePanel from "@/components/ui/resizable-panel";
import Spinner from "@/components/ui/spinner";
import { usePanZoom } from "@/hooks/use-pan-zoom";
@@ -26,42 +27,48 @@ function ImageCanvas({ image }: WorkspaceProps) {
);
}
-type EditorProps = { source: Source };
+type EditorProps = { state: ReturnType<Workspace["state"]["getState"]> };
-function LoadingStatus({ source }: EditorProps) {
- if (!source.error) {
+function LoadingStatus({ state }: EditorProps) {
+ if (state.status !== "error") {
return <Spinner />;
}
return (
<p className="max-w-md text-center text-neutral-400">
- Couldn't open {source.file.name}: {source.error}
+ Couldn't open {state.file}: {state.error}
</p>
);
}
-function EditorContent({ source }: EditorProps) {
- if (source.image) {
+function EditorContent({ state }: EditorProps) {
+ if (state.status === "ready") {
+ const { document } = state;
+ const image = document.resources.get(
+ document.scene.getState().source,
+ ).image;
return (
- <RendererProvider source={source.image}>
- <ImageCanvas image={source.image} />
- <Sidebar />
- </RendererProvider>
+ <DocumentProvider value={document}>
+ <RendererProvider source={image}>
+ <ImageCanvas image={image} />
+ <Sidebar />
+ </RendererProvider>
+ </DocumentProvider>
);
}
return (
<>
<div className="grid flex-1 place-items-center">
- <LoadingStatus source={source} />
+ <LoadingStatus state={state} />
</div>
<ResizablePanel />
</>
);
}
-export default function Editor({ source }: EditorProps) {
+export default function Editor({ state }: EditorProps) {
return (
<main className="flex h-dvh flex-col md:flex-row">
- <EditorContent source={source} />
+ <EditorContent state={state} />
</main>
);
}
diff --git a/src/app/editor/renderer/provider.tsx b/src/app/editor/renderer/provider.tsx
index aac8648..4f55474 100644
--- a/src/app/editor/renderer/provider.tsx
+++ b/src/app/editor/renderer/provider.tsx
@@ -7,7 +7,8 @@ import {
} from "react";
import type { Target } from "vgpu";
import { useGpu } from "vgpu-react";
-import { type Scene, useScene } from "@/app/scene";
+import { useDocument } from "@/app/document/provider";
+import type { Scene } from "@/app/scene";
import { createRenderer } from "./renderer";
const RendererContext = createContext<ReturnType<typeof createRenderer> | null>(
@@ -26,20 +27,18 @@ type RendererProviderProps = { source: Target; children: ReactNode };
export function RendererProvider({ source, children }: RendererProviderProps) {
const gpu = useGpu();
+ const document = useDocument();
const renderer = useMemo(() => createRenderer(gpu, source), [gpu, source]);
useEffect(() => {
const render = (scene: Scene) => {
- if (scene.source?.image !== source) {
- return;
- }
renderer.update(scene);
};
- const unsubscribe = useScene.subscribe(render);
- render(useScene.getState());
+ const unsubscribe = document.scene.subscribe(render);
+ render(document.scene.getState());
return () => {
unsubscribe();
renderer.dispose();
};
- }, [renderer, source]);
+ }, [renderer, document]);
return <RendererContext value={renderer}>{children}</RendererContext>;
}
diff --git a/src/app/editor/sidebar/adjustment-controls.tsx b/src/app/editor/sidebar/adjustment-controls.tsx
index b453477..8db523e 100644
--- a/src/app/editor/sidebar/adjustment-controls.tsx
+++ b/src/app/editor/sidebar/adjustment-controls.tsx
@@ -1,9 +1,10 @@
import type { ComponentProps } from "react";
+import { setAdjustments } from "@/app/document/edits";
+import { useDocument, useScene } from "@/app/document/provider";
import {
type Adjustments,
adjustmentLimits,
defaultAdjustments,
- useScene,
} from "@/app/scene";
import { Slider } from "@/components/ui/slider";
@@ -28,12 +29,12 @@ type AdjustmentSliderProps = Pick<
function AdjustmentSlider({ name, ...props }: AdjustmentSliderProps) {
const value = useScene((scene) => scene.adjustments[name]);
- const onChange = useScene((scene) => scene.setAdjustments);
+ const document = useDocument();
return (
<Slider
{...props}
value={value}
- onChange={(value) => onChange({ [name]: value })}
+ onChange={(value) => setAdjustments(document, { [name]: value })}
defaultValue={defaultAdjustments[name]}
min={-adjustmentLimits[name]}
max={adjustmentLimits[name]}
diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/sidebar/index.tsx
index 1372fc0..9fa7b2d 100644
--- a/src/app/editor/sidebar/index.tsx
+++ b/src/app/editor/sidebar/index.tsx
@@ -1,12 +1,15 @@
import { 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 { useScene } from "@/app/scene";
import ResizablePanel from "@/components/ui/resizable-panel";
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 AdjustmentControls from "./adjustment-controls";
const histogramColors = ["#f25445", "#6bd175", "#5c8ffa"] as const;
@@ -19,9 +22,12 @@ function ToneCurvesPanel({
}) {
const renderer = useRenderer();
const toneCurve = useScene((scene) => scene.toneCurve);
- const setToneCurve = useScene((scene) => scene.setToneCurve);
+ const document = useDocument();
return (
- <ToneCurves points={toneCurve} onChange={setToneCurve}>
+ <ToneCurves
+ points={toneCurve}
+ onChange={(points) => setToneCurve(document, points)}
+ >
<Histogram
histogram={histogram}
image={renderer.inputImage}
@@ -38,13 +44,17 @@ function ToneCurvesPanel({
export function Sidebar() {
const gpu = useGpu();
+ const gesture = useEditGesture(useDocument().history);
const renderer = useRenderer();
const histogram = useMemo(() => createHistogram(gpu), [gpu]);
useEffect(() => () => histogram.dispose(), [histogram]);
return (
<ResizablePanel>
<div className="flex h-full flex-col divide-y divide-black">
- <div className="min-h-0 flex-1 divide-y divide-black overflow-y-auto">
+ <div
+ {...gesture}
+ className="min-h-0 flex-1 divide-y divide-black overflow-y-auto"
+ >
<section className="bg-neutral-900 p-0.5 pb-0">
<Histogram
histogram={histogram}
@@ -59,6 +69,7 @@ export function Sidebar() {
<AdjustmentControls />
<ToneCurvesPanel histogram={histogram} />
</div>
+ <HistoryControls />
<ExportButton />
</div>
</ResizablePanel>
diff --git a/src/app/index.tsx b/src/app/index.tsx
index ec11d48..b037ae7 100644
--- a/src/app/index.tsx
+++ b/src/app/index.tsx
@@ -1,15 +1,15 @@
+import { useStore } from "zustand";
import { useFileDrop } from "@/hooks/use-file-drop";
-import { useControls } from "./controls";
import Editor from "./editor";
import Landing from "./landing";
-import { useScene } from "./scene";
+import { useWorkspace } from "./workspace/use-workspace";
export default function App() {
- const { openFiles } = useControls();
- useFileDrop(openFiles);
- const source = useScene((scene) => scene.source);
- if (!source) {
- return <Landing onOpen={openFiles} />;
+ const { workspace, controls } = useWorkspace();
+ useFileDrop(controls.openFiles);
+ const state = useStore(workspace.state);
+ if (state.status === "empty") {
+ return <Landing onOpen={controls.openFiles} />;
}
- return <Editor source={source} />;
+ return <Editor state={state} />;
}
diff --git a/src/app/loaders/camera-raw-xmp.ts b/src/app/loaders/camera-raw-xmp.ts
index af93898..890a757 100644
--- a/src/app/loaders/camera-raw-xmp.ts
+++ b/src/app/loaders/camera-raw-xmp.ts
@@ -1,4 +1,6 @@
-import { type Adjustments, useScene } from "@/app/scene";
+import { setAdjustments } from "@/app/document/edits";
+import type { Adjustments } from "@/app/scene";
+import type { Workspace } from "@/app/workspace";
import {
type CameraRawXmp,
isCameraRawXmp,
@@ -22,22 +24,20 @@ function toAdjustments(xmp: CameraRawXmp): Partial<Adjustments> {
);
}
-async function importCameraRawXmp(file: File) {
- if (!(file instanceof File)) {
- throw new Error("importCameraRawXmp requires a File.");
- }
- const source = useScene.getState().source;
- if (!source) {
- throw new Error("Load an image before importing adjustments.");
- }
- const adjustments = toAdjustments(readCameraRawXmp(await file.text()));
- if (useScene.getState().source === source) {
- useScene.getState().setAdjustments(adjustments);
- }
+export function createCameraRawXmpLoader(workspace: Workspace): FileLoader {
+ return {
+ kind: "settings",
+ accepts: isCameraRawXmp,
+ async load(file) {
+ if (!(file instanceof File)) {
+ throw new Error("importXmp requires a File.");
+ }
+ const document = workspace.getDocument();
+ const adjustments = toAdjustments(readCameraRawXmp(await file.text()));
+ if (workspace.state.getState().document === document) {
+ document.history.commit();
+ setAdjustments(document, adjustments);
+ }
+ },
+ };
}
-
-export const cameraRawXmpLoader: FileLoader = {
- kind: "settings",
- accepts: isCameraRawXmp,
- load: importCameraRawXmp,
-};
diff --git a/src/app/loaders/image.ts b/src/app/loaders/image.ts
index 391513b..93d5035 100644
--- a/src/app/loaders/image.ts
+++ b/src/app/loaders/image.ts
@@ -1,36 +1,34 @@
import type { Gpu } from "vgpu";
-import { defaultAdjustments, useScene } from "@/app/scene";
+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 type { FileLoader } from "./registry";
-export function createImageLoader(gpu: Gpu): FileLoader {
+export function createImageLoader(gpu: Gpu, workspace: Workspace): FileLoader {
return {
kind: "document",
accepts: canDecode,
- load: async (file) => {
+ async load(file) {
if (!(file instanceof File)) {
throw new Error("loadImage requires a File.");
}
- const source = { file };
- useScene.getState().source?.image?.color.dispose();
- useScene.setState({
- source,
- adjustments: { ...defaultAdjustments },
- toneCurve: defaultCurve,
- });
- try {
+ await workspace.open(file.name, async () => {
const image = await decode(gpu, file);
- if (useScene.getState().source !== source) {
- image.color.dispose();
- return;
- }
- useScene.setState({ source: { file, image } });
- } catch (error) {
- if (useScene.getState().source === source) {
- useScene.setState({ source: { file, error: String(error) } });
- }
- }
+ const resources = createResources();
+ const source = resources.add(file, image);
+ return createDocument(
+ {
+ size: [image.size[0], image.size[1]],
+ source,
+ adjustments: { ...defaultAdjustments },
+ toneCurve: defaultCurve,
+ },
+ resources,
+ );
+ });
},
};
}
diff --git a/src/app/loaders/registry.ts b/src/app/loaders/registry.ts
index 2ca1d4d..d94dd83 100644
--- a/src/app/loaders/registry.ts
+++ b/src/app/loaders/registry.ts
@@ -1,5 +1,3 @@
-import { useScene } from "@/app/scene";
-
export type FileLoader = {
kind: "document" | "settings";
accepts: (file: File) => boolean;
@@ -8,12 +6,12 @@ export type FileLoader = {
type Job = { file: File; loader: FileLoader };
-async function loadBatch(jobs: Job[]) {
+async function loadBatch(jobs: Job[], ready: () => boolean) {
const document = jobs.find(({ loader }) => loader.kind === "document");
if (document) {
await document.loader.load(document.file);
}
- if (!useScene.getState().source?.image) {
+ if (!ready()) {
return;
}
for (const { file, loader } of jobs) {
@@ -23,11 +21,14 @@ async function loadBatch(jobs: Job[]) {
}
}
-export function createLoaderRegistry(loaders: readonly FileLoader[]) {
+export function createLoaderRegistry(
+ loaders: readonly FileLoader[],
+ ready: () => boolean,
+) {
let pending = Promise.resolve();
function enqueue(jobs: Job[]) {
- const result = pending.then(() => loadBatch(jobs));
+ const result = pending.then(() => loadBatch(jobs, ready));
// Return the failure to the caller while allowing later batches to run.
pending = result.catch(() => {});
return result;
diff --git a/src/app/scene/index.ts b/src/app/scene/index.ts
index 2dd56a8..2fb8ecd 100644
--- a/src/app/scene/index.ts
+++ b/src/app/scene/index.ts
@@ -1,11 +1,4 @@
-import type { Target } from "vgpu";
-import { create } from "zustand";
-import {
- defaultCurve,
- type ToneCurve,
- validateCurve,
-} from "@/features/tone-curves/curve";
-
+import type { ToneCurve } from "@/features/tone-curves/curve";
import type { Adjustments } from "@/lib/adjustments";
export type { Adjustments } from "@/lib/adjustments";
@@ -36,33 +29,10 @@ export const adjustmentLimits: Adjustments = {
saturation: 100,
};
-export type Source = { file: File; image?: Target; error?: string };
+/** Serializable document content. Image bytes and GPU resources live elsewhere. */
export type Scene = {
- source?: Source;
- adjustments: Adjustments;
- toneCurve: ToneCurve;
-};
-type SceneStore = Scene & {
- setAdjustments: (change: Partial<Adjustments>) => void;
- /** Ordered points in 0..1; endpoints follow the lower-left and upper-right edges. Omit to reset. */
- setToneCurve: (toneCurve?: ToneCurve) => void;
+ readonly size: readonly [number, number];
+ readonly source: string;
+ readonly adjustments: Readonly<Adjustments>;
+ readonly toneCurve: ToneCurve;
};
-
-export const useScene = create<SceneStore>((set, get) => ({
- adjustments: { ...defaultAdjustments },
- toneCurve: defaultCurve,
- setAdjustments: (change) => {
- const { source, adjustments } = get();
- if (!source) {
- throw new Error("Load an image before changing adjustments.");
- }
- set({ adjustments: { ...adjustments, ...change } });
- },
- setToneCurve: (toneCurve = defaultCurve) => {
- if (!get().source) {
- throw new Error("Load an image before changing the tone curve.");
- }
- validateCurve(toneCurve);
- set({ toneCurve: toneCurve.map((point) => ({ ...point })) });
- },
-}));
diff --git a/src/app/workspace/index.ts b/src/app/workspace/index.ts
new file mode 100644
index 0000000..580cb88
--- /dev/null
+++ b/src/app/workspace/index.ts
@@ -0,0 +1,57 @@
+import { createStore } from "zustand/vanilla";
+import type { EditorDocument } from "@/app/document";
+
+type WorkspaceState =
+ | { status: "empty"; file?: undefined; document?: undefined }
+ | { status: "loading"; file: string; document?: undefined }
+ | { status: "error"; file: string; error: string; document?: undefined }
+ | { status: "ready"; file: string; document: EditorDocument };
+
+/** Single-document policy; document instances remain independent of this session. */
+export function createWorkspace() {
+ const state = createStore<WorkspaceState>(() => ({ status: "empty" }));
+ let generation = 0;
+ let closed = false;
+ return {
+ state: {
+ getState: state.getState,
+ getInitialState: state.getInitialState,
+ subscribe: state.subscribe,
+ },
+ getDocument() {
+ const document = state.getState().document;
+ if (!document) {
+ throw new Error("Load an image before editing.");
+ }
+ return document;
+ },
+ async open(file: string, load: () => Promise<EditorDocument>) {
+ if (closed) {
+ throw new Error("Workspace is closed.");
+ }
+ const request = ++generation;
+ const previous = state.getState().document;
+ state.setState({ status: "loading", file }, true);
+ previous?.dispose();
+ try {
+ const document = await load();
+ if (request !== generation) {
+ document.dispose();
+ return;
+ }
+ state.setState({ status: "ready", file, document }, true);
+ } catch (error) {
+ if (request === generation) {
+ state.setState({ status: "error", file, error: String(error) }, true);
+ }
+ }
+ },
+ dispose() {
+ closed = true;
+ generation++;
+ state.getState().document?.dispose();
+ state.setState({ status: "empty" }, true);
+ },
+ };
+}
+export type Workspace = ReturnType<typeof createWorkspace>;
diff --git a/src/app/workspace/use-workspace.ts b/src/app/workspace/use-workspace.ts
new file mode 100644
index 0000000..9a70e78
--- /dev/null
+++ b/src/app/workspace/use-workspace.ts
@@ -0,0 +1,21 @@
+import { useEffect, useMemo } from "react";
+import { useGpu } from "vgpu-react";
+import { createControls } from "@/app/controls";
+import { createWorkspace } from "./index";
+
+/** Connects an imperative workspace and its browser commands to the app lifetime. */
+export function useWorkspace() {
+ const gpu = useGpu();
+ const session = useMemo(() => {
+ const workspace = createWorkspace();
+ return { workspace, controls: createControls(gpu, workspace) };
+ }, [gpu]);
+ useEffect(() => {
+ window.openlight = session.controls;
+ return () => {
+ Reflect.deleteProperty(window, "openlight");
+ session.workspace.dispose();
+ };
+ }, [session]);
+ return session;
+}
diff --git a/src/hooks/use-edit-gesture.ts b/src/hooks/use-edit-gesture.ts
new file mode 100644
index 0000000..0eb6930
--- /dev/null
+++ b/src/hooks/use-edit-gesture.ts
@@ -0,0 +1,78 @@
+import {
+ type KeyboardEvent,
+ type PointerEvent,
+ useEffect,
+ useRef,
+} from "react";
+
+type Edit = { begin: () => void; commit: () => void; cancel: () => void };
+type Gesture = "pointerup" | "keyup";
+
+/** Groups pointer and repeated keyboard changes; text fields commit their own draft. */
+export function useEditGesture(edit: Edit) {
+ const active = useRef<Gesture | null>(null);
+ function begin(end: Gesture) {
+ active.current = end;
+ edit.begin();
+ }
+ useEffect(() => {
+ function finish(event: Event) {
+ if (active.current !== event.type) {
+ return;
+ }
+ active.current = null;
+ edit.commit();
+ }
+ function cancel() {
+ if (!active.current) {
+ return;
+ }
+ active.current = null;
+ edit.cancel();
+ }
+ const controller = new AbortController();
+ const { signal } = controller;
+ window.addEventListener("pointerup", finish, { signal });
+ window.addEventListener("keyup", finish, { signal });
+ window.addEventListener("pointercancel", cancel, { signal });
+ window.addEventListener("blur", cancel, { signal });
+ return () => {
+ controller.abort();
+ cancel();
+ };
+ }, [edit]);
+ return {
+ onPointerDownCapture(event: PointerEvent) {
+ if (event.button === 0) {
+ const focused = document.activeElement;
+ if (
+ focused instanceof HTMLInputElement &&
+ focused.type === "text" &&
+ focused !== event.target
+ ) {
+ focused.blur();
+ }
+ begin("pointerup");
+ }
+ },
+ onPointerMoveCapture() {
+ if (active.current === "pointerup") {
+ edit.begin();
+ }
+ },
+ onKeyDownCapture(event: KeyboardEvent) {
+ if (
+ event.metaKey ||
+ event.ctrlKey ||
+ event.altKey ||
+ active.current === "pointerup" ||
+ (event.target instanceof HTMLInputElement &&
+ event.target.type !== "range")
+ ) {
+ return;
+ }
+ // Unused keys create no history entry; shortcuts keep their own transactions.
+ begin("keyup");
+ },
+ };
+}
diff --git a/src/lib/history.ts b/src/lib/history.ts
new file mode 100644
index 0000000..d67a3f5
--- /dev/null
+++ b/src/lib/history.ts
@@ -0,0 +1,79 @@
+import { createStore, type StoreApi } from "zustand/vanilla";
+
+/** Bounded immutable snapshots, grouped explicitly by an editing gesture. */
+export function createHistory<T extends object>(
+ state: StoreApi<T>,
+ equal: (a: T, b: T) => boolean,
+ limit = 100,
+) {
+ const status = createStore(() => ({ undoCount: 0, redoCount: 0 }));
+ const past: T[] = [];
+ const future: T[] = [];
+ let group: T | undefined;
+ const publish = () =>
+ status.setState({ undoCount: past.length, redoCount: future.length });
+ function record(before: T) {
+ if (equal(before, state.getState())) {
+ return;
+ }
+ past.push(before);
+ if (past.length > limit) {
+ past.shift();
+ }
+ future.length = 0;
+ publish();
+ }
+ function commit() {
+ const before = group;
+ group = undefined;
+ if (before !== undefined) {
+ record(before);
+ }
+ }
+ function cancel() {
+ const before = group;
+ group = undefined;
+ if (before !== undefined) {
+ state.setState(before, true);
+ }
+ }
+ function travel(from: T[], to: T[]) {
+ commit();
+ const next = from.pop();
+ if (next === undefined) {
+ return;
+ }
+ to.push(state.getState());
+ state.setState(next, true);
+ publish();
+ }
+ return {
+ status: {
+ getState: status.getState,
+ getInitialState: status.getInitialState,
+ subscribe: status.subscribe,
+ },
+ update(next: T) {
+ const before = state.getState();
+ if (equal(before, next)) {
+ return;
+ }
+ state.setState(next, true);
+ if (!group) {
+ record(before);
+ }
+ },
+ begin() {
+ group ??= state.getState();
+ },
+ commit,
+ cancel,
+ undo: () => travel(past, future),
+ redo: () => travel(future, past),
+ clear() {
+ group = undefined;
+ past.length = future.length = 0;
+ publish();
+ },
+ };
+}
diff --git a/tests/curves.e2e.ts b/tests/curves.e2e.ts
deleted file mode 100644
index e6681bd..0000000
--- a/tests/curves.e2e.ts
+++ /dev/null
@@ -1,436 +0,0 @@
-import type { Page } from "@playwright/test";
-import { interpolatePchip } from "@/lib/math";
-import { expect, test } from "./fixtures";
-
-async function centerPixel(page: Page) {
- const screenshot = await page.locator("canvas").screenshot();
- return page.evaluate(
- async (bytes) => {
- const image = await createImageBitmap(
- new Blob([new Uint8Array(bytes)], { type: "image/png" }),
- );
- const canvas = new OffscreenCanvas(image.width, image.height);
- const context = canvas.getContext("2d");
- if (!context) {
- throw new Error("Cannot read the preview screenshot.");
- }
- context.drawImage(image, 0, 0);
- image.close();
- return [
- ...context.getImageData(canvas.width / 2, canvas.height / 2, 1, 1).data,
- ];
- },
- [...screenshot],
- );
-}
-
-test("a master curve maps colors beyond its white endpoint to white", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- await page.evaluate(() =>
- window.openlight.loadImage(
- new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#305080"/></svg>',
- ],
- "blue.svg",
- { type: "image/svg+xml" },
- ),
- ),
- );
- await expect.poll(() => centerPixel(page)).toEqual([48, 80, 128, 255]);
- await page.evaluate(() =>
- window.openlight.setToneCurve([
- { x: 0, y: 0 },
- { x: 0.1, y: 1 },
- ]),
- );
- await expect.poll(() => centerPixel(page)).toEqual([255, 255, 255, 255]);
-});
-
-test("curve commands reject invalid edits, reset, and start fresh for another image", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- const result = await page.evaluate(async () => {
- const image = new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',
- ],
- "curve.svg",
- { type: "image/svg+xml" },
- );
- await window.openlight.loadImage(image);
- const initial = window.openlight.getState().toneCurve;
- const points = [
- { x: 0, y: 0 },
- { x: 0.5, y: 0.75 },
- { x: 1, y: 1 },
- ];
- window.openlight.setToneCurve(points);
- points[1].y = 0.25;
- const edited = window.openlight.getState().toneCurve;
- const snapshot = window.openlight.getState();
- snapshot.toneCurve[1].y = 0;
- const afterSnapshotChange = window.openlight.getState().toneCurve;
- const rejected = [
- [],
- [{ x: 0, y: 0 }],
- [
- { x: 0, y: 0 },
- { x: 0, y: 1 },
- ],
- [
- { x: 0, y: 0 },
- { x: 1 / 2048, y: 1 },
- ],
- [
- { x: 0, y: 0 },
- { x: 0.8, y: 0.5 },
- { x: 0.5, y: 1 },
- ],
- [
- { x: 0, y: 0 },
- { x: 1, y: Number.NaN },
- ],
- [
- { x: 0, y: -1 },
- { x: 1, y: 1 },
- ],
- [
- { x: 0.1, y: 0.1 },
- { x: 1, y: 1 },
- ],
- [
- { x: 0, y: 0 },
- { x: 0.9, y: 0.9 },
- ],
- ].map((curve) => {
- try {
- window.openlight.setToneCurve(curve);
- return false;
- } catch (error) {
- return error instanceof Error && error.message.length > 0;
- }
- });
- const afterRejected = window.openlight.getState().toneCurve;
- window.openlight.setToneCurve();
- const reset = window.openlight.getState().toneCurve;
- window.openlight.setToneCurve(edited);
- await window.openlight.loadImage(
- new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#305080"/></svg>',
- ],
- "another.svg",
- { type: "image/svg+xml" },
- ),
- );
- return {
- initial,
- edited,
- afterSnapshotChange,
- rejected,
- afterRejected,
- reset,
- reloaded: window.openlight.getState().toneCurve,
- file: window.openlight.getState().file,
- };
- });
- const identity = [
- { x: 0, y: 0 },
- { x: 1, y: 1 },
- ];
- expect(result.initial).toEqual(identity);
- expect(result.edited).toEqual([
- { x: 0, y: 0 },
- { x: 0.5, y: 0.75 },
- { x: 1, y: 1 },
- ]);
- expect(result.afterSnapshotChange).toEqual(result.edited);
- expect(result.rejected).toEqual(Array(9).fill(true));
- expect(result.afterRejected).toEqual(result.edited);
- expect(result.reset).toEqual(identity);
- expect(result.reloaded).toEqual(identity);
- expect(result.file).toBe("another.svg");
- await expect.poll(() => centerPixel(page)).toEqual([48, 80, 128, 255]);
-});
-
-test("curves render after adjustments and resetting restores the preview", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- await page.evaluate(() =>
- window.openlight.loadImage(
- new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',
- ],
- "gray.svg",
- { type: "image/svg+xml" },
- ),
- ),
- );
- await expect.poll(() => centerPixel(page)).toEqual([128, 128, 128, 255]);
- const original = await page.locator("canvas").screenshot();
- const points = [
- { x: 0, y: 0 },
- { x: 0.5, y: 0.75 },
- { x: 1, y: 1 },
- ];
- await page.evaluate((curve) => window.openlight.setToneCurve(curve), points);
- await expect
- .poll(async () => (await centerPixel(page))[0])
- .toBeCloseTo(192, -1);
- await page.evaluate(() => window.openlight.setToneCurve());
- await expect
- .poll(() => page.locator("canvas").screenshot())
- .toEqual(original);
- await page.evaluate(() => window.openlight.setAdjustments({ exposure: -1 }));
- await expect.poll(async () => (await centerPixel(page))[0]).toBeLessThan(120);
- const adjusted = await centerPixel(page);
- const adjustedPreview = await page.locator("canvas").screenshot();
- await page.evaluate((curve) => window.openlight.setToneCurve(curve), points);
- const expected = interpolatePchip(points)(adjusted[0] / 255) * 255;
- await expect
- .poll(async () => Math.abs((await centerPixel(page))[0] - expected))
- .toBeLessThan(2);
- await page.evaluate(() => window.openlight.setToneCurve());
- await expect
- .poll(() => page.locator("canvas").screenshot())
- .toEqual(adjustedPreview);
- await page.evaluate(() => window.openlight.setAdjustments({ exposure: 0 }));
- await expect
- .poll(() => page.locator("canvas").screenshot())
- .toEqual(original);
-});
-
-test("the curve panel edits points over a combined input histogram", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- await page.evaluate(() =>
- window.openlight.loadImage(
- new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',
- ],
- "gray.svg",
- { type: "image/svg+xml" },
- ),
- ),
- );
- const graph = page.getByRole("application", { name: "Tone curve" });
- await graph.scrollIntoViewIfNeeded();
- const bounds = await graph.boundingBox();
- if (!bounds) {
- throw new Error("Curve graph is not visible.");
- }
- const input = page.locator('svg[aria-label="input histogram"] polyline');
- const output = page
- .locator('svg[aria-label="output histogram"] polyline')
- .first();
- await expect(input).toHaveCount(1);
- await expect(input).toHaveAttribute("points", /,0\.0/);
- await expect(output).toHaveAttribute("points", /,0\.0/);
- const inputBefore = await input.getAttribute("points");
- const inputNode = await input.elementHandle();
- const outputBefore = await output.getAttribute("points");
- await graph.click({
- position: { x: bounds.width / 2, y: bounds.height / 2 },
- });
- await expect(graph.locator("circle")).toHaveCount(3);
- 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: 5 },
- );
- await page.mouse.up();
- const edited = await page.evaluate(
- () => window.openlight.getState().toneCurve[1],
- );
- expect(edited.x).toBeCloseTo(0.5, 2);
- expect(edited.y).toBeCloseTo(0.75, 2);
- await expect(output).not.toHaveAttribute("points", outputBefore ?? "");
- await expect(input).toHaveAttribute("points", inputBefore ?? "");
- expect(await inputNode?.evaluate((node) => node.isConnected)).toBe(true);
- await expect
- .poll(async () => (await centerPixel(page))[0])
- .toBeGreaterThan(185);
- await graph.press("Shift+ArrowDown");
- expect(
- (await page.evaluate(() => window.openlight.getState().toneCurve[1])).y,
- ).toBeCloseTo(edited.y - 0.01, 5);
- await graph.press("Delete");
- await expect(graph.locator("circle")).toHaveCount(2);
- await expect.poll(() => centerPixel(page)).toEqual([128, 128, 128, 255]);
- await graph.press("Enter");
- await expect(graph.locator("circle")).toHaveCount(3);
- await graph.press("ArrowUp");
- expect(
- (await page.evaluate(() => window.openlight.getState().toneCurve[1])).y,
- ).toBeCloseTo(0.501, 5);
- await graph.dblclick({
- position: { x: bounds.width / 2, y: bounds.height * 0.499 },
- });
- await expect(graph.locator("circle")).toHaveCount(2);
- await page.evaluate(() =>
- window.openlight.setToneCurve([
- { x: 0, y: 0 },
- { x: 0.3, y: 0.4 },
- { x: 0.7, y: 0.6 },
- { x: 1, y: 1 },
- ]),
- );
- await expect(graph.locator("circle")).toHaveCount(4);
- await page.mouse.move(
- bounds.x + bounds.width * 0.3,
- bounds.y + bounds.height * 0.6,
- );
- await page.mouse.down();
- await page.mouse.move(bounds.x + bounds.width + 20, bounds.y - 20, {
- steps: 5,
- });
- await page.mouse.up();
- const constrained = await page.evaluate(
- () => window.openlight.getState().toneCurve,
- );
- expect(constrained[1].x).toBeLessThan(constrained[2].x);
- expect(constrained[1].y).toBe(1);
- await page.mouse.move(
- bounds.x + bounds.width / 2,
- bounds.y + bounds.height / 2,
- );
- expect(
- await page.evaluate(() => window.openlight.getState().toneCurve),
- ).toEqual(constrained);
- await page.getByRole("button", { name: "Reset curve" }).click();
- await expect(graph.locator("circle")).toHaveCount(2);
- expect(
- await page.evaluate(() => window.openlight.getState().toneCurve),
- ).toEqual([
- { x: 0, y: 0 },
- { x: 1, y: 1 },
- ]);
- await expect.poll(() => centerPixel(page)).toEqual([128, 128, 128, 255]);
- await page.evaluate(() => window.openlight.setAdjustments({ exposure: -1 }));
- await expect(input).not.toHaveAttribute("points", inputBefore ?? "");
-});
-
-test("endpoints follow the edges, remap black and white, and reset on double-click", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- for (const example of [
- {
- color: "#000000",
- index: 0,
- start: { x: 0, y: 0 },
- vertical: { x: 0, y: 0.25 },
- horizontal: { x: 0.2, y: 0 },
- expected: 64,
- },
- {
- color: "#ffffff",
- index: 1,
- start: { x: 1, y: 1 },
- vertical: { x: 1, y: 0.75 },
- horizontal: { x: 0.8, y: 1 },
- expected: 191,
- },
- ]) {
- await page.evaluate(
- (color) =>
- window.openlight.loadImage(
- new File(
- [
- `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="${color}"/></svg>`,
- ],
- "endpoint.svg",
- { type: "image/svg+xml" },
- ),
- ),
- example.color,
- );
- const graph = page.getByRole("application", { name: "Tone curve" });
- await graph.evaluate((element) =>
- element.scrollIntoView({ block: "center" }),
- );
- const bounds = await graph.boundingBox();
- if (!bounds) {
- throw new Error("Curve graph is not visible.");
- }
- const screen = (point: { x: number; y: number }) => ({
- x: bounds.x + point.x * bounds.width,
- y: bounds.y + (1 - point.y) * bounds.height,
- });
- const start = screen(example.start);
- const vertical = screen(example.vertical);
- const horizontal = screen(example.horizontal);
- await page.mouse.move(start.x, start.y);
- await page.mouse.down();
- await page.mouse.move(vertical.x, vertical.y, { steps: 5 });
- await page.mouse.up();
- const moved = await page.evaluate(
- (index) => window.openlight.getState().toneCurve[index],
- example.index,
- );
- expect(moved.x).toBeCloseTo(example.vertical.x, 2);
- expect(moved.y).toBeCloseTo(example.vertical.y, 2);
- await expect
- .poll(async () =>
- Math.max(
- ...(await centerPixel(page))
- .slice(0, 3)
- .map((value) => Math.abs(value - example.expected)),
- ),
- )
- .toBeLessThan(2);
- await graph.dblclick({
- position: {
- x: example.vertical.x * bounds.width,
- y: (1 - example.vertical.y) * bounds.height,
- },
- });
- await expect(graph.locator("circle")).toHaveCount(2);
- expect(
- await page.evaluate(
- (index) => window.openlight.getState().toneCurve[index],
- example.index,
- ),
- ).toEqual(example.start);
- await page.mouse.move(start.x, start.y);
- await page.mouse.down();
- await page.mouse.move(horizontal.x, horizontal.y, { steps: 5 });
- await page.mouse.up();
- const shifted = await page.evaluate(
- (index) => window.openlight.getState().toneCurve[index],
- example.index,
- );
- expect(shifted.x).toBeCloseTo(example.horizontal.x, 2);
- expect(shifted.y).toBeCloseTo(example.horizontal.y, 2);
- await graph.dblclick({
- position: {
- x: example.horizontal.x * bounds.width,
- y: (1 - example.horizontal.y) * bounds.height,
- },
- });
- expect(
- await page.evaluate(() => window.openlight.getState().toneCurve),
- ).toEqual([
- { x: 0, y: 0 },
- { x: 1, y: 1 },
- ]);
- }
-});
diff --git a/tests/curves.test.ts b/tests/curves.test.ts
index b08cc2b..66e4355 100644
--- a/tests/curves.test.ts
+++ b/tests/curves.test.ts
@@ -2,35 +2,30 @@ import { expect, test } from "@playwright/test";
import { sampleCurve } from "@/features/tone-curves/curve";
import { interpolatePchip } from "@/lib/math";
-test("the diagonal samples to identity, including black and white", () => {
- const points = [
+test("curves interpolate smoothly through their handles without overshoot", () => {
+ const identity = [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
];
- const samples = sampleCurve(points, 257);
+ const samples = sampleCurve(identity, 257);
expect(samples).toBeInstanceOf(Float32Array);
for (let i = 0; i < samples.length; i++) {
expect(samples[i]).toBeCloseTo(i / 256, 7);
}
-});
-test("a midtone lift interpolates the handles with a smooth cubic", () => {
- const evaluate = interpolatePchip([
+ const lift = interpolatePchip([
{ x: 0, y: 0 },
{ x: 0.5, y: 0.75 },
{ x: 1, y: 1 },
]);
- expect(evaluate(0.25)).toBeCloseTo(0.453125, 7);
- expect(evaluate(0.5)).toBe(0.75);
- expect(evaluate(0.75)).toBeCloseTo(0.921875, 7);
- expect(evaluate(-1)).toBe(0);
- expect(evaluate(2)).toBe(1);
- const leftSlope = (evaluate(0.5) - evaluate(0.5 - 0.00001)) / 0.00001;
- const rightSlope = (evaluate(0.5 + 0.00001) - evaluate(0.5)) / 0.00001;
+ expect(lift(0.25)).toBeCloseTo(0.453125, 7);
+ expect(lift(0.5)).toBe(0.75);
+ expect(lift(0.75)).toBeCloseTo(0.921875, 7);
+ expect(lift(-1)).toBe(0);
+ expect(lift(2)).toBe(1);
+ const leftSlope = (lift(0.5) - lift(0.5 - 0.00001)) / 0.00001;
+ const rightSlope = (lift(0.5 + 0.00001) - lift(0.5)) / 0.00001;
expect(leftSlope).toBeCloseTo(rightSlope, 3);
-});
-
-test("unevenly spaced points, plateaus, and reversals do not overshoot", () => {
const points = [
{ x: 0, y: 0 },
{ x: 0.02, y: 0.4 },
diff --git a/tests/documents.test.ts b/tests/documents.test.ts
new file mode 100644
index 0000000..33df7e3
--- /dev/null
+++ b/tests/documents.test.ts
@@ -0,0 +1,98 @@
+import { expect, test } from "@playwright/test";
+import { createDocument } from "@/app/document";
+import { setAdjustments, setToneCurve } from "@/app/document/edits";
+import { defaultAdjustments } from "@/app/scene";
+import { createWorkspace } from "@/app/workspace";
+import { defaultCurve } from "@/features/tone-curves/curve";
+
+function document() {
+ return createDocument({
+ size: [32, 32],
+ source: "image-1",
+ adjustments: { ...defaultAdjustments },
+ toneCurve: defaultCurve,
+ });
+}
+
+test("documents edit independently without React, retain bounded history, and reject edits after replacement", async () => {
+ const first = document();
+ const second = document();
+ setAdjustments(first, { exposure: 1 });
+ const points = [
+ { x: 0, y: 0 },
+ { x: 0.5, y: 0.7 },
+ { x: 1, y: 1 },
+ ];
+ setToneCurve(first, points);
+ points[1].y = 0.2;
+ expect(first.scene.getState().toneCurve[1].y).toBe(0.7);
+ expect(second.scene.getState().adjustments.exposure).toBe(0);
+ expect(second.history.status.getState().undoCount).toBe(0);
+ const unchanged = first.scene.getState();
+ for (const curve of [
+ [],
+ [{ x: 0, y: 0 }],
+ [
+ { x: 0, y: 0 },
+ { x: 0, y: 1 },
+ ],
+ [
+ { x: 0, y: 0 },
+ { x: 1 / 2048, y: 1 },
+ ],
+ [
+ { x: 0, y: 0 },
+ { x: 0.8, y: 0.5 },
+ { x: 0.5, y: 1 },
+ ],
+ [
+ { x: 0, y: 0 },
+ { x: 1, y: Number.NaN },
+ ],
+ [
+ { x: 0, y: -1 },
+ { x: 1, y: 1 },
+ ],
+ [
+ { x: 0.1, y: 0.1 },
+ { x: 1, y: 1 },
+ ],
+ [
+ { x: 0, y: 0 },
+ { x: 0.9, y: 0.9 },
+ ],
+ ]) {
+ expect(() => setToneCurve(first, curve)).toThrow();
+ }
+ expect(first.scene.getState()).toBe(unchanged);
+ first.history.undo();
+ expect(first.scene.getState().toneCurve).toEqual(defaultCurve);
+ for (let i = 0; i < 150; i++) setAdjustments(first, { exposure: i % 2 });
+ expect(first.history.status.getState().undoCount).toBe(100);
+ for (let i = 0; i < 100; i++) first.history.undo();
+ expect(first.history.status.getState()).toEqual({
+ undoCount: 0,
+ redoCount: 100,
+ });
+ setAdjustments(first, { contrast: 10 });
+ expect(first.history.status.getState()).toEqual({
+ undoCount: 1,
+ redoCount: 0,
+ });
+ const workspace = createWorkspace();
+ await workspace.open("first", async () => first);
+ const stale = document();
+ let release = () => {};
+ const pending = new Promise<typeof stale>((resolve) => {
+ release = () => resolve(stale);
+ });
+ const loading = workspace.open("slow", () => pending);
+ await workspace.open("second", async () => second);
+ release();
+ await loading;
+ expect(() => setAdjustments(stale, { exposure: 2 })).toThrow("closed");
+ expect(workspace.getDocument()).toBe(second);
+ expect(() => setAdjustments(first, { exposure: 2 })).toThrow("closed");
+ workspace.dispose();
+ expect(() => setAdjustments(second, { exposure: 2 })).toThrow("closed");
+});
diff --git a/tests/editing.e2e.ts b/tests/editing.e2e.ts
new file mode 100644
index 0000000..d69d20e
--- /dev/null
+++ b/tests/editing.e2e.ts
@@ -0,0 +1,252 @@
+import { readFile } from "node:fs/promises";
+import { interpolatePchip } from "@/lib/math";
+import { expect, test } from "./fixtures";
+import { readImage } from "./images";
+
+test("edit a photo, inspect the preview and histograms, undo changes, and export", async ({
+ page,
+}) => {
+ await page.goto("/");
+ await expect(page.getByRole("button", { name: "Open image" })).toBeVisible();
+ await page
+ .locator('input[type="file"]')
+ .setInputFiles("tests/fixtures/photo.svg");
+ const canvas = page.locator("canvas");
+ const output = page
+ .getByLabel("output histogram", { exact: true })
+ .locator("polyline")
+ .first();
+ await expect(
+ page.getByLabel("output histogram", { exact: true }).locator("polygon"),
+ ).toHaveCount(3);
+ 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());
+ expect((await readImage(page)).center).toEqual([128, 128, 128, 255]);
+
+ await test.step("exposure moves the preview and RGB histogram, then resets", async () => {
+ const exposure = page.getByRole("slider", {
+ name: "Exposure",
+ exact: true,
+ });
+ await exposure.focus();
+ 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);
+ 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 page.mouse.up();
+ expect(
+ (await page.evaluate(() => window.openlight.getState())).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);
+ await page.keyboard.press("ControlOrMeta+z");
+ await expect.poll(() => canvas.screenshot()).toEqual(original);
+ await page.keyboard.press("ControlOrMeta+Shift+z");
+ await expect.poll(() => canvas.screenshot()).not.toEqual(original);
+ await exposure.dblclick();
+ await expect(exposure).toHaveValue("0");
+ await expect(output).toHaveAttribute("points", histogram ?? "");
+ await expect.poll(() => canvas.screenshot()).toEqual(original);
+ });
+
+ await test.step("light and color controls render together and reset", async () => {
+ for (const [label, value] of [
+ ["Highlights", -50],
+ ["Shadows", 50],
+ ["Whites", 25],
+ ["Blacks", -25],
+ ] as const) {
+ const field = page.getByRole("textbox", { name: label, exact: true });
+ await field.fill(String(value));
+ await field.press("Enter");
+ await expect(
+ page.getByRole("slider", { name: label, exact: true }),
+ ).toHaveValue(String(value));
+ }
+ await page.evaluate(() =>
+ window.openlight.setAdjustments({
+ contrast: 20,
+ incrementalTemperature: 15,
+ incrementalTint: -10,
+ vibrance: 30,
+ saturation: -20,
+ }),
+ );
+ await expect.poll(() => canvas.screenshot()).not.toEqual(original);
+ await expect(output).not.toHaveAttribute("points", histogram ?? "");
+ const edited = await readImage(page);
+ expect(edited.center).not.toEqual([128, 128, 128, 255]);
+ await page.evaluate(
+ (adjustments) => window.openlight.setAdjustments(adjustments),
+ initial.adjustments,
+ );
+ await expect.poll(() => canvas.screenshot()).toEqual(original);
+ });
+
+ await test.step("curve gestures change output after adjustments and undo as one edit", async () => {
+ await page.evaluate(() =>
+ window.openlight.setAdjustments({ exposure: -1 }),
+ );
+ const adjusted = await readImage(page);
+ const graph = page.getByRole("application", { name: "Tone curve" });
+ await graph.scrollIntoViewIfNeeded();
+ const input = page
+ .getByLabel("input histogram", { exact: true })
+ .locator("polyline");
+ await expect(input).toHaveAttribute("points", /,\d{1,2}\./);
+ const inputBefore = await input.getAttribute("points");
+ const before = await page.evaluate(
+ () => window.openlight.getState().history.undoCount,
+ );
+ 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 page.mouse.up();
+ await expect(graph.locator("circle")).toHaveCount(3);
+ expect(
+ (await page.evaluate(() => window.openlight.getState())).history
+ .undoCount,
+ ).toBe(before + 1);
+ await expect(input).toHaveAttribute("points", inputBefore ?? "");
+ const curved = await readImage(page);
+ const curve = await page.evaluate(
+ () => window.openlight.getState().toneCurve,
+ );
+ const expected = interpolatePchip(curve)(adjusted.center[0] / 255) * 255;
+ expect(Math.abs(curved.center[0] - expected)).toBeLessThan(2);
+ await page.keyboard.press("ControlOrMeta+z");
+ expect(await readImage(page)).toEqual(adjusted);
+ await page.keyboard.press("ControlOrMeta+Shift+z");
+ expect(await readImage(page)).toEqual(curved);
+ await graph.press("Shift+ArrowDown");
+ await graph.press("Delete");
+ await expect(graph.locator("circle")).toHaveCount(2);
+ expect(await readImage(page)).toEqual(adjusted);
+ await graph.press("Enter");
+ await graph.press("ArrowUp");
+ await expect(graph.locator("circle")).toHaveCount(3);
+ await page.getByRole("button", { name: "Reset curve" }).click();
+ await expect(graph.locator("circle")).toHaveCount(2);
+ await page.evaluate(() => window.openlight.setAdjustments({ exposure: 0 }));
+ await expect.poll(() => canvas.screenshot()).toEqual(original);
+ for (const { from, to, sample, expected } of [
+ { 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 page.mouse.up();
+ expect(
+ Math.abs((await readImage(page))[sample][0] - expected),
+ ).toBeLessThan(2);
+ await graph.dblclick({
+ position: { x: to[0] * bounds.width, y: to[1] * bounds.height },
+ });
+ expect(
+ await page.evaluate(() => window.openlight.getState().toneCurve),
+ ).toEqual(initial.toneCurve);
+ }
+ });
+
+ await test.step("export retains edits and original dimensions independently of viewport zoom", async () => {
+ await page.evaluate(() => {
+ window.openlight.beginEdit();
+ window.openlight.setAdjustments({
+ exposure: 1,
+ highlights: -20,
+ shadows: 30,
+ whites: 10,
+ blacks: -5,
+ });
+ window.openlight.setToneCurve([
+ { x: 0, y: 0 },
+ { x: 0.5, y: 0.75 },
+ { x: 1, y: 1 },
+ ]);
+ window.openlight.commitEdit();
+ });
+ const expected = await readImage(page);
+ expect(expected.center[0]).toBeGreaterThan(190);
+ 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");
+ const trigger = page.getByRole("button", { name: "Export", exact: true });
+ const dialog = page.getByRole("dialog", { name: "Export image" });
+ const sizes: number[] = [];
+ for (const quality of [null, 20, 95]) {
+ await trigger.click();
+ if (quality !== null) {
+ await dialog.getByText("Smaller files", { exact: true }).click();
+ const field = dialog.getByRole("textbox", { name: "Quality" });
+ await field.fill(String(quality));
+ await field.press("Enter");
+ }
+ const pending = page.waitForEvent("download");
+ await dialog.getByRole("button", { name: "Save image" }).click();
+ const download = await pending;
+ expect(download.suggestedFilename()).toBe(
+ quality === null ? "export.png" : "export.jpg",
+ );
+ const path = await download.path();
+ if (!path) throw new Error("Missing image download.");
+ const bytes = await readFile(path);
+ const actual = await readImage(page, bytes);
+ expect(actual.size).toEqual([1200, 800]);
+ expect(
+ Math.abs(actual.center[0] - expected.center[0]),
+ ).toBeLessThanOrEqual(3);
+ if (quality === null) expect(actual).toEqual(expected);
+ else sizes.push(bytes.length);
+ await expect(dialog).toBeHidden();
+ await expect(trigger).toBeFocused();
+ }
+ expect(sizes[1]).toBeGreaterThan(sizes[0]);
+ await trigger.click();
+ await expect(dialog.getByRole("slider", { name: "Quality" })).toHaveValue(
+ "95",
+ );
+ await page.keyboard.press("Escape");
+ await expect(dialog).toBeHidden();
+ });
+});
diff --git a/tests/endpoints.e2e.ts b/tests/endpoints.e2e.ts
deleted file mode 100644
index 48fac21..0000000
--- a/tests/endpoints.e2e.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { expect, test } from "./fixtures";
-
-test("black and white points preserve midgray, clip or lift endpoints, and reset", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- const outputs = await page.evaluate(async () => {
- const canvas = new OffscreenCanvas(256, 2);
- const context = canvas.getContext("2d");
- if (!context) throw new Error("Cannot create tone ramp.");
- const pixels = context.createImageData(256, 2);
- for (let x = 0; x < 256; x++) {
- pixels.data.set([x, x, x, 255], x * 4);
- pixels.data.set(
- [x, Math.max(0, x - 10), Math.max(0, x - 20), 255],
- (256 + x) * 4,
- );
- }
- context.putImageData(pixels, 0, 0);
- await window.openlight.loadImage(
- new File([await canvas.convertToBlob()], "ramp.png", {
- type: "image/png",
- }),
- );
- const outputs = [];
- for (const [whites, blacks] of [
- [0, 0],
- [100, 0],
- [-100, 0],
- [0, -100],
- [0, 100],
- [100, -100],
- [-100, 100],
- [0, 0],
- ]) {
- window.openlight.setAdjustments({ whites, blacks });
- const image = await createImageBitmap(
- await window.openlight.exportImage(),
- );
- context.drawImage(image, 0, 0);
- image.close();
- outputs.push([...context.getImageData(0, 0, 256, 2).data]);
- }
- return outputs;
- });
- const [
- original,
- whiteClip,
- whiteLower,
- blackClip,
- blackLift,
- clipped,
- compressed,
- reset,
- ] = outputs;
- for (const output of outputs) {
- for (let x = 0; x < 256; x++) {
- const [red, green, blue, alpha] = output.slice(x * 4, x * 4 + 4);
- expect(
- Math.max(red, green, blue) - Math.min(red, green, blue),
- ).toBeLessThanOrEqual(1);
- expect(alpha).toBe(255);
- if (x > 0) {
- const step = red - output[(x - 1) * 4];
- expect(step).toBeGreaterThanOrEqual(0);
- expect(step).toBeLessThanOrEqual(3);
- }
- }
- expect(output.slice(128 * 4, 128 * 4 + 4)).toEqual([128, 128, 128, 255]);
- }
- for (let x = 0; x < 256; x++) {
- expect(original[x * 4]).toBe(x);
- if (x <= 127) expect(whiteClip[x * 4]).toBe(x);
- if (x <= 127) expect(whiteLower[x * 4]).toBe(x);
- if (x >= 128) expect(blackClip[x * 4]).toBe(x);
- if (x >= 128) expect(blackLift[x * 4]).toBe(x);
- }
- for (const output of [whiteClip, clipped]) {
- expect(output[230 * 4]).toBe(255);
- expect(output.slice((256 + 255) * 4)).toEqual([255, 255, 255, 255]);
- }
- for (const output of [blackClip, clipped]) {
- expect(output[25 * 4]).toBe(0);
- expect(output.slice((256 + 25) * 4, (256 + 26) * 4)).toEqual([
- 0, 0, 0, 255,
- ]);
- }
- for (const output of [blackLift, compressed]) {
- expect(output[0]).toBeGreaterThanOrEqual(25);
- expect(output[0]).toBeLessThanOrEqual(26);
- }
- for (const output of [whiteLower, compressed]) {
- expect(output[255 * 4]).toBeGreaterThanOrEqual(229);
- expect(output[255 * 4]).toBeLessThanOrEqual(230);
- }
- expect(reset).toEqual(original);
-});
diff --git a/tests/export.e2e.ts b/tests/export.e2e.ts
deleted file mode 100644
index 3ad1f4b..0000000
--- a/tests/export.e2e.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { expect, test } from "./fixtures";
-
-test("exports full-resolution PNGs with current edits through the API and button", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- await page.evaluate(async () => {
- await window.openlight.loadImage(
- new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800"><rect width="1200" height="800" fill="#808080"/><rect width="100" height="100" fill="black"/></svg>',
- ],
- "photo.original.svg",
- { type: "image/svg+xml" },
- ),
- );
- });
- const button = page.getByRole("button", { name: "Export", exact: true });
- await expect(button).toBeVisible();
- const original = await page.evaluate(async () => {
- const file = await window.openlight.exportImage();
- const image = await createImageBitmap(file);
- const canvas = new OffscreenCanvas(image.width, image.height);
- const context = canvas.getContext("2d");
- if (!context) throw new Error("Cannot read exported image.");
- context.drawImage(image, 0, 0);
- image.close();
- return [...context.getImageData(600, 400, 1, 1).data];
- });
- expect(original).toEqual([128, 128, 128, 255]);
- await page.evaluate(() => {
- window.openlight.setAdjustments({
- exposure: 1,
- highlights: -20,
- shadows: 30,
- whites: 10,
- blacks: -5,
- });
- window.openlight.setToneCurve([
- { x: 0, y: 0 },
- { x: 0.5, y: 0.75 },
- { x: 1, y: 1 },
- ]);
- });
- // The viewport may be zoomed; exporting still includes the original image edges.
- await page.locator("canvas").hover();
- await page.keyboard.down("Control");
- await page.mouse.wheel(0, -100);
- await page.keyboard.up("Control");
- const pending = page.waitForEvent("download");
- await button.click();
- await page.getByRole("button", { name: "Save image" }).click();
- const download = await pending;
- expect(download.suggestedFilename()).toBe("export.png");
- const path = await download.path();
- if (!path) throw new Error("Missing downloaded PNG.");
- const pixels = await page.evaluate(
- async (bytes) => {
- const image = await createImageBitmap(
- new Blob([new Uint8Array(bytes)], { type: "image/png" }),
- );
- const canvas = new OffscreenCanvas(image.width, image.height);
- const context = canvas.getContext("2d");
- if (!context) throw new Error("Cannot read exported image.");
- context.drawImage(image, 0, 0);
- image.close();
- return {
- size: [canvas.width, canvas.height],
- center: [...context.getImageData(600, 400, 1, 1).data],
- corner: [...context.getImageData(10, 10, 1, 1).data],
- };
- },
- [...(await readFile(path))],
- );
- expect(pixels.size).toEqual([1200, 800]);
- expect(pixels.corner).toEqual([0, 0, 0, 255]);
- // Exposure alone produces about 175; the lifted curve must also be present.
- expect(pixels.center[0]).toBeGreaterThan(190);
- expect(pixels.center[0]).toBeLessThan(255);
- expect(pixels.center[3]).toBe(255);
- await expect(button).toBeEnabled();
-});
-
-test("export dialog selects JPEG quality, preserves settings, and dismisses", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- await page.evaluate(async () => {
- const canvas = new OffscreenCanvas(256, 256);
- const context = canvas.getContext("2d");
- if (!context) throw new Error("Cannot create test image.");
- const pixels = context.createImageData(256, 256);
- for (let i = 0; i < pixels.data.length; i += 4) {
- pixels.data[i] = (i * 31) % 251;
- pixels.data[i + 1] = (i * 17) % 253;
- pixels.data[i + 2] = (i * 7) % 255;
- pixels.data[i + 3] = 255;
- }
- context.putImageData(pixels, 0, 0);
- await window.openlight.loadImage(
- new File([await canvas.convertToBlob()], "texture.png", {
- type: "image/png",
- }),
- );
- });
- const trigger = page.getByRole("button", { name: "Export", exact: true });
- const dialog = page.getByRole("dialog", { name: "Export image" });
- await trigger.click();
- await expect(dialog.getByRole("radio", { name: /png/i })).toBeChecked();
- await expect(dialog.getByRole("slider", { name: "Quality" })).toBeHidden();
- await dialog.getByText("Smaller files", { exact: true }).click();
- const quality = dialog.getByRole("slider", { name: "Quality" });
- await expect(quality).toHaveValue("90");
- const sizes: number[] = [];
- for (const value of [20, 95]) {
- await dialog.getByRole("textbox", { name: "Quality" }).fill(String(value));
- await dialog.getByRole("textbox", { name: "Quality" }).press("Enter");
- const pending = page.waitForEvent("download");
- await dialog.getByRole("button", { name: "Save image" }).click();
- const download = await pending;
- expect(download.suggestedFilename()).toBe("export.jpg");
- const path = await download.path();
- if (!path) throw new Error("Missing JPEG download.");
- const bytes = await readFile(path);
- expect([...bytes.subarray(0, 3)]).toEqual([255, 216, 255]);
- sizes.push(bytes.length);
- await expect(dialog).toBeHidden();
- await expect(trigger).toBeFocused();
- await trigger.click();
- await expect(quality).toHaveValue(String(value));
- }
- expect(sizes[1]).toBeGreaterThan(sizes[0]);
- await page.keyboard.press("Escape");
- await expect(dialog).toBeHidden();
- await expect(trigger).toBeFocused();
- await trigger.click();
- await dialog.getByRole("button", { name: "Cancel" }).click();
- await expect(dialog).toBeHidden();
- const result = await page.evaluate(async () => {
- const file = await window.openlight.exportImage({
- format: "jpeg",
- quality: 80,
- });
- const image = await createImageBitmap(file);
- const size = [image.width, image.height];
- image.close();
- return { name: file.name, type: file.type, size };
- });
- expect(result).toEqual({
- name: "export.jpg",
- type: "image/jpeg",
- size: [256, 256],
- });
-});
diff --git a/tests/fixtures/photo.svg b/tests/fixtures/photo.svg
new file mode 100644
index 0000000..be4968c
--- /dev/null
+++ b/tests/fixtures/photo.svg
@@ -0,0 +1,8 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800">
+ <title>Photo editing test chart</title>
+ <rect width="1200" height="800" fill="#808080"/>
+ <rect width="200" height="800" fill="#202020"/>
+ <rect x="1000" width="200" height="800" fill="#e0e0e0"/>
+ <rect width="100" height="100" fill="black"/>
+ <rect x="250" y="100" width="200" height="200" fill="#305080"/>
+</svg>
diff --git a/tests/fixtures/tones.png b/tests/fixtures/tones.png
new file mode 100644
index 0000000..af9bd43
Binary files /dev/null and b/tests/fixtures/tones.png differ
diff --git a/tests/formats/heic.e2e.ts b/tests/heic.e2e.ts
similarity index 92%
rename from tests/formats/heic.e2e.ts
rename to tests/heic.e2e.ts
index de39c13..339f4c3 100644
--- a/tests/formats/heic.e2e.ts
+++ b/tests/heic.e2e.ts
@@ -1,11 +1,11 @@
import { readFile } from "node:fs/promises";
-import { expect, test } from "@playwright/test";
+import { expect, test } from "./fixtures";
test("loads a HEIC image with the expected dimensions and pixels", async ({
page,
}) => {
const bytes = await readFile(
- new URL("../fixtures/patches.heic", import.meta.url),
+ new URL("./fixtures/patches.heic", import.meta.url),
);
await page.goto("/");
await page.waitForFunction(() => window.openlight);
diff --git a/tests/highlights-shadows.e2e.ts b/tests/highlights-shadows.e2e.ts
deleted file mode 100644
index 57a275a..0000000
--- a/tests/highlights-shadows.e2e.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-import { expect, test } from "./fixtures";
-
-function linear(value: number) {
- const encoded = value / 255;
- return encoded <= 0.04045
- ? encoded / 12.92
- : ((encoded + 0.055) / 1.055) ** 2.4;
-}
-
-test("highlights preserve ramps, compose with preparation, and reset", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- const result = await page.evaluate(async () => {
- // The same bright patch appears on two backgrounds, above a translucent row.
- const width = 1025;
- const height = 513;
- const canvas = new OffscreenCanvas(width, height);
- const context = canvas.getContext("2d");
- if (!context) throw new Error("Cannot create highlights fixture.");
- const pixels = context.createImageData(width, height);
- for (let y = 0; y < height; y++) {
- for (let x = 0; x < width; x++) {
- const patch = Math.abs(x - 256) < 32 || Math.abs(x - 768) < 32;
- const background = x < 512 ? 64 : 248;
- let value = patch && Math.abs(y - 256) < 32 ? 240 : background;
- if (y < 64) value = Math.round((x * 255) / (width - 1));
- pixels.data.set(
- [value, value, value, y === height - 1 ? 128 : 255],
- (y * width + x) * 4,
- );
- }
- }
- context.putImageData(pixels, 0, 0);
- context.fillStyle = "rgb(200, 230, 200)";
- context.fillRect(0, height - 2, width, 1);
- const file = new File([await canvas.convertToBlob()], "contexts.png", {
- type: "image/png",
- });
- const read = async () => {
- const bitmap = await createImageBitmap(
- await window.openlight.exportImage(),
- );
- context.clearRect(0, 0, width, height);
- context.drawImage(bitmap, 0, 0);
- bitmap.close();
- return [...context.getImageData(0, 0, width, height).data];
- };
- await window.openlight.loadImage(file);
- const neutral = await read();
- window.openlight.setAdjustments({ highlights: -100 });
- const negative = await read();
- window.openlight.setAdjustments({ highlights: -50 });
- const half = await read();
- window.openlight.setAdjustments({ highlights: 100 });
- const positive = await read();
- window.openlight.setAdjustments({ highlights: 0, shadows: 100 });
- const liftedShadows = await read();
- window.openlight.setAdjustments({ shadows: 50 });
- const halfShadows = await read();
- const prepared = {
- highlights: -75,
- shadows: 0,
- exposure: 0.4,
- incrementalTemperature: 20,
- incrementalTint: -12,
- };
- window.openlight.setAdjustments(prepared);
- const changed = await read();
- await window.openlight.loadImage(file);
- window.openlight.setAdjustments(prepared);
- const fresh = await read();
- window.openlight.setAdjustments({
- highlights: 0,
- exposure: 0,
- incrementalTemperature: 0,
- incrementalTint: 0,
- });
- const reset = await read();
- const patchIndices = [226, 738].map((x) => (256 * width + x) * 4);
- return {
- neutral: patchIndices.map((i) => neutral[i]),
- negative: patchIndices.map((i) => negative[i]),
- positive: patchIndices.map((i) => positive[i]),
- shadowRamps: [halfShadows, liftedShadows].map((output) =>
- Array.from({ length: width }, (_, x) => output[(32 * width + x) * 4]),
- ),
- reloadMatches: changed.every((value, i) => value === fresh[i]),
- ramps: [neutral, negative, half, positive].map((output) =>
- Array.from({ length: width }, (_, x) => output[(32 * width + x) * 4]),
- ),
- resetMatches: reset.every((value, i) => value === neutral[i]),
- alphaMatches: [negative, positive, changed, fresh].every((output) =>
- output.every((value, i) => i % 4 !== 3 || value === neutral[i]),
- ),
- neutralColors: [negative, positive].every((output) =>
- output
- .slice(32 * width * 4, 33 * width * 4)
- .every(
- (value, i) =>
- i % 4 === 3 || Math.abs(value - output[i - (i % 4)]) <= 1,
- ),
- ),
- pastel: [neutral, negative, half].map((output) =>
- output.slice((height - 2) * width * 4, (height - 2) * width * 4 + 3),
- ),
- };
- });
- expect(result.neutral).toEqual([240, 240]);
- expect(result.positive[0]).toBe(result.positive[1]);
- for (const value of result.negative) expect(value).toBeLessThan(240);
- for (const value of result.positive) expect(value).toBeGreaterThan(240);
- const [neutral, negative, half, positive] = result.ramps;
- const [halfShadows, liftedShadows] = result.shadowRamps;
- for (const ramp of result.ramps) {
- expect(ramp[0]).toBe(0);
- for (let x = 1; x < ramp.length; x++) {
- expect(ramp[x] - ramp[x - 1]).toBeGreaterThanOrEqual(-1);
- expect(ramp[x] - ramp[x - 1]).toBeLessThanOrEqual(6);
- }
- }
- for (let x = 0; x < neutral.length; x++) {
- expect(liftedShadows[x]).toBeGreaterThanOrEqual(neutral[x]);
- expect(halfShadows[x]).toBeGreaterThanOrEqual(neutral[x]);
- expect(halfShadows[x]).toBeLessThanOrEqual(liftedShadows[x]);
- expect(
- Math.abs(
- linear(halfShadows[x]) -
- (linear(neutral[x]) + linear(liftedShadows[x])) / 2,
- ),
- ).toBeLessThan(0.01);
- }
- expect(liftedShadows[0]).toBe(0);
- expect(liftedShadows.at(-1)).toBe(255);
- for (let x = 0; x < neutral.length; x++) {
- expect(negative[x]).toBeLessThanOrEqual(half[x]);
- expect(half[x]).toBeLessThanOrEqual(neutral[x]);
- expect(positive[x]).toBeGreaterThanOrEqual(neutral[x]);
- expect(
- Math.abs(
- linear(half[x]) - (linear(neutral[x]) + linear(negative[x])) / 2,
- ),
- ).toBeLessThan(0.01);
- }
- expect(result.reloadMatches).toBe(true);
- expect(result.resetMatches).toBe(true);
- expect(result.alphaMatches).toBe(true);
- expect(result.neutralColors).toBe(true);
- const [pastel, darkened, halfway] = result.pastel;
- expect(Math.abs(darkened[0] - darkened[2])).toBeLessThanOrEqual(1);
- for (let channel = 0; channel < 3; channel++) {
- expect(darkened[channel]).toBeLessThan(pastel[channel]);
- expect(
- Math.abs(
- linear(halfway[channel]) -
- (linear(pastel[channel]) + linear(darkened[channel])) / 2,
- ),
- ).toBeLessThan(0.01);
- }
-});
diff --git a/tests/histogram.e2e.ts b/tests/histogram.e2e.ts
deleted file mode 100644
index f780a69..0000000
--- a/tests/histogram.e2e.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { expect, test } from "@playwright/test";
-
-test("the RGB histogram follows image edits and resets", async ({ page }) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- await page.evaluate(() =>
- window.openlight.loadImage(
- new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',
- ],
- "gray.svg",
- { type: "image/svg+xml" },
- ),
- ),
- );
- const histogram = page.getByLabel("output histogram", { exact: true });
- await expect(histogram).toBeVisible();
- const curves = histogram.locator("polygon");
- await expect(curves).toHaveCount(3);
- for (const curve of await curves.all()) {
- await expect(curve).toBeVisible();
- }
- const original = await curves.first().getAttribute("points");
- if (!original) throw new Error("Missing histogram points.");
- await page.evaluate(() => {
- for (let i = 1; i <= 120; i++) {
- window.openlight.setAdjustments({ exposure: i / 120 });
- }
- });
- await expect(curves.first()).not.toHaveAttribute("points", original);
- await page.evaluate(() => window.openlight.setAdjustments({ exposure: 0 }));
- await expect(curves.first()).toHaveAttribute("points", original);
-});
diff --git a/tests/images.ts b/tests/images.ts
new file mode 100644
index 0000000..9a5845e
--- /dev/null
+++ b/tests/images.ts
@@ -0,0 +1,27 @@
+import type { Page } from "@playwright/test";
+
+/** Read actual exported or downloaded pixels, independently of the renderer. */
+export async function readImage(page: Page, bytes?: Uint8Array) {
+ return page.evaluate(
+ async (bytes) => {
+ const file = bytes
+ ? new Blob([new Uint8Array(bytes)])
+ : await window.openlight.exportImage();
+ const image = await createImageBitmap(file);
+ const canvas = new OffscreenCanvas(image.width, image.height);
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Cannot read image pixels.");
+ context.drawImage(image, 0, 0);
+ image.close();
+ return {
+ size: [canvas.width, canvas.height],
+ center: [
+ ...context.getImageData(canvas.width / 2, canvas.height / 2, 1, 1)
+ .data,
+ ],
+ corner: [...context.getImageData(10, 10, 1, 1).data],
+ };
+ },
+ bytes ? [...bytes] : null,
+ );
+}
diff --git a/tests/loaders.e2e.ts b/tests/loaders.e2e.ts
index 799bb2f..c810c6e 100644
--- a/tests/loaders.e2e.ts
+++ b/tests/loaders.e2e.ts
@@ -1,4 +1,6 @@
-import { expect, type Page, test } from "@playwright/test";
+import type { Page } from "@playwright/test";
+import { expect, test } from "./fixtures";
+import { readImage } from "./images";
type InputFile = { name: string; content: string; type?: string };
@@ -29,7 +31,7 @@ async function openFiles(page: Page, files: InputFile[]) {
}, files);
}
-test("file batches load one image before its settings, regardless of file order", async ({
+test("open image and XMP batches, recover from failures, and replace a document during export", async ({
page,
}) => {
await page.goto("/");
@@ -98,13 +100,6 @@ test("file batches load one image before its settings, regardless of file order"
blacks: 0,
});
}
-});
-
-test("consecutive batches keep settings with their image and recover from a failed image", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
const state = await page.evaluate(
async (batches) => {
await Promise.all(
@@ -149,4 +144,87 @@ test("consecutive batches keep settings with their image and recover from a fail
await expect(
page.getByRole("textbox", { name: "Exposure", exact: true }),
).toHaveValue("-1.00");
+
+ const baseline = await readImage(page);
+ const before = await page.evaluate(() => window.openlight.getState());
+ await page.evaluate(() => {
+ window.openlight.beginEdit();
+ window.openlight.setAdjustments({ exposure: 0.5 });
+ window.openlight.setAdjustments({ exposure: 1, shadows: 20 });
+ window.openlight.setToneCurve([
+ { x: 0, y: 0 },
+ { x: 0.5, y: 0.7 },
+ { x: 1, y: 1 },
+ ]);
+ window.openlight.commitEdit();
+ });
+ const edited = await readImage(page);
+ expect(edited).not.toEqual(baseline);
+ expect(
+ (await page.evaluate(() => window.openlight.getState())).history.undoCount,
+ ).toBe(before.history.undoCount + 1);
+ await page.evaluate(() => window.openlight.undo());
+ expect(await readImage(page)).toEqual(baseline);
+ await page.evaluate(() => window.openlight.redo());
+ expect(await readImage(page)).toEqual(edited);
+ await page.evaluate(() => {
+ window.openlight.setAdjustments({ exposure: 1 });
+ window.openlight.beginEdit();
+ window.openlight.setAdjustments({ exposure: -1 });
+ window.openlight.cancelEdit();
+ });
+ expect(await readImage(page)).toEqual(edited);
+ expect(
+ (await page.evaluate(() => window.openlight.getState())).history.undoCount,
+ ).toBe(before.history.undoCount + 1);
+ await page.evaluate(() => {
+ window.openlight.undo();
+ window.openlight.beginEdit();
+ window.openlight.setAdjustments({ contrast: 20 });
+ });
+ const imported = await openFiles(page, [
+ settings('crs:Highlights2012="-50"'),
+ ]);
+ expect(imported.history).toEqual({
+ undoCount: before.history.undoCount + 2,
+ redoCount: 0,
+ });
+ await page.evaluate(() => window.openlight.undo());
+ expect(
+ (await page.evaluate(() => window.openlight.getState())).adjustments,
+ ).toMatchObject({ highlights: 0, contrast: 20 });
+
+ const expected = await readImage(page);
+ const exported = await page.evaluate(async () => {
+ const api = window.openlight;
+ const convert = OffscreenCanvas.prototype.convertToBlob;
+ let release = () => {};
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ OffscreenCanvas.prototype.convertToBlob = async function (options) {
+ await gate;
+ return convert.call(this, options);
+ };
+ try {
+ const pending = api.exportImage();
+ await api.loadImage(
+ new File(
+ ['<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>'],
+ "replacement.svg",
+ { type: "image/svg+xml" },
+ ),
+ );
+ release();
+ return [...new Uint8Array(await (await pending).arrayBuffer())];
+ } finally {
+ release();
+ OffscreenCanvas.prototype.convertToBlob = convert;
+ }
+ });
+ expect(await readImage(page, new Uint8Array(exported))).toEqual(expected);
+ const replaced = await page.evaluate(() => window.openlight.getState());
+ expect(replaced.documentId).not.toBe(before.documentId);
+ expect(replaced.history).toEqual({ undoCount: 0, redoCount: 0 });
+ expect(replaced.toneCurve).toEqual(before.toneCurve);
});
diff --git a/tests/rendering.e2e.ts b/tests/rendering.e2e.ts
new file mode 100644
index 0000000..7c6d6c0
--- /dev/null
+++ b/tests/rendering.e2e.ts
@@ -0,0 +1,182 @@
+import { readFile } from "node:fs/promises";
+import { expect, test } from "./fixtures";
+
+function linear(value: number) {
+ const encoded = value / 255;
+ return encoded <= 0.04045
+ ? encoded / 12.92
+ : ((encoded + 0.055) / 1.055) ** 2.4;
+}
+
+test("tone adjustments preserve ramps, colors and alpha, compose, and reset", async ({
+ page,
+}) => {
+ await page.goto("/");
+ await page.waitForFunction(() => window.openlight);
+ const bytes = await readFile("tests/fixtures/tones.png");
+ const result = await page.evaluate(
+ async (bytes) => {
+ const api = window.openlight;
+ const file = new File([new Uint8Array(bytes)], "tones.png", {
+ type: "image/png",
+ });
+ await api.loadImage(file);
+ const defaults = api.getState().adjustments;
+ const canvas = new OffscreenCanvas(256, 128);
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Cannot read tone chart.");
+ const read = async () => {
+ const image = await createImageBitmap(await api.exportImage());
+ context.clearRect(0, 0, 256, 128);
+ context.drawImage(image, 0, 0);
+ image.close();
+ return [...context.getImageData(0, 0, 256, 128).data];
+ };
+ const neutral = await read();
+ const outputs = [];
+ for (const change of [
+ {},
+ { whites: 100 },
+ { whites: -100 },
+ { blacks: -100 },
+ { blacks: 100 },
+ { whites: 100, blacks: -100 },
+ { whites: -100, blacks: 100 },
+ { highlights: -100 },
+ { highlights: -50 },
+ { highlights: 100 },
+ { shadows: 50 },
+ { shadows: 100 },
+ ]) {
+ api.setAdjustments({ ...defaults, ...change });
+ const pixels = await read();
+ outputs.push({
+ ramp: Array.from({ length: 256 }, (_, x) => pixels[x * 4]),
+ pastel: pixels.slice(126 * 256 * 4, 126 * 256 * 4 + 3),
+ patches: [64, 192].map((x) => pixels[(96 * 256 + x) * 4]),
+ colorEnds: [25, 255].map((x) =>
+ pixels.slice((125 * 256 + x) * 4, (125 * 256 + x) * 4 + 3),
+ ),
+ alphaMatches: pixels.every(
+ (value, i) => i % 4 !== 3 || value === neutral[i],
+ ),
+ grayMatches: pixels
+ .slice(0, 256 * 4)
+ .every(
+ (value, i) =>
+ i % 4 === 3 || Math.abs(value - pixels[i - (i % 4)]) <= 1,
+ ),
+ });
+ }
+ const prepared = {
+ ...defaults,
+ highlights: -75,
+ exposure: 0.4,
+ incrementalTemperature: 20,
+ incrementalTint: -12,
+ };
+ api.setAdjustments(prepared);
+ const edited = await read();
+ await api.loadImage(file);
+ api.setAdjustments(prepared);
+ const fresh = await read();
+ api.setAdjustments(defaults);
+ const reset = await read();
+ return {
+ outputs,
+ reloadMatches: edited.every((value, i) => value === fresh[i]),
+ resetMatches: neutral.every((value, i) => value === reset[i]),
+ };
+ },
+ [...bytes],
+ );
+ const [
+ original,
+ whiteClip,
+ whiteLower,
+ blackClip,
+ blackLift,
+ clipped,
+ compressed,
+ negative,
+ half,
+ positive,
+ halfShadows,
+ liftedShadows,
+ ] = result.outputs;
+ for (const output of result.outputs) {
+ expect(output.alphaMatches).toBe(true);
+ expect(output.grayMatches).toBe(true);
+ for (let x = 1; x < 256; x++) {
+ expect(output.ramp[x] - output.ramp[x - 1]).toBeGreaterThanOrEqual(-1);
+ expect(output.ramp[x] - output.ramp[x - 1]).toBeLessThanOrEqual(6);
+ }
+ }
+ for (const output of result.outputs.slice(0, 7))
+ expect(output.ramp[128]).toBe(128);
+ for (let x = 0; x < 256; x++) {
+ expect(original.ramp[x]).toBe(x);
+ if (x <= 127) {
+ expect(whiteClip.ramp[x]).toBe(x);
+ expect(whiteLower.ramp[x]).toBe(x);
+ } else {
+ expect(blackClip.ramp[x]).toBe(x);
+ expect(blackLift.ramp[x]).toBe(x);
+ }
+ expect(negative.ramp[x]).toBeLessThanOrEqual(half.ramp[x]);
+ expect(half.ramp[x]).toBeLessThanOrEqual(x);
+ expect(positive.ramp[x]).toBeGreaterThanOrEqual(x);
+ expect(halfShadows.ramp[x]).toBeGreaterThanOrEqual(x);
+ expect(halfShadows.ramp[x]).toBeLessThanOrEqual(liftedShadows.ramp[x]);
+ for (const [middle, full] of [
+ [half, negative],
+ [halfShadows, liftedShadows],
+ ]) {
+ expect(
+ Math.abs(
+ linear(middle.ramp[x]) - (linear(x) + linear(full.ramp[x])) / 2,
+ ),
+ ).toBeLessThan(0.01);
+ }
+ }
+ for (const output of [whiteClip, clipped]) {
+ expect(output.ramp[230]).toBe(255);
+ expect(output.colorEnds[1]).toEqual([255, 255, 255]);
+ }
+ for (const output of [blackClip, clipped]) {
+ expect(output.ramp[25]).toBe(0);
+ expect(output.colorEnds[0]).toEqual([0, 0, 0]);
+ }
+ for (const output of [blackLift, compressed]) {
+ expect(output.ramp[0]).toBeGreaterThanOrEqual(25);
+ expect(output.ramp[0]).toBeLessThanOrEqual(26);
+ }
+ for (const output of [whiteLower, compressed]) {
+ expect(output.ramp[255]).toBeGreaterThanOrEqual(229);
+ expect(output.ramp[255]).toBeLessThanOrEqual(230);
+ }
+ expect(original.patches).toEqual([240, 240]);
+ expect(negative.patches[0]).toBe(negative.patches[1]);
+ expect(negative.patches[0]).toBeLessThan(240);
+ expect(positive.patches[0]).toBe(positive.patches[1]);
+ expect(positive.patches[0]).toBeGreaterThan(240);
+ for (const output of [negative, half, positive, liftedShadows])
+ expect(output.ramp[0]).toBe(0);
+ expect(liftedShadows.ramp[255]).toBe(255);
+ expect(Math.abs(negative.pastel[0] - negative.pastel[2])).toBeLessThanOrEqual(
+ 1,
+ );
+ for (let channel = 0; channel < 3; channel++) {
+ expect(negative.pastel[channel]).toBeLessThan(original.pastel[channel]);
+ expect(
+ Math.abs(
+ linear(half.pastel[channel]) -
+ (linear(original.pastel[channel]) +
+ linear(negative.pastel[channel])) /
+ 2,
+ ),
+ ).toBeLessThan(0.01);
+ }
+ expect(result.reloadMatches).toBe(true);
+ expect(result.resetMatches).toBe(true);
+});
diff --git a/tests/smoke.e2e.ts b/tests/smoke.e2e.ts
deleted file mode 100644
index 07c8bbb..0000000
--- a/tests/smoke.e2e.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { expect, test } from "./fixtures";
-
-test("app opens without crashing", async ({ page }) => {
- await page.goto("/");
- await expect(page.getByRole("button", { name: "Open image" })).toBeVisible();
- await page.evaluate(
- () =>
- new Promise<void>((resolve) =>
- requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
- ),
- );
-});
-
-test("browser actions load, adjust, reset, and report failures", async ({
- page,
-}) => {
- await page.goto("/");
- await page.waitForFunction(() => window.openlight);
- await page.evaluate(() => {
- const image = new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/><rect width="8" height="32" fill="#202020"/><rect x="24" width="8" height="32" fill="#e0e0e0"/></svg>',
- ],
- "gray.svg",
- { type: "image/svg+xml" },
- );
- window.openlight.openFile(image);
- return window.openlight.getState();
- });
- await expect(page.locator("polyline").first()).toHaveAttribute(
- "points",
- /,0\.0/,
- );
- const canvas = page.locator("canvas");
- const before = await canvas.screenshot();
- const toneControls = [
- { name: "highlights", label: "Highlights", x: 16, level: 128 },
- { name: "shadows", label: "Shadows", x: 16, level: 128 },
- { name: "whites", label: "Whites", x: 28, level: 224 },
- { name: "blacks", label: "Blacks", x: 4, level: 32 },
- ];
- for (const { name, label, x, level } of toneControls) {
- const slider = page.getByRole("slider", { name: label, exact: true });
- const field = page.getByRole("textbox", { name: label, exact: true });
- await expect(slider).toHaveAttribute("min", "-100");
- await expect(slider).toHaveAttribute("max", "100");
- await expect(slider).toHaveValue("0");
- const pixels: number[] = [];
- for (const value of [-100, 100]) {
- await field.fill(String(value));
- await field.press("Enter");
- await expect(slider).toHaveValue(String(value));
- const state = await page.evaluate(() => window.openlight.getState());
- expect(state.adjustments).toMatchObject({ [name]: value });
- pixels.push(
- await page.evaluate(async (x) => {
- const image = await createImageBitmap(
- await window.openlight.exportImage(),
- );
- const canvas = new OffscreenCanvas(image.width, image.height);
- const context = canvas.getContext("2d");
- if (!context) throw new Error("Cannot read exported image.");
- context.drawImage(image, 0, 0);
- image.close();
- return context.getImageData(x, 16, 1, 1).data[0];
- }, x),
- );
- }
- expect(pixels[0]).toBeLessThan(level);
- expect(pixels[1]).toBeGreaterThan(level);
- await expect.poll(() => canvas.screenshot()).not.toEqual(before);
- await slider.dblclick();
- await expect(field).toHaveValue("0");
- await expect.poll(() => canvas.screenshot()).toEqual(before);
- }
- const histogram = await page
- .locator("polyline")
- .first()
- .getAttribute("points");
- const edited = await page.evaluate(() => {
- window.openlight.setAdjustments({ exposure: -1 });
- window.openlight.setAdjustments({ exposure: 1, saturation: -25 });
- return window.openlight.getState();
- });
- expect(edited.adjustments.exposure).toBe(1);
- await expect(
- page.getByRole("textbox", { name: "Exposure", exact: true }),
- ).toHaveValue("1.00");
- await expect(page.locator("polyline").first()).not.toHaveAttribute(
- "points",
- histogram ?? "",
- );
- expect(await canvas.screenshot()).not.toEqual(before);
- expect(
- await page.locator("polyline").first().getAttribute("points"),
- ).not.toBe(histogram);
- await page.evaluate(() => {
- window.openlight.setAdjustments({ exposure: 0, saturation: 0 });
- });
- await expect.poll(() => canvas.screenshot()).toEqual(before);
- await page.evaluate(async () => {
- window.openlight.setAdjustments({
- highlights: -50,
- shadows: 50,
- whites: 25,
- blacks: -25,
- });
- const superseded = window.openlight.openFile(
- new File(
- ['<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>'],
- "superseded.svg",
- { type: "image/svg+xml" },
- ),
- );
- const latest = window.openlight.openFile(
- new File(["invalid"], "broken.png", { type: "image/png" }),
- );
- await Promise.all([superseded, latest]);
- });
- await expect(
- page.getByText("Couldn't open broken.png:", { exact: false }),
- ).toBeVisible();
- const recovered = await page.evaluate(async () => {
- await window.openlight.openFile(
- new File(
- [
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/><rect width="8" height="32" fill="#202020"/><rect x="24" width="8" height="32" fill="#e0e0e0"/></svg>',
- ],
- "replacement.svg",
- { type: "image/svg+xml" },
- ),
- );
- return window.openlight.getState();
- });
- expect(recovered.file).toBe("replacement.svg");
- expect(recovered.adjustments).toMatchObject({
- highlights: 0,
- shadows: 0,
- whites: 0,
- blacks: 0,
- });
- await expect.poll(() => canvas.screenshot()).toEqual(before);
-});