Skip to content

Free open-source image editor for the browser

Land zod validation, tech-debt cleanup, and the Base UI design system (#44)

Rodrigo Belfiorefc2f45e9dcba
diff --git a/API.md b/API.md
index e1491c3..c7c1571 100644
--- a/API.md
+++ b/API.md
@@ -92,11 +92,7 @@ A linear gradient has full coverage at `start`, zero at `end`; its points must b
A 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 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 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.
+Editor behavior for the rail, canvas bar, overlays, and Healing is described in [DESIGN.md](DESIGN.md#editor-tools).
## History
@@ -162,7 +158,7 @@ The image renders at the document dimensions and downsamples to `longEdge` with
`scene` is the `getState()` scene; each image layer's `source` names an entry in `sources`. Opening the file with `loadScene`, `openFile`, a drop, or the file picker decodes the stored source again and restores the frame and every layer as a new document with empty history. Preview settings and history are not saved.
-Opening validates every value as the matching command does, and a file that fails leaves the workspace in its error state. A parameter missing from `adjustments`, `details`, `vignette`, `fill`, or `colorMixer` takes its default, so older files still open when a group gains a parameter; a RAW image without a white balance uses its As Shot value. `version` increases only when older files can no longer open as written; a newer version is rejected.
+Opening validates every value as the matching command does, and a file that fails leaves the workspace in its error state with a message naming the first invalid field. Fields OpenLight does not know are dropped. A parameter missing from `adjustments`, `details`, `vignette`, `fill`, or `colorMixer` takes its default, so older files still open when a group gains a parameter; a RAW image without a white balance uses its As Shot value. `version` increases only when older files can no longer open as written; a newer version is rejected.
## Drafts
diff --git a/DESIGN.md b/DESIGN.md
index 9300eef..0fbe994 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -1,13 +1,35 @@
# Interface design system
-OpenLight uses a small set of shared UI primitives so the editor reads as one application across tools and panels.
+OpenLight uses a small set of shared UI primitives so the editor reads as one application across tools and panels. They live in `src/components/ui`; floating parts are built on [Base UI](https://base-ui.com), which owns positioning, focus, dismissal, keyboard navigation, and ARIA.
+
+| Component | Use |
+| --- | --- |
+| `Button`, `IconButton` | Actions. `IconButton` is a ghost icon button whose `label` names it and shows as its tooltip, with an optional `shortcut`. |
+| `Chip`, `ChipGroup` | Pill buttons in the bar over the canvas; `aria-pressed` shows a toggle on, and a group is segmented. |
+| `Tooltip` | A hint on hover or focus for any control, with an optional shortcut written as `Mod Z` (⌘ or Ctrl). |
+| `Menu`, `MenuItem`, `MenuSeparator`, `Submenu` | Commands such as Duplicate, Move, or Delete. |
+| `Select` | A choice that replaces a current value, with `field` or `pill` trigger. |
+| `Popover` | Settings that open beside a pill, such as bar controls that no longer fit. |
+| `Surface` | The elevated panel under every menu, select, and popover; popup parts render as one. |
## Selection and menus
-- Use `Select` for a choice that replaces a current value. Its trigger may use the panel `field` style or floating-toolbar `pill` style; its options always open on the shared elevated surface.
-- Use `Menu` for commands such as Duplicate, Move, or Delete. `Menu` and `Select` both use `MenuSurface`, which owns the anchored popover, border, background, shadow, item hover, dismissal, and keyboard navigation.
+- Use `Menu` for commands and `Popover` for settings; a menu's arrow keys and typeahead would fight sliders and fields inside it. Menu items close the menu when chosen, and nested choices use a `Submenu` rather than a control inside the menu.
+- Use `Select` for a choice that replaces a current value. Its options check the selected one.
- Do not render a native HTML `select` in product UI. Specialized browser pickers such as file and color inputs are allowed when the browser owns behavior OpenLight does not reproduce.
-- Put a check beside the selected option. Keep command menus unselected unless the command itself represents a persistent state.
+- While a surface is open it owns the keyboard: editor shortcuts pause until it closes.
+
+## Tooltips
+
+- Every icon-only control has a tooltip; use `IconButton` or wrap the control in `Tooltip`. Do not use the native `title` attribute.
+- A tooltip names the control in a few words and adds the shortcut beside it; longer guidance belongs in the panel or a canvas hint.
+- A tooltip is not the accessible name. Keep `aria-label` on icon-only controls; `IconButton` sets it from `label`.
+- Text that may be cut short, such as a layer name, shows its tooltip only when truncated.
+
+## Panels
+
+- `EditorPanel` stacks its sections in the order written with a divider between each; `PanelBody` is the section that scrolls, and `PanelHeader` titles a section. The editing sidebar's order is the JSX in `app/editor/sidebar.tsx`.
+- `EditorViewport` is the canvas region: a `ViewportStage` inside it pans and zooms with the image, and other children float over it without panning.
## Panel collections
@@ -25,3 +47,13 @@ OpenLight uses a small set of shared UI primitives so the editor reads as one ap
- Use `ScrubInput` for numbers that primarily read as inline text and secondarily accept typing. Inline variants hug the current digits and unit, keep their label close, and show only a subtly rounded background while text editing is active. Reserve the persistent bordered `box` variant for form fields that need explicit input chrome.
- Give toolbar slider values an explicit minimum character width when their expected range changes digit count. Set it at the call site from the useful range: percentages reserve three tabular characters, while brush size uses the actual maximum's digit count. Do not guess a global maximum.
- Text uses the global body size. Express hierarchy with weight and color.
+
+## Editor tools
+
+How the rail, canvas bar, sidebar, and layer stack behave. Commands they call are in the [control API](API.md).
+
+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 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/bun.lock b/bun.lock
index 9118f2b..487d023 100644
--- a/bun.lock
+++ b/bun.lock
@@ -13,12 +13,14 @@
"@vercel/speed-insights": "^2.0.0",
"class-variance-authority": "^0.7.1",
"cn": "^0.2.4",
+ "idb": "^8.0.3",
"raw-webgpu": "0.1.1",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"tailwindcss": "^4.3.3",
"vgpu": "^0.3.1",
"vgpu-react": "^0.3.0",
+ "zod": "^4.4.3",
"zustand": "^5.0.15",
},
"devDependencies": {
@@ -246,6 +248,8 @@
"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
+ "idb": ["[email protected]", "", {}, "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg=="],
+
"jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
"lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
diff --git a/package.json b/package.json
index 10d6ead..33ba83a 100644
--- a/package.json
+++ b/package.json
@@ -20,12 +20,14 @@
"@vercel/speed-insights": "^2.0.0",
"class-variance-authority": "^0.7.1",
"cn": "^0.2.4",
+ "idb": "^8.0.3",
"raw-webgpu": "0.1.1",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"tailwindcss": "^4.3.3",
"vgpu": "^0.3.1",
"vgpu-react": "^0.3.0",
+ "zod": "^4.4.3",
"zustand": "^5.0.15"
},
"devDependencies": {
diff --git a/src/app/controls.ts b/src/app/controls.ts
index f3d9f69..510ce7b 100644
--- a/src/app/controls.ts
+++ b/src/app/controls.ts
@@ -24,9 +24,9 @@ import type {
Vignette,
} from "@/core/document";
import type { WhiteBalance } from "@/core/image";
-import decode from "@/core/image/decode";
+import { decode } from "@/core/image/decode";
import type { ImageFrame, Point } from "@/core/image/frame";
-import { setAdjustments } from "@/features/adjustments/edits";
+import { setAdjustments, setExposure } from "@/features/adjustments/edits";
import { defaultAdjustments } from "@/features/adjustments/model";
import { resetColorMixer, setColorMixer } from "@/features/color-mixer/edits";
import {
@@ -34,6 +34,7 @@ import {
type MixerChange,
type MixerColor,
} from "@/features/color-mixer/model";
+import { applyCrop } from "@/features/crop/edits";
import { setDetails } from "@/features/details/edits";
import { defaultDetails } from "@/features/details/model";
import { setFill } from "@/features/fill/edits";
@@ -44,7 +45,6 @@ import {
duplicateLayer,
type LayerPlacement,
moveLayer,
- setExposure,
setLayer,
setLayerMask,
setMaskOperation,
@@ -159,13 +159,7 @@ export function createControls(
moveLayer: (id: string, index: number, parentId?: string) =>
moveLayer(workspace.getDocument(), id, index, parentId),
selectLayer: (id: string) => workspace.getDocument().selectLayer(id),
- setFrame(frame: ImageFrame) {
- const document = workspace.getDocument();
- document.edit({
- ...document.scene.getState(),
- frame: structuredClone(frame),
- });
- },
+ setFrame: (frame: ImageFrame) => applyCrop(workspace.getDocument(), frame),
setPreview: (change: Partial<Preview>) =>
workspace.getDocument().preview.setState(change),
beginEdit: () => workspace.getDocument().history.begin(),
diff --git a/src/app/draft/store.ts b/src/app/draft/store.ts
index 641ee90..8d62067 100644
--- a/src/app/draft/store.ts
+++ b/src/app/draft/store.ts
@@ -1,34 +1,38 @@
-import { openScene, type SceneJson, snapshotScene } from "@/app/scene-file";
+import { type DBSchema, type IDBPDatabase, openDB } from "idb";
+import { z } from "zod/mini";
+import { openScene, snapshotScene } from "@/app/scene-file";
import type { EditorDocument } from "@/core/document";
import type { ImageSource } from "@/core/image";
+import { parse } from "@/lib/parse";
/** Raised only when older drafts can no longer open as written; the scene inside keeps its own version. */
const version = 1;
/** The latest document: the scene JSON a scene file holds, while its source files live in their own store by ID. */
-export type DraftRecord = { version: number; name: string; scene: SceneJson };
+const recordSchema = z.object(
+ {
+ version: z.int().check(z.minimum(1)),
+ name: z.string(),
+ scene: z.unknown(),
+ },
+ "Invalid draft",
+);
+export type DraftRecord = z.output<typeof recordSchema>;
export type Draft = { record: DraftRecord; files: ReadonlyMap<string, Blob> };
/** A draft of the document shown as `name`, captured synchronously so the document may change or close meanwhile. */
-export function snapshotDraft(document: EditorDocument, name: string): Draft {
+export function snapshotDraft(document: EditorDocument, name: string) {
const { json, files } = snapshotScene(document);
return { record: { version, name, scene: json }, files };
}
-/** Storage returns whatever an earlier version wrote, so the record is checked where it is read. */
-function validateRecord(record: DraftRecord | undefined): DraftRecord {
- if (
- !record ||
- !Number.isInteger(record.version) ||
- record.version < 1 ||
- typeof record.name !== "string"
- ) {
- throw Error("Invalid draft.");
- }
- if (record.version > version) {
+/** Storage returns whatever an earlier version wrote, so the record is parsed where it is read; the scene opens later. */
+function readRecord(record: unknown) {
+ const read = parse(recordSchema, record, "Invalid draft");
+ if (read.version > version) {
throw Error("This draft needs a newer version of OpenLight.");
}
- return record;
+ return read;
}
/** Opens a draft through the same validation as a scene file. */
@@ -36,44 +40,31 @@ export async function openDraft(
{ record, files }: Draft,
decode: (file: File) => Promise<ImageSource>,
) {
- return openScene(validateRecord(record).scene, files, decode);
+ return openScene(readRecord(record).scene, files, decode);
}
-/** Resolves once every request issued in the transaction has run, so callers read results from the requests. */
-function complete(transaction: IDBTransaction) {
- return new Promise<void>((resolve, reject) => {
- transaction.oncomplete = () => resolve();
- transaction.onerror = () => reject(transaction.error);
- transaction.onabort = () =>
- reject(transaction.error ?? Error("Draft storage was interrupted."));
- });
+interface DraftDatabase extends DBSchema {
+ draft: { key: "latest"; value: unknown };
+ sources: { key: string; value: Blob };
}
/**
* One draft in IndexedDB: the record under a single key, and source files keyed by source ID.
* Operations run one at a time in call order, so a discard never races a save.
- * Requests are issued from the transaction's own callbacks, never after an await, so it can't auto-commit early.
*/
-export function createDraftStore(
- factory: IDBFactory | undefined = globalThis.indexedDB,
- name = "openlight",
-) {
- let database: Promise<IDBDatabase> | undefined;
+export function createDraftStore(name = "openlight") {
+ let database: Promise<IDBPDatabase<DraftDatabase>> | undefined;
let queue = Promise.resolve();
function connect() {
- if (!factory) {
+ if (!globalThis.indexedDB) {
return Promise.reject(Error("IndexedDB is unavailable."));
}
- database ??= new Promise<IDBDatabase>((resolve, reject) => {
- const opening = factory.open(name, 1);
- opening.onupgradeneeded = () => {
- opening.result.createObjectStore("draft");
- opening.result.createObjectStore("sources");
- };
- opening.onsuccess = () => resolve(opening.result);
- opening.onerror = () => reject(opening.error);
- opening.onblocked = () => reject(Error("Draft storage is blocked."));
+ database ??= openDB<DraftDatabase>(name, 1, {
+ upgrade(database) {
+ database.createObjectStore("draft");
+ database.createObjectStore("sources");
+ },
}).catch((error) => {
database = undefined;
throw error;
@@ -81,7 +72,7 @@ export function createDraftStore(
return database;
}
- function run<T>(task: (database: IDBDatabase) => Promise<T>) {
+ function run<T>(task: (database: IDBPDatabase<DraftDatabase>) => Promise<T>) {
const result = queue.then(async () => task(await connect()));
queue = result.then(
() => {},
@@ -98,56 +89,45 @@ export function createDraftStore(
["draft", "sources"],
"readwrite",
);
- transaction.objectStore("draft").put(record, "latest");
const sources = transaction.objectStore("sources");
- const stored = sources.getAllKeys();
- stored.onsuccess = () => {
- for (const [id, file] of files) {
- if (!stored.result.includes(id)) {
- sources.put(file, id);
- }
- }
- for (const id of stored.result) {
- if (typeof id === "string" && !files.has(id)) {
- sources.delete(id);
- }
- }
- };
- await complete(transaction);
+ const stored = await sources.getAllKeys();
+ await Promise.all([
+ transaction.objectStore("draft").put(record, "latest"),
+ ...[...files]
+ .filter(([id]) => !stored.includes(id))
+ .map(([id, file]) => sources.put(file, id)),
+ ...stored
+ .filter((id) => !files.has(id))
+ .map((id) => sources.delete(id)),
+ transaction.done,
+ ]);
});
},
/** The draft's display name, without reading its source files. */
peek() {
return run(async (database) => {
- const transaction = database.transaction("draft");
- const record: IDBRequest<DraftRecord | undefined> = transaction
- .objectStore("draft")
- .get("latest");
- await complete(transaction);
- return record.result && { name: validateRecord(record.result).name };
+ const record = await database.get("draft", "latest");
+ return record && { name: readRecord(record).name };
});
},
/** The record with every stored source file; a save leaves only the files the draft uses. */
read() {
return run(async (database): Promise<Draft | undefined> => {
const transaction = database.transaction(["draft", "sources"]);
- const record: IDBRequest<DraftRecord | undefined> = transaction
- .objectStore("draft")
- .get("latest");
const sources = transaction.objectStore("sources");
- const ids = sources.getAllKeys();
- const blobs: IDBRequest<Blob[]> = sources.getAll();
- await complete(transaction);
- if (!record.result) {
+ const [record, ids, blobs] = await Promise.all([
+ transaction.objectStore("draft").get("latest"),
+ sources.getAllKeys(),
+ sources.getAll(),
+ transaction.done,
+ ]);
+ if (!record) {
return undefined;
}
- const files = new Map<string, Blob>();
- ids.result.forEach((id, index) => {
- if (typeof id === "string") {
- files.set(id, blobs.result[index]);
- }
- });
- return { record: validateRecord(record.result), files };
+ return {
+ record: readRecord(record),
+ files: new Map(ids.map((id, index) => [id, blobs[index]])),
+ };
});
},
discard() {
@@ -156,9 +136,11 @@ export function createDraftStore(
["draft", "sources"],
"readwrite",
);
- transaction.objectStore("draft").clear();
- transaction.objectStore("sources").clear();
- await complete(transaction);
+ await Promise.all([
+ transaction.objectStore("draft").clear(),
+ transaction.objectStore("sources").clear(),
+ transaction.done,
+ ]);
});
},
};
diff --git a/src/app/editor/adjust/index.tsx b/src/app/editor/adjust/index.tsx
index c2f5526..9bd08e4 100644
--- a/src/app/editor/adjust/index.tsx
+++ b/src/app/editor/adjust/index.tsx
@@ -1,5 +1,4 @@
-import { useCallback, useEffect, useMemo } from "react";
-import { useGpu } from "vgpu-react";
+import { useCallback } from "react";
import { useStore } from "zustand";
import { PanelHeader } from "@/components/editor/panel";
import { useRenderer } from "@/components/editor/pipeline";
@@ -7,13 +6,12 @@ import { useDocument, useScene } from "@/components/editor/session";
import { Slider } from "@/components/ui/slider";
import { adjustmentTarget, type Layer, type ToneCurve } from "@/core/document";
import { AdjustmentControls } from "@/features/adjustments/controls";
+import { setExposure } from "@/features/adjustments/edits";
import { ColorMixerControls } from "@/features/color-mixer/controls";
import { DetailsControls } from "@/features/details/controls";
import { FillControls } from "@/features/fill/controls";
import { HealControls } from "@/features/heal/controls";
import { Histogram } from "@/features/histogram";
-import { createHistogram } from "@/features/histogram/histogram";
-import { setExposure } from "@/features/layers/edits";
import { setToneCurve } from "@/features/tone-curves/edits";
import { ToneCurves } from "@/features/tone-curves/tone-curves";
import { VignetteControls } from "@/features/vignette/controls";
@@ -23,14 +21,10 @@ import { useEditGesture } from "@/hooks/use-edit-gesture";
const curveHistogramColors = ["#a3a3a3"] as const;
function CurveInputHistogram({ id }: { id: string }) {
- const gpu = useGpu();
const renderer = useRenderer();
- const histogram = useMemo(() => createHistogram(gpu), [gpu]);
const image = useCallback(() => renderer.inputImage(id), [renderer, id]);
- useEffect(() => () => histogram.dispose(), [histogram]);
return (
<Histogram
- histogram={histogram}
image={image}
subscribe={renderer.subscribe}
colors={curveHistogramColors}
diff --git a/src/app/editor/backdrop.tsx b/src/app/editor/backdrop.tsx
index 41389dc..f727d4f 100644
--- a/src/app/editor/backdrop.tsx
+++ b/src/app/editor/backdrop.tsx
@@ -1,7 +1,7 @@
import { useRef } from "react";
import { clock } from "vgpu";
import { Canvas, useCanvas, useFrameLoop, useGpu, useShader } from "vgpu-react";
-import usePointer from "@/hooks/use-pointer";
+import { usePointer } from "@/hooks/use-pointer";
import shader from "./backdrop.wgsl";
const strength = { none: 0, hover: 0.05, drag: 1 };
@@ -31,7 +31,7 @@ function Glow() {
return null;
}
-export default function Backdrop() {
+export function Backdrop() {
return (
<Canvas className="absolute inset-0 -z-10 size-full" dpr={[1, 2]}>
<Glow />
diff --git a/src/app/editor/canvas.tsx b/src/app/editor/canvas.tsx
deleted file mode 100644
index d7e38d6..0000000
--- a/src/app/editor/canvas.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import type { ReactNode } from "react";
-import { Image } from "@/components/editor/image";
-import { useScene } from "@/components/editor/session";
-import { EditorViewport } from "@/components/editor/viewport";
-import { CanvasToolbar } from "@/features/layers/toolbar";
-import { ComparisonDivider } from "./comparison-divider";
-import { MaskOverlaySync } from "./mask-overlay";
-
-/** The shared canvas; the active tool supplies the overlay on it and the options in the bar above it. */
-export function EditorCanvas({
- tools,
- options,
-}: {
- tools: ReactNode;
- options?: ReactNode;
-}) {
- const size = useScene((scene) => scene.frame.size);
- return (
- <EditorViewport
- size={size}
- overlay={
- <>
- <ComparisonDivider />
- <CanvasToolbar>{options}</CanvasToolbar>
- <MaskOverlaySync />
- </>
- }
- tools={tools}
- >
- <Image original="originalImage" />
- </EditorViewport>
- );
-}
diff --git a/src/app/editor/clipping-controls.tsx b/src/app/editor/clipping-controls.tsx
index 8d166d4..f2dfc8e 100644
--- a/src/app/editor/clipping-controls.tsx
+++ b/src/app/editor/clipping-controls.tsx
@@ -1,6 +1,6 @@
import { useStore } from "zustand";
import { useDocument } from "@/components/editor/session";
-import Button from "@/components/ui/button";
+import { IconButton } from "@/components/ui/button";
export function ClippingControls() {
const { preview } = useDocument();
@@ -10,11 +10,9 @@ export function ClippingControls() {
return (
<div className="pointer-events-none absolute inset-x-1 top-1 z-10 flex justify-between">
{(["shadows", "highlights"] as const).map((range) => (
- <Button
+ <IconButton
key={range}
- variant="ghost"
- aria-label={`Show clipped ${range}`}
- title={`Show clipped ${range}`}
+ label={`Show clipped ${range}`}
aria-pressed={state[range]}
className="pointer-events-auto flex size-6 items-center justify-center rounded-sm bg-neutral-900/80 p-0 opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100 aria-pressed:bg-neutral-700 aria-pressed:text-white aria-pressed:opacity-100 pointer-coarse:opacity-100"
onClick={() => preview.setState({ [range]: !state[range] })}
@@ -27,7 +25,7 @@ export function ClippingControls() {
>
<path d="M6 2 11 10H1Z" />
</svg>
- </Button>
+ </IconButton>
))}
</div>
);
diff --git a/src/app/editor/comparison-control.tsx b/src/app/editor/comparison-control.tsx
index 705acc3..0b9f7e0 100644
--- a/src/app/editor/comparison-control.tsx
+++ b/src/app/editor/comparison-control.tsx
@@ -1,8 +1,9 @@
import { useEffect } from "react";
import { useStore } from "zustand";
import { useDocument } from "@/components/editor/session";
-import Button from "@/components/ui/button";
+import { IconButton } from "@/components/ui/button";
import type { Preview } from "@/core/document";
+import { isTyping } from "@/lib/dom";
export function ComparisonControl() {
const { preview } = useDocument();
@@ -26,14 +27,7 @@ export function ComparisonControl() {
) {
return;
}
- const target = event.target;
- if (
- target instanceof HTMLElement &&
- (target.isContentEditable ||
- target.closest(
- 'input:not([type="range"]), textarea, select, [role="dialog"]',
- ))
- ) {
+ if (isTyping(event.target)) {
return;
}
event.preventDefault();
@@ -56,12 +50,10 @@ export function ComparisonControl() {
};
}, [preview]);
return (
- <Button
- variant="ghost"
- size="icon"
- aria-label="Compare before and after"
+ <IconButton
+ label="Compare before and after"
+ shortcut="Hold \"
aria-pressed={comparison !== "edited"}
- title="Compare before and after (hold backslash for original)"
className="aria-pressed:bg-neutral-700 aria-pressed:text-neutral-100"
onClick={() =>
preview.setState({
@@ -79,6 +71,6 @@ export function ComparisonControl() {
>
<path d="M10 2v16M7 5H3v10h4M13 5h4v10h-4" />
</svg>
- </Button>
+ </IconButton>
);
}
diff --git a/src/app/editor/empty.tsx b/src/app/editor/empty.tsx
index 558b756..d9fe077 100644
--- a/src/app/editor/empty.tsx
+++ b/src/app/editor/empty.tsx
@@ -1,25 +1,25 @@
-import { useEffect, useMemo, useRef } from "react";
+import { useRef } from "react";
import { type Gpu, target } from "vgpu";
import { useGpu } from "vgpu-react";
import { sceneExtension } from "@/app/loaders/scene";
import type { Workspace } from "@/app/workspace";
import { RendererProvider } from "@/components/editor/pipeline";
import { DocumentProvider } from "@/components/editor/session";
-import Button from "@/components/ui/button";
+import { Button } from "@/components/ui/button";
import { Notice } from "@/components/ui/notice";
-import Spinner from "@/components/ui/spinner";
+import { Spinner } from "@/components/ui/spinner";
import { TextLink } from "@/components/ui/text-link";
import { createDocument, createResources } from "@/core/document";
import { createImageSource } from "@/core/image";
import { accept } from "@/core/image/decode";
import { imageFrame } from "@/core/image/frame";
import { MaskToolProvider } from "@/features/layers/mask-tool";
-import { AdjustPanel } from "./adjust";
-import Backdrop from "./backdrop";
+import { useDisposable } from "@/hooks/use-disposable";
+import { Backdrop } from "./backdrop";
import { EditorHeader } from "./header";
import { createImageLayer } from "./layers";
import { createEditorRenderer } from "./renderer";
-import { EditorSidebar } from "./sidebar";
+import { PlaceholderSidebar } from "./sidebar";
import { ToolTabList } from "./tool-rail";
import { tools } from "./tools";
@@ -131,8 +131,7 @@ export function EmptyEditor({
draft,
}: { state: EmptyState; draft?: Recovery } & OpenProps) {
const gpu = useGpu();
- const document = useMemo(() => createEmptyDocument(gpu), [gpu]);
- useEffect(() => () => document.dispose(), [document]);
+ const document = useDisposable(() => createEmptyDocument(gpu), [gpu]);
return (
<DocumentProvider value={document}>
<RendererProvider createRenderer={createEditorRenderer}>
@@ -145,9 +144,7 @@ export function EmptyEditor({
<Status state={state} onOpen={onOpen} />
{draft && <RecoverDraft {...draft} />}
</div>
- <EditorSidebar inert>
- <AdjustPanel />
- </EditorSidebar>
+ <PlaceholderSidebar />
</div>
</MaskToolProvider>
</RendererProvider>
diff --git a/src/app/editor/export/index.tsx b/src/app/editor/export/index.tsx
index a8cc055..6ba0af4 100644
--- a/src/app/editor/export/index.tsx
+++ b/src/app/editor/export/index.tsx
@@ -3,14 +3,14 @@ import { type ReactNode, useMemo, useRef, useState } from "react";
import { useGpu } from "vgpu-react";
import { writeSceneFile } from "@/app/loaders/scene";
import { Image } from "@/components/editor/image";
-import { EditorPanel, PanelHeader } from "@/components/editor/panel";
+import { EditorPanel, PanelBody, PanelHeader } from "@/components/editor/panel";
import { useDocument, useScene } from "@/components/editor/session";
-import { EditorViewport } from "@/components/editor/viewport";
-import Button from "@/components/ui/button";
+import { EditorViewport, ViewportStage } from "@/components/editor/viewport";
+import { Button } from "@/components/ui/button";
import { ScrubInput } from "@/components/ui/scrub-input";
import { Select } from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
-import Spinner from "@/components/ui/spinner";
+import { Spinner } from "@/components/ui/spinner";
import type { Point } from "@/core/image/frame";
import { useShortcuts } from "@/hooks/use-shortcuts";
import { type ExportFormat, exportImage, exportSize } from "./export-image";
@@ -240,47 +240,53 @@ export function ExportMode({ onClose }: { onClose: () => void }) {
};
return (
<>
- <EditorViewport
- size={encoded?.image.size ?? output}
- overlay={pending && <LoadingOverlay />}
- >
- {encoded && <Image image={encoded.image} />}
+ <EditorViewport size={encoded?.image.size ?? output}>
+ <ViewportStage>
+ {encoded && <Image image={encoded.image} />}
+ </ViewportStage>
+ {pending && <LoadingOverlay />}
</EditorViewport>
- <EditorPanel header={<PanelHeader title="Export" onClose={onClose} />}>
- <section aria-label="Image export" className="flex flex-col gap-5 p-4">
- <FormatSelect value={format} onChange={setFormat} />
- {format.lossy && (
- <Slider
- label="Quality"
- value={quality}
- onChange={setQuality}
- min={1}
- max={100}
- defaultValue={80}
- />
- )}
- <SizeFields size={size} longEdge={edge} onChange={setLongEdge}>
- <span>File size</span>
- <span
- className={cn(
- "col-span-2 flex items-center justify-end gap-1.5 text-neutral-100 tabular-nums",
- pending && "text-neutral-500",
- )}
- >
- {encoded ? formatBytes(encoded.bytes) : "…"}
- {pending && <Spinner className="size-3" />}
- </span>
- </SizeFields>
- <Button className="w-full py-2" onClick={save}>
- Save image
- </Button>
- {error && (
- <p className="text-red-400" role="alert">
- {error}
- </p>
- )}
- </section>
- <SaveScene />
+ <EditorPanel>
+ <PanelHeader title="Export" onClose={onClose} />
+ <PanelBody>
+ <section
+ aria-label="Image export"
+ className="flex flex-col gap-5 p-4"
+ >
+ <FormatSelect value={format} onChange={setFormat} />
+ {format.lossy && (
+ <Slider
+ label="Quality"
+ value={quality}
+ onChange={setQuality}
+ min={1}
+ max={100}
+ defaultValue={80}
+ />
+ )}
+ <SizeFields size={size} longEdge={edge} onChange={setLongEdge}>
+ <span>File size</span>
+ <span
+ className={cn(
+ "col-span-2 flex items-center justify-end gap-1.5 text-neutral-100 tabular-nums",
+ pending && "text-neutral-500",
+ )}
+ >
+ {encoded ? formatBytes(encoded.bytes) : "…"}
+ {pending && <Spinner className="size-3" />}
+ </span>
+ </SizeFields>
+ <Button className="w-full py-2" onClick={save}>
+ Save image
+ </Button>
+ {error && (
+ <p className="text-red-400" role="alert">
+ {error}
+ </p>
+ )}
+ </section>
+ <SaveScene />
+ </PanelBody>
</EditorPanel>
</>
);
diff --git a/src/app/editor/export/preview.tsx b/src/app/editor/export/preview.tsx
index 55064ca..1834402 100644
--- a/src/app/editor/export/preview.tsx
+++ b/src/app/editor/export/preview.tsx
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react";
import type { Target } from "vgpu";
import { useGpu } from "vgpu-react";
import { useRenderer } from "@/components/editor/pipeline";
-import linearize from "@/core/image/decode/linearize";
+import { linearize } from "@/core/image/decode/linearize";
import { type ExportOptions, encodeImage } from "./export-image";
/** Quiet time after a change before encoding; typical encodes take tens of milliseconds. */
diff --git a/src/app/editor/header.tsx b/src/app/editor/header.tsx
index 1082b1c..563b095 100644
--- a/src/app/editor/header.tsx
+++ b/src/app/editor/header.tsx
@@ -1,4 +1,5 @@
import type { ReactNode } from "react";
+import { Tooltip } from "@/components/ui/tooltip";
/** Identity on the left, document actions on the right; present in every editor state. */
export function EditorHeader({
@@ -15,9 +16,9 @@ export function EditorHeader({
<span className="font-medium text-neutral-200">OpenLight</span>
</span>
{file && (
- <span className="min-w-0 truncate text-neutral-500" title={file}>
- {file}
- </span>
+ <Tooltip content={file}>
+ <span className="min-w-0 truncate text-neutral-500">{file}</span>
+ </Tooltip>
)}
<div className="ml-auto flex items-center gap-1">{children}</div>
</header>
diff --git a/src/app/editor/histogram.tsx b/src/app/editor/histogram.tsx
index 9270072..a172dd3 100644
--- a/src/app/editor/histogram.tsx
+++ b/src/app/editor/histogram.tsx
@@ -1,25 +1,18 @@
-import { useEffect, useMemo } from "react";
-import { useGpu } from "vgpu-react";
import { useRenderer } from "@/components/editor/pipeline";
import { Histogram } from "@/features/histogram";
-import { createHistogram } from "@/features/histogram/histogram";
import { ClippingControls } from "./clipping-controls";
const colors = ["#f25445", "#6bd175", "#5c8ffa"] as const;
export function ImageHistogram() {
- const gpu = useGpu();
const renderer = useRenderer();
- const histogram = useMemo(() => createHistogram(gpu), [gpu]);
- useEffect(() => () => histogram.dispose(), [histogram]);
return (
<section
aria-label="Image histogram"
- className="group relative shrink-0 border-b border-black bg-neutral-900 max-md:absolute max-md:bottom-full max-md:left-3 max-md:z-10 max-md:mb-3 max-md:h-14 max-md:w-44 max-md:overflow-hidden max-md:border-0 max-md:bg-neutral-800/80 max-md:backdrop-blur-sm"
+ className="group relative shrink-0 bg-neutral-900 max-md:absolute max-md:bottom-full max-md:left-3 max-md:z-10 max-md:mb-3 max-md:h-14 max-md:w-44 max-md:overflow-hidden max-md:border-0 max-md:bg-neutral-800/80 max-md:backdrop-blur-sm"
>
<ClippingControls />
<Histogram
- histogram={histogram}
image={renderer.outputImage}
subscribe={renderer.subscribe}
colors={colors}
diff --git a/src/app/editor/history.tsx b/src/app/editor/history.tsx
index 5b2c125..aa4facb 100644
--- a/src/app/editor/history.tsx
+++ b/src/app/editor/history.tsx
@@ -1,7 +1,7 @@
import { useStore } from "zustand";
import { useDocument } from "@/components/editor/session";
import { Icon } from "@/components/icons/icon";
-import Button from "@/components/ui/button";
+import { IconButton } from "@/components/ui/button";
import { useShortcuts } from "@/hooks/use-shortcuts";
export function HistoryControls() {
@@ -15,32 +15,26 @@ export function HistoryControls() {
});
return (
<fieldset aria-label="History" className="flex items-center gap-0.5">
- <Button
- variant="ghost"
- size="icon"
- className="disabled:pointer-events-none disabled:opacity-25"
- aria-label="Undo"
- title="Undo (Ctrl/⌘ Z)"
+ <IconButton
+ label="Undo"
+ shortcut="Mod Z"
disabled={!undoCount}
onClick={history.undo}
>
<Icon viewBox="0 0 20 20" className="size-4">
<path d="m7 4-4 4 4 4M3 8h8a5 5 0 0 1 0 10" />
</Icon>
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="disabled:pointer-events-none disabled:opacity-25"
- aria-label="Redo"
- title="Redo (Ctrl/⌘ Shift Z)"
+ </IconButton>
+ <IconButton
+ label="Redo"
+ shortcut="Mod Shift Z"
disabled={!redoCount}
onClick={history.redo}
>
<Icon viewBox="0 0 20 20" className="size-4">
<path d="m13 4 4 4-4 4m4-4H9a5 5 0 0 0 0 10" />
</Icon>
- </Button>
+ </IconButton>
</fieldset>
);
}
diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsx
index ea09175..f672cdb 100644
--- a/src/app/editor/index.tsx
+++ b/src/app/editor/index.tsx
@@ -1,22 +1,31 @@
import type { ReactNode } from "react";
import type { Workspace } from "@/app/workspace";
import { BrushProvider } from "@/components/editor/brush-tool";
+import { Image } from "@/components/editor/image";
import { RendererProvider } from "@/components/editor/pipeline";
-import { DocumentProvider, useDocument } from "@/components/editor/session";
-import Button from "@/components/ui/button";
+import {
+ DocumentProvider,
+ useDocument,
+ useScene,
+} from "@/components/editor/session";
+import { EditorViewport, ViewportStage } from "@/components/editor/viewport";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
import type { Mask } from "@/core/document";
import { findLayer, locateLayer } from "@/core/document";
import { HealingProvider } from "@/features/heal/mode";
import { addLayer } from "@/features/layers/edits";
import { MaskToolProvider, type Nesting } from "@/features/layers/mask-tool";
+import { CanvasToolbar } from "@/features/layers/toolbar";
import { useShortcuts } from "@/hooks/use-shortcuts";
-import { AdjustPanel } from "./adjust";
-import { EditorCanvas } from "./canvas";
+import { blurActive } from "@/lib/dom";
import { ComparisonControl } from "./comparison-control";
+import { ComparisonDivider } from "./comparison-divider";
import { EmptyEditor, type Recovery } from "./empty";
import { EditorHeader } from "./header";
import { HistoryControls } from "./history";
import { createMask } from "./layers";
+import { MaskOverlaySync } from "./mask-overlay";
import { createEditorRenderer } from "./renderer";
import { EditorSidebar } from "./sidebar";
import { ToolRail } from "./tool-rail";
@@ -26,6 +35,7 @@ import { exportTool, ToolProvider, tools, useTool } from "./tools";
function ToolView() {
const { tool, setTool } = useTool();
const document = useDocument();
+ const size = useScene((scene) => scene.frame.size);
// Enter and Escape leave one level: shape tools return to Adjust, where the selection climbs to the image.
function up() {
const layers = document.scene.getState().layers;
@@ -39,22 +49,23 @@ function ToolView() {
);
function close() {
setTool(tools[0]);
- if (window.document.activeElement instanceof HTMLElement) {
- window.document.activeElement.blur();
- }
+ blurActive();
}
if ("View" in tool) {
return <tool.View onClose={close} />;
}
return (
<>
- <EditorCanvas
- tools={"Canvas" in tool ? <tool.Canvas key={tool.id} /> : undefined}
- options={"Options" in tool ? <tool.Options /> : undefined}
- />
- <EditorSidebar>
- <AdjustPanel />
- </EditorSidebar>
+ <EditorViewport size={size}>
+ <ViewportStage>
+ <Image original="originalImage" />
+ {"Canvas" in tool && <tool.Canvas key={tool.id} />}
+ </ViewportStage>
+ <ComparisonDivider />
+ <CanvasToolbar>{"Options" in tool && <tool.Options />}</CanvasToolbar>
+ <MaskOverlaySync />
+ </EditorViewport>
+ <EditorSidebar />
</>
);
}
@@ -63,14 +74,15 @@ function ExportButton() {
const { tool, setTool } = useTool();
const exporting = tool === exportTool;
return (
- <Button
- aria-pressed={exporting}
- title="Export (E)"
- className="ml-1 aria-pressed:bg-neutral-600"
- onClick={() => setTool(exporting ? tools[0] : exportTool)}
- >
- Export
- </Button>
+ <Tooltip content="Export the photo or save a scene" shortcut="E">
+ <Button
+ aria-pressed={exporting}
+ className="ml-1 aria-pressed:bg-neutral-600"
+ onClick={() => setTool(exporting ? tools[0] : exportTool)}
+ >
+ Export
+ </Button>
+ </Tooltip>
);
}
@@ -164,7 +176,7 @@ function EditorContent({ state, onOpen, draft }: EditorProps) {
</DocumentProvider>
);
}
-export default function Editor(props: EditorProps) {
+export function Editor(props: EditorProps) {
return (
<main className="flex h-dvh flex-col">
<EditorContent {...props} />
diff --git a/src/app/editor/layers.ts b/src/app/editor/layers.ts
index 303b100..7f1b879 100644
--- a/src/app/editor/layers.ts
+++ b/src/app/editor/layers.ts
@@ -1,3 +1,8 @@
+import { ColorMixerIcon } from "@/components/icons/color-mixer";
+import { DetailsIcon } from "@/components/icons/details";
+import { ExposureIcon } from "@/components/icons/exposure";
+import { HealIcon } from "@/components/icons/heal";
+import { VignetteIcon } from "@/components/icons/vignette";
import type {
EditorDocument,
EffectLayer,
@@ -12,7 +17,9 @@ import { defaultAdjustments } from "@/features/adjustments/model";
import { defaultMixer, isNeutral } from "@/features/color-mixer/model";
import { defaultDetails } from "@/features/details/model";
import { defaultFill } from "@/features/fill/model";
+import type { EffectKind } from "@/features/layers/controls";
import { defaultCurve } from "@/features/tone-curves/curve";
+import { defaultVignette } from "@/features/vignette/model";
function baseLayer() {
return { id: crypto.randomUUID(), visible: true, opacity: 1, children: [] };
@@ -35,31 +42,40 @@ export function createImageLayer(
};
}
+/** Every effect kind's name and mark, in Add menu order; the stack and new layers read it. */
+export const effectKinds = [
+ { kind: "details", label: "Details", Icon: DetailsIcon, addable: true },
+ { kind: "exposure", label: "Exposure", Icon: ExposureIcon, addable: true },
+ {
+ kind: "color-mixer",
+ label: "Color Mixer",
+ Icon: ColorMixerIcon,
+ addable: true,
+ },
+ { kind: "vignette", label: "Vignette", Icon: VignetteIcon, addable: true },
+ { kind: "fill", label: "Color", addable: true },
+ { kind: "heal", label: "Healing", Icon: HealIcon, addable: false },
+] as const satisfies readonly EffectKind[];
+
export function createLayer<K extends EffectLayer["kind"]>(
kind: K,
): Extract<EffectLayer, { kind: K }>;
export function createLayer(kind: EffectLayer["kind"]): EffectLayer {
- const base = baseLayer();
+ const name = effectKinds.find((entry) => entry.kind === kind)?.label ?? kind;
+ const base = { ...baseLayer(), name };
switch (kind) {
case "details":
- return { ...base, kind, name: "Details", details: { ...defaultDetails } };
+ return { ...base, kind, details: { ...defaultDetails } };
case "exposure":
- return { ...base, kind, name: "Exposure", exposure: 1 };
+ return { ...base, kind, exposure: 1 };
case "vignette":
- return {
- ...base,
- kind,
- name: "Vignette",
- vignette: { intensity: 50, softness: 50 },
- };
+ return { ...base, kind, vignette: { ...defaultVignette, intensity: 50 } };
case "color-mixer":
- return { ...base, kind, name: "Color Mixer", colorMixer: defaultMixer };
+ return { ...base, kind, colorMixer: defaultMixer };
case "fill":
- return { ...base, kind, name: "Color", fill: { ...defaultFill } };
+ return { ...base, kind, fill: { ...defaultFill } };
case "heal":
- return { ...base, kind, name: "Healing", patches: [] };
- default:
- throw Error("Unknown layer kind.");
+ return { ...base, kind, patches: [] };
}
}
diff --git a/src/app/editor/sidebar.tsx b/src/app/editor/sidebar.tsx
index 46a727a..3ddaea2 100644
--- a/src/app/editor/sidebar.tsx
+++ b/src/app/editor/sidebar.tsx
@@ -1,21 +1,15 @@
-import type { ReactNode } from "react";
-import { EditorPanel } from "@/components/editor/panel";
+import { EditorPanel, PanelBody } from "@/components/editor/panel";
import { useDocument } from "@/components/editor/session";
import type { EffectLayer } from "@/core/document";
import { findLayer } from "@/core/document";
import { LayersControls } from "@/features/layers/controls";
import { addLayer } from "@/features/layers/edits";
+import { AdjustPanel } from "./adjust";
import { ImageHistogram } from "./histogram";
-import { createLayer } from "./layers";
+import { createLayer, effectKinds } from "./layers";
-/** Histogram above, the mode's controls in the middle, the layer stack below once there is a document. */
-export function EditorSidebar({
- children,
- inert,
-}: {
- children: ReactNode;
- inert?: boolean;
-}) {
+/** The layer stack with the effects the app offers; a new effect goes inside a selected root mask or above the selection. */
+function EditorLayers() {
const document = useDocument();
function add(kind: EffectLayer["kind"]) {
const scene = document.scene.getState();
@@ -27,13 +21,30 @@ export function EditorSidebar({
: { above: selected };
addLayer(document, createLayer(kind), placement);
}
+ return <LayersControls effects={effectKinds} onAdd={add} />;
+}
+
+/** The editing sidebar, top to bottom; reorder the sections here. */
+export function EditorSidebar() {
+ return (
+ <EditorPanel>
+ <ImageHistogram />
+ <EditorLayers />
+ <PanelBody>
+ <AdjustPanel />
+ </PanelBody>
+ </EditorPanel>
+ );
+}
+
+/** Before a document opens, the sidebar shows default controls, dimmed, without a layer stack. */
+export function PlaceholderSidebar() {
return (
- <EditorPanel
- inert={inert}
- header={<ImageHistogram />}
- footer={!inert && <LayersControls onAdd={add} />}
- >
- {children}
+ <EditorPanel inert>
+ <ImageHistogram />
+ <PanelBody>
+ <AdjustPanel />
+ </PanelBody>
</EditorPanel>
);
}
diff --git a/src/app/editor/tool-rail.tsx b/src/app/editor/tool-rail.tsx
index 3ab7d34..f0dfc3b 100644
--- a/src/app/editor/tool-rail.tsx
+++ b/src/app/editor/tool-rail.tsx
@@ -1,9 +1,10 @@
import { GithubIcon } from "@/components/icons/github";
import { Tab, TabList } from "@/components/ui/tabs";
+import { Tooltip } from "@/components/ui/tooltip";
import { useShortcuts } from "@/hooks/use-shortcuts";
import { type Tool, tools, useTool } from "./tools";
-/** Icon tabs in a column at the window's left edge on desktop, a bar above the canvas on mobile; titles carry the label and shortcut. Without a handler the tabs are inert. */
+/** Icon tabs in a column at the window's left edge on desktop, a bar above the canvas on mobile; tooltips carry the label and shortcut. Without a handler the tabs are inert. */
export function ToolTabList({
selected,
onSelect,
@@ -16,30 +17,35 @@ export function ToolTabList({
<div className="flex shrink-0 gap-1 overflow-auto border-black border-b bg-panel p-1.5 md:w-11 md:flex-col md:border-r md:border-b-0">
<TabList aria-label="Tools" className="md:flex-col">
{editing.map((entry) => (
- <Tab
+ <Tooltip
key={entry.id}
- selected={entry === selected}
- disabled={!onSelect}
- size="icon"
- className="disabled:pointer-events-none disabled:opacity-40"
- aria-label={entry.label}
- title={`${entry.label} (${entry.key.toUpperCase()})`}
- onClick={() => onSelect?.(entry)}
+ content={entry.label}
+ shortcut={entry.key.toUpperCase()}
+ side="right"
>
- <entry.Icon className="size-5" />
- </Tab>
+ <Tab
+ selected={entry === selected}
+ disabled={!onSelect}
+ size="icon"
+ aria-label={entry.label}
+ onClick={() => onSelect?.(entry)}
+ >
+ <entry.Icon className="size-5" />
+ </Tab>
+ </Tooltip>
))}
</TabList>
- <a
- href="https://github.com/roprgm/openlight"
- target="_blank"
- rel="noreferrer"
- aria-label="OpenLight on GitHub"
- title="OpenLight on GitHub"
- className="ml-auto grid place-items-center rounded-md p-1.5 text-neutral-500 transition-colors hover:bg-neutral-700/50 hover:text-neutral-100 md:mt-auto md:ml-0"
- >
- <GithubIcon className="size-5" />
- </a>
+ <Tooltip content="OpenLight on GitHub" side="right">
+ <a
+ href="https://github.com/roprgm/openlight"
+ target="_blank"
+ rel="noreferrer"
+ aria-label="OpenLight on GitHub"
+ className="ml-auto grid place-items-center rounded-md p-1.5 text-neutral-500 transition-colors hover:bg-neutral-700/50 hover:text-neutral-100 md:mt-auto md:ml-0"
+ >
+ <GithubIcon className="size-5" />
+ </a>
+ </Tooltip>
</div>
);
}
diff --git a/src/app/index.tsx b/src/app/index.tsx
index 2c3fed5..cd08ef4 100644
--- a/src/app/index.tsx
+++ b/src/app/index.tsx
@@ -1,13 +1,13 @@
import { useStore } from "zustand";
import { DraftNotice } from "@/app/draft/notice";
-import Editor from "@/app/editor";
+import { Editor } from "@/app/editor";
import { useWorkspace } from "@/app/workspace/use-workspace";
import { useFileDrop } from "@/hooks/use-file-drop";
/** Visiting /demo opens a bundled photo instead of the empty state. */
const startup = location.pathname === "/demo" ? "/images/demo.jpg" : undefined;
-export default function App() {
+export function App() {
const { workspace, controls, drafts } = useWorkspace(startup);
useFileDrop(controls.openFiles);
const state = useStore(workspace.state);
diff --git a/src/app/loaders/camera-raw-xmp.ts b/src/app/loaders/camera-raw-xmp.ts
index ebd1e70..4796ea8 100644
--- a/src/app/loaders/camera-raw-xmp.ts
+++ b/src/app/loaders/camera-raw-xmp.ts
@@ -7,8 +7,8 @@ import {
isCameraRawXmp,
readCameraRawXmp,
} from "@/features/camera-raw-xmp/xmp";
-import { setDetails } from "@/features/details/edits";
-import { validateDetails } from "@/features/details/model";
+import { detailsChange, setDetails } from "@/features/details/edits";
+import { parse } from "@/lib/parse";
import type { FileLoader } from "./registry";
function toAdjustments(xmp: CameraRawXmp): Partial<Adjustments> {
@@ -28,7 +28,7 @@ function toAdjustments(xmp: CameraRawXmp): Partial<Adjustments> {
}
function applyClarity(document: EditorDocument, clarity: number) {
- validateDetails({ clarity });
+ parse(detailsChange, { clarity }, "Invalid detail adjustment");
const scene = document.scene.getState();
if (
clarity === 0 &&
diff --git a/src/app/loaders/image.ts b/src/app/loaders/image.ts
index 9ec6f22..3f5bee3 100644
--- a/src/app/loaders/image.ts
+++ b/src/app/loaders/image.ts
@@ -2,7 +2,7 @@ import type { Gpu } from "vgpu";
import { createImageLayer } from "@/app/editor/layers";
import type { Workspace } from "@/app/workspace";
import { createDocument, createResources } from "@/core/document";
-import decode, { canDecode } from "@/core/image/decode";
+import { canDecode, decode } from "@/core/image/decode";
import { imageFrame } from "@/core/image/frame";
async function loadDocument(gpu: Gpu, file: File) {
diff --git a/src/app/loaders/scene.ts b/src/app/loaders/scene.ts
index 30f655d..a35f647 100644
--- a/src/app/loaders/scene.ts
+++ b/src/app/loaders/scene.ts
@@ -3,8 +3,7 @@ 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 { decode } from "@/core/image/decode";
import type { FileLoader } from "./registry";
export const sceneExtension = ".openlight";
@@ -19,6 +18,7 @@ export function isSceneFile(file: 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 { writeZip } = await import("@/lib/zip");
const archive = await writeZip([
{
name: "scene.json",
@@ -36,6 +36,7 @@ export async function openSceneFile(
file: Blob,
decode: (file: File) => Promise<ImageSource>,
) {
+ const { readZip } = await import("@/lib/zip");
const entries = await readZip(file, inflateLimit);
const json = entries.get("scene.json");
if (!json) {
diff --git a/src/app/scene-file.ts b/src/app/scene-file.ts
index 5f25bd8..042c449 100644
--- a/src/app/scene-file.ts
+++ b/src/app/scene-file.ts
@@ -1,31 +1,32 @@
+import { z } from "zod/mini";
import {
createDocument,
createResources,
type EditorDocument,
type ProcessingLayer,
type Scene,
+ walkLayers,
} from "@/core/document";
-import type { ImageSource, WhiteBalance } from "@/core/image";
-import { validateFrame } from "@/core/image/frame";
+import type { ImageSource } from "@/core/image";
+import { frameSchema } from "@/core/image/frame";
import {
+ adjustmentsSchema,
defaultAdjustments,
- validateAdjustments,
+ exposureSchema,
} from "@/features/adjustments/model";
-import { defaultMixer, validateMixer } from "@/features/color-mixer/model";
-import { defaultDetails, validateDetails } from "@/features/details/model";
-import { defaultFill, validateFill } from "@/features/fill/model";
-import { validateHealPatch } from "@/features/heal/model";
+import { defaultMixer, mixerSchema } from "@/features/color-mixer/model";
+import { defaultDetails, detailsSchema } from "@/features/details/model";
+import { defaultFill, fillSchema } from "@/features/fill/model";
+import { healPatchSchema } from "@/features/heal/model";
import {
- validateDepth,
- validateExposure,
- validateLayerSettings,
- validateMask,
- validateMaskOperation,
-} from "@/features/layers/edits";
-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";
+ layerSettings,
+ maskOperation,
+ maskSchema,
+} from "@/features/layers/model";
+import { curveSchema } from "@/features/tone-curves/curve";
+import { defaultVignette, vignetteSchema } from "@/features/vignette/model";
+import { whiteBalanceSchema } from "@/features/white-balance/edits";
+import { parse, withDefaults } from "@/lib/parse";
/** Raised only when older files can no longer load as written; a parameter added later takes its default. */
const version = 1;
@@ -52,184 +53,158 @@ export function snapshotScene(document: EditorDocument) {
return { json, files: new Map([[source, file]]) };
}
-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.");
- }
- ids.add(id);
-}
-
-/** Parameters missing from a group take their defaults, so older files load after the group gains one. */
-function complete<T extends object>(
- defaults: T,
- value: Partial<T> | undefined,
- validate: (value: T) => void,
-) {
- const merged = { ...defaults, ...value };
- validate(merged);
- return merged;
-}
-
-/** Absolute white balance applies only to RAW images, which fall back to their as-shot balance. */
-function readWhiteBalance(
- balance: WhiteBalance | undefined,
- asShot: WhiteBalance | undefined,
-) {
- if (!asShot || !balance) {
- return asShot;
- }
- const whiteBalance = { temperature: balance.temperature, tint: balance.tint };
- validateWhiteBalance(whiteBalance, asShot);
- return whiteBalance;
-}
+const id = z.string().check(z.minLength(1));
+const adjustments = withDefaults(defaultAdjustments, adjustmentsSchema);
-function readLayer(layer: ProcessingLayer, ids: Set<string>): ProcessingLayer {
- const { id, name, visible, opacity, children } = layer;
- readId(id, ids);
- validateLayerSettings({ name, visible, opacity });
- if (!Array.isArray(children)) {
- throw Error("Layer children must be a list.");
- }
- const base = {
- id,
- name,
- visible,
- opacity,
- children: children.map((child) => readLayer(child, ids)),
- };
- switch (layer.kind) {
- case "exposure":
- validateExposure(layer.exposure);
- return { ...base, kind: layer.kind, exposure: layer.exposure };
- case "details":
- return {
+/** Layers nest two levels, so a child's own children must be empty. */
+function processingLayer(children: z.ZodMiniType<readonly ProcessingLayer[]>) {
+ const base = { id, ...layerSettings.shape, children };
+ return z.discriminatedUnion(
+ "kind",
+ [
+ z.object({
...base,
- kind: layer.kind,
- details: complete(defaultDetails, layer.details, validateDetails),
- };
- case "vignette":
- return {
+ kind: z.literal("exposure"),
+ exposure: exposureSchema,
+ }),
+ z.object({
...base,
- kind: layer.kind,
- vignette: complete(defaultVignette, layer.vignette, validateVignette),
- };
- case "color-mixer":
- return {
+ kind: z.literal("details"),
+ details: withDefaults(defaultDetails, detailsSchema),
+ }),
+ z.object({
...base,
- kind: layer.kind,
- colorMixer: complete(defaultMixer, layer.colorMixer, validateMixer),
- };
- case "fill":
- return {
+ kind: z.literal("vignette"),
+ vignette: withDefaults(defaultVignette, vignetteSchema),
+ }),
+ z.object({
...base,
- kind: layer.kind,
- fill: complete(defaultFill, layer.fill, validateFill),
- };
- case "heal":
- if (!Array.isArray(layer.patches)) {
- throw Error("A Healing layer needs a list of patches.");
- }
- for (const patch of layer.patches) {
- readId(patch.id, ids);
- validateHealPatch(patch);
- }
- return { ...base, kind: layer.kind, patches: layer.patches };
- case "mask":
- validateMaskOperation(layer.operation);
- validateMask(layer.mask);
- validateCurve(layer.toneCurve);
- return {
+ kind: z.literal("color-mixer"),
+ colorMixer: withDefaults(defaultMixer, mixerSchema),
+ }),
+ z.object({
...base,
- kind: layer.kind,
- operation: layer.operation,
- mask: layer.mask,
- adjustments: complete(
- defaultAdjustments,
- layer.adjustments,
- validateAdjustments,
- ),
- toneCurve: layer.toneCurve,
- };
- default: {
- const unknown: never = layer;
- throw Error(`Unknown layer kind: ${Reflect.get(unknown, "kind")}.`);
- }
- }
+ kind: z.literal("fill"),
+ fill: withDefaults(defaultFill, fillSchema),
+ }),
+ z.object({
+ ...base,
+ kind: z.literal("heal"),
+ patches: z.array(healPatchSchema),
+ }),
+ z.object({
+ ...base,
+ kind: z.literal("mask"),
+ operation: maskOperation,
+ mask: maskSchema,
+ adjustments,
+ toneCurve: curveSchema,
+ }),
+ ],
+ {
+ error: (issue) =>
+ issue.code === "invalid_union"
+ ? `Unknown layer kind: ${Reflect.get(Object(issue.input), "kind")}`
+ : undefined,
+ },
+ );
+}
+
+function empty(message: string) {
+ return z.pipe(
+ z.array(z.unknown()).check(z.maxLength(0, message)),
+ z.transform((): ProcessingLayer[] => []),
+ );
}
+const child = processingLayer(
+ empty("Layers support two levels: a parent and its children"),
+);
+
+const imageLayer = z.object({
+ kind: z.literal("image"),
+ id,
+ name: layerSettings.shape.name,
+ source: id,
+ whiteBalance: z.optional(
+ z.object({ temperature: z.number(), tint: z.number() }),
+ ),
+ adjustments,
+ toneCurve: curveSchema,
+ children: empty("The image layer cannot contain layers"),
+});
+
+const sceneSchema = z
+ .object({
+ frame: frameSchema,
+ layers: z.tuple([imageLayer], processingLayer(z.array(child))),
+ })
+ .check(
+ z.refine((scene) => {
+ const ids = Array.from(walkLayers(scene.layers), ({ layer }) => [
+ layer.id,
+ ...(layer.kind === "heal"
+ ? layer.patches.map((patch) => patch.id)
+ : []),
+ ]).flat();
+ return new Set(ids).size === ids.length;
+ }, "Layer and patch IDs must be unique"),
+ );
+
+const notScene = "This file doesn't contain an OpenLight scene";
+const header = z.object(
+ {
+ format: z.literal("openlight", notScene),
+ version: z.int().check(z.minimum(1)),
+ },
+ notScene,
+);
+const savedSchema = z.extend(header, {
+ sources: z.record(
+ z.string(),
+ z.object({ name: z.string(), type: z.string() }),
+ ),
+ scene: sceneSchema,
+});
+
/**
* Opens a saved scene as a new document, validating every value as the edit that made it.
* Scene files and drafts both open through here; `files` holds each source's bytes by ID.
*/
export async function openScene(
- saved: SceneJson,
+ saved: unknown,
files: ReadonlyMap<string, Blob>,
decode: (file: File) => Promise<ImageSource>,
) {
- if (saved?.format !== "openlight") {
- throw Error("This file doesn't contain an OpenLight scene.");
- }
- if (!Number.isInteger(saved.version) || saved.version < 1) {
- throw Error("Invalid scene version.");
- }
- if (saved.version > version) {
+ if (parse(header, saved, "Invalid scene").version > version) {
throw Error("This scene needs a newer version of OpenLight.");
}
- const { frame, layers } = saved.scene ?? {};
- validateFrame(frame);
- if (!Array.isArray(layers) || layers[0]?.kind !== "image") {
- throw Error("A scene must start with its image layer.");
- }
- const [image, ...rest] = layers;
- const ids = new Set<string>();
- readId(image.id, ids);
- validateLayerSettings({ name: image.name });
- if (image.children?.length) {
- throw Error("The image layer cannot contain layers.");
- }
- validateCurve(image.toneCurve);
- const adjustments = complete(
- defaultAdjustments,
- image.adjustments,
- validateAdjustments,
- );
- const children = rest.map((layer) => readLayer(layer, ids));
- validateDepth(children);
- const source = saved.sources?.[image.source];
+ const { sources, scene } = parse(savedSchema, saved, "Invalid scene");
+ const [image, ...layers] = scene.layers;
+ const source = sources[image.source];
const data = files.get(image.source);
- if (typeof source?.name !== "string" || !data) {
+ if (!source || !data) {
throw Error("The scene's image is missing.");
}
const sourceFile = new File([data], source.name, { type: source.type });
const decoded = await decode(sourceFile);
+ const asShot = decoded.raw?.asShot;
+ // Absolute white balance applies only to RAW images, which fall back to their as-shot balance.
+ const whiteBalance =
+ asShot && image.whiteBalance
+ ? parse(
+ whiteBalanceSchema(asShot),
+ image.whiteBalance,
+ "Invalid RAW white balance",
+ )
+ : asShot;
const resources = createResources();
try {
- const id = resources.add(sourceFile, decoded, image.source);
+ resources.add(sourceFile, decoded, image.source);
return createDocument(
{
- frame: {
- center: frame.center,
- size: frame.size,
- rotation: frame.rotation,
- angle: frame.angle,
- scale: frame.scale,
- },
- layers: [
- {
- kind: "image",
- id: image.id,
- name: image.name,
- source: id,
- whiteBalance: readWhiteBalance(
- image.whiteBalance,
- decoded.raw?.asShot,
- ),
- adjustments,
- toneCurve: image.toneCurve,
- children: [],
- },
- ...children,
- ],
+ frame: scene.frame,
+ layers: [{ ...image, whiteBalance }, ...layers],
},
resources,
);
diff --git a/src/components/editor/brush-canvas.tsx b/src/components/editor/brush-canvas.tsx
index cc7a654..12ec5ab 100644
--- a/src/components/editor/brush-canvas.tsx
+++ b/src/components/editor/brush-canvas.tsx
@@ -9,7 +9,9 @@ import {
import type { BrushStroke, StrokePoint } from "@/core/document";
import type { Point } from "@/core/image/frame";
import { useShortcuts } from "@/hooks/use-shortcuts";
+import { blurActive } from "@/lib/dom";
import { useBrushTool } from "./brush-tool";
+import { CanvasHint } from "./canvas-hint";
import { useDocumentMapping } from "./mapping";
import { useDocument } from "./session";
import { useViewport } from "./viewport";
@@ -20,7 +22,7 @@ type Stroke = {
/** The last screen position, handed to the viewport when a second finger turns the stroke into a pinch. */
client: Point;
/** The viewport bounds measured once; pointer capture keeps them valid for the drag. */
- box: DOMRect | undefined;
+ box: DOMRect;
pending: StrokePoint[];
frame?: number;
};
@@ -72,7 +74,7 @@ export function BrushCanvas({
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string>();
const gradient = useId();
- function point(event: PointerLike, box: DOMRect | undefined): StrokePoint {
+ function point(event: PointerLike, box: DOMRect): StrokePoint {
const [x, y] = mapping.toDocument(event.clientX, event.clientY, box);
return [x, y, event.pointerType === "pen" ? event.pressure : 1];
}
@@ -181,10 +183,10 @@ export function BrushCanvas({
if (event.button !== 0 || !event.isPrimary || camera.panMode) {
return;
}
- if (busy) {
+ const box = camera.ref.current?.getBoundingClientRect();
+ if (busy || !box) {
return;
}
- const box = camera.ref.current?.getBoundingClientRect();
const first = point(event, box);
if (event.altKey && onPickSource) {
onPickSource([first[0], first[1]]);
@@ -216,9 +218,7 @@ export function BrushCanvas({
event.preventDefault();
event.stopPropagation();
event.currentTarget.setPointerCapture(event.pointerId);
- if (window.document.activeElement instanceof HTMLElement) {
- window.document.activeElement.blur();
- }
+ blurActive();
}
function move(event: PointerEvent<HTMLDivElement>) {
const bounds = event.currentTarget.getBoundingClientRect();
@@ -315,11 +315,7 @@ export function BrushCanvas({
/>
</svg>
)}
- {status && (
- <p className="pointer-events-none absolute bottom-3 left-3 rounded-full bg-neutral-800/80 px-3 py-1.5 text-white backdrop-blur-sm">
- {status}
- </p>
- )}
+ {status && <CanvasHint>{status}</CanvasHint>}
</div>
);
}
diff --git a/src/components/editor/canvas-hint.tsx b/src/components/editor/canvas-hint.tsx
new file mode 100644
index 0000000..27aed0e
--- /dev/null
+++ b/src/components/editor/canvas-hint.tsx
@@ -0,0 +1,10 @@
+import type { ReactNode } from "react";
+
+/** A short instruction in the canvas corner that never takes the pointer. */
+export function CanvasHint({ children }: { children: ReactNode }) {
+ return (
+ <p className="pointer-events-none absolute bottom-3 left-3 rounded-full bg-neutral-800/80 px-3 py-1.5 text-white backdrop-blur-sm">
+ {children}
+ </p>
+ );
+}
diff --git a/src/components/editor/image.tsx b/src/components/editor/image.tsx
index 87b1126..107d897 100644
--- a/src/components/editor/image.tsx
+++ b/src/components/editor/image.tsx
@@ -1,9 +1,10 @@
-import { useEffect, useMemo } from "react";
+import { useEffect } from "react";
import type { Target } from "vgpu";
import { useCanvas, useFrame, useGpu } from "vgpu-react";
import { useStore } from "zustand";
import type { ImageFrame } from "@/core/image/frame";
import { createDisplay } from "@/core/renderer";
+import { useDisposable } from "@/hooks/use-disposable";
import { fitScale } from "@/hooks/use-pan-zoom";
import { useRenderer } from "./pipeline";
import { useDocument, useScene } from "./session";
@@ -32,8 +33,7 @@ export function Image({
useScene((scene) => scene.layers[0].source),
).image.size;
const renderer = useRenderer();
- const display = useMemo(() => createDisplay(gpu), [gpu]);
- useEffect(() => () => display.dispose(), [display]);
+ const display = useDisposable(() => createDisplay(gpu), [gpu]);
const render = useFrame((frame) => {
const before = original && renderer[original]();
const target = typeof image === "string" ? renderer[image]() : image;
diff --git a/src/components/editor/mapping.ts b/src/components/editor/mapping.ts
index ac43e0c..0b4960f 100644
--- a/src/components/editor/mapping.ts
+++ b/src/components/editor/mapping.ts
@@ -13,10 +13,7 @@ export function useDocumentMapping() {
/** Source pixels per viewport pixel along the frame's axes. */
pixelsPerViewportPixel: Math.abs(frame.scale[0]) / scale,
/** The document position under client coordinates, given the viewport bounds. */
- toDocument(clientX: number, clientY: number, box?: DOMRect): Point {
- if (!box) {
- return frame.center;
- }
+ toDocument(clientX: number, clientY: number, box: DOMRect): Point {
const offset = sourceOffset(
frame,
(clientX - box.left - box.width / 2 - view.pan[0]) / scale,
diff --git a/src/components/editor/panel.tsx b/src/components/editor/panel.tsx
index b86fa56..d40009b 100644
--- a/src/components/editor/panel.tsx
+++ b/src/components/editor/panel.tsx
@@ -1,52 +1,47 @@
-import { cn } from "cn";
-import type { KeyboardEventHandler, ReactNode } from "react";
+import type { ComponentProps, ReactNode } from "react";
import { CloseIcon } from "@/components/icons/close";
-import Button from "@/components/ui/button";
-import ResizablePanel from "@/components/ui/resizable-panel";
+import { IconButton } from "@/components/ui/button";
+import { ResizablePanel } from "@/components/ui/resizable-panel";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useEditorSession } from "./session";
-/** The resizable side panel: a fixed header, scrolling controls, and a fixed footer. */
+/**
+ * The resizable side panel. Its sections stack in the order written, with a divider between each;
+ * give one a PanelBody to scroll. An inert panel shows its contents dimmed and unresponsive.
+ */
export function EditorPanel({
- header,
- children,
- footer,
inert,
- onKeyDown,
-}: {
- header?: ReactNode;
- children: ReactNode;
- footer?: ReactNode;
- /** Contents shown but unresponsive, as when the document is a placeholder; the panel still scrolls. */
- inert?: boolean;
- onKeyDown?: KeyboardEventHandler<HTMLElement>;
-}) {
+ children,
+ ...props
+}: ComponentProps<"aside">) {
const { width, onWidthChange } = useEditorSession();
return (
- <ResizablePanel
- width={width}
- onWidthChange={onWidthChange}
- className={cn("flex min-h-0 flex-col", inert && "opacity-50")}
- onKeyDown={onKeyDown}
- >
- <div inert={inert} className="contents">
- {header}
- </div>
- <ScrollArea
- fade
- className="flex-1"
- role="region"
- aria-label="Editor controls"
+ <ResizablePanel width={width} onWidthChange={onWidthChange} {...props}>
+ <div
+ inert={inert}
+ data-inert={inert}
+ className="flex h-full min-h-0 flex-col divide-y divide-black data-[inert=true]:opacity-50"
>
- <div inert={inert}>{children}</div>
- </ScrollArea>
- <div inert={inert} className="contents">
- {footer}
+ {children}
</div>
</ResizablePanel>
);
}
+/** The panel section that takes the remaining height and scrolls. */
+export function PanelBody({ children }: { children: ReactNode }) {
+ return (
+ <ScrollArea
+ fade
+ className="flex-1"
+ role="region"
+ aria-label="Editor controls"
+ >
+ {children}
+ </ScrollArea>
+ );
+}
+
/** A title with optional actions and a close button, sized to the panel row. */
export function PanelHeader({
title,
@@ -62,15 +57,9 @@ export function PanelHeader({
<h2 className="flex-1 font-medium text-neutral-200">{title}</h2>
{children}
{onClose && (
- <Button
- variant="ghost"
- size="icon"
- aria-label="Close"
- title="Close (Esc)"
- onClick={onClose}
- >
+ <IconButton label="Close" shortcut="Esc" onClick={onClose}>
<CloseIcon className="size-4" />
- </Button>
+ </IconButton>
)}
</div>
);
diff --git a/src/components/editor/pipeline.tsx b/src/components/editor/pipeline.tsx
index 7e2c497..e6d6aff 100644
--- a/src/components/editor/pipeline.tsx
+++ b/src/components/editor/pipeline.tsx
@@ -3,7 +3,6 @@ import {
type ReactNode,
useContext,
useEffect,
- useMemo,
useState,
} from "react";
import type { Gpu } from "vgpu";
@@ -12,6 +11,7 @@ import { Notice } from "@/components/ui/notice";
import { adjustmentTarget } from "@/core/document";
import type { ImageSource } from "@/core/image";
import type { createRenderer } from "@/core/renderer";
+import { useDisposable } from "@/hooks/use-disposable";
import { useDocument, useScene } from "./session";
const RendererContext = createContext<ReturnType<typeof createRenderer> | null>(
@@ -50,7 +50,7 @@ export function RendererProvider({
const document = useDocument();
const sourceId = useScene((scene) => scene.layers[0].source);
const source = document.resources.get(sourceId);
- const renderer = useMemo(
+ const renderer = useDisposable(
() => createRenderer(gpu, source),
[gpu, source, createRenderer],
);
@@ -97,7 +97,6 @@ export function RendererProvider({
unsubscribeScene();
unsubscribeSelection();
unsubscribeHistory();
- renderer.dispose();
};
}, [renderer, document]);
diff --git a/src/components/editor/viewport.tsx b/src/components/editor/viewport.tsx
index 2fdb3ab..a936150 100644
--- a/src/components/editor/viewport.tsx
+++ b/src/components/editor/viewport.tsx
@@ -1,7 +1,8 @@
import { createContext, type ReactNode, useContext } from "react";
import { Canvas } from "vgpu-react";
import { Icon } from "@/components/icons/icon";
-import Button from "@/components/ui/button";
+import { Button, IconButton } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
import type { Point } from "@/core/image/frame";
import { usePanZoom } from "@/hooks/use-pan-zoom";
import { useEditorSession } from "./session";
@@ -24,53 +25,54 @@ function ZoomControl() {
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">
- <Button
- variant="ghost"
- aria-label="Zoom out"
- className="flex size-6 items-center justify-center rounded-full p-0"
+ <IconButton
+ label="Zoom out"
+ side="top"
+ className="size-6 rounded-full p-0"
onClick={() => zoomBy(1 / 1.25)}
>
<Icon viewBox="0 0 20 20" className="size-3.5">
<path d="M5 10h10" />
</Icon>
- </Button>
- <Button
- variant="ghost"
- 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={() =>
- fitted ? zoomTo(1 / (scale * devicePixelRatio)) : resetView()
- }
- >
- {percent}%
- </Button>
- <Button
- variant="ghost"
- aria-label="Zoom in"
- className="flex size-6 items-center justify-center rounded-full p-0"
+ </IconButton>
+ <Tooltip content={fitted ? "Zoom to 100%" : "Fit to view"} side="top">
+ <Button
+ variant="ghost"
+ className="min-w-14 rounded-full px-1 py-0.5 text-neutral-200 tabular-nums"
+ onClick={() =>
+ fitted ? zoomTo(1 / (scale * devicePixelRatio)) : resetView()
+ }
+ >
+ {percent}%
+ </Button>
+ </Tooltip>
+ <IconButton
+ label="Zoom in"
+ side="top"
+ className="size-6 rounded-full p-0"
onClick={() => zoomBy(1.25)}
>
<Icon viewBox="0 0 20 20" className="size-3.5">
<path d="M10 5v10M5 10h10" />
</Icon>
- </Button>
+ </IconButton>
</div>
</div>
);
}
+/**
+ * The canvas region: a camera over `size` for everything inside, and the zoom control.
+ * Put the pannable content in a ViewportStage; other children float over it without panning.
+ */
export function EditorViewport({
size,
constrain = true,
children,
- overlay,
- tools,
}: {
size: Point;
constrain?: boolean;
children: ReactNode;
- overlay?: ReactNode;
- tools?: ReactNode;
}) {
const { camera } = useEditorSession();
const viewport = usePanZoom(camera, size, { constrain, padding: 24 });
@@ -80,18 +82,24 @@ export function EditorViewport({
aria-label="Image canvas"
>
<Viewport value={viewport}>
- <div
- ref={viewport.ref}
- {...viewport.handlers}
- data-pan-mode={viewport.panMode}
- className="relative size-full cursor-grab touch-none active:cursor-grabbing data-[pan-mode=true]:[&_*]:cursor-grab! data-[pan-mode=true]:active:[&_*]:cursor-grabbing!"
- >
- <Canvas className="absolute inset-0 size-full">{children}</Canvas>
- {tools}
- </div>
- {overlay}
+ {children}
<ZoomControl />
</Viewport>
</section>
);
}
+
+/** The area that pans and zooms: the GPU canvas, with tool overlays drawn over it as siblings. */
+export function ViewportStage({ children }: { children: ReactNode }) {
+ const viewport = useViewport();
+ return (
+ <div
+ ref={viewport.ref}
+ {...viewport.handlers}
+ data-pan-mode={viewport.panMode}
+ className="relative size-full cursor-grab touch-none active:cursor-grabbing data-[pan-mode=true]:[&_*]:cursor-grab! data-[pan-mode=true]:active:[&_*]:cursor-grabbing!"
+ >
+ <Canvas className="absolute inset-0 size-full">{children}</Canvas>
+ </div>
+ );
+}
diff --git a/src/components/icons/color-mixer.tsx b/src/components/icons/color-mixer.tsx
new file mode 100644
index 0000000..d23f8ea
--- /dev/null
+++ b/src/components/icons/color-mixer.tsx
@@ -0,0 +1,11 @@
+import { Icon, type IconProps } from "./icon";
+
+export function ColorMixerIcon(props: IconProps) {
+ return (
+ <Icon {...props}>
+ <circle cx="9" cy="9" r="5" />
+ <circle cx="15" cy="9" r="5" />
+ <circle cx="12" cy="15" r="5" />
+ </Icon>
+ );
+}
diff --git a/src/components/icons/details.tsx b/src/components/icons/details.tsx
new file mode 100644
index 0000000..1192b11
--- /dev/null
+++ b/src/components/icons/details.tsx
@@ -0,0 +1,9 @@
+import { Icon, type IconProps } from "./icon";
+
+export function DetailsIcon(props: IconProps) {
+ return (
+ <Icon {...props}>
+ <path d="m4 18 8-14 8 14H4Zm8-8v6" />
+ </Icon>
+ );
+}
diff --git a/src/components/icons/exposure.tsx b/src/components/icons/exposure.tsx
new file mode 100644
index 0000000..0a76bc7
--- /dev/null
+++ b/src/components/icons/exposure.tsx
@@ -0,0 +1,10 @@
+import { Icon, type IconProps } from "./icon";
+
+export function ExposureIcon(props: IconProps) {
+ return (
+ <Icon {...props}>
+ <circle cx="12" cy="12" r="8" />
+ <path d="M12 4a8 8 0 0 1 0 16Z" fill="currentColor" stroke="none" />
+ </Icon>
+ );
+}
diff --git a/src/components/icons/vignette.tsx b/src/components/icons/vignette.tsx
new file mode 100644
index 0000000..88c6e7c
--- /dev/null
+++ b/src/components/icons/vignette.tsx
@@ -0,0 +1,10 @@
+import { Icon, type IconProps } from "./icon";
+
+export function VignetteIcon(props: IconProps) {
+ return (
+ <Icon {...props}>
+ <circle cx="12" cy="12" r="8" />
+ <circle cx="12" cy="12" r="3" />
+ </Icon>
+ );
+}
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 71db322..e8e1f25 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -1,16 +1,17 @@
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
import type { ComponentProps } from "react";
+import { Tooltip } from "./tooltip";
const button = cva(
- "cursor-pointer rounded-md transition-colors focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-neutral-400/80",
+ "cursor-pointer rounded-md transition-colors focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-neutral-400/80 disabled:pointer-events-none disabled:opacity-40",
{
variants: {
variant: {
default:
"bg-neutral-700 text-neutral-100 shadow-ridge hover:bg-neutral-600 active:bg-neutral-700 active:shadow-groove",
ghost:
- "text-neutral-400 hover:bg-neutral-700/50 hover:text-neutral-100 active:bg-neutral-700",
+ "text-neutral-400 hover:bg-neutral-700/50 hover:text-neutral-100 active:bg-neutral-700 data-popup-open:bg-neutral-700/50 data-popup-open:text-neutral-100",
},
/** Both sizes pad 6 px vertically, so text and 16 px icons produce the same height. */
size: {
@@ -22,7 +23,7 @@ const button = cva(
},
);
-export default function Button({
+export function Button({
className,
variant,
size,
@@ -36,3 +37,21 @@ export default function Button({
/>
);
}
+
+/** A ghost icon button; its label names it for assistive technology and shows as its tooltip. */
+export function IconButton({
+ label,
+ shortcut,
+ side,
+ ...props
+}: ComponentProps<typeof Button> & {
+ label: string;
+ shortcut?: string;
+ side?: ComponentProps<typeof Tooltip>["side"];
+}) {
+ return (
+ <Tooltip content={label} shortcut={shortcut} side={side}>
+ <Button variant="ghost" size="icon" aria-label={label} {...props} />
+ </Tooltip>
+ );
+}
diff --git a/src/components/ui/chip.tsx b/src/components/ui/chip.tsx
new file mode 100644
index 0000000..805052f
--- /dev/null
+++ b/src/components/ui/chip.tsx
@@ -0,0 +1,42 @@
+import { cva, type VariantProps } from "class-variance-authority";
+import { cn } from "cn";
+import type { ComponentProps } from "react";
+
+const chip = cva(
+ "shrink-0 cursor-pointer rounded-full px-2.5 whitespace-nowrap text-neutral-400 transition-colors hover:bg-white/10 hover:text-neutral-100 focus-visible:outline-1 focus-visible:outline-neutral-400/80 aria-pressed:bg-white/15 aria-pressed:text-neutral-100 data-popup-open:bg-white/15 data-popup-open:text-neutral-100",
+ {
+ variants: {
+ /** "segment" sits inside a ChipGroup. */
+ size: {
+ default: "h-7 pointer-coarse:h-9",
+ segment: "h-6 pointer-coarse:h-8",
+ },
+ },
+ defaultVariants: { size: "default" },
+ },
+);
+
+/** A pill button for the bar over the canvas; `aria-pressed` shows it on. */
+export function Chip({
+ className,
+ size,
+ ...props
+}: ComponentProps<"button"> & VariantProps<typeof chip>) {
+ return (
+ <button
+ type="button"
+ className={cn(chip({ size }), className)}
+ {...props}
+ />
+ );
+}
+
+/** Segmented chips, one of which is pressed. */
+export function ChipGroup({ className, ...props }: ComponentProps<"fieldset">) {
+ return (
+ <fieldset
+ className={cn("flex gap-0.5 rounded-full bg-white/5 p-0.5", className)}
+ {...props}
+ />
+ );
+}
diff --git a/src/components/ui/menu-surface.tsx b/src/components/ui/menu-surface.tsx
deleted file mode 100644
index 1d44cb5..0000000
--- a/src/components/ui/menu-surface.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { type AriaRole, type ReactNode, useId, useRef, useState } from "react";
-
-function focusChoice(surface: HTMLElement) {
- const selected = surface.querySelector<HTMLElement>('[aria-selected="true"]');
- const first = surface.querySelector<HTMLElement>("button:not(:disabled)");
- (selected ?? first)?.focus();
-}
-
-function moveFocus(menu: HTMLElement, direction: number) {
- const items = [
- ...menu.querySelectorAll<HTMLButtonElement>("button:not(:disabled)"),
- ];
- const current = items.indexOf(document.activeElement as HTMLButtonElement);
- const next =
- current < 0 ? 0 : (current + direction + items.length) % items.length;
- items[next]?.focus();
-}
-
-/** Anchored elevated surface shared by command menus and value selectors. */
-export function MenuSurface({
- trigger,
- children,
- role = "menu",
-}: {
- trigger: (id: string, open: boolean) => ReactNode;
- children: ReactNode;
- role?: AriaRole;
-}) {
- const id = useId();
- const popover = useRef<HTMLDivElement>(null);
- const [open, setOpen] = useState(false);
- return (
- <>
- {trigger(id, open)}
- <div
- id={id}
- ref={popover}
- popover="auto"
- onBeforeToggle={(event) => setOpen(event.newState === "open")}
- onToggle={(event) => {
- if (event.newState === "open") {
- requestAnimationFrame(() => {
- const surface = popover.current;
- if (surface?.matches(":popover-open")) focusChoice(surface);
- });
- }
- }}
- className="fixed inset-auto z-50 m-0 mt-1 max-h-[calc(100dvh-1rem)] min-w-40 overflow-y-auto rounded-lg border border-black/60 bg-neutral-800 p-1 text-neutral-200 shadow-float [position-area:bottom_span-left] [position-try-fallbacks:flip-block] [&_button]:w-full [&_button]:rounded-md [&_button]:px-2.5 [&_button]:py-1.5 [&_button]:text-left [&_button:disabled]:text-neutral-600 [&_button:disabled:hover]:bg-transparent [&_button:hover]:bg-white/8"
- >
- {/* biome-ignore lint/a11y/noStaticElementInteractions: delegated interaction serves the dynamic menu or listbox role. */}
- <div
- role={role}
- onClick={(event) => {
- const target = event.target as Element;
- if (target.closest('button[type="submit"]')) {
- popover.current?.hidePopover();
- }
- }}
- onKeyDown={(event) => {
- if (event.key === "ArrowDown" || event.key === "ArrowUp") {
- event.preventDefault();
- moveFocus(
- event.currentTarget,
- event.key === "ArrowDown" ? 1 : -1,
- );
- }
- }}
- >
- {open && children}
- </div>
- </div>
- </>
- );
-}
diff --git a/src/components/ui/menu.tsx b/src/components/ui/menu.tsx
index d3cdc04..7c07009 100644
--- a/src/components/ui/menu.tsx
+++ b/src/components/ui/menu.tsx
@@ -1,52 +1,103 @@
-import { cva } from "class-variance-authority";
-import type { ReactNode } from "react";
-import { MenuSurface } from "./menu-surface";
-
-const trigger = cva(
- "grid shrink-0 place-items-center text-neutral-400 hover:text-neutral-100",
- {
- variants: {
- variant: {
- row: "size-7 rounded-md hover:bg-white/8 pointer-coarse:size-10",
- pill: "h-7 rounded-full px-2.5 hover:bg-white/10 pointer-coarse:h-9",
- },
- },
- },
-);
+import { Menu as Primitive } from "@base-ui/react/menu";
+import { cn } from "cn";
+import { type ComponentProps, type ReactNode, useState } from "react";
+import { Icon } from "@/components/icons/icon";
+import { Button } from "./button";
+import { Chip } from "./chip";
+import { Surface } from "./surface";
+import { Tooltip } from "./tooltip";
/**
- * A button that floats a menu below itself. Submit buttons inside close it; other controls keep it open,
- * so it can hold settings as well as commands. Its children mount only while it is open.
+ * A button that opens a list of commands. The label names the button and shows as its tooltip.
+ * Items mount only while the menu is open. For settings, use a Popover.
*/
export function Menu({
label,
- children,
icon,
variant = "row",
+ children,
}: {
label: string;
- children: ReactNode;
icon: ReactNode;
+ /** "row" sits in a panel row; "pill" sits in the bar over the canvas. */
variant?: "row" | "pill";
+ children: ReactNode;
}) {
+ // The tooltip steps aside while the menu is open, so Escape closes the menu.
+ const [open, setOpen] = useState(false);
return (
- <MenuSurface
- trigger={(id, open) => (
- <button
- type="button"
+ <Primitive.Root open={open} onOpenChange={setOpen}>
+ <Tooltip content={label} disabled={open}>
+ <Primitive.Trigger
aria-label={label}
- aria-expanded={open}
- aria-haspopup="menu"
- aria-controls={id}
- title={label}
- popoverTarget={id}
- className={trigger({ variant })}
+ render={
+ variant === "pill" ? (
+ <Chip className="grid place-items-center px-2" />
+ ) : (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="pointer-coarse:size-10"
+ />
+ )
+ }
>
{icon}
- </button>
+ </Primitive.Trigger>
+ </Tooltip>
+ <Primitive.Portal>
+ <Primitive.Positioner sideOffset={4} align="end" className="z-50">
+ <Primitive.Popup render={(props) => <Surface {...props} />}>
+ {children}
+ </Primitive.Popup>
+ </Primitive.Positioner>
+ </Primitive.Portal>
+ </Primitive.Root>
+ );
+}
+
+export function MenuItem({
+ className,
+ ...props
+}: ComponentProps<typeof Primitive.Item>) {
+ return (
+ <Primitive.Item
+ className={cn(
+ "flex cursor-default items-center gap-2 rounded-md px-2.5 py-1.5 outline-none select-none data-disabled:text-neutral-600 data-highlighted:bg-white/8",
+ className,
)}
- >
- {children}
- </MenuSurface>
+ {...props}
+ />
+ );
+}
+
+export function MenuSeparator() {
+ return <Primitive.Separator className="mx-1 my-1 h-px bg-white/10" />;
+}
+
+/** An item that opens a nested list of commands beside the menu. */
+export function Submenu({
+ label,
+ children,
+}: {
+ label: string;
+ children: ReactNode;
+}) {
+ return (
+ <Primitive.SubmenuRoot>
+ <Primitive.SubmenuTrigger className="flex cursor-default items-center justify-between gap-4 rounded-md px-2.5 py-1.5 outline-none select-none data-highlighted:bg-white/8 data-popup-open:bg-white/8">
+ {label}
+ <Icon className="size-3 text-neutral-400">
+ <path d="m9 5 7 7-7 7" />
+ </Icon>
+ </Primitive.SubmenuTrigger>
+ <Primitive.Portal>
+ <Primitive.Positioner sideOffset={4} alignOffset={-4} className="z-50">
+ <Primitive.Popup render={(props) => <Surface {...props} />}>
+ {children}
+ </Primitive.Popup>
+ </Primitive.Positioner>
+ </Primitive.Portal>
+ </Primitive.SubmenuRoot>
);
}
diff --git a/src/components/ui/notice.tsx b/src/components/ui/notice.tsx
index 9a40c4f..c25bf50 100644
--- a/src/components/ui/notice.tsx
+++ b/src/components/ui/notice.tsx
@@ -2,7 +2,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
import type { ComponentProps, ReactNode } from "react";
import { CloseIcon } from "@/components/icons/close";
-import Button from "./button";
+import { IconButton } from "./button";
const notice = cva(
"bottom-3 z-50 flex max-w-sm items-start gap-2 rounded-lg border border-black/60 bg-neutral-800 py-2 pl-3 shadow-float",
@@ -61,15 +61,9 @@ export function Notice({
{actions && <div className="flex gap-2">{actions}</div>}
</div>
{onDismiss && (
- <Button
- variant="ghost"
- size="icon"
- aria-label="Dismiss"
- className="mr-1"
- onClick={onDismiss}
- >
+ <IconButton label="Dismiss" className="mr-1" onClick={onDismiss}>
<CloseIcon />
- </Button>
+ </IconButton>
)}
</div>
);
diff --git a/src/components/ui/popover.tsx b/src/components/ui/popover.tsx
new file mode 100644
index 0000000..2d72ce9
--- /dev/null
+++ b/src/components/ui/popover.tsx
@@ -0,0 +1,37 @@
+import { Popover as Primitive } from "@base-ui/react/popover";
+import { type ReactNode, useState } from "react";
+import { Chip } from "./chip";
+import { Surface } from "./surface";
+import { Tooltip } from "./tooltip";
+
+/** A pill that opens settings beside it, such as bar controls that no longer fit. */
+export function Popover({
+ label,
+ icon,
+ children,
+}: {
+ label: string;
+ icon: ReactNode;
+ children: ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ return (
+ <Primitive.Root open={open} onOpenChange={setOpen}>
+ <Tooltip content={label} disabled={open}>
+ <Primitive.Trigger
+ aria-label={label}
+ render={<Chip className="grid place-items-center px-2" />}
+ >
+ {icon}
+ </Primitive.Trigger>
+ </Tooltip>
+ <Primitive.Portal>
+ <Primitive.Positioner sideOffset={4} align="end" className="z-50">
+ <Primitive.Popup render={(props) => <Surface {...props} />}>
+ {children}
+ </Primitive.Popup>
+ </Primitive.Positioner>
+ </Primitive.Portal>
+ </Primitive.Root>
+ );
+}
diff --git a/src/components/ui/resizable-panel.tsx b/src/components/ui/resizable-panel.tsx
index ad7f7f0..f3abacc 100644
--- a/src/components/ui/resizable-panel.tsx
+++ b/src/components/ui/resizable-panel.tsx
@@ -9,7 +9,7 @@ type ResizablePanelProps = ComponentProps<"aside"> & {
};
/** Bottom panel on mobile; right-side panel with a draggable left edge on desktop. */
-export default function ResizablePanel({
+export function ResizablePanel({
width = 320,
onWidthChange,
min = 240,
diff --git a/src/components/ui/select.tsx b/src/components/ui/select.tsx
index 79ad1ae..0ede079 100644
--- a/src/components/ui/select.tsx
+++ b/src/components/ui/select.tsx
@@ -1,7 +1,10 @@
+import { Select as Primitive } from "@base-ui/react/select";
import { cva } from "class-variance-authority";
import { cn } from "cn";
+import { useState } from "react";
import { Icon } from "@/components/icons/icon";
-import { MenuSurface } from "./menu-surface";
+import { Surface } from "./surface";
+import { Tooltip } from "./tooltip";
export type SelectOption<T extends string = string> = {
value: T;
@@ -9,87 +12,102 @@ export type SelectOption<T extends string = string> = {
disabled?: boolean;
};
-type SelectProps<T extends string> = {
- "aria-label": string;
- value?: T;
- options: readonly SelectOption<T>[];
- onChange: (value: T) => void;
- placeholder?: string;
- title?: string;
- className?: string;
- /** "field" sits in a panel; "pill" sits in the bar over the canvas. */
- variant?: "field" | "pill";
-};
-
-const control = cva(
+const trigger = cva(
"inline-flex min-w-0 shrink-0 cursor-pointer items-center justify-between gap-2 text-neutral-200 outline-none focus-visible:ring-1 focus-visible:ring-white/20",
{
variants: {
+ /** "field" sits in a panel; "pill" sits in the bar over the canvas. */
variant: {
field:
"rounded border border-black bg-neutral-900 py-0.5 pr-2 pl-1 shadow-groove",
- pill: "h-7 rounded-full bg-white/10 px-3 hover:bg-white/15 pointer-coarse:h-9",
+ pill: "h-7 rounded-full bg-white/10 px-3 hover:bg-white/15 data-popup-open:bg-white/15 pointer-coarse:h-9",
},
},
},
);
-/** A value selector using the same elevated option surface as row and toolbar menus. */
+/** A value chosen from a list on the shared surface, with the selected option checked. */
export function Select<T extends string>({
"aria-label": label,
value,
options,
onChange,
placeholder,
- title,
+ tooltip,
className,
variant = "field",
-}: SelectProps<T>) {
- const selectedIndex = options.findIndex((option) => option.value === value);
- const selected = options[selectedIndex];
+}: {
+ "aria-label": string;
+ value?: T;
+ options: readonly SelectOption<T>[];
+ onChange: (value: T) => void;
+ placeholder?: string;
+ tooltip?: string;
+ className?: string;
+ variant?: "field" | "pill";
+}) {
+ const [open, setOpen] = useState(false);
+ const control = (
+ <Primitive.Trigger
+ aria-label={label}
+ className={cn(trigger({ variant }), className)}
+ >
+ <Primitive.Value placeholder={placeholder} className="truncate" />
+ <Icon className="size-3 shrink-0 text-neutral-400">
+ <path d="m6 9 6 6 6-6" />
+ </Icon>
+ </Primitive.Trigger>
+ );
return (
- <MenuSurface
- role="listbox"
- trigger={(id, open) => (
- <button
- type="button"
- role="combobox"
- aria-label={label}
- aria-controls={id}
- aria-expanded={open}
- aria-haspopup="listbox"
- title={title}
- popoverTarget={id}
- className={cn(control({ variant }), className)}
- >
- <span className="truncate">{selected?.label ?? placeholder}</span>
- <Icon className="size-3 shrink-0 text-neutral-400">
- <path d="m6 9 6 6 6-6" />
- </Icon>
- </button>
- )}
+ <Primitive.Root
+ items={options}
+ value={value ?? null}
+ open={open}
+ onOpenChange={setOpen}
+ onValueChange={(next) => {
+ const option = options.find((item) => item.value === next);
+ if (option) {
+ onChange(option.value);
+ }
+ }}
>
- {options.map((option, index) => {
- const active = index === selectedIndex;
- return (
- <button
- key={`${option.value}-${index}`}
- type="submit"
- role="option"
- aria-selected={active}
- disabled={option.disabled}
- onClick={() => onChange(option.value)}
- className="flex items-center justify-between gap-4 aria-selected:bg-neutral-700"
+ {tooltip ? (
+ <Tooltip content={tooltip} disabled={open}>
+ {control}
+ </Tooltip>
+ ) : (
+ control
+ )}
+ <Primitive.Portal>
+ <Primitive.Positioner
+ sideOffset={4}
+ alignItemWithTrigger={false}
+ className="z-50"
+ >
+ <Primitive.Popup
+ render={(props) => <Surface {...props} />}
+ className="min-w-(--anchor-width)"
>
- {option.label}
- {active && (
- <Icon className="size-3.5 shrink-0 text-neutral-300">
- <path d="m5 12 4 4L19 6" />
- </Icon>
- )}
- </button>
- );
- })}
- </MenuSurface>
+ <Primitive.List>
+ {options.map((option, index) => (
+ <Primitive.Item
+ key={`${option.value}-${index}`}
+ value={option.value}
+ disabled={option.disabled}
+ className="flex cursor-default items-center justify-between gap-4 rounded-md px-2.5 py-1.5 outline-none select-none data-disabled:text-neutral-600 data-highlighted:bg-white/8 data-selected:bg-neutral-700"
+ >
+ <Primitive.ItemText>{option.label}</Primitive.ItemText>
+ <Primitive.ItemIndicator>
+ <Icon className="size-3.5 shrink-0 text-neutral-300">
+ <path d="m5 12 4 4L19 6" />
+ </Icon>
+ </Primitive.ItemIndicator>
+ </Primitive.Item>
+ ))}
+ </Primitive.List>
+ </Primitive.Popup>
+ </Primitive.Positioner>
+ </Primitive.Portal>
+ </Primitive.Root>
);
}
diff --git a/src/components/ui/spinner.tsx b/src/components/ui/spinner.tsx
index f78c1b0..30e7fd9 100644
--- a/src/components/ui/spinner.tsx
+++ b/src/components/ui/spinner.tsx
@@ -1,10 +1,7 @@
import { cn } from "cn";
import type { ComponentProps } from "react";
-export default function Spinner({
- className,
- ...props
-}: ComponentProps<"div">) {
+export function Spinner({ className, ...props }: ComponentProps<"div">) {
return (
<div
aria-label="Loading"
diff --git a/src/components/ui/surface.tsx b/src/components/ui/surface.tsx
new file mode 100644
index 0000000..9ac7a55
--- /dev/null
+++ b/src/components/ui/surface.tsx
@@ -0,0 +1,19 @@
+import { cn } from "cn";
+import type { ComponentProps } from "react";
+
+/**
+ * The elevated floating panel under menus, selects, and popovers. Render a popup part as one:
+ * `<Menu.Popup render={(props) => <Surface {...props} />} />`.
+ */
+export function Surface({ className, ...props }: ComponentProps<"div">) {
+ return (
+ <div
+ data-surface=""
+ className={cn(
+ "max-h-(--available-height) min-w-40 origin-(--transform-origin) overflow-y-auto rounded-lg border border-black/60 bg-neutral-800 p-1 text-neutral-200 shadow-float outline-none transition-[opacity,scale] duration-100 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsx
index 5900cec..4b3695a 100644
--- a/src/components/ui/tabs.tsx
+++ b/src/components/ui/tabs.tsx
@@ -1,6 +1,6 @@
import { cn } from "cn";
import type { ComponentProps, KeyboardEvent } from "react";
-import Button from "./button";
+import { Button } from "./button";
const steps: Record<string, number> = {
ArrowRight: 1,
diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsx
new file mode 100644
index 0000000..50e126c
--- /dev/null
+++ b/src/components/ui/tooltip.tsx
@@ -0,0 +1,50 @@
+import { Tooltip as Primitive } from "@base-ui/react/tooltip";
+import type { ReactElement, ReactNode } from "react";
+
+/** Shares hover timing, so moving between controls shows their tips without waiting again. */
+export function TooltipProvider({ children }: { children: ReactNode }) {
+ return <Primitive.Provider delay={500}>{children}</Primitive.Provider>;
+}
+
+const mac =
+ typeof navigator !== "undefined" &&
+ /Mac|iPhone|iPad/.test(navigator.platform);
+
+/** Writes "Mod" as the platform's command key. */
+function keys(shortcut: string) {
+ return shortcut.replace("Mod", mac ? "⌘" : "Ctrl");
+}
+
+/**
+ * A short hint on hover or keyboard focus, with an optional shortcut. It wraps one element that
+ * accepts a ref and props, and names nothing for assistive technology; the element keeps its own label.
+ */
+export function Tooltip({
+ content,
+ shortcut,
+ side = "bottom",
+ disabled,
+ children,
+}: {
+ content: ReactNode;
+ shortcut?: string;
+ side?: "top" | "right" | "bottom" | "left";
+ disabled?: boolean;
+ children: ReactElement;
+}) {
+ return (
+ <Primitive.Root disabled={disabled}>
+ <Primitive.Trigger render={children} />
+ <Primitive.Portal>
+ <Primitive.Positioner side={side} sideOffset={6} className="z-50">
+ <Primitive.Popup className="flex max-w-64 origin-(--transform-origin) items-center gap-2 rounded-md border border-black/60 bg-neutral-950 px-2 py-1 text-neutral-200 shadow-float transition-[opacity,scale] duration-100 data-ending-style:opacity-0 data-instant:transition-none data-starting-style:scale-95 data-starting-style:opacity-0">
+ {content}
+ {shortcut && (
+ <kbd className="text-neutral-500">{keys(shortcut)}</kbd>
+ )}
+ </Primitive.Popup>
+ </Primitive.Positioner>
+ </Primitive.Portal>
+ </Primitive.Root>
+ );
+}
diff --git a/src/core/document/brush.ts b/src/core/document/brush.ts
index 1fa1d21..af82563 100644
--- a/src/core/document/brush.ts
+++ b/src/core/document/brush.ts
@@ -1,35 +1,15 @@
-import type { BrushStroke, StrokePoint } from "./scene";
+import { z } from "zod/mini";
+import { unit } from "@/lib/parse";
-export function validPoints(points: readonly StrokePoint[]) {
- return (
- Array.isArray(points) &&
- points.length > 0 &&
- points.every(
- (point) =>
- Array.isArray(point) &&
- point.length === 3 &&
- point.every(Number.isFinite) &&
- point[2] >= 0 &&
- point[2] <= 1,
- )
- );
-}
+/** Finite source-pixel coordinates and a pressure from 0 to 1. */
+export const strokePoints = z
+ .array(z.tuple([z.number(), z.number(), unit]))
+ .check(z.minLength(1));
-export function validateStroke(stroke: BrushStroke) {
- if (
- (stroke.mode !== "paint" && stroke.mode !== "erase") ||
- !Number.isFinite(stroke.size) ||
- stroke.size <= 0 ||
- !Number.isFinite(stroke.feather) ||
- stroke.feather < 0 ||
- stroke.feather > 1 ||
- !Number.isFinite(stroke.flow) ||
- stroke.flow < 0 ||
- stroke.flow > 1 ||
- !validPoints(stroke.points)
- ) {
- throw Error(
- "A stroke needs a paint or erase mode, a positive size, feather and flow from 0 to 1, and finite points with pressure from 0 to 1.",
- );
- }
-}
+export const strokeSchema = z.object({
+ mode: z.enum(["paint", "erase"]),
+ size: z.number().check(z.positive()),
+ feather: unit,
+ flow: unit,
+ points: strokePoints,
+});
diff --git a/src/core/image/decode/heic.ts b/src/core/image/decode/heic.ts
index 93403fc..8a5b98d 100644
--- a/src/core/image/decode/heic.ts
+++ b/src/core/image/decode/heic.ts
@@ -227,7 +227,7 @@ function sizeOf(ispe: Uint8Array) {
return [view.getUint32(4), view.getUint32(8)] as const;
}
-export function parseHeic(bytes: Uint8Array) {
+function parseHeic(bytes: Uint8Array) {
const reader = new Reader(bytes);
const meta = find(reader.boxes(0, reader.bytes.byteLength), "meta");
const boxes = reader.boxes(meta.start + 4, meta.end);
diff --git a/src/core/image/decode/index.ts b/src/core/image/decode/index.ts
index 55bf0e6..52f2aea 100644
--- a/src/core/image/decode/index.ts
+++ b/src/core/image/decode/index.ts
@@ -1,8 +1,6 @@
import type { Gpu, Target } from "vgpu";
import { createImageSource, type ImageSource } from "@/core/image";
-import { decodeHeic } from "./heic";
-import linearize from "./linearize";
-import decodeSvg from "./svg";
+import { linearize } from "./linearize";
import type { Decoder } from "./types";
export type { Target };
@@ -23,8 +21,8 @@ function pixelFormat(load: () => Promise<Decoder>) {
}
const native = pixelFormat(async () => createImageBitmap);
-const svg = pixelFormat(async () => decodeSvg);
-const heic = pixelFormat(async () => decodeHeic);
+const svg = pixelFormat(async () => (await import("./svg")).decodeSvg);
+const heic = pixelFormat(async () => (await import("./heic")).decodeHeic);
const tiff = async (gpu: Gpu, file: File) =>
(await import("./tiff")).decodeTiff(gpu, file);
const raw = async (gpu: Gpu, file: File) =>
@@ -99,10 +97,7 @@ export const accept = formats
export const canDecode = (file: File) => formatOf(file) !== undefined;
/** Decodes the file into a linear rgba16float target: the format's decoder, then its GPU leg. */
-export default async function decode(
- gpu: Gpu,
- file: File,
-): Promise<ImageSource> {
+export async function decode(gpu: Gpu, file: File): Promise<ImageSource> {
const format = formatOf(file);
if (!format) {
throw new Error(`Unsupported image: ${file.name}`);
diff --git a/src/core/image/decode/linearize.ts b/src/core/image/decode/linearize.ts
index 740a434..19c2e2e 100644
--- a/src/core/image/decode/linearize.ts
+++ b/src/core/image/decode/linearize.ts
@@ -1,4 +1,5 @@
-import { effect, frame, type Gpu, target } from "vgpu";
+import { effect, frame, type Gpu, type Target, target } from "vgpu";
+import { weakMemo } from "@/lib/weak-memo";
import shader from "./linearize.wgsl";
import type { Decoded } from "./types";
@@ -6,7 +7,7 @@ type Size = [number, number];
/** Display P3 primaries, which TypeScript's VideoColorPrimaries doesn't list yet. */
const isP3 = (frame?: VideoFrame) =>
- (frame?.colorSpace.primaries as string) === "smpte432";
+ `${frame?.colorSpace.primaries}` === "smpte432";
/** A texture whose format decodes sRGB-encoded bytes to linear when read. */
function staging(gpu: Gpu, size: Size) {
@@ -64,21 +65,30 @@ function stage(gpu: Gpu, decoded: Decoded) {
return texture;
}
+/** One conversion pass per GPU, released with its device. */
+const conversion = weakMemo((gpu: Gpu) => effect(gpu, shader));
+
/** GPU leg for sRGB-encoded decoders: renders the decoded image into a linear Rec.2020 rgba16float target. */
-export default function linearize(gpu: Gpu, decoded: Decoded) {
+export function linearize(gpu: Gpu, decoded: Decoded) {
const frames = "tiles" in decoded ? decoded : undefined;
const rotation = frames?.rotation ?? 0;
const p3 = Number(isP3(frames?.tiles[0]));
const size: Size = [decoded.width, decoded.height];
const source = stage(gpu, decoded);
- const image = target(gpu, {
- size: rotation % 2 ? [size[1], size[0]] : size,
- format: "rgba16float",
- });
- const params = { size, rotation, p3 };
- frame(gpu, (f) =>
- f.pass(image, effect(gpu, shader, { set: { source, params } })),
- );
- source.dispose();
- return image;
+ let image: Target | undefined;
+ try {
+ const output = target(gpu, {
+ size: rotation % 2 ? [size[1], size[0]] : size,
+ format: "rgba16float",
+ });
+ image = output;
+ const params = { size, rotation, p3 };
+ frame(gpu, (f) => f.pass(output, conversion(gpu).set({ source, params })));
+ return output;
+ } catch (error) {
+ image?.color.dispose();
+ throw error;
+ } finally {
+ source.dispose();
+ }
}
diff --git a/src/core/image/decode/raw.ts b/src/core/image/decode/raw.ts
index 2e9cc49..ccb90f0 100644
--- a/src/core/image/decode/raw.ts
+++ b/src/core/image/decode/raw.ts
@@ -1,17 +1,14 @@
-import { createRawDecoder, type RawDecoder } from "raw-webgpu";
+import { createRawDecoder } from "raw-webgpu";
import { type Gpu, type Target, target } from "vgpu";
import { createImageSource } from "@/core/image";
+import { weakMemo } from "@/lib/weak-memo";
-const decoders = new WeakMap<Gpu, RawDecoder>();
+/** One decoder per GPU, released with its device. */
+const decoder = weakMemo((gpu: Gpu) => createRawDecoder(gpu.gpu));
/** Adapts package-owned sensor sources to OpenLight's document and renderer lifetimes. */
export async function decodeRaw(gpu: Gpu, file: File) {
- let decoder = decoders.get(gpu);
- if (!decoder) {
- decoder = createRawDecoder(gpu.gpu);
- decoders.set(gpu, decoder);
- }
- const source = await decoder.load(file);
+ const source = await decoder(gpu).load(file);
let original: Target | undefined;
try {
original = target(gpu, { size: source.size, format: "rgba16float" });
diff --git a/src/core/image/decode/svg.ts b/src/core/image/decode/svg.ts
index 0d2dbf1..93375da 100644
--- a/src/core/image/decode/svg.ts
+++ b/src/core/image/decode/svg.ts
@@ -1,7 +1,7 @@
const fallbackSize = 1024;
/** Rasterizes through an <img>, since SVGs without intrinsic size can't go straight to a bitmap. */
-export default async function decodeSvg(file: Blob) {
+export async function decodeSvg(file: Blob) {
const image = new Image();
image.src = URL.createObjectURL(file);
await image.decode();
diff --git a/src/core/image/decode/tiff.ts b/src/core/image/decode/tiff.ts
index d3f4638..43eae7d 100644
--- a/src/core/image/decode/tiff.ts
+++ b/src/core/image/decode/tiff.ts
@@ -1,15 +1,10 @@
-import {
- type Effect,
- effect,
- frame,
- type Gpu,
- type Target,
- target,
-} from "vgpu";
+import { effect, frame, type Gpu, type Target, target } from "vgpu";
import { createImageSource } from "@/core/image";
+import { weakMemo } from "@/lib/weak-memo";
import shader from "./tiff.wgsl";
-const transfers = new WeakMap<Gpu, Effect>();
+/** One transfer pass per GPU, released with its device. */
+const transfer = weakMemo((gpu: Gpu) => effect(gpu, shader));
/** Transfers package-owned pixels into the editor's owned vgpu target, entirely on GPU. */
export async function decodeTiff(gpu: Gpu, file: File) {
@@ -17,14 +12,12 @@ export async function decodeTiff(gpu: Gpu, file: File) {
const decoded = await decodeTiff(gpu.gpu, file);
let image: Target | undefined;
try {
- const transfer = transfers.get(gpu) ?? effect(gpu, shader);
- transfers.set(gpu, transfer);
const output = target(gpu, { size: decoded.size, format: "rgba16float" });
image = output;
frame(gpu, (frame) =>
frame.pass(
output,
- transfer.set({ source: decoded.texture.createView() }),
+ transfer(gpu).set({ source: decoded.texture.createView() }),
),
);
return createImageSource(image);
diff --git a/src/core/image/frame.ts b/src/core/image/frame.ts
index 40afd2d..ff1cf2d 100644
--- a/src/core/image/frame.ts
+++ b/src/core/image/frame.ts
@@ -1,3 +1,6 @@
+import { z } from "zod/mini";
+import { parse, point } from "@/lib/parse";
+
export type Point = readonly [number, number];
export type ImageFrame = {
center: Point;
@@ -28,23 +31,21 @@ export function frameValues(frame: ImageFrame) {
];
}
-export function validateFrame(frame: ImageFrame) {
- if (
- !frame ||
- ![frame.center, frame.size, frame.scale].every(
- (point) =>
- Array.isArray(point) &&
- point.length === 2 &&
- Number.isFinite(point[0]) &&
- Number.isFinite(point[1]),
- ) ||
- !Number.isFinite(frame.rotation) ||
- !Number.isFinite(frame.angle) ||
- frame.size.some((value) => value < 1) ||
- frame.scale.some((value) => value === 0)
- ) {
- throw new Error("Invalid image frame.");
- }
+const nonzero = z
+ .number()
+ .check(z.refine((value) => value !== 0, "Scale is zero"));
+const side = z.number().check(z.minimum(1));
+
+export const frameSchema = z.object({
+ center: point,
+ size: z.tuple([side, side]),
+ rotation: z.number(),
+ angle: z.number(),
+ scale: z.tuple([nonzero, nonzero]),
+});
+
+export function validateFrame(frame: unknown): ImageFrame {
+ return parse(frameSchema, frame, "Invalid image frame");
}
export function sourceOffset(frame: ImageFrame, x: number, y: number): Point {
diff --git a/src/core/renderer/display/index.ts b/src/core/renderer/display/index.ts
index 0e60741..2387667 100644
--- a/src/core/renderer/display/index.ts
+++ b/src/core/renderer/display/index.ts
@@ -1,6 +1,5 @@
import {
type Buffer,
- type Effect,
effect,
type Frame,
frame,
@@ -22,6 +21,7 @@ import {
gradientParams,
modifierData,
} from "@/core/renderer/blend";
+import { weakMemo } from "@/lib/weak-memo";
import coverageShader from "./coverage.wgsl";
import shader from "./image.wgsl";
@@ -125,8 +125,9 @@ export function createDisplay(gpu: Gpu) {
});
}
-const displays = new WeakMap<Gpu, ReturnType<typeof createDisplay>>();
-const previews = new WeakMap<Gpu, Effect>();
+/** Off-screen drawing keeps one display and one coverage pass per GPU, released with its device. */
+const bitmapDisplay = weakMemo((gpu: Gpu) => createDisplay(gpu));
+const coveragePreview = weakMemo((gpu: Gpu) => effect(gpu, coverageShader));
export type CoverageRegion = { origin: Point; extent: Point };
@@ -137,11 +138,7 @@ export async function renderCoverage(
size: Point,
region: CoverageRegion = { origin: [0, 0], extent: coverage.size },
) {
- let preview = previews.get(gpu);
- if (!preview) {
- preview = effect(gpu, coverageShader);
- previews.set(gpu, preview);
- }
+ const preview = coveragePreview(gpu);
const canvas = new OffscreenCanvas(size[0], size[1]);
const output = surface(gpu, canvas, { size, dpr: 1 });
try {
@@ -163,11 +160,7 @@ export async function renderCoverage(
/** Draws an image into an off-screen canvas of `size` and takes its pixels; one display serves each GPU. */
export async function renderBitmap(gpu: Gpu, image: Target, size: Point) {
- let display = displays.get(gpu);
- if (!display) {
- display = createDisplay(gpu);
- displays.set(gpu, display);
- }
+ const display = bitmapDisplay(gpu);
const canvas = new OffscreenCanvas(size[0], size[1]);
const output = surface(gpu, canvas, { size, dpr: 1 });
try {
diff --git a/src/core/renderer/index.ts b/src/core/renderer/index.ts
index 073d4d6..1be9b49 100644
--- a/src/core/renderer/index.ts
+++ b/src/core/renderer/index.ts
@@ -110,10 +110,11 @@ 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.
+ // Every mask updates once, bypassed or not, so a hidden mask keeps its cache; child masks only shape their parent's coverage.
+ const coverage = new Map<string, RenderInput | undefined>();
for (const { layer, parent } of walkLayers(scene.layers)) {
if (layer.kind === "mask" && parent?.kind !== "mask") {
- raster.update(layer, developed.size);
+ coverage.set(layer.id, raster.update(layer, developed.size));
}
}
const image =
@@ -121,7 +122,7 @@ export function createRenderer(
const images = compose(image, scene, {
inputId,
retain: (id) => active.add(id),
- coverage: (layer) => raster.update(layer, developed.size),
+ coverage: (layer) => coverage.get(layer.id),
brush: (id, strokes) => raster.brush(id, strokes, developed.size),
});
for (const id of instances) {
diff --git a/src/core/renderer/mask/index.ts b/src/core/renderer/mask/index.ts
index 64be664..8e9f725 100644
--- a/src/core/renderer/mask/index.ts
+++ b/src/core/renderer/mask/index.ts
@@ -38,7 +38,7 @@ type Group = {
};
/** A mask's own coverage followed by the children that shape it, in stored order. */
-export function maskOps(layer: MaskLayer): readonly MaskModifier[] {
+function maskOps(layer: MaskLayer): readonly MaskModifier[] {
return [
{ id: layer.id, mask: layer.mask, operation: "add", opacity: 1 },
...maskModifiers(layer),
diff --git a/src/features/adjustments/edits.ts b/src/features/adjustments/edits.ts
index 5e24fdb..c08571c 100644
--- a/src/features/adjustments/edits.ts
+++ b/src/features/adjustments/edits.ts
@@ -3,20 +3,35 @@ import {
type EditorDocument,
editLayer,
} from "@/core/document";
-import { validateAdjustments } from "./model";
+import { change, parse } from "@/lib/parse";
+import { adjustmentsSchema, exposureSchema } from "./model";
+
+const adjustmentChange = change(adjustmentsSchema);
export function setAdjustments(
document: EditorDocument,
- change: Partial<Adjustments>,
+ adjustments: Partial<Adjustments>,
id = document.scene.getState().layers[0].id,
) {
- validateAdjustments(change);
+ const values = parse(adjustmentChange, adjustments, "Invalid adjustment");
editLayer(document, id, (layer) => {
if (layer.kind !== "image" && layer.kind !== "mask") {
throw Error("Select an image or mask layer.");
}
- const adjustments = { ...layer.adjustments, ...change };
+ return { ...layer, adjustments: { ...layer.adjustments, ...values } };
+ });
+}
- return { ...layer, adjustments };
+export function setExposure(
+ document: EditorDocument,
+ id: string,
+ exposure: number,
+) {
+ const value = parse(exposureSchema, exposure, "Invalid Exposure");
+ editLayer(document, id, (layer) => {
+ if (layer.kind !== "exposure") {
+ throw Error("Select an exposure layer.");
+ }
+ return { ...layer, exposure: value };
});
}
diff --git a/src/features/adjustments/model.ts b/src/features/adjustments/model.ts
index 6b288f7..2ce11f3 100644
--- a/src/features/adjustments/model.ts
+++ b/src/features/adjustments/model.ts
@@ -1,4 +1,6 @@
+import { z } from "zod/mini";
import type { Adjustments } from "@/core/document";
+import { range } from "@/lib/parse";
export const defaultAdjustments: Adjustments = {
exposure: 0,
@@ -26,17 +28,20 @@ export const adjustmentLimits: Adjustments = {
saturation: 100,
};
-export function validateAdjustments(change: Partial<Adjustments>) {
- for (const [name, value] of Object.entries(change)) {
- const limit = Reflect.get(adjustmentLimits, name);
- if (
- typeof limit !== "number" ||
- typeof value !== "number" ||
- !Number.isFinite(value) ||
- value > limit ||
- value < -limit
- ) {
- throw new Error(`Invalid adjustment: ${name}.`);
- }
- }
-}
+const signed = (limit: number) => range(-limit, limit);
+
+export const adjustmentsSchema = z.object({
+ exposure: signed(adjustmentLimits.exposure),
+ incrementalTemperature: signed(adjustmentLimits.incrementalTemperature),
+ incrementalTint: signed(adjustmentLimits.incrementalTint),
+ contrast: signed(adjustmentLimits.contrast),
+ highlights: signed(adjustmentLimits.highlights),
+ shadows: signed(adjustmentLimits.shadows),
+ whites: signed(adjustmentLimits.whites),
+ blacks: signed(adjustmentLimits.blacks),
+ vibrance: signed(adjustmentLimits.vibrance),
+ saturation: signed(adjustmentLimits.saturation),
+}) satisfies z.ZodMiniType<Adjustments>;
+
+/** An Exposure layer's value, in EV like the adjustment. */
+export const exposureSchema = signed(adjustmentLimits.exposure);
diff --git a/src/features/color-mixer/controls.tsx b/src/features/color-mixer/controls.tsx
index 33c1413..de798ec 100644
--- a/src/features/color-mixer/controls.tsx
+++ b/src/features/color-mixer/controls.tsx
@@ -2,6 +2,7 @@ import { useId, useState } from "react";
import { useDocument } from "@/components/editor/session";
import { ScrubInput } from "@/components/ui/scrub-input";
import { Tab, TabList } from "@/components/ui/tabs";
+import { Tooltip } from "@/components/ui/tooltip";
import { VerticalSlider } from "@/components/ui/vertical-slider";
import type { ColorMixer } from "@/core/document";
import { setColorMixer } from "./edits";
@@ -34,30 +35,29 @@ function ColorSlider({
const change = (value: number) =>
setColorMixer(document, color.id, { [channel]: value }, layerId);
return (
- <div
- className="flex min-w-0 flex-col items-center gap-1"
- title={color.label}
- >
- <ScrubInput
- aria-label={`${label} value`}
- className="w-full leading-4 [&>span]:px-0 [&_input]:text-center [&_input]:tracking-tight"
- variant="text"
- value={value}
- onChange={change}
- min={-100}
- max={100}
- />
- <VerticalSlider
- label={label}
- value={value}
- onChange={change}
- min={-100}
- max={100}
- defaultValue={0}
- stops={gradient(color.hue, channel)}
- color={`hsl(${color.hue} 65% 55%)`}
- />
- </div>
+ <Tooltip content={color.label}>
+ <div className="flex min-w-0 flex-col items-center gap-1">
+ <ScrubInput
+ aria-label={`${label} value`}
+ className="w-full leading-4 [&>span]:px-0 [&_input]:text-center [&_input]:tracking-tight"
+ variant="text"
+ value={value}
+ onChange={change}
+ min={-100}
+ max={100}
+ />
+ <VerticalSlider
+ label={label}
+ value={value}
+ onChange={change}
+ min={-100}
+ max={100}
+ defaultValue={0}
+ stops={gradient(color.hue, channel)}
+ color={`hsl(${color.hue} 65% 55%)`}
+ />
+ </div>
+ </Tooltip>
);
}
diff --git a/src/features/color-mixer/edits.ts b/src/features/color-mixer/edits.ts
index 923da59..6a4b1a5 100644
--- a/src/features/color-mixer/edits.ts
+++ b/src/features/color-mixer/edits.ts
@@ -3,32 +3,28 @@ import {
type EditorDocument,
editLayer,
} from "@/core/document";
+import { parse } from "@/lib/parse";
import {
channels,
colors,
defaultMixer,
type MixerChange,
type MixerColor,
- validMixerValue,
+ mixerChange,
+ mixerColor,
} from "./model";
-export function changeColorMixer(
+function changeColorMixer(
current: ColorMixer,
color: MixerColor,
change: MixerChange,
) {
- const index = colors.findIndex(({ id }) => id === color);
- if (index < 0) {
- throw new Error(`Invalid color range: ${color}.`);
- }
- for (const [name, value] of Object.entries(change)) {
- if (!channels.some(({ id }) => id === name) || !validMixerValue(value)) {
- throw new Error(`Invalid color mixer adjustment: ${name}.`);
- }
- }
+ const selected = parse(mixerColor, color, "Invalid color range");
+ const index = colors.findIndex(({ id }) => id === selected);
+ const values = parse(mixerChange, change, "Invalid color mixer adjustment");
const next = { ...current };
for (const { id } of channels) {
- const value = change[id];
+ const value = values[id];
if (value !== undefined && value !== current[id][index]) {
next[id] = current[id].with(index, value);
}
diff --git a/src/features/color-mixer/model.ts b/src/features/color-mixer/model.ts
index 156c527..647821b 100644
--- a/src/features/color-mixer/model.ts
+++ b/src/features/color-mixer/model.ts
@@ -1,4 +1,6 @@
+import { z } from "zod/mini";
import type { ColorMixer } from "@/core/document";
+import { change, range } from "@/lib/parse";
// Oklab angles of the eight full-saturation sRGB colors, for circular interpolation.
export const colors = [
@@ -33,23 +35,17 @@ export function isNeutral(mixer: ColorMixer) {
return channels.every(({ id }) => mixer[id].every((value) => value === 0));
}
-export function validMixerValue(value: unknown) {
- return (
- typeof value === "number" &&
- Number.isFinite(value) &&
- Math.abs(value) <= 100
- );
-}
+const shift = range(-100, 100);
+const shifts = z.array(shift).check(z.length(colors.length));
-export function validateMixer(mixer: ColorMixer) {
- for (const [name, values] of Object.entries(mixer)) {
- if (
- !channels.some(({ id }) => id === name) ||
- !Array.isArray(values) ||
- values.length !== colors.length ||
- !values.every(validMixerValue)
- ) {
- throw new Error(`Invalid color mixer adjustment: ${name}.`);
- }
- }
-}
+export const mixerSchema = z.object({
+ hue: shifts,
+ saturation: shifts,
+ luminance: shifts,
+}) satisfies z.ZodMiniType<ColorMixer>;
+
+/** One color's channels; unspecified channels keep their values. */
+export const mixerChange = change(
+ z.object({ hue: shift, saturation: shift, luminance: shift }),
+);
+export const mixerColor = z.enum(colors.map(({ id }) => id));
diff --git a/src/features/crop/edits.ts b/src/features/crop/edits.ts
new file mode 100644
index 0000000..ed0a75d
--- /dev/null
+++ b/src/features/crop/edits.ts
@@ -0,0 +1,7 @@
+import type { EditorDocument } from "@/core/document";
+import { type ImageFrame, validateFrame } from "@/core/image/frame";
+
+/** Replaces the crop, rotation, and flip as one edit, respecting an open history group; the frame is copied. */
+export function applyCrop(document: EditorDocument, frame: ImageFrame) {
+ document.edit({ ...document.scene.getState(), frame: validateFrame(frame) });
+}
diff --git a/src/features/crop/view.tsx b/src/features/crop/view.tsx
index 5c7d116..b756715 100644
--- a/src/features/crop/view.tsx
+++ b/src/features/crop/view.tsx
@@ -1,15 +1,17 @@
import { useState } from "react";
import { Image } from "@/components/editor/image";
-import { EditorPanel, PanelHeader } from "@/components/editor/panel";
+import { EditorPanel, PanelBody, PanelHeader } from "@/components/editor/panel";
import { useDocument, useEditorSession } from "@/components/editor/session";
-import { EditorViewport } from "@/components/editor/viewport";
+import { EditorViewport, ViewportStage } from "@/components/editor/viewport";
import { FlipIcon } from "@/components/icons/flip";
import { RotateIcon } from "@/components/icons/rotate";
-import Button from "@/components/ui/button";
+import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
+import { Tooltip } from "@/components/ui/tooltip";
import { imageFrame, type Point } from "@/core/image/frame";
import { useShortcuts } from "@/hooks/use-shortcuts";
+import { applyCrop } from "./edits";
import { fitRatio, flip, rotate, turn } from "./geometry";
import { CropOverlay } from "./overlay";
@@ -41,8 +43,7 @@ export function CropEditor({ onClose }: { onClose: () => void }) {
fitView();
}
function apply() {
- document.history.commit();
- document.edit({ ...document.scene.getState(), frame });
+ applyCrop(document, frame);
fitView();
onClose();
}
@@ -92,16 +93,17 @@ export function CropEditor({ onClose }: { onClose: () => void }) {
return (
<>
<EditorViewport size={reference} constrain={false}>
- <Image image="fullImage" geometry={frame} />
- <CropOverlay
- frame={frame}
- source={source}
- ratio={ratio}
- onChange={setFrame}
- />
+ <ViewportStage>
+ <Image image="fullImage" geometry={frame} />
+ <CropOverlay
+ frame={frame}
+ source={source}
+ ratio={ratio}
+ onChange={setFrame}
+ />
+ </ViewportStage>
</EditorViewport>
<EditorPanel
- header={<PanelHeader title="Crop" onClose={onClose} />}
onKeyDown={(event) => {
// Enter on a panel button is its click; the crop handles still apply.
if (
@@ -112,73 +114,72 @@ export function CropEditor({ onClose }: { onClose: () => void }) {
event.stopPropagation();
}
}}
- footer={
- <div className="border-t border-black p-3">
- <Button className="w-full py-2" onClick={apply}>
- Apply crop
- </Button>
- </div>
- }
>
- <section aria-label="Crop tool" className="space-y-5 p-4">
- <div className="flex items-center justify-between text-neutral-400">
- Aspect ratio
- <Select
- aria-label="Aspect ratio"
- value={ratio === null ? "free" : `${ratio}`}
- options={ratioOptions}
- className="w-24"
- onChange={changeRatio}
- />
- </div>
- <section
- aria-label="Rotate and flip image"
- className="grid grid-cols-4 items-center gap-2"
- >
- <h3 className="col-span-3 text-neutral-400">Rotate & flip</h3>
- <Button
- variant="ghost"
- className="justify-self-end px-2 py-1"
- onClick={reset}
+ <PanelHeader title="Crop" onClose={onClose} />
+ <PanelBody>
+ <section aria-label="Crop tool" className="space-y-5 p-4">
+ <div className="flex items-center justify-between text-neutral-400">
+ Aspect ratio
+ <Select
+ aria-label="Aspect ratio"
+ value={ratio === null ? "free" : `${ratio}`}
+ options={ratioOptions}
+ className="w-24"
+ onChange={changeRatio}
+ />
+ </div>
+ <section
+ aria-label="Rotate and flip image"
+ className="grid grid-cols-4 items-center gap-2"
>
- Reset
- </Button>
-
- {actions.map((action) => {
- const Icon = "turn" in action ? RotateIcon : FlipIcon;
-
- return (
- <Button
- key={action.label}
- variant="ghost"
- aria-label={action.label}
- title={action.label}
- className="flex h-9 items-center justify-center gap-1 rounded-md px-1"
- onClick={() => applyAction(action)}
- >
- <Icon style={{ transform: action.transform }} />
- {"turn" in action && <span>90°</span>}
- </Button>
- );
- })}
+ <h3 className="col-span-3 text-neutral-400">Rotate & flip</h3>
+ <Button
+ variant="ghost"
+ className="justify-self-end px-2 py-1"
+ onClick={reset}
+ >
+ Reset
+ </Button>
+ {actions.map((action) => {
+ const Icon = "turn" in action ? RotateIcon : FlipIcon;
+ return (
+ <Tooltip key={action.label} content={action.label}>
+ <Button
+ variant="ghost"
+ aria-label={action.label}
+ className="flex h-9 items-center justify-center gap-1 rounded-md px-1"
+ onClick={() => applyAction(action)}
+ >
+ <Icon style={{ transform: action.transform }} />
+ {"turn" in action && <span>90°</span>}
+ </Button>
+ </Tooltip>
+ );
+ })}
+ </section>
+ <Slider
+ label="Rotation"
+ min={-45}
+ max={45}
+ step={0.1}
+ value={frame.angle}
+ defaultValue={0}
+ onChange={(angle) => setFrame(rotate(frame, angle, source))}
+ />
+ <p className="text-neutral-500">
+ Drag edges or corners to crop, inside to move, outside to rotate.
+ Space + drag to pan; Ctrl/⌘ + scroll to zoom.
+ </p>
+ <p className="tabular-nums text-neutral-400">
+ {frame.size.map(Math.round).join(" × ")} px
+ </p>
</section>
- <Slider
- label="Rotation"
- min={-45}
- max={45}
- step={0.1}
- value={frame.angle}
- defaultValue={0}
- onChange={(angle) => setFrame(rotate(frame, angle, source))}
- />
- <p className="text-neutral-500">
- Drag edges or corners to crop, inside to move, outside to rotate.
- Space + drag to pan; Ctrl/⌘ + scroll to zoom.
- </p>
- <p className="tabular-nums text-neutral-400">
- {frame.size.map(Math.round).join(" × ")} px
- </p>
- </section>
+ </PanelBody>
+ <div className="p-3">
+ <Button className="w-full py-2" onClick={apply}>
+ Apply crop
+ </Button>
+ </div>
</EditorPanel>
</>
);
diff --git a/src/features/details/edits.ts b/src/features/details/edits.ts
index 0f3dc0a..eb1e776 100644
--- a/src/features/details/edits.ts
+++ b/src/features/details/edits.ts
@@ -1,16 +1,19 @@
import { type Details, type EditorDocument, editLayer } from "@/core/document";
-import { validateDetails } from "./model";
+import { change, parse } from "@/lib/parse";
+import { detailsSchema } from "./model";
+
+export const detailsChange = change(detailsSchema);
export function setDetails(
document: EditorDocument,
- change: Partial<Details>,
+ details: Partial<Details>,
id: string,
) {
- validateDetails(change);
+ const values = parse(detailsChange, details, "Invalid detail adjustment");
editLayer(document, id, (layer) => {
if (layer.kind !== "details") {
throw Error("Select a Details layer.");
}
- return { ...layer, details: { ...layer.details, ...change } };
+ return { ...layer, details: { ...layer.details, ...values } };
});
}
diff --git a/src/features/details/model.ts b/src/features/details/model.ts
index 99c99fb..65319f2 100644
--- a/src/features/details/model.ts
+++ b/src/features/details/model.ts
@@ -1,4 +1,6 @@
+import { z } from "zod/mini";
import type { Details } from "@/core/document";
+import { range } from "@/lib/parse";
export const defaultDetails: Details = {
clarity: 0,
@@ -11,17 +13,8 @@ export const detailLimits = {
sharpenRadius: [0.5, 3],
} as const;
-export function validateDetails(change: Partial<Details>) {
- for (const [name, value] of Object.entries(change)) {
- const limits = Reflect.get(detailLimits, name);
- if (
- !Array.isArray(limits) ||
- typeof value !== "number" ||
- !Number.isFinite(value) ||
- value < limits[0] ||
- value > limits[1]
- ) {
- throw Error(`Invalid detail adjustment: ${name}.`);
- }
- }
-}
+export const detailsSchema = z.object({
+ clarity: range(...detailLimits.clarity),
+ sharpening: range(...detailLimits.sharpening),
+ sharpenRadius: range(...detailLimits.sharpenRadius),
+}) satisfies z.ZodMiniType<Details>;
diff --git a/src/features/fill/edits.ts b/src/features/fill/edits.ts
index 15f9511..5ca11c1 100644
--- a/src/features/fill/edits.ts
+++ b/src/features/fill/edits.ts
@@ -1,23 +1,19 @@
import { type EditorDocument, editLayer, type Fill } from "@/core/document";
-import { validateFill } from "./model";
+import { change, parse } from "@/lib/parse";
+import { fillSchema } from "./model";
+
+const fillChange = change(fillSchema);
export function setFill(
document: EditorDocument,
- change: Partial<Fill>,
+ fill: Partial<Fill>,
id: string,
) {
- validateFill(change);
+ const values = parse(fillChange, fill, "Invalid fill setting");
editLayer(document, id, (layer) => {
if (layer.kind !== "fill") {
throw Error("Select a color layer.");
}
- return {
- ...layer,
- fill: {
- ...layer.fill,
- ...change,
- ...(change.color ? { color: change.color.toLowerCase() } : {}),
- },
- };
+ return { ...layer, fill: { ...layer.fill, ...values } };
});
}
diff --git a/src/features/fill/model.ts b/src/features/fill/model.ts
index 1c4ae8a..3eb69a1 100644
--- a/src/features/fill/model.ts
+++ b/src/features/fill/model.ts
@@ -1,3 +1,4 @@
+import { z } from "zod/mini";
import type { Blend, Fill } from "@/core/document";
export const blends: readonly (readonly [Blend, string])[] = [
@@ -15,21 +16,14 @@ export const defaultFill: Readonly<Fill> = {
blend: "normal",
};
-export function validateFill(change: Partial<Fill>) {
- for (const [name, value] of Object.entries(change)) {
- const valid =
- name === "color"
- ? typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value)
- : name === "blend" && blends.some(([blend]) => blend === value);
- if (!valid) {
- throw new Error(`Invalid fill setting: ${name}.`);
- }
- }
-}
+export const fillSchema = z.object({
+ color: z.string().check(z.regex(/^#[0-9a-f]{6}$/i), z.toLowerCase()),
+ blend: z.enum(blends.map(([blend]) => blend)),
+}) satisfies z.ZodMiniType<Fill>;
/** The sRGB channels of a `#rrggbb` color, 0 to 1. */
export function parseColor(color: string): [number, number, number] {
- return [1, 3, 5].map(
- (offset) => Number.parseInt(color.slice(offset, offset + 2), 16) / 255,
- ) as [number, number, number];
+ const channel = (offset: number) =>
+ Number.parseInt(color.slice(offset, offset + 2), 16) / 255;
+ return [channel(1), channel(3), channel(5)];
}
diff --git a/src/features/heal/anchor.tsx b/src/features/heal/anchor.tsx
index 18d728d..78feb87 100644
--- a/src/features/heal/anchor.tsx
+++ b/src/features/heal/anchor.tsx
@@ -6,7 +6,7 @@ import type { Point } from "@/core/image/frame";
type Drag = {
pointer: number;
- box?: DOMRect;
+ box: DOMRect;
start: Point;
/** The value when the drag began; a live edit changes the rendered value under the pointer. */
from: Point;
@@ -65,7 +65,7 @@ function DraggedAnchor({
if (commit) document.history.commit();
else document.history.cancel();
}
- function point(event: PointerEvent<SVGCircleElement>, box?: DOMRect) {
+ function point(event: PointerEvent<SVGCircleElement>, box: DOMRect) {
return mapping.toDocument(event.clientX, event.clientY, box);
}
function cancel() {
@@ -76,10 +76,10 @@ function DraggedAnchor({
}
useEffect(() => () => end(false), []);
function start(event: PointerEvent<SVGCircleElement>) {
- if (event.button !== 0 || !event.isPrimary || camera.panMode) {
+ const box = camera.ref.current?.getBoundingClientRect();
+ if (event.button !== 0 || !event.isPrimary || camera.panMode || !box) {
return;
}
- const box = camera.ref.current?.getBoundingClientRect();
opened.current = document.history.begin();
current.current = {
pointer: event.pointerId,
diff --git a/src/features/heal/controls.tsx b/src/features/heal/controls.tsx
index cbd6598..a73522a 100644
--- a/src/features/heal/controls.tsx
+++ b/src/features/heal/controls.tsx
@@ -2,7 +2,7 @@ import { CoverageThumbnail } from "@/components/editor/coverage-thumbnail";
import { useDocument } from "@/components/editor/session";
import { HealIcon } from "@/components/icons/heal";
import { Icon } from "@/components/icons/icon";
-import { Menu } from "@/components/ui/menu";
+import { Menu, MenuItem } from "@/components/ui/menu";
import { PanelListItem } from "@/components/ui/panel-list";
import type { HealPatch } from "@/core/document";
import { deleteHealPatch, duplicateHealPatch } from "./edits";
@@ -46,23 +46,21 @@ function PatchActions({
</Icon>
}
>
- <button
- type="submit"
+ <MenuItem
onClick={() =>
selectPatch(duplicateHealPatch(document, layer, patch.id))
}
>
Duplicate
- </button>
- <button
- type="submit"
+ </MenuItem>
+ <MenuItem
onClick={() => {
deleteHealPatch(document, layer, patch.id);
selectPatch(next);
}}
>
Delete
- </button>
+ </MenuItem>
</Menu>
);
}
diff --git a/src/features/heal/edits.ts b/src/features/heal/edits.ts
index 5dbe378..235ae2d 100644
--- a/src/features/heal/edits.ts
+++ b/src/features/heal/edits.ts
@@ -6,13 +6,10 @@ import {
type Layer,
type StrokePoint,
} from "@/core/document";
-import { validPoints } from "@/core/document/brush";
+import { strokePoints } from "@/core/document/brush";
import type { Point } from "@/core/image/frame";
-import {
- validateOffset,
- validatePatchBlend,
- validatePatchStroke,
-} from "./model";
+import { parse, point } from "@/lib/parse";
+import { patchBlend, patchStroke } from "./model";
export function addHealPatch(
document: EditorDocument,
@@ -20,14 +17,13 @@ export function addHealPatch(
stroke: BrushStroke,
offset: Point,
) {
- validatePatchStroke(stroke);
- validateOffset(offset);
+ const painted = parse(patchStroke, stroke, "Invalid heal stroke");
const patch: HealPatch = {
id: crypto.randomUUID(),
- feather: stroke.feather,
- stroke: { ...structuredClone(stroke), feather: 0 },
+ feather: painted.feather,
+ stroke: { ...painted, feather: 0 },
opacity: 1,
- offset: [offset[0], offset[1]],
+ offset: parse(point, offset, "Invalid heal source"),
};
editLayer(document, id, (layer) => ({
...layer,
@@ -63,12 +59,12 @@ export function setHealPatch(
patchId: string,
change: { feather?: number; opacity?: number },
) {
- validatePatchBlend(change);
+ const blend = parse(patchBlend, change, "Invalid heal patch");
editPatches(document, id, patchId, (patches, index) =>
patches.with(index, {
...patches[index],
- feather: change.feather ?? patches[index].feather,
- opacity: change.opacity ?? patches[index].opacity,
+ feather: blend.feather ?? patches[index].feather,
+ opacity: blend.opacity ?? patches[index].opacity,
}),
);
}
@@ -103,11 +99,7 @@ export function extendHealPatch(
id: string,
points: readonly StrokePoint[],
) {
- if (!validPoints(points)) {
- throw Error(
- "Stroke points need finite coordinates and pressure from 0 to 1.",
- );
- }
+ const added = parse(strokePoints, points, "Invalid stroke points");
editLayer(document, id, (layer) => {
if (layer.kind !== "heal" || !layer.patches.length) {
throw Error("Start a heal patch before extending it.");
@@ -120,7 +112,7 @@ export function extendHealPatch(
...patch,
stroke: {
...patch.stroke,
- points: [...patch.stroke.points, ...points],
+ points: [...patch.stroke.points, ...added],
},
}
: patch,
@@ -135,9 +127,9 @@ export function setHealSource(
patchId: string,
offset: Point,
) {
- validateOffset(offset);
+ const source = parse(point, offset, "Invalid heal source");
editPatches(document, id, patchId, (patches, index) =>
- patches.with(index, { ...patches[index], offset: [offset[0], offset[1]] }),
+ patches.with(index, { ...patches[index], offset: source }),
);
}
@@ -148,11 +140,11 @@ export function setHealDestination(
patchId: string,
destination: Point,
) {
- validateOffset(destination);
+ const [targetX, targetY] = parse(point, destination, "Invalid heal target");
editPatches(document, id, patchId, (patches, index) => {
const patch = patches[index];
const [x, y] = patch.stroke.points[0];
- const delta: Point = [destination[0] - x, destination[1] - y];
+ const delta: Point = [targetX - x, targetY - y];
return patches.with(index, {
...patch,
stroke: {
diff --git a/src/features/heal/mode.tsx b/src/features/heal/mode.tsx
index c49e341..420beb6 100644
--- a/src/features/heal/mode.tsx
+++ b/src/features/heal/mode.tsx
@@ -5,10 +5,14 @@ import {
useContext,
useState,
} from "react";
+import type { Point } from "@/core/image/frame";
const HealingContext = createContext<{
feather: number;
setFeather: (feather: number) => void;
+ /** A donor chosen with Alt-click for the next strokes; without one, each stroke searches. */
+ source?: Point;
+ setSource: (source?: Point) => void;
selectedPatch?: string;
selectPatch: (id?: string) => void;
hoveredPatch?: string;
@@ -24,6 +28,7 @@ export function HealingProvider({
onEdit?: () => void;
}) {
const [feather, setFeather] = useState(0.1);
+ const [source, setSource] = useState<Point>();
const [selectedPatch, setSelectedPatch] = useState<string>();
const [hoveredPatch, setHoveredPatch] = useState<string>();
const selectPatch = useCallback(
@@ -38,6 +43,8 @@ export function HealingProvider({
value={{
feather,
setFeather,
+ source,
+ setSource,
selectedPatch,
selectPatch,
hoveredPatch,
diff --git a/src/features/heal/model.ts b/src/features/heal/model.ts
index 84dffc9..4322570 100644
--- a/src/features/heal/model.ts
+++ b/src/features/heal/model.ts
@@ -1,11 +1,13 @@
+import { z } from "zod/mini";
import {
type BrushStroke,
findLayer,
type HealPatch,
type Scene,
} from "@/core/document";
-import { validateStroke } from "@/core/document/brush";
+import { strokeSchema } from "@/core/document/brush";
import type { Point } from "@/core/image/frame";
+import { change, point, unit } from "@/lib/parse";
export function findHealPatch(scene: Scene, layerId: string, patchId: string) {
const layer = findLayer(scene.layers, layerId);
@@ -59,44 +61,31 @@ export function patchBounds(
export function patchThumbnailRegion(
stroke: BrushStroke,
size: readonly number[],
-) {
+): { origin: Point; extent: Point } {
const { origin, extent } = patchBounds(stroke, size);
const side = Math.max(extent[0], extent[1]) * 1.1;
return {
origin: [
origin[0] + (extent[0] - side) / 2,
origin[1] + (extent[1] - side) / 2,
- ] as Point,
- extent: [side, side] as Point,
+ ],
+ extent: [side, side],
};
}
-export function validateOffset(offset: Point) {
- if (offset.length !== 2 || !offset.every(Number.isFinite)) {
- throw Error("A heal source needs two finite source-pixel offsets.");
- }
-}
+export const patchStroke = strokeSchema.check(
+ z.refine(
+ (stroke) => stroke.mode === "paint",
+ "Heal patches use painted strokes",
+ ),
+);
-export function validatePatchStroke(stroke: BrushStroke) {
- validateStroke(stroke);
- if (stroke.mode !== "paint") {
- throw Error("Heal patches use painted strokes.");
- }
-}
+export const patchBlend = change(z.object({ feather: unit, opacity: unit }));
-export function validatePatchBlend(change: {
- feather?: number;
- opacity?: number;
-}) {
- for (const [name, value] of Object.entries(change)) {
- if (typeof value !== "number" || !(value >= 0 && value <= 1)) {
- throw Error(`Heal patch ${name} must be between 0 and 1.`);
- }
- }
-}
-
-export function validateHealPatch(patch: HealPatch) {
- validatePatchStroke(patch.stroke);
- validateOffset(patch.offset);
- validatePatchBlend({ feather: patch.feather, opacity: patch.opacity });
-}
+export const healPatchSchema = z.object({
+ id: z.string().check(z.minLength(1)),
+ feather: unit,
+ stroke: patchStroke,
+ opacity: unit,
+ offset: point,
+}) satisfies z.ZodMiniType<HealPatch>;
diff --git a/src/features/heal/options.tsx b/src/features/heal/options.tsx
index 864966d..f6aebb1 100644
--- a/src/features/heal/options.tsx
+++ b/src/features/heal/options.tsx
@@ -1,14 +1,22 @@
import { useBrushTool } from "@/components/editor/brush-tool";
import { useDocument, useSelectedLayer } from "@/components/editor/session";
import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";
+import { Chip } from "@/components/ui/chip";
import { Slider } from "@/components/ui/slider";
+import { Tooltip } from "@/components/ui/tooltip";
import { setHealPatch } from "./edits";
import { useHealing } from "./mode";
export function HealOptions() {
const document = useDocument();
const { settings, maxSize, setPreview, update } = useBrushTool();
- const { feather: nextFeather, setFeather, selectedPatch } = useHealing();
+ const {
+ feather: nextFeather,
+ setFeather,
+ source,
+ setSource,
+ selectedPatch,
+ } = useHealing();
const layer = useSelectedLayer();
const selected =
layer?.kind === "heal"
@@ -62,6 +70,11 @@ export function HealOptions() {
onChange={(value) => changePatch({ opacity: value / 100 })}
/>
)}
+ {source && (
+ <Tooltip content="Find each stroke's donor again; Alt-click sets one">
+ <Chip onClick={() => setSource(undefined)}>Automatic source</Chip>
+ </Tooltip>
+ )}
</>
);
}
diff --git a/src/features/heal/overlay.tsx b/src/features/heal/overlay.tsx
index 79bf4ec..ab0ba3d 100644
--- a/src/features/heal/overlay.tsx
+++ b/src/features/heal/overlay.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { useGpu } from "vgpu-react";
import { BrushCanvas } from "@/components/editor/brush-canvas";
import { useDocumentMapping } from "@/components/editor/mapping";
@@ -7,6 +7,7 @@ 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 { useDisposable } from "@/hooks/use-disposable";
import { addHealPatch, extendHealPatch, setHealSource } from "./edits";
import { useHealing } from "./mode";
import { dabTouchesImage, findHealPatch } from "./model";
@@ -29,11 +30,19 @@ export function HealOverlay({
const renderer = useRenderer();
const mapping = useDocumentMapping();
const gpu = useGpu();
- const search = useMemo(() => createHealSearch(gpu), [gpu]);
- const { feather, selectedPatch, selectPatch, hoveredPatch } = useHealing();
- const [source, setSource] = useState<Point>();
+ const search = useDisposable(() => createHealSearch(gpu), [gpu]);
+ const {
+ feather,
+ source,
+ setSource,
+ selectedPatch,
+ selectPatch,
+ hoveredPatch,
+ } = useHealing();
const [drawingPatch, setDrawingPatch] = useState<string>();
const [resolvingSource, setResolvingSource] = useState<string>();
+ // A manual donor belongs to this visit to the tool.
+ useEffect(() => () => setSource(undefined), [setSource]);
const selectedHealLayer = useToolLayer({
accepts: isHealLayer,
create: onCreate,
@@ -49,7 +58,6 @@ export function HealOverlay({
const pending = useRef<
{ layer: string; patch: string; automatic: boolean } | undefined
>(undefined);
- useEffect(() => () => search.dispose(), [search]);
async function complete(signal: AbortSignal) {
const current = pending.current;
try {
@@ -170,16 +178,6 @@ export function HealOverlay({
/>
</svg>
)}
- {source && (
- <button
- type="button"
- onPointerDown={(event) => event.stopPropagation()}
- onClick={() => setSource(undefined)}
- className="absolute right-3 bottom-3 rounded-full bg-neutral-800/80 px-3 py-1.5 text-white"
- >
- Automatic source
- </button>
- )}
</BrushCanvas>
);
}
diff --git a/src/features/heal/source.ts b/src/features/heal/source.ts
index 737702e..c92de07 100644
--- a/src/features/heal/source.ts
+++ b/src/features/heal/source.ts
@@ -6,7 +6,7 @@ import { patchBounds } from "./model";
import shader from "./source.wgsl";
/** Boundary matching on a thumbnail. The painted interior never contributes to the score. */
-export function matchSource(
+function matchSource(
pixels: Float32Array,
size: readonly number[],
dimensions: readonly number[],
diff --git a/src/features/histogram/histogram.ts b/src/features/histogram/histogram.ts
index d02a3d8..75f0603 100644
--- a/src/features/histogram/histogram.ts
+++ b/src/features/histogram/histogram.ts
@@ -1,6 +1,7 @@
import { compute, type Gpu, type Target } from "vgpu";
import shader from "./histogram.wgsl";
+/** Counts an image into 256 bins per channel on the GPU and reads back normalized heights. */
export function createHistogram(gpu: Gpu) {
const bins = gpu.device.createBuffer({
size: 3072,
@@ -16,82 +17,13 @@ export function createHistogram(gpu: Gpu) {
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));
- }
return {
- read,
- attach(
- svg: SVGSVGElement,
- image: () => Target | undefined,
- 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;
- let requested = false;
- async function update() {
- requested = true;
- if (pending) {
- return;
- }
- pending = true;
- try {
- do {
- requested = false;
- const source = image();
- if (!source) {
- for (const { polygon, polyline } of curves) {
- polygon.setAttribute("points", "");
- polyline.setAttribute("points", "");
- }
- return;
- }
- const values = await read(source, working, colors.length);
- if (!plot.isConnected) {
- return;
- }
- if (requested) {
- continue;
- }
- 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);
- });
- } while (requested);
- } catch (error) {
- if (plot.isConnected) {
- console.error(error);
- }
- } finally {
- pending = false;
- }
- }
- return {
- update,
- dispose: () => plot.remove(),
- };
+ async 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));
},
dispose() {
bins.dispose();
diff --git a/src/features/histogram/index.tsx b/src/features/histogram/index.tsx
index a6388c9..2f2c0df 100644
--- a/src/features/histogram/index.tsx
+++ b/src/features/histogram/index.tsx
@@ -1,32 +1,108 @@
import { type ComponentProps, useCallback } from "react";
import type { Target } from "vgpu";
-import type { createHistogram } from "./histogram";
+import { useGpu } from "vgpu-react";
+import { useDisposable } from "@/hooks/use-disposable";
+import { createHistogram } from "./histogram";
+
+type Colors = readonly [string] | readonly [string, string, string];
+
+/** Draws each channel as a filled polygon with an outline; one read runs at a time and the latest request wins. */
+function plot(
+ svg: SVGSVGElement,
+ read: (image: Target) => Promise<Float32Array>,
+ image: () => Target | undefined,
+ colors: Colors,
+) {
+ const namespace = "http://www.w3.org/2000/svg";
+ const group = 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");
+ group.append(polygon, polyline);
+ return { polygon, polyline };
+ });
+ svg.append(group);
+ let pending = false;
+ let requested = false;
+ async function update() {
+ requested = true;
+ if (pending) {
+ return;
+ }
+ pending = true;
+ try {
+ do {
+ requested = false;
+ const source = image();
+ if (!source) {
+ for (const { polygon, polyline } of curves) {
+ polygon.setAttribute("points", "");
+ polyline.setAttribute("points", "");
+ }
+ return;
+ }
+ const values = await read(source);
+ if (!group.isConnected) {
+ return;
+ }
+ if (requested) {
+ continue;
+ }
+ 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);
+ });
+ } while (requested);
+ } catch (error) {
+ if (group.isConnected) {
+ console.error(error);
+ }
+ } finally {
+ pending = false;
+ }
+ }
+ return { update, dispose: () => group.remove() };
+}
type Props = ComponentProps<"svg"> & {
- histogram: ReturnType<typeof createHistogram>;
image: () => Target | undefined;
subscribe: (listener: () => void) => () => void;
- colors: readonly [string] | readonly [string, string, string];
+ colors: Colors;
working?: boolean;
};
export function Histogram({
- histogram,
image,
subscribe,
colors,
- working,
+ working = false,
...props
}: Props) {
+ const gpu = useGpu();
+ const histogram = useDisposable(() => createHistogram(gpu), [gpu]);
const attach = useCallback(
(svg: SVGSVGElement | null) => {
if (svg) {
- const plot = histogram.attach(svg, image, colors, working);
- plot.update();
- const unsubscribe = subscribe(plot.update);
+ const chart = plot(
+ svg,
+ (source) => histogram.read(source, working, colors.length),
+ image,
+ colors,
+ );
+ chart.update();
+ const unsubscribe = subscribe(chart.update);
return () => {
unsubscribe();
- plot.dispose();
+ chart.dispose();
};
}
},
diff --git a/src/features/layers/brush-options.tsx b/src/features/layers/brush-options.tsx
index 5439084..0300d11 100644
--- a/src/features/layers/brush-options.tsx
+++ b/src/features/layers/brush-options.tsx
@@ -1,10 +1,12 @@
import { useBrushTool } from "@/components/editor/brush-tool";
import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";
+import { Chip, ChipGroup } from "@/components/ui/chip";
import { Slider } from "@/components/ui/slider";
+import { Tooltip } from "@/components/ui/tooltip";
const modes = [
- ["paint", "Paint", "Add coverage"],
- ["erase", "Erase", "Remove coverage (Alt while painting)"],
+ ["paint", "Paint", "Add coverage", undefined],
+ ["erase", "Erase", "Remove coverage", "Hold Alt"],
] as const;
/** The next stroke's mode, size, edge, and flow, in the bar over the canvas. Alt shows on the Erase chip. */
@@ -13,23 +15,19 @@ export function BrushOptions() {
const variant = barSlider(useBarDensity());
return (
<>
- <fieldset
- aria-label="Brush mode"
- className="flex gap-0.5 rounded-full bg-white/5 p-0.5"
- >
- {modes.map(([mode, label, title]) => (
- <button
- key={mode}
- type="button"
- aria-pressed={erase === (mode === "erase")}
- title={title}
- onClick={() => update({ erase: mode === "erase" })}
- className="h-6 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-8"
- >
- {label}
- </button>
+ <ChipGroup aria-label="Brush mode">
+ {modes.map(([mode, label, hint, shortcut]) => (
+ <Tooltip key={mode} content={hint} shortcut={shortcut}>
+ <Chip
+ size="segment"
+ aria-pressed={erase === (mode === "erase")}
+ onClick={() => update({ erase: mode === "erase" })}
+ >
+ {label}
+ </Chip>
+ </Tooltip>
))}
- </fieldset>
+ </ChipGroup>
<Slider
label="Size"
value={settings.size}
diff --git a/src/features/layers/controls.tsx b/src/features/layers/controls.tsx
index 23c4f93..bf02eeb 100644
--- a/src/features/layers/controls.tsx
+++ b/src/features/layers/controls.tsx
@@ -1,23 +1,24 @@
-import { memo, useCallback, useEffect, useState } from "react";
+import {
+ type ComponentType,
+ memo,
+ useCallback,
+ useEffect,
+ useState,
+} from "react";
import { useStore } from "zustand";
import { PanelHeader } from "@/components/editor/panel";
import { useDocument, useScene } from "@/components/editor/session";
-import { HealIcon } from "@/components/icons/heal";
-import { Icon } from "@/components/icons/icon";
-import { Menu } from "@/components/ui/menu";
+import { Icon, type IconProps } from "@/components/icons/icon";
+import { Menu, MenuItem } from "@/components/ui/menu";
import { PanelListItem } from "@/components/ui/panel-list";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { Tooltip } from "@/components/ui/tooltip";
import {
TreeDrag,
type TreeDrop,
useTreeDragItem,
} from "@/components/ui/tree-drag";
-import {
- type EffectLayer,
- findLayer,
- type Layer,
- type ProcessingLayer,
-} from "@/core/document";
+import { type EffectLayer, findLayer, type Layer } from "@/core/document";
import { useShortcuts } from "@/hooks/use-shortcuts";
import { layerDrop } from "./drop";
import { deleteLayer, moveLayer, setLayer } from "./edits";
@@ -26,45 +27,22 @@ import { useMaskTool } from "./mask-tool";
import { LayerActions, MaskNesting } from "./menu";
import { ImageThumbnail, MaskThumbnail } from "./thumbnails";
-type EffectKind = Exclude<ProcessingLayer["kind"], "mask" | "fill">;
+/** How the stack shows and offers each effect kind; the app supplies them so this feature names no other. */
+export type EffectKind = {
+ readonly kind: EffectLayer["kind"];
+ readonly label: string;
+ readonly Icon?: ComponentType<IconProps>;
+ /** Offered in the Add menu; tools create the others. */
+ readonly addable: boolean;
+};
-/** Each effect's mark in the layer stack; a new effect kind must name one. */
-function EffectIcon({ kind }: { kind: EffectKind }) {
- switch (kind) {
- case "heal":
- return <HealIcon className="size-4" />;
- case "color-mixer":
- return (
- <Icon className="size-4">
- <circle cx="9" cy="9" r="5" />
- <circle cx="15" cy="9" r="5" />
- <circle cx="12" cy="15" r="5" />
- </Icon>
- );
- case "details":
- return (
- <Icon className="size-4">
- <path d="m4 18 8-14 8 14H4Zm8-8v6" />
- </Icon>
- );
- case "vignette":
- return (
- <Icon className="size-4">
- <circle cx="12" cy="12" r="8" />
- <circle cx="12" cy="12" r="3" />
- </Icon>
- );
- case "exposure":
- return (
- <Icon className="size-4">
- <circle cx="12" cy="12" r="8" />
- <path d="M12 4a8 8 0 0 1 0 16Z" fill="currentColor" stroke="none" />
- </Icon>
- );
- }
-}
-
-function LayerThumbnail({ layer }: { layer: Layer }) {
+function LayerThumbnail({
+ layer,
+ effects,
+}: {
+ layer: Layer;
+ effects: readonly EffectKind[];
+}) {
if (layer.kind === "image") {
return <ImageThumbnail />;
}
@@ -81,9 +59,10 @@ function LayerThumbnail({ layer }: { layer: Layer }) {
/>
);
}
+ const Icon = effects.find(({ kind }) => kind === layer.kind)?.Icon;
return (
<span className="grid size-8 shrink-0 place-items-center rounded border border-black/50 bg-neutral-950/40 text-neutral-400">
- <EffectIcon kind={layer.kind} />
+ {Icon && <Icon className="size-4" />}
</span>
);
}
@@ -93,11 +72,13 @@ const LayerRow = memo(function LayerRow({
layer,
parent,
depth,
+ effects,
onSelect,
}: {
layer: Layer;
parent?: Layer;
depth: number;
+ effects: readonly EffectKind[];
onSelect: (id: string) => void;
}) {
const document = useDocument();
@@ -133,30 +114,35 @@ const LayerRow = memo(function LayerRow({
style={{ paddingLeft: depth * 12 }}
className="pr-1 data-[dragging=true]:opacity-40 data-[drop=inside]:ring-1 data-[drop=inside]:ring-blue-400 data-[drop=inside]:ring-inset data-[drop=before]:before:absolute data-[drop=before]:before:inset-x-0 data-[drop=before]:before:-top-px data-[drop=before]:before:border-t-2 data-[drop=before]:before:border-blue-400 data-[drop=after]:after:absolute data-[drop=after]:after:inset-x-0 data-[drop=after]:after:-bottom-px data-[drop=after]:after:border-b-2 data-[drop=after]:after:border-blue-400"
>
- <button
- type="button"
- aria-label={`Show ${layer.name}`}
- aria-pressed={visible}
+ <Tooltip
+ content={visible ? "Hide layer" : "Show layer"}
disabled={isImage}
- onClick={() => {
- if (!isImage) {
- setLayer(document, layer.id, { visible: !visible });
- }
- }}
- className="grid h-full w-8 shrink-0 place-items-center text-neutral-400 hover:text-neutral-100 disabled:text-neutral-600 aria-[pressed=false]:text-neutral-600 pointer-coarse:w-11"
>
- <Icon className="size-3.5">
- <path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Z" />
- <circle cx="12" cy="12" r="3" />
- </Icon>
- </button>
+ <button
+ type="button"
+ aria-label={`Show ${layer.name}`}
+ aria-pressed={visible}
+ disabled={isImage}
+ onClick={() => {
+ if (!isImage) {
+ setLayer(document, layer.id, { visible: !visible });
+ }
+ }}
+ className="grid h-full w-8 shrink-0 place-items-center text-neutral-400 hover:text-neutral-100 disabled:text-neutral-600 aria-[pressed=false]:text-neutral-600 pointer-coarse:w-11"
+ >
+ <Icon className="size-3.5">
+ <path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Z" />
+ <circle cx="12" cy="12" r="3" />
+ </Icon>
+ </button>
+ </Tooltip>
<button
type="button"
aria-label={`Select ${layer.name}`}
onClick={() => onSelect(layer.id)}
className="mr-2 shrink-0"
>
- <LayerThumbnail layer={layer} />
+ <LayerThumbnail layer={layer} effects={effects} />
</button>
<LayerName
layer={layer}
@@ -164,12 +150,17 @@ const LayerRow = memo(function LayerRow({
dragHandle={dragHandle}
/>
{isSubmask && (
- <span
- title={layer.operation}
- className="grid size-6 shrink-0 place-items-center text-neutral-500"
+ <Tooltip
+ content={
+ maskSign === "+"
+ ? `Adds to ${parent?.name}`
+ : `Subtracts from ${parent?.name}`
+ }
>
- {maskSign}
- </span>
+ <span className="grid size-6 shrink-0 place-items-center text-neutral-500">
+ {maskSign}
+ </span>
+ </Tooltip>
)}
{layer.children.length > 0 && (
<button
@@ -185,15 +176,14 @@ const LayerRow = memo(function LayerRow({
</button>
)}
{layer.kind === "image" && (
- <span
- title="Base image is locked"
- className="grid size-7 shrink-0 place-items-center text-neutral-500"
- >
- <Icon className="size-3.5">
- <rect x="6" y="10" width="12" height="10" rx="2" />
- <path d="M8 10V7a4 4 0 0 1 8 0v3" />
- </Icon>
- </span>
+ <Tooltip content="The base image stays at the bottom">
+ <span className="grid size-7 shrink-0 place-items-center text-neutral-500">
+ <Icon className="size-3.5">
+ <rect x="6" y="10" width="12" height="10" rx="2" />
+ <path d="M8 10V7a4 4 0 0 1 8 0v3" />
+ </Icon>
+ </span>
+ </Tooltip>
)}
{layer.kind === "mask" && !parent && <MaskNesting layer={layer} />}
{layer.kind !== "image" && (
@@ -209,6 +199,7 @@ const LayerRow = memo(function LayerRow({
layer={child}
parent={layer}
depth={depth + 1}
+ effects={effects}
onSelect={onSelect}
/>
))}
@@ -217,8 +208,10 @@ const LayerRow = memo(function LayerRow({
});
export function LayersControls({
+ effects,
onAdd,
}: {
+ effects: readonly EffectKind[];
onAdd: (kind: EffectLayer["kind"]) => void;
}) {
const document = useDocument();
@@ -252,7 +245,7 @@ export function LayersControls({
return (
<section
aria-label="Layers"
- className="grid max-h-1/2 min-h-36 shrink-0 grid-rows-[auto_minmax(0,1fr)] border-t border-black bg-panel"
+ className="grid max-h-1/2 min-h-36 shrink-0 grid-rows-[auto_minmax(0,1fr)] bg-panel"
>
<PanelHeader title="Layers">
<Menu
@@ -263,21 +256,13 @@ export function LayersControls({
</Icon>
}
>
- <button type="submit" onClick={() => onAdd("details")}>
- Details
- </button>
- <button type="submit" onClick={() => onAdd("exposure")}>
- Exposure
- </button>
- <button type="submit" onClick={() => onAdd("color-mixer")}>
- Color Mixer
- </button>
- <button type="submit" onClick={() => onAdd("vignette")}>
- Vignette
- </button>
- <button type="submit" onClick={() => onAdd("fill")}>
- Color
- </button>
+ {effects
+ .filter(({ addable }) => addable)
+ .map(({ kind, label }) => (
+ <MenuItem key={kind} onClick={() => onAdd(kind)}>
+ {label}
+ </MenuItem>
+ ))}
</Menu>
</PanelHeader>
<ScrollArea fade>
@@ -293,6 +278,7 @@ export function LayersControls({
key={layer.id}
layer={layer}
depth={0}
+ effects={effects}
onSelect={select}
/>
))}
diff --git a/src/features/layers/edits.ts b/src/features/layers/edits.ts
index 9659496..4852efd 100644
--- a/src/features/layers/edits.ts
+++ b/src/features/layers/edits.ts
@@ -13,43 +13,9 @@ import {
updateLayer,
walkLayers,
} from "@/core/document";
-import { validateStroke, validPoints } from "@/core/document/brush";
-
-export function validateMask(mask: Mask) {
- if (mask.kind === "brush") {
- if (!Array.isArray(mask.strokes)) {
- throw Error("A brush mask needs a list of strokes.");
- }
- mask.strokes.forEach(validateStroke);
- return;
- }
- if (mask.kind === "radial") {
- if (
- mask.center.length !== 2 ||
- mask.radius.length !== 2 ||
- ![...mask.center, ...mask.radius, mask.angle, mask.feather].every(
- Number.isFinite,
- ) ||
- mask.radius.some((value) => value <= 0) ||
- mask.feather < 0 ||
- mask.feather > 1
- ) {
- throw Error(
- "A radial gradient needs positive radii, finite geometry, and feather from 0 to 1.",
- );
- }
- return;
- }
- if (
- mask.kind !== "linear" ||
- mask.start.length !== 2 ||
- mask.end.length !== 2 ||
- ![...mask.start, ...mask.end].every(Number.isFinite) ||
- (mask.start[0] === mask.end[0] && mask.start[1] === mask.end[1])
- ) {
- throw Error("A gradient needs two distinct finite points.");
- }
-}
+import { strokePoints, strokeSchema } from "@/core/document/brush";
+import { change, parse } from "@/lib/parse";
+import { layerSettings, maskOperation, maskSchema } from "./model";
function processingLayer(document: EditorDocument, id: string) {
const layer = findLayer(document.scene.getState().layers, id);
@@ -140,63 +106,25 @@ export function addLayer(
return layer.id;
}
-type LayerSettings = Pick<ProcessingLayer, "visible" | "opacity" | "name">;
-
-export function validateLayerSettings(change: Partial<LayerSettings>) {
- if (
- Object.keys(change).some(
- (key) => !["visible", "opacity", "name"].includes(key),
- ) ||
- Object.values(change).some((value) => value === undefined) ||
- (change.opacity !== undefined &&
- (!Number.isFinite(change.opacity) ||
- change.opacity < 0 ||
- change.opacity > 1)) ||
- (change.visible !== undefined && typeof change.visible !== "boolean") ||
- (change.name !== undefined &&
- (typeof change.name !== "string" || !change.name.trim()))
- ) {
- throw Error("Invalid layer settings.");
- }
-}
+const settingsChange = change(layerSettings);
export function setLayer(
document: EditorDocument,
id: string,
- change: Partial<LayerSettings>,
+ values: Partial<Pick<ProcessingLayer, "visible" | "opacity" | "name">>,
) {
- validateLayerSettings(change);
+ const settings = parse(settingsChange, values, "Invalid layer settings");
processingLayer(document, id);
- editLayer(document, id, (layer) => ({ ...layer, ...change }));
-}
-
-export function validateExposure(exposure: number) {
- if (!Number.isFinite(exposure) || Math.abs(exposure) > 5) {
- throw Error("Exposure must be between -5 and 5 EV.");
- }
-}
-
-export function setExposure(
- document: EditorDocument,
- id: string,
- exposure: number,
-) {
- validateExposure(exposure);
- editLayer(document, id, (layer) => {
- if (layer.kind !== "exposure") {
- throw Error("Select an exposure layer.");
- }
- return { ...layer, exposure };
- });
+ editLayer(document, id, (layer) => ({ ...layer, ...settings }));
}
export function setLayerMask(document: EditorDocument, id: string, mask: Mask) {
- validateMask(mask);
+ const next = parse(maskSchema, mask, "Invalid mask");
editLayer(document, id, (layer) => {
if (layer.kind !== "mask") {
throw Error("Select a mask layer.");
}
- return { ...layer, mask: structuredClone(mask) };
+ return { ...layer, mask: next };
});
}
@@ -213,12 +141,12 @@ export function paintStroke(
id: string,
stroke: BrushStroke,
) {
- validateStroke(stroke);
+ const painted = parse(strokeSchema, stroke, "Invalid stroke");
editLayer(document, id, (item) => {
const { layer, strokes } = brushLayer(item);
return {
...layer,
- mask: { kind: "brush", strokes: [...strokes, structuredClone(stroke)] },
+ mask: { kind: "brush", strokes: [...strokes, painted] },
};
});
}
@@ -229,18 +157,14 @@ export function extendStroke(
id: string,
points: readonly StrokePoint[],
) {
- if (!validPoints(points)) {
- throw Error(
- "Stroke points need finite coordinates and pressure from 0 to 1.",
- );
- }
+ const added = parse(strokePoints, points, "Invalid stroke points");
editLayer(document, id, (item) => {
const { layer, strokes } = brushLayer(item);
const last = strokes.at(-1);
if (!last) {
throw Error("Start a stroke before extending it.");
}
- const stroke = { ...last, points: [...last.points, ...points] };
+ const stroke = { ...last, points: [...last.points, ...added] };
return {
...layer,
mask: { kind: "brush", strokes: [...strokes.slice(0, -1), stroke] },
@@ -248,23 +172,17 @@ export function extendStroke(
});
}
-export function validateMaskOperation(operation: MaskLayer["operation"]) {
- if (operation !== "add" && operation !== "subtract") {
- throw Error("Choose Add or Subtract for a mask.");
- }
-}
-
export function setMaskOperation(
document: EditorDocument,
id: string,
operation: MaskLayer["operation"],
) {
- validateMaskOperation(operation);
+ const next = parse(maskOperation, operation, "Invalid mask operation");
editLayer(document, id, (layer) => {
if (layer.kind !== "mask") {
throw Error("Select a mask layer.");
}
- return { ...layer, operation };
+ return { ...layer, operation: next };
});
}
diff --git a/src/features/layers/gradient-overlay.tsx b/src/features/layers/gradient-overlay.tsx
index d3ba3f7..48ecedd 100644
--- a/src/features/layers/gradient-overlay.tsx
+++ b/src/features/layers/gradient-overlay.tsx
@@ -1,11 +1,13 @@
import { type PointerEvent, useEffect, useRef, useState } from "react";
import { useStore } from "zustand";
+import { CanvasHint } from "@/components/editor/canvas-hint";
import { useDocumentMapping } from "@/components/editor/mapping";
import { useDocument, useScene } from "@/components/editor/session";
import { useViewport } from "@/components/editor/viewport";
import { findLayer, type Gradient, locateLayer } from "@/core/document";
import type { Point } from "@/core/image/frame";
import { useShortcuts } from "@/hooks/use-shortcuts";
+import { blurActive } from "@/lib/dom";
import { setLayerMask } from "./edits";
import {
drawGradient,
@@ -19,7 +21,7 @@ import { type Nesting, useMaskTool } from "./mask-tool";
type Drag = {
pointer: number;
/** The viewport bounds measured once; pointer capture keeps them valid for the drag. */
- box: DOMRect | undefined;
+ box: DOMRect;
from: Point;
to: Point;
mask: Gradient;
@@ -72,11 +74,12 @@ export function GradientOverlay({ shape }: { shape: Gradient["kind"] }) {
}
},
});
- function documentPoint(event: PointerEvent, box: DOMRect | undefined): Point {
+ function documentPoint(event: PointerEvent, box: DOMRect): Point {
return mapping.toDocument(event.clientX, event.clientY, box);
}
function start(event: PointerEvent<HTMLDivElement>) {
- if (event.button !== 0 || !event.isPrimary || camera.panMode) {
+ const box = camera.ref.current?.getBoundingClientRect();
+ if (event.button !== 0 || !event.isPrimary || camera.panMode || !box) {
return;
}
const target =
@@ -88,7 +91,6 @@ export function GradientOverlay({ shape }: { shape: Gradient["kind"] }) {
const handle = gradientHandles.find((handle) => handle === target);
// Guides win over drawing, unless a chosen nesting is waiting for this shape.
const drawing = !handle || !mask || tool.pending?.shape === shape;
- const box = camera.ref.current?.getBoundingClientRect();
const from = documentPoint(event, box);
if (drawing) {
const location = locateLayer(document.scene.getState().layers, selected);
@@ -131,9 +133,7 @@ export function GradientOverlay({ shape }: { shape: Gradient["kind"] }) {
event.stopPropagation();
event.currentTarget.setPointerCapture(event.pointerId);
// Keys after a drag belong to the mask, not to the button that started the tool.
- if (window.document.activeElement instanceof HTMLElement) {
- window.document.activeElement.blur();
- }
+ blurActive();
}
function move(event: PointerEvent<HTMLDivElement>) {
const drag = dragging.current;
@@ -209,10 +209,10 @@ export function GradientOverlay({ shape }: { shape: Gradient["kind"] }) {
extent={Math.hypot(...camera.viewport)}
/>
)}
- <p className="pointer-events-none absolute bottom-3 left-3 rounded-full bg-neutral-800/80 px-3 py-1.5 text-white backdrop-blur-sm">
+ <CanvasHint>
Drag to draw · Shift constrains · Alt subtracts from the selected mask ·
Enter when done
- </p>
+ </CanvasHint>
</div>
);
}
diff --git a/src/features/layers/layer-name.tsx b/src/features/layers/layer-name.tsx
index b5803e8..8c6a1c4 100644
--- a/src/features/layers/layer-name.tsx
+++ b/src/features/layers/layer-name.tsx
@@ -1,5 +1,6 @@
import { type ComponentProps, useState } from "react";
import { useDocument } from "@/components/editor/session";
+import { Tooltip } from "@/components/ui/tooltip";
import type { Layer } from "@/core/document";
import { setLayer } from "./edits";
@@ -15,6 +16,7 @@ export function LayerName({
}) {
const document = useDocument();
const [renaming, setRenaming] = useState(false);
+ const [truncated, setTruncated] = useState(false);
if (renaming) {
return (
<input
@@ -46,17 +48,24 @@ export function LayerName({
setRenaming(true);
}
}
+ // Only a name cut short needs its tooltip.
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>
+ <Tooltip content={layer.name} disabled={!truncated}>
+ <button
+ {...dragHandle}
+ type="button"
+ aria-label={layer.name}
+ onClick={onSelect}
+ onDoubleClick={rename}
+ onPointerEnter={(event) =>
+ setTruncated(
+ event.currentTarget.scrollWidth > event.currentTarget.clientWidth,
+ )
+ }
+ className="min-w-0 flex-1 self-stretch truncate text-left touch-manipulation cursor-grab active:cursor-grabbing"
+ >
+ {layer.name}
+ </button>
+ </Tooltip>
);
}
diff --git a/src/features/layers/mask-options.tsx b/src/features/layers/mask-options.tsx
index b4ce175..c3839e5 100644
--- a/src/features/layers/mask-options.tsx
+++ b/src/features/layers/mask-options.tsx
@@ -1,8 +1,10 @@
import { useStore } from "zustand";
import { useDocument, useScene } from "@/components/editor/session";
import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";
+import { Chip } from "@/components/ui/chip";
import { Select } from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
+import { Tooltip } from "@/components/ui/tooltip";
import { locateLayer, type MaskLayer } from "@/core/document";
import { useShortcuts } from "@/hooks/use-shortcuts";
import { setLayerMask, setMaskOperation } from "./edits";
@@ -31,15 +33,11 @@ export function MaskOptions({ layer }: { layer: MaskLayer }) {
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>
+ <Tooltip content="Show the mask overlay" shortcut="O">
+ <Chip aria-pressed={shown} onClick={toggleOverlay}>
+ Overlay
+ </Chip>
+ </Tooltip>
{layer.mask.kind === "radial" && (
<Slider
label="Feather"
@@ -64,7 +62,7 @@ export function MaskOptions({ layer }: { layer: MaskLayer }) {
<Select
variant="pill"
aria-label="Mask operation"
- title="Combine with the parent mask"
+ tooltip="Combine with the parent mask"
value={layer.operation}
options={[
{ value: "add", label: "Add" },
diff --git a/src/features/layers/mask-tool.tsx b/src/features/layers/mask-tool.tsx
index 96f689a..f785ee3 100644
--- a/src/features/layers/mask-tool.tsx
+++ b/src/features/layers/mask-tool.tsx
@@ -9,6 +9,7 @@ import {
import { createStore, type StoreApi } from "zustand/vanilla";
import { useDocument } from "@/components/editor/session";
import type { Gradient, Mask } from "@/core/document";
+import { blurActive } from "@/lib/dom";
/** Where a new mask goes: inside a mask group, adding or subtracting coverage. */
export type Nesting = {
@@ -91,9 +92,7 @@ export function MaskToolProvider({
edit: (shape) => {
setPending(null);
// Keys after entering or leaving belong to the canvas, not to the row or tab that asked.
- if (window.document.activeElement instanceof HTMLElement) {
- window.document.activeElement.blur();
- }
+ blurActive();
if (shape) {
onTool?.(shape);
} else {
diff --git a/src/features/layers/menu.tsx b/src/features/layers/menu.tsx
index 6fb7093..a0cc56e 100644
--- a/src/features/layers/menu.tsx
+++ b/src/features/layers/menu.tsx
@@ -1,7 +1,6 @@
import { useDocument, useScene } from "@/components/editor/session";
import { Icon } from "@/components/icons/icon";
-import { Menu } from "@/components/ui/menu";
-import { Select } from "@/components/ui/select";
+import { Menu, MenuItem, MenuSeparator, Submenu } from "@/components/ui/menu";
import {
findLayer,
locateLayer,
@@ -40,60 +39,40 @@ function LayerActionItems({
}
return (
<>
- <button
- type="submit"
+ <MenuItem
disabled={index === siblings.length - 1}
onClick={() => moveLayer(document, layer.id, index + 1, parent?.id)}
>
Move up
- </button>
- <button
- type="submit"
+ </MenuItem>
+ <MenuItem
disabled={index === bottom}
onClick={() => moveLayer(document, layer.id, index - 1, parent?.id)}
>
Move down
- </button>
- {parent && (
- <button type="submit" onClick={moveOut}>
- Move out
- </button>
- )}
+ </MenuItem>
+ {parent && <MenuItem onClick={moveOut}>Move out</MenuItem>}
{containers.length > 0 && (
- <div className="flex items-center justify-between gap-3 px-2.5 py-1.5">
- Move into
- <Select
- aria-label={`Move ${layer.name} into`}
- placeholder="Choose layer"
- options={containers.map((item) => ({
- value: item.id,
- label: item.name,
- }))}
- className="max-w-32"
- onChange={(id) => {
- const target = findLayer(layers, id);
- if (target) {
- moveLayer(
- document,
- layer.id,
- target.children.length,
- target.id,
- );
+ <Submenu label="Move into">
+ {containers.map((target) => (
+ <MenuItem
+ key={target.id}
+ onClick={() =>
+ moveLayer(document, layer.id, target.children.length, target.id)
}
- }}
- />
- </div>
+ >
+ {target.name}
+ </MenuItem>
+ ))}
+ </Submenu>
)}
- <div className="my-1 border-t border-white/10" />
- <button
- type="submit"
- onClick={() => onSelect(duplicateLayer(document, layer.id))}
- >
+ <MenuSeparator />
+ <MenuItem onClick={() => onSelect(duplicateLayer(document, layer.id))}>
Duplicate
- </button>
- <button type="submit" onClick={() => deleteLayer(document, layer.id)}>
+ </MenuItem>
+ <MenuItem onClick={() => deleteLayer(document, layer.id)}>
Delete
- </button>
+ </MenuItem>
</>
);
}
@@ -124,16 +103,15 @@ export function MaskNesting({ layer }: { layer: MaskLayer }) {
}
>
{shapes.map(([shape, name]) => (
- <button
+ <MenuItem
key={shape}
- type="submit"
onClick={() => {
document.selectLayer(layer.id);
tool.add(layer.id, operation, shape);
}}
>
{name}
- </button>
+ </MenuItem>
))}
</Menu>
));
diff --git a/src/features/layers/model.ts b/src/features/layers/model.ts
new file mode 100644
index 0000000..589b1be
--- /dev/null
+++ b/src/features/layers/model.ts
@@ -0,0 +1,36 @@
+import { z } from "zod/mini";
+import type { Mask, MaskLayer } from "@/core/document";
+import { strokeSchema } from "@/core/document/brush";
+import { point, unit } from "@/lib/parse";
+
+const positive = z.number().check(z.positive());
+
+export const maskSchema = z.discriminatedUnion("kind", [
+ z
+ .object({ kind: z.literal("linear"), start: point, end: point })
+ .check(
+ z.refine(
+ ({ start, end }) => start[0] !== end[0] || start[1] !== end[1],
+ "A gradient needs two distinct points",
+ ),
+ ),
+ z.object({
+ kind: z.literal("radial"),
+ center: point,
+ radius: z.tuple([positive, positive]),
+ angle: z.number(),
+ feather: unit,
+ }),
+ z.object({ kind: z.literal("brush"), strokes: z.array(strokeSchema) }),
+]) satisfies z.ZodMiniType<Mask>;
+
+export const maskOperation = z.enum([
+ "add",
+ "subtract",
+]) satisfies z.ZodMiniType<MaskLayer["operation"]>;
+
+export const layerSettings = z.object({
+ name: z.string().check(z.trim(), z.minLength(1)),
+ visible: z.boolean(),
+ opacity: unit,
+});
diff --git a/src/features/layers/thumbnails.tsx b/src/features/layers/thumbnails.tsx
index 51b0c36..5dbd6a7 100644
--- a/src/features/layers/thumbnails.tsx
+++ b/src/features/layers/thumbnails.tsx
@@ -3,6 +3,7 @@ import { useGpu } from "vgpu-react";
import { CoverageThumbnail } from "@/components/editor/coverage-thumbnail";
import { useDocument, useScene } from "@/components/editor/session";
import { Icon } from "@/components/icons/icon";
+import { Tooltip } from "@/components/ui/tooltip";
import type { MaskLayer } from "@/core/document";
import { renderBitmap } from "@/core/renderer";
import { MaskFill } from "./mask-fill";
@@ -44,14 +45,15 @@ export function ImageThumbnail() {
};
}, [gpu, source]);
return (
- <canvas
- ref={canvas}
- width={64}
- height={64}
- aria-label="Original image thumbnail"
- title={error ?? "Original image"}
- className={frame}
- />
+ <Tooltip content={error ?? "Original image"}>
+ <canvas
+ ref={canvas}
+ width={64}
+ height={64}
+ aria-label="Original image thumbnail"
+ className={frame}
+ />
+ </Tooltip>
);
}
diff --git a/src/features/layers/toolbar.tsx b/src/features/layers/toolbar.tsx
index ed76be9..22034da 100644
--- a/src/features/layers/toolbar.tsx
+++ b/src/features/layers/toolbar.tsx
@@ -7,7 +7,7 @@ import {
useBarDensity,
} from "@/components/editor/toolbar-density";
import { Icon } from "@/components/icons/icon";
-import { Menu } from "@/components/ui/menu";
+import { Popover } from "@/components/ui/popover";
import { Slider } from "@/components/ui/slider";
import { findLayer, type ProcessingLayer } from "@/core/document";
import { useEditGesture } from "@/hooks/use-edit-gesture";
@@ -96,8 +96,7 @@ export function CanvasToolbar({ children }: { children?: ReactNode }) {
{inlineLayer && <LayerOptions layer={layer} />}
</Density>
{(menuTool || menuLayer) && (
- <Menu
- variant="pill"
+ <Popover
label="More options"
icon={
<Icon className="size-4">
@@ -115,7 +114,7 @@ export function CanvasToolbar({ children }: { children?: ReactNode }) {
{menuLayer && <LayerOptions layer={layer} />}
</div>
</Density>
- </Menu>
+ </Popover>
)}
</fieldset>
);
diff --git a/src/features/tone-curves/curve.ts b/src/features/tone-curves/curve.ts
index aef8ef3..ce745c8 100644
--- a/src/features/tone-curves/curve.ts
+++ b/src/features/tone-curves/curve.ts
@@ -1,5 +1,7 @@
+import { z } from "zod/mini";
import type { CurvePoint, ToneCurve } from "@/core/document";
import { clamp, interpolatePchip } from "@/lib/math";
+import { unit } from "@/lib/parse";
export const defaultCurve: ToneCurve = [
{ x: 0, y: 0 },
@@ -8,35 +10,19 @@ export const defaultCurve: ToneCurve = [
const gap = 1 / 1024;
-export function validateCurve(points: ToneCurve) {
- if (!Array.isArray(points) || points.length < 2) {
- throw new Error("A curve needs at least two points.");
- }
- for (const [index, point] of points.entries()) {
- if (
- !point ||
- ![point.x, point.y].every(
- (value) => Number.isFinite(value) && value >= 0 && value <= 1,
- )
- ) {
- throw new Error(
- "Curve coordinates must be finite numbers between 0 and 1.",
- );
- }
- if (index > 0 && point.x < points[index - 1].x + gap) {
- throw new Error(
- "Curve points must be ordered with a minimum x gap of 1/1024.",
- );
- }
- }
- const first = points[0];
- const last = points[points.length - 1];
- if ((first.x !== 0 && first.y !== 0) || (last.x !== 1 && last.y !== 1)) {
- throw new Error(
- "Curve endpoints must follow the lower-left and upper-right edges.",
- );
- }
-}
+export const curveSchema = z.array(z.object({ x: unit, y: unit })).check(
+ z.minLength(2, "A curve needs at least two points"),
+ z.refine(
+ (points) =>
+ points.every((point, i) => !i || point.x >= points[i - 1].x + gap),
+ "Curve points must be ordered with a minimum x gap of 1/1024",
+ ),
+ z.refine((points) => {
+ const first = points[0];
+ const last = points[points.length - 1];
+ return (first.x === 0 || first.y === 0) && (last.x === 1 || last.y === 1);
+ }, "Curve endpoints must follow the lower-left and upper-right edges"),
+) satisfies z.ZodMiniType<ToneCurve>;
export function moveCurvePoint(
points: ToneCurve,
diff --git a/src/features/tone-curves/edits.ts b/src/features/tone-curves/edits.ts
index f8e4ff7..30db39e 100644
--- a/src/features/tone-curves/edits.ts
+++ b/src/features/tone-curves/edits.ts
@@ -3,18 +3,19 @@ import {
editLayer,
type ToneCurve,
} from "@/core/document";
-import { defaultCurve, validateCurve } from "./curve";
+import { parse } from "@/lib/parse";
+import { curveSchema, defaultCurve } from "./curve";
export function setToneCurve(
document: EditorDocument,
points: ToneCurve = defaultCurve,
id = document.scene.getState().layers[0].id,
) {
- validateCurve(points);
+ const toneCurve = parse(curveSchema, points, "Invalid tone curve");
editLayer(document, id, (layer) => {
if (layer.kind !== "image" && layer.kind !== "mask") {
throw Error("Select an image or mask layer.");
}
- return { ...layer, toneCurve: points.map((point) => ({ ...point })) };
+ return { ...layer, toneCurve };
});
}
diff --git a/src/features/tone-curves/tone-curves.tsx b/src/features/tone-curves/tone-curves.tsx
index 697fd2a..21ffe19 100644
--- a/src/features/tone-curves/tone-curves.tsx
+++ b/src/features/tone-curves/tone-curves.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from "react";
-import Button from "@/components/ui/button";
+import { Button } from "@/components/ui/button";
import type { ToneCurve } from "@/core/document";
import { defaultCurve } from "./curve";
import { Graph } from "./graph";
diff --git a/src/features/vignette/edits.ts b/src/features/vignette/edits.ts
index 558a773..831b6fd 100644
--- a/src/features/vignette/edits.ts
+++ b/src/features/vignette/edits.ts
@@ -1,29 +1,19 @@
import { type EditorDocument, editLayer, type Vignette } from "@/core/document";
+import { change, parse } from "@/lib/parse";
+import { vignetteSchema } from "./model";
-export function validateVignette(change: Partial<Vignette>) {
- for (const [name, value] of Object.entries(change)) {
- if (
- (name !== "intensity" && name !== "softness") ||
- typeof value !== "number" ||
- !Number.isFinite(value) ||
- value < 0 ||
- value > 100
- ) {
- throw new Error(`Invalid vignette adjustment: ${name}.`);
- }
- }
-}
+const vignetteChange = change(vignetteSchema);
export function setVignette(
document: EditorDocument,
- change: Partial<Vignette>,
+ vignette: Partial<Vignette>,
id: string,
) {
- validateVignette(change);
+ const values = parse(vignetteChange, vignette, "Invalid vignette adjustment");
editLayer(document, id, (layer) => {
if (layer.kind !== "vignette") {
throw Error("Select a vignette layer.");
}
- return { ...layer, vignette: { ...layer.vignette, ...change } };
+ return { ...layer, vignette: { ...layer.vignette, ...values } };
});
}
diff --git a/src/features/vignette/model.ts b/src/features/vignette/model.ts
index 84557ad..51437cd 100644
--- a/src/features/vignette/model.ts
+++ b/src/features/vignette/model.ts
@@ -1,6 +1,13 @@
+import { z } from "zod/mini";
import type { Vignette } from "@/core/document";
+import { range } from "@/lib/parse";
export const defaultVignette: Readonly<Vignette> = {
intensity: 0,
softness: 50,
};
+
+export const vignetteSchema = z.object({
+ intensity: range(0, 100),
+ softness: range(0, 100),
+}) satisfies z.ZodMiniType<Vignette>;
diff --git a/src/features/white-balance/edits.ts b/src/features/white-balance/edits.ts
index 7999927..90e1e50 100644
--- a/src/features/white-balance/edits.ts
+++ b/src/features/white-balance/edits.ts
@@ -1,5 +1,7 @@
+import { z } from "zod/mini";
import { type EditorDocument, editLayer } from "@/core/document";
import type { WhiteBalance } from "@/core/image";
+import { parse, range } from "@/lib/parse";
export function whiteBalanceLimits(asShot: WhiteBalance) {
return {
@@ -14,18 +16,13 @@ export function whiteBalanceLimits(asShot: WhiteBalance) {
};
}
-export function validateWhiteBalance(
- balance: WhiteBalance,
- asShot: WhiteBalance,
-) {
- const limits = whiteBalanceLimits(asShot);
- for (const channel of ["temperature", "tint"] as const) {
- const value = balance[channel];
- const { min, max } = limits[channel];
- if (!Number.isFinite(value) || value < min || value > max) {
- throw Error("Invalid RAW white balance.");
- }
- }
+/** Absolute white balance within the ranges that include the file's as-shot value. */
+export function whiteBalanceSchema(asShot: WhiteBalance) {
+ const { temperature, tint } = whiteBalanceLimits(asShot);
+ return z.object({
+ temperature: range(temperature.min, temperature.max),
+ tint: range(tint.min, tint.max),
+ }) satisfies z.ZodMiniType<WhiteBalance>;
}
/** Without a change, resets to the camera's as-shot balance. */
@@ -38,11 +35,13 @@ export function setWhiteBalance(
if (!asShot) {
throw Error("This image does not support RAW white balance.");
}
- let whiteBalance = asShot;
- if (change) {
- whiteBalance = { ...(scene.layers[0].whiteBalance ?? asShot), ...change };
- validateWhiteBalance(whiteBalance, asShot);
- }
+ const whiteBalance = change
+ ? parse(
+ whiteBalanceSchema(asShot),
+ { ...(scene.layers[0].whiteBalance ?? asShot), ...change },
+ "Invalid RAW white balance",
+ )
+ : asShot;
editLayer(document, scene.layers[0].id, (layer) => {
if (layer.kind !== "image") {
throw Error("Select the image layer.");
diff --git a/src/hooks/use-disposable.ts b/src/hooks/use-disposable.ts
new file mode 100644
index 0000000..d71a41b
--- /dev/null
+++ b/src/hooks/use-disposable.ts
@@ -0,0 +1,14 @@
+import { type DependencyList, useEffect, useMemo } from "react";
+
+/**
+ * A resource created for the current dependencies and disposed when they change or the component unmounts.
+ * Every owner goes through here, so a change to how React keeps memoized values has one place to adapt.
+ */
+export function useDisposable<T extends { dispose(): void }>(
+ create: () => T,
+ deps: DependencyList,
+) {
+ const value = useMemo(create, deps);
+ useEffect(() => () => value.dispose(), [value]);
+ return value;
+}
diff --git a/src/hooks/use-pan-zoom.ts b/src/hooks/use-pan-zoom.ts
index 234e37d..ab38307 100644
--- a/src/hooks/use-pan-zoom.ts
+++ b/src/hooks/use-pan-zoom.ts
@@ -10,10 +10,9 @@ import {
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
+import type { Point } from "@/core/image/frame";
import type { View } from "@/core/renderer";
-
-type Size = readonly [number, number, ...unknown[]];
-type Point = readonly [number, number];
+import { isTyping } from "@/lib/dom";
const fit: View = { zoom: 1, pan: [0, 0] };
export const createCamera = () => createStore<View>(() => fit);
@@ -45,7 +44,7 @@ function zoomAt(view: View, focal: Point, zoom: number, minimum = 1): View {
};
}
-export function fitScale(content: Size, viewport: Size) {
+export function fitScale(content: Point, viewport: Point) {
return Math.min(
viewport[0] / content[0],
viewport[1] / content[1],
@@ -54,7 +53,7 @@ export function fitScale(content: Size, viewport: Size) {
}
/** Axes smaller than the viewport stay centered; larger ones cannot pan past their edge. */
-function clamp(view: View, content: Size, viewport: Size): View {
+function clamp(view: View, content: Point, viewport: Point): View {
const scale = fitScale(content, viewport) * view.zoom;
const axis = (i: 0 | 1) => {
const room = Math.max(0, (content[i] * scale - viewport[i]) / 2);
@@ -66,7 +65,7 @@ function clamp(view: View, content: Size, viewport: Size): View {
};
}
-function inset(size: Size, padding: number): Point {
+function inset(size: Point, padding: number): Point {
return [
Math.max(0, size[0] - padding * 2),
Math.max(0, size[1] - padding * 2),
@@ -80,7 +79,7 @@ function inset(size: Size, padding: number): Point {
*/
export function usePanZoom(
state: Camera,
- content: Size,
+ content: Point,
{ constrain = true, padding = 0 } = {},
) {
const ref = useRef<HTMLDivElement>(null);
@@ -103,14 +102,7 @@ export function usePanZoom(
) {
return;
}
- const target = event.target;
- if (
- target instanceof HTMLElement &&
- (target.isContentEditable ||
- target.closest(
- 'input:not([type="range"]), textarea, select, dialog, [role="dialog"]',
- ))
- ) {
+ if (isTyping(event.target)) {
return;
}
event.preventDefault();
@@ -135,7 +127,7 @@ export function usePanZoom(
(next: (view: View) => View, bounded = constrain) => {
const element = ref.current;
if (element) {
- const viewport: Size = [element.clientWidth, element.clientHeight];
+ const viewport: Point = [element.clientWidth, element.clientHeight];
state.setState((view) => {
const result = next(view);
return bounded
diff --git a/src/hooks/use-pointer.ts b/src/hooks/use-pointer.ts
index f46d907..608c6ee 100644
--- a/src/hooks/use-pointer.ts
+++ b/src/hooks/use-pointer.ts
@@ -4,7 +4,7 @@ type Mode = "none" | "hover" | "drag";
type Pointer = { x: number; y: number; mode: Mode };
/** Where the mouse or a dragged file last was, as fractions of the viewport. */
-export default function usePointer() {
+export function usePointer() {
const pointer = useRef<Pointer>({ x: 0, y: 0, mode: "none" });
useEffect(() => {
diff --git a/src/hooks/use-shortcuts.ts b/src/hooks/use-shortcuts.ts
index 61e40cb..ddad013 100644
--- a/src/hooks/use-shortcuts.ts
+++ b/src/hooks/use-shortcuts.ts
@@ -1,4 +1,5 @@
import { useEffect, useEffectEvent } from "react";
+import { isTyping, typingFields } from "@/lib/dom";
/** View-scoped keyboard actions. Text fields opt in explicitly. */
export function useShortcuts(
@@ -11,19 +12,14 @@ export function useShortcuts(
if ((event.repeat && !modifier) || event.isComposing || event.altKey) {
return;
}
- const target = event.target;
- if (window.document.querySelector(":popover-open")) {
+ // An open menu, select, or popover owns the keyboard.
+ if (window.document.querySelector("[data-surface][data-open]")) {
return;
}
- const typing =
- 'input:not([type="range"]), textarea, select, dialog, [role="dialog"]';
// Enter on a focused button or link is its activation, not a shortcut.
- const owned = event.key === "Enter" ? `${typing}, button, a` : typing;
- if (
- !inputs &&
- target instanceof HTMLElement &&
- (target.isContentEditable || target.closest(owned))
- ) {
+ const owned =
+ event.key === "Enter" ? `${typingFields}, button, a` : typingFields;
+ if (!inputs && isTyping(event.target, owned)) {
return;
}
const action = actions[`${modifier}${shift}${event.key.toLowerCase()}`];
diff --git a/src/lib/dom.ts b/src/lib/dom.ts
new file mode 100644
index 0000000..7d299cf
--- /dev/null
+++ b/src/lib/dom.ts
@@ -0,0 +1,17 @@
+/** Fields that own their keys, so page shortcuts and held keys leave them alone. */
+export const typingFields =
+ 'input:not([type="range"]), textarea, select, dialog, [role="dialog"]';
+
+export function isTyping(target: EventTarget | null, fields = typingFields) {
+ return (
+ target instanceof HTMLElement &&
+ (target.isContentEditable || target.closest(fields) !== null)
+ );
+}
+
+/** Returns keys to the page, as after a button that started a canvas gesture. */
+export function blurActive() {
+ if (document.activeElement instanceof HTMLElement) {
+ document.activeElement.blur();
+ }
+}
diff --git a/src/lib/parse.ts b/src/lib/parse.ts
new file mode 100644
index 0000000..97e1beb
--- /dev/null
+++ b/src/lib/parse.ts
@@ -0,0 +1,47 @@
+import { en } from "zod/locales";
+import { z } from "zod/mini";
+
+// zod/mini ships without messages; English keeps errors readable.
+z.config(en());
+
+/** Parses `value`, or throws one readable error naming the subject, the first invalid path, and why. */
+export function parse<S extends z.ZodMiniType>(
+ schema: S,
+ value: unknown,
+ subject: string,
+): z.output<S> {
+ const result = schema.safeParse(value);
+ if (result.success) {
+ return result.data;
+ }
+ const [issue] = result.error.issues;
+ const path = issue.path.join(".");
+ throw Error(`${subject}${path ? ` ${path}` : ""}: ${issue.message}.`);
+}
+
+/** A change to some of an object's fields; unknown fields are rejected. */
+export function change<Shape extends z.core.$ZodShape>(
+ schema: z.ZodMiniObject<Shape>,
+) {
+ return z.partial(z.strictObject(schema.shape));
+}
+
+/** Missing object fields take their defaults before parsing, as for a file older than a parameter. */
+export function withDefaults<S extends z.ZodMiniType>(
+ defaults: object,
+ schema: S,
+) {
+ return z.pipe(
+ z.transform((value: unknown) =>
+ value && typeof value === "object" && !Array.isArray(value)
+ ? { ...defaults, ...value }
+ : value,
+ ),
+ schema,
+ );
+}
+
+export const range = (min: number, max: number) =>
+ z.number().check(z.minimum(min), z.maximum(max));
+export const unit = range(0, 1);
+export const point = z.tuple([z.number(), z.number()]);
diff --git a/src/lib/weak-memo.ts b/src/lib/weak-memo.ts
new file mode 100644
index 0000000..be0856c
--- /dev/null
+++ b/src/lib/weak-memo.ts
@@ -0,0 +1,12 @@
+/** Creates one value per key object on first use; an entry goes when its key is collected. */
+export function weakMemo<K extends WeakKey, V>(create: (key: K) => V) {
+ const values = new WeakMap<K, V>();
+ return (key: K) => {
+ let value = values.get(key);
+ if (value === undefined) {
+ value = create(key);
+ values.set(key, value);
+ }
+ return value;
+ };
+}
diff --git a/src/main.tsx b/src/main.tsx
index d1f7d13..20ab5e1 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -4,8 +4,9 @@ import { Component, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { GpuProvider } from "vgpu-react";
-import App from "@/app";
+import { App } from "@/app";
import { TextLink } from "@/components/ui/text-link";
+import { TooltipProvider } from "@/components/ui/tooltip";
import "./index.css";
/** GPU initialization throws during render; without WebGPU the page would otherwise stay blank. */
@@ -45,7 +46,9 @@ if (root) {
<>
<GpuBoundary>
<GpuProvider>
- <App />
+ <TooltipProvider>
+ <App />
+ </TooltipProvider>
</GpuProvider>
</GpuBoundary>
<Analytics />
diff --git a/tests/brush.e2e.ts b/tests/brush.e2e.ts
index 7d897ab..c5b7270 100644
--- a/tests/brush.e2e.ts
+++ b/tests/brush.e2e.ts
@@ -212,10 +212,7 @@ test("paint a brush mask, adjust it in the sidebar, erase, and undo", async ({
exact: true,
})
.click();
- await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Brush", exact: true })
- .click();
+ await page.getByRole("menuitem", { name: "Brush", exact: true }).click();
await expect(
page.getByRole("tab", { name: "Brush", exact: true }),
).toHaveAttribute("aria-selected", "true");
diff --git a/tests/color-mixer-editing.ts b/tests/color-mixer-editing.ts
index 22a6f6a..b342d44 100644
--- a/tests/color-mixer-editing.ts
+++ b/tests/color-mixer-editing.ts
@@ -7,8 +7,7 @@ export async function colorMixerEditing(page: Page) {
await test.step("color mixer switches channels, groups vertical drags, exports selected colors and resets", async () => {
await page.getByRole("button", { name: "Add effect", exact: true }).click();
await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Color Mixer", exact: true })
+ .getByRole("menuitem", { name: "Color Mixer", exact: true })
.click();
const before = (await state()).history.undoCount;
const hue = page.getByRole("slider", { name: "Blue hue", exact: true });
diff --git a/tests/documents.test.ts b/tests/documents.test.ts
index eff6114..dac83fc 100644
--- a/tests/documents.test.ts
+++ b/tests/documents.test.ts
@@ -6,9 +6,10 @@ import { createDocument, createResources } from "@/core/document";
import { createImageSource } from "@/core/image";
import { imageFrame } from "@/core/image/frame";
import { setAdjustments } from "@/features/adjustments/edits";
-import { validateDetails } from "@/features/details/model";
+import { detailsChange } from "@/features/details/edits";
import { defaultCurve } from "@/features/tone-curves/curve";
import { setToneCurve } from "@/features/tone-curves/edits";
+import { parse } from "@/lib/parse";
function document() {
return createDocument({
@@ -55,7 +56,9 @@ test("documents edit independently without React, retain bounded history, and re
{ sharpenRadius: 3.1 },
{ sharpenRadius: NaN },
]) {
- expect(() => validateDetails(change)).toThrow("Invalid detail adjustment");
+ expect(() =>
+ parse(detailsChange, change, "Invalid detail adjustment"),
+ ).toThrow("Invalid detail adjustment");
}
setAdjustments(first, { exposure: 1 });
diff --git a/tests/draft.e2e.ts b/tests/draft.e2e.ts
index e0f5fbb..0135ea9 100644
--- a/tests/draft.e2e.ts
+++ b/tests/draft.e2e.ts
@@ -110,10 +110,13 @@ test("without IndexedDB a notice suggests scene files and editing still works",
await page
.locator('input[type="file"]')
.setInputFiles("tests/fixtures/photo.svg");
+ const exposure = page.getByRole("textbox", { name: "Exposure", exact: true });
+ await expect(exposure).toBeEnabled();
+ await expect
+ .poll(() => page.evaluate(() => window.openlight.getState().documentId))
+ .toBeDefined();
await page.evaluate(() => window.openlight.setAdjustments({ exposure: 1 }));
- await expect(
- page.getByRole("textbox", { name: "Exposure", exact: true }),
- ).toHaveValue("1.00");
+ await expect(exposure).toHaveValue("1.00");
await notice.getByRole("button", { name: "Dismiss" }).click();
await expect(notice).toHaveCount(0);
// The autosave after that edit fails the same way without bringing the notice back.
diff --git a/tests/draft.test.ts b/tests/draft.test.ts
index a023a9c..eab26b6 100644
--- a/tests/draft.test.ts
+++ b/tests/draft.test.ts
@@ -55,8 +55,8 @@ test("a draft survives storage's structured clone, reopens under its source ID,
const { record, files } = stored;
const malformed: [unknown, string][] = [
- [undefined, "Invalid draft."],
- [{ ...record, version: "1" }, "Invalid draft."],
+ [undefined, "Invalid draft"],
+ [{ ...record, version: "1" }, "Invalid draft version"],
[{ ...record, version: 2 }, "This draft needs a newer version"],
[{ ...record, scene: undefined }, "doesn't contain an OpenLight scene"],
[
diff --git a/tests/editing.e2e.ts b/tests/editing.e2e.ts
index c6ba1af..181fd56 100644
--- a/tests/editing.e2e.ts
+++ b/tests/editing.e2e.ts
@@ -311,10 +311,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
await test.step("clarity changes local contrast and histogram, then undoes and resets", async () => {
await page.getByRole("button", { name: "Add effect", exact: true }).click();
- await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Details", exact: true })
- .click();
+ await page.getByRole("menuitem", { name: "Details", exact: true }).click();
const field = page.getByRole("textbox", { name: "Clarity", exact: true });
const slider = page.getByRole("slider", { name: "Clarity", exact: true });
await field.fill("100");
@@ -1002,6 +999,18 @@ test("edit a photo, inspect the preview and histograms, undo changes, and export
await quality.fill("95");
await quality.press("Enter");
const large = await save("photo.jpg");
+ // The estimate encodes what Save writes, so it matches the file within its rounding.
+ const estimate = panel.getByText(/^[\d.,]+\s*(kB|MB)$/);
+ await expect
+ .poll(async () => {
+ const text = (await estimate.textContent()) ?? "";
+ const unit = text.includes("MB") ? 1e6 : 1e3;
+ return Math.abs(
+ Number(text.replace(/[^\d.]/g, "")) * unit - large.length,
+ );
+ })
+ .toBeLessThan(Math.max(1000, large.length * 0.01));
+ expect(large.length).toBeGreaterThan(small.length);
for (const bytes of [small, large]) {
const actual = await readImage(page, bytes);
expect(actual.size).toEqual([1200, 800]);
diff --git a/tests/fill.e2e.ts b/tests/fill.e2e.ts
index 93e7e83..de7e60e 100644
--- a/tests/fill.e2e.ts
+++ b/tests/fill.e2e.ts
@@ -9,10 +9,7 @@ test("a color layer paints the image or a brush stroke with Photoshop blends", a
const state = () => page.evaluate(() => window.openlight.getState());
async function addColor() {
await page.getByRole("button", { name: "Add effect", exact: true }).click();
- await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Color", exact: true })
- .click();
+ await page.getByRole("menuitem", { name: "Color", exact: true }).click();
}
await page.goto("/");
await page
diff --git a/tests/heal.e2e.ts b/tests/heal.e2e.ts
index 3a8401b..8a5aba8 100644
--- a/tests/heal.e2e.ts
+++ b/tests/heal.e2e.ts
@@ -182,6 +182,8 @@ test("Healing paints patches, edits them, and undoes", async ({ page }) => {
bounds.y + bounds.height / 2 + 160 * scale,
);
await page.keyboard.up("Alt");
+ const automatic = toolbar.getByRole("button", { name: "Automatic source" });
+ await expect(automatic).toBeVisible();
const targetX = bounds.x + bounds.width / 2 - 250 * scale;
const targetY = bounds.y + bounds.height / 2 - 200 * scale;
await page.mouse.move(targetX, targetY);
@@ -210,6 +212,9 @@ test("Healing paints patches, edits them, and undoes", async ({ page }) => {
expect((await readImage(page, undefined, [[350, 200]])).samples?.[0]).toEqual(
[128, 128, 128, 255],
);
+ // Automatic source drops the manual donor, so the next patch searches for its own.
+ await automatic.click();
+ await expect(automatic).toHaveCount(0);
await page.mouse.click(
bounds.x + bounds.width / 2 + 250 * scale,
bounds.y + bounds.height / 2 + 200 * scale,
@@ -222,6 +227,18 @@ test("Healing paints patches, edits them, and undoes", async ({ page }) => {
return healing?.kind === "heal" && !editing ? healing.patches.length : 0;
})
.toBe(2);
+ const donors = await page.evaluate(() => {
+ const healing = window.openlight
+ .getState()
+ .scene?.layers.find((item) => item.kind === "heal");
+ return healing?.kind === "heal"
+ ? healing.patches.map(({ stroke, offset }) => [
+ Math.round(stroke.points[0][0] + offset[0]),
+ Math.round(stroke.points[0][1] + offset[1]),
+ ])
+ : [];
+ });
+ expect(donors[1]).not.toEqual(donors[0]);
const firstPatch = patchList.getByRole("button", { name: "Select patch 1" });
await firstPatch.hover();
await expect(canvas.locator(`[data-heal-patch="${manual.id}"]`)).toHaveCount(
diff --git a/tests/heal.test.ts b/tests/heal.test.ts
index 3ac7a9f..ddcb7ff 100644
--- a/tests/heal.test.ts
+++ b/tests/heal.test.ts
@@ -116,7 +116,7 @@ test("heal patches reuse brush rasters, scale with the proxy, undo, and release
addHealPatch(document, id, { ...stroke, mode: "erase" }, [1, 2]),
).toThrow("painted");
expect(() => setHealSource(document, id, patch, [NaN, 0])).toThrow(
- "finite",
+ "Invalid heal source",
);
expect(() => setHealPatch(document, id, patch, { feather: NaN })).toThrow(
"feather",
diff --git a/tests/layers.e2e.ts b/tests/layers.e2e.ts
index df866d3..cd38919 100644
--- a/tests/layers.e2e.ts
+++ b/tests/layers.e2e.ts
@@ -27,10 +27,7 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({
await page
.getByRole("button", { name: `${name} actions`, exact: true })
.click();
- await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: command, exact: true })
- .click();
+ await page.getByRole("menuitem", { name: command, exact: true }).click();
}
async function dragLayer(name: string, target: string, fraction: number) {
const from = await box(
@@ -71,10 +68,7 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({
page.getByRole("textbox", { name: "Clarity", exact: true }),
).toHaveCount(0);
await page.getByRole("button", { name: "Add effect", exact: true }).click();
- await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Details", exact: true })
- .click();
+ await page.getByRole("menuitem", { name: "Details", exact: true }).click();
await setField("Clarity", "-100");
expect((await readImage(page)).corner[0]).toBeGreaterThan(0);
await page.getByRole("button", { name: "Undo", exact: true }).click();
@@ -243,8 +237,7 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({
.getByRole("button", { name: "Subtract from Sky", exact: true })
.click();
await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Linear gradient", exact: true })
+ .getByRole("menuitem", { name: "Linear gradient", exact: true })
.click();
await drag(page, from, to);
expect((await samples(page))[0]).toEqual(original[0]);
@@ -264,13 +257,11 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({
await test.step("child effects can leave the mask, reorder and return through undo", async () => {
const masked = await samples(page);
await page.getByRole("button", { name: "Add effect", exact: true }).click();
+ await expect(page.getByRole("menu")).toBeVisible();
await page.keyboard.press("Escape");
- await expect(page.locator("[popover]:popover-open")).toHaveCount(0);
+ await expect(page.getByRole("menu")).toHaveCount(0);
await page.getByRole("button", { name: "Add effect", exact: true }).click();
- await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Vignette", exact: true })
- .click();
+ await page.getByRole("menuitem", { name: "Vignette", exact: true }).click();
expect(
(await state()).scene?.layers[1].children.map((layer) => layer.kind),
).toEqual(["vignette"]);
@@ -395,8 +386,7 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({
})
.click();
await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Radial gradient", exact: true })
+ .getByRole("menuitem", { name: "Radial gradient", exact: true })
.click();
await drag(page, origin, [
origin[0] + 220 * scale,
@@ -422,11 +412,14 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({
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%");
+ const fitted = await zoom.innerText();
+ await page.mouse.move(0, 0);
+ await zoom.hover();
+ await expect(page.getByText("Zoom to 100%", { exact: true })).toBeVisible();
await zoom.click();
await expect(zoom).toHaveText("100%");
await zoom.click();
- await expect(zoom).toHaveAttribute("title", "Zoom to 100%");
+ await expect(zoom).toHaveText(fitted);
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.ts
index 27fb448..cae4376 100644
--- a/tests/layers.test.ts
+++ b/tests/layers.test.ts
@@ -12,13 +12,13 @@ import {
} from "@/core/document";
import { createImageSource } from "@/core/image";
import { imageFrame } from "@/core/image/frame";
+import { setExposure } from "@/features/adjustments/edits";
import { layerDrop } from "@/features/layers/drop";
import {
addLayer,
deleteLayer,
duplicateLayer,
moveLayer,
- setExposure,
setLayer,
setLayerMask,
} from "@/features/layers/edits";
diff --git a/tests/vignette.e2e.ts b/tests/vignette.e2e.ts
index 7563426..3a63277 100644
--- a/tests/vignette.e2e.ts
+++ b/tests/vignette.e2e.ts
@@ -13,10 +13,7 @@ test("vignette darkens a white image's edges, softens, undoes and disables", asy
),
});
await page.getByRole("button", { name: "Add effect", exact: true }).click();
- await page
- .locator("[popover]:popover-open")
- .getByRole("button", { name: "Vignette", exact: true })
- .click();
+ await page.getByRole("menuitem", { name: "Vignette", exact: true }).click();
const intensity = page.getByRole("textbox", {
name: "Intensity",
exact: true,