Free open-source image editor for the browser
Improve histogram
Rodrigo20b4753cf469
diff --git a/AGENTS.md b/AGENTS.mdindex 73d7c5f..db8cd57 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -9,7 +9,8 @@ Demonstrate a professional photo editor with little, readable code.## 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 the smallest complete implementation that preserves clear ownership. Evaluate simplicity across the whole feature, including lifecycle glue and consumers; moving lines into helpers is not a reduction.+Start with a direct function and thin UI composition. Add a layer only when it hides a real responsibility or removes duplication; keep cohesive work together when splitting it would only add forwarding.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.@@ -23,6 +24,8 @@ The Zustand scene store owns document state. UI interactions and browser command## Structure+Prefer named exports (`export function`) and named imports. Use default exports only when a concrete integration requires or clearly benefits from them, such as a worker loader or dynamic-import consumer that expects a default export.+The `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:- `app/`: application shell, app-wide state, and composition. It may import every folder below; no folder imports it.diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsxindex 9164604..7126ae2 100644--- a/src/app/editor/index.tsx+++ b/src/app/editor/index.tsx@@ -6,7 +6,7 @@ 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";+import { Sidebar } from "./sidebar";type WorkspaceProps = { image: Target };diff --git a/src/app/editor/renderer/renderer.ts b/src/app/editor/renderer/renderer.tsindex 2427583..bde96e2 100644--- a/src/app/editor/renderer/renderer.ts+++ b/src/app/editor/renderer/renderer.ts@@ -7,11 +7,6 @@ import {target,} from "vgpu";import type { Scene } from "@/app/scene";-import { histogram } from "@/features/histogram/bins";-import {- type HistogramMode,- histogramChart,-} from "@/features/histogram/histogram";import type { View } from "@/hooks/use-pan-zoom";import adjustmentsShader from "@/lib/adjustments/adjustments.wgsl";import { sampleCurve } from "@/lib/curves";@@ -19,10 +14,6 @@ import curvesShader from "@/lib/curves/curves.wgsl";import shader from "./renderer.wgsl";const curveSize = 1024;-export type HistogramOptions = {- stage?: "input" | "output";- mode?: HistogramMode;-};/** Owns scene passes and intermediate textures for one decoded source. */export function createRenderer(gpu: Gpu, source: Target) {@@ -38,7 +29,6 @@ export function createRenderer(gpu: Gpu, source: Target) {const applyCurve = effect(gpu, curvesShader, {set: { source: adjusted.color, curve },});- let bins: ReturnType<typeof histogram> | undefined;const display = effect(gpu, shader, {set: {sourceSampler: sampler(gpu, { magFilter: "linear", minFilter: "linear" }),@@ -46,29 +36,10 @@ export function createRenderer(gpu: Gpu, source: Target) {});const canvases = new Set<{ canvas: Target & { dpr: number }; view: View }>();- const charts = {- input: new Set<ReturnType<typeof histogramChart>>(),- output: new Set<ReturnType<typeof histogramChart>>(),- };- let disposed = false;- let sampling = false;- async function drawHistograms(- image: Target,- outputs: Set<ReturnType<typeof histogramChart>>,- space: "display" | "working",- ) {- if (disposed || outputs.size === 0) {- return;- }- bins ??= histogram(gpu);- const counts = await bins.read(image, space);- if (!disposed) {- for (const draw of outputs) {- draw(counts);- }- }- }+ let output = adjusted;return {+ inputImage: () => adjusted,+ outputImage: () => output,attachCanvas(canvas: Target & { dpr: number }, view: View) {const output = { canvas, view };canvases.add(output);@@ -76,22 +47,12 @@ export function createRenderer(gpu: Gpu, source: Target) {canvases.delete(output);};},- attachHistogram(- svg: SVGSVGElement,- { stage = "output", mode = "rgb" }: HistogramOptions = {},- ) {- const draw = histogramChart(svg, mode);- charts[stage].add(draw);- return () => {- charts[stage].delete(draw);- };- },render(frame: Frame, scene: Scene) {frame.pass(adjusted,adjust.set({ source: source.color, adjustments: scene.adjustments }),);- let output = adjusted;+ output = adjusted;if (scene.curve.some((point) => point.x !== point.y)) {curve.write(sampleCurve(scene.curve, curveSize));frame.pass(curved, applyCurve);@@ -111,29 +72,9 @@ export function createRenderer(gpu: Gpu, source: Target) {}),);}- if (sampling || charts.input.size + charts.output.size === 0) {- return;- }- sampling = true;- frame.done- .then(async () => {- await drawHistograms(adjusted, charts.input, "working");- await drawHistograms(output, charts.output, "display");- })- .catch((error: unknown) => {- if (!disposed) {- console.error(error);- }- })- .finally(() => {- sampling = false;- });},dispose() {- disposed = true;canvases.clear();- charts.input.clear();- charts.output.clear();adjusted.color.dispose();curved.color.dispose();curve.dispose();diff --git a/src/app/editor/sidebar/curves/index.tsx b/src/app/editor/sidebar/curves/index.tsxindex 1406656..9244b97 100644--- a/src/app/editor/sidebar/curves/index.tsx+++ b/src/app/editor/sidebar/curves/index.tsx@@ -1,8 +1,17 @@-import Histogram from "@/app/editor/sidebar/histogram";+import { useRenderer } from "@/app/editor/renderer/provider";import { useScene } from "@/app/scene";+import { Histogram } from "@/features/histogram";+import type { createHistogram } from "@/features/histogram/histogram";import Graph from "./graph";-export default function Curves() {+const histogramColors = ["#a3a3a3"] as const;++type CurvesProps = {+ histogram: ReturnType<typeof createHistogram>;+};++export function Curves({ histogram }: CurvesProps) {+ const renderer = useRenderer();const points = useScene((scene) => scene.curve);const setCurve = useScene((scene) => scene.setCurve);return (@@ -33,9 +42,13 @@ export default function Curves() {<div className="px-0.5"><div className="relative aspect-square rounded border border-black bg-neutral-900 shadow-groove"><Histogram+ histogram={histogram}+ image={renderer.inputImage}+ colors={histogramColors}+ working+ fillOpacity={0.65}+ aria-label="input histogram"className="pointer-events-none absolute inset-0 h-full w-full opacity-25"- mode="combined"- stage="input"/><Graph onChange={setCurve} points={points} /></div>diff --git a/src/app/editor/sidebar/histogram.tsx b/src/app/editor/sidebar/histogram.tsxdeleted file mode 100644index 6e91f3e..0000000--- a/src/app/editor/sidebar/histogram.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { useEffect, useRef } from "react";-import { useRenderer } from "@/app/editor/renderer/provider";-import type { HistogramOptions } from "@/app/editor/renderer/renderer";--type HistogramProps = HistogramOptions & { className?: string };--export default function Histogram({- stage = "output",- mode = "rgb",- className = "h-24 w-full",-}: HistogramProps) {- const renderer = useRenderer();- const ref = useRef<SVGSVGElement>(null);- useEffect(() => {- if (ref.current) {- return renderer.attachHistogram(ref.current, { stage, mode });- }- }, [renderer, stage, mode]);- return (- <svg- ref={ref}- aria-label={`${stage} histogram`}- className={className}- preserveAspectRatio="none"- viewBox="0 0 255 100"- />- );-}diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/sidebar/index.tsxindex 17c9269..996e443 100644--- a/src/app/editor/sidebar/index.tsx+++ b/src/app/editor/sidebar/index.tsx@@ -1,19 +1,36 @@+import { useEffect, useMemo } from "react";+import { useGpu } from "vgpu-react";+import { useRenderer } from "@/app/editor/renderer/provider";import ResizablePanel from "@/components/ui/resizable-panel";+import { Histogram } from "@/features/histogram";+import { createHistogram } from "@/features/histogram/histogram";import AdjustmentControls from "./adjustment-controls";-import Curves from "./curves";+import { Curves } from "./curves";import ExportButton from "./export-button";-import Histogram from "./histogram";-export default function Sidebar() {+const histogramColors = ["#f25445", "#6bd175", "#5c8ffa"] as const;++export function Sidebar() {+ const gpu = useGpu();+ const renderer = useRenderer();+ const histogram = useMemo(() => createHistogram(gpu), [gpu]);+ useEffect(() => () => histogram.dispose(), [histogram]);return (<ResizablePanel><div className="flex h-full flex-col divide-y divide-black"><div className="min-h-0 flex-1 divide-y divide-black overflow-y-auto"><section className="bg-neutral-900 p-0.5 pb-0">- <Histogram />+ <Histogram+ histogram={histogram}+ image={renderer.outputImage}+ colors={histogramColors}+ fillOpacity={0.2}+ className="h-30 w-full"+ aria-label="output histogram"+ /></section><AdjustmentControls />- <Curves />+ <Curves histogram={histogram} /></div><ExportButton /></div>diff --git a/src/features/histogram/bins.ts b/src/features/histogram/bins.tsdeleted file mode 100644index 88d467b..0000000--- a/src/features/histogram/bins.ts+++ /dev/null@@ -1,21 +0,0 @@-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, space: "display" | "working" = "display") {- buffer.write(emptyBins);- counter- .set({- source: image.color,- params: { working: Number(space === "working") },- })- .dispatch(32, 20);- return new Uint32Array(await buffer.read());- },- };-}diff --git a/src/features/histogram/bins.wgsl b/src/features/histogram/bins.wgsldeleted file mode 100644index e4eea36..0000000--- a/src/features/histogram/bins.wgsl+++ /dev/null@@ -1,38 +0,0 @@-import { display } from "../../lib/color.wgsl";-import { linearToSrgb3 } from "@vgpu/wgsl-std/color";--struct Params {- working: u32,-}--@group(0) @binding(0) var source: texture_2d<f32>;-@group(0) @binding(1) var<storage, read_write> bins: array<atomic<u32>, 768>;-@group(0) @binding(2) var<uniform> params: Params;--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;--// 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) {- if (any(id.xy >= samples)) {- return;- }- let texel = textureLoad(source, id.xy * textureDimensions(source) / samples, 0).rgb;- var encoded = display(texel);- if (params.working != 0u) {- encoded = linearToSrgb3(clamp(texel, vec3f(0.0), vec3f(1.0)));- }- softBin(0u, encoded.r * 255.0);- softBin(1u, encoded.g * 255.0);- softBin(2u, encoded.b * 255.0);-}diff --git a/src/features/histogram/histogram.ts b/src/features/histogram/histogram.tsindex 6cbf24c..b13b04a 100644--- a/src/features/histogram/histogram.ts+++ b/src/features/histogram/histogram.ts@@ -1,66 +1,82 @@-const channels = ["#f25445", "#6bd175", "#5c8ffa"];-const binCount = 256;-const kernel = [1, 4, 6, 4, 1];-const kernelWeight = 16;+import { compute, frameLoop, type Gpu, type Target } from "vgpu";+import shader from "./histogram.wgsl";-export type HistogramMode = "rgb" | "combined";--/** 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;+export function createHistogram(gpu: Gpu) {+ const bins = gpu.device.createBuffer({+ size: 3072,+ usage: ["storage", "copy_dst"],});-}--/** RGB polyline points on a 255×100 box: smoothed, then square-root scaled to the shared peak. */-function curves(bins: Uint32Array, mode: HistogramMode) {- let counts = channels.map((_, channel) => smooth(bins, channel));- if (mode === "combined") {- counts = [- counts[0].map((count, bin) => count + counts[1][bin] + counts[2][bin]),- ];- }- 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,- mode: HistogramMode = "rgb",-) {- let colors = channels;- let opacity = 0.2;- if (mode === "combined") {- colors = ["#a3a3a3"];- opacity = 0.65;+ const heights = gpu.device.createBuffer({+ size: 3072,+ usage: ["storage", "copy_src"],+ });+ const count = compute(gpu, shader, { entry: "count", set: { bins } });+ const finish = compute(gpu, shader, {+ entry: "finish",+ set: { bins, heights },+ });+ const empty = new Uint32Array(768);+ async function read(image: Target, working = false, channels: 1 | 3 = 3) {+ const params = { working: Number(working), channels };+ bins.write(empty);+ count.set({ source: image.color, params }).dispatch(32, 20);+ finish.set({ params }).dispatch(1);+ return new Float32Array(await heights.read(channels * 1024));}- svg.innerHTML = `<title>Histogram</title>${colors- .map(- (color) =>- `<g><polygon fill="${color}" fill-opacity="${opacity}"/><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, mode).forEach((points, channel) => {- polygons[channel].setAttribute("points", `0,100 ${points} 255,100`);- lines[channel].setAttribute("points", points);- });+ return {+ read,+ attach(+ svg: SVGSVGElement,+ image: () => Target,+ colors: readonly [string] | readonly [string, string, string],+ working = false,+ ) {+ const namespace = "http://www.w3.org/2000/svg";+ const plot = document.createElementNS(namespace, "g");+ const curves = colors.map((color) => {+ const polygon = document.createElementNS(namespace, "polygon");+ const polyline = document.createElementNS(namespace, "polyline");+ polygon.setAttribute("fill", color);+ polygon.setAttribute("stroke", "none");+ polyline.setAttribute("fill", "none");+ polyline.setAttribute("stroke", color);+ polyline.setAttribute("vector-effect", "non-scaling-stroke");+ plot.append(polygon, polyline);+ return { polygon, polyline };+ });+ svg.append(plot);+ let pending = false;+ const loop = frameLoop(gpu, async () => {+ if (pending) {+ return;+ }+ pending = true;+ try {+ const values = await read(image(), working, colors.length);+ curves.forEach(({ polygon, polyline }, channel) => {+ const points = Array.from(+ values.subarray(channel * 256, (channel + 1) * 256),+ (y, x) => `${x},${y.toFixed(1)}`,+ ).join(" ");+ polygon.setAttribute("points", `0,100 ${points} 255,100`);+ polyline.setAttribute("points", points);+ });+ } catch (error) {+ if (plot.isConnected) {+ console.error(error);+ }+ } finally {+ pending = false;+ }+ });+ return () => {+ loop.stop();+ plot.remove();+ };+ },+ dispose() {+ bins.dispose();+ heights.dispose();+ },};}diff --git a/src/features/histogram/histogram.wgsl b/src/features/histogram/histogram.wgslnew file mode 100644index 0000000..d59e375--- /dev/null+++ b/src/features/histogram/histogram.wgsl@@ -0,0 +1,71 @@+import { display } from "../../lib/color.wgsl";+import { linearToSrgb3 } from "@vgpu/wgsl-std/color";++struct Params {+ working: u32,+ channels: u32,+}++@group(0) @binding(0) var source: texture_2d<f32>;+@group(0) @binding(1) var<storage, read_write> bins: array<atomic<u32>, 768>;+@group(0) @binding(2) var<uniform> params: Params;+@group(0) @binding(3) var<storage, read_write> heights: array<f32>;++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;++// 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 count(@builtin(global_invocation_id) id: vec3u) {+ if (any(id.xy >= samples)) {+ return;+ }+ let texel = textureLoad(source, id.xy * textureDimensions(source) / samples, 0).rgb;+ var encoded = display(texel);+ if (params.working != 0u) {+ encoded = linearToSrgb3(clamp(texel, vec3f(0.0), vec3f(1.0)));+ }+ softBin(0u, encoded.r * 255.0);+ softBin(1u, encoded.g * 255.0);+ softBin(2u, encoded.b * 255.0);+}++var<workgroup> peaks: array<f32, 256>;+const kernel = array<f32, 5>(1.0, 4.0, 6.0, 4.0, 1.0);++// A separate dispatch makes every bin visible before smoothing. One workgroup+// reduces the shared peak, then writes only the requested 256 or 768 ordinates.+@compute @workgroup_size(256) fn finish(@builtin(local_invocation_index) bin: u32) {+ var values = vec3f(0.0);+ for (var k = 0u; k < 5u; k++) {+ let neighbor = i32(bin) + i32(k) - 2;+ if (neighbor >= 0 && neighbor < 256) {+ for (var channel = 0u; channel < 3u; channel++) {+ values[channel] += f32(atomicLoad(&bins[channel * 256u + u32(neighbor)])) * kernel[k] / 16.0;+ }+ }+ }+ if (params.channels == 1u) {+ values = vec3f(values.r + values.g + values.b, 0.0, 0.0);+ }+ peaks[bin] = max(values.r, max(values.g, values.b));+ workgroupBarrier();+ for (var stride = 128u; stride > 0u; stride /= 2u) {+ if (bin < stride) {+ peaks[bin] = max(peaks[bin], peaks[bin + stride]);+ }+ workgroupBarrier();+ }+ for (var channel = 0u; channel < params.channels; channel++) {+ heights[channel * 256u + bin] = 100.0 * (1.0 - sqrt(values[channel] / max(1.0, peaks[0])));+ }+}diff --git a/src/features/histogram/index.tsx b/src/features/histogram/index.tsxnew file mode 100644index 0000000..b697e2d--- /dev/null+++ b/src/features/histogram/index.tsx@@ -0,0 +1,36 @@+import { type ComponentProps, useCallback } from "react";+import type { Target } from "vgpu";+import type { createHistogram } from "./histogram";++type Props = ComponentProps<"svg"> & {+ histogram: ReturnType<typeof createHistogram>;+ image: () => Target;+ colors: readonly [string] | readonly [string, string, string];+ working?: boolean;+};++export function Histogram({+ histogram,+ image,+ colors,+ working,+ ...props+}: Props) {+ const attach = useCallback(+ (svg: SVGSVGElement | null) => {+ if (svg) {+ return histogram.attach(svg, image, colors, working);+ }+ },+ [histogram, image, colors, working],+ );+ return (+ <svg+ ref={attach}+ aria-label="Histogram"+ viewBox="0 0 255 100"+ preserveAspectRatio="none"+ {...props}+ />+ );+}diff --git a/tests/curves.e2e.ts b/tests/curves.e2e.tsindex 3916179..07c9cf2 100644--- a/tests/curves.e2e.ts+++ b/tests/curves.e2e.ts@@ -208,6 +208,7 @@ test("the curve panel edits points over a combined input histogram", async ({await expect(input).toHaveAttribute("points", /,0\.0/);await expect(output).toHaveAttribute("points", /,0\.0/);const inputBefore = await input.getAttribute("points");+ const inputNode = await input.elementHandle();const outputBefore = await output.getAttribute("points");await graph.click({position: { x: bounds.width / 2, y: bounds.height / 2 },@@ -231,6 +232,7 @@ test("the curve panel edits points over a combined input histogram", async ({expect(edited.y).toBeCloseTo(0.75, 2);await expect(output).not.toHaveAttribute("points", outputBefore ?? "");await expect(input).toHaveAttribute("points", inputBefore ?? "");+ expect(await inputNode?.evaluate((node) => node.isConnected)).toBe(true);await expect.poll(async () => (await centerPixel(page))[0]).toBeGreaterThan(185);diff --git a/tests/histogram.e2e.ts b/tests/histogram.e2e.tsnew file mode 100644index 0000000..4d301ac--- /dev/null+++ b/tests/histogram.e2e.ts@@ -0,0 +1,24 @@+import { expect, test } from "@playwright/test";++test("loading an image renders the RGB histogram", async ({ page }) => {+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ await page.evaluate(() =>+ 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>',+ ],+ "gray.svg",+ { type: "image/svg+xml" },+ ),+ ),+ );+ const histogram = page.getByLabel("output histogram", { exact: true });+ await expect(histogram).toBeVisible();+ const curves = histogram.locator("polygon");+ await expect(curves).toHaveCount(3);+ for (const curve of await curves.all()) {+ await expect(curve).toBeVisible();+ }+});