Free open-source image editor for the browser
Fix Healing's first stroke and nested donors; tidy editor ownership (#41)
Rodrigo Belfiore96a7009ae984
diff --git a/API.md b/API.mdindex d2340e6..e1491c3 100644--- a/API.md+++ b/API.md@@ -92,9 +92,9 @@ A linear gradient has full coverage at `start`, zero at `end`; its points must bA brush mask is a list of strokes. Each stroke has `mode` (`"paint"` or `"erase"`), `size` (diameter in source pixels), `feather` and `flow` (0–1), and `points`, each `[x, y, pressure]` in source pixels with pressure 0–1. Dabs land every quarter diameter along the points; a paint stroke adds `flow × pressure` of the remaining coverage under each dab, and an erase stroke removes that share of the existing coverage. The renderer rasterizes strokes into a cached coverage texture at source resolution and only stamps new points, so appending to the last stroke is cheap and undo replays the rest. A brush inside another mask keeps its own coverage, paint and erase strokes alike, which the mask adds or subtracts scaled by the brush layer's opacity. A mask with no painted coverage and nothing added to it is bypassed.-The sidebar always shows the output histogram, the selected layer's controls, and the layer stack; layers and controls scroll independently. The rail holds tools: **A** Adjust, **B** Brush, **L** Linear gradient, **R** Radial gradient, **H** Healing, and **C** Crop; **E** opens Export from the header. A selected mask is *active*: the sidebar shows its adjustments and the bar its opacity. It is *edited* only while a shape tool is on the rail, which shows its guides or brush and the overlay; Adjust leaves the canvas to pan and zoom. Selecting a mask in the stack arms the tool of its shape; selecting the image or an effect returns to Adjust. **Enter**, or **Escape** with no drag in progress, leaves one level at a time: a shape tool returns to Adjust with the mask still selected, so its sliders stay at hand without guides over the image, and in Adjust the selection climbs to the parent mask, then to the image with its global controls. The shape's key or the mask's row enters editing again. Enter on a focused button stays its click. The bar over the image edits the active tool and the selected layer: the tool's options, then the layer's opacity, Overlay, and a radial mask's Feather or a child mask's operation. It never wraps: when the canvas is narrow it drops the slider bars, then moves the layer options and finally everything into a menu at its end. Dragging with a gradient tool draws a new mask above the selection; the tool stays active, and **Alt** while starting the drag subtracts the gradient from the selected mask instead. Choosing the Brush tool creates an empty brush mask above the selection at once, so adjustments made before the first stroke belong to it; leaving the tool while that mask has no strokes and nothing else changed removes it together with its history entry. A brush stroke paints into the selected brush mask, or starts a new brush mask. Creating inside a mask happens in the layer stack: each root mask row has Add and Subtract menus that choose a shape and nest the next mask inside it, and **Delete** removes the selected layer with any tool. The brush bar sets size, feather, flow, and paint or erase; **[** and **]** resize, holding **Alt** erases and shows Erase pressed, and **Escape** cancels the stroke. On a touch screen a second finger during a stroke cancels it and pinches instead, so painting and zooming never mix. The brush cursor previews the dab's feather and remains visible while Size or Feather is edited. Creating the mask and each stroke are separate undo steps.+The sidebar always shows the output histogram, the selected layer's controls under that layer's name (or Image), and the layer stack; layers and controls scroll independently. The zoom percentage counts image pixels per device pixel: clicking it at fit zooms to 100%, and anywhere else returns to fit. The rail holds tools: **A** Adjust, **B** Brush, **L** Linear gradient, **R** Radial gradient, **H** Healing, and **C** Crop; **E** opens Export from the header. A selected mask is *active*: the sidebar shows its adjustments and the bar its opacity. It is *edited* only while a shape tool is on the rail, which shows its guides or brush and the overlay; Adjust leaves the canvas to pan and zoom. Selecting a mask in the stack arms the tool of its shape; selecting the image or an effect returns to Adjust. **Enter**, or **Escape** with no drag in progress, leaves one level at a time: a shape tool returns to Adjust with the mask still selected, so its sliders stay at hand without guides over the image, and in Adjust the selection climbs to the parent mask, then to the image with its global controls. The shape's key or the mask's row enters editing again. Enter on a focused button stays its click. The bar over the image edits the active tool and the selected layer: the tool's options, then the layer's opacity, Overlay, and a radial mask's Feather or a child mask's operation. It never wraps: when the canvas is narrow it drops the slider bars, then moves the layer options and finally everything into a menu at its end. Dragging with a gradient tool draws a new mask above the selection; the tool stays active, and **Alt** while starting the drag subtracts the gradient from the selected mask instead. Choosing the Brush tool creates an empty brush mask above the selection at once, so adjustments made before the first stroke belong to it; leaving the tool while that mask has no strokes and nothing else changed removes it together with its history entry. A brush stroke paints into the selected brush mask, or starts a new brush mask. Creating inside a mask happens in the layer stack: each root mask row has Add and Subtract menus that choose a shape and nest the next mask inside it, and **Delete** removes the selected layer with any tool. The brush bar sets size, feather, flow, and paint or erase; **[** and **]** resize, holding **Alt** erases and shows Erase pressed, and **Escape** cancels the stroke. On a touch screen a second finger during a stroke cancels it and pinches instead, so painting and zooming never mix. The brush cursor previews the dab's feather and remains visible while Size or Feather is edited. Creating the mask and each stroke are separate undo steps.-**H** enters Healing and creates an empty Healing layer unless one is selected. Each stroke becomes a patch filled from a donor elsewhere in the image. Size sets the next stroke and never resizes an existing patch. Healing keeps its own next-stroke Feather, initially 10%, without changing the Brush tool. A selected patch exposes editable Feather and Opacity; feather softens the accumulated hard-stroke shape inward from its contour rather than expanding it or feathering every dab independently. A stroke whose brush does not reach the image is declined. Healing chooses a nearby donor automatically; **Alt-click** sets it manually, and Automatic source clears the override. Its boundary correction is bounded to avoid extreme color gains and remains independent of Feather and Opacity. A stroke's donor search keeps its history group open, so Size, Feather, or a handle drag started meanwhile joins that stroke's undo step. Each patch receives the visible result of every earlier patch in its layer. The sidebar numbers patches in replay order; drawing, selection, and row hover show their destination contour and first-point anchor. Dragging the destination anchor moves the shape while its source stays fixed. A completed patch also shows a quieter source contour whose anchor changes the same donor coordinates as the panel. **Escape** cancels painting or pending processing; Enter leaves after completion. Leaving an untouched new layer removes it.+**H** enters Healing and creates an empty Healing layer unless one is selected. Each stroke becomes a patch filled from a donor elsewhere in the image. Size sets the next stroke and never resizes an existing patch. Healing keeps its own next-stroke Feather, initially 10%, without changing the Brush tool. A selected patch exposes editable Feather and Opacity; feather softens the accumulated hard-stroke shape inward from its contour rather than expanding it or feathering every dab independently. A stroke whose brush does not reach the image is declined. Healing chooses a nearby donor automatically; **Alt-click** sets it manually, and Automatic source clears the override. Its boundary correction is bounded to avoid extreme color gains and remains independent of Feather and Opacity. A stroke's donor search keeps its history group open, so Size, Feather, or a handle drag started meanwhile joins that stroke's undo step. Each patch receives the visible result of every earlier patch in its layer. The sidebar numbers patches in replay order with each one's brush size and any lowered opacity; drawing, selection, and row hover show their destination contour and first-point anchor. Dragging the destination anchor moves the shape while its source stays fixed. A completed patch also shows a quieter source contour whose anchor moves its donor. **Escape** cancels painting or pending processing; Enter leaves after completion. Leaving an untouched new layer removes it.The red overlay shows a mask being edited that does not change the image yet: a gradient being drawn, or the selected mask while its adjustments and curve are default and its effects are off. Once the mask applies an effect, the image itself shows it, so painting continues without the tint. The Overlay button shows whether the overlay is visible; it and **O** show or hide the overlay for the selected mask in any tool, until another layer is selected. The tint follows the layer's opacity, which scales the mask's coverage. The curve's input histogram weighs pixels by that coverage, so it describes what the curve affects; it ignores opacity and stays available while the layer is hidden or at zero opacity. Selected masks stay editable: drag the center to move, guides to resize or rotate, and the radial inner handle or Feather slider to soften its edge. Shift constrains drawing; Escape cancels the gesture; Delete/Backspace removes the selected mask. Each gesture is one undo. A new mask shows a red overlay of its coverage until Enter leaves editing or its first adjustment; the overlay also shows while drawing or dragging a guide. Add/Subtract menus accept either gradient shape. **+** adds an effect, inside a selected top-level mask or above the selected sibling. Eye buttons toggle visibility; the inspector edits opacity. Drag a layer name to reorder (insertion line) or nest (highlighted row); the base stays locked and nesting is limited to two levels. Double-click a name to rename; the row menu also duplicates, deletes, reorders, or reparents. Image import still replaces the document; multiple image layers and additional blend modes are not implemented.diff --git a/src/app/controls.ts b/src/app/controls.tsindex 96fbfff..f3d9f69 100644--- a/src/app/controls.ts+++ b/src/app/controls.ts@@ -11,8 +11,7 @@ import {import { createCameraRawXmpLoader } from "@/app/loaders/camera-raw-xmp";import { createImageLoader } from "@/app/loaders/image";import { createLoaderRegistry } from "@/app/loaders/registry";-import { createSceneLoader } from "@/app/loaders/scene";-import { writeSceneFile } from "@/app/scene-file";+import { createSceneLoader, writeSceneFile } from "@/app/loaders/scene";import type {Adjustments,BrushStroke,diff --git a/src/app/editor/adjust/index.tsx b/src/app/editor/adjust/index.tsxindex 2d91e5b..c2f5526 100644--- a/src/app/editor/adjust/index.tsx+++ b/src/app/editor/adjust/index.tsx@@ -56,18 +56,6 @@ function LayerCurve({ id, toneCurve }: { id: string; toneCurve: ToneCurve }) {);}-/** The sidebar heading for each layer kind's controls; a new kind must name one. */-const titles: Record<Layer["kind"], string> = {- image: "Adjustments",- mask: "Adjustments",- exposure: "Adjustments",- details: "Adjustments",- vignette: "Adjustments",- "color-mixer": "Adjustments",- fill: "Adjustments",- heal: "Healing",-};-function SelectedControls({ layer }: { layer: Layer }) {const document = useDocument();switch (layer.kind) {@@ -129,7 +117,7 @@ export function AdjustPanel() {);return (<div {...gesture}>- <PanelHeader title={titles[target.kind]} />+ <PanelHeader title={target.kind === "image" ? "Image" : target.name} /><SelectedControls layer={target} /></div>);diff --git a/src/app/editor/empty.tsx b/src/app/editor/empty.tsxindex 5c98f64..558b756 100644--- a/src/app/editor/empty.tsx+++ b/src/app/editor/empty.tsx@@ -1,7 +1,7 @@import { useEffect, useMemo, useRef } from "react";import { type Gpu, target } from "vgpu";import { useGpu } from "vgpu-react";-import { sceneExtension } from "@/app/scene-file";+import { sceneExtension } from "@/app/loaders/scene";import type { Workspace } from "@/app/workspace";import { RendererProvider } from "@/components/editor/pipeline";import { DocumentProvider } from "@/components/editor/session";@@ -135,11 +135,7 @@ export function EmptyEditor({useEffect(() => () => document.dispose(), [document]);return (<DocumentProvider value={document}>- <RendererProvider- createRenderer={(rendererGpu, source) =>- createEditorRenderer(rendererGpu, source)- }- >+ <RendererProvider createRenderer={createEditorRenderer}><MaskToolProvider onCreate={() => {}}><EditorHeader file={state.file} /><div className="flex min-h-0 flex-1 flex-col md:flex-row">diff --git a/src/app/editor/export/index.tsx b/src/app/editor/export/index.tsxindex 588cbaf..a8cc055 100644--- a/src/app/editor/export/index.tsx+++ b/src/app/editor/export/index.tsx@@ -1,7 +1,7 @@import { cn } from "cn";import { type ReactNode, useMemo, useRef, useState } from "react";import { useGpu } from "vgpu-react";-import { writeSceneFile } from "@/app/scene-file";+import { writeSceneFile } from "@/app/loaders/scene";import { Image } from "@/components/editor/image";import { EditorPanel, PanelHeader } from "@/components/editor/panel";import { useDocument, useScene } from "@/components/editor/session";diff --git a/src/app/editor/sidebar.tsx b/src/app/editor/sidebar.tsxindex 5827014..46a727a 100644--- a/src/app/editor/sidebar.tsx+++ b/src/app/editor/sidebar.tsx@@ -8,7 +8,7 @@ import { addLayer } from "@/features/layers/edits";import { ImageHistogram } from "./histogram";import { createLayer } from "./layers";-/** Histogram above, the mode's controls in the middle, the layer stack below. */+/** Histogram above, the mode's controls in the middle, the layer stack below once there is a document. */export function EditorSidebar({children,inert,@@ -31,7 +31,7 @@ export function EditorSidebar({<EditorPanelinert={inert}header={<ImageHistogram />}- footer={<LayersControls onAdd={add} />}+ footer={!inert && <LayersControls onAdd={add} />}>{children}</EditorPanel>diff --git a/src/app/loaders/scene.ts b/src/app/loaders/scene.tsindex 2d121cc..30f655d 100644--- a/src/app/loaders/scene.ts+++ b/src/app/loaders/scene.ts@@ -1,9 +1,54 @@import type { Gpu } from "vgpu";-import { isSceneFile, openSceneFile } from "@/app/scene-file";+import { openScene, snapshotScene } from "@/app/scene-file";import type { Workspace } from "@/app/workspace";+import type { EditorDocument } from "@/core/document";+import type { ImageSource } from "@/core/image";import decode from "@/core/image/decode";+import { readZip, writeZip } from "@/lib/zip";import type { FileLoader } from "./registry";+export const sceneExtension = ".openlight";++/** Sources are stored, so only `scene.json` inflates; a scene with 7,000 stroke points is about 200 kB. */+const inflateLimit = 256 * 2 ** 20;++export function isSceneFile(file: File) {+ return file.name.toLowerCase().endsWith(sceneExtension);+}++/** The document as a ZIP archive: a deflated `scene.json` and each source's bytes at `sources/<id>`. */+export async function writeSceneFile(document: EditorDocument) {+ const { json, files } = snapshotScene(document);+ const archive = await writeZip([+ {+ name: "scene.json",+ data: new Blob([JSON.stringify(json)]),+ deflate: true,+ },+ ...[...files].map(([id, file]) => ({ name: `sources/${id}`, data: file })),+ ]);+ const [file] = files.values();+ const name = file.name.replace(/\.[^.]*$/, "") || "scene";+ return new File([archive], `${name}${sceneExtension}`);+}++export async function openSceneFile(+ file: Blob,+ decode: (file: File) => Promise<ImageSource>,+) {+ const entries = await readZip(file, inflateLimit);+ const json = entries.get("scene.json");+ if (!json) {+ throw Error("This file doesn't contain an OpenLight scene.");+ }+ const files = new Map(+ [...entries].flatMap(([name, data]) =>+ name.startsWith("sources/") ? [[name.slice(8), data] as const] : [],+ ),+ );+ return openScene(JSON.parse(await json.text()), files, decode);+}+export function createSceneLoader(gpu: Gpu, workspace: Workspace): FileLoader {return {kind: "document",diff --git a/src/app/scene-file.ts b/src/app/scene-file.tsindex f9ee63a..5f25bd8 100644--- a/src/app/scene-file.ts+++ b/src/app/scene-file.ts@@ -26,7 +26,6 @@ import { validateCurve } from "@/features/tone-curves/curve";import { validateVignette } from "@/features/vignette/edits";import { defaultVignette } from "@/features/vignette/model";import { validateWhiteBalance } from "@/features/white-balance/edits";-import { readZip, writeZip } from "@/lib/zip";/** Raised only when older files can no longer load as written; a parameter added later takes its default. */const version = 1;@@ -39,15 +38,6 @@ export type SceneJson = {scene: Scene;};-export const sceneExtension = ".openlight";--/** Sources are stored, so only `scene.json` inflates; a scene with 7,000 stroke points is about 200 kB. */-const inflateLimit = 256 * 2 ** 20;--export function isSceneFile(file: File) {- return file.name.toLowerCase().endsWith(sceneExtension);-}-/** The document's scene and the source files it references, read without rendering. */export function snapshotScene(document: EditorDocument) {const scene = document.scene.getState();@@ -62,22 +52,6 @@ export function snapshotScene(document: EditorDocument) {return { json, files: new Map([[source, file]]) };}-/** The document as a ZIP archive: a deflated `scene.json` and each source's bytes at `sources/<id>`. */-export async function writeSceneFile(document: EditorDocument) {- const { json, files } = snapshotScene(document);- const archive = await writeZip([- {- name: "scene.json",- data: new Blob([JSON.stringify(json)]),- deflate: true,- },- ...[...files].map(([id, file]) => ({ name: `sources/${id}`, data: file })),- ]);- const [file] = files.values();- const name = file.name.replace(/\.[^.]*$/, "") || "scene";- return new File([archive], `${name}${sceneExtension}`);-}-function readId(id: string, ids: Set<string>) {if (typeof id !== "string" || !id || ids.has(id)) {throw Error("Layer and patch IDs must be unique strings.");@@ -264,20 +238,3 @@ export async function openScene(throw error;}}--export async function openSceneFile(- file: Blob,- decode: (file: File) => Promise<ImageSource>,-) {- const entries = await readZip(file, inflateLimit);- const json = entries.get("scene.json");- if (!json) {- throw Error("This file doesn't contain an OpenLight scene.");- }- const files = new Map(- [...entries].flatMap(([name, data]) =>- name.startsWith("sources/") ? [[name.slice(8), data] as const] : [],- ),- );- return openScene(JSON.parse(await json.text()), files, decode);-}diff --git a/src/components/editor/session.tsx b/src/components/editor/session.tsxindex 8733e20..fb6ad14 100644--- a/src/components/editor/session.tsx+++ b/src/components/editor/session.tsx@@ -6,7 +6,7 @@ import {useState,} from "react";import { useStore } from "zustand";-import type { EditorDocument, Scene } from "@/core/document";+import { type EditorDocument, findLayer, type Scene } from "@/core/document";import { createCamera } from "@/hooks/use-pan-zoom";const Session = createContext<{@@ -29,6 +29,12 @@ export function useDocument() {export function useScene<T>(selector: (scene: Scene) => T) {return useStore(useDocument().scene, selector);}+/** The selected layer, following both the scene and the selection. */+export function useSelectedLayer() {+ const document = useDocument();+ const id = useStore(document.selection, (state) => state.layerId);+ return useStore(document.scene, (scene) => findLayer(scene.layers, id));+}/** Preserve document UI state while independent tools mount and unmount. */export function DocumentProvider({diff --git a/src/components/editor/tool-layer.ts b/src/components/editor/tool-layer.tsnew file mode 100644index 0000000..444ac26--- /dev/null+++ b/src/components/editor/tool-layer.ts@@ -0,0 +1,47 @@+import { useEffect } from "react";+import { findLayer, type Layer } from "@/core/document";+import { useDocument } from "./session";++/**+ * Keeps a tool on a layer it accepts. Opening without one, or with `fresh`, creates a layer that leaves+ * with the tool unless anything happened after its creation; selecting any other layer leaves the tool.+ * Returns a lookup of the selected layer at call time, for pointer handlers that run before a render.+ */+export function useToolLayer<L extends Layer>({+ accepts,+ create,+ leave,+ fresh = false,+}: {+ accepts: (layer: Layer) => layer is L;+ create: () => void;+ leave: () => void;+ fresh?: boolean;+}) {+ const document = useDocument();+ function selected() {+ const layer = findLayer(+ document.scene.getState().layers,+ document.selection.getState().layerId,+ );+ return layer && accepts(layer) ? layer : undefined;+ }+ useEffect(() => {+ const before = fresh || !selected() ? document.scene.getState() : undefined;+ if (before) {+ create();+ }+ const unsubscribe = document.selection.subscribe(() => {+ if (!selected()) {+ leave();+ }+ });+ return () => {+ unsubscribe();+ if (before) {+ document.history.drop(before);+ }+ };+ }, []);+ return selected;+}diff --git a/src/components/editor/viewport.tsx b/src/components/editor/viewport.tsxindex 5d4c4ca..2fdb3ab 100644--- a/src/components/editor/viewport.tsx+++ b/src/components/editor/viewport.tsx@@ -17,8 +17,10 @@ export function useViewport() {/** Zoom as Photoshop counts it: 100% shows one image pixel per device pixel. */function ZoomControl() {- const { scale, zoomBy, resetView } = useViewport();+ const { view, scale, zoomBy, zoomTo, resetView } = useViewport();const percent = Math.round(scale * devicePixelRatio * 100);+ // Fit toggles to 100%; any other zoom returns to fit.+ const fitted = view.zoom === 1;return (<div className="absolute right-3 bottom-3"><div className="flex items-center rounded-full bg-neutral-800/80 p-0.5 backdrop-blur-sm">@@ -34,9 +36,11 @@ function ZoomControl() {</Button><Buttonvariant="ghost"- title="Fit to view"+ title={fitted ? "Zoom to 100%" : "Fit to view"}className="min-w-14 rounded-full px-1 py-0.5 text-neutral-200 tabular-nums"- onClick={() => resetView()}+ onClick={() =>+ fitted ? zoomTo(1 / (scale * devicePixelRatio)) : resetView()+ }>{percent}%</Button>diff --git a/src/components/icons/heal.tsx b/src/components/icons/heal.tsxindex 418114a..eb6fbe9 100644--- a/src/components/icons/heal.tsx+++ b/src/components/icons/heal.tsx@@ -3,8 +3,16 @@ import { Icon, type IconProps } from "./icon";export function HealIcon(props: IconProps) {return (<Icon {...props}>- <path d="m7 21-4-4a2.8 2.8 0 0 1 0-4L12.5 3.5a2.8 2.8 0 0 1 4 0l4 4a2.8 2.8 0 0 1 0 4L11 21H7Z" />- <path d="m5 11 9 9M7 21h14" />+ <g transform="rotate(-45 12 12)">+ <rect x="2.5" y="8" width="19" height="8" rx="4" />+ <path d="M9 8v8M15 8v8" />+ <g fill="currentColor" stroke="none">+ <circle cx="11" cy="11" r="0.75" />+ <circle cx="13" cy="11" r="0.75" />+ <circle cx="11" cy="13" r="0.75" />+ <circle cx="13" cy="13" r="0.75" />+ </g>+ </g></Icon>);}diff --git a/src/core/document/tree.ts b/src/core/document/tree.tsindex 022f499..90c69d5 100644--- a/src/core/document/tree.ts+++ b/src/core/document/tree.ts@@ -1,28 +1,27 @@import type { EditorDocument } from "./index";import type { Layer, MaskLayer, ProcessingLayer, Scene } from "./scene";-export function walkLayers(layers: readonly Layer[]): Layer[] {- return layers.flatMap((layer) => [layer, ...walkLayers(layer.children)]);-}-type LayerLocation = {layer: Layer;siblings: readonly Layer[];parent?: Layer;};-export function locateLayer(+/** Every layer with its position, parents before their children. */+export function* walkLayers(layers: readonly Layer[],- id: string,parent?: Layer,-): LayerLocation | undefined {+): Generator<LayerLocation> {for (const layer of layers) {- if (layer.id === id) {- return { layer, siblings: layers, parent };- }- const child = locateLayer(layer.children, id, layer);- if (child) {- return child;+ yield { layer, siblings: layers, parent };+ yield* walkLayers(layer.children, layer);+ }+}++export function locateLayer(layers: readonly Layer[], id: string) {+ for (const location of walkLayers(layers)) {+ if (location.layer.id === id) {+ return location;}}return undefined;diff --git a/src/core/renderer/index.ts b/src/core/renderer/index.tsindex 12741f5..073d4d6 100644--- a/src/core/renderer/index.ts+++ b/src/core/renderer/index.ts@@ -1,5 +1,10 @@import type { Gpu, Target, Timer } from "vgpu";-import type { BrushStroke, Layer, MaskLayer, Scene } from "@/core/document";+import {+ type BrushStroke,+ type MaskLayer,+ type Scene,+ walkLayers,+} from "@/core/document";import type { ImageSource, WhiteBalance } from "@/core/image";import { createRenderGraph } from "./graph";import { createMaskRaster } from "./mask";@@ -106,16 +111,10 @@ export function createRenderer(const active = new Set<string>();const developed = raw?.render() ?? source;// A mask updates its rasters with those of the masks inside it, which only shape its coverage.- function prepare(layer: Layer, parent?: Layer) {+ for (const { layer, parent } of walkLayers(scene.layers)) {if (layer.kind === "mask" && parent?.kind !== "mask") {raster.update(layer, developed.size);}- for (const child of layer.children) {- prepare(child, layer);- }- }- for (const layer of scene.layers) {- prepare(layer);}const image =factor > 1 ? proxy.render(developed, factor, version) : input(developed);diff --git a/src/features/heal/controls.tsx b/src/features/heal/controls.tsxindex 794acaf..cbd6598 100644--- a/src/features/heal/controls.tsx+++ b/src/features/heal/controls.tsx@@ -4,9 +4,8 @@ import { HealIcon } from "@/components/icons/heal";import { Icon } from "@/components/icons/icon";import { Menu } from "@/components/ui/menu";import { PanelListItem } from "@/components/ui/panel-list";-import { ScrubInput } from "@/components/ui/scrub-input";import type { HealPatch } from "@/core/document";-import { deleteHealPatch, duplicateHealPatch, setHealSource } from "./edits";+import { deleteHealPatch, duplicateHealPatch } from "./edits";import { useHealing } from "./mode";import { patchThumbnailRegion } from "./model";@@ -68,41 +67,12 @@ function PatchActions({);}-function SourceFields({- layer,- patch,- limit,-}: {- layer: string;- patch: HealPatch;- limit: readonly [number, number];-}) {- const document = useDocument();- const { selectPatch } = useHealing();- const destination = patch.stroke.points[0];- return (- <div- className="flex shrink-0 items-center gap-1"- onPointerDownCapture={() => selectPatch(patch.id)}- >- {(["X", "Y"] as const).map((axis, index) => (- <ScrubInput- key={axis}- aria-label={`Source ${axis}`}- label={axis}- value={Math.round(destination[index] + patch.offset[index])}- min={0}- max={limit[index]}- variant="text"- onChange={(value) => {- const offset: [number, number] = [patch.offset[0], patch.offset[1]];- offset[index] = Math.round(value - destination[index]);- setHealSource(document, layer, patch.id, offset);- }}- />- ))}- </div>- );+/** The brush size, and the opacity once lowered; the donor is edited on the canvas. */+function patchSummary(patch: HealPatch) {+ const size = `${Math.round(patch.stroke.size)} px`;+ return patch.opacity < 1+ ? `${size} · ${Math.round(patch.opacity * 100)}%`+ : size;}/** Shows the ordered repair stack; selection is shared with the canvas and floating bar. */@@ -150,8 +120,10 @@ export function HealControls({fallback={<PendingThumbnail />}/><span className="min-w-0 flex-1 truncate">Patch {index + 1}</span>+ <span className="shrink-0 text-neutral-500 tabular-nums">+ {patchSummary(patch)}+ </span></button>- <SourceFields layer={id} patch={patch} limit={source.image.size} /><PatchActionslayer={id}patch={patch}diff --git a/src/features/heal/model.ts b/src/features/heal/model.tsindex e35fa90..84dffc9 100644--- a/src/features/heal/model.ts+++ b/src/features/heal/model.ts@@ -1,9 +1,14 @@-import type { BrushStroke, HealPatch, Scene } from "@/core/document";+import {+ type BrushStroke,+ findLayer,+ type HealPatch,+ type Scene,+} from "@/core/document";import { validateStroke } from "@/core/document/brush";import type { Point } from "@/core/image/frame";export function findHealPatch(scene: Scene, layerId: string, patchId: string) {- const layer = scene.layers.find((layer) => layer.id === layerId);+ const layer = findLayer(scene.layers, layerId);if (layer?.kind !== "heal") return;return layer.patches.find((patch) => patch.id === patchId);}diff --git a/src/features/heal/options.tsx b/src/features/heal/options.tsxindex e7b1ccb..864966d 100644--- a/src/features/heal/options.tsx+++ b/src/features/heal/options.tsx@@ -1,8 +1,7 @@import { useBrushTool } from "@/components/editor/brush-tool";-import { useDocument, useScene } from "@/components/editor/session";+import { useDocument, useSelectedLayer } from "@/components/editor/session";import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";import { Slider } from "@/components/ui/slider";-import { findLayer } from "@/core/document";import { setHealPatch } from "./edits";import { useHealing } from "./mode";@@ -10,9 +9,7 @@ export function HealOptions() {const document = useDocument();const { settings, maxSize, setPreview, update } = useBrushTool();const { feather: nextFeather, setFeather, selectedPatch } = useHealing();- const layer = useScene((scene) =>- findLayer(scene.layers, document.selection.getState().layerId),- );+ const layer = useSelectedLayer();const selected =layer?.kind === "heal"? layer.patches.find((patch) => patch.id === selectedPatch)diff --git a/src/features/heal/overlay.tsx b/src/features/heal/overlay.tsxindex cce6a5a..79bf4ec 100644--- a/src/features/heal/overlay.tsx+++ b/src/features/heal/overlay.tsx@@ -3,8 +3,9 @@ import { useGpu } from "vgpu-react";import { BrushCanvas } from "@/components/editor/brush-canvas";import { useDocumentMapping } from "@/components/editor/mapping";import { useRenderer } from "@/components/editor/pipeline";-import { useDocument, useScene } from "@/components/editor/session";-import { findLayer } from "@/core/document";+import { useDocument, useSelectedLayer } from "@/components/editor/session";+import { useToolLayer } from "@/components/editor/tool-layer";+import type { Layer } from "@/core/document";import type { Point } from "@/core/image/frame";import { addHealPatch, extendHealPatch, setHealSource } from "./edits";import { useHealing } from "./mode";@@ -12,12 +13,16 @@ import { dabTouchesImage, findHealPatch } from "./model";import { HealPatchHitTarget, HealPatchOutline } from "./outline";import { createHealSearch } from "./source";+function isHealLayer(layer: Layer): layer is Extract<Layer, { kind: "heal" }> {+ return layer.kind === "heal";+}+/** Paints ordinary brush strokes; only the donor search and patch edits belong to Heal. */export function HealOverlay({onCreate,onDone,}: {- onCreate: () => string;+ onCreate: () => void;onDone: () => void;}) {const document = useDocument();@@ -29,10 +34,13 @@ export function HealOverlay({const [source, setSource] = useState<Point>();const [drawingPatch, setDrawingPatch] = useState<string>();const [resolvingSource, setResolvingSource] = useState<string>();- const layer = useScene((scene) =>- findLayer(scene.layers, document.selection.getState().layerId),- );- const healLayer = layer?.kind === "heal" ? layer : undefined;+ const selectedHealLayer = useToolLayer({+ accepts: isHealLayer,+ create: onCreate,+ leave: onDone,+ });+ const layer = useSelectedLayer();+ const healLayer = layer && isHealLayer(layer) ? layer : undefined;const patches = healLayer?.patches ?? [];const hovered = patches.some((patch) => patch.id === hoveredPatch)? hoveredPatch@@ -41,32 +49,6 @@ export function HealOverlay({const pending = useRef<{ layer: string; patch: string; automatic: boolean } | undefined>(undefined);- useEffect(() => {- const layer = findLayer(- document.scene.getState().layers,- document.selection.getState().layerId,- );- const before =- layer?.kind === "heal" ? undefined : document.scene.getState();- if (before) {- onCreate();- }- const unsubscribe = document.selection.subscribe(() => {- const layer = findLayer(- document.scene.getState().layers,- document.selection.getState().layerId,- );- if (layer?.kind !== "heal") {- onDone();- }- });- return () => {- unsubscribe();- if (before) {- document.history.drop(before);- }- };- }, []);useEffect(() => () => search.dispose(), [search]);async function complete(signal: AbortSignal) {const current = pending.current;@@ -101,8 +83,8 @@ export function HealOverlay({erase={false}feather={feather}onStart={(stroke) => {- const layer = healLayer;- if (!layer) throw Error("Select a Healing layer.");+ const layer = selectedHealLayer();+ if (!layer) return false;const [x, y] = stroke.points[0];const size = document.resources.get(document.scene.getState().layers[0].source,diff --git a/src/features/layers/brush-overlay.tsx b/src/features/layers/brush-overlay.tsxindex 6be1666..2f00755 100644--- a/src/features/layers/brush-overlay.tsx+++ b/src/features/layers/brush-overlay.tsx@@ -1,55 +1,36 @@-import { useEffect, useRef } from "react";+import { useRef } from "react";import { BrushCanvas } from "@/components/editor/brush-canvas";import { useBrushTool } from "@/components/editor/brush-tool";import { useDocument } from "@/components/editor/session";-import { findLayer } from "@/core/document";+import { useToolLayer } from "@/components/editor/tool-layer";+import type { Layer, MaskLayer } from "@/core/document";import { extendStroke, paintStroke } from "./edits";import { useMaskTool } from "./mask-tool";+function isBrushMask(layer: Layer): layer is MaskLayer {+ return layer.kind === "mask" && layer.mask.kind === "brush";+}+/** Keeps a brush mask selected; an untouched new mask disappears on leaving. */export function BrushOverlay() {const document = useDocument();const tool = useMaskTool();const brush = useBrushTool();const painting = useRef<string | undefined>(undefined);- function selectedBrush() {- const layer = findLayer(- document.scene.getState().layers,- document.selection.getState().layerId,- );- return layer?.kind === "mask" && layer.mask.kind === "brush"- ? layer.id- : undefined;- }- useEffect(() => {+ const selectedBrush = useToolLayer({+ accepts: isBrushMask,+ create: () => tool.create({ kind: "brush", strokes: [] }),+ leave: () => tool.edit(),// A chosen nesting starts a new brush even over a selected one.- const before =- tool.pending?.shape === "brush" || !selectedBrush()- ? document.scene.getState()- : undefined;- if (before) {- tool.create({ kind: "brush", strokes: [] });- }- const unsubscribe = document.selection.subscribe(() => {- if (!selectedBrush()) {- tool.edit();- }- });- return () => {- unsubscribe();- // The new mask leaves with the tool unless anything happened after its creation.- if (before) {- document.history.drop(before);- }- };- }, []);+ fresh: tool.pending?.shape === "brush",+ });return (<BrushCanvaslabel="Brush canvas"hint="Drag to paint · Alt erases · [ ] resize · Enter when done"erase={brush.erase}onStart={(stroke) => {- const id = selectedBrush();+ const id = selectedBrush()?.id;if (!id) return false;painting.current = id;paintStroke(document, id, stroke);diff --git a/src/features/layers/controls.tsx b/src/features/layers/controls.tsxindex 2b35378..23c4f93 100644--- a/src/features/layers/controls.tsx+++ b/src/features/layers/controls.tsx@@ -1,10 +1,4 @@-import {- type ComponentProps,- memo,- useCallback,- useEffect,- useState,-} from "react";+import { memo, useCallback, useEffect, useState } from "react";import { useStore } from "zustand";import { PanelHeader } from "@/components/editor/panel";import { useDocument, useScene } from "@/components/editor/session";@@ -27,6 +21,7 @@ import {import { useShortcuts } from "@/hooks/use-shortcuts";import { layerDrop } from "./drop";import { deleteLayer, moveLayer, setLayer } from "./edits";+import { LayerName } from "./layer-name";import { useMaskTool } from "./mask-tool";import { LayerActions, MaskNesting } from "./menu";import { ImageThumbnail, MaskThumbnail } from "./thumbnails";@@ -93,63 +88,6 @@ function LayerThumbnail({ layer }: { layer: Layer }) {);}-function LayerName({- layer,- onSelect,- dragHandle,-}: {- layer: Layer;- onSelect: () => void;- dragHandle: ComponentProps<"button">;-}) {- const document = useDocument();- const [renaming, setRenaming] = useState(false);- if (renaming) {- return (- <input- aria-label="Layer name"- ref={(input) => input?.select()}- defaultValue={layer.name}- className="min-w-0 flex-1 rounded border border-neutral-500 bg-neutral-900 px-1 text-neutral-100 outline-none"- onKeyDown={(event) => {- if (event.key === "Enter") {- event.currentTarget.blur();- }- if (event.key === "Escape") {- event.currentTarget.value = layer.name;- event.currentTarget.blur();- }- }}- onBlur={(event) => {- const name = event.currentTarget.value.trim();- if (name && name !== layer.name) {- setLayer(document, layer.id, { name });- }- setRenaming(false);- }}- />- );- }- function rename() {- if (layer.kind !== "image") {- setRenaming(true);- }- }- return (- <button- {...dragHandle}- type="button"- aria-label={layer.name}- title={layer.name}- onClick={onSelect}- onDoubleClick={rename}- className="min-w-0 flex-1 self-stretch truncate text-left touch-manipulation cursor-grab active:cursor-grabbing"- >- {layer.name}- </button>- );-}-/** Rows subscribe to selection themselves, so unchanged branches skip when a sibling edits. */const LayerRow = memo(function LayerRow({layer,diff --git a/src/features/layers/edits.ts b/src/features/layers/edits.tsindex d0b605e..9659496 100644--- a/src/features/layers/edits.ts+++ b/src/features/layers/edits.ts@@ -120,12 +120,14 @@ export function addLayer(placement?: LayerPlacement,) {const scene = document.scene.getState();- const existing = new Set(walkLayers(scene.layers).map((item) => item.id));+ const existing = new Set(+ Array.from(walkLayers(scene.layers), (item) => item.layer.id),+ );for (const item of walkLayers([layer])) {- if (existing.has(item.id)) {+ if (existing.has(item.layer.id)) {throw Error("Layer IDs must be unique.");}- existing.add(item.id);+ existing.add(item.layer.id);}const { parentId, index } = placementIndex(scene, placement);const next = changeChildren(scene, parentId, (layers) =>diff --git a/src/features/layers/layer-name.tsx b/src/features/layers/layer-name.tsxnew file mode 100644index 0000000..b5803e8--- /dev/null+++ b/src/features/layers/layer-name.tsx@@ -0,0 +1,62 @@+import { type ComponentProps, useState } from "react";+import { useDocument } from "@/components/editor/session";+import type { Layer } from "@/core/document";+import { setLayer } from "./edits";++/** The row's name selects and drags the layer; a double-click renames any layer but the image. */+export function LayerName({+ layer,+ onSelect,+ dragHandle,+}: {+ layer: Layer;+ onSelect: () => void;+ dragHandle: ComponentProps<"button">;+}) {+ const document = useDocument();+ const [renaming, setRenaming] = useState(false);+ if (renaming) {+ return (+ <input+ aria-label="Layer name"+ ref={(input) => input?.select()}+ defaultValue={layer.name}+ className="min-w-0 flex-1 rounded border border-neutral-500 bg-neutral-900 px-1 text-neutral-100 outline-none"+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.currentTarget.blur();+ }+ if (event.key === "Escape") {+ event.currentTarget.value = layer.name;+ event.currentTarget.blur();+ }+ }}+ onBlur={(event) => {+ const name = event.currentTarget.value.trim();+ if (name && name !== layer.name) {+ setLayer(document, layer.id, { name });+ }+ setRenaming(false);+ }}+ />+ );+ }+ function rename() {+ if (layer.kind !== "image") {+ setRenaming(true);+ }+ }+ return (+ <button+ {...dragHandle}+ type="button"+ aria-label={layer.name}+ title={layer.name}+ onClick={onSelect}+ onDoubleClick={rename}+ className="min-w-0 flex-1 self-stretch truncate text-left touch-manipulation cursor-grab active:cursor-grabbing"+ >+ {layer.name}+ </button>+ );+}diff --git a/src/features/layers/mask-options.tsx b/src/features/layers/mask-options.tsxnew file mode 100644index 0000000..b4ce175--- /dev/null+++ b/src/features/layers/mask-options.tsx@@ -0,0 +1,80 @@+import { useStore } from "zustand";+import { useDocument, useScene } from "@/components/editor/session";+import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";+import { Select } from "@/components/ui/select";+import { Slider } from "@/components/ui/slider";+import { locateLayer, type MaskLayer } from "@/core/document";+import { useShortcuts } from "@/hooks/use-shortcuts";+import { setLayerMask, setMaskOperation } from "./edits";+import { useMaskTool } from "./mask-tool";++/** The selected mask's options in the canvas bar: its overlay, a radial feather, and a child's operation. */+export function MaskOptions({ layer }: { layer: MaskLayer }) {+ const document = useDocument();+ const tool = useMaskTool();+ const density = useBarDensity();+ const parent = useScene(+ (scene) => locateLayer(scene.layers, layer.id)?.parent,+ );+ // The button reports what the canvas shows, whether by choice or by default.+ const shown = useStore(+ document.preview,+ (preview) => preview.maskOverlay !== undefined,+ );+ const toggleOverlay = () => tool.showOverlay(!shown);+ useShortcuts({ o: toggleOverlay });+ return (+ <>+ {density !== "menu" && (+ <hr+ aria-orientation="vertical"+ className="h-4 w-px border-0 bg-white/15"+ />+ )}+ <button+ type="button"+ aria-pressed={shown}+ title="Show the mask overlay (O)"+ onClick={toggleOverlay}+ className="h-7 rounded-full px-2.5 text-neutral-400 hover:bg-white/10 hover:text-neutral-100 aria-pressed:bg-white/15 aria-pressed:text-neutral-100 pointer-coarse:h-9"+ >+ Overlay+ </button>+ {layer.mask.kind === "radial" && (+ <Slider+ label="Feather"+ value={layer.mask.feather * 100}+ min={0}+ max={100}+ defaultValue={50}+ unit="%"+ valueWidth={3}+ variant={barSlider(density)}+ onChange={(value) => {+ if (layer.mask.kind === "radial") {+ setLayerMask(document, layer.id, {+ ...layer.mask,+ feather: value / 100,+ });+ }+ }}+ />+ )}+ {parent?.kind === "mask" && (+ <Select+ variant="pill"+ aria-label="Mask operation"+ title="Combine with the parent mask"+ value={layer.operation}+ options={[+ { value: "add", label: "Add" },+ { value: "subtract", label: "Subtract" },+ ]}+ onChange={(operation) =>+ setMaskOperation(document, layer.id, operation)+ }+ />+ )}+ </>+ );+}diff --git a/src/features/layers/toolbar.tsx b/src/features/layers/toolbar.tsxindex 22e4e21..ed76be9 100644--- a/src/features/layers/toolbar.tsx+++ b/src/features/layers/toolbar.tsx@@ -8,88 +8,11 @@ import {} from "@/components/editor/toolbar-density";import { Icon } from "@/components/icons/icon";import { Menu } from "@/components/ui/menu";-import { Select } from "@/components/ui/select";import { Slider } from "@/components/ui/slider";-import {- findLayer,- locateLayer,- type MaskLayer,- type ProcessingLayer,-} from "@/core/document";+import { findLayer, type ProcessingLayer } from "@/core/document";import { useEditGesture } from "@/hooks/use-edit-gesture";-import { useShortcuts } from "@/hooks/use-shortcuts";-import { setLayer, setLayerMask, setMaskOperation } from "./edits";-import { useMaskTool } from "./mask-tool";--function MaskOptions({ layer }: { layer: MaskLayer }) {- const document = useDocument();- const tool = useMaskTool();- const density = useBarDensity();- const parent = useScene(- (scene) => locateLayer(scene.layers, layer.id)?.parent,- );- // The button reports what the canvas shows, whether by choice or by default.- const shown = useStore(- document.preview,- (preview) => preview.maskOverlay !== undefined,- );- const toggleOverlay = () => tool.showOverlay(!shown);- useShortcuts({ o: toggleOverlay });- return (- <>- {density !== "menu" && (- <hr- aria-orientation="vertical"- className="h-4 w-px border-0 bg-white/15"- />- )}- <button- type="button"- aria-pressed={shown}- title="Show the mask overlay (O)"- onClick={toggleOverlay}- className="h-7 rounded-full px-2.5 text-neutral-400 hover:bg-white/10 hover:text-neutral-100 aria-pressed:bg-white/15 aria-pressed:text-neutral-100 pointer-coarse:h-9"- >- Overlay- </button>- {layer.mask.kind === "radial" && (- <Slider- label="Feather"- value={layer.mask.feather * 100}- min={0}- max={100}- defaultValue={50}- unit="%"- valueWidth={3}- variant={barSlider(density)}- onChange={(value) => {- if (layer.mask.kind === "radial") {- setLayerMask(document, layer.id, {- ...layer.mask,- feather: value / 100,- });- }- }}- />- )}- {parent?.kind === "mask" && (- <Select- variant="pill"- aria-label="Mask operation"- title="Combine with the parent mask"- value={layer.operation}- options={[- { value: "add", label: "Add" },- { value: "subtract", label: "Subtract" },- ]}- onChange={(operation) =>- setMaskOperation(document, layer.id, operation)- }- />- )}- </>- );-}+import { setLayer } from "./edits";+import { MaskOptions } from "./mask-options";function LayerOptions({ layer }: { layer: ProcessingLayer }) {const document = useDocument();diff --git a/src/hooks/use-pan-zoom.ts b/src/hooks/use-pan-zoom.tsindex 99e063c..234e37d 100644--- a/src/hooks/use-pan-zoom.ts+++ b/src/hooks/use-pan-zoom.ts@@ -2,6 +2,7 @@ import {type PointerEvent,useCallback,useEffect,+ useEffectEvent,useLayoutEffect,useRef,useState,@@ -148,6 +149,31 @@ export function usePanZoom(useLayoutEffect(() => update((view) => view), [update, viewport]);+ const wheel = useEffectEvent((event: WheelEvent) => {+ event.preventDefault();+ const element = ref.current;+ if (!element) {+ return;+ }+ const { left, top, width, height } = element.getBoundingClientRect();+ const focal: Point = [+ event.clientX - left - width / 2,+ event.clientY - top - height / 2,+ ];+ update((view) => {+ if (event.ctrlKey || event.metaKey) {+ return zoomAt(+ view,+ focal,+ view.zoom * Math.exp(-event.deltaY / 100),+ constrain ? 1 : fitZoom.current * 0.1,+ );+ }+ return pan(view, -event.deltaX, -event.deltaY);+ });+ });++ // One listener and observer per element; the wheel handler reads the latest content and bounds.useLayoutEffect(() => {const element = ref.current;if (!element) {@@ -159,31 +185,16 @@ export function usePanZoom(measure();const observer = new ResizeObserver(measure);observer.observe(element);- const wheel = (event: WheelEvent) => {- event.preventDefault();- const { left, top, width, height } = element.getBoundingClientRect();- const focal: Point = [- event.clientX - left - width / 2,- event.clientY - top - height / 2,- ];- update((view) => {- if (event.ctrlKey || event.metaKey) {- return zoomAt(- view,- focal,- view.zoom * Math.exp(-event.deltaY / 100),- constrain ? 1 : fitZoom.current * 0.1,- );- }- return pan(view, -event.deltaX, -event.deltaY);- });- };- element.addEventListener("wheel", wheel, { passive: false });+ const controller = new AbortController();+ element.addEventListener("wheel", wheel, {+ passive: false,+ signal: controller.signal,+ });return () => {observer.disconnect();- element.removeEventListener("wheel", wheel);+ controller.abort();};- }, [update, constrain]);+ }, []);const release = (event: PointerEvent<HTMLElement>) =>pointers.current.delete(event.pointerId);@@ -200,6 +211,9 @@ export function usePanZoom(constrain ? 1 : fitZoom.current * 0.1,),);+ /** An exact zoom may go below fit, as 100% does for a small image on a dense display. */+ const zoomTo = (zoom: number) =>+ update((view) => zoomAt(view, [0, 0], zoom, zoom));function track(pointerId: number, position: Point, element: Element) {if (pointers.current.size === 0) {boundedDrag.current = constrain && !panMode;@@ -272,6 +286,7 @@ export function usePanZoom(handlers,resetView,zoomBy,+ zoomTo,panMode,scale: fitScale(content, inset(viewport, padding)) * view.zoom,};diff --git a/tests/brush.e2e.ts b/tests/brush.e2e.tsindex 19112f4..7d897ab 100644--- a/tests/brush.e2e.ts+++ b/tests/brush.e2e.ts@@ -50,7 +50,7 @@ test("paint a brush mask, adjust it in the sidebar, erase, and undo", async ({options.getByRole("textbox", { name: "Size", exact: true }),).toBeVisible();await expect(- page.getByRole("heading", { name: "Adjustments", exact: true }),+ page.getByRole("heading", { name: "Brush", exact: true }),).toBeVisible();const bounds = await box(canvas);const scale = Math.min(bounds.width / 1200, bounds.height / 800, 2);@@ -302,7 +302,7 @@ test("a second finger during a touch stroke cancels it and pinches instead", asyawait page.getByRole("tab", { name: "Brush", exact: true }).click();const canvas = page.getByLabel("Brush canvas", { exact: true });await expect(canvas).toBeVisible();- const zoom = page.locator('button[title="Fit to view"]');+ const zoom = page.getByRole("button", { name: /^\d+%$/ });const before = await zoom.textContent();const bounds = await box(canvas);const [cx, cy] = [diff --git a/tests/editing.e2e.ts b/tests/editing.e2e.tsindex e891604..c6ba1af 100644--- a/tests/editing.e2e.ts+++ b/tests/editing.e2e.ts@@ -37,7 +37,8 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportawait expect(page.getByRole("button", { name: "choose a file" }),).toBeVisible();- await expect(page.getByRole("heading", { name: "Layers" })).toBeVisible();+ // The start screen has no layer stack until a document opens.+ await expect(page.getByRole("heading", { name: "Layers" })).toHaveCount(0);await expect(page.getByRole("tab", { name: "Adjust" })).toBeDisabled();await page.locator('input[type="file"]')@@ -60,7 +61,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportawait test.step("image adjustments share a single section", async () => {await expect(- page.getByRole("heading", { name: "Adjustments", exact: true }),+ page.getByRole("heading", { name: "Image", exact: true }),).toBeVisible();await expect(page.getByRole("slider", { name: "Clarity", exact: true }),@@ -499,7 +500,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportawait page.keyboard.press("ArrowLeft");await expect(selected).toHaveAccessibleName("Radial gradient");await expect(- page.getByRole("heading", { name: "Adjustments", exact: true }),+ page.getByRole("heading", { name: "Image", exact: true }),).toBeVisible();await page.keyboard.press("ArrowLeft");await page.keyboard.press("ArrowLeft");diff --git a/tests/heal.e2e.ts b/tests/heal.e2e.tsindex dbce56e..3a8401b 100644--- a/tests/heal.e2e.ts+++ b/tests/heal.e2e.ts@@ -205,14 +205,8 @@ test("Healing paints patches, edits them, and undoes", async ({ page }) => {if (layer?.kind !== "heal") throw Error("Healing layer missing");const patch = layer.patches.at(-1);if (!patch) throw Error("Healing patch missing");- return {- id: patch.id,- y: Math.round(patch.stroke.points[0][1] + patch.offset[1]),- };+ return { id: patch.id };});- await expect(- page.getByRole("textbox", { name: "Source Y", exact: true }),- ).toHaveValue(`${manual.y}`);expect((await readImage(page, undefined, [[350, 200]])).samples?.[0]).toEqual([128, 128, 128, 255],);@@ -246,10 +240,19 @@ test("Healing paints patches, edits them, and undoes", async ({ page }) => {return healing?.kind === "heal" ? healing.patches.length : 0;}),).toBe(2);- const sourceX = firstPatch- .locator("..")- .getByRole("textbox", { name: "Source X", exact: true });- const beforeDrag = Number(await sourceX.inputValue());+ const sourceX = () =>+ page.evaluate((patchId) => {+ const healing = window.openlight+ .getState()+ .scene?.layers.find((item) => item.kind === "heal");+ const patch =+ healing?.kind === "heal"+ ? healing.patches.find((item) => item.id === patchId)+ : undefined;+ if (!patch) throw Error("Healing patch missing");+ return Math.round(patch.stroke.points[0][0] + patch.offset[0]);+ }, manual.id);+ const beforeDrag = await sourceX();const handle = canvas.locator('[data-heal-source-handle="true"]');const handleBounds = await handle.boundingBox();if (!handleBounds) throw Error("Healing source handle is unavailable");@@ -267,10 +270,8 @@ test("Healing paints patches, edits them, and undoes", async ({ page }) => {handleBounds.y + handleBounds.height / 2,);await page.mouse.up();- await expect- .poll(async () => Number(await sourceX.inputValue()))- .not.toBe(beforeDrag);- const fixedSource = Number(await sourceX.inputValue());+ await expect.poll(sourceX).not.toBe(beforeDrag);+ const fixedSource = await sourceX();const beforeDestination = await page.evaluate((patchId) => {const healing = window.openlight.getState()@@ -308,7 +309,7 @@ test("Healing paints patches, edits them, and undoes", async ({ page }) => {}, manual.id),).not.toBe(beforeDestination);- await expect(sourceX).toHaveValue(`${fixedSource}`);+ expect(await sourceX()).toBe(fixedSource);await feather.fill("60");await feather.press("Enter");const opacity = page.getByRole("textbox", {@@ -350,3 +351,64 @@ test("Healing paints patches, edits them, and undoes", async ({ page }) => {page.getByRole("textbox", { name: "Feather", exact: true }),).toHaveValue("50");});++test("Healing takes the first stroke after H and finds donors inside a mask", async ({+ page,+}) => {+ await page.goto("/");+ await page+ .locator('input[type="file"]')+ .setInputFiles("tests/fixtures/photo.svg");+ await expect(+ page.getByRole("textbox", { name: "Exposure", exact: true }),+ ).toHaveValue("0.00");+ const canvas = page.getByRole("region", { name: "Image canvas" });+ const bounds = await box(canvas);+ const spot = [bounds.x + bounds.width * 0.3, bounds.y + bounds.height * 0.4];+ async function healedPatches() {+ await expect+ .poll(() =>+ page.evaluate(() => {+ const { history } = window.openlight.getState();+ return "editing" in history && history.editing;+ }),+ )+ .toBe(false);+ return page.evaluate(() => {+ const selected = window.openlight.getState().selectedLayerId;+ const layers = window.openlight.getState().scene?.layers ?? [];+ const layer = layers+ .flatMap((layer) => [layer, ...layer.children])+ .find((layer) => layer.id === selected);+ return layer?.kind === "heal" ? layer.patches : [];+ });+ }++ await page.keyboard.press("h");+ await page.mouse.click(spot[0], spot[1]);+ expect(await healedPatches()).toHaveLength(1);++ await page.keyboard.press("Enter");+ const nested = await page.evaluate(() => {+ const api = window.openlight;+ const mask = api.addLayer("mask");+ api.setLayerMask(mask, {+ kind: "radial",+ center: [600, 400],+ radius: [2000, 2000],+ angle: 0,+ feather: 0,+ });+ const heal = api.addLayer("heal", { inside: mask });+ api.selectLayer(heal);+ return heal;+ });+ await page.keyboard.press("h");+ await page.mouse.click(spot[0], spot[1]);+ const patches = await healedPatches();+ expect(+ await page.evaluate(() => window.openlight.getState().selectedLayerId),+ ).toBe(nested);+ expect(patches).toHaveLength(1);+ expect(patches[0].offset).not.toEqual([0, 0]);+});diff --git a/tests/layers.e2e.ts b/tests/layers.e2e.tsindex e8a0de2..df866d3 100644--- a/tests/layers.e2e.ts+++ b/tests/layers.e2e.ts@@ -65,7 +65,7 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({).toHaveValue("0.00");await test.step("Details is an optional effect, separate from image adjustments", async () => {await expect(- page.getByRole("heading", { name: "Adjustments", exact: true }),+ page.getByRole("heading", { name: "Image", exact: true }),).toBeVisible();await expect(page.getByRole("textbox", { name: "Clarity", exact: true }),@@ -363,7 +363,7 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({).toBeVisible();const panel = page.getByRole("region", { name: "Editor controls" });await expect(- panel.getByRole("heading", { name: "Adjustments", exact: true }),+ panel.getByRole("heading", { name: "Radial Gradient", exact: true }),).toBeVisible();await expect(panel.getByRole("textbox", { name: "Feather", exact: true }),@@ -416,11 +416,17 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({.first().click();await page.getByRole("button", { name: "Zoom in", exact: true }).click();- const zoom = page.getByTitle("Fit to view");+ const zoom = page.getByRole("button", { name: /^\d+%$/ });const percent = await zoom.innerText();await page.getByLabel("Move gradient", { exact: true }).dblclick();await expect(zoom).toHaveText(percent);await zoom.click();+ // At fit the percentage zooms to one image pixel per device pixel, then fits again.+ await expect(zoom).toHaveAttribute("title", "Zoom to 100%");+ await zoom.click();+ await expect(zoom).toHaveText("100%");+ await zoom.click();+ await expect(zoom).toHaveAttribute("title", "Zoom to 100%");await page.setViewportSize({ width: 390, height: 844 });await page.getByRole("button", { name: "photo.svg", exact: true }).click();await page.keyboard.press("r");diff --git a/tests/layers.test.ts b/tests/layers.test.tsindex ec46861..27fb448 100644--- a/tests/layers.test.ts+++ b/tests/layers.test.ts@@ -124,8 +124,9 @@ test("nested layers compose in order, move atomically, and duplicate with indepe"exposure","vignette",]);- const ids = walkLayers(document.scene.getState().layers).map(- (layer) => layer.id,+ const ids = Array.from(+ walkLayers(document.scene.getState().layers),+ ({ layer }) => layer.id,);expect(new Set(ids).size).toBe(ids.length);moveLayer(document, exposure, 1);@@ -180,7 +181,14 @@ test("nested layers compose in order, move atomically, and duplicate with indepedocument.history.undo();expect(document.scene.getState()).toBe(unchanged);document.selectLayer(exposure);+ await renderer.update(document.scene.getState());+ const retained = renderer.inspect().effects;deleteLayer(document, mask);+ // A deleted layer's passes, and those of its children, leave with it; its duplicate keeps its own.+ await renderer.update(document.scene.getState());+ const { effects, passes } = renderer.inspect();+ expect(effects).toBeLessThan(retained);+ expect(effects).toBe(passes.length);expect(document.selection.getState().layerId).toBe("base");expect(findLayer(document.scene.getState().layers, exposure),diff --git a/tests/scene-file.test.ts b/tests/scene-file.test.tsindex 834203e..3342ec4 100644--- a/tests/scene-file.test.ts+++ b/tests/scene-file.test.ts@@ -2,7 +2,7 @@ import { expect, test } from "bun:test";import { init, target } from "vgpu/mock";import { createControls } from "@/app/controls";import { createImageLayer } from "@/app/editor/layers";-import { openSceneFile } from "@/app/scene-file";+import { openSceneFile } from "@/app/loaders/scene";import { createWorkspace } from "@/app/workspace";import { createDocument, createResources } from "@/core/document";import { createImageSource, type WhiteBalance } from "@/core/image";