Free open-source image editor for the browser
Add Auto white balance from one GPU reduction (#63)
Rodrigo Belfiore8b28770a6a87
diff --git a/API.md b/API.mdindex 9672793..65303a5 100644--- a/API.md+++ b/API.md@@ -64,6 +64,8 @@ Create an empty Heal effect with `addLayer("heal")`.For RAW sources, `setWhiteBalance({ temperature, tint })` sets absolute Kelvin and DNG tint, preserving unspecified values. Temperature accepts 2000–25000 K and tint accepts -150–150, extending either range to include the file's As Shot value. `setWhiteBalance()` restores that value (the decoder's daylight fallback if camera multipliers are unavailable). Non-RAW sources and invalid values throw. Incremental temperature/tint remain separate RGB adjustments.+`autoWhiteBalance()` neutralizes the photo's color cast as one edit and resolves once it is made. The GPU measures the cast of the source before any edit, as its edges' average color, so calling it again gives the same balance. A RAW photo's white balance moves from As Shot; any other photo's incremental temperature and tint are replaced. When another photo opens first, it resolves without an edit.+Edits update the scene and history synchronously. Rendering may finish later, particularly RAW development. Tests should wait for visible results; `exportImage()` renders and waits for its captured scene independently of the preview.`setFrame(frame)` replaces the complete [ImageFrame](src/core/image/frame.ts) as an undoable edit. Geometry uses finite two-element coordinate pairs, positive dimensions, and nonzero scale. The frame is validated and copied; later changes to the supplied object do not affect the document.diff --git a/README.md b/README.mdindex 0168755..524c564 100644--- a/README.md+++ b/README.md@@ -12,6 +12,7 @@ Image processing runs on your own GPU with WebGPU. Photos never leave your devic**Adjust**- Exposure, contrast, highlights, shadows, whites, blacks, temperature, tint, vibrance, and saturation.+- Auto white balance, which neutralizes the photo's color cast as a starting point for temperature and tint.- Tone curves with a live input histogram.- Clarity and sharpening.- Color Mixer with eight hue, saturation, and luminance ranges.diff --git a/src/app/controls.ts b/src/app/controls.tsindex b55b8af..4dfb742 100644--- a/src/app/controls.ts+++ b/src/app/controls.ts@@ -54,6 +54,7 @@ import { defaultCurve } from "@/features/tone-curves/curve";import { setToneCurve } from "@/features/tone-curves/edits";import { setVignette } from "@/features/vignette/edits";import { defaultVignette } from "@/features/vignette/model";+import { autoWhiteBalance } from "@/features/white-balance/auto";import { setWhiteBalance } from "@/features/white-balance/edits";import { type Command, runCommand } from "./commands";import {@@ -106,6 +107,7 @@ export function createControls(setAdjustments(workspace.getDocument(), change, id),setWhiteBalance: (change?: Partial<WhiteBalance>) =>setWhiteBalance(workspace.getDocument(), change),+ autoWhiteBalance: () => autoWhiteBalance(workspace.getDocument(), gpu),setToneCurve: (curve?: ToneCurve, id?: string) =>setToneCurve(workspace.getDocument(), curve, id),setColorMixer(color: MixerColor, change: MixerChange, id?: string) {diff --git a/src/app/editor/adjust/index.tsx b/src/app/editor/adjust/index.tsxindex cc94f27..68ef50c 100644--- a/src/app/editor/adjust/index.tsx+++ b/src/app/editor/adjust/index.tsx@@ -45,7 +45,7 @@ import {vignetteParameters,} from "@/features/vignette/controls";import {- useWhiteBalanceParameters,+ useWhiteBalance,WhiteBalanceControls,} from "@/features/white-balance/controls";import { useEditGesture } from "@/hooks/use-edit-gesture";@@ -120,16 +120,13 @@ function SelectedControls({ layer }: { layer: Layer }) {case "details":return <DetailsControls id={layer.id} details={layer.details} />;case "image":+ case "mask":return (<><AdjustmentControlsid={layer.id}adjustments={layer.adjustments}- temperature={- document.resources.get(layer.source).raw && (- <WhiteBalanceControls />- )- }+ whiteBalance={<WhiteBalanceControls layer={layer} />}/><div className="px-3.5 pb-3.5"><LayerCurve id={layer.id} toneCurve={layer.toneCurve} />@@ -152,15 +149,6 @@ function SelectedControls({ layer }: { layer: Layer }) {</section>);}- case "mask":- return (- <>- <AdjustmentControls id={layer.id} adjustments={layer.adjustments} />- <div className="px-3.5 pb-3.5">- <LayerCurve id={layer.id} toneCurve={layer.toneCurve} />- </div>- </>- );}}@@ -216,7 +204,7 @@ function AdjustmentDials({action: ReactNode;}) {const document = useDocument();- const whiteBalance = useWhiteBalanceParameters();+ const whiteBalance = useWhiteBalance(layer);const header = (<DockChipslabel="Adjustment group"@@ -252,16 +240,35 @@ function AdjustmentDials({}const adjustments = (controls: Parameters<typeof adjustmentParameters>[3]) =>adjustmentParameters(document, layer.id, layer.adjustments, controls);- // A RAW image's own white balance takes the place of the incremental temperature and tint.- const balance = layer.kind === "image" && whiteBalance;- let parameters = adjustments(tone);if (group === "color") {- parameters = balance- ? [...balance, ...adjustments(color.slice(2))]- : adjustments(color);+ return (+ <DockControls+ header={header}+ action={+ <>+ {whiteBalance.auto && (+ <Button+ variant="ghost"+ size="sm"+ aria-label="Auto white balance"+ onClick={whiteBalance.auto}+ >+ Auto+ </Button>+ )}+ {action}+ </>+ }+ parameters={[...whiteBalance.parameters, ...adjustments(color)]}+ />+ );}return (- <DockControls header={header} action={action} parameters={parameters} />+ <DockControls+ header={header}+ action={action}+ parameters={adjustments(tone)}+ />);}diff --git a/src/core/document/index.ts b/src/core/document/index.tsindex 2b76474..3661380 100644--- a/src/core/document/index.ts+++ b/src/core/document/index.ts@@ -135,6 +135,10 @@ export function createDocument(initial: Scene, resources = createResources()) {validateFrame(next.frame);update(next);},+ /** Whether the document was disposed, so work that outlived it can drop its result. */+ get closed() {+ return closed;+ },dispose() {if (closed) {return;diff --git a/src/features/adjustments/controls.tsx b/src/features/adjustments/controls.tsxindex a6159c6..07ba143 100644--- a/src/features/adjustments/controls.tsx+++ b/src/features/adjustments/controls.tsx@@ -6,17 +6,13 @@ import type { Adjustments, EditorDocument } from "@/core/document";import { setAdjustments } from "./edits";import { adjustmentLimits, defaultAdjustments } from "./model";-const stops: Partial<Record<keyof Adjustments, string[]>> = {- incrementalTemperature: ["#4a6fc3", "#c3b84a"],- incrementalTint: ["#5ab34a", "#b34ab3"],- saturation: [- "#7b7d85",- "#868686 50%",- "#7fa066 68%",- "#b8a75c 84%",- "#c25a48",- ],-};+const saturationStops = [+ "#7b7d85",+ "#868686 50%",+ "#7fa066 68%",+ "#b8a75c 84%",+ "#c25a48",+];export const tone = [["exposure", "Exposure"],@@ -26,9 +22,8 @@ export const tone = [["whites", "Whites"],["blacks", "Blacks"],] as const;+/** White balance, which leads the color group, has its own controls. */export const color = [- ["incrementalTemperature", "Temp"],- ["incrementalTint", "Tint"],["vibrance", "Vibrance"],["saturation", "Saturation"],] as const;@@ -45,7 +40,10 @@ export function adjustmentParameters(label,value: adjustments[name],step: name === "exposure" ? 0.01 : 1,- stops: name === "vibrance" ? stops.saturation : stops[name],+ stops:+ name === "vibrance" || name === "saturation"+ ? saturationStops+ : undefined,min: -adjustmentLimits[name],max: adjustmentLimits[name],defaultValue: defaultAdjustments[name],@@ -68,25 +66,21 @@ function AdjustmentSliders({);}-/** The temperature slot replaces the incremental temperature and tint sliders. */+/** Tone, then the white balance's controls, then color. */export function AdjustmentControls({id,adjustments,- temperature,+ whiteBalance,}: {id: string;adjustments: Readonly<Adjustments>;- temperature?: ReactNode;+ whiteBalance: ReactNode;}) {return (<section className="flex flex-col gap-1.5 p-3.5"><AdjustmentSliders id={id} adjustments={adjustments} controls={tone} />- {temperature}- <AdjustmentSliders- id={id}- adjustments={adjustments}- controls={temperature ? color.slice(2) : color}- />+ {whiteBalance}+ <AdjustmentSliders id={id} adjustments={adjustments} controls={color} /></section>);}diff --git a/src/features/white-balance/auto.ts b/src/features/white-balance/auto.tsnew file mode 100644index 0000000..661c5cc--- /dev/null+++ b/src/features/white-balance/auto.ts@@ -0,0 +1,75 @@+import type { Gpu } from "vgpu";+import type { EditorDocument } from "@/core/document";+import { clamp } from "@/lib/math";+import { castOf, measureLight, type Rgb } from "./cast";+import {+ setIncrementalBalance,+ setWhiteBalance,+ whiteBalanceLimits,+} from "./edits";++/**+ * Light between tungsten and daylight follows the Planckian locus, where a blackbody gains 0.22 stops+ * of green per stop of warmth in the working space. Temperature controls move along it.+ */+const locusGreen = 0.22;+/**+ * A photo is seldom off the locus, while colored edges often mislead the estimate's green, so tint+ * takes a quarter of the green the locus doesn't explain.+ */+const tintShare = 0.25;++// A RAW photo's warmth in stops per mired and green per unit of tint, fitted on six cameras.+const rawWarmthPerMired = -0.01;+const rawGreenPerTint = -0.006;++// Each channel's gain in log odds per unit of the incremental controls: the first-order terms of+// adjustWhiteBalance in prepare.wgsl. Temperature bends harder toward blue than toward yellow.+const warming: Rgb = [0.0405, 0.0308, 0.0104];+const cooling: Rgb = [0.0095, -0.007, -0.0482];+const tinting: Rgb = [0.0053, -0.0059, 0.0102];++/** The cast that log-odds gains make where each channel sits at `level`, which they move by 1 − level. */+function moved([r, g, b]: Rgb, level: Rgb) {+ return castOf([r * (1 - level[0]), g * (1 - level[1]), b * (1 - level[2])]);+}++/**+ * Neutralizes the photo's cast, measured before any edit, as one edit: temperature takes all of the+ * warmth, tint a share of the green off the locus. A RAW photo's own balance moves from As Shot; any+ * other photo's incremental temperature and tint replace their values.+ */+export async function autoWhiteBalance(document: EditorDocument, gpu: Gpu) {+ const image = document.scene.getState().layers[0];+ const source = document.resources.get(image.source);+ const light = await measureLight(gpu, source.image);+ if (!light || document.closed) {+ return;+ }+ const cast = castOf(light.stops);+ const green = tintShare * (cast.green - locusGreen * cast.warmth);+ if (source.raw) {+ const { asShot } = source.raw;+ const limits = whiteBalanceLimits(asShot);+ const mireds = 1e6 / asShot.temperature - cast.warmth / rawWarmthPerMired;+ setWhiteBalance(document, {+ temperature: clamp(+ 1e6 / Math.max(mireds, 1),+ limits.temperature.min,+ limits.temperature.max,+ ),+ tint: clamp(+ asShot.tint - green / rawGreenPerTint,+ limits.tint.min,+ limits.tint.max,+ ),+ });+ return;+ }+ const temperature = moved(cast.warmth > 0 ? cooling : warming, light.level);+ const tint = moved(tinting, light.level);+ setIncrementalBalance(document, image.id, {+ incrementalTemperature: clamp(-cast.warmth / temperature.warmth, -100, 100),+ incrementalTint: clamp(-green / tint.green, -100, 100),+ });+}diff --git a/src/features/white-balance/cast.ts b/src/features/white-balance/cast.tsnew file mode 100644index 0000000..cf99f51--- /dev/null+++ b/src/features/white-balance/cast.ts@@ -0,0 +1,35 @@+import { compute, type Gpu, type Target } from "vgpu";+import { weakMemo } from "@/lib/weak-memo";+import shader from "./cast.wgsl";++export type Rgb = readonly [number, number, number];+/** A color cast: `warmth`, red over blue, and `green`, green over red and blue. */+export type Cast = { warmth: number; green: number };++export function castOf([red, green, blue]: Rgb): Cast {+ return { warmth: red - blue, green: green - (red + blue) / 2 };+}++const measure = weakMemo((gpu: Gpu) =>+ compute(gpu, shader, { entry: "measure" }),+);++/**+ * Reduces `image` on the GPU to the light's color in stops and each channel's level where the edges+ * are; nothing for an image without usable pixels.+ */+export async function measureLight(gpu: Gpu, image: Target) {+ const light = gpu.device.createBuffer({+ size: 32,+ usage: ["storage", "copy_src"],+ });+ try {+ measure(gpu).set({ source: image.color, light }).dispatch(1);+ const [r, g, b, , lr, lg, lb] = new Float32Array(await light.read(32));+ const stops: Rgb = [r, g, b];+ const level: Rgb = [lr, lg, lb];+ return stops.every(Number.isFinite) ? { stops, level } : undefined;+ } finally {+ light.dispose();+ }+}diff --git a/src/features/white-balance/cast.wgsl b/src/features/white-balance/cast.wgslnew file mode 100644index 0000000..eb59e61--- /dev/null+++ b/src/features/white-balance/cast.wgsl@@ -0,0 +1,78 @@+import { luminance } from "../../core/image/color.wgsl";++// Gray edge (van de Weijer, Gevers, and Gijsenij, 2007): differences between neighboring surfaces+// average to the light's color, so a large colored area counts only at its edges. One workgroup walks+// a grid of samples and reduces it to the light's color in stops, beside each channel's level where+// the edges are. Without usable edges, the mean color decides both. Brighter pixels weigh more, since+// shadows take their color from whatever light fills them.+const samples = vec2u(512u, 320u);+const threads = 256u;+// A high norm leans on the strongest edges.+const norm = 6.0;++struct Light {+ stops: vec3f,+ level: vec3f,+}++@group(0) @binding(0) var source: texture_2d<f32>;+@group(0) @binding(1) var<storage, read_write> light: Light;++var<workgroup> edges: array<vec3f, threads>;+var<workgroup> levels: array<vec3f, threads>;+// Usable colors, summed, and in w their count.+var<workgroup> colors: array<vec4f, threads>;++fn sample(point: vec2u) -> vec4f {+ return textureLoad(source, point * textureDimensions(source) / samples, 0);+}++// Opaque, bright enough that noise doesn't decide its color, and short of highlights, which clip or+// roll off to white whatever the light.+fn usable(color: vec4f) -> bool {+ return color.a > 0.5 && max(color.r, max(color.g, color.b)) < 0.85 && luminance(color.rgb) > 0.005;+}++@compute @workgroup_size(threads) fn measure(@builtin(local_invocation_index) thread: u32) {+ var edge = vec3f(0.0);+ var level = vec3f(0.0);+ var color = vec4f(0.0);+ for (var i = thread; i < samples.x * samples.y; i += threads) {+ let point = vec2u(i % samples.x, i / samples.x);+ let here = sample(point);+ if (!usable(here)) {+ continue;+ }+ let weight = luminance(here.rgb);+ color += vec4f(here.rgb, 1.0) * weight;+ let right = sample(min(point + vec2u(1u, 0u), samples - 1u));+ let below = sample(min(point + vec2u(0u, 1u), samples - 1u));+ if (usable(right) && usable(below)) {+ let across = right.rgb - here.rgb;+ let down = below.rgb - here.rgb;+ let strength = pow(sqrt(across * across + down * down), vec3f(norm)) * weight;+ edge += strength;+ level += strength * here.rgb;+ }+ }+ edges[thread] = edge;+ levels[thread] = level;+ colors[thread] = color;+ workgroupBarrier();+ for (var stride = threads / 2u; stride > 0u; stride /= 2u) {+ if (thread < stride) {+ edges[thread] += edges[thread + stride];+ levels[thread] += levels[thread + stride];+ colors[thread] += colors[thread + stride];+ }+ workgroupBarrier();+ }+ if (thread == 0u) {+ let mean = colors[0].rgb / colors[0].w;+ let edged = all(edges[0] > vec3f(0.0));+ light = Light(+ select(log2(mean), log2(edges[0]) / norm, edged),+ select(mean, levels[0] / edges[0], edged),+ );+ }+}diff --git a/src/features/white-balance/controls.tsx b/src/features/white-balance/controls.tsxindex 96a8fad..11e2930 100644--- a/src/features/white-balance/controls.tsx+++ b/src/features/white-balance/controls.tsx@@ -1,63 +1,129 @@import { Slider } from "@roprgm/ui/slider";+import { useGpu } from "vgpu-react";import type { Parameter } from "@/components/editor/parameter";-import { useDocument, useScene } from "@/components/editor/session";-import { setWhiteBalance, whiteBalanceLimits } from "./edits";+import { useDocument } from "@/components/editor/session";+import type { EditorDocument, ImageLayer, MaskLayer } from "@/core/document";+import { autoWhiteBalance } from "./auto";+import {+ setIncrementalBalance,+ setWhiteBalance,+ whiteBalanceLimits,+} from "./edits";-/** Temperature and tint from the camera's as-shot balance; null for an image that isn't RAW. */-export function useWhiteBalanceParameters(): Parameter[] | null {- const document = useDocument();- const source = useScene((scene) => scene.layers[0].source);- const selected = useScene((scene) => scene.layers[0].whiteBalance);- const asShot = document.resources.get(source).raw?.asShot;- if (!asShot) {- return null;- }- const balance = selected ?? asShot;- const limits = whiteBalanceLimits(asShot);+const temperatureStops = ["#4a6fc3", "#c3b84a"];+const tintStops = ["#5ab34a", "#b34ab3"];++/** The incremental temperature and tint an image's or mask's adjustments apply. */+function incremental(+ document: EditorDocument,+ { id, adjustments }: ImageLayer | MaskLayer,+): [Parameter, Parameter] {+ const range = { min: -100, max: 100, step: 1, defaultValue: 0 };return [{- id: "temperature",- label: "Temperature (K)",- value: balance.temperature,- ...limits.temperature,- defaultValue: asShot.temperature,- onChange: (temperature) => setWhiteBalance(document, { temperature }),+ ...range,+ id: "incrementalTemperature",+ label: "Temp",+ value: adjustments.incrementalTemperature,+ stops: temperatureStops,+ onChange: (incrementalTemperature) =>+ setIncrementalBalance(document, id, { incrementalTemperature }),},{- id: "tint",+ ...range,+ id: "incrementalTint",label: "Tint",- value: balance.tint,- step: 0.1,- ...limits.tint,- defaultValue: asShot.tint,- onChange: (tint) => setWhiteBalance(document, { tint }),+ value: adjustments.incrementalTint,+ stops: tintStops,+ onChange: (incrementalTint) =>+ setIncrementalBalance(document, id, { incrementalTint }),},];}-export function WhiteBalanceControls() {+/**+ * A layer's white balance as a temperature and a tint, with the actions it offers. A RAW photo sets its+ * own in kelvin, from its camera's As Shot; other photos and every mask shift theirs incrementally.+ * Auto neutralizes the photo, so only the image layer offers it.+ */+export function useWhiteBalance(layer: ImageLayer | MaskLayer): {+ parameters: [Parameter, Parameter];+ auto?: () => void;+ asShot?: () => void;+} {const document = useDocument();- const parameters = useWhiteBalanceParameters();- if (!parameters) {- return null;+ const gpu = useGpu();+ if (layer.kind === "mask") {+ return { parameters: incremental(document, layer) };}- const [temperature, tint] = parameters;+ const auto = () => void autoWhiteBalance(document, gpu);+ const raw = document.resources.get(layer.source).raw;+ if (!raw) {+ return { parameters: incremental(document, layer), auto };+ }+ const balance = layer.whiteBalance ?? raw.asShot;+ const limits = whiteBalanceLimits(raw.asShot);+ return {+ parameters: [+ {+ id: "temperature",+ label: "Temperature (K)",+ value: balance.temperature,+ stops: temperatureStops,+ ...limits.temperature,+ defaultValue: raw.asShot.temperature,+ onChange: (temperature) => setWhiteBalance(document, { temperature }),+ },+ {+ id: "tint",+ label: "Tint",+ value: balance.tint,+ step: 0.1,+ stops: tintStops,+ ...limits.tint,+ defaultValue: raw.asShot.tint,+ onChange: (tint) => setWhiteBalance(document, { tint }),+ },+ ],+ auto,+ asShot: () => setWhiteBalance(document),+ };+}++function Action({ label, onClick }: { label: string; onClick: () => void }) {+ return (+ <button+ type="button"+ className="pointer-events-auto cursor-pointer text-muted hover:text-foreground"+ onClick={onClick}+ >+ {label}+ </button>+ );+}++/** The temperature and tint sliders, with As Shot and Auto beside the temperature's label. */+export function WhiteBalanceControls({+ layer,+}: {+ layer: ImageLayer | MaskLayer;+}) {+ const {+ parameters: [temperature, tint],+ asShot,+ auto,+ } = useWhiteBalance(layer);return (<><div className="relative"><Slider {...temperature} />- {/* The slider's label row again, its text hidden, so As Shot follows the label without a row of its own. */}+ {/* The slider's label row again, its text hidden, so the actions follow the label without a row of their own. */}<div className="pointer-events-none absolute inset-x-0 top-0 z-20 flex items-center gap-2 py-0.5"><span aria-hidden className="invisible">{temperature.label}</span>- <button- type="button"- className="pointer-events-auto cursor-pointer text-muted hover:text-foreground"- onClick={() => setWhiteBalance(document)}- >- As Shot- </button>+ {asShot && <Action label="As Shot" onClick={asShot} />}+ {auto && <Action label="Auto" onClick={auto} />}</div></div><Slider {...tint} />diff --git a/src/features/white-balance/edits.ts b/src/features/white-balance/edits.tsindex 90e1e50..05795fe 100644--- a/src/features/white-balance/edits.ts+++ b/src/features/white-balance/edits.ts@@ -1,7 +1,11 @@import { z } from "zod/mini";-import { type EditorDocument, editLayer } from "@/core/document";+import {+ type Adjustments,+ type EditorDocument,+ editLayer,+} from "@/core/document";import type { WhiteBalance } from "@/core/image";-import { parse, range } from "@/lib/parse";+import { change, parse, range } from "@/lib/parse";export function whiteBalanceLimits(asShot: WhiteBalance) {return {@@ -49,3 +53,30 @@ export function setWhiteBalance(return { ...layer, whiteBalance };});}++type Incremental = Pick<+ Adjustments,+ "incrementalTemperature" | "incrementalTint"+>;++/** The adjustments' temperature and tint, -100 to 100, which shift an image or mask's RGB. */+const incrementalChange = change(+ z.object({+ incrementalTemperature: range(-100, 100),+ incrementalTint: range(-100, 100),+ }) satisfies z.ZodMiniType<Incremental>,+);++export function setIncrementalBalance(+ document: EditorDocument,+ id: string,+ values: Partial<Incremental>,+) {+ const balance = parse(incrementalChange, values, "Invalid white balance");+ editLayer(document, id, (layer) => {+ if (layer.kind !== "image" && layer.kind !== "mask") {+ throw Error("Select an image or a mask.");+ }+ return { ...layer, adjustments: { ...layer.adjustments, ...balance } };+ });+}diff --git a/tests/auto-white-balance.e2e.ts b/tests/auto-white-balance.e2e.tsnew file mode 100644index 0000000..5cd9bcc--- /dev/null+++ b/tests/auto-white-balance.e2e.ts@@ -0,0 +1,122 @@+import { readFile } from "node:fs/promises";+import type { Page } from "@playwright/test";+import { expect, test } from "./fixtures";+import { readImage } from "./images";++/** Gray stripes under warm light, as linear sRGB encoded in an SVG; the middle stripe is middle gray. */+function castWedge() {+ const light = [1.3, 1, 0.6];+ const middle =+ 0.18 / (0.2126 * light[0] + 0.7152 * light[1] + 0.0722 * light[2]);+ // The sRGB curve above its linear toe, which no stripe reaches.+ const encode = (value: number) =>+ Math.round(255 * (1.055 * value ** (1 / 2.4) - 0.055))+ .toString(16)+ .padStart(2, "0");+ const stripes = [+ [0, 48, 0.3],+ [48, 96, 0.55],+ [96, 160, 1],+ [160, 208, 1.7],+ [208, 256, 2.6],+ ].map(([x, end, level]) => {+ const fill = light.map((channel) => encode(middle * level * channel));+ return `<rect x="${x}" width="${end - x}" height="128" fill="#${fill.join("")}"/>`;+ });+ return `<svg xmlns="http://www.w3.org/2000/svg" width="256" height="128">${stripes.join("")}</svg>`;+}++function spread([r, g, b]: number[]) {+ return Math.max(r, g, b) - Math.min(r, g, b);+}++const undoCount = (page: Page) =>+ page.evaluate(() => window.openlight.getState().history.undoCount);++test("Auto takes most of a warm photo's cast away as one undoable edit", async ({+ page,+}) => {+ await page.goto("/");+ await page.locator('input[type="file"]').setInputFiles({+ name: "cast.svg",+ mimeType: "image/svg+xml",+ buffer: Buffer.from(castWedge()),+ });+ const auto = page.getByRole("button", { name: "Auto", exact: true });+ await expect(auto).toBeVisible();+ const cast = await readImage(page);+ expect(spread(cast.center)).toBeGreaterThan(30);++ await auto.click();+ await expect.poll(() => undoCount(page)).toBe(1);+ // A starting point: most of the cast goes.+ expect(spread((await readImage(page)).center)).toBeLessThan(+ spread(cast.center) / 4,+ );+ const { incrementalTemperature } = await page.evaluate(+ () => window.openlight.getState().adjustments,+ );+ expect(incrementalTemperature).toBeLessThan(0);++ await page.getByRole("button", { name: "Undo", exact: true }).click();+ expect(await readImage(page)).toEqual(cast);+});++test("Auto moves a RAW photo's white balance from As Shot toward neutral", async ({+ page,+}) => {+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ const bytes = [...(await readFile("tests/fixtures/raw/bayer.dng"))];+ await page.evaluate(+ (bytes) =>+ window.openlight.loadImage(+ new File([new Uint8Array(bytes)], "bayer.dng"),+ ),+ bytes,+ );+ const asShot = await page.evaluate(+ () => window.openlight.getState().whiteBalance,+ );+ const cast = await readImage(page);+ expect(spread(cast.center)).toBeGreaterThan(80);++ await page.getByRole("button", { name: "Auto", exact: true }).click();+ await expect.poll(() => undoCount(page)).toBe(1);+ expect(spread((await readImage(page)).center)).toBeLessThan(+ spread(cast.center) / 4,+ );+ const balance = await page.evaluate(+ () => window.openlight.getState().whiteBalance,+ );+ expect(balance?.temperature).toBeLessThan(asShot?.temperature ?? 0);++ await page.getByRole("button", { name: "Undo", exact: true }).click();+ expect(await readImage(page)).toEqual(cast);+ // The cast is measured on the As Shot development, so Auto gives the same balance again.+ await page.evaluate(() => window.openlight.autoWhiteBalance());+ expect(+ await page.evaluate(() => window.openlight.getState().whiteBalance),+ ).toEqual(balance);+});++test("Auto drops its result when another photo opens while it measures", async ({+ page,+}) => {+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ const photo = [...Buffer.from(castWedge())];+ await page.evaluate(async (bytes) => {+ const open = () =>+ window.openlight.loadImage(+ new File([new Uint8Array(bytes)], "cast.svg", {+ type: "image/svg+xml",+ }),+ );+ await open();+ const auto = window.openlight.autoWhiteBalance();+ await open();+ await auto;+ }, photo);+ expect(await undoCount(page)).toBe(0);+});