Skip to content

Free open-source image editor for the browser

Save scenes and recover drafts (#38)

Rodrigo Belfioree59bcb79c1df
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 35237e1..b72bcb1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -20,7 +20,7 @@ jobs:
- uses: actions/checkout@v7
- uses: oven-sh/setup-bun@v2
with:
- bun-version: 1.3.2
+ bun-version: 1.4.2
- run: bun install --frozen-lockfile
- name: Lint and format
run: bunx --no-install biome ci .
diff --git a/API.md b/API.md
index d0211d8..d2340e6 100644
--- a/API.md
+++ b/API.md
@@ -25,13 +25,16 @@ These methods accept browser `File` objects and return `Promise<void>`. Await th
| Method | Behavior |
| --- | --- |
-| `openFile(file)` | Opens one image or imports one Camera Raw XMP file. |
-| `openFiles(files)` | Opens the first recognized image, then imports recognized XMP files in order. Unsupported files are ignored. |
+| `openFile(file)` | Opens one image or [scene file](#scene-files), or imports one Camera Raw XMP file. |
+| `openFiles(files)` | Opens the first recognized image or scene file, then imports recognized XMP files in order. Unsupported files are ignored. |
| `loadImage(file)` | Loads a file as an image, replacing the current document and its history. |
+| `loadScene(file)` | Opens a scene file as a new document, replacing the current one and its history. |
+| `recoverDraft()` | Opens the stored [draft](#drafts) as a new document, like `loadScene`. Rejects when no draft is stored or storage fails. |
+| `discardDraft()` | Deletes the stored draft and its source files. |
| `loadUrl(url)` | Fetches an image from a same-origin URL and loads it. |
| `importXmp(file)` | Applies supported Camera Raw adjustments as one undoable edit. |
-Loading calls are queued. XMP import is skipped if no document is ready; an invalid XMP import can reject without blocking later loads. Image decoding failures appear in the workspace's error state and do not reject the loading promise. Check `getState().documentId` to confirm success. Loading completion does not guarantee the preview has rendered.
+Loading calls are queued. XMP import is skipped if no document is ready; an invalid XMP import can reject without blocking later loads. Image and scene failures appear in the workspace's error state and do not reject the loading promise. Check `getState().documentId` to confirm success. Loading completion does not guarantee the preview has rendered.
## Editing
@@ -144,6 +147,31 @@ try {
The image renders at the document dimensions and downsamples to `longEdge` with high-quality smoothing. Invalid values throw, as does a format the browser cannot encode.
+## Scene files
+
+`exportScene()` returns `Promise<File>`: the document as an `.openlight` file named after its source image, which **Save scene** in the Export panel downloads. It is a ZIP archive holding the source file's original bytes at `sources/<id>` and a deflated `scene.json`:
+
+```json
+{
+ "format": "openlight",
+ "version": 1,
+ "sources": { "<id>": { "name": "photo.jpg", "type": "image/jpeg" } },
+ "scene": { "frame": {}, "layers": [] }
+}
+```
+
+`scene` is the `getState()` scene; each image layer's `source` names an entry in `sources`. Opening the file with `loadScene`, `openFile`, a drop, or the file picker decodes the stored source again and restores the frame and every layer as a new document with empty history. Preview settings and history are not saved.
+
+Opening validates every value as the matching command does, and a file that fails leaves the workspace in its error state. A parameter missing from `adjustments`, `details`, `vignette`, `fill`, or `colorMixer` takes its default, so older files still open when a group gains a parameter; a RAW image without a white balance uses its As Shot value. `version` increases only when older files can no longer open as written; a newer version is rejected.
+
+## Drafts
+
+Once a document has an edit, OpenLight keeps it as the draft in the browser's IndexedDB, so closing the tab loses nothing. A save follows 1.5 s after the last scene change and flushes when the tab is hidden or the page unloads; saves run one at a time and never render. Opening an image or scene without editing it keeps the previous draft. Only the latest document is kept.
+
+A draft stores the same `scene.json` object a [scene file](#scene-files) holds, in a record with its own `version` and the document's name, while each source file sits in a separate store under its source ID. A save keeps source files already stored under their ID and deletes unreferenced ones in the same transaction, so edits never rewrite the photo.
+
+On a fresh load the start screen shows a notice in the viewport's corner with **Recover** and **Forget**. `recoverDraft()` opens the draft through the same validation as a scene file, restoring each source under its original ID, with empty history; a newer draft `version` is rejected rather than dropped, and a parameter added to a group since takes its default. `discardDraft()` removes it. Both return `Promise<void>`. When IndexedDB is unavailable or fails, a dismissible notice suggests saving a scene file, and editing continues.
+
## State
`getState()` returns a detached snapshot containing `file`, `documentId`, `scene`, `selectedLayerId`, `size`, `frame`, `adjustments`, `whiteBalance`, `details`, `toneCurve`, `colorMixer`, `vignette`, `preview`, and `history`. `scene` contains `frame` and the layer tree. The top-level adjustment, tone-curve, and white-balance values come from `scene.layers[0]`; details, color-mixer, and vignette values describe the first matching root layer from the bottom, or its defaults. `colorMixer` contains eight-value `hue`, `saturation`, and `luminance` arrays in the color order above, defaulting to zero. `whiteBalance` contains absolute temperature/tint for RAW sources and is undefined for other sources. `file` is the filename, and `history` contains `undoCount`, `redoCount`, and `editing`, which is true while a group is open.
diff --git a/CONTEXT.md b/CONTEXT.md
index bad4cbe..af05a08 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -11,7 +11,9 @@ OpenLight edits documents containing image content and adjustments.
| **Healing patch** | One painted, non-destructive repair in a Healing layer. It copies a nearby donor, found automatically or set by hand, with a bounded boundary color correction. Patches replay in order and each sees the result of the preceding patches. Size belongs to the recorded hard stroke; feather and opacity remain editable on its accumulated shape. |
| **Image source** | An image used as input to the document's composition. It is content within a document. |
| **Edit** | One reversible content change. A continuous slider or curve drag is one edit, as is importing a set of adjustments. |
-| **Workspace** | The open-document session. It currently holds at most one document, replaced when another image is opened. |
+| **Scene file** | A document saved as an `.openlight` archive: its scene and the original source files. Opening it creates a document that continues editing; history and preview settings are not saved. |
+| **Draft** | The latest edited document, kept in the browser as a scene with its source files so it survives closing the tab. The start screen offers to recover or forget it; recovering opens a new document with empty history. |
+| **Workspace** | The open-document session. It currently holds at most one document, replaced when another image or scene file is opened. |
| **Tool** | What a drag on the canvas does: Brush paints, Healing repairs, and Linear and Radial gradient draw masks and edit the selected gradient's guides. Adjust leaves the canvas to pan and zoom. Crop and Export bring their own view. Switching tools never changes the sidebar; Brush and Healing create their layer on entry and remove it again if it leaves untouched. A selected mask is *active*; it is *edited* only while a shape tool is on. |
Use these names consistently in code, UI text, and documentation.
diff --git a/DESIGN.md b/DESIGN.md
index 2fce849..9300eef 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -20,6 +20,8 @@ OpenLight uses a small set of shared UI primitives so the editor reads as one ap
- Use shared components for repeated interaction and surface behavior. Keep feature-specific composition in the feature.
- Use Tailwind tokens already present in the shared primitive for color, borders, shadows, focus, and pointer-coarse sizing. A caller chooses a documented variant instead of recreating the surface.
- Anchor viewport-corner controls and messages 12 px from both edges. Tool overlays cover the full viewport; the camera preserves a 24 px margin around fitted content without shrinking that coordinate space.
+- Use `Notice` for a message floating over the viewport that must not block editing, such as a storage failure or an offer to recover a draft. Choose its `tone` (status or alert, which sets the ARIA role), `placement`, and `anchor` (the window, or the editor viewport it renders inside); pass `actions` for buttons under the message and `onDismiss` when the user may close it.
+- Use `TextLink` for an underlined link inside running text. It renders an anchor with `href` and a button otherwise; the `muted` variant stays in the sentence's color for secondary actions such as Forget.
- Use `ScrubInput` for numbers that primarily read as inline text and secondarily accept typing. Inline variants hug the current digits and unit, keep their label close, and show only a subtly rounded background while text editing is active. Reserve the persistent bordered `box` variant for form fields that need explicit input chrome.
- Give toolbar slider values an explicit minimum character width when their expected range changes digit count. Set it at the call site from the useful range: percentages reserve three tabular characters, while brush size uses the actual maximum's digit count. Do not guess a global maximum.
- Text uses the global body size. Express hierarchy with weight and color.
diff --git a/README.md b/README.md
index f71df1d..bbee03f 100644
--- a/README.md
+++ b/README.md
@@ -45,8 +45,10 @@ Image processing runs on your own GPU with WebGPU. Photos never leave your devic
- Open JPEG, PNG, WebP, AVIF, GIF, BMP, SVG, HEIC, TIFF at 8-bit, 16-bit, and floating-point precision, and camera RAW/DNG with absolute white balance and As Shot reset.
- Import Camera Raw XMP settings.
- Export PNG, JPEG, or WebP with resizing, a live preview, and the resulting file size.
+- Save the photo with every edit as an OpenLight scene, then open it to continue editing.
+- Recover the latest edited photo after closing the tab, from a draft kept in the browser.
-Documents live in memory for now; export saves a flattened image. HEIC needs a browser with a WebCodecs HEVC decoder. RAW decoding uses [raw-webgpu](https://github.com/roprgm/raw-webgpu), which documents format support and limitations.
+Export saves a flattened image, a scene file keeps the photo with its edits, and the browser keeps the latest edited document as a draft. HEIC needs a browser with a WebCodecs HEVC decoder. RAW decoding uses [raw-webgpu](https://github.com/roprgm/raw-webgpu), which documents format support and limitations.
## Browser support
diff --git a/src/app/controls.ts b/src/app/controls.ts
index 135b59a..96fbfff 100644
--- a/src/app/controls.ts
+++ b/src/app/controls.ts
@@ -1,4 +1,9 @@
import type { Gpu } from "vgpu";
+import {
+ createDraftStore,
+ type DraftStore,
+ openDraft,
+} from "@/app/draft/store";
import {
type ExportOptions,
exportImage,
@@ -6,6 +11,8 @@ import {
import { createCameraRawXmpLoader } from "@/app/loaders/camera-raw-xmp";
import { createImageLoader } from "@/app/loaders/image";
import { createLoaderRegistry } from "@/app/loaders/registry";
+import { createSceneLoader } from "@/app/loaders/scene";
+import { writeSceneFile } from "@/app/scene-file";
import type {
Adjustments,
BrushStroke,
@@ -18,6 +25,7 @@ import type {
Vignette,
} from "@/core/document";
import type { WhiteBalance } from "@/core/image";
+import decode from "@/core/image/decode";
import type { ImageFrame, Point } from "@/core/image/frame";
import { setAdjustments } from "@/features/adjustments/edits";
import { defaultAdjustments } from "@/features/adjustments/model";
@@ -57,11 +65,16 @@ import {
import type { Workspace } from "./workspace";
/** Imperative commands bound to an explicit workspace, usable without React. */
-export function createControls(gpu: Gpu, workspace: Workspace) {
+export function createControls(
+ gpu: Gpu,
+ workspace: Workspace,
+ drafts: DraftStore = createDraftStore(),
+) {
const image = createImageLoader(gpu, workspace);
const xmp = createCameraRawXmpLoader(workspace);
+ const scene = createSceneLoader(gpu, workspace);
const files = createLoaderRegistry(
- [xmp, image],
+ [scene, xmp, image],
() => workspace.state.getState().status === "ready",
);
@@ -70,6 +83,18 @@ export function createControls(gpu: Gpu, workspace: Workspace) {
openFile: (file: File) => files.openFiles([file]),
loadImage: (file: File) => files.loadFile(image, file),
loadUrl: image.loadUrl,
+ loadScene: (file: File) => files.loadFile(scene, file),
+ /** Opens the stored draft like a scene file; a draft that fails to open leaves the workspace in its error state. */
+ async recoverDraft() {
+ const draft = await drafts.read();
+ if (!draft) {
+ throw Error("There is no draft to recover.");
+ }
+ await workspace.open(draft.record.name, () =>
+ openDraft(draft, (file) => decode(gpu, file)),
+ );
+ },
+ discardDraft: () => drafts.discard(),
importXmp: (file: File) => files.loadFile(xmp, file),
setDetails(change: Partial<Details>, id?: string) {
const document = workspace.getDocument();
@@ -151,6 +176,7 @@ export function createControls(gpu: Gpu, workspace: Workspace) {
redo: () => workspace.getDocument().history.redo(),
exportImage: (options?: ExportOptions) =>
exportImage(gpu, workspace.getDocument(), options),
+ exportScene: () => writeSceneFile(workspace.getDocument()),
getState() {
const { file, document } = workspace.state.getState();
const scene = document?.scene.getState();
diff --git a/src/app/draft/autosave.ts b/src/app/draft/autosave.ts
new file mode 100644
index 0000000..87c2619
--- /dev/null
+++ b/src/app/draft/autosave.ts
@@ -0,0 +1,65 @@
+import type { Workspace } from "@/app/workspace";
+import type { EditorDocument } from "@/core/document";
+import { type DraftStore, snapshotDraft } from "./store";
+
+/**
+ * Keeps the workspace's document as the draft once it has an edit, so opening an image alone never replaces one.
+ * Saves wait for `delay` after the last change and flush when the page hides; the store runs them in order.
+ */
+export function createAutosave(
+ workspace: Workspace,
+ store: DraftStore,
+ onError: (error: unknown) => void,
+ delay = 1500,
+) {
+ let watched: { document: EditorDocument; name: string } | undefined;
+ let changed = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let unsubscribe = () => {};
+
+ function flush() {
+ clearTimeout(timer);
+ timer = undefined;
+ if (!changed || !watched) {
+ return;
+ }
+ changed = false;
+ store.save(snapshotDraft(watched.document, watched.name)).catch(onError);
+ }
+
+ // The workspace publishes a replacement before disposing the old document, so its last edits still flush here.
+ function watch() {
+ const { document, file } = workspace.state.getState();
+ if (document === watched?.document) {
+ return;
+ }
+ flush();
+ unsubscribe();
+ watched = document && { document, name: file };
+ unsubscribe =
+ document?.scene.subscribe(() => {
+ changed = true;
+ clearTimeout(timer);
+ timer = setTimeout(flush, delay);
+ }) ?? (() => {});
+ }
+
+ function hidden() {
+ if (window.document.visibilityState === "hidden") {
+ flush();
+ }
+ }
+
+ const detach = workspace.state.subscribe(watch);
+ window.addEventListener("pagehide", flush);
+ window.document.addEventListener("visibilitychange", hidden);
+ return {
+ dispose() {
+ flush();
+ detach();
+ unsubscribe();
+ window.removeEventListener("pagehide", flush);
+ window.document.removeEventListener("visibilitychange", hidden);
+ },
+ };
+}
diff --git a/src/app/draft/notice.tsx b/src/app/draft/notice.tsx
new file mode 100644
index 0000000..9f3e1bd
--- /dev/null
+++ b/src/app/draft/notice.tsx
@@ -0,0 +1,17 @@
+import { Notice } from "@/components/ui/notice";
+
+/** Draft storage failures stay out of the way: the editor keeps working and a scene file still saves the work. */
+export function DraftNotice({
+ error,
+ onDismiss,
+}: {
+ error: string;
+ onDismiss: () => void;
+}) {
+ return (
+ <Notice onDismiss={onDismiss}>
+ Drafts can't be kept in this browser: {error} Save a scene from Export to
+ keep your edits.
+ </Notice>
+ );
+}
diff --git a/src/app/draft/session.ts b/src/app/draft/session.ts
new file mode 100644
index 0000000..e1e58db
--- /dev/null
+++ b/src/app/draft/session.ts
@@ -0,0 +1,51 @@
+import { createStore } from "zustand/vanilla";
+import type { DraftStore } from "./store";
+
+function message(error: unknown) {
+ return error instanceof Error ? error.message : String(error);
+}
+
+/**
+ * What the start screen offers from draft storage: whether a draft exists, and a failure to mention without blocking.
+ * Autosave fails the same way on every save, so a dismissed message stays dismissed.
+ */
+export function createDraftSession(
+ store: DraftStore,
+ commands: { recoverDraft(): Promise<void>; discardDraft(): Promise<void> },
+) {
+ const state = createStore<{ available?: boolean; error?: string }>(
+ () => ({}),
+ );
+ let dismissed: string | undefined;
+ function report(error: unknown) {
+ if (message(error) !== dismissed) {
+ state.setState({ error: message(error) });
+ }
+ }
+ return {
+ state,
+ report,
+ /** Looks for a draft from an earlier visit. */
+ offer() {
+ store
+ .peek()
+ .then((found) => state.setState({ available: Boolean(found) }))
+ .catch(report);
+ },
+ recover() {
+ state.setState({ available: false });
+ commands.recoverDraft().catch(report);
+ },
+ forget() {
+ commands
+ .discardDraft()
+ .then(() => state.setState({ available: false }), report);
+ },
+ dismiss() {
+ dismissed = state.getState().error;
+ state.setState({ error: undefined });
+ },
+ };
+}
+
+export type DraftSession = ReturnType<typeof createDraftSession>;
diff --git a/src/app/draft/store.ts b/src/app/draft/store.ts
new file mode 100644
index 0000000..641ee90
--- /dev/null
+++ b/src/app/draft/store.ts
@@ -0,0 +1,167 @@
+import { openScene, type SceneJson, snapshotScene } from "@/app/scene-file";
+import type { EditorDocument } from "@/core/document";
+import type { ImageSource } from "@/core/image";
+
+/** Raised only when older drafts can no longer open as written; the scene inside keeps its own version. */
+const version = 1;
+
+/** The latest document: the scene JSON a scene file holds, while its source files live in their own store by ID. */
+export type DraftRecord = { version: number; name: string; scene: SceneJson };
+export type Draft = { record: DraftRecord; files: ReadonlyMap<string, Blob> };
+
+/** A draft of the document shown as `name`, captured synchronously so the document may change or close meanwhile. */
+export function snapshotDraft(document: EditorDocument, name: string): Draft {
+ const { json, files } = snapshotScene(document);
+ return { record: { version, name, scene: json }, files };
+}
+
+/** Storage returns whatever an earlier version wrote, so the record is checked where it is read. */
+function validateRecord(record: DraftRecord | undefined): DraftRecord {
+ if (
+ !record ||
+ !Number.isInteger(record.version) ||
+ record.version < 1 ||
+ typeof record.name !== "string"
+ ) {
+ throw Error("Invalid draft.");
+ }
+ if (record.version > version) {
+ throw Error("This draft needs a newer version of OpenLight.");
+ }
+ return record;
+}
+
+/** Opens a draft through the same validation as a scene file. */
+export async function openDraft(
+ { record, files }: Draft,
+ decode: (file: File) => Promise<ImageSource>,
+) {
+ return openScene(validateRecord(record).scene, files, decode);
+}
+
+/** Resolves once every request issued in the transaction has run, so callers read results from the requests. */
+function complete(transaction: IDBTransaction) {
+ return new Promise<void>((resolve, reject) => {
+ transaction.oncomplete = () => resolve();
+ transaction.onerror = () => reject(transaction.error);
+ transaction.onabort = () =>
+ reject(transaction.error ?? Error("Draft storage was interrupted."));
+ });
+}
+
+/**
+ * One draft in IndexedDB: the record under a single key, and source files keyed by source ID.
+ * Operations run one at a time in call order, so a discard never races a save.
+ * Requests are issued from the transaction's own callbacks, never after an await, so it can't auto-commit early.
+ */
+export function createDraftStore(
+ factory: IDBFactory | undefined = globalThis.indexedDB,
+ name = "openlight",
+) {
+ let database: Promise<IDBDatabase> | undefined;
+ let queue = Promise.resolve();
+
+ function connect() {
+ if (!factory) {
+ return Promise.reject(Error("IndexedDB is unavailable."));
+ }
+ database ??= new Promise<IDBDatabase>((resolve, reject) => {
+ const opening = factory.open(name, 1);
+ opening.onupgradeneeded = () => {
+ opening.result.createObjectStore("draft");
+ opening.result.createObjectStore("sources");
+ };
+ opening.onsuccess = () => resolve(opening.result);
+ opening.onerror = () => reject(opening.error);
+ opening.onblocked = () => reject(Error("Draft storage is blocked."));
+ }).catch((error) => {
+ database = undefined;
+ throw error;
+ });
+ return database;
+ }
+
+ function run<T>(task: (database: IDBDatabase) => Promise<T>) {
+ const result = queue.then(async () => task(await connect()));
+ queue = result.then(
+ () => {},
+ () => {},
+ );
+ return result;
+ }
+
+ return {
+ /** Keeps source files already stored under their ID and deletes the ones the draft no longer uses. */
+ save({ record, files }: Draft) {
+ return run(async (database) => {
+ const transaction = database.transaction(
+ ["draft", "sources"],
+ "readwrite",
+ );
+ transaction.objectStore("draft").put(record, "latest");
+ const sources = transaction.objectStore("sources");
+ const stored = sources.getAllKeys();
+ stored.onsuccess = () => {
+ for (const [id, file] of files) {
+ if (!stored.result.includes(id)) {
+ sources.put(file, id);
+ }
+ }
+ for (const id of stored.result) {
+ if (typeof id === "string" && !files.has(id)) {
+ sources.delete(id);
+ }
+ }
+ };
+ await complete(transaction);
+ });
+ },
+ /** The draft's display name, without reading its source files. */
+ peek() {
+ return run(async (database) => {
+ const transaction = database.transaction("draft");
+ const record: IDBRequest<DraftRecord | undefined> = transaction
+ .objectStore("draft")
+ .get("latest");
+ await complete(transaction);
+ return record.result && { name: validateRecord(record.result).name };
+ });
+ },
+ /** The record with every stored source file; a save leaves only the files the draft uses. */
+ read() {
+ return run(async (database): Promise<Draft | undefined> => {
+ const transaction = database.transaction(["draft", "sources"]);
+ const record: IDBRequest<DraftRecord | undefined> = transaction
+ .objectStore("draft")
+ .get("latest");
+ const sources = transaction.objectStore("sources");
+ const ids = sources.getAllKeys();
+ const blobs: IDBRequest<Blob[]> = sources.getAll();
+ await complete(transaction);
+ if (!record.result) {
+ return undefined;
+ }
+ const files = new Map<string, Blob>();
+ ids.result.forEach((id, index) => {
+ if (typeof id === "string") {
+ files.set(id, blobs.result[index]);
+ }
+ });
+ return { record: validateRecord(record.result), files };
+ });
+ },
+ discard() {
+ return run(async (database) => {
+ const transaction = database.transaction(
+ ["draft", "sources"],
+ "readwrite",
+ );
+ transaction.objectStore("draft").clear();
+ transaction.objectStore("sources").clear();
+ await complete(transaction);
+ });
+ },
+ };
+}
+
+export type DraftStore = ReturnType<typeof createDraftStore>;
diff --git a/src/app/editor/empty.tsx b/src/app/editor/empty.tsx
index 96e7147..5c98f64 100644
--- a/src/app/editor/empty.tsx
+++ b/src/app/editor/empty.tsx
@@ -1,10 +1,14 @@
import { useEffect, useMemo, useRef } from "react";
import { type Gpu, target } from "vgpu";
import { useGpu } from "vgpu-react";
+import { sceneExtension } from "@/app/scene-file";
import type { Workspace } from "@/app/workspace";
import { RendererProvider } from "@/components/editor/pipeline";
import { DocumentProvider } from "@/components/editor/session";
+import Button from "@/components/ui/button";
+import { Notice } from "@/components/ui/notice";
import Spinner from "@/components/ui/spinner";
+import { TextLink } from "@/components/ui/text-link";
import { createDocument, createResources } from "@/core/document";
import { createImageSource } from "@/core/image";
import { accept } from "@/core/image/decode";
@@ -25,17 +29,11 @@ type OpenProps = { onOpen: (files: File[]) => void };
function OpenImage({ onOpen }: OpenProps) {
const input = useRef<HTMLInputElement>(null);
return (
- <p className="mt-8 rounded-full border border-neutral-700 border-dashed px-5 py-2.5 text-neutral-500">
+ <p className="mt-4 text-neutral-500">
Drop an image here or{" "}
- <button
- type="button"
- onClick={() => input.current?.click()}
- className="cursor-pointer text-neutral-200 underline decoration-neutral-600 underline-offset-4 transition-colors hover:decoration-neutral-200 focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-neutral-400/80"
- >
- choose a file
- </button>
+ <TextLink onClick={() => input.current?.click()}>choose a file</TextLink>
<input
- accept={accept}
+ accept={`${accept},${sceneExtension}`}
hidden
multiple
onChange={(event) => {
@@ -56,6 +54,32 @@ type EmptyState = Exclude<
{ status: "ready" }
>;
+/** A draft kept from an earlier visit, offered until it is recovered or forgotten. */
+export type Recovery = {
+ onRecover: () => void;
+ onForget: () => void;
+};
+
+/** Offered away from the welcome copy, since returning users see it on every visit. */
+function RecoverDraft({ onRecover, onForget }: Recovery) {
+ return (
+ <Notice
+ anchor="viewport"
+ placement="start"
+ actions={
+ <>
+ <Button onClick={onRecover}>Recover</Button>
+ <Button variant="ghost" onClick={onForget}>
+ Forget
+ </Button>
+ </>
+ }
+ >
+ Your last scene is still here from a previous visit.
+ </Notice>
+ );
+}
+
function Status({ state, onOpen }: { state: EmptyState } & OpenProps) {
if (state.status === "loading") {
return <Spinner />;
@@ -72,7 +96,13 @@ function Status({ state, onOpen }: { state: EmptyState } & OpenProps) {
}
return (
<>
- <img alt="" className="w-16" height="64" src="/logo.svg" width="64" />
+ <img
+ alt=""
+ className="mb-1.5 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={onOpen} />
@@ -98,7 +128,8 @@ function createEmptyDocument(gpu: Gpu) {
export function EmptyEditor({
state,
onOpen,
-}: { state: EmptyState } & OpenProps) {
+ draft,
+}: { state: EmptyState; draft?: Recovery } & OpenProps) {
const gpu = useGpu();
const document = useMemo(() => createEmptyDocument(gpu), [gpu]);
useEffect(() => () => document.dispose(), [document]);
@@ -113,9 +144,10 @@ export function EmptyEditor({
<EditorHeader file={state.file} />
<div className="flex min-h-0 flex-1 flex-col md:flex-row">
<ToolTabList selected={tools[0]} />
- <div className="relative isolate grid min-h-0 min-w-0 flex-1 place-content-center justify-items-center gap-3 overflow-hidden bg-[radial-gradient(circle,#292929,#131313_55%)] p-6">
+ <div className="relative isolate grid min-h-0 min-w-0 flex-1 place-content-center justify-items-center gap-1.5 overflow-hidden bg-[radial-gradient(circle,#292929,#131313_55%)] p-6">
<Backdrop />
<Status state={state} onOpen={onOpen} />
+ {draft && <RecoverDraft {...draft} />}
</div>
<EditorSidebar inert>
<AdjustPanel />
diff --git a/src/app/editor/export/index.tsx b/src/app/editor/export/index.tsx
index c1d4ddb..588cbaf 100644
--- a/src/app/editor/export/index.tsx
+++ b/src/app/editor/export/index.tsx
@@ -1,6 +1,7 @@
import { cn } from "cn";
import { type ReactNode, useMemo, useRef, useState } from "react";
import { useGpu } from "vgpu-react";
+import { writeSceneFile } from "@/app/scene-file";
import { Image } from "@/components/editor/image";
import { EditorPanel, PanelHeader } from "@/components/editor/panel";
import { useDocument, useScene } from "@/components/editor/session";
@@ -149,6 +150,53 @@ function SizeFields({
);
}
+function download(file: File) {
+ const url = URL.createObjectURL(file);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = file.name;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
+
+function SaveScene() {
+ const editorDocument = useDocument();
+ const saving = useRef(false);
+ const [error, setError] = useState("");
+ const save = async () => {
+ if (saving.current) {
+ return;
+ }
+ saving.current = true;
+ setError("");
+ try {
+ download(await writeSceneFile(editorDocument));
+ } catch (error) {
+ setError(error instanceof Error ? error.message : "Couldn't save scene.");
+ } finally {
+ saving.current = false;
+ }
+ };
+ return (
+ <section
+ aria-label="Scene export"
+ className="flex flex-col gap-3 border-black border-t p-4"
+ >
+ <p className="text-neutral-500">
+ Saves the photo and every edit in one file. Open it to continue editing.
+ </p>
+ <Button className="w-full py-2" onClick={save}>
+ Save scene
+ </Button>
+ {error && (
+ <p className="text-red-400" role="alert">
+ {error}
+ </p>
+ )}
+ </section>
+ );
+}
+
function LoadingOverlay() {
return (
<div className="pointer-events-none absolute inset-0 grid place-items-center">
@@ -181,13 +229,7 @@ export function ExportMode({ onClose }: { onClose: () => void }) {
exporting.current = true;
setError("");
try {
- const file = await exportImage(gpu, editorDocument, options);
- const url = URL.createObjectURL(file);
- const link = document.createElement("a");
- link.href = url;
- link.download = file.name;
- link.click();
- setTimeout(() => URL.revokeObjectURL(url), 1000);
+ download(await exportImage(gpu, editorDocument, options));
} catch (error) {
setError(
error instanceof Error ? error.message : "Couldn't export image.",
@@ -205,10 +247,7 @@ export function ExportMode({ onClose }: { onClose: () => void }) {
{encoded && <Image image={encoded.image} />}
</EditorViewport>
<EditorPanel header={<PanelHeader title="Export" onClose={onClose} />}>
- <section
- aria-label="Export settings"
- className="flex flex-col gap-5 p-4"
- >
+ <section aria-label="Image export" className="flex flex-col gap-5 p-4">
<FormatSelect value={format} onChange={setFormat} />
{format.lossy && (
<Slider
@@ -241,6 +280,7 @@ export function ExportMode({ onClose }: { onClose: () => void }) {
</p>
)}
</section>
+ <SaveScene />
</EditorPanel>
</>
);
diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsx
index d0cd7c9..ea09175 100644
--- a/src/app/editor/index.tsx
+++ b/src/app/editor/index.tsx
@@ -13,7 +13,7 @@ import { useShortcuts } from "@/hooks/use-shortcuts";
import { AdjustPanel } from "./adjust";
import { EditorCanvas } from "./canvas";
import { ComparisonControl } from "./comparison-control";
-import { EmptyEditor } from "./empty";
+import { EmptyEditor, type Recovery } from "./empty";
import { EditorHeader } from "./header";
import { HistoryControls } from "./history";
import { createMask } from "./layers";
@@ -150,10 +150,11 @@ function DocumentEditor({ file }: { file: string }) {
type EditorProps = {
state: ReturnType<Workspace["state"]["getState"]>;
onOpen: (files: File[]) => void;
+ draft?: Recovery;
};
-function EditorContent({ state, onOpen }: EditorProps) {
+function EditorContent({ state, onOpen, draft }: EditorProps) {
if (state.status !== "ready") {
- return <EmptyEditor state={state} onOpen={onOpen} />;
+ return <EmptyEditor state={state} onOpen={onOpen} draft={draft} />;
}
return (
<DocumentProvider key={state.document.id} value={state.document}>
diff --git a/src/app/index.tsx b/src/app/index.tsx
index c9dcae1..2c3fed5 100644
--- a/src/app/index.tsx
+++ b/src/app/index.tsx
@@ -1,4 +1,5 @@
import { useStore } from "zustand";
+import { DraftNotice } from "@/app/draft/notice";
import Editor from "@/app/editor";
import { useWorkspace } from "@/app/workspace/use-workspace";
import { useFileDrop } from "@/hooks/use-file-drop";
@@ -7,8 +8,17 @@ import { useFileDrop } from "@/hooks/use-file-drop";
const startup = location.pathname === "/demo" ? "/images/demo.jpg" : undefined;
export default function App() {
- const { workspace, controls } = useWorkspace(startup);
+ const { workspace, controls, drafts } = useWorkspace(startup);
useFileDrop(controls.openFiles);
const state = useStore(workspace.state);
- return <Editor state={state} onOpen={controls.openFiles} />;
+ const { available, error } = useStore(drafts.state);
+ const recovery = available
+ ? { onRecover: drafts.recover, onForget: drafts.forget }
+ : undefined;
+ return (
+ <>
+ <Editor state={state} onOpen={controls.openFiles} draft={recovery} />
+ {error && <DraftNotice error={error} onDismiss={drafts.dismiss} />}
+ </>
+ );
}
diff --git a/src/app/loaders/scene.ts b/src/app/loaders/scene.ts
new file mode 100644
index 0000000..2d121cc
--- /dev/null
+++ b/src/app/loaders/scene.ts
@@ -0,0 +1,20 @@
+import type { Gpu } from "vgpu";
+import { isSceneFile, openSceneFile } from "@/app/scene-file";
+import type { Workspace } from "@/app/workspace";
+import decode from "@/core/image/decode";
+import type { FileLoader } from "./registry";
+
+export function createSceneLoader(gpu: Gpu, workspace: Workspace): FileLoader {
+ return {
+ kind: "document",
+ accepts: isSceneFile,
+ async load(file) {
+ if (!(file instanceof File)) {
+ throw new Error("loadScene requires a File.");
+ }
+ await workspace.open(file.name, () =>
+ openSceneFile(file, (source) => decode(gpu, source)),
+ );
+ },
+ };
+}
diff --git a/src/app/scene-file.ts b/src/app/scene-file.ts
new file mode 100644
index 0000000..f9ee63a
--- /dev/null
+++ b/src/app/scene-file.ts
@@ -0,0 +1,283 @@
+import {
+ createDocument,
+ createResources,
+ type EditorDocument,
+ type ProcessingLayer,
+ type Scene,
+} from "@/core/document";
+import type { ImageSource, WhiteBalance } from "@/core/image";
+import { validateFrame } from "@/core/image/frame";
+import {
+ defaultAdjustments,
+ validateAdjustments,
+} from "@/features/adjustments/model";
+import { defaultMixer, validateMixer } from "@/features/color-mixer/model";
+import { defaultDetails, validateDetails } from "@/features/details/model";
+import { defaultFill, validateFill } from "@/features/fill/model";
+import { validateHealPatch } from "@/features/heal/model";
+import {
+ validateDepth,
+ validateExposure,
+ validateLayerSettings,
+ validateMask,
+ validateMaskOperation,
+} from "@/features/layers/edits";
+import { validateCurve } from "@/features/tone-curves/curve";
+import { validateVignette } from "@/features/vignette/edits";
+import { defaultVignette } from "@/features/vignette/model";
+import { validateWhiteBalance } from "@/features/white-balance/edits";
+import { readZip, writeZip } from "@/lib/zip";
+
+/** Raised only when older files can no longer load as written; a parameter added later takes its default. */
+const version = 1;
+
+/** A saved scene: the scene as edited and the name and type of each source file, stored beside it by ID. */
+export type SceneJson = {
+ format: "openlight";
+ version: number;
+ sources: Record<string, { name: string; type: string }>;
+ scene: Scene;
+};
+
+export const sceneExtension = ".openlight";
+
+/** Sources are stored, so only `scene.json` inflates; a scene with 7,000 stroke points is about 200 kB. */
+const inflateLimit = 256 * 2 ** 20;
+
+export function isSceneFile(file: File) {
+ return file.name.toLowerCase().endsWith(sceneExtension);
+}
+
+/** The document's scene and the source files it references, read without rendering. */
+export function snapshotScene(document: EditorDocument) {
+ const scene = document.scene.getState();
+ const { source } = scene.layers[0];
+ const { file } = document.resources.get(source);
+ const json: SceneJson = {
+ format: "openlight",
+ version,
+ sources: { [source]: { name: file.name, type: file.type } },
+ scene,
+ };
+ return { json, files: new Map([[source, file]]) };
+}
+
+/** The document as a ZIP archive: a deflated `scene.json` and each source's bytes at `sources/<id>`. */
+export async function writeSceneFile(document: EditorDocument) {
+ const { json, files } = snapshotScene(document);
+ const archive = await writeZip([
+ {
+ name: "scene.json",
+ data: new Blob([JSON.stringify(json)]),
+ deflate: true,
+ },
+ ...[...files].map(([id, file]) => ({ name: `sources/${id}`, data: file })),
+ ]);
+ const [file] = files.values();
+ const name = file.name.replace(/\.[^.]*$/, "") || "scene";
+ return new File([archive], `${name}${sceneExtension}`);
+}
+
+function readId(id: string, ids: Set<string>) {
+ if (typeof id !== "string" || !id || ids.has(id)) {
+ throw Error("Layer and patch IDs must be unique strings.");
+ }
+ ids.add(id);
+}
+
+/** Parameters missing from a group take their defaults, so older files load after the group gains one. */
+function complete<T extends object>(
+ defaults: T,
+ value: Partial<T> | undefined,
+ validate: (value: T) => void,
+) {
+ const merged = { ...defaults, ...value };
+ validate(merged);
+ return merged;
+}
+
+/** Absolute white balance applies only to RAW images, which fall back to their as-shot balance. */
+function readWhiteBalance(
+ balance: WhiteBalance | undefined,
+ asShot: WhiteBalance | undefined,
+) {
+ if (!asShot || !balance) {
+ return asShot;
+ }
+ const whiteBalance = { temperature: balance.temperature, tint: balance.tint };
+ validateWhiteBalance(whiteBalance, asShot);
+ return whiteBalance;
+}
+
+function readLayer(layer: ProcessingLayer, ids: Set<string>): ProcessingLayer {
+ const { id, name, visible, opacity, children } = layer;
+ readId(id, ids);
+ validateLayerSettings({ name, visible, opacity });
+ if (!Array.isArray(children)) {
+ throw Error("Layer children must be a list.");
+ }
+ const base = {
+ id,
+ name,
+ visible,
+ opacity,
+ children: children.map((child) => readLayer(child, ids)),
+ };
+ switch (layer.kind) {
+ case "exposure":
+ validateExposure(layer.exposure);
+ return { ...base, kind: layer.kind, exposure: layer.exposure };
+ case "details":
+ return {
+ ...base,
+ kind: layer.kind,
+ details: complete(defaultDetails, layer.details, validateDetails),
+ };
+ case "vignette":
+ return {
+ ...base,
+ kind: layer.kind,
+ vignette: complete(defaultVignette, layer.vignette, validateVignette),
+ };
+ case "color-mixer":
+ return {
+ ...base,
+ kind: layer.kind,
+ colorMixer: complete(defaultMixer, layer.colorMixer, validateMixer),
+ };
+ case "fill":
+ return {
+ ...base,
+ kind: layer.kind,
+ fill: complete(defaultFill, layer.fill, validateFill),
+ };
+ case "heal":
+ if (!Array.isArray(layer.patches)) {
+ throw Error("A Healing layer needs a list of patches.");
+ }
+ for (const patch of layer.patches) {
+ readId(patch.id, ids);
+ validateHealPatch(patch);
+ }
+ return { ...base, kind: layer.kind, patches: layer.patches };
+ case "mask":
+ validateMaskOperation(layer.operation);
+ validateMask(layer.mask);
+ validateCurve(layer.toneCurve);
+ return {
+ ...base,
+ kind: layer.kind,
+ operation: layer.operation,
+ mask: layer.mask,
+ adjustments: complete(
+ defaultAdjustments,
+ layer.adjustments,
+ validateAdjustments,
+ ),
+ toneCurve: layer.toneCurve,
+ };
+ default: {
+ const unknown: never = layer;
+ throw Error(`Unknown layer kind: ${Reflect.get(unknown, "kind")}.`);
+ }
+ }
+}
+
+/**
+ * Opens a saved scene as a new document, validating every value as the edit that made it.
+ * Scene files and drafts both open through here; `files` holds each source's bytes by ID.
+ */
+export async function openScene(
+ saved: SceneJson,
+ files: ReadonlyMap<string, Blob>,
+ decode: (file: File) => Promise<ImageSource>,
+) {
+ if (saved?.format !== "openlight") {
+ throw Error("This file doesn't contain an OpenLight scene.");
+ }
+ if (!Number.isInteger(saved.version) || saved.version < 1) {
+ throw Error("Invalid scene version.");
+ }
+ if (saved.version > version) {
+ throw Error("This scene needs a newer version of OpenLight.");
+ }
+ const { frame, layers } = saved.scene ?? {};
+ validateFrame(frame);
+ if (!Array.isArray(layers) || layers[0]?.kind !== "image") {
+ throw Error("A scene must start with its image layer.");
+ }
+ const [image, ...rest] = layers;
+ const ids = new Set<string>();
+ readId(image.id, ids);
+ validateLayerSettings({ name: image.name });
+ if (image.children?.length) {
+ throw Error("The image layer cannot contain layers.");
+ }
+ validateCurve(image.toneCurve);
+ const adjustments = complete(
+ defaultAdjustments,
+ image.adjustments,
+ validateAdjustments,
+ );
+ const children = rest.map((layer) => readLayer(layer, ids));
+ validateDepth(children);
+ const source = saved.sources?.[image.source];
+ const data = files.get(image.source);
+ if (typeof source?.name !== "string" || !data) {
+ throw Error("The scene's image is missing.");
+ }
+ const sourceFile = new File([data], source.name, { type: source.type });
+ const decoded = await decode(sourceFile);
+ const resources = createResources();
+ try {
+ const id = resources.add(sourceFile, decoded, image.source);
+ return createDocument(
+ {
+ frame: {
+ center: frame.center,
+ size: frame.size,
+ rotation: frame.rotation,
+ angle: frame.angle,
+ scale: frame.scale,
+ },
+ layers: [
+ {
+ kind: "image",
+ id: image.id,
+ name: image.name,
+ source: id,
+ whiteBalance: readWhiteBalance(
+ image.whiteBalance,
+ decoded.raw?.asShot,
+ ),
+ adjustments,
+ toneCurve: image.toneCurve,
+ children: [],
+ },
+ ...children,
+ ],
+ },
+ resources,
+ );
+ } catch (error) {
+ resources.dispose();
+ throw error;
+ }
+}
+
+export async function openSceneFile(
+ file: Blob,
+ decode: (file: File) => Promise<ImageSource>,
+) {
+ const entries = await readZip(file, inflateLimit);
+ const json = entries.get("scene.json");
+ if (!json) {
+ throw Error("This file doesn't contain an OpenLight scene.");
+ }
+ const files = new Map(
+ [...entries].flatMap(([name, data]) =>
+ name.startsWith("sources/") ? [[name.slice(8), data] as const] : [],
+ ),
+ );
+ return openScene(JSON.parse(await json.text()), files, decode);
+}
diff --git a/src/app/workspace/use-workspace.ts b/src/app/workspace/use-workspace.ts
index c158315..a8ed6e3 100644
--- a/src/app/workspace/use-workspace.ts
+++ b/src/app/workspace/use-workspace.ts
@@ -1,27 +1,37 @@
import { useEffect, useMemo } from "react";
import { useGpu } from "vgpu-react";
import { createControls } from "@/app/controls";
+import { createAutosave } from "@/app/draft/autosave";
+import { createDraftSession } from "@/app/draft/session";
+import { createDraftStore } from "@/app/draft/store";
import { createWorkspace } from ".";
/**
- * Connects an imperative workspace and its browser commands to the app lifetime.
- * A startup URL opens while the session is created, so the first paint is already loading.
+ * Connects an imperative workspace, its browser commands, and draft autosave to the app lifetime.
+ * A startup URL opens while the session is created, so the first paint is already loading; otherwise a stored draft is offered.
*/
export function useWorkspace(startup?: string) {
const gpu = useGpu();
const session = useMemo(() => {
const workspace = createWorkspace();
- const controls = createControls(gpu, workspace);
+ const store = createDraftStore();
+ const controls = createControls(gpu, workspace, store);
+ const drafts = createDraftSession(store, controls);
if (startup) {
void controls.loadUrl(startup);
+ } else {
+ drafts.offer();
}
- return { workspace, controls };
+ return { workspace, store, controls, drafts };
}, [gpu, startup]);
useEffect(() => {
- window.openlight = session.controls;
+ const { workspace, store, controls, drafts } = session;
+ const autosave = createAutosave(workspace, store, drafts.report);
+ window.openlight = controls;
return () => {
Reflect.deleteProperty(window, "openlight");
- session.workspace.dispose();
+ autosave.dispose();
+ workspace.dispose();
};
}, [session]);
return session;
diff --git a/src/components/editor/pipeline.tsx b/src/components/editor/pipeline.tsx
index 7781a58..7e2c497 100644
--- a/src/components/editor/pipeline.tsx
+++ b/src/components/editor/pipeline.tsx
@@ -8,6 +8,7 @@ import {
} from "react";
import type { Gpu } from "vgpu";
import { useGpu } from "vgpu-react";
+import { Notice } from "@/components/ui/notice";
import { adjustmentTarget } from "@/core/document";
import type { ImageSource } from "@/core/image";
import type { createRenderer } from "@/core/renderer";
@@ -27,12 +28,9 @@ export function useRenderer() {
function RendererError({ message }: { message: string }) {
return (
- <p
- role="alert"
- className="fixed bottom-4 left-4 rounded bg-neutral-900 px-3 py-2 text-red-300"
- >
+ <Notice tone="alert" placement="start">
Renderer error: {message}
- </p>
+ </Notice>
);
}
diff --git a/src/components/ui/notice.tsx b/src/components/ui/notice.tsx
new file mode 100644
index 0000000..9a40c4f
--- /dev/null
+++ b/src/components/ui/notice.tsx
@@ -0,0 +1,76 @@
+import { cva, type VariantProps } from "class-variance-authority";
+import { cn } from "cn";
+import type { ComponentProps, ReactNode } from "react";
+import { CloseIcon } from "@/components/icons/close";
+import Button from "./button";
+
+const notice = cva(
+ "bottom-3 z-50 flex max-w-sm items-start gap-2 rounded-lg border border-black/60 bg-neutral-800 py-2 pl-3 shadow-float",
+ {
+ variants: {
+ /** Status messages read as ordinary text; alerts are red and interrupt assistive technology. */
+ tone: {
+ status: "text-neutral-300",
+ alert: "text-red-300",
+ },
+ /** 12 px from the edge, or centered along it. */
+ placement: {
+ start: "left-3",
+ center: "-translate-x-1/2 left-1/2",
+ },
+ /** Over the whole window, or inside the nearest positioned ancestor such as the editor viewport. */
+ anchor: {
+ window: "fixed",
+ viewport: "absolute",
+ },
+ },
+ defaultVariants: { tone: "status", placement: "center", anchor: "window" },
+ },
+);
+
+type NoticeProps = ComponentProps<"div"> &
+ VariantProps<typeof notice> & {
+ /** Buttons shown under the message. */
+ actions?: ReactNode;
+ onDismiss?: () => void;
+ };
+
+/** A message floating over the viewport that doesn't block the editor. */
+export function Notice({
+ className,
+ tone,
+ placement,
+ anchor,
+ actions,
+ onDismiss,
+ children,
+ ...props
+}: NoticeProps) {
+ return (
+ <div
+ role={tone === "alert" ? "alert" : "status"}
+ className={cn(
+ notice({ tone, placement, anchor }),
+ onDismiss || "pr-3",
+ className,
+ )}
+ {...props}
+ >
+ <div className="flex flex-col gap-2">
+ <p>{children}</p>
+ {actions && <div className="flex gap-2">{actions}</div>}
+ </div>
+ {onDismiss && (
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label="Dismiss"
+ className="mr-1"
+ onClick={onDismiss}
+ >
+ <CloseIcon />
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/ui/text-link.tsx b/src/components/ui/text-link.tsx
new file mode 100644
index 0000000..97a0892
--- /dev/null
+++ b/src/components/ui/text-link.tsx
@@ -0,0 +1,34 @@
+import { cva, type VariantProps } from "class-variance-authority";
+import { cn } from "cn";
+import type { ComponentProps } from "react";
+
+const link = cva(
+ "cursor-pointer underline underline-offset-4 transition-colors focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-neutral-400/80",
+ {
+ variants: {
+ /** Default links stand out from their sentence; muted ones stay in its color until hovered. */
+ variant: {
+ default:
+ "text-neutral-200 decoration-neutral-600 hover:decoration-neutral-200",
+ muted:
+ "decoration-neutral-700 hover:text-neutral-300 hover:decoration-neutral-400",
+ },
+ },
+ defaultVariants: { variant: "default" },
+ },
+);
+
+type TextLinkProps = VariantProps<typeof link> &
+ (
+ | ({ href: string } & ComponentProps<"a">)
+ | ({ href?: undefined } & ComponentProps<"button">)
+ );
+
+/** An underlined link inside running text: an anchor with `href`, otherwise a button. */
+export function TextLink({ className, variant, ...props }: TextLinkProps) {
+ const classes = cn(link({ variant }), className);
+ if (props.href !== undefined) {
+ return <a className={classes} {...props} />;
+ }
+ return <button className={classes} type="button" {...props} />;
+}
diff --git a/src/core/document/resources.ts b/src/core/document/resources.ts
index cfa7638..1dcb505 100644
--- a/src/core/document/resources.ts
+++ b/src/core/document/resources.ts
@@ -5,11 +5,14 @@ export function createResources() {
const images = new Map<string, { file: File } & ImageSource>();
let disposed = false;
return {
- add(file: File, source: ImageSource) {
+ /** A saved document restores each source under its original ID. */
+ add(file: File, source: ImageSource, id: string = crypto.randomUUID()) {
if (disposed) {
throw new Error("Document is closed.");
}
- const id = crypto.randomUUID();
+ if (images.has(id)) {
+ throw new Error("Image resource already exists.");
+ }
images.set(id, { file, ...source });
return id;
},
diff --git a/src/features/adjustments/edits.ts b/src/features/adjustments/edits.ts
index eb9d753..5e24fdb 100644
--- a/src/features/adjustments/edits.ts
+++ b/src/features/adjustments/edits.ts
@@ -3,25 +3,14 @@ import {
type EditorDocument,
editLayer,
} from "@/core/document";
-import { adjustmentLimits } from "./model";
+import { validateAdjustments } from "./model";
export function setAdjustments(
document: EditorDocument,
change: Partial<Adjustments>,
id = document.scene.getState().layers[0].id,
) {
- for (const [name, value] of Object.entries(change)) {
- const limit = Reflect.get(adjustmentLimits, name);
- if (
- typeof limit !== "number" ||
- typeof value !== "number" ||
- !Number.isFinite(value) ||
- value > limit ||
- value < -limit
- ) {
- throw new Error(`Invalid adjustment: ${name}.`);
- }
- }
+ validateAdjustments(change);
editLayer(document, id, (layer) => {
if (layer.kind !== "image" && layer.kind !== "mask") {
throw Error("Select an image or mask layer.");
diff --git a/src/features/adjustments/model.ts b/src/features/adjustments/model.ts
index 879aa87..6b288f7 100644
--- a/src/features/adjustments/model.ts
+++ b/src/features/adjustments/model.ts
@@ -25,3 +25,18 @@ export const adjustmentLimits: Adjustments = {
vibrance: 100,
saturation: 100,
};
+
+export function validateAdjustments(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) ||
+ value > limit ||
+ value < -limit
+ ) {
+ throw new Error(`Invalid adjustment: ${name}.`);
+ }
+ }
+}
diff --git a/src/features/color-mixer/edits.ts b/src/features/color-mixer/edits.ts
index 1eba982..923da59 100644
--- a/src/features/color-mixer/edits.ts
+++ b/src/features/color-mixer/edits.ts
@@ -9,6 +9,7 @@ import {
defaultMixer,
type MixerChange,
type MixerColor,
+ validMixerValue,
} from "./model";
export function changeColorMixer(
@@ -21,12 +22,7 @@ export function changeColorMixer(
throw new Error(`Invalid color range: ${color}.`);
}
for (const [name, value] of Object.entries(change)) {
- if (
- !channels.some(({ id }) => id === name) ||
- typeof value !== "number" ||
- !Number.isFinite(value) ||
- Math.abs(value) > 100
- ) {
+ if (!channels.some(({ id }) => id === name) || !validMixerValue(value)) {
throw new Error(`Invalid color mixer adjustment: ${name}.`);
}
}
diff --git a/src/features/color-mixer/model.ts b/src/features/color-mixer/model.ts
index 766022f..156c527 100644
--- a/src/features/color-mixer/model.ts
+++ b/src/features/color-mixer/model.ts
@@ -32,3 +32,24 @@ export const defaultMixer: ColorMixer = Object.freeze({
export function isNeutral(mixer: ColorMixer) {
return channels.every(({ id }) => mixer[id].every((value) => value === 0));
}
+
+export function validMixerValue(value: unknown) {
+ return (
+ typeof value === "number" &&
+ Number.isFinite(value) &&
+ Math.abs(value) <= 100
+ );
+}
+
+export function validateMixer(mixer: ColorMixer) {
+ for (const [name, values] of Object.entries(mixer)) {
+ if (
+ !channels.some(({ id }) => id === name) ||
+ !Array.isArray(values) ||
+ values.length !== colors.length ||
+ !values.every(validMixerValue)
+ ) {
+ throw new Error(`Invalid color mixer adjustment: ${name}.`);
+ }
+ }
+}
diff --git a/src/features/heal/edits.ts b/src/features/heal/edits.ts
index 332b539..5dbe378 100644
--- a/src/features/heal/edits.ts
+++ b/src/features/heal/edits.ts
@@ -6,9 +6,13 @@ import {
type Layer,
type StrokePoint,
} from "@/core/document";
-import { validateStroke, validPoints } from "@/core/document/brush";
+import { validPoints } from "@/core/document/brush";
import type { Point } from "@/core/image/frame";
-import { validateOffset } from "./model";
+import {
+ validateOffset,
+ validatePatchBlend,
+ validatePatchStroke,
+} from "./model";
export function addHealPatch(
document: EditorDocument,
@@ -16,10 +20,7 @@ export function addHealPatch(
stroke: BrushStroke,
offset: Point,
) {
- validateStroke(stroke);
- if (stroke.mode !== "paint") {
- throw Error("Heal patches use painted strokes.");
- }
+ validatePatchStroke(stroke);
validateOffset(offset);
const patch: HealPatch = {
id: crypto.randomUUID(),
@@ -55,12 +56,6 @@ function editPatches(
});
}
-function unit(name: string, value: number | undefined) {
- if (value !== undefined && !(value >= 0 && value <= 1)) {
- throw Error(`Heal patch ${name} must be between 0 and 1.`);
- }
-}
-
/** Edits one patch's blend; its shape and donor stay as painted. */
export function setHealPatch(
document: EditorDocument,
@@ -68,8 +63,7 @@ export function setHealPatch(
patchId: string,
change: { feather?: number; opacity?: number },
) {
- unit("feather", change.feather);
- unit("opacity", change.opacity);
+ validatePatchBlend(change);
editPatches(document, id, patchId, (patches, index) =>
patches.with(index, {
...patches[index],
diff --git a/src/features/heal/model.ts b/src/features/heal/model.ts
index bfaed69..e35fa90 100644
--- a/src/features/heal/model.ts
+++ b/src/features/heal/model.ts
@@ -1,4 +1,5 @@
-import type { BrushStroke, Scene } from "@/core/document";
+import type { BrushStroke, HealPatch, Scene } from "@/core/document";
+import { validateStroke } from "@/core/document/brush";
import type { Point } from "@/core/image/frame";
export function findHealPatch(scene: Scene, layerId: string, patchId: string) {
@@ -70,3 +71,27 @@ export function validateOffset(offset: Point) {
throw Error("A heal source needs two finite source-pixel offsets.");
}
}
+
+export function validatePatchStroke(stroke: BrushStroke) {
+ validateStroke(stroke);
+ if (stroke.mode !== "paint") {
+ throw Error("Heal patches use painted strokes.");
+ }
+}
+
+export function validatePatchBlend(change: {
+ feather?: number;
+ opacity?: number;
+}) {
+ for (const [name, value] of Object.entries(change)) {
+ if (typeof value !== "number" || !(value >= 0 && value <= 1)) {
+ throw Error(`Heal patch ${name} must be between 0 and 1.`);
+ }
+ }
+}
+
+export function validateHealPatch(patch: HealPatch) {
+ validatePatchStroke(patch.stroke);
+ validateOffset(patch.offset);
+ validatePatchBlend({ feather: patch.feather, opacity: patch.opacity });
+}
diff --git a/src/features/layers/edits.ts b/src/features/layers/edits.ts
index f432ffe..d0b605e 100644
--- a/src/features/layers/edits.ts
+++ b/src/features/layers/edits.ts
@@ -6,6 +6,7 @@ import {
type Layer,
locateLayer,
type Mask,
+ type MaskLayer,
type ProcessingLayer,
type Scene,
type StrokePoint,
@@ -14,7 +15,7 @@ import {
} from "@/core/document";
import { validateStroke, validPoints } from "@/core/document/brush";
-function validateMask(mask: Mask) {
+export function validateMask(mask: Mask) {
if (mask.kind === "brush") {
if (!Array.isArray(mask.strokes)) {
throw Error("A brush mask needs a list of strokes.");
@@ -76,7 +77,7 @@ function changeChildren(
}));
}
-function validateDepth(layers: readonly Layer[]) {
+export function validateDepth(layers: readonly Layer[]) {
if (
layers.some((layer) =>
layer.children.some((child) => child.children.length > 0),
@@ -137,11 +138,9 @@ export function addLayer(
return layer.id;
}
-export function setLayer(
- document: EditorDocument,
- id: string,
- change: Partial<Pick<ProcessingLayer, "visible" | "opacity" | "name">>,
-) {
+type LayerSettings = Pick<ProcessingLayer, "visible" | "opacity" | "name">;
+
+export function validateLayerSettings(change: Partial<LayerSettings>) {
if (
Object.keys(change).some(
(key) => !["visible", "opacity", "name"].includes(key),
@@ -157,18 +156,30 @@ export function setLayer(
) {
throw Error("Invalid layer settings.");
}
+}
+
+export function setLayer(
+ document: EditorDocument,
+ id: string,
+ change: Partial<LayerSettings>,
+) {
+ validateLayerSettings(change);
processingLayer(document, id);
editLayer(document, id, (layer) => ({ ...layer, ...change }));
}
+export function validateExposure(exposure: number) {
+ if (!Number.isFinite(exposure) || Math.abs(exposure) > 5) {
+ throw Error("Exposure must be between -5 and 5 EV.");
+ }
+}
+
export function setExposure(
document: EditorDocument,
id: string,
exposure: number,
) {
- if (!Number.isFinite(exposure) || Math.abs(exposure) > 5) {
- throw Error("Exposure must be between -5 and 5 EV.");
- }
+ validateExposure(exposure);
editLayer(document, id, (layer) => {
if (layer.kind !== "exposure") {
throw Error("Select an exposure layer.");
@@ -235,14 +246,18 @@ export function extendStroke(
});
}
+export function validateMaskOperation(operation: MaskLayer["operation"]) {
+ if (operation !== "add" && operation !== "subtract") {
+ throw Error("Choose Add or Subtract for a mask.");
+ }
+}
+
export function setMaskOperation(
document: EditorDocument,
id: string,
- operation: "add" | "subtract",
+ operation: MaskLayer["operation"],
) {
- if (operation !== "add" && operation !== "subtract") {
- throw Error("Choose Add or Subtract for a mask.");
- }
+ validateMaskOperation(operation);
editLayer(document, id, (layer) => {
if (layer.kind !== "mask") {
throw Error("Select a mask layer.");
diff --git a/src/features/white-balance/edits.ts b/src/features/white-balance/edits.ts
index 86b2cb1..7999927 100644
--- a/src/features/white-balance/edits.ts
+++ b/src/features/white-balance/edits.ts
@@ -14,7 +14,10 @@ export function whiteBalanceLimits(asShot: WhiteBalance) {
};
}
-function validateWhiteBalance(balance: WhiteBalance, asShot: WhiteBalance) {
+export function validateWhiteBalance(
+ balance: WhiteBalance,
+ asShot: WhiteBalance,
+) {
const limits = whiteBalanceLimits(asShot);
for (const channel of ["temperature", "tint"] as const) {
const value = balance[channel];
diff --git a/src/lib/zip.ts b/src/lib/zip.ts
new file mode 100644
index 0000000..e119c4c
--- /dev/null
+++ b/src/lib/zip.ts
@@ -0,0 +1,187 @@
+/** A ZIP archive with stored or deflated entries up to 4 GB each, using the browser's compression streams. */
+
+const crcTable = new Uint32Array(256).map((_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) {
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ }
+ return c;
+});
+
+async function crc32(blob: Blob) {
+ let crc = ~0;
+ const reader = blob.stream().getReader();
+ for (
+ let chunk = await reader.read();
+ !chunk.done;
+ chunk = await reader.read()
+ ) {
+ const bytes = chunk.value;
+ for (let i = 0; i < bytes.length; i++) {
+ crc = crcTable[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
+ }
+ }
+ return ~crc >>> 0;
+}
+
+function transform(
+ blob: Blob,
+ stream: CompressionStream | DecompressionStream,
+) {
+ return new Response(blob.stream().pipeThrough(stream)).blob();
+}
+
+/** A signature followed by little-endian fields of two or four bytes. */
+function record(signature: number, fields: readonly [number, 2 | 4][]) {
+ const view = new DataView(
+ new ArrayBuffer(4 + fields.reduce((sum, [, size]) => sum + size, 0)),
+ );
+ view.setUint32(0, signature, true);
+ let at = 4;
+ for (const [value, size] of fields) {
+ if (size === 2) {
+ view.setUint16(at, value, true);
+ } else {
+ view.setUint32(at, value, true);
+ }
+ at += size;
+ }
+ return view.buffer;
+}
+
+export type ZipEntry = { name: string; data: Blob; deflate?: boolean };
+
+export async function writeZip(entries: readonly ZipEntry[]) {
+ const files: BlobPart[] = [];
+ const directory: BlobPart[] = [];
+ let offset = 0;
+ for (const { name, data, deflate } of entries) {
+ const path = new TextEncoder().encode(name);
+ const body = deflate
+ ? await transform(data, new CompressionStream("deflate-raw"))
+ : data;
+ if (Math.max(data.size, body.size, offset) > 0xffffffff) {
+ throw Error("ZIP entries are limited to 4 GB.");
+ }
+ // Version 2.0, UTF-8 names, method, the DOS epoch as modification time, CRC, sizes, and name length.
+ const fields: [number, 2 | 4][] = [
+ [20, 2],
+ [0x800, 2],
+ [deflate ? 8 : 0, 2],
+ [0, 2],
+ [0x21, 2],
+ [await crc32(data), 4],
+ [body.size, 4],
+ [data.size, 4],
+ [path.length, 2],
+ [0, 2],
+ ];
+ files.push(record(0x04034b50, fields), path, body);
+ directory.push(
+ record(0x02014b50, [
+ [20, 2],
+ ...fields,
+ [0, 2],
+ [0, 2],
+ [0, 2],
+ [0, 4],
+ [offset, 4],
+ ]),
+ path,
+ );
+ offset += 30 + path.length + body.size;
+ }
+ const directorySize = new Blob(directory).size;
+ return new Blob([
+ ...files,
+ ...directory,
+ record(0x06054b50, [
+ [0, 2],
+ [0, 2],
+ [entries.length, 2],
+ [entries.length, 2],
+ [directorySize, 4],
+ [offset, 4],
+ [0, 2],
+ ]),
+ ]);
+}
+
+/**
+ * Entries by name, found through the central directory so archives written with data descriptors read too.
+ * A deflated entry inflates only when it declares at most `inflateLimit` bytes, since a small archive can declare gigabytes.
+ */
+export async function readZip(archive: Blob, inflateLimit = 0xffffffff) {
+ // The end record is 22 bytes, followed by a comment of at most 64 KiB.
+ const tailStart = Math.max(0, archive.size - 22 - 0xffff);
+ const tail = new DataView(await archive.slice(tailStart).arrayBuffer());
+ let end = tail.byteLength - 22;
+ while (end >= 0 && tail.getUint32(end, true) !== 0x06054b50) {
+ end--;
+ }
+ if (end < 0) {
+ throw Error("Not a ZIP archive.");
+ }
+ const count = tail.getUint16(end + 10, true);
+ const size = tail.getUint32(end + 12, true);
+ const start = tail.getUint32(end + 16, true);
+ if (start + size > tailStart + end) {
+ throw Error("Invalid ZIP directory.");
+ }
+ const directory = new DataView(
+ await archive.slice(start, start + size).arrayBuffer(),
+ );
+ const decoder = new TextDecoder();
+ const entries = new Map<string, Blob>();
+ for (let at = 0, index = 0; index < count; index++) {
+ if (at + 46 > size || directory.getUint32(at, true) !== 0x02014b50) {
+ throw Error("Invalid ZIP directory.");
+ }
+ const method = directory.getUint16(at + 10, true);
+ const compressed = directory.getUint32(at + 20, true);
+ const inflated = directory.getUint32(at + 24, true);
+ const nameLength = directory.getUint16(at + 28, true);
+ const offset = directory.getUint32(at + 42, true);
+ if (at + 46 + nameLength > size) {
+ throw Error("Invalid ZIP directory.");
+ }
+ const name = decoder.decode(
+ new Uint8Array(directory.buffer, at + 46, nameLength),
+ );
+ at +=
+ 46 +
+ nameLength +
+ directory.getUint16(at + 30, true) +
+ directory.getUint16(at + 32, true);
+ // Local headers repeat the name but may carry a different extra field.
+ const local = new DataView(
+ await archive.slice(offset, offset + 30).arrayBuffer(),
+ );
+ if (local.byteLength < 30 || local.getUint32(0, true) !== 0x04034b50) {
+ throw Error(`Invalid ZIP entry: ${name}.`);
+ }
+ const data =
+ offset + 30 + local.getUint16(26, true) + local.getUint16(28, true);
+ if (data + compressed > start) {
+ throw Error(`Truncated ZIP entry: ${name}.`);
+ }
+ const body = archive.slice(data, data + compressed);
+ if (method === 0) {
+ entries.set(name, body);
+ } else if (method !== 8) {
+ throw Error(`Unsupported ZIP compression in ${name}.`);
+ } else if (inflated > inflateLimit) {
+ throw Error(`ZIP entry is too large: ${name}.`);
+ } else {
+ const blob = await transform(
+ body,
+ new DecompressionStream("deflate-raw"),
+ );
+ if (blob.size !== inflated) {
+ throw Error(`Corrupt ZIP entry: ${name}.`);
+ }
+ entries.set(name, blob);
+ }
+ }
+ return entries;
+}
diff --git a/src/main.tsx b/src/main.tsx
index ff8ea42..d1f7d13 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client";
import { GpuProvider } from "vgpu-react";
import App from "@/app";
+import { TextLink } from "@/components/ui/text-link";
import "./index.css";
/** GPU initialization throws during render; without WebGPU the page would otherwise stay blank. */
@@ -29,12 +30,9 @@ class GpuBoundary extends Component<
in a recent Chrome, Edge, Safari, or Firefox.
</p>
<p className="text-neutral-500">{String(this.state.error)}</p>
- <a
- href="https://github.com/roprgm/openlight"
- className="text-neutral-200 underline decoration-neutral-600 underline-offset-4 hover:decoration-neutral-200"
- >
+ <TextLink href="https://github.com/roprgm/openlight">
github.com/roprgm/openlight
- </a>
+ </TextLink>
</main>
);
}
diff --git a/tests/draft.e2e.ts b/tests/draft.e2e.ts
new file mode 100644
index 0000000..e0f5fbb
--- /dev/null
+++ b/tests/draft.e2e.ts
@@ -0,0 +1,125 @@
+import type { Page } from "@playwright/test";
+import { expect, test } from "./fixtures";
+import { readImage } from "./images";
+
+/** The stored draft's base exposure and source keys, read straight from IndexedDB. */
+function storedDraft(page: Page) {
+ return page.evaluate(
+ () =>
+ new Promise<{ exposure: number; sources: IDBValidKey[] } | null>(
+ (resolve, reject) => {
+ const opening = indexedDB.open("openlight", 1);
+ opening.onerror = () => reject(opening.error);
+ opening.onsuccess = () => {
+ const database = opening.result;
+ const transaction = database.transaction(["draft", "sources"]);
+ const record = transaction.objectStore("draft").get("latest");
+ const sources = transaction.objectStore("sources").getAllKeys();
+ transaction.oncomplete = () => {
+ database.close();
+ resolve(
+ record.result
+ ? {
+ exposure:
+ record.result.scene.scene.layers[0].adjustments
+ .exposure,
+ sources: sources.result,
+ }
+ : null,
+ );
+ };
+ };
+ },
+ ),
+ );
+}
+
+test("edits survive a reload as a draft that recovers, keeps editing, and can be forgotten", async ({
+ page,
+}) => {
+ await page.goto("/");
+ const recover = page.getByRole("button", { name: "Recover", exact: true });
+ const forget = page.getByRole("button", { name: "Forget", exact: true });
+ await page
+ .locator('input[type="file"]')
+ .setInputFiles("tests/fixtures/photo.svg");
+ const exposure = page.getByRole("textbox", { name: "Exposure", exact: true });
+ await expect(exposure).toHaveValue("0.00");
+ await expect(recover).toHaveCount(0);
+ expect(await storedDraft(page)).toBeNull();
+
+ await page.evaluate(() => {
+ const api = window.openlight;
+ api.setAdjustments({ exposure: -1 });
+ const mask = api.addLayer("mask");
+ api.setLayerMask(mask, {
+ kind: "radial",
+ center: [600, 400],
+ radius: [300, 200],
+ angle: 0,
+ feather: 0.5,
+ });
+ api.setAdjustments({ exposure: 1.5 }, mask);
+ api.selectLayer(api.getState().scene?.layers[0].id ?? "");
+ });
+ await expect(exposure).toHaveValue("-1.00");
+ const samples = [
+ [600, 400],
+ [1100, 400],
+ ] as const;
+ const edited = await readImage(page, undefined, samples);
+ await expect.poll(() => storedDraft(page)).toMatchObject({ exposure: -1 });
+ const { sources } = (await storedDraft(page)) ?? { sources: [] };
+ expect(sources).toHaveLength(1);
+
+ await page.reload();
+ await expect(recover).toBeVisible();
+ await expect(forget).toBeVisible();
+ await recover.click();
+ await expect(exposure).toHaveValue("-1.00");
+ expect(await readImage(page, undefined, samples)).toEqual(edited);
+ expect(
+ (await page.evaluate(() => window.openlight.getState())).history.undoCount,
+ ).toBe(0);
+
+ await page.evaluate(() => window.openlight.setAdjustments({ exposure: 0.5 }));
+ await expect(exposure).toHaveValue("0.50");
+ // The recovered source keeps its ID, so the save reuses the stored file.
+ await expect
+ .poll(() => storedDraft(page))
+ .toEqual({ exposure: 0.5, sources });
+
+ await page.reload();
+ await forget.click();
+ await expect(recover).toHaveCount(0);
+ expect(await storedDraft(page)).toBeNull();
+ await page.reload();
+ await expect(page.getByText("choose a file")).toBeVisible();
+ await expect(recover).toHaveCount(0);
+});
+
+test("without IndexedDB a notice suggests scene files and editing still works", async ({
+ page,
+}) => {
+ await page.addInitScript(() =>
+ Object.defineProperty(window, "indexedDB", { value: undefined }),
+ );
+ await page.goto("/");
+ const notice = page.getByRole("status").filter({ hasText: "Drafts" });
+ await expect(notice).toContainText("Save a scene from Export");
+ await page
+ .locator('input[type="file"]')
+ .setInputFiles("tests/fixtures/photo.svg");
+ await page.evaluate(() => window.openlight.setAdjustments({ exposure: 1 }));
+ await expect(
+ page.getByRole("textbox", { name: "Exposure", exact: true }),
+ ).toHaveValue("1.00");
+ await notice.getByRole("button", { name: "Dismiss" }).click();
+ await expect(notice).toHaveCount(0);
+ // The autosave after that edit fails the same way without bringing the notice back.
+ await page.waitForTimeout(2000);
+ await expect(notice).toHaveCount(0);
+ await expect(
+ page.evaluate(() => window.openlight.recoverDraft()),
+ ).rejects.toThrow("IndexedDB is unavailable.");
+});
diff --git a/tests/draft.test.ts b/tests/draft.test.ts
new file mode 100644
index 0000000..a023a9c
--- /dev/null
+++ b/tests/draft.test.ts
@@ -0,0 +1,86 @@
+import { expect, test } from "bun:test";
+import { init, target } from "vgpu/mock";
+import { openDraft, snapshotDraft } from "@/app/draft/store";
+import { createImageLayer, createLayer } from "@/app/editor/layers";
+import { createDocument, createResources } from "@/core/document";
+import { createImageSource } from "@/core/image";
+import { imageFrame } from "@/core/image/frame";
+import { setAdjustments } from "@/features/adjustments/edits";
+import { addLayer } from "@/features/layers/edits";
+import { setVignette } from "@/features/vignette/edits";
+
+test("a draft survives storage's structured clone, reopens under its source ID, and rejects malformed records", async () => {
+ const gpu = await init();
+ const decode = () =>
+ Promise.resolve(
+ createImageSource(target(gpu, { size: [8, 4], format: "rgba16float" })),
+ );
+ const bytes = new Uint8Array([1, 2, 3, 4]);
+ const resources = createResources();
+ const source = resources.add(
+ new File([bytes], "photo.png", { type: "image/png" }),
+ await decode(),
+ );
+ expect(() =>
+ resources.add(
+ new File([], "copy.png"),
+ createImageSource(target(gpu, { size: [1, 1] })),
+ source,
+ ),
+ ).toThrow("already exists");
+ const document = createDocument(
+ {
+ frame: imageFrame([8, 4]),
+ layers: [createImageLayer(source, "photo.png")],
+ },
+ resources,
+ );
+ setAdjustments(document, { exposure: 0.5 });
+ const vignette = addLayer(document, createLayer("vignette"));
+ setVignette(document, { intensity: 30, softness: 70 }, vignette);
+ const edited = document.scene.getState();
+
+ // IndexedDB stores values with the structured clone algorithm, which keeps File objects.
+ const stored = structuredClone(snapshotDraft(document, "photo.png"));
+ document.dispose();
+ expect(stored.record).toMatchObject({ version: 1, name: "photo.png" });
+ const file = stored.files.get(source);
+ expect(file).toBeInstanceOf(File);
+ expect(await file?.bytes()).toEqual(bytes);
+ const recovered = await openDraft(stored, decode);
+ expect(recovered.scene.getState()).toEqual(edited);
+ expect(recovered.resources.get(source).file.name).toBe("photo.png");
+ expect(recovered.history.status.getState().undoCount).toBe(0);
+ recovered.dispose();
+
+ const { record, files } = stored;
+ const malformed: [unknown, string][] = [
+ [undefined, "Invalid draft."],
+ [{ ...record, version: "1" }, "Invalid draft."],
+ [{ ...record, version: 2 }, "This draft needs a newer version"],
+ [{ ...record, scene: undefined }, "doesn't contain an OpenLight scene"],
+ [
+ { ...record, scene: { ...record.scene, version: 2 } },
+ "This scene needs a newer version",
+ ],
+ ];
+ for (const [value, message] of malformed) {
+ await expect(
+ openDraft({ record: value as typeof record, files }, decode),
+ ).rejects.toThrow(message);
+ }
+ await expect(openDraft({ record, files: new Map() }, decode)).rejects.toThrow(
+ "The scene's image is missing.",
+ );
+
+ // A draft from before a group gained a parameter opens with its default, as a scene file does.
+ const older = structuredClone(record);
+ const layer = older.scene.scene.layers[1];
+ if (layer.kind !== "vignette") throw Error("Missing vignette.");
+ Reflect.deleteProperty(layer.vignette, "softness");
+ const reopened = await openDraft({ record: older, files }, decode);
+ expect(reopened.scene.getState().layers[1]).toMatchObject({
+ vignette: { intensity: 30, softness: 50 },
+ });
+ reopened.dispose();
+});
diff --git a/tests/editing.e2e.ts b/tests/editing.e2e.ts
index dbcaf18..e891604 100644
--- a/tests/editing.e2e.ts
+++ b/tests/editing.e2e.ts
@@ -482,7 +482,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
await exportButton.click();
await expect(exportButton).toHaveAttribute("aria-pressed", "true");
await expect(
- page.getByRole("region", { name: "Export settings" }),
+ page.getByRole("region", { name: "Image export" }),
).toBeVisible();
await expect(
page.getByRole("region", { name: "Layers", exact: true }),
@@ -495,14 +495,15 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
await modes.getByRole("tab", { name: "Crop" }).click();
await expect(selected).toHaveAccessibleName("Crop");
await page.keyboard.press("ArrowLeft");
+ await expect(selected).toHaveAccessibleName("Healing");
+ await page.keyboard.press("ArrowLeft");
await expect(selected).toHaveAccessibleName("Radial gradient");
await expect(
page.getByRole("heading", { name: "Adjustments", exact: true }),
).toBeVisible();
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
- await page.keyboard.press("ArrowLeft");
- await expect(selected).toHaveAccessibleName("Healing");
+ await expect(selected).toHaveAccessibleName("Brush");
await page.keyboard.press("ArrowLeft");
await expect(selected).toHaveAccessibleName("Adjust");
await expect(selected).toBeFocused();
@@ -973,7 +974,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
expect(expected.corner[3]).toBe(255);
await canvas.hover();
await zoom(page, Math.E);
- const panel = page.getByRole("region", { name: "Export settings" });
+ const panel = page.getByRole("region", { name: "Image export" });
await page.getByRole("button", { name: "Export", exact: true }).click();
const quality = panel.getByRole("textbox", { name: "Quality" });
async function save(name: string) {
diff --git a/tests/fixtures/info-zip.zip b/tests/fixtures/info-zip.zip
new file mode 100644
index 0000000..c7f418d
Binary files /dev/null and b/tests/fixtures/info-zip.zip differ
diff --git a/tests/scene-file.e2e.ts b/tests/scene-file.e2e.ts
new file mode 100644
index 0000000..06c97f1
--- /dev/null
+++ b/tests/scene-file.e2e.ts
@@ -0,0 +1,72 @@
+import { readFile } from "node:fs/promises";
+import { expect, test } from "./fixtures";
+import { readImage } from "./images";
+
+test("a saved scene reopens the photo with its edits and keeps editing", async ({
+ page,
+}) => {
+ await page.goto("/");
+ const picker = page.locator('input[type="file"]');
+ await picker.setInputFiles("tests/fixtures/photo.svg");
+ const exposure = page.getByRole("textbox", { name: "Exposure", exact: true });
+ await expect(exposure).toHaveValue("0.00");
+ // Inside the radial mask, and on the light strip outside it.
+ const samples = [
+ [600, 400],
+ [1100, 400],
+ ] as const;
+ const baseline = await readImage(page, undefined, samples);
+ await page.evaluate(() => {
+ const api = window.openlight;
+ api.setAdjustments({ exposure: -1 });
+ const mask = api.addLayer("mask");
+ api.setLayerMask(mask, {
+ kind: "radial",
+ center: [600, 400],
+ radius: [300, 200],
+ angle: 0,
+ feather: 0.5,
+ });
+ api.setAdjustments({ exposure: 1.5 }, mask);
+ api.setFill({ color: "#3060c0", blend: "soft-light" });
+ api.selectLayer(api.getState().scene?.layers[0].id ?? "");
+ });
+ await expect(exposure).toHaveValue("-1.00");
+ const edited = await readImage(page, undefined, samples);
+ const [inside, outside] = edited.samples ?? [];
+ expect(outside[0]).toBeLessThan(baseline.samples?.[1][0] ?? 0);
+ expect(inside).not.toEqual(outside);
+
+ await page.getByRole("button", { name: "Export", exact: true }).click();
+ const pending = page.waitForEvent("download");
+ await page
+ .getByRole("region", { name: "Scene export" })
+ .getByRole("button", { name: "Save scene" })
+ .click();
+ const download = await pending;
+ expect(download.suggestedFilename()).toBe("photo.openlight");
+ const path = await download.path();
+ if (!path) throw new Error("Missing scene download.");
+
+ await page.reload();
+ await expect(picker).toHaveAttribute("accept", /\.openlight/);
+ await picker.setInputFiles({
+ name: "photo.openlight",
+ mimeType: "",
+ buffer: await readFile(path),
+ });
+ await expect(exposure).toHaveValue("-1.00");
+ await expect(page.getByText("photo.openlight")).toBeVisible();
+ await expect(
+ page
+ .getByRole("region", { name: "Layers", exact: true })
+ .getByText("Color"),
+ ).toBeVisible();
+ expect(await readImage(page, undefined, samples)).toEqual(edited);
+
+ await page.evaluate(() => window.openlight.setAdjustments({ exposure: 0 }));
+ await expect(exposure).toHaveValue("0.00");
+ await page.keyboard.press("ControlOrMeta+z");
+ await expect(exposure).toHaveValue("-1.00");
+ expect(await readImage(page, undefined, samples)).toEqual(edited);
+});
diff --git a/tests/scene-file.test.ts b/tests/scene-file.test.ts
new file mode 100644
index 0000000..834203e
--- /dev/null
+++ b/tests/scene-file.test.ts
@@ -0,0 +1,192 @@
+import { expect, test } from "bun:test";
+import { init, target } from "vgpu/mock";
+import { createControls } from "@/app/controls";
+import { createImageLayer } from "@/app/editor/layers";
+import { openSceneFile } from "@/app/scene-file";
+import { createWorkspace } from "@/app/workspace";
+import { createDocument, createResources } from "@/core/document";
+import { createImageSource, type WhiteBalance } from "@/core/image";
+import { imageFrame } from "@/core/image/frame";
+import { readZip, writeZip } from "@/lib/zip";
+
+const asShot = { temperature: 5000, tint: 10 };
+const size = [64, 32] as const;
+const bytes = new Uint8Array(4096).map((_, index) => index * 7);
+
+async function decoder(balance?: WhiteBalance) {
+ const gpu = await init();
+ const decoded: File[] = [];
+ function decode(file: File) {
+ decoded.push(file);
+ const raw = balance && {
+ asShot: balance,
+ createPass(): never {
+ throw Error("Not rendered.");
+ },
+ dispose() {},
+ };
+ return Promise.resolve(
+ createImageSource(target(gpu, { size, format: "rgba16float" }), raw),
+ );
+ }
+ return { decode, decoded };
+}
+
+test("scene files reopen the photo with every layer for further editing", async () => {
+ const workspace = createWorkspace();
+ const api = createControls(await init(), workspace);
+ const raw = await decoder(asShot);
+ try {
+ await workspace.open("photo.nef", async () => {
+ const file = new File([bytes], "photo.nef", {
+ type: "image/x-nikon-nef",
+ });
+ const resources = createResources();
+ const source = resources.add(file, await raw.decode(file));
+ return createDocument(
+ {
+ frame: imageFrame(size),
+ layers: [createImageLayer(source, "photo.nef", asShot)],
+ },
+ resources,
+ );
+ });
+ api.setAdjustments({ exposure: 1, contrast: 20 });
+ api.setWhiteBalance({ temperature: 6500 });
+ api.setToneCurve([
+ { x: 0, y: 0 },
+ { x: 0.5, y: 0.6 },
+ { x: 1, y: 1 },
+ ]);
+ api.setFrame({
+ center: [30, 16],
+ size: [40, 24],
+ rotation: 90,
+ angle: 5,
+ scale: [-1, 1],
+ });
+ const mask = api.addLayer("mask");
+ api.setLayerMask(mask, {
+ kind: "brush",
+ strokes: [
+ {
+ mode: "paint",
+ size: 6,
+ feather: 0.5,
+ flow: 0.8,
+ points: [
+ [10.25, 8, 1],
+ [20, 12.5, 0.5],
+ ],
+ },
+ ],
+ });
+ api.setAdjustments({ shadows: 40 }, mask);
+ api.setDetails({ clarity: 30 }, api.addLayer("details", { inside: mask }));
+ const subtract = api.addLayer("mask", { inside: mask });
+ api.setLayerMask(subtract, {
+ kind: "radial",
+ center: [16, 16],
+ radius: [8, 6],
+ angle: 30,
+ feather: 0.4,
+ });
+ api.setMaskOperation(subtract, "subtract");
+ const heal = api.addLayer("heal");
+ api.addHealPatch(
+ heal,
+ { mode: "paint", size: 4, feather: 0.2, flow: 1, points: [[40, 20, 1]] },
+ [-6, 2],
+ );
+ api.setFill({ color: "#123456", blend: "soft-light" });
+ const fill = api.getState().scene?.layers.at(-1)?.id ?? "";
+ api.setLayer(fill, { name: "Warm", opacity: 0.5, visible: false });
+ api.setVignette({ intensity: 70, softness: 20 });
+ api.setColorMixer("blue", { hue: 20, luminance: -10 });
+ api.setExposure(api.addLayer("exposure"), -0.5);
+ const edited = workspace.getDocument().scene.getState();
+
+ const file = await api.exportScene();
+ expect(file.name).toBe("photo.openlight");
+ const entries = await readZip(file);
+ const json = JSON.parse((await entries.get("scene.json")?.text()) ?? "");
+ const { source } = edited.layers[0];
+ expect(json).toMatchObject({
+ format: "openlight",
+ version: 1,
+ sources: { [source]: { name: "photo.nef", type: "image/x-nikon-nef" } },
+ scene: edited,
+ });
+ const stored = await entries.get(`sources/${source}`)?.bytes();
+ expect(stored).toEqual(bytes);
+
+ const opened = await openSceneFile(file, raw.decode);
+ const reopened = raw.decoded.at(-1);
+ expect(reopened?.name).toBe("photo.nef");
+ expect(reopened?.type).toBe("image/x-nikon-nef");
+ expect(await reopened?.bytes()).toEqual(bytes);
+ expect(opened.scene.getState()).toEqual(edited);
+ expect(opened.history.status.getState().undoCount).toBe(0);
+ opened.dispose();
+
+ async function archive(value: unknown, sources = entries) {
+ return writeZip([
+ { name: "scene.json", data: new Blob([JSON.stringify(value)]) },
+ ...[...sources]
+ .filter(([name]) => name !== "scene.json")
+ .map(([name, data]) => ({ name, data })),
+ ]);
+ }
+ const invalid: [Blob, string][] = [
+ [new Blob(["not a zip"]), "Not a ZIP archive."],
+ [
+ await archive({ ...json, format: "other" }),
+ "doesn't contain an OpenLight scene",
+ ],
+ [await archive({ ...json, version: 2 }), "needs a newer version"],
+ [await archive(json, new Map()), "The scene's image is missing."],
+ [
+ await archive({
+ ...json,
+ scene: {
+ ...json.scene,
+ layers: [...json.scene.layers, json.scene.layers[1]],
+ },
+ }),
+ "IDs must be unique",
+ ],
+ [
+ await archive({
+ ...json,
+ scene: {
+ ...json.scene,
+ layers: [
+ ...json.scene.layers,
+ { ...json.scene.layers[2], id: "new", kind: "text" },
+ ],
+ },
+ }),
+ "Unknown layer kind: text.",
+ ],
+ ];
+ for (const [value, message] of invalid) {
+ await expect(openSceneFile(value, raw.decode)).rejects.toThrow(message);
+ }
+
+ // A parameter missing from a group takes its default, as in a file older than that parameter.
+ const vignette = json.scene.layers.find(
+ (layer: { kind: string }) => layer.kind === "vignette",
+ );
+ delete vignette.vignette.softness;
+ delete json.scene.layers[0].whiteBalance;
+ const older = await openSceneFile(await archive(json), raw.decode);
+ const loaded = older.scene.getState();
+ expect(loaded.layers[0].whiteBalance).toEqual(asShot);
+ expect(
+ loaded.layers.find((layer) => layer.kind === "vignette"),
+ ).toMatchObject({ vignette: { intensity: 70, softness: 50 } });
+ older.dispose();
+ } finally {
+ workspace.dispose();
+ }
+});
diff --git a/tests/zip.test.ts b/tests/zip.test.ts
new file mode 100644
index 0000000..d37b71e
--- /dev/null
+++ b/tests/zip.test.ts
@@ -0,0 +1,47 @@
+import { expect, test } from "bun:test";
+import { readZip, writeZip } from "@/lib/zip";
+
+test("zip archives round-trip stored and deflated entries and read Info-ZIP data descriptors", async () => {
+ const fixture = await readZip(Bun.file("tests/fixtures/info-zip.zip"));
+ expect(await fixture.get("deflated.txt")?.text()).toBe(
+ "deflated by Info-ZIP ".repeat(20),
+ );
+ expect(await fixture.get("-")?.text()).toBe("streamed ".repeat(8));
+
+ const bytes = new Uint8Array(70_000).map((_, index) => index * 13);
+ const archive = await writeZip([
+ { name: "check", data: new Blob(["123456789"]) },
+ {
+ name: "notes/ñandú.txt",
+ data: new Blob(["ñandú ".repeat(100)]),
+ deflate: true,
+ },
+ { name: "image.raw", data: new Blob([bytes]) },
+ ]);
+ // The first local header's CRC field holds the standard check value.
+ const crc = new DataView(await archive.slice(14, 18).arrayBuffer());
+ expect(crc.getUint32(0, true)).toBe(0xcbf43926);
+ const entries = await readZip(archive);
+ expect([...entries.keys()]).toEqual([
+ "check",
+ "notes/ñandú.txt",
+ "image.raw",
+ ]);
+ expect(await entries.get("notes/ñandú.txt")?.text()).toBe(
+ "ñandú ".repeat(100),
+ );
+ expect(await entries.get("image.raw")?.bytes()).toEqual(bytes);
+
+ // A deflated entry declares its size, so a small archive can't inflate into gigabytes.
+ await expect(readZip(archive, 100)).rejects.toThrow(
+ "ZIP entry is too large: notes/ñandú.txt.",
+ );
+ // The directory sits at the end, so a truncated archive fails before any entry is read.
+ await expect(readZip(archive.slice(0, 40))).rejects.toThrow(
+ "Not a ZIP archive.",
+ );
+ const tail = archive.slice(archive.size - 22 - 3 * 46 - 30);
+ await expect(readZip(new Blob([tail]))).rejects.toThrow(
+ "Invalid ZIP directory.",
+ );
+});