Skip to content

Free open-source image editor for the browser

Add modular batch loaders and Camera Raw import

Rodrigo513de0fd9d7c
diff --git a/README.md b/README.md
index 4445fce..be7411f 100644
--- a/README.md
+++ b/README.md
@@ -29,15 +29,32 @@ 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 calls the store actions directly:
+components attach their outputs through `useRenderer`. The API exposes application commands and scene actions:
```js
-await openlight.loadImage(new File([bytes], "photo.png", { type: "image/png" }));
+await openlight.openFiles([
+ new File([imageBytes], "photo.png", { type: "image/png" }),
+ new File([xmpText], "photo.xmp"),
+]);
openlight.setAdjustments({ exposure: 1, saturation: -25 });
const state = // Or read immediately: openlight.getState()
```
+`openFiles` is shared by the app-wide drop handler, image picker, and browser
+automation. Each batch opens the first recognized image, then applies all settings
+files in their input order. Additional images are ignored without decoding them.
+Camera Raw settings accept `.xmp` and `.xml` files containing the Camera Raw namespace.
+Settings alone apply to the current image. Unsupported files and settings without
+a loaded image are ignored; a failed image load skips that batch's settings.
+Batches run sequentially, including calls through `openFile`, `loadImage`, and
+`importXmp`, so settings cannot spill onto an image from a later batch.
+
+`app/loaders/registry.ts` owns matching, 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.
+
`setAdjustments` merges a partial update. Exposure accepts -5 to 5; other
adjustments accept -100 to 100. Loading another image resets adjustments.
-State includes the file name and adjustments. `loadImage` starts decoding
-immediately and resolves after decoding finishes; failures appear in the editor. The renderer runs every frame.
+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.
diff --git a/src/app/scene/controls.ts b/src/app/controls.ts
similarity index 59%
rename from src/app/scene/controls.ts
rename to src/app/controls.ts
index 290353f..0ac04a1 100644
--- a/src/app/scene/controls.ts
+++ b/src/app/controls.ts
@@ -4,7 +4,10 @@ import {
type ExportOptions,
exportImage,
} from "@/app/editor/export/export-image";
-import { useScene } from ".";
+import { cameraRawXmpLoader } from "@/app/loaders/camera-raw-xmp";
+import { createImageLoader } from "@/app/loaders/image";
+import { createLoaderRegistry } from "@/app/loaders/registry";
+import { useScene } from "@/app/scene";
function getState() {
const scene = useScene.getState();
@@ -23,16 +26,20 @@ declare global {
export function useControls() {
const gpu = useGpu();
- const controls = useMemo(
- () => ({
- loadImage: (file: File) => useScene.getState().loadImage(gpu, file),
+ 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],
- );
+ };
+ }, [gpu]);
useEffect(() => {
window.openlight = controls;
return () => {
diff --git a/src/app/index.tsx b/src/app/index.tsx
index 36f2079..ec11d48 100644
--- a/src/app/index.tsx
+++ b/src/app/index.tsx
@@ -1,13 +1,15 @@
+import { useFileDrop } from "@/hooks/use-file-drop";
+import { useControls } from "./controls";
import Editor from "./editor";
import Landing from "./landing";
import { useScene } from "./scene";
-import { useControls } from "./scene/controls";
export default function App() {
- const { loadImage } = useControls();
+ const { openFiles } = useControls();
+ useFileDrop(openFiles);
const source = useScene((scene) => scene.source);
if (!source) {
- return <Landing onOpen={loadImage} />;
+ return <Landing onOpen={openFiles} />;
}
return <Editor source={source} />;
}
diff --git a/src/app/landing/index.tsx b/src/app/landing/index.tsx
index 1a9c64d..462998c 100644
--- a/src/app/landing/index.tsx
+++ b/src/app/landing/index.tsx
@@ -1,9 +1,9 @@
-import { type DragEvent, useRef } from "react";
+import { useRef } from "react";
import Button from "@/components/ui/button";
-import { accept, canDecode } from "@/lib/decode";
+import { accept } from "@/lib/decode";
import Backdrop from "./backdrop";
-type OpenProps = { onOpen: (files: FileList | null) => void };
+type OpenProps = { onOpen: (files: File[]) => void };
function OpenImage({ onOpen }: OpenProps) {
const input = useRef<HTMLInputElement>(null);
@@ -15,7 +15,13 @@ function OpenImage({ onOpen }: OpenProps) {
<input
accept={accept}
hidden
- onChange={(event) => onOpen(event.currentTarget.files)}
+ multiple
+ onChange={(event) => {
+ const files = event.currentTarget.files;
+ if (files?.length) {
+ onOpen(Array.from(files));
+ }
+ }}
ref={input}
type="file"
/>
@@ -23,31 +29,14 @@ function OpenImage({ onOpen }: OpenProps) {
);
}
-type LandingProps = { onOpen: (image: File) => void };
-
-export default function Landing({ onOpen }: LandingProps) {
- const open = (files: FileList | null) => {
- const image = files?.[0];
- if (image && canDecode(image)) {
- onOpen(image);
- }
- };
- const drop = (event: DragEvent) => {
- event.preventDefault();
- open(event.dataTransfer.files);
- };
-
+export default function Landing({ onOpen }: OpenProps) {
return (
- <main
- className="relative isolate grid h-full place-content-center justify-items-center gap-3 bg-[radial-gradient(circle,#292929,#131313_55%)]"
- onDragOver={(event) => event.preventDefault()}
- onDrop={drop}
- >
+ <main className="relative isolate grid h-full place-content-center justify-items-center gap-3 bg-[radial-gradient(circle,#292929,#131313_55%)]">
<Backdrop />
<img alt="" className="w-16" height="64" src="/logo.svg" width="64" />
<h1 className="text-2xl font-bold">OpenLight</h1>
<p className="text-neutral-400">Edit photos in your browser.</p>
- <OpenImage onOpen={open} />
+ <OpenImage onOpen={onOpen} />
</main>
);
}
diff --git a/src/app/loaders/camera-raw-xmp.ts b/src/app/loaders/camera-raw-xmp.ts
new file mode 100644
index 0000000..ee0f626
--- /dev/null
+++ b/src/app/loaders/camera-raw-xmp.ts
@@ -0,0 +1,36 @@
+import { type Adjustments, useScene } from "@/app/scene";
+import {
+ type CameraRawXmp,
+ isCameraRawXmp,
+ readCameraRawXmp,
+} from "@/features/camera-raw-xmp/xmp";
+import type { FileLoader } from "./registry";
+
+function toAdjustments(xmp: CameraRawXmp): Partial<Adjustments> {
+ return {
+ ...(xmp.exposure2012 === undefined ? {} : { exposure: xmp.exposure2012 }),
+ ...(xmp.contrast2012 === undefined ? {} : { contrast: xmp.contrast2012 }),
+ ...(xmp.vibrance === undefined ? {} : { vibrance: xmp.vibrance }),
+ ...(xmp.saturation === undefined ? {} : { saturation: xmp.saturation }),
+ };
+}
+
+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 const cameraRawXmpLoader: FileLoader = {
+ kind: "settings",
+ accepts: isCameraRawXmp,
+ load: importCameraRawXmp,
+};
diff --git a/src/app/loaders/image.ts b/src/app/loaders/image.ts
new file mode 100644
index 0000000..391513b
--- /dev/null
+++ b/src/app/loaders/image.ts
@@ -0,0 +1,36 @@
+import type { Gpu } from "vgpu";
+import { defaultAdjustments, useScene } from "@/app/scene";
+import { defaultCurve } from "@/features/tone-curves/curve";
+import decode, { canDecode } from "@/lib/decode";
+import type { FileLoader } from "./registry";
+
+export function createImageLoader(gpu: Gpu): FileLoader {
+ return {
+ kind: "document",
+ accepts: canDecode,
+ load: async (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 {
+ 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) } });
+ }
+ }
+ },
+ };
+}
diff --git a/src/app/loaders/registry.ts b/src/app/loaders/registry.ts
new file mode 100644
index 0000000..2ca1d4d
--- /dev/null
+++ b/src/app/loaders/registry.ts
@@ -0,0 +1,52 @@
+import { useScene } from "@/app/scene";
+
+export type FileLoader = {
+ kind: "document" | "settings";
+ accepts: (file: File) => boolean;
+ load: (file: File) => Promise<void>;
+};
+
+type Job = { file: File; loader: FileLoader };
+
+async function loadBatch(jobs: Job[]) {
+ const document = jobs.find(({ loader }) => loader.kind === "document");
+ if (document) {
+ await document.loader.load(document.file);
+ }
+ if (!useScene.getState().source?.image) {
+ return;
+ }
+ for (const { file, loader } of jobs) {
+ if (loader.kind === "settings") {
+ await loader.load(file);
+ }
+ }
+}
+
+export function createLoaderRegistry(loaders: readonly FileLoader[]) {
+ let pending = Promise.resolve();
+
+ function enqueue(jobs: Job[]) {
+ const result = pending.then(() => loadBatch(jobs));
+ // Return the failure to the caller while allowing later batches to run.
+ pending = result.catch(() => {});
+ return result;
+ }
+
+ function openFiles(files: readonly File[]) {
+ const jobs = files.flatMap((file) => {
+ if (!(file instanceof File)) {
+ throw new Error("openFiles requires Files.");
+ }
+ const loader = loaders.find((loader) => loader.accepts(file));
+ return loader ? [{ file, loader }] : [];
+ });
+ return enqueue(jobs);
+ }
+
+ function loadFile(loader: FileLoader, file: File) {
+ return enqueue([{ file, loader }]);
+ }
+
+ return { openFiles, loadFile };
+}
diff --git a/src/app/scene/index.ts b/src/app/scene/index.ts
index 1e1f873..de371c5 100644
--- a/src/app/scene/index.ts
+++ b/src/app/scene/index.ts
@@ -1,11 +1,10 @@
-import type { Gpu, Target } from "vgpu";
+import type { Target } from "vgpu";
import { create } from "zustand";
import {
defaultCurve,
type ToneCurve,
validateCurve,
} from "@/features/tone-curves/curve";
-import decode from "@/lib/decode";
/** Non-destructive edits: exposure in stops, the rest -100..100. */
export type Adjustments = {
@@ -42,7 +41,6 @@ export type Scene = {
toneCurve: ToneCurve;
};
type SceneStore = Scene & {
- loadImage: (gpu: Gpu, file: File) => Promise<void>;
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;
@@ -51,30 +49,6 @@ type SceneStore = Scene & {
export const useScene = create<SceneStore>((set, get) => ({
adjustments: { ...defaultAdjustments },
toneCurve: defaultCurve,
- loadImage: async (gpu, file) => {
- if (!(file instanceof File)) {
- throw new Error("loadImage requires a File.");
- }
- const source = { file };
- get().source?.image?.color.dispose();
- set({
- source,
- adjustments: { ...defaultAdjustments },
- toneCurve: defaultCurve,
- });
- try {
- const image = await decode(gpu, file);
- if (get().source !== source) {
- image.color.dispose();
- return;
- }
- set({ source: { file, image } });
- } catch (error) {
- if (get().source === source) {
- set({ source: { file, error: String(error) } });
- }
- }
- },
setAdjustments: (change) => {
const { source, adjustments } = get();
if (!source) {
diff --git a/src/features/camera-raw-xmp/xmp.ts b/src/features/camera-raw-xmp/xmp.ts
new file mode 100644
index 0000000..f063a24
--- /dev/null
+++ b/src/features/camera-raw-xmp/xmp.ts
@@ -0,0 +1,38 @@
+const cameraRaw = "http://ns.adobe.com/camera-raw-settings/1.0/";
+const rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
+
+export type CameraRawXmp = {
+ exposure2012?: number;
+ contrast2012?: number;
+ vibrance?: number;
+ saturation?: number;
+};
+
+const attributes = {
+ Exposure2012: "exposure2012",
+ Contrast2012: "contrast2012",
+ Vibrance: "vibrance",
+ Saturation: "saturation",
+} as const satisfies Record<string, keyof CameraRawXmp>;
+
+export function isCameraRawXmp(file: File) {
+ return /\.(xmp|xml)$/i.test(file.name);
+}
+
+export function readCameraRawXmp(text: string): CameraRawXmp {
+ const document = new DOMParser().parseFromString(text, "application/xml");
+ const description = document.getElementsByTagNameNS(rdf, "Description")[0];
+ if (!description) {
+ return {};
+ }
+ return Object.fromEntries(
+ Object.entries(attributes).flatMap(([attribute, setting]) => {
+ const raw = description.getAttributeNS(cameraRaw, attribute);
+ if (raw === null || raw.trim() === "") {
+ return [];
+ }
+ const value = Number(raw);
+ return Number.isFinite(value) ? [[setting, value]] : [];
+ }),
+ );
+}
diff --git a/src/hooks/use-file-drop.ts b/src/hooks/use-file-drop.ts
new file mode 100644
index 0000000..7d02a9c
--- /dev/null
+++ b/src/hooks/use-file-drop.ts
@@ -0,0 +1,19 @@
+import { useEffect } from "react";
+
+export function useFileDrop(onFiles: (files: File[]) => void) {
+ useEffect(() => {
+ const controller = new AbortController();
+ const { signal } = controller;
+ const preventDefault = (event: DragEvent) => event.preventDefault();
+ const drop = (event: DragEvent) => {
+ event.preventDefault();
+ const files = event.dataTransfer?.files;
+ if (files?.length) {
+ onFiles(Array.from(files));
+ }
+ };
+ document.addEventListener("dragover", preventDefault, { signal });
+ document.addEventListener("drop", drop, { signal });
+ return () => controller.abort();
+ }, [onFiles]);
+}
diff --git a/tests/loaders.e2e.ts b/tests/loaders.e2e.ts
new file mode 100644
index 0000000..218cf64
--- /dev/null
+++ b/tests/loaders.e2e.ts
@@ -0,0 +1,133 @@
+import { expect, type Page, test } from "@playwright/test";
+
+type InputFile = { name: string; content: string; type?: string };
+
+function image(name = "photo.svg"): InputFile {
+ return {
+ name,
+ type: "image/svg+xml",
+ content:
+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',
+ };
+}
+
+function settings(attributes: string, name = "photo.xmp"): InputFile {
+ return {
+ name,
+ content: `<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" ${attributes} /></rdf:RDF>`,
+ };
+}
+
+async function openFiles(page: Page, files: InputFile[]) {
+ return page.evaluate(async (files) => {
+ await window.openlight.openFiles(
+ files.map(
+ ({ name, content, type }) => new File([content], name, { type }),
+ ),
+ );
+ return window.openlight.getState();
+ }, files);
+}
+
+test("file batches load one image before its settings, regardless of file order", async ({
+ page,
+}) => {
+ await page.goto("/");
+ await page.waitForFunction(() => window.openlight);
+ const unrelated = { name: "notes.txt", content: "Not an image" };
+ const empty = await openFiles(page, [
+ unrelated,
+ settings('crs:Exposure2012="2"'),
+ ]);
+ expect(empty.file).toBeUndefined();
+ await expect(page.getByRole("button", { name: "Open image" })).toBeVisible();
+
+ for (const settingsFirst of [true, false]) {
+ const parameters = settings(
+ 'crs:Exposure2012="1.25" crs:Contrast2012="-20" crs:Vibrance="30" crs:Saturation="-10"',
+ settingsFirst ? "photo.xml" : "photo.xmp",
+ );
+ const ignored = { name: "second.png", content: "invalid image" };
+ const files = settingsFirst
+ ? [parameters, image(), ignored]
+ : [image(), ignored, parameters];
+ const state = await openFiles(page, [unrelated, ...files]);
+ expect(state).toMatchObject({
+ file: "photo.svg",
+ adjustments: {
+ exposure: 1.25,
+ contrast: -20,
+ vibrance: 30,
+ saturation: -10,
+ },
+ });
+ await expect(
+ page.getByRole("textbox", { name: "Exposure", exact: true }),
+ ).toHaveValue("1.25");
+ const before = await page.locator("canvas").screenshot();
+ const partial = await openFiles(page, [
+ settings('crs:Exposure2012="3"'),
+ settings('crs:Exposure2012="-1"'),
+ ]);
+ expect(partial.adjustments).toMatchObject({
+ exposure: -1,
+ contrast: -20,
+ vibrance: 30,
+ saturation: -10,
+ });
+ await expect
+ .poll(() => page.locator("canvas").screenshot())
+ .not.toEqual(before);
+ }
+});
+
+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(
+ batches.map((files) =>
+ window.openlight.openFiles(
+ files.map(
+ ({ name, content, type }) => new File([content], name, { type }),
+ ),
+ ),
+ ),
+ );
+ return window.openlight.getState();
+ },
+ [
+ [settings('crs:Exposure2012="4"'), image("first.svg")],
+ [image("second.svg"), settings('crs:Contrast2012="20"')],
+ ],
+ );
+ expect(state).toMatchObject({
+ file: "second.svg",
+ adjustments: { exposure: 0, contrast: 20 },
+ });
+ const failed = await openFiles(page, [
+ settings('crs:Exposure2012="3"'),
+ { name: "broken.png", content: "invalid image" },
+ ]);
+ expect(failed).toMatchObject({
+ file: "broken.png",
+ adjustments: { exposure: 0, contrast: 0 },
+ });
+ await expect(
+ page.getByText("Couldn't open broken.png:", { exact: false }),
+ ).toBeVisible();
+ const recovered = await openFiles(page, [
+ settings('crs:Exposure2012="-1"'),
+ image(),
+ ]);
+ expect(recovered).toMatchObject({
+ file: "photo.svg",
+ adjustments: { exposure: -1, contrast: 0 },
+ });
+ await expect(
+ page.getByRole("textbox", { name: "Exposure", exact: true }),
+ ).toHaveValue("-1.00");
+});
diff --git a/tests/smoke.e2e.ts b/tests/smoke.e2e.ts
index 9e14740..fe546c8 100644
--- a/tests/smoke.e2e.ts
+++ b/tests/smoke.e2e.ts
@@ -40,7 +40,7 @@ test("browser actions load, adjust, reset, and report failures", async ({
"gray.svg",
{ type: "image/svg+xml" },
);
- window.openlight.loadImage(image);
+ window.openlight.openFile(image);
return window.openlight.getState();
});
await expect(page.locator("polyline").first()).toHaveAttribute(
@@ -75,14 +75,14 @@ test("browser actions load, adjust, reset, and report failures", async ({
});
await expect.poll(() => canvas.screenshot()).toEqual(before);
await page.evaluate(async () => {
- const superseded = window.openlight.loadImage(
+ 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.loadImage(
+ const latest = window.openlight.openFile(
new File(["invalid"], "broken.png", { type: "image/png" }),
);
await Promise.all([superseded, latest]);
@@ -91,7 +91,7 @@ test("browser actions load, adjust, reset, and report failures", async ({
page.getByText("Couldn't open broken.png:", { exact: false }),
).toBeVisible();
const recovered = await page.evaluate(async () => {
- await window.openlight.loadImage(
+ 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"/></svg>',