Skip to content

Free open-source image editor for the browser

Run core integration tests without a browser (#2)

Rodrigo Belfiore1822429d7a6b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..500165e
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,30 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@v7
+ - uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.2
+ - run: bun install --frozen-lockfile
+ - name: Lint and format
+ run: bunx --no-install biome ci .
+ - name: Tests
+ run: bun run test
+ - name: Typecheck and build
+ run: bun run build
diff --git a/AGENTS.md b/AGENTS.md
index ad46f3f..0e65b9b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -60,10 +60,10 @@ All React bindings come from `vgpu-react`; everything else comes from `vgpu`.
## Testing
-Prefer a few broad end-to-end tests over many granular tests. Keep one main editing session that opens a fixture, changes controls, checks the preview and histogram, edits curves, uses undo/redo, and exports. Extend that session with named steps instead of adding a test per control. Check actual pixels against known values, with a small tolerance when needed; changed state or a changed screenshot alone does not prove correct rendering. Keep independent loading and rendering checks separate, and load real files for format coverage. Use browser-free tests for invariants that the editing session cannot meaningfully exercise.
+Prefer a few broad integration tests over many granular tests. Run document, history, loader, and renderer orchestration checks in Bun using real application modules and `vgpu/mock`. Keep GPU pixel, browser UI, and codec checks in Playwright; the mock does not execute shaders. Keep one main editing session that opens a fixture, changes controls, checks the preview and histogram, edits curves, uses undo/redo, and exports. Extend that session with named steps instead of adding a test per control. Check actual pixels against known values, with a small tolerance when needed; changed state or a changed screenshot alone does not prove correct rendering. Keep independent loading and rendering checks separate, and load real files for format coverage. Use browser-free tests for invariants that the editing session cannot meaningfully exercise.
Maintain a browser-side control API with semantic commands for loading, editing, and reading state. Extend it with new workflows; it must work in local browsers, CI, and remote sessions. Use DOM interaction when testing the UI itself. Wait for visible results without adding production completion tracking.
## Done
-`bun run check` formats and lints. `bun run build` type-checks. `bun run test` runs the browser tests. Run all three after changing files and before a commit.
+`bun run check` formats and lints. `bun run build` type-checks. `bun run test` runs browser-free tests. `bun run test:browser` runs GPU/browser tests. Run all four after changing files and before a commit.
diff --git a/README.md b/README.md
index 651c1da..9c848f0 100644
--- a/README.md
+++ b/README.md
@@ -14,8 +14,10 @@ bun dev
```
```sh
-bun run check # format + lint
-bun run build # typecheck + bundle
+bun run check # format + lint
+bun run build # typecheck + bundle
+bun run test # fast integration tests; no browser or GPU
+bun run test:browser # pixels, UI, and codecs; requires Chromium + WebGPU
```
## License
diff --git a/bun.lock b/bun.lock
index 2bc8476..c8daf09 100644
--- a/bun.lock
+++ b/bun.lock
@@ -21,10 +21,12 @@
"devDependencies": {
"@biomejs/biome": "2.5.11",
"@playwright/test": "^1.62.1",
+ "@types/bun": "^1.4.1",
"@types/node": "^26.4.1",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.5",
"@vitejs/plugin-react": "^6.1.1",
+ "@xmldom/xmldom": "^0.9.12",
"typescript": "^7.0.2",
"vite": "^8.2.2",
},
@@ -131,6 +133,8 @@
"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="],
+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],
+
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA=="],
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w=="],
@@ -195,6 +199,10 @@
"@webgpu/types": ["@webgpu/[email protected]", "", {}, "sha512-0cF7RFM2edNoiIS1ODJp0/Gzv4/xSXhwoR0YCza+OWpJWtn4wmo9DvK91aLlH9+uUnwIriP7ZiC3WitmyhuzBw=="],
+ "@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A=="],
+
+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],
+
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
diff --git a/bunfig.toml b/bunfig.toml
new file mode 100644
index 0000000..3efd738
--- /dev/null
+++ b/bunfig.toml
@@ -0,0 +1,3 @@
+[test]
+root = "./tests"
+preload = ["./tests/setup.ts"]
diff --git a/package.json b/package.json
index f80d94c..4c904ce 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,8 @@
"dev": "vite",
"build": "tsc && vite build",
"check": "biome check --write",
- "test": "playwright test"
+ "test": "bun test",
+ "test:browser": "playwright test"
},
"dependencies": {
"@fontsource-variable/geist": "^5.3.0",
@@ -25,10 +26,12 @@
"devDependencies": {
"@biomejs/biome": "2.5.11",
"@playwright/test": "^1.62.1",
+ "@types/bun": "^1.4.1",
"@types/node": "^26.4.1",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.5",
"@vitejs/plugin-react": "^6.1.1",
+ "@xmldom/xmldom": "^0.9.12",
"typescript": "^7.0.2",
"vite": "^8.2.2"
}
diff --git a/playwright.config.ts b/playwright.config.ts
index 3376768..0bcace3 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -7,7 +7,7 @@ if (process.platform !== "darwin") {
export default defineConfig({
testDir: "./tests",
- testMatch: ["**/*.e2e.ts", "**/*.test.ts"],
+ testMatch: "**/*.e2e.ts",
use: {
channel: "chromium",
baseURL: "http://127.0.0.1:4173",
diff --git a/tests/curves.test.ts b/tests/curves.test.ts
index 66e4355..e924842 100644
--- a/tests/curves.test.ts
+++ b/tests/curves.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from "@playwright/test";
+import { expect, test } from "bun:test";
import { sampleCurve } from "@/features/tone-curves/curve";
import { interpolatePchip } from "@/lib/math";
diff --git a/tests/documents.test.ts b/tests/documents.test.ts
index 657360d..9daf648 100644
--- a/tests/documents.test.ts
+++ b/tests/documents.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from "@playwright/test";
+import { expect, test } from "bun:test";
import { init, target } from "vgpu/mock";
import { createDocument } from "@/app/document";
import { setAdjustments, setToneCurve } from "@/app/document/edits";
@@ -97,42 +97,42 @@ test("documents edit independently without React, retain bounded history, and re
expect(() => setAdjustments(first, { exposure: 2 })).toThrow("closed");
workspace.dispose();
expect(() => setAdjustments(second, { exposure: 2 })).toThrow("closed");
- await test.step("resources survive undo and are released after cancellation, branching, and history eviction", async () => {
- const gpu = await init();
- const resources = createResources();
- const file = new File(["fixture"], "image.png");
- const add = () => resources.add(file, target(gpu, { size: [2, 2] }));
- const source = add();
- const doc = createDocument(
- { ...document().scene.getState(), source },
- resources,
- );
- const replace = (source: string) =>
- doc.edit({ ...doc.scene.getState(), source });
- const canceled = add();
- doc.history.begin();
- replace(canceled);
- expect(resources.get(source)).toBeDefined();
- doc.history.cancel();
- expect(() => resources.get(canceled)).toThrow("unavailable");
- const branch = add();
- replace(branch);
- doc.history.undo();
- expect(resources.get(branch)).toBeDefined();
- doc.history.redo();
- expect(doc.scene.getState().source).toBe(branch);
- doc.history.undo();
- setAdjustments(doc, { exposure: 1 });
- expect(() => resources.get(branch)).toThrow("unavailable");
- const replacement = add();
- replace(replacement);
- for (let i = 0; i < 100; i++) {
- setAdjustments(doc, { exposure: i % 2 });
- }
- expect(() => resources.get(source)).toThrow("unavailable");
- expect(resources.get(replacement)).toBeDefined();
- doc.dispose();
- expect(() => resources.get(replacement)).toThrow("unavailable");
- gpu.dispose();
- });
+
+ // Resources survive undo and are released after cancellation, branching, and eviction.
+ const gpu = await init();
+ const resources = createResources();
+ const file = new File(["fixture"], "image.png");
+ const add = () => resources.add(file, target(gpu, { size: [2, 2] }));
+ const source = add();
+ const doc = createDocument(
+ { ...document().scene.getState(), source },
+ resources,
+ );
+ const replace = (source: string) =>
+ doc.edit({ ...doc.scene.getState(), source });
+ const canceled = add();
+ doc.history.begin();
+ replace(canceled);
+ expect(resources.get(source)).toBeDefined();
+ doc.history.cancel();
+ expect(() => resources.get(canceled)).toThrow("unavailable");
+ const branch = add();
+ replace(branch);
+ doc.history.undo();
+ expect(resources.get(branch)).toBeDefined();
+ doc.history.redo();
+ expect(doc.scene.getState().source).toBe(branch);
+ doc.history.undo();
+ setAdjustments(doc, { exposure: 1 });
+ expect(() => resources.get(branch)).toThrow("unavailable");
+ const replacement = add();
+ replace(replacement);
+ for (let i = 0; i < 100; i++) {
+ setAdjustments(doc, { exposure: i % 2 });
+ }
+ expect(() => resources.get(source)).toThrow("unavailable");
+ expect(resources.get(replacement)).toBeDefined();
+ doc.dispose();
+ expect(() => resources.get(replacement)).toThrow("unavailable");
+ gpu.dispose();
});
diff --git a/tests/loaders.e2e.ts b/tests/loaders.e2e.ts
index c810c6e..002296a 100644
--- a/tests/loaders.e2e.ts
+++ b/tests/loaders.e2e.ts
@@ -1,200 +1,47 @@
-import type { Page } from "@playwright/test";
+import { readFile } from "node:fs/promises";
import { expect, test } from "./fixtures";
import { readImage } from "./images";
-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("open image and XMP batches, recover from failures, and replace a document during export", async ({
+test("decode an image, apply XMP, recover from failure, and replace a document during export", 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:Highlights2012="-50" crs:Shadows2012="50" crs:Whites2012="25" crs:Blacks2012="-25" 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,
- highlights: -50,
- shadows: 50,
- whites: 25,
- blacks: -25,
- 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,
- highlights: -50,
- shadows: 50,
- whites: 25,
- blacks: -25,
- vibrance: 30,
- saturation: -10,
- });
- await expect
- .poll(() => page.locator("canvas").screenshot())
- .not.toEqual(before);
- const reset = await openFiles(page, [
- settings(
- 'crs:Highlights2012="0" crs:Shadows2012="0" crs:Whites2012="0" crs:Blacks2012="0"',
- ),
- ]);
- expect(reset.adjustments).toMatchObject({
- highlights: 0,
- shadows: 0,
- whites: 0,
- blacks: 0,
- });
- }
- 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"')],
- ],
+ await page.evaluate(() =>
+ window.openlight.loadImage(new File(["invalid"], "broken.png")),
);
- 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 page.evaluate(
+ (text) =>
+ window.openlight.loadImage(
+ new File([text], "photo.svg", { type: "image/svg+xml" }),
+ ),
+ await readFile("tests/fixtures/photo.svg", "utf8"),
+ );
+ const baseline = await readImage(page);
+ expect(baseline.center).toEqual([128, 128, 128, 255]);
+ await page.evaluate(() =>
+ window.openlight.importXmp(
+ new File(
+ [
+ '<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/" crs:Exposure2012="-1" /></rdf:RDF>',
+ ],
+ "photo.xmp",
+ ),
+ ),
+ );
await expect(
page.getByRole("textbox", { name: "Exposure", exact: true }),
).toHaveValue("-1.00");
-
- const baseline = await readImage(page);
+ const expected = await readImage(page);
+ expect(expected.center[0]).toBeLessThan(baseline.center[0]);
const before = await page.evaluate(() => window.openlight.getState());
- await page.evaluate(() => {
- window.openlight.beginEdit();
- window.openlight.setAdjustments({ exposure: 0.5 });
- window.openlight.setAdjustments({ exposure: 1, shadows: 20 });
- window.openlight.setToneCurve([
- { x: 0, y: 0 },
- { x: 0.5, y: 0.7 },
- { x: 1, y: 1 },
- ]);
- window.openlight.commitEdit();
- });
- const edited = await readImage(page);
- expect(edited).not.toEqual(baseline);
- expect(
- (await page.evaluate(() => window.openlight.getState())).history.undoCount,
- ).toBe(before.history.undoCount + 1);
await page.evaluate(() => window.openlight.undo());
expect(await readImage(page)).toEqual(baseline);
await page.evaluate(() => window.openlight.redo());
- expect(await readImage(page)).toEqual(edited);
- await page.evaluate(() => {
- window.openlight.setAdjustments({ exposure: 1 });
- window.openlight.beginEdit();
- window.openlight.setAdjustments({ exposure: -1 });
- window.openlight.cancelEdit();
- });
- expect(await readImage(page)).toEqual(edited);
- expect(
- (await page.evaluate(() => window.openlight.getState())).history.undoCount,
- ).toBe(before.history.undoCount + 1);
- await page.evaluate(() => {
- window.openlight.undo();
- window.openlight.beginEdit();
- window.openlight.setAdjustments({ contrast: 20 });
- });
- const imported = await openFiles(page, [
- settings('crs:Highlights2012="-50"'),
- ]);
- expect(imported.history).toEqual({
- undoCount: before.history.undoCount + 2,
- redoCount: 0,
- });
- await page.evaluate(() => window.openlight.undo());
- expect(
- (await page.evaluate(() => window.openlight.getState())).adjustments,
- ).toMatchObject({ highlights: 0, contrast: 20 });
-
- const expected = await readImage(page);
+ expect(await readImage(page)).toEqual(expected);
const exported = await page.evaluate(async () => {
const api = window.openlight;
const convert = OffscreenCanvas.prototype.convertToBlob;
@@ -226,5 +73,5 @@ test("open image and XMP batches, recover from failures, and replace a document
const replaced = await page.evaluate(() => window.openlight.getState());
expect(replaced.documentId).not.toBe(before.documentId);
expect(replaced.history).toEqual({ undoCount: 0, redoCount: 0 });
- expect(replaced.toneCurve).toEqual(before.toneCurve);
+ expect(replaced.adjustments.exposure).toBe(0);
});
diff --git a/tests/loaders.test.ts b/tests/loaders.test.ts
new file mode 100644
index 0000000..a68da67
--- /dev/null
+++ b/tests/loaders.test.ts
@@ -0,0 +1,155 @@
+import { expect, test } from "bun:test";
+import { createDocument } from "@/app/document";
+import { setAdjustments } from "@/app/document/edits";
+import { createCameraRawXmpLoader } from "@/app/loaders/camera-raw-xmp";
+import { createLoaderRegistry, type FileLoader } from "@/app/loaders/registry";
+import { defaultAdjustments } from "@/app/scene";
+import { createWorkspace } from "@/app/workspace";
+import { defaultCurve } from "@/features/tone-curves/curve";
+
+function settings(attributes: string, name = "photo.xmp") {
+ return new File(
+ [
+ `<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>`,
+ ],
+ name,
+ );
+}
+
+test("file batches preserve ordering, group imports, recover from failures, and discard stale settings", async () => {
+ const workspace = createWorkspace();
+ // Substitute decoding only; the registry, workspace, XMP parser, and documents are real.
+ const image: FileLoader = {
+ kind: "document",
+ accepts: (file) => file.name.endsWith(".png"),
+ load: (file) =>
+ workspace.open(file.name, async () => {
+ if (file.name === "broken.png") throw new Error("Decode failed");
+ return createDocument({
+ size: [32, 32],
+ source: file.name,
+ adjustments: { ...defaultAdjustments },
+ toneCurve: defaultCurve,
+ });
+ }),
+ };
+ const xmp = createCameraRawXmpLoader(workspace);
+ const registry = createLoaderRegistry(
+ [xmp, image],
+ () => workspace.state.getState().status === "ready",
+ );
+ const photo = new File([], "photo.png");
+ const exposure = settings('crs:Exposure2012="1.25"');
+ try {
+ await registry.openFiles([new File([], "notes.txt"), exposure]);
+ expect(workspace.state.getState()).toEqual({ status: "empty" });
+ for (const settingsFirst of [true, false]) {
+ const parameters = settings(
+ 'crs:Exposure2012="1.25" crs:Contrast2012="-20" crs:Highlights2012="-50" crs:Shadows2012="50" crs:Whites2012="25" crs:Blacks2012="-25" crs:Vibrance="30" crs:Saturation="-10"',
+ settingsFirst ? "photo.xml" : "photo.xmp",
+ );
+ const images = [photo, new File([], "broken.png")];
+ await registry.openFiles(
+ settingsFirst ? [parameters, ...images] : [...images, parameters],
+ );
+ const document = workspace.getDocument();
+ expect(workspace.state.getState().file).toBe("photo.png");
+ const imported = {
+ ...defaultAdjustments,
+ exposure: 1.25,
+ contrast: -20,
+ highlights: -50,
+ shadows: 50,
+ whites: 25,
+ blacks: -25,
+ vibrance: 30,
+ saturation: -10,
+ };
+ expect(document.scene.getState().adjustments).toEqual(imported);
+ await registry.openFiles([
+ settings('crs:Exposure2012="3"'),
+ settings('crs:Exposure2012="-1"'),
+ ]);
+ expect(document.scene.getState().adjustments).toEqual({
+ ...imported,
+ exposure: -1,
+ });
+ document.history.undo();
+ expect(document.scene.getState().adjustments.exposure).toBe(3);
+ document.history.redo();
+ document.history.begin();
+ setAdjustments(document, { contrast: 20 });
+ setAdjustments(document, { contrast: 30 });
+ await registry.openFiles([
+ settings(
+ 'crs:Highlights2012="0" crs:Shadows2012="0" crs:Whites2012="0" crs:Blacks2012="0"',
+ ),
+ ]);
+ expect(document.history.status.getState()).toEqual({
+ undoCount: 5,
+ redoCount: 0,
+ });
+ expect(document.scene.getState().adjustments).toMatchObject({
+ highlights: 0,
+ shadows: 0,
+ whites: 0,
+ blacks: 0,
+ });
+ document.history.undo();
+ expect(document.scene.getState().adjustments).toEqual({
+ ...imported,
+ exposure: -1,
+ contrast: 30,
+ });
+ document.history.undo();
+ expect(document.scene.getState().adjustments.contrast).toBe(-20);
+ }
+ await Promise.all([
+ registry.openFiles([exposure, new File([], "first.png")]),
+ registry.openFiles([
+ new File([], "second.png"),
+ settings('crs:Contrast2012="20"'),
+ ]),
+ ]);
+ expect(workspace.state.getState().file).toBe("second.png");
+ expect(workspace.getDocument().scene.getState().adjustments).toEqual({
+ ...defaultAdjustments,
+ contrast: 20,
+ });
+ await registry.openFiles([exposure, new File([], "broken.png")]);
+ expect(workspace.state.getState()).toMatchObject({
+ status: "error",
+ file: "broken.png",
+ error: "Error: Decode failed",
+ });
+ await registry.openFiles([exposure, photo]);
+ const recovered = workspace.getDocument();
+ expect(recovered.scene.getState().adjustments.exposure).toBe(1.25);
+ await expect(
+ registry.openFiles([settings('crs:Exposure2012="99"')]),
+ ).rejects.toThrow("Invalid adjustment");
+ await registry.openFiles([
+ settings('crs:Contrast2012="10" crs:Exposure2012="NaN"'),
+ ]);
+ expect(recovered.scene.getState().adjustments).toEqual({
+ ...defaultAdjustments,
+ exposure: 1.25,
+ contrast: 10,
+ });
+
+ // Hold file reading so replacement happens before the old import completes.
+ const text = Promise.withResolvers<string>();
+ const delayed = settings('crs:Exposure2012="4"');
+ delayed.text = () => text.promise;
+ const pending = xmp.load(delayed);
+ await registry.loadFile(image, photo);
+ text.resolve(await exposure.text());
+ await pending;
+ expect(workspace.getDocument()).not.toBe(recovered);
+ expect(workspace.getDocument().scene.getState().adjustments).toEqual(
+ defaultAdjustments,
+ );
+ } finally {
+ workspace.dispose();
+ }
+});
diff --git a/tests/renderer.test.ts b/tests/renderer.test.ts
new file mode 100644
index 0000000..8467d71
--- /dev/null
+++ b/tests/renderer.test.ts
@@ -0,0 +1,93 @@
+import { expect, mock, test } from "bun:test";
+import {
+ frame,
+ getMockGPUDeviceInstrumentation,
+ init,
+ target,
+} from "vgpu/mock";
+import { createDocument } from "@/app/document";
+import { setAdjustments, setToneCurve } from "@/app/document/edits";
+import { createRenderer } from "@/app/editor/renderer/renderer";
+import { defaultAdjustments } from "@/app/scene";
+import { defaultCurve } from "@/features/tone-curves/curve";
+
+test("rendering follows grouped edits and undo, reuses pipelines, and releases owned targets", async () => {
+ const gpu = await init();
+ const source = target(gpu, { size: [32, 16], format: "rgba16float" });
+ const canvas = Object.assign(target(gpu, { size: [64, 32] }), { dpr: 2 });
+ const document = createDocument({
+ size: [32, 16],
+ source: "photo",
+ adjustments: { ...defaultAdjustments },
+ toneCurve: defaultCurve,
+ });
+ const renderer = createRenderer(gpu, source);
+ const notify = mock(() => {});
+ const detach = renderer.subscribe(notify);
+ const unsubscribe = document.scene.subscribe(renderer.update);
+ const draw = () =>
+ frame(gpu, (frame) =>
+ renderer.draw(frame, canvas, { pan: [4, 8], zoom: 2 }),
+ );
+ try {
+ draw();
+ expect(notify).not.toHaveBeenCalled();
+ renderer.update(document.scene.getState());
+ const adjusted = renderer.inputImage();
+ expect(adjusted.size).toEqual(source.size);
+ expect(adjusted.format).toBe(source.format);
+ expect(renderer.outputImage()).toBe(adjusted);
+ document.history.begin();
+ setAdjustments(document, { exposure: 0.5 });
+ setAdjustments(document, { exposure: 1 });
+ setToneCurve(document, [
+ { x: 0, y: 0 },
+ { x: 0.5, y: 0.7 },
+ { x: 1, y: 1 },
+ ]);
+ document.history.commit();
+ const curved = renderer.outputImage();
+ expect(curved).not.toBe(adjusted);
+ expect(curved.size).toEqual(source.size);
+ expect(renderer.inputImage()).toBe(adjusted);
+ expect(document.history.status.getState()).toEqual({
+ undoCount: 1,
+ redoCount: 0,
+ });
+ draw();
+ const calls = getMockGPUDeviceInstrumentation(gpu.gpu).calls;
+ const pipelines = calls.createRenderPipeline;
+ expect(pipelines).toBeGreaterThan(0);
+ const late = mock(() => {});
+ const detachLate = renderer.subscribe(late);
+ expect(late).toHaveBeenCalledTimes(1);
+ detachLate();
+ document.history.undo();
+ expect(renderer.outputImage()).toBe(adjusted);
+ expect(document.scene.getState().adjustments.exposure).toBe(0);
+ document.history.redo();
+ expect(renderer.outputImage()).toBe(curved);
+ document.history.begin();
+ setToneCurve(document);
+ expect(renderer.outputImage()).toBe(adjusted);
+ document.history.cancel();
+ expect(renderer.outputImage()).toBe(curved);
+ draw();
+ expect(calls.createRenderPipeline).toBe(pipelines);
+ expect(notify).toHaveBeenCalledTimes(8);
+ expect(late).toHaveBeenCalledTimes(1);
+ detach();
+ setAdjustments(document, { exposure: -1 });
+ expect(notify).toHaveBeenCalledTimes(8);
+ renderer.dispose();
+ expect(() => adjusted.color.view).toThrow("destroyed");
+ expect(() => curved.color.view).toThrow("destroyed");
+ expect(() => source.color.view).not.toThrow();
+ } finally {
+ unsubscribe();
+ detach();
+ renderer.dispose();
+ document.dispose();
+ gpu.dispose();
+ }
+});
diff --git a/tests/setup.ts b/tests/setup.ts
new file mode 100644
index 0000000..1e2ad67
--- /dev/null
+++ b/tests/setup.ts
@@ -0,0 +1,15 @@
+import { transformWgsl } from "@vgpu/wgsl/loader-vite";
+import { DOMParser } from "@xmldom/xmldom";
+import { plugin } from "bun";
+
+Object.assign(globalThis, { DOMParser });
+
+await plugin({
+ name: "wgsl",
+ setup(build) {
+ build.onLoad({ filter: /\.wgsl$/ }, async ({ path }) => ({
+ contents: (await transformWgsl(await Bun.file(path).text(), path)).code,
+ loader: "js",
+ }));
+ },
+});
diff --git a/tsconfig.json b/tsconfig.json
index bdaa721..6c61b69 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ES2023",
"lib": ["ES2023", "DOM"],
- "types": ["node"],
+ "types": ["node", "bun"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",