Free open-source image editor for the browser
Add GPU photo adjustments, shared scene rendering, and browser commands
Rodrigoa6a2c8d1279b
diff --git a/AGENTS.md b/AGENTS.mdindex c11113f..73d7c5f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -2,14 +2,25 @@A Vite, React, and vgpu app. Bun for install and scripts. Biome for format and lint.-`src/main.tsx` owns runtime and provider composition. Browser and WebGPU lifecycles stay behind `vgpu-react` providers and hooks.+Demonstrate a professional photo editor with little, readable code.++`src/main.tsx` owns runtime and provider composition.## SizeKeep each file focused on one responsibility and one abstraction level. Entry points compose; providers, hooks, and domain modules own lifecycles and policy.Prefer the smallest implementation that preserves clear ownership.+Prefer direct vgpu operations. Add wrappers, validation, scheduling, or caching only for a current requirement.One component per responsibility: when a component holds state or refs that only part of its markup uses, extract that part into its own component. Within a file, define a function above the function that uses it.+## Engine and React++React owns UI composition, controls, and mounting engine outputs. Scene actions perform decoding and other processing imperatively. The engine owns GPU resources, rendering, and derived data such as histogram bins; frame data stays outside React state and props.++Providers expose stable engine instances and connect their lifetime to mounting and cleanup. The engine creates and disposes its resources. Canvas and histogram components attach their outputs through the provider.++The Zustand scene store owns document state. UI interactions and browser commands call the same actions; the renderer reads the scene directly.+## StructureThe `src/` root holds entrypoints, ambient types, and global styles. Import across folders through the `@/` alias (`@/hooks/use-pointer`); relative paths stay inside a folder. Source modules belong to these folders:@@ -22,6 +33,7 @@ The `src/` root holds entrypoints, ambient types, and global styles. Import acroDependencies point downward: `app/` may import every folder; `features/` may import `components/`, `hooks/`, and `lib/`; `components/` and `hooks/` may import `lib/`.Keep feature-specific components, hooks, and helpers inside their feature. Move them to a generic folder only when their interface no longer contains feature concepts.+Keep the histogram in `features/`; revisit its placement only when its responsibilities change.## Styling@@ -32,17 +44,19 @@ Tailwind classes stay inline in the component that renders them; reuse styling bAll React bindings come from `vgpu-react`; everything else comes from `vgpu`.- `useGpu()` returns the `Gpu`. Every vgpu call takes it as the first argument.-- Build pipelines once: `useMemo(() => effect(gpu, shader), [gpu])`.+- Build pipelines once per engine instance and reuse them across frames.- `useSurface(canvasRef)` turns a `<canvas>` into a render target and disposes it on unmount. Its options are read once; to change them, remount the canvas with a `key`.- `useFrameLoop` renders every animation frame. `useFrame` returns a function that renders once, for pointer and other events.-- Shader code lives in `.wgsl` files next to the component that imports them. The Vite loader and ambient types are already configured.+- Shader code lives in `.wgsl` files beside the module that owns it, or in `lib/` for reusable GPU operations. The Vite loader and ambient types are already configured.- The working space is linear Rec.2020 in `rgba16float`. Decoders convert into it, the editor shader converts out of it; nothing in between assumes a format or primaries, so both can change (an 8-bit variant is planned).+- `lib/adjustments/adjustments.wgsl` works in that space; its `Adjustments` struct mirrors the TypeScript type in the UI's units, and its constants were fitted against reference exports; treat them as data, not formulas to tidy.+- Retain `workerDecoder` for the upcoming RAW decoding implementation.## TestingPrefer a small number of browser-level tests for real application features. Each test should exercise a complete user-visible behavior and cover as much relevant code as practical. Avoid narrow unit tests for simple implementation details and do not add tests only to increase coverage.-Maintain a browser-side control API for agents and browser tests. Expose stable, semantic commands for real workflows such as loading an image, changing an adjustment, reading application state, and waiting for processing or rendering to settle. Commands must call the same application actions as the UI so they exercise production behavior without reproducing pointer or keyboard input. Use DOM interaction only when the UI interaction itself is under test.+Maintain a browser-side control API for agents and browser tests. Expose stable, semantic commands for real workflows such as loading an image, changing an adjustment, and reading application state. Use DOM interaction only when the UI interaction itself is under test. Tests wait for visible results without adding production completion tracking.Extend the control API whenever a feature adds a workflow that agents need to exercise. It may require an explicit test mode, but it must work in local browsers, CI, and remote browser sessions.diff --git a/README.md b/README.mdindex 0fa9bee..4445fce 100644--- a/README.md+++ b/README.md@@ -21,3 +21,23 @@ bun run build # typecheck + bundle## License[MIT](LICENSE)++## Browser controls++`window.openlight` is available after the app mounts, including production builds.+The UI, renderer, and browser API share the Zustand scene store in+`src/app/scene/index.ts`. The scene currently contains a source image and+adjustments. `app/editor/renderer/renderer.ts` executes the adjustment and display passes imperatively through+vgpu. `RendererProvider` owns the engine and frame loop; canvas and histogram+components attach their outputs through `useRenderer`. The API calls the store actions directly:++```js+await openlight.loadImage(new File([bytes], "photo.png", { type: "image/png" }));+openlight.setAdjustments({ exposure: 1, saturation: -25 });+const state = // Or read immediately: openlight.getState()+```++`setAdjustments` merges a partial update. Exposure accepts -5 to 5; other+adjustments accept -100 to 100. Loading another image resets adjustments.+State includes the file name and adjustments. `loadImage` starts decoding+immediately and resolves after decoding finishes; failures appear in the editor. The renderer runs every frame.diff --git a/bun.lock b/bun.lockindex 0649425..19ff72b 100644--- a/bun.lock+++ b/bun.lock@@ -14,6 +14,7 @@"tailwindcss": "^4.3.3","vgpu": "^0.3.1","vgpu-react": "^0.2.0",+ "zustand": "^5.0.15",},"devDependencies": {"@biomejs/biome": "2.5.11",@@ -285,6 +286,8 @@"zod": ["[email protected]", "", {}, "sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA=="],+ "zustand": ["[email protected]", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A=="],+"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],diff --git a/package.json b/package.jsonindex 9bb58d0..432617b 100644--- a/package.json+++ b/package.json@@ -17,7 +17,8 @@"react-dom": "^19.2.8","tailwindcss": "^4.3.3","vgpu": "^0.3.1",- "vgpu-react": "^0.2.0"+ "vgpu-react": "^0.2.0",+ "zustand": "^5.0.15"},"devDependencies": {"@biomejs/biome": "2.5.11",diff --git a/playwright.config.ts b/playwright.config.tsindex 3b70c47..0bcace3 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -1,13 +1,17 @@import { defineConfig } from "@playwright/test";+const args = ["--enable-unsafe-webgpu"];+if (process.platform !== "darwin") {+ args.push("--use-webgpu-adapter=swiftshader");+}+export default defineConfig({testDir: "./tests",testMatch: "**/*.e2e.ts",use: {+ channel: "chromium",baseURL: "http://127.0.0.1:4173",- launchOptions: {- args: ["--enable-unsafe-webgpu", "--use-webgpu-adapter=swiftshader"],- },+ launchOptions: { args },},webServer: {command: "bun run dev -- --host 127.0.0.1 --port 4173 --strictPort",diff --git a/src/app/editor.tsx b/src/app/editor.tsxdeleted file mode 100644index 378dbd9..0000000--- a/src/app/editor.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { useEffect, useState } from "react";-import { sampler } from "vgpu";-import { Canvas, useCanvas, useFrameLoop, useGpu, useShader } from "vgpu-react";-import ResizablePanel from "@/components/ui/resizable-panel";-import Spinner from "@/components/ui/spinner";-import Histogram from "@/features/histogram/histogram";-import usePanZoom, { type View } from "@/hooks/use-pan-zoom";-import decode, { type Target } from "@/lib/decode";-import shader from "./editor.wgsl";--type Decoding = { image?: Target; error?: string };--/** Decodes the file into the GPU, disposing it on cleanup. */-function useDecode(file: File) {- const gpu = useGpu();- const [state, setState] = useState<Decoding>({});-- useEffect(() => {- let cancelled = false;- const decoding = decode(gpu, file);- decoding.then(- (image) => !cancelled && setState({ image }),- (error: Error) => !cancelled && setState({ error: error.message }),- );- return () => {- cancelled = true;- decoding.then(- (image) => image.color.dispose(),- () => {},- );- setState({});- };- }, [gpu, file]);-- return state;-}--type ImageProps = { image: Target; view: View };--function Image({ image, view }: ImageProps) {- const gpu = useGpu();- const target = useCanvas();- const draw = useShader(shader, {- set: {- sourceSampler: sampler(gpu, { magFilter: "linear", minFilter: "linear" }),- },- });-- useFrameLoop((frame) => {- draw.set({- source: image.color,- params: {- size: target.size,- image: image.size,- pan: view.pan.map((p) => p * target.dpr),- zoom: view.zoom,- },- });- frame.pass(target, draw);- });-- return null;-}--type EditorProps = { file: File };--export default function Editor({ file }: EditorProps) {- const { image, error } = useDecode(file);- const { ref, view, handlers } = usePanZoom(image?.size);-- return (- <main className="flex h-full">- <div- className="grid min-w-0 flex-1 cursor-grab touch-none place-items-center active:cursor-grabbing"- ref={ref}- {...handlers}- >- {image ? (- <Canvas className="size-full min-h-0">- <Image image={image} view={view} />- </Canvas>- ) : error ? (- <p className="max-w-md text-center text-neutral-400">- Couldn't open {file.name}: {error}- </p>- ) : (- <Spinner />- )}- </div>- <ResizablePanel>{image && <Histogram image={image} />}</ResizablePanel>- </main>- );-}diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsxnew file mode 100644index 0000000..9164604--- /dev/null+++ b/src/app/editor/index.tsx@@ -0,0 +1,57 @@+import { Canvas } from "vgpu-react";+import type { Source } from "@/app/scene";+import ResizablePanel from "@/components/ui/resizable-panel";+import Spinner from "@/components/ui/spinner";+import usePanZoom from "@/hooks/use-pan-zoom";+import type { Target } from "@/lib/decode";+import CanvasRenderer from "./renderer";+import { RendererProvider } from "./renderer/provider";+import Sidebar from "./sidebar";++type WorkspaceProps = { image: Target };++function Workspace({ image }: WorkspaceProps) {+ const { ref, view, handlers } = usePanZoom(image.size);++ return (+ <RendererProvider source={image}>+ <div+ className="grid min-w-0 flex-1 cursor-grab touch-none place-items-center active:cursor-grabbing"+ ref={ref}+ {...handlers}+ >+ <Canvas className="size-full min-h-0">+ <CanvasRenderer view={view} />+ </Canvas>+ </div>+ <Sidebar />+ </RendererProvider>+ );+}++type EditorProps = { source: Source };++export default function Editor({ source }: EditorProps) {+ const { image, error } = source;++ return (+ <main className="flex h-full">+ {image ? (+ <Workspace image={image} />+ ) : (+ <>+ <div className="grid flex-1 place-items-center">+ {error ? (+ <p className="max-w-md text-center text-neutral-400">+ Couldn't open {source.file.name}: {error}+ </p>+ ) : (+ <Spinner />+ )}+ </div>+ <ResizablePanel />+ </>+ )}+ </main>+ );+}diff --git a/src/app/editor/renderer/index.tsx b/src/app/editor/renderer/index.tsxnew file mode 100644index 0000000..777f3b1--- /dev/null+++ b/src/app/editor/renderer/index.tsx@@ -0,0 +1,16 @@+import { useEffect } from "react";+import { useCanvas } from "vgpu-react";+import type { View } from "@/hooks/use-pan-zoom";+import { useRenderer } from "./provider";++type CanvasRendererProps = { view: View };++export default function CanvasRenderer({ view }: CanvasRendererProps) {+ const renderer = useRenderer();+ const canvas = useCanvas();+ useEffect(+ () => renderer.attachCanvas(canvas, view),+ [renderer, canvas, view],+ );+ return null;+}diff --git a/src/app/editor/renderer/provider.tsx b/src/app/editor/renderer/provider.tsxnew file mode 100644index 0000000..7a122a1--- /dev/null+++ b/src/app/editor/renderer/provider.tsx@@ -0,0 +1,38 @@+import {+ createContext,+ type ReactNode,+ useContext,+ useEffect,+ useMemo,+} from "react";+import type { Target } from "vgpu";+import { useFrameLoop, useGpu } from "vgpu-react";+import { useScene } from "@/app/scene";+import { createRenderer } from "./renderer";++const RendererContext = createContext<ReturnType<typeof createRenderer> | null>(+ null,+);++export function useRenderer() {+ const renderer = useContext(RendererContext);+ if (!renderer) {+ throw new Error("useRenderer requires RendererProvider.");+ }+ return renderer;+}++type RendererProviderProps = { source: Target; children: ReactNode };++export function RendererProvider({ source, children }: RendererProviderProps) {+ const gpu = useGpu();+ const renderer = useMemo(() => createRenderer(gpu, source), [gpu, source]);+ useEffect(() => () => renderer.dispose(), [renderer]);+ useFrameLoop((frame) => {+ const scene = useScene.getState();+ if (scene.source?.image === source) {+ renderer.render(frame, scene);+ }+ });+ return <RendererContext value={renderer}>{children}</RendererContext>;+}diff --git a/src/app/editor/renderer/renderer.ts b/src/app/editor/renderer/renderer.tsnew file mode 100644index 0000000..4aa6d0f--- /dev/null+++ b/src/app/editor/renderer/renderer.ts@@ -0,0 +1,99 @@+import {+ effect,+ type Frame,+ type Gpu,+ sampler,+ type Target,+ target,+} from "vgpu";+import type { Scene } from "@/app/scene";+import { histogram } from "@/features/histogram/bins";+import { histogramChart } from "@/features/histogram/histogram";+import type { View } from "@/hooks/use-pan-zoom";+import adjustmentsShader from "@/lib/adjustments/adjustments.wgsl";+import shader from "./renderer.wgsl";++/** Owns scene passes and intermediate textures for one decoded source. */+export function createRenderer(gpu: Gpu, source: Target) {+ const output = target(gpu, { size: source.size, format: source.format });+ const adjust = effect(gpu, adjustmentsShader, {+ set: { sourceSampler: sampler(gpu) },+ });+ const bins = histogram(gpu);+ const display = effect(gpu, shader, {+ set: {+ sourceSampler: sampler(gpu, { magFilter: "linear", minFilter: "linear" }),+ },+ });++ const canvases = new Set<{ canvas: Target & { dpr: number }; view: View }>();+ const charts = new Set<ReturnType<typeof histogramChart>>();+ let disposed = false;+ let sampling = false;+ return {+ attachCanvas(canvas: Target & { dpr: number }, view: View) {+ const output = { canvas, view };+ canvases.add(output);+ return () => {+ canvases.delete(output);+ };+ },+ attachHistogram(svg: SVGSVGElement) {+ const draw = histogramChart(svg);+ charts.add(draw);+ return () => {+ charts.delete(draw);+ };+ },+ render(frame: Frame, scene: Scene) {+ frame.pass(+ output,+ adjust.set({ source: source.color, adjustments: scene.adjustments }),+ );+ for (const { canvas, view } of canvases) {+ frame.pass(+ canvas,+ display.set({+ source: output.color,+ params: {+ size: canvas.size,+ sourceSize: output.size,+ pan: view.pan.map((p) => p * canvas.dpr),+ zoom: view.zoom,+ },+ }),+ );+ }+ if (sampling || charts.size === 0) {+ return;+ }+ sampling = true;+ frame.done+ .then(async () => {+ if (disposed) {+ return;+ }+ const counts = await bins.read(output);+ if (!disposed) {+ for (const draw of charts) {+ draw(counts);+ }+ }+ })+ .catch((error: unknown) => {+ if (!disposed) {+ console.error(error);+ }+ })+ .finally(() => {+ sampling = false;+ });+ },+ dispose() {+ disposed = true;+ canvases.clear();+ charts.clear();+ output.color.dispose();+ },+ };+}diff --git a/src/app/editor.wgsl b/src/app/editor/renderer/renderer.wgslsimilarity index 68%rename from src/app/editor.wgslrename to src/app/editor/renderer/renderer.wgslindex db35f9a..73b84bf 100644--- a/src/app/editor.wgsl+++ b/src/app/editor/renderer/renderer.wgsl@@ -1,8 +1,8 @@-import { display } from "../lib/color.wgsl";+import { display } from "../../../lib/color.wgsl";struct Params {size: vec2f,- image: vec2f,+ sourceSize: vec2f,pan: vec2f,zoom: f32,}@@ -14,8 +14,8 @@ const background = vec3f(0.09);@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {// Zoom 1 fits the image (contain, capped at 1:1), scaled about the center, then shifted by pan.- let scale = min(min(params.size.x / params.image.x, params.size.y / params.image.y), 1.0) * params.zoom;- let p = ((uv - 0.5) * params.size - params.pan) / (params.image * scale) + 0.5;+ let scale = min(min(params.size.x / params.sourceSize.x, params.size.y / params.sourceSize.y), 1.0) * params.zoom;+ let p = ((uv - 0.5) * params.size - params.pan) / (params.sourceSize * scale) + 0.5;let inside = all(p >= vec2f(0.0)) && all(p <= vec2f(1.0));let color = display(textureSampleLevel(source, sourceSampler, p, 0.0).rgb);return vec4f(select(background, color, inside), 1.0);diff --git a/src/app/editor/sidebar/adjustment-controls.tsx b/src/app/editor/sidebar/adjustment-controls.tsxnew file mode 100644index 0000000..df3033c--- /dev/null+++ b/src/app/editor/sidebar/adjustment-controls.tsx@@ -0,0 +1,76 @@+import { adjustmentLimits, defaultAdjustments, useScene } from "@/app/scene";+import { Slider } from "@/components/ui/slider";++const stops = {+ temp: ["#4a6fc3", "#c3b84a"],+ tint: ["#5ab34a", "#b34ab3"],+ saturation: [+ "#7b7d85",+ "#868686 50%",+ "#7fa066 68%",+ "#b8a75c 84%",+ "#c25a48",+ ],+};++export default function AdjustmentControls() {+ const value = useScene((scene) => scene.adjustments);+ const onChange = useScene((scene) => scene.setAdjustments);+ return (+ <section className="flex flex-col gap-3 p-4 shadow-ridge">+ <Slider+ defaultValue={defaultAdjustments.exposure}+ label="Exposure"+ max={adjustmentLimits.exposure}+ min={-adjustmentLimits.exposure}+ onChange={(exposure) => onChange({ exposure })}+ step={0.01}+ value={value.exposure}+ />+ <Slider+ defaultValue={defaultAdjustments.temp}+ label="Temp"+ max={adjustmentLimits.temp}+ min={-adjustmentLimits.temp}+ onChange={(temp) => onChange({ temp })}+ stops={stops.temp}+ value={value.temp}+ />+ <Slider+ defaultValue={defaultAdjustments.tint}+ label="Tint"+ max={adjustmentLimits.tint}+ min={-adjustmentLimits.tint}+ onChange={(tint) => onChange({ tint })}+ stops={stops.tint}+ value={value.tint}+ />+ <Slider+ defaultValue={defaultAdjustments.contrast}+ label="Contrast"+ max={adjustmentLimits.contrast}+ min={-adjustmentLimits.contrast}+ onChange={(contrast) => onChange({ contrast })}+ value={value.contrast}+ />+ <Slider+ defaultValue={defaultAdjustments.vibrance}+ label="Vibrance"+ max={adjustmentLimits.vibrance}+ min={-adjustmentLimits.vibrance}+ onChange={(vibrance) => onChange({ vibrance })}+ stops={stops.saturation}+ value={value.vibrance}+ />+ <Slider+ defaultValue={defaultAdjustments.saturation}+ label="Saturation"+ max={adjustmentLimits.saturation}+ min={-adjustmentLimits.saturation}+ onChange={(saturation) => onChange({ saturation })}+ stops={stops.saturation}+ value={value.saturation}+ />+ </section>+ );+}diff --git a/src/app/editor/sidebar/histogram.tsx b/src/app/editor/sidebar/histogram.tsxnew file mode 100644index 0000000..c6efeeb--- /dev/null+++ b/src/app/editor/sidebar/histogram.tsx@@ -0,0 +1,20 @@+import { useEffect, useRef } from "react";+import { useRenderer } from "@/app/editor/renderer/provider";++export default function Histogram() {+ const renderer = useRenderer();+ const ref = useRef<SVGSVGElement>(null);+ useEffect(() => {+ if (ref.current) {+ return renderer.attachHistogram(ref.current);+ }+ }, [renderer]);+ return (+ <svg+ ref={ref}+ className="h-24 w-full"+ preserveAspectRatio="none"+ viewBox="0 0 255 100"+ />+ );+}diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/sidebar/index.tsxnew file mode 100644index 0000000..4a3b2c5--- /dev/null+++ b/src/app/editor/sidebar/index.tsx@@ -0,0 +1,16 @@+import ResizablePanel from "@/components/ui/resizable-panel";+import AdjustmentControls from "./adjustment-controls";+import Histogram from "./histogram";++export default function Sidebar() {+ return (+ <ResizablePanel>+ <div className="flex flex-col divide-y divide-black">+ <section className="bg-neutral-900 p-0.5 pb-0">+ <Histogram />+ </section>+ <AdjustmentControls />+ </div>+ </ResizablePanel>+ );+}diff --git a/src/app/index.tsx b/src/app/index.tsxindex 58f4d1c..36f2079 100644--- a/src/app/index.tsx+++ b/src/app/index.tsx@@ -1,13 +1,13 @@-import { useState } from "react";import Editor from "./editor";import Landing from "./landing";+import { useScene } from "./scene";+import { useControls } from "./scene/controls";export default function App() {- const [file, setFile] = useState<File>();-- if (!file) {- return <Landing onOpen={setFile} />;+ const { loadImage } = useControls();+ const source = useScene((scene) => scene.source);+ if (!source) {+ return <Landing onOpen={loadImage} />;}-- return <Editor file={file} />;+ return <Editor source={source} />;}diff --git a/src/app/backdrop.tsx b/src/app/landing/backdrop.tsxsimilarity index 100%rename from src/app/backdrop.tsxrename to src/app/landing/backdrop.tsxdiff --git a/src/app/backdrop.wgsl b/src/app/landing/backdrop.wgslsimilarity index 100%rename from src/app/backdrop.wgslrename to src/app/landing/backdrop.wgsldiff --git a/src/app/landing.tsx b/src/app/landing/index.tsxsimilarity index 100%rename from src/app/landing.tsxrename to src/app/landing/index.tsxdiff --git a/src/app/scene/controls.ts b/src/app/scene/controls.tsnew file mode 100644index 0000000..8af0ff3--- /dev/null+++ b/src/app/scene/controls.ts@@ -0,0 +1,36 @@+import { useEffect, useMemo } from "react";+import { useGpu } from "vgpu-react";+import { useScene } from ".";++function getState() {+ const scene = useScene.getState();+ return {+ file: scene.source?.file.name,+ adjustments: { ...scene.adjustments },+ };+}++declare global {+ interface Window {+ openlight: ReturnType<typeof useControls>;+ }+}++export function useControls() {+ const gpu = useGpu();+ const controls = useMemo(+ () => ({+ loadImage: (file: File) => useScene.getState().loadImage(gpu, file),+ setAdjustments: useScene.getState().setAdjustments,+ getState,+ }),+ [gpu],+ );+ useEffect(() => {+ window.openlight = controls;+ return () => {+ Reflect.deleteProperty(window, "openlight");+ };+ }, [controls]);+ return controls;+}diff --git a/src/app/scene/index.ts b/src/app/scene/index.tsnew file mode 100644index 0000000..269bdf6--- /dev/null+++ b/src/app/scene/index.ts@@ -0,0 +1,69 @@+import type { Gpu, Target } from "vgpu";+import { create } from "zustand";+import decode from "@/lib/decode";++/** Non-destructive edits: exposure in stops, the rest -100..100. */+export type Adjustments = {+ exposure: number;+ temp: number;+ tint: number;+ contrast: number;+ vibrance: number;+ saturation: number;+};++export const defaultAdjustments: Adjustments = {+ exposure: 0,+ temp: 0,+ tint: 0,+ contrast: 0,+ vibrance: 0,+ saturation: 0,+};++export const adjustmentLimits: Adjustments = {+ exposure: 5,+ temp: 100,+ tint: 100,+ contrast: 100,+ vibrance: 100,+ saturation: 100,+};++export type Source = { file: File; image?: Target; error?: string };+export type Scene = { source?: Source; adjustments: Adjustments };+type SceneStore = Scene & {+ loadImage: (gpu: Gpu, file: File) => Promise<void>;+ setAdjustments: (change: Partial<Adjustments>) => void;+};++export const useScene = create<SceneStore>((set, get) => ({+ adjustments: { ...defaultAdjustments },+ loadImage: async (gpu, file) => {+ if (!(file instanceof File)) {+ throw new Error("loadImage requires a File.");+ }+ const source = { file };+ get().source?.image?.color.dispose();+ set({ source, adjustments: { ...defaultAdjustments } });+ try {+ const image = await decode(gpu, file);+ if (get().source !== source) {+ image.color.dispose();+ return;+ }+ set({ source: { file, image } });+ } catch (error) {+ if (get().source === source) {+ set({ source: { file, error: String(error) } });+ }+ }+ },+ setAdjustments: (change) => {+ const { source, adjustments } = get();+ if (!source) {+ throw new Error("Load an image before changing adjustments.");+ }+ set({ adjustments: { ...adjustments, ...change } });+ },+}));diff --git a/src/features/histogram/bins.ts b/src/features/histogram/bins.tsnew file mode 100644index 0000000..89bc193--- /dev/null+++ b/src/features/histogram/bins.ts@@ -0,0 +1,16 @@+import { compute, type Gpu, storage, type Target } from "vgpu";+import shader from "./bins.wgsl";++export const emptyBins = new Uint32Array(3 * 256);++export function histogram(gpu: Gpu) {+ const buffer = storage(gpu, emptyBins.byteLength);+ const counter = compute(gpu, shader, { set: { bins: buffer } });+ return {+ async read(image: Target) {+ buffer.write(emptyBins);+ counter.set({ source: image.color }).dispatch(32, 20);+ return new Uint32Array(await buffer.read());+ },+ };+}diff --git a/src/features/histogram/bins.wgsl b/src/features/histogram/bins.wgslindex 75b31fb..a7adcce 100644--- a/src/features/histogram/bins.wgsl+++ b/src/features/histogram/bins.wgsl@@ -1,16 +1,20 @@import { display } from "../../lib/color.wgsl";@group(0) @binding(0) var source: texture_2d<f32>;-// 256 bins per channel, then the peak of the interior bins for scaling the chart.-@group(0) @binding(1) var<storage, read_write> bins: array<atomic<u32>, 769>;+@group(0) @binding(1) var<storage, read_write> bins: array<atomic<u32>, 768>;const samples = vec2u(512, 320);+// Soft-binning weight spread across a bin pair; kept as a fixed-point scale so atomics stay integer.+const weight = 1024u;-fn count(channel: u32, bin: u32) {- let n = atomicAdd(&bins[channel * 256u + bin], 1u) + 1u;- if (bin > 0u && bin < 255u) {- atomicMax(&bins[768], n);- }+// Splits one texel's vote between its two nearest bins instead of flooring into a single one.+fn softBin(channel: u32, position: f32) {+ let clamped = clamp(position, 0.0, 255.0);+ let lo = u32(floor(clamped));+ let hi = min(lo + 1u, 255u);+ let hiWeight = u32(round((clamped - f32(lo)) * f32(weight)));+ atomicAdd(&bins[channel * 256u + lo], weight - hiWeight);+ atomicAdd(&bins[channel * 256u + hi], hiWeight);}@compute @workgroup_size(16, 16) fn main(@builtin(global_invocation_id) id: vec3u) {@@ -18,8 +22,8 @@ fn count(channel: u32, bin: u32) {return;}let texel = textureLoad(source, id.xy * textureDimensions(source) / samples, 0).rgb;- let bin = vec3u(round(display(texel) * 255.0));- count(0u, bin.r);- count(1u, bin.g);- count(2u, bin.b);+ let encoded = display(texel) * 255.0;+ softBin(0u, encoded.r);+ softBin(1u, encoded.g);+ softBin(2u, encoded.b);}diff --git a/src/features/histogram/histogram.ts b/src/features/histogram/histogram.tsnew file mode 100644index 0000000..7352065--- /dev/null+++ b/src/features/histogram/histogram.ts@@ -0,0 +1,50 @@+const channels = ["#f25445", "#6bd175", "#5c8ffa"];+const binCount = 256;+const kernel = [1, 4, 6, 4, 1];+const kernelWeight = 16;++/** Applies the binomial kernel over one channel's soft-binned counts. */+function smooth(bins: Uint32Array, channel: number) {+ return Array.from({ length: binCount }, (_, bin) => {+ let sum = 0;+ for (let k = 0; k < kernel.length; k++) {+ const i = bin + k - 2;+ if (i >= 0 && i < binCount) {+ sum += bins[channel * binCount + i] * kernel[k];+ }+ }+ return sum / kernelWeight;+ });+}++/** RGB polyline points on a 255×100 box: smoothed, then square-root scaled to the shared peak. */+function curves(bins: Uint32Array) {+ const counts = channels.map((_, channel) => smooth(bins, channel));+ const peak = Math.max(1, ...counts.flat());+ return counts.map((channel) =>+ channel+ .map((count, bin) => {+ const height = Math.sqrt(Math.min(1, count / peak));+ return `${bin},${(100 - 100 * height).toFixed(1)}`;+ })+ .join(" "),+ );+}++/** Binds a histogram output once; subsequent updates write directly to its SVG. */+export function histogramChart(svg: SVGSVGElement) {+ svg.innerHTML = `<title>Histogram</title>${channels+ .map(+ (color) =>+ `<g><polygon fill="${color}" fill-opacity="0.2"/><polyline fill="none" stroke="${color}" vector-effect="non-scaling-stroke"/></g>`,+ )+ .join("")}`;+ const polygons = svg.querySelectorAll("polygon");+ const lines = svg.querySelectorAll("polyline");+ return (bins: Uint32Array) => {+ curves(bins).forEach((points, channel) => {+ polygons[channel].setAttribute("points", `0,100 ${points} 255,100`);+ lines[channel].setAttribute("points", points);+ });+ };+}diff --git a/src/features/histogram/histogram.tsx b/src/features/histogram/histogram.tsxdeleted file mode 100644index fa5db1f..0000000--- a/src/features/histogram/histogram.tsx+++ /dev/null@@ -1,76 +0,0 @@-import { useEffect, useMemo, useState } from "react";-import { compute, storage, type Target } from "vgpu";-import { useGpu } from "vgpu-react";-import shader from "./bins.wgsl";--const channels = ["#f25445", "#6bd175", "#5c8ffa"];-const empty = new Uint32Array(769);--/** Bins a 512×320 sampling of the displayed image on the GPU whenever it changes. */-function useBins(image: Target) {- const gpu = useGpu();- const [bins, setBins] = useState(empty);- const buffer = useMemo(() => storage(gpu, empty.byteLength), [gpu]);- const counter = useMemo(- () => compute(gpu, shader, { set: { bins: buffer } }),- [gpu, buffer],- );-- useEffect(() => {- let stale = false;- buffer.write(empty);- counter.set({ source: image.color }).dispatch(32, 20);- buffer.read().then((data) => !stale && setBins(new Uint32Array(data)));- return () => {- stale = true;- };- }, [buffer, counter, image]);-- return bins;-}--/** One channel as "x,y" pairs on a 255×100 box: 5-tap smoothed, square-root scaled to the interior peak. */-function curve(bins: Uint32Array, channel: number) {- const peak = Math.max(bins[768], 1);- return Array.from({ length: 256 }, (_, bin) => {- let sum = 0;- for (let k = -2; k <= 2; k++) {- const i = Math.min(255, Math.max(0, bin + k));- sum += bins[channel * 256 + i] * (3 - Math.abs(k));- }- return `${bin},${(100 - 100 * Math.sqrt(sum / 9 / peak)).toFixed(1)}`;- }).join(" ");-}--type HistogramProps = { image: Target };--export default function Histogram({ image }: HistogramProps) {- const bins = useBins(image);- return (- <svg- className="h-24 w-full"- preserveAspectRatio="none"- viewBox="0 0 255 100"- >- <title>Histogram</title>- {channels.map((color, channel) => {- const points = curve(bins, channel);- return (- <g key={color}>- <polygon- fill={color}- fillOpacity={0.2}- points={`0,100 ${points} 255,100`}- />- <polyline- fill="none"- points={points}- stroke={color}- vectorEffect="non-scaling-stroke"- />- </g>- );- })}- </svg>- );-}diff --git a/src/lib/adjustments/adjustments.wgsl b/src/lib/adjustments/adjustments.wgslnew file mode 100644index 0000000..473b9d5--- /dev/null+++ b/src/lib/adjustments/adjustments.wgsl@@ -0,0 +1,68 @@+struct Adjustments {+ exposure: f32,+ temp: f32,+ tint: f32,+ contrast: f32,+ vibrance: f32,+ saturation: f32,+}++@group(0) @binding(0) var source: texture_2d<f32>;+@group(0) @binding(1) var sourceSampler: sampler;+@group(0) @binding(2) var<uniform> adjustments: Adjustments;++// All adjustment functions accept and return linear Rec.2020.+fn adjustExposure(color: vec3f, stops: f32) -> vec3f {+ let bounded = clamp(color, vec3f(0.0), vec3f(1.0));+ if stops < 0.0 {+ return exp2(stops * 1.09) * pow(bounded, vec3f(exp2(-stops * 0.14)));+ }+ let gain = mix(vec2f(1.11, -0.11) * min(stops, 1.0), vec2f(4.05, -0.63), max(stops - 1.0, 0.0) / 4.0);+ return 1.0 - pow(1.0 - pow(bounded, vec3f(exp2(gain.y))), vec3f(exp2(gain.x)));+}++fn interpolateGain(amount: f32, half: vec3f, full: vec3f) -> vec3f {+ let strength = 2.0 * abs(amount);+ return mix(half * min(strength, 1.0), full, max(strength - 1.0, 0.0));+}++fn adjustWhiteBalance(color: vec3f, temperature: f32, tint: f32) -> vec3f {+ let warmth = vec3f(2.50, 1.19, -1.89) * temperature+ + (vec3f(1.55, 1.89, 2.93) + vec3f(-1.47, -1.05, -0.69) * temperature) * abs(temperature);+ let tintGain = (vec3f(0.53, -0.59, 1.02) + vec3f(0.64, 0.94, 1.35) * tint) * tint;+ let gain = warmth + tintGain;+ let bounded = min(color, vec3f(1.0));+ return bounded / (bounded + (1.0 - bounded) * exp2(-gain)) + (color - bounded);+}++fn adjustContrast(color: vec3f, amount: f32) -> vec3f {+ let positive = interpolateGain(amount - 1.0, vec3f(0.32, 1.48, 0.0), vec3f(0.59, 2.77, 0.0)).xy;+ let gain = select(positive, vec2f(-0.43, -2.51) * (1.0 - amount), amount < 1.0);+ let bounded = min(color, vec3f(1.0));+ return color + bounded * (1.0 - bounded) * (gain.x + gain.y * (bounded - 0.5));+}++fn adjustSaturation(color: vec3f, amount: f32) -> vec3f {+ let luminance = dot(color, vec3f(0.2627, 0.6780, 0.0593));+ return vec3f(luminance) + (color - vec3f(luminance)) * amount;+}++fn adjustVibrance(color: vec3f, amount: f32) -> vec3f {+ let high = max(max(color.r, color.g), color.b);+ let low = max(0.0, min(min(color.r, color.g), color.b));+ let saturation = 1.0 - sqrt(low / max(high, 0.000001));+ let scale = 1.0 + amount * select(0.63, 0.23, amount < 0.0) * (1.0 - sign(amount) * saturation);+ return max(vec3f(high) + (color - vec3f(high)) * scale, vec3f(0.0));+}++@fragment+fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {+ let input = textureSample(source, sourceSampler, uv);+ var color = input.rgb;+ color = adjustExposure(color, adjustments.exposure);+ color = adjustWhiteBalance(color, adjustments.temp / 100.0, adjustments.tint / 100.0);+ color = adjustContrast(color, 1.0 + adjustments.contrast / 100.0);+ color = adjustVibrance(color, adjustments.vibrance / 100.0);+ color = adjustSaturation(color, 1.0 + adjustments.saturation / 100.0);+ return vec4f(color, input.a);+}diff --git a/tests/smoke.e2e.ts b/tests/smoke.e2e.tsindex e7429da..9e14740 100644--- a/tests/smoke.e2e.ts+++ b/tests/smoke.e2e.ts@@ -19,3 +19,90 @@ test("app opens without crashing", async ({ page }) => {);expect(errors, errors.join("\n")).toEqual([]);});++test("browser actions load, adjust, reset, and report failures", async ({+ page,+}) => {+ const errors: string[] = [];+ page.on("pageerror", (error) => errors.push(error.message));+ page.on("console", (message) => {+ if (message.type() === "error") {+ errors.push(message.text());+ }+ });+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ await page.evaluate(() => {+ const image = new File(+ [+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',+ ],+ "gray.svg",+ { type: "image/svg+xml" },+ );+ window.openlight.loadImage(image);+ return window.openlight.getState();+ });+ await expect(page.locator("polyline").first()).toHaveAttribute(+ "points",+ /,0\.0/,+ );+ const canvas = page.locator("canvas");+ const before = await canvas.screenshot();+ const histogram = await page+ .locator("polyline")+ .first()+ .getAttribute("points");+ const edited = await page.evaluate(() => {+ window.openlight.setAdjustments({ exposure: -1 });+ window.openlight.setAdjustments({ exposure: 1, saturation: -25 });+ return window.openlight.getState();+ });+ expect(edited.adjustments.exposure).toBe(1);+ await expect(+ page.getByRole("textbox", { name: "Exposure", exact: true }),+ ).toHaveValue("1.00");+ await expect(page.locator("polyline").first()).not.toHaveAttribute(+ "points",+ histogram ?? "",+ );+ expect(await canvas.screenshot()).not.toEqual(before);+ expect(+ await page.locator("polyline").first().getAttribute("points"),+ ).not.toBe(histogram);+ await page.evaluate(() => {+ window.openlight.setAdjustments({ exposure: 0, saturation: 0 });+ });+ await expect.poll(() => canvas.screenshot()).toEqual(before);+ await page.evaluate(async () => {+ const superseded = window.openlight.loadImage(+ new File(+ ['<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>'],+ "superseded.svg",+ { type: "image/svg+xml" },+ ),+ );+ const latest = window.openlight.loadImage(+ new File(["invalid"], "broken.png", { type: "image/png" }),+ );+ await Promise.all([superseded, latest]);+ });+ await expect(+ page.getByText("Couldn't open broken.png:", { exact: false }),+ ).toBeVisible();+ const recovered = await page.evaluate(async () => {+ await window.openlight.loadImage(+ new File(+ [+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',+ ],+ "replacement.svg",+ { type: "image/svg+xml" },+ ),+ );+ return window.openlight.getState();+ });+ expect(recovered.file).toBe("replacement.svg");+ await expect.poll(() => canvas.screenshot()).toEqual(before);+ expect(errors).toEqual([]);+});