Free open-source image editor for the browser
Add clarity and sharpening (#6)
Rodrigo Belfioreb5a4a4c2041e
diff --git a/src/app/editor/sidebar/adjustment-controls.tsx b/src/app/editor/sidebar/adjustment-controls.tsxindex 84d946d..aadb64b 100644--- a/src/app/editor/sidebar/adjustment-controls.tsx+++ b/src/app/editor/sidebar/adjustment-controls.tsx@@ -1,10 +1,12 @@-import type { ComponentProps } from "react";+import type { ComponentProps, ReactNode } from "react";import { useDocument, useScene } from "@/components/editor/session";+import { Collapsible } from "@/components/ui/collapsible";import { Slider } from "@/components/ui/slider";import { setAdjustments } from "@/lib/editor/document/edits";import {type Adjustments,adjustmentLimits,+ adjustmentMinimums,defaultAdjustments,} from "@/lib/editor/scene";@@ -36,41 +38,57 @@ function AdjustmentSlider({ name, ...props }: AdjustmentSliderProps) {value={value}onChange={(value) => setAdjustments(document, { [name]: value })}defaultValue={defaultAdjustments[name]}- min={-adjustmentLimits[name]}+ min={adjustmentMinimums[name] ?? -adjustmentLimits[name]}max={adjustmentLimits[name]}/>);}-export default function AdjustmentControls() {+export default function AdjustmentControls({ curves }: { curves: ReactNode }) {return (- <section className="flex flex-col gap-2 p-4 shadow-ridge">- <AdjustmentSlider name="exposure" label="Exposure" step={0.01} />- <AdjustmentSlider- name="incrementalTemperature"- label="Temp"- stops={stops.incrementalTemperature}- />- <AdjustmentSlider- name="incrementalTint"- label="Tint"- stops={stops.incrementalTint}- />- <AdjustmentSlider name="contrast" label="Contrast" />- <AdjustmentSlider name="highlights" label="Highlights" />- <AdjustmentSlider name="shadows" label="Shadows" />- <AdjustmentSlider name="whites" label="Whites" />- <AdjustmentSlider name="blacks" label="Blacks" />- <AdjustmentSlider- name="vibrance"- label="Vibrance"- stops={stops.saturation}- />- <AdjustmentSlider- name="saturation"- label="Saturation"- stops={stops.saturation}- />- </section>+ <>+ <Collapsible title="Light">+ <div className="flex flex-col gap-2">+ <AdjustmentSlider name="exposure" label="Exposure" step={0.01} />+ <AdjustmentSlider name="contrast" label="Contrast" />+ <AdjustmentSlider name="highlights" label="Highlights" />+ <AdjustmentSlider name="shadows" label="Shadows" />+ <AdjustmentSlider name="whites" label="Whites" />+ <AdjustmentSlider name="blacks" label="Blacks" />+ </div>+ <div className="pt-3">{curves}</div>+ </Collapsible>+ <Collapsible title="Color">+ <div className="flex flex-col gap-2">+ <AdjustmentSlider+ name="incrementalTemperature"+ label="Temp"+ stops={stops.incrementalTemperature}+ />+ <AdjustmentSlider+ name="incrementalTint"+ label="Tint"+ stops={stops.incrementalTint}+ />+ <AdjustmentSlider+ name="vibrance"+ label="Vibrance"+ stops={stops.saturation}+ />+ <AdjustmentSlider+ name="saturation"+ label="Saturation"+ stops={stops.saturation}+ />+ </div>+ </Collapsible>+ <Collapsible title="Details">+ <div className="flex flex-col gap-2">+ <AdjustmentSlider name="clarity" label="Clarity" />+ <AdjustmentSlider name="sharpening" label="Sharpening" />+ <AdjustmentSlider name="sharpenRadius" label="Radius" step={0.1} />+ </div>+ </Collapsible>+ </>);}diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/sidebar/index.tsxindex eb22ba3..2eb48df 100644--- a/src/app/editor/sidebar/index.tsx+++ b/src/app/editor/sidebar/index.tsx@@ -73,8 +73,9 @@ export function Sidebar({ children }: { children?: ReactNode }) {aria-label="output histogram"/></section>- <AdjustmentControls />- <ToneCurvesPanel histogram={histogram} />+ <AdjustmentControls+ curves={<ToneCurvesPanel histogram={histogram} />}+ /></div><div className="flex shrink-0 items-center gap-2 bg-panel p-3"><HistoryControls />diff --git a/src/app/loaders/camera-raw-xmp.ts b/src/app/loaders/camera-raw-xmp.tsindex cf94a38..dfd03ae 100644--- a/src/app/loaders/camera-raw-xmp.ts+++ b/src/app/loaders/camera-raw-xmp.ts@@ -12,6 +12,7 @@ function toAdjustments(xmp: CameraRawXmp): Partial<Adjustments> {const adjustments: Partial<Adjustments> = {exposure: xmp.exposure2012,contrast: xmp.contrast2012,+ clarity: xmp.clarity2012,highlights: xmp.highlights2012,shadows: xmp.shadows2012,whites: xmp.whites2012,diff --git a/src/components/ui/collapsible.tsx b/src/components/ui/collapsible.tsxnew file mode 100644index 0000000..c4dbe8a--- /dev/null+++ b/src/components/ui/collapsible.tsx@@ -0,0 +1,51 @@+import { type ReactNode, useId, useState } from "react";++/** Accessible disclosure with animated height and keyboard-safe collapsed content. */+export function Collapsible({+ title,+ children,+ defaultOpen = true,+}: {+ title: string;+ children: ReactNode;+ defaultOpen?: boolean;+}) {+ const [open, setOpen] = useState(defaultOpen);+ const id = useId();+ return (+ <section className="shadow-ridge">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={id}+ onClick={() => setOpen(!open)}+ className="flex w-full cursor-pointer items-center gap-1 px-3 py-2.5 text-left text-sm text-neutral-300 transition-colors hover:bg-white/3 hover:text-neutral-100 outline-none focus-visible:bg-white/8 focus-visible:text-white"+ >+ <svg+ aria-hidden="true"+ viewBox="0 0 18 18"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ data-open={open}+ className="size-4 shrink-0 text-neutral-500 transition-transform duration-200 ease-out data-[open=true]:rotate-90 motion-reduce:transition-none"+ >+ <path d="m7 5 4 4-4 4" />+ </svg>+ {title}+ </button>+ <div+ id={id}+ inert={!open}+ data-open={open}+ className="invisible grid grid-rows-[0fr] transition-[grid-template-rows,visibility] duration-200 ease-out data-[open=true]:visible data-[open=true]:grid-rows-[1fr] motion-reduce:transition-none"+ >+ <div className="min-h-0 overflow-hidden">+ <div className="px-4 pt-1 pb-4">{children}</div>+ </div>+ </div>+ </section>+ );+}diff --git a/src/features/camera-raw-xmp/xmp.ts b/src/features/camera-raw-xmp/xmp.tsindex 815d4c7..9587152 100644--- a/src/features/camera-raw-xmp/xmp.ts+++ b/src/features/camera-raw-xmp/xmp.ts@@ -4,6 +4,7 @@ const rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";export type CameraRawXmp = {exposure2012?: number;contrast2012?: number;+ clarity2012?: number;highlights2012?: number;shadows2012?: number;whites2012?: number;@@ -15,6 +16,7 @@ export type CameraRawXmp = {const attributes = {Exposure2012: "exposure2012",Contrast2012: "contrast2012",+ Clarity2012: "clarity2012",Highlights2012: "highlights2012",Shadows2012: "shadows2012",Whites2012: "whites2012",diff --git a/src/features/tone-curves/tone-curves.tsx b/src/features/tone-curves/tone-curves.tsxindex 123830c..2dc22ad 100644--- a/src/features/tone-curves/tone-curves.tsx+++ b/src/features/tone-curves/tone-curves.tsx@@ -11,7 +11,7 @@ type ToneCurvesProps = {export function ToneCurves({ points, onChange, children }: ToneCurvesProps) {return (- <section aria-label="Curves" className="space-y-2.5 p-4 shadow-ridge">+ <section aria-label="Curves" className="space-y-2.5"><div className="flex items-center justify-between"><h2 className="text-sm text-neutral-400">Curves</h2><Buttondiff --git a/src/lib/editor/document/edits.ts b/src/lib/editor/document/edits.tsindex 1d75274..a10d32d 100644--- a/src/lib/editor/document/edits.ts+++ b/src/lib/editor/document/edits.ts@@ -1,4 +1,8 @@-import { type Adjustments, adjustmentLimits } from "@/lib/editor/scene";+import {+ type Adjustments,+ adjustmentLimits,+ adjustmentMinimums,+} from "@/lib/editor/scene";import {defaultCurve,type ToneCurve,@@ -16,7 +20,8 @@ export function setAdjustments(typeof limit !== "number" ||typeof value !== "number" ||!Number.isFinite(value) ||- Math.abs(value) > limit+ value > limit ||+ value < (Reflect.get(adjustmentMinimums, name) ?? -limit)) {throw new Error(`Invalid adjustment: ${name}.`);}diff --git a/src/lib/editor/renderer.ts b/src/lib/editor/renderer.tsindex 3b5e0b2..496362d 100644--- a/src/lib/editor/renderer.ts+++ b/src/lib/editor/renderer.ts@@ -3,12 +3,15 @@ import { createAdjustments } from "@/lib/adjustments";import type { Scene } from "@/lib/editor/scene";import { createImageFrame } from "@/lib/image-frame";import { createToneCurves } from "@/lib/tone-curves";+import { createUnsharpMask } from "@/lib/unsharp-mask";/** Owns scene passes and intermediate textures for one decoded source. */export function createRenderer(gpu: Gpu, source: Target) {const adjust = createAdjustments(gpu, source);const adjusted = adjust.output;const toneCurves = createToneCurves(gpu, adjusted);+ const clarity = createUnsharpMask(gpu, source, 16);+ const sharpen = createUnsharpMask(gpu, source);const transform = createImageFrame(gpu);let original = source;@@ -34,7 +37,20 @@ export function createRenderer(gpu: Gpu, source: Target) {update(scene: Scene) {frame(gpu, (frame) => {adjust.render(frame, scene.adjustments);- fullImage = toneCurves.render(frame, scene.toneCurve);+ const curved = toneCurves.render(frame, scene.toneCurve);+ const {+ clarity: amount,+ sharpening,+ sharpenRadius,+ } = scene.adjustments;+ const clarified = clarity.render(frame, curved, amount / 200, 64);+ fullImage = sharpen.render(+ frame,+ clarified,+ // Slider 150 applies a 3× detail gain; radius remains Gaussian sigma.+ sharpening / 50,+ sharpenRadius,+ );[original, input, output] = transform.render(frame,[source, adjusted, fullImage],@@ -50,6 +66,8 @@ export function createRenderer(gpu: Gpu, source: Target) {listeners.clear();adjust.dispose();toneCurves.dispose();+ clarity.dispose();+ sharpen.dispose();transform.dispose();},};diff --git a/src/lib/editor/scene.ts b/src/lib/editor/scene.tsindex e6e41fd..9c2a6bb 100644--- a/src/lib/editor/scene.ts+++ b/src/lib/editor/scene.ts@@ -1,8 +1,12 @@-import type { Adjustments } from "@/lib/adjustments";+import type { Adjustments as ToneAdjustments } from "@/lib/adjustments";import type { ImageFrame } from "@/lib/image-frame/geometry";import type { ToneCurve } from "@/lib/tone-curves/curve";-export type { Adjustments } from "@/lib/adjustments";+export type Adjustments = ToneAdjustments & {+ clarity: number;+ sharpening: number;+ sharpenRadius: number;+};export const defaultAdjustments: Adjustments = {exposure: 0,@@ -15,6 +19,9 @@ export const defaultAdjustments: Adjustments = {blacks: 0,vibrance: 0,saturation: 0,+ clarity: 0,+ sharpening: 0,+ sharpenRadius: 1,};export const adjustmentLimits: Adjustments = {@@ -28,6 +35,14 @@ export const adjustmentLimits: Adjustments = {blacks: 100,vibrance: 100,saturation: 100,+ clarity: 100,+ sharpening: 150,+ sharpenRadius: 3,+};++export const adjustmentMinimums: Partial<Adjustments> = {+ sharpening: 0,+ sharpenRadius: 0.5,};/** Serializable document content. Image bytes and GPU resources live elsewhere. */diff --git a/src/lib/unsharp-mask/index.ts b/src/lib/unsharp-mask/index.tsnew file mode 100644index 0000000..96709ef--- /dev/null+++ b/src/lib/unsharp-mask/index.ts@@ -0,0 +1,63 @@+import {+ effect,+ type Frame,+ type Gpu,+ sampler,+ type Target,+ target,+} from "vgpu";+import shader from "./unsharp-mask.wgsl";++/** Owns a separable luminance blur and unsharp-mask output. Radius is Gaussian sigma in source pixels. */+export function createUnsharpMask(gpu: Gpu, source: Target, reduction = 1) {+ const size: [number, number] = [+ Math.ceil(source.size[0] / reduction),+ Math.ceil(source.size[1] / reduction),+ ];+ const modes = reduction === 1 ? [1, 2] : [0, 1, 2];+ const temporary = Array.from({ length: modes.length }, () =>+ target(gpu, { size, format: "rgba16float" }),+ );+ const output = target(gpu, { size: source.size, format: source.format });+ const linearSampler = sampler(gpu, {+ minFilter: "linear",+ magFilter: "linear",+ });+ // Reduce, blur horizontally, blur vertically, reconstruct. Each pass owns its uniforms.+ const passes = Array.from({ length: 4 }, (_, mode) =>+ effect(gpu, shader, {+ set: {+ base: source.color,+ linearSampler,+ params: { mode, reduction, amount: 0, sigma: 1 },+ },+ }),+ );+ return {+ render(frame: Frame, input: Target, amount: number, radius: number) {+ if (amount === 0) return input;+ const params = { reduction, amount, sigma: radius / reduction };+ for (const [i, image] of temporary.entries()) {+ frame.pass(+ image,+ passes[modes[i]].set({+ params: { ...params, mode: modes[i] },+ source: i === 0 ? input.color : temporary[i - 1].color,+ }),+ );+ }+ frame.pass(+ output,+ passes[3].set({+ source: input.color,+ base: temporary[temporary.length - 1].color,+ params: { ...params, mode: 3 },+ }),+ );+ return output;+ },+ dispose() {+ for (const image of [...temporary, output]) image.color.dispose();+ },+ };+}diff --git a/src/lib/unsharp-mask/unsharp-mask.wgsl b/src/lib/unsharp-mask/unsharp-mask.wgslnew file mode 100644index 0000000..6819965--- /dev/null+++ b/src/lib/unsharp-mask/unsharp-mask.wgsl@@ -0,0 +1,55 @@+import { linearToSrgb, srgbToLinear } from "@vgpu/wgsl-std/color";+import { luminance } from "../color.wgsl";++struct Params { mode: u32, reduction: i32, amount: f32, sigma: f32 }+@group(0) @binding(0) var source: texture_2d<f32>;+@group(0) @binding(1) var base: texture_2d<f32>;+@group(0) @binding(2) var linearSampler: sampler;+@group(0) @binding(3) var<uniform> params: Params;++fn load(p: vec2i) -> vec4f {+ return textureLoad(source, clamp(p, vec2i(0), vec2i(textureDimensions(source)) - 1), 0);+}++@fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {+ let p = vec2i(position.xy);+ if (params.mode == 0u) {+ var total = vec2f(0.0);+ for (var y = 0; y < params.reduction; y++) {+ for (var x = 0; x < params.reduction; x++) {+ let pixel = load(p * params.reduction + vec2i(x, y));+ total += vec2f(linearToSrgb(max(luminance(pixel.rgb), 0.0)), 1.0) * pixel.a;+ }+ }+ return vec4f(total / f32(params.reduction * params.reduction), 0.0, 1.0);+ }+ if (params.mode < 3u) {+ let sigma = params.sigma;+ let axis = select(vec2i(0, 1), vec2i(1, 0), params.mode == 1u);+ var total = vec2f(0.0);+ var weights = 0.0;+ let radius = i32(ceil(3.0 * sigma));+ for (var offset = -radius; offset <= radius; offset++) {+ let distance = f32(offset) / sigma;+ let weight = exp(-0.5 * distance * distance);+ let pixel = load(p + axis * offset);+ var value = pixel.rg;+ if (params.mode == 1u && params.reduction == 1) {+ value = vec2f(linearToSrgb(max(luminance(pixel.rgb), 0.0)), 1.0) * pixel.a;+ }+ total += value * weight;+ weights += weight;+ }+ return vec4f(total / weights, 0.0, 1.0);+ }+ let pixel = load(p);+ if (pixel.a == 0.0) { return pixel; }+ let y = max(luminance(pixel.rgb), 0.0);+ let lightness = linearToSrgb(y);+ let uv = position.xy / (f32(params.reduction) * vec2f(textureDimensions(base)));+ let blurred = textureSampleLevel(base, linearSampler, uv, 0.0).rg;+ let mean = blurred.r / max(blurred.g, 0.000001);+ let outputY = srgbToLinear(max(lightness + params.amount * (lightness - mean), 0.0));+ let rgb = select(vec3f(outputY), pixel.rgb * (outputY / max(y, 0.000001)), y > 0.000001);+ return vec4f(rgb, pixel.a);+}diff --git a/tests/clarity.e2e.ts b/tests/clarity.e2e.tsnew file mode 100644index 0000000..7f3efb0--- /dev/null+++ b/tests/clarity.e2e.ts@@ -0,0 +1,155 @@+import { expect, test } from "./fixtures";++// Full-resolution Gaussian reference, independent of GPU passes and working-space conversion.+function expectedStep(+ x: number,+ left: number,+ right: number,+ amount: number,+ sigma: number,+) {+ let sum = 0;+ let weights = 0;+ const radius = Math.ceil(3 * sigma);+ for (let offset = -radius; offset <= radius; offset++) {+ const weight = Math.exp(-0.5 * (offset / sigma) ** 2);+ sum += (x + offset < 512 ? left : right) * weight;+ weights += weight;+ }+ const original = x < 512 ? left : right;+ return Math.max(+ 0,+ Math.min(255, original + amount * (original - sum / weights)),+ );+}++test("detail filters follow Gaussian unsharp masking and preserve flat fields and alpha", async ({+ page,+}) => {+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ const xs = [+ 0, 256, 384, 448, 504, 509, 510, 511, 512, 513, 514, 519, 576, 640, 768,+ 1023,+ ];+ const result = await page.evaluate(async (xs) => {+ const api = window.openlight;+ const load = async (width: number, height: number, shapes: string) => {+ await api.loadImage(+ new File(+ [+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">${shapes}</svg>`,+ ],+ "probe.svg",+ { type: "image/svg+xml" },+ ),+ );+ };+ const read = async (positions: number[][]) => {+ const image = await createImageBitmap(await api.exportImage());+ const canvas = new OffscreenCanvas(image.width, image.height);+ const context = canvas.getContext("2d");+ if (!context) throw new Error("Cannot read clarity probe.");+ context.drawImage(image, 0, 0);+ image.close();+ return positions.map(([x, y]) => [+ ...context.getImageData(x, y, 1, 1).data,+ ]);+ };+ const steps = [];+ for (const [left, right] of [+ [64, 192],+ [0, 128],+ ]) {+ await load(+ 1024,+ 129,+ [left, right]+ .map(+ (value, i) =>+ `<rect x="${i * 512}" width="512" height="129" fill="rgb(${value},${value},${value})"/>`,+ )+ .join(""),+ );+ const settings = [+ ...[-100, -50, 0, 50, 100].map((clarity) => ({+ clarity,+ sharpening: 0,+ sharpenRadius: 1,+ })),+ ...[0.5, 1, 1.7, 3].flatMap((sharpenRadius) =>+ [0, 50, 100, 150].map((sharpening) => ({+ clarity: 0,+ sharpening,+ sharpenRadius,+ })),+ ),+ ];+ for (const adjustment of settings) {+ api.setAdjustments(adjustment);+ steps.push({+ left,+ right,+ amount: adjustment.sharpening+ ? adjustment.sharpening / 50+ : adjustment.clarity / 200,+ sigma: adjustment.sharpening ? adjustment.sharpenRadius : 64,+ pixels: await read(xs.map((x) => [x, 64])),+ });+ }+ }+ await load(127, 65, '<rect width="127" height="65" fill="#737373"/>');+ const flat = [];+ for (const clarity of [-100, 0, 100]) {+ api.setAdjustments({ clarity, sharpening: 150, sharpenRadius: 3 });+ flat.push(+ ...(await read([+ [0, 0],+ [63, 32],+ [126, 64],+ ])),+ );+ }+ await load(+ 127,+ 65,+ '<rect width="64" height="65" fill="#737373" fill-opacity="0.5"/>',+ );+ const positions = [+ [10, 32],+ [63, 32],+ [64, 32],+ [126, 64],+ ];+ const neutral = await read(positions);+ const alpha = [];+ for (const clarity of [-100, 100]) {+ api.setAdjustments({ clarity, sharpening: 150, sharpenRadius: 3 });+ alpha.push(await read(positions));+ }+ return { steps, flat, neutral, alpha };+ }, xs);+ for (const { left, right, amount, sigma, pixels } of result.steps) {+ for (const [i, pixel] of pixels.entries()) {+ for (const channel of pixel.slice(0, 3))+ expect(+ Math.abs(channel - expectedStep(xs[i], left, right, amount, sigma)),+ ).toBeLessThanOrEqual(2);+ expect(pixel[3]).toBe(255);+ }+ }+ for (const pixel of result.flat) {+ for (const channel of pixel.slice(0, 3))+ expect(Math.abs(channel - 115)).toBeLessThanOrEqual(1);+ expect(pixel[3]).toBe(255);+ }+ for (const pixels of result.alpha) {+ for (const [i, pixel] of pixels.entries()) {+ expect(pixel[3]).toBe(result.neutral[i][3]);+ for (const [channel, value] of pixel.entries())+ expect(+ Math.abs(value - result.neutral[i][channel]),+ ).toBeLessThanOrEqual(2);+ }+ }+});diff --git a/tests/documents.test.ts b/tests/documents.test.tsindex 44ff4ae..46a9d1e 100644--- a/tests/documents.test.ts+++ b/tests/documents.test.ts@@ -20,6 +20,16 @@ function document() {test("documents edit independently without React, retain bounded history, and reject edits after replacement", async () => {const first = document();const second = document();+ for (const change of [+ { sharpening: -1 },+ { sharpening: 151 },+ { sharpenRadius: 0 },+ { sharpenRadius: 3.1 },+ { sharpenRadius: NaN },+ ]) {+ expect(() => setAdjustments(first, change)).toThrow("Invalid adjustment");+ }+setAdjustments(first, { exposure: 1 });const points = [{ x: 0, y: 0 },diff --git a/tests/editing.e2e.ts b/tests/editing.e2e.tsindex c9e40ed..8ffbf38 100644--- a/tests/editing.e2e.ts+++ b/tests/editing.e2e.ts@@ -62,6 +62,27 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportconst initial = await state();expect((await readImage(page)).center).toEqual([128, 128, 128, 255]);+ await test.step("adjustment sections collapse independently without changing the scene", async () => {+ for (const [title, label] of [+ ["Light", "Exposure"],+ ["Color", "Temp"],+ ["Details", "Clarity"],+ ]) {+ const summary = page.getByRole("button", { name: title, exact: true });+ const control = page.getByRole("slider", { name: label, exact: true });+ await summary.click();+ await expect(summary).toHaveAttribute("aria-expanded", "false");+ await expect(control).toBeHidden();+ if (title === "Light")+ await expect(+ page.getByRole("region", { name: "Curves", exact: true }),+ ).toBeHidden();+ expect(await state()).toEqual(initial);+ await summary.press("Enter");+ await expect(control).toBeVisible();+ }+ });+await test.step("zoomed rendering reaches the edges of the editor viewport", async () => {const viewport = await page.getByRole("region", { name: "Image canvas" })@@ -295,6 +316,53 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportawait expect.poll(() => canvas.screenshot()).toEqual(original);});+ await test.step("clarity changes local contrast and histogram, then undoes and resets", async () => {+ const field = page.getByRole("textbox", { name: "Clarity", exact: true });+ const slider = page.getByRole("slider", { name: "Clarity", exact: true });+ await field.fill("100");+ await field.press("Enter");+ await expect(slider).toHaveValue("100");+ await expect(output).not.toHaveAttribute("points", histogram ?? "");+ const positive = await readImage(page);+ expect(positive.center).toEqual([128, 128, 128, 255]);+ expect(positive.corner).toEqual([0, 0, 0, 255]);+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ await expect(slider).toHaveValue("0");+ expect((await readImage(page)).center).toEqual([128, 128, 128, 255]);+ await field.fill("-100");+ await field.press("Enter");+ expect((await readImage(page)).center).toEqual([128, 128, 128, 255]);+ expect((await readImage(page)).corner[0]).toBeGreaterThan(0);+ await slider.dblclick();+ await expect(slider).toHaveValue("0");+ await expect(output).toHaveAttribute("points", histogram ?? "");+ });++ await test.step("sharpening amount and radius edit, undo, and reset", async () => {+ const amount = page.getByRole("textbox", {+ name: "Sharpening",+ exact: true,+ });+ const radius = page.getByRole("textbox", { name: "Radius", exact: true });+ await amount.fill("100");+ await amount.press("Enter");+ await radius.fill("3");+ await radius.press("Enter");+ await expect(output).not.toHaveAttribute("points", histogram ?? "");+ expect((await readImage(page)).center).toEqual([128, 128, 128, 255]);+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ await expect(radius).toHaveValue("1.0");+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ await expect(amount).toHaveValue("0");+ await expect(output).toHaveAttribute("points", histogram ?? "");+ await amount.fill("150");+ await amount.press("Enter");+ await page+ .getByRole("slider", { name: "Sharpening", exact: true })+ .dblclick();+ await expect(amount).toHaveValue("0");+ });+await test.step("curve gestures change output after adjustments and undo as one edit", async () => {await page.evaluate(() =>window.openlight.setAdjustments({ exposure: -1 }),@@ -346,9 +414,14 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export{ from: [0, 1], to: [0, 0.75], sample: "corner", expected: 64 },{ from: [1, 0], to: [0.1, 0], sample: "center", expected: 255 },] as const) {+ await graph.scrollIntoViewIfNeeded();+ const bounds = await box(graph);await drag(page,- [bounds.x + from[0] * bounds.width, bounds.y + from[1] * bounds.height],+ [+ bounds.x + 1 + from[0] * (bounds.width - 2),+ bounds.y + 1 + from[1] * (bounds.height - 2),+ ],[bounds.x + to[0] * bounds.width, bounds.y + to[1] * bounds.height],5,);@@ -807,6 +880,9 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportshadows: 30,whites: 10,blacks: -5,+ clarity: -50,+ sharpening: 100,+ sharpenRadius: 1,});window.openlight.setToneCurve([{ x: 0, y: 0 },@@ -818,7 +894,8 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportconst expected = await readImage(page);expect(expected.center[0]).toBeGreaterThan(190);expect(expected.center[0]).toBeLessThan(255);- expect(expected.corner).toEqual([0, 0, 0, 255]);+ expect(expected.corner[0]).toBeGreaterThan(0);+ expect(expected.corner[3]).toBe(255);await canvas.hover();await zoom(page, Math.E);const trigger = page.getByRole("button", { name: "Export", exact: true });diff --git a/tests/renderer.test.ts b/tests/renderer.test.tsindex f499ca6..52480c4 100644--- a/tests/renderer.test.ts+++ b/tests/renderer.test.ts@@ -12,6 +12,51 @@ import { defaultAdjustments } from "@/lib/editor/scene";import { createDisplay } from "@/lib/image-display";import { imageFrame } from "@/lib/image-frame/geometry";import { defaultCurve } from "@/lib/tone-curves/curve";+import { createUnsharpMask } from "@/lib/unsharp-mask";++test.each([1, 16])(+ "unsharp mask at reduction %s bypasses zero, reuses pipelines, and owns its outputs",+ async (reduction) => {+ const gpu = await init();+ const source = target(gpu, { size: [127, 65], format: "rgba16float" });+ const clarity = createUnsharpMask(gpu, source, reduction);+ let output = source;+ const render = (amount: number) =>+ frame(gpu, (f) => {+ output = clarity.render(+ f,+ source,+ amount / 200,+ reduction === 1 ? 1 : 64,+ );+ });+ try {+ render(0);+ expect(output).toBe(source);+ const calls = getMockGPUDeviceInstrumentation(gpu.gpu).calls;+ expect(calls.createRenderPipeline ?? 0).toBe(0);+ render(100);+ const filtered = output;+ expect(filtered).not.toBe(source);+ expect(filtered.size).toEqual(source.size);+ const pipelines = calls.createRenderPipeline;+ for (const amount of [-100, -50, 25, 75]) {+ render(amount);+ expect(output).toBe(filtered);+ }+ expect(calls.createRenderPipeline).toBe(pipelines);+ render(0);+ expect(output).toBe(source);+ clarity.dispose();+ expect(() => filtered.color.view).toThrow("destroyed");+ expect(() => source.color.view).not.toThrow();+ } finally {+ clarity.dispose();+ source.color.dispose();+ gpu.dispose();+ }+ },+);test("rendering follows grouped edits and undo, reuses pipelines, and releases owned targets", async () => {const gpu = await init();@@ -81,7 +126,12 @@ test("rendering follows grouped edits and undo, reuses pipelines, and releases oexpect(notify).toHaveBeenCalledTimes(8);expect(late).toHaveBeenCalledTimes(1);detach();- setAdjustments(document, { exposure: -1 });+ setAdjustments(document, {+ exposure: -1,+ clarity: 50,+ sharpening: 100,+ sharpenRadius: 2,+ });expect(notify).toHaveBeenCalledTimes(8);document.edit({...document.scene.getState(),