Free open-source image editor for the browser
Give the editor a mobile layout and stop it crashing on phones (#51)
Rodrigo Belfiorede09b42fe2d2
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex fcda156..4c8c47f 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -12,15 +12,16 @@ Where the code lives and the rules that keep it in place. Keep this file true: w| `app/loaders` | Image, scene file, and Camera Raw XMP loaders. || `app/draft` | The draft autosaved in the browser. || `app/controls.ts` | `window.openlight`, documented in [API.md](API.md). |-| `app/editor/index.tsx` | The editor with a document: header, tool rail, viewport, sidebar. A tool's `View` replaces viewport and sidebar. |+| `app/editor/index.tsx` | The editor with a document: header, then a tool's canvas and controls in the layout. A tool's `View` replaces both. || `app/editor/empty.tsx` | The editor before a document opens: welcome or loading status, and the placeholder sidebar. || `app/editor/sidebar.tsx` | Sidebar sections in order: `EditorSidebar` with a document, `PlaceholderSidebar` without one. |-| `app/editor/tools.tsx`, `tool-rail.tsx` | The rail. A tool brings a `Canvas` overlay, `Options` for the bar over the image, or its own `View`. |+| `app/editor/tools.tsx`, `tool-rail.tsx` | The tools and the desktop rail. A tool brings a `Canvas` overlay, `Options` for the bar over the image or the dock, or its own `View`. |+| `app/editor/dock.tsx` | The mobile dock's tabs and what it shows: the layer stack, a tool's options, or the selected layer's dials. || `app/editor/renderer.ts` | Composes feature passes into the preview and export pipelines. || `app/editor/mask-overlay.tsx` | The only writer of the mask overlay, derived from the selection. || `app/editor/layers.ts` | The effect kinds the app offers and their layer factories. || `app/editor/export` | The export view. |-| `components/editor` | Editor primitives: panel, viewport, document and renderer contexts, brush input. |+| `components/editor` | Editor primitives: layout, panel, dock, parameters, viewport, document and renderer contexts, brush input. || `components/ui` | What [`@roprgm/ui`](https://ui.roprgm.com) lacks; see [DESIGN.md](DESIGN.md). || `core/document` | Scene contract, layer tree, history, resources. || `core/image` | Image sources, decoding, geometry, color. |@@ -29,7 +30,13 @@ Where the code lives and the rules that keep it in place. Keep this file true: w| `lib` | Utilities independent of OpenLight. || `tests` | `*.test.ts` run in Bun with `vgpu/mock`; `*.e2e.ts` run in Chromium; `fixtures/` holds test images. |-Below the `md` breakpoint (768 px) the same components rearrange through `max-md:` classes: the rail runs along the top and the sidebar becomes a bottom sheet. The output histogram is mounted from the sidebar but floats above that sheet over the image; the placeholder sidebar hides it on mobile.+## Layouts++`useDesktopLayout` in `components/editor/layout.tsx` is the one switch between two layouts, read from the same media query as Tailwind's `md` (768 px), so a class and the tree change in the same frame. Every view renders an `EditorLayout` with its canvas and controls, inside an `EditorFrame` that outlives the views: rail, canvas, and sidebar in a row on desktop; canvas, dock, and tab bar in a column on mobile. The app supplies the rail and the tab bar to the frame.++- The canvas keeps its place in both layouts, so crossing the breakpoint moves it without mounting it again. The sidebar and the dock swap; neither mounts hidden, since each subscribes to the document and the histogram reads the GPU.+- Features describe numbers as `Parameter`s drawn as sliders in the sidebar and dials in the dock, and other controls once for both. Composition that differs sits beside its desktop form: `AdjustPanel` and `AdjustDock`, or a tool's `Options` under the `dock` density.+- State that outlives a layout, such as the tool, selection, camera, and history, lives above `EditorLayout`.## Layers@@ -52,6 +59,7 @@ Dependencies point downward. Features do not import each other; `app/` connects## Rendering- `core/renderer` defines passes as nodes (`node`, `pipeline`, `split`, `merge`); the graph owns intermediate textures and timing. Features declare passes; `app/editor/renderer.ts` connects them.+- The graph keeps intermediate textures for the last two sets of sizes it rendered, so interactive proxy renders and full renders alternate without reallocating full-size textures, which a phone's GPU memory cannot absorb gesture after gesture.- Use `vgpu` for GPU work and `vgpu-react` for bindings. Create pipelines once per engine and reuse them. Keep `.wgsl` beside its owner.- The working space is linear Rec.2020 in `rgba16float`. Decoders convert into it and display converts out; passes preserve format and primaries unless they explicitly convert.- Layers process in stack order; the image layer's adjustments and tone curve run last, on the composite.diff --git a/DESIGN.md b/DESIGN.mdindex 4586450..0ba000c 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -1,16 +1,17 @@# Interface design system-OpenLight uses a small set of shared UI primitives so the editor reads as one application across tools and panels. They come from [`@roprgm/ui`](https://ui.roprgm.com), imported per component as `@roprgm/ui/<name>`, with its theme imported in `src/index.css`; floating parts are built on [Base UI](https://base-ui.com), which owns positioning, focus, dismissal, keyboard navigation, and ARIA. `src/components/ui` keeps only what the library does not provide yet: `TextLink` and `TreeDrag`.+OpenLight uses a small set of shared UI primitives so the editor reads as one application across tools and panels. They come from [`@roprgm/ui`](https://ui.roprgm.com), imported per component as `@roprgm/ui/<name>`, with its theme imported in `src/index.css`; floating parts are built on [Base UI](https://base-ui.com), which owns positioning, focus, dismissal, keyboard navigation, and ARIA. `src/components/ui` keeps only what the library does not provide yet: `TextLink`, `TreeDrag`, and `Dial`.| Component | Use || --- | --- || `Button`, `IconButton` | Actions. `IconButton` is a ghost icon button whose `label` names it and shows as its tooltip, with an optional `shortcut`; use `size="icon-sm"` in headers, rows, and bars. |-| `Chip` | Pill buttons in the bar over the canvas; `aria-pressed` shows a toggle on. A segmented group is a `fieldset` of chips. |+| `Chip` | Pill buttons in the bar over the canvas and the dock; `aria-pressed` shows a toggle on. A segmented group is a `fieldset` of chips; `DockChips` is the dock's. || `Tooltip` | A hint on hover or focus for any control: a `TooltipTrigger` renders the control and `TooltipContent` holds the hint, with an optional shortcut written as `Mod Z` (⌘ or Ctrl). || `Menu`, `MenuItem`, `MenuSeparator`, `Submenu` | Commands such as Duplicate, Move, or Delete, in a `MenuContent` opened by a `MenuTrigger` that renders a control such as an `IconButton`; a `Submenu` holds a `SubmenuTrigger` and a `SubmenuContent`. || `Select` | A choice that replaces a current value, with `field` or `pill` trigger. || `Popover` | Settings that open beside a `PopoverTrigger`, such as bar controls that no longer fit; its `PopoverContent` holds `CardSection`s. || `Slider`, `ScrubInput` | Numbers. A `Slider` is `panel`, `toolbar`, or `compact`, or stands upright with `orientation="vertical"`; `format` writes the value and whatever follows its digits reads as the unit. |+| `Dial`, `DialRow` | Numbers in the mobile dock: a drag anywhere on the dial sets it, right or up to add, and a double tap resets. A `DialRow` never scrolls under a finger: its dials center with a capped gap, and those that don't fit page behind an arrow. |## Selection and menus@@ -30,6 +31,8 @@ OpenLight uses a small set of shared UI primitives so the editor reads as one ap- `EditorPanel` stacks its sections in the order written with a divider between each; `PanelBody` is the section that takes the remaining height, with its `header` fixed above the part that scrolls. `PanelHeader` titles a section and rules it off. The layers section keeps room for three rows and shows, empty, before a document opens. 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.+- A feature describes its numbers once as `Parameter`s, which the sidebar draws as `Slider`s and the dock as `Dial`s. Controls that aren't numbers, such as a curve or a color, are the same component in both.+- In the dock, `DockControls` puts a centered header, usually `DockChips` choosing a group or mode, over a `DialRow`; while a dial drags, its name and value replace the header. The dock takes its view's height: dials keep it low, and a graph such as the curve raises it with a short transition. A view whose sidebar panel doesn't suit a phone, such as Crop, passes its own `dock` to `EditorLayout`.## Panel collectionsdiff --git a/src/app/editor/adjust/index.tsx b/src/app/editor/adjust/index.tsxindex 11ad3d8..cc94f27 100644--- a/src/app/editor/adjust/index.tsx+++ b/src/app/editor/adjust/index.tsx@@ -1,30 +1,57 @@+import { Button } from "@roprgm/ui/button";import { Slider } from "@roprgm/ui/slider";-import { useCallback } from "react";+import { type ReactNode, useCallback, useState } from "react";import { useStore } from "zustand";import { effectKinds } from "@/app/editor/layers";+import { DockChips, DockControls } from "@/components/editor/dock";import { PanelBody, PanelHeader } from "@/components/editor/panel";+import type { Parameter } from "@/components/editor/parameter";import { useRenderer } from "@/components/editor/pipeline";import { useDocument, useScene } from "@/components/editor/session";import {adjustmentTarget,+ type EditorDocument,findLayer,+ type ImageLayer,type Layer,+ type MaskLayer,type ToneCurve,} from "@/core/document";-import { AdjustmentControls } from "@/features/adjustments/controls";+import {+ AdjustmentControls,+ adjustmentParameters,+ color,+ tone,+} from "@/features/adjustments/controls";import { setExposure } from "@/features/adjustments/edits";-import { ColorMixerControls } from "@/features/color-mixer/controls";-import { DetailsControls } from "@/features/details/controls";+import {+ ColorMixerControls,+ mixerParameters,+} from "@/features/color-mixer/controls";+import { channels, type MixerChannel } from "@/features/color-mixer/model";+import {+ DetailsControls,+ detailsParameters,+} from "@/features/details/controls";import { FillControls } from "@/features/fill/controls";import { HealControls } from "@/features/heal/controls";import { Histogram } from "@/features/histogram";import { OverlayToggle } from "@/features/layers/overlay-toggle";+import { defaultCurve } from "@/features/tone-curves/curve";import { setToneCurve } from "@/features/tone-curves/edits";import { ToneCurves } from "@/features/tone-curves/tone-curves";-import { VignetteControls } from "@/features/vignette/controls";-import { WhiteBalanceControls } from "@/features/white-balance/controls";+import {+ VignetteControls,+ vignetteParameters,+} from "@/features/vignette/controls";+import {+ useWhiteBalanceParameters,+ WhiteBalanceControls,+} from "@/features/white-balance/controls";import { useEditGesture } from "@/hooks/use-edit-gesture";+type Kind<K extends Layer["kind"]> = Extract<Layer, { kind: K }>;+/** Names what the controls edit, not the layer, whose name the stack already shows. */function panelTitle(layer: Layer) {if (layer.kind === "image") return "Adjustments";@@ -50,20 +77,43 @@ function CurveInputHistogram({ id }: { id: string }) {);}-function LayerCurve({ id, toneCurve }: { id: string; toneCurve: ToneCurve }) {+function LayerCurve({+ id,+ toneCurve,+ fill,+}: {+ id: string;+ toneCurve: ToneCurve;+ fill?: boolean;+}) {const document = useDocument();return (- <div className="px-3.5 pb-3.5">- <ToneCurves- points={toneCurve}- onChange={(points) => setToneCurve(document, points, id)}- >- <CurveInputHistogram id={id} />- </ToneCurves>- </div>+ <ToneCurves+ points={toneCurve}+ fill={fill}+ onChange={(points) => setToneCurve(document, points, id)}+ >+ <CurveInputHistogram id={id} />+ </ToneCurves>);}+function exposureParameter(+ document: EditorDocument,+ layer: Kind<"exposure">,+): Parameter {+ return {+ id: "exposure",+ label: "Exposure",+ value: layer.exposure,+ min: -5,+ max: 5,+ step: 0.01,+ defaultValue: 0,+ onChange: (value) => setExposure(document, layer.id, value),+ };+}+function SelectedControls({ layer }: { layer: Layer }) {const document = useDocument();switch (layer.kind) {@@ -81,7 +131,9 @@ function SelectedControls({ layer }: { layer: Layer }) {)}/>- <LayerCurve id={layer.id} toneCurve={layer.toneCurve} />+ <div className="px-3.5 pb-3.5">+ <LayerCurve id={layer.id} toneCurve={layer.toneCurve} />+ </div></>);case "color-mixer":@@ -92,33 +144,29 @@ function SelectedControls({ layer }: { layer: Layer }) {return <FillControls id={layer.id} fill={layer.fill} />;case "heal":return <HealControls id={layer.id} patches={layer.patches} />;- case "exposure":+ case "exposure": {+ const { id, ...parameter } = exposureParameter(document, layer);return (<section className="p-3.5">- <Slider- label="Exposure"- value={layer.exposure}- min={-5}- max={5}- step={0.01}- defaultValue={0}- onChange={(value) => setExposure(document, layer.id, value)}- />+ <Slider {...parameter} /></section>);+ }case "mask":return (<><AdjustmentControls id={layer.id} adjustments={layer.adjustments} />- <LayerCurve id={layer.id} toneCurve={layer.toneCurve} />+ <div className="px-3.5 pb-3.5">+ <LayerCurve id={layer.id} toneCurve={layer.toneCurve} />+ </div></>);}}-export function AdjustPanel() {+/** The layer the controls edit, the selection or the mask a selected child mask belongs to, and whether a mask is selected. */+function useAdjustmentTarget() {const document = useDocument();- const gesture = useEditGesture(document.history);const selected = useStore(document.selection, (state) => state.layerId);const target = useScene((scene) => adjustmentTarget(scene.layers, selected) ?? scene.layers[0],@@ -126,6 +174,13 @@ export function AdjustPanel() {const mask = useScene((scene) => findLayer(scene.layers, selected)?.kind === "mask",);+ return { target, mask };+}++export function AdjustPanel() {+ const document = useDocument();+ const gesture = useEditGesture(document.history);+ const { target, mask } = useAdjustmentTarget();return (<PanelBodyheader={@@ -140,3 +195,181 @@ export function AdjustPanel() {</PanelBody>);}++const groups = [+ ["light", "Light"],+ ["color", "Color"],+ ["curve", "Curve"],+] as const;+type Group = (typeof groups)[number][0];++/** An image or mask in the dock: its tone, color, or curve, one group at a time. */+function AdjustmentDials({+ layer,+ group,+ onGroupChange,+ action,+}: {+ layer: ImageLayer | MaskLayer;+ group: Group;+ onGroupChange: (group: Group) => void;+ action: ReactNode;+}) {+ const document = useDocument();+ const whiteBalance = useWhiteBalanceParameters();+ const header = (+ <DockChips+ label="Adjustment group"+ items={groups}+ value={group}+ onChange={onGroupChange}+ />+ );+ if (group === "curve") {+ return (+ <DockControls+ tall+ header={header}+ action={+ <>+ <Button+ variant="ghost"+ size="sm"+ aria-label="Reset curve"+ onClick={() => setToneCurve(document, defaultCurve, layer.id)}+ >+ Reset+ </Button>+ {action}+ </>+ }+ >+ <div className="mx-auto min-h-0 w-full max-w-72 flex-1 px-3.5">+ <LayerCurve id={layer.id} toneCurve={layer.toneCurve} fill />+ </div>+ </DockControls>+ );+ }+ const adjustments = (controls: Parameters<typeof adjustmentParameters>[3]) =>+ adjustmentParameters(document, layer.id, layer.adjustments, controls);+ // A RAW image's own white balance takes the place of the incremental temperature and tint.+ const balance = layer.kind === "image" && whiteBalance;+ let parameters = adjustments(tone);+ if (group === "color") {+ parameters = balance+ ? [...balance, ...adjustments(color.slice(2))]+ : adjustments(color);+ }+ return (+ <DockControls header={header} action={action} parameters={parameters} />+ );+}++function MixerDials({ layer }: { layer: Kind<"color-mixer"> }) {+ const document = useDocument();+ const [channel, setChannel] = useState<MixerChannel>("hue");+ return (+ <DockControls+ header={+ <DockChips+ label="Color Mixer adjustment"+ items={channels.map(({ id, label }) => [id, label] as const)}+ value={channel}+ onChange={setChannel}+ />+ }+ parameters={mixerParameters(+ document,+ layer.id,+ layer.colorMixer,+ channel,+ )}+ />+ );+}++function DockTitle({ layer }: { layer: Layer }) {+ return <h2 className="font-medium text-foreground">{panelTitle(layer)}</h2>;+}++function SelectedDials({+ layer,+ mask,+ group,+ onGroupChange,+}: {+ layer: Layer;+ mask: boolean;+ group: Group;+ onGroupChange: (group: Group) => void;+}) {+ const document = useDocument();+ switch (layer.kind) {+ case "image":+ case "mask":+ return (+ <AdjustmentDials+ layer={layer}+ group={group}+ onGroupChange={onGroupChange}+ action={mask && <OverlayToggle />}+ />+ );+ case "color-mixer":+ return <MixerDials layer={layer} />;+ case "details":+ return (+ <DockControls+ header={<DockTitle layer={layer} />}+ parameters={detailsParameters(document, layer.id, layer.details)}+ />+ );+ case "vignette":+ return (+ <DockControls+ header={<DockTitle layer={layer} />}+ parameters={vignetteParameters(document, layer.id, layer.vignette)}+ />+ );+ case "exposure":+ return (+ <DockControls+ header={<DockTitle layer={layer} />}+ parameters={[exposureParameter(document, layer)]}+ />+ );+ case "fill":+ return (+ <DockControls header={<DockTitle layer={layer} />}>+ <FillControls id={layer.id} fill={layer.fill} />+ </DockControls>+ );+ case "heal":+ return (+ <DockControls header={<DockTitle layer={layer} />}>+ <div className="max-h-48 overflow-y-auto">+ <HealControls id={layer.id} patches={layer.patches} />+ </div>+ </DockControls>+ );+ }+}++/** The selected layer's controls in the dock: dials where the sidebar has sliders. */+export function AdjustDock() {+ const document = useDocument();+ const gesture = useEditGesture(document.history);+ const { target, mask } = useAdjustmentTarget();+ // The group stays as the selection moves between images and masks.+ const [group, setGroup] = useState<Group>("light");+ return (+ <div className="flex min-h-0 flex-1 flex-col" {...gesture}>+ <SelectedDials+ layer={target}+ mask={mask}+ group={group}+ onGroupChange={setGroup}+ />+ </div>+ );+}diff --git a/src/app/editor/dock.tsx b/src/app/editor/dock.tsxnew file mode 100644index 0000000..57bfe5e--- /dev/null+++ b/src/app/editor/dock.tsx@@ -0,0 +1,113 @@+import { Tab, TabList, Tabs } from "@roprgm/ui/tabs";+import { createContext, type ReactNode, useContext, useState } from "react";+import { useDocument } from "@/components/editor/session";+import { Density } from "@/components/editor/toolbar-density";+import { LayersIcon } from "@/components/icons/layers";+import { useEditGesture } from "@/hooks/use-edit-gesture";+import { AdjustDock } from "./adjust";+import { EditorLayers } from "./sidebar";+import { type Tool, tools, useTool } from "./tools";++/** Whether the dock shows the layer stack; the sidebar always does, so only the mobile layout reads it. */+const Stack = createContext<{+ open: boolean;+ setOpen: (open: boolean) => void;+} | null>(null);++function useStack() {+ const stack = useContext(Stack);+ if (!stack) {+ throw new Error("A dock provider is required.");+ }+ return stack;+}++export function DockProvider({ children }: { children: ReactNode }) {+ const [open, setOpen] = useState(false);+ return <Stack value={{ open, setOpen }}>{children}</Stack>;+}++type DockTab = Tool | "layers";++/**+ * The mobile layout's tabs under the dock: Layers, then the rail's tools, each its icon over its+ * name. Without a handler the tabs are inert.+ */+export function DockTabList({+ selected,+ onSelect,+}: {+ selected: DockTab;+ onSelect?: (tab: DockTab) => void;+}) {+ const editing = tools.filter((entry) => entry.group === "edit");+ const tab = "h-13 min-w-12 flex-1 flex-col gap-0.5 px-2";+ return (+ <Tabs value={selected} onValueChange={onSelect} className="surface-panel">+ <TabList+ aria-label="Tools"+ className="gap-0.5 overflow-x-auto px-2 py-1.5 shadow-[inset_0_1px_0_var(--color-edge)] [scrollbar-width:none]"+ >+ <Tab value="layers" disabled={!onSelect} className={tab}>+ <LayersIcon className="size-5" />+ Layers+ </Tab>+ {editing.map((entry) => (+ <Tab+ key={entry.id}+ value={entry}+ disabled={!onSelect}+ aria-label={entry.label}+ className={tab}+ >+ <entry.Icon className="size-5" />+ {entry.shortLabel}+ </Tab>+ ))}+ </TabList>+ </Tabs>+ );+}++/** Opening the stack leaves a tool with its own view, as picking a tool closes the stack. */+export function DockTabs() {+ const { tool, setTool } = useTool();+ const { open, setOpen } = useStack();+ const view = "View" in tool;+ function select(tab: DockTab) {+ setOpen(tab === "layers");+ if (tab !== "layers") {+ setTool(tab);+ } else if (view) {+ setTool(tools[0]);+ }+ }+ return (+ <DockTabList selected={open && !view ? "layers" : tool} onSelect={select} />+ );+}++/** The shared canvas's dock: the stack, the tool's options as dials, or the selected layer's dials. */+export function DockPanel() {+ const document = useDocument();+ const gesture = useEditGesture(document.history);+ const { open } = useStack();+ const { tool } = useTool();+ if (open) {+ return (+ <div className="flex h-48 min-h-0 flex-col">+ <EditorLayers fill />+ </div>+ );+ }+ if ("Options" in tool) {+ return (+ <div className="flex min-h-0 flex-1 flex-col" {...gesture}>+ <Density value="dock">+ <tool.Options />+ </Density>+ </div>+ );+ }+ return <AdjustDock />;+}diff --git a/src/app/editor/empty.tsx b/src/app/editor/empty.tsxindex 6f9153e..7badf2f 100644--- a/src/app/editor/empty.tsx+++ b/src/app/editor/empty.tsx@@ -7,6 +7,7 @@ import { type Gpu, target } from "vgpu";import { useGpu } from "vgpu-react";import { sceneExtension } from "@/app/loaders/scene";import type { Workspace } from "@/app/workspace";+import { EditorFrame, EditorLayout } from "@/components/editor/layout";import { RendererProvider } from "@/components/editor/pipeline";import { DocumentProvider } from "@/components/editor/session";import { TextLink } from "@/components/ui/text-link";@@ -16,7 +17,9 @@ import { accept } from "@/core/image/decode";import { imageFrame } from "@/core/image/frame";import { MaskToolProvider } from "@/features/layers/mask-tool";import { useDisposable } from "@/hooks/use-disposable";+import { AdjustDock } from "./adjust";import { Backdrop } from "./backdrop";+import { DockTabList } from "./dock";import { EditorHeader } from "./header";import { createImageLayer } from "./layers";import { createEditorRenderer } from "./renderer";@@ -122,7 +125,7 @@ function createEmptyDocument(gpu: Gpu) {);}-/** The editor shell without a document: the light backdrop and workspace status fill the canvas area. */+/** The editor shell without a document: the light backdrop and workspace status fill the canvas area, beside inert controls. */export function EmptyEditor({state,onOpen,@@ -135,15 +138,23 @@ export function EmptyEditor({<RendererProvider createRenderer={createEditorRenderer}><MaskToolProvider onCreate={() => {}}><EditorHeader file={state.file} />- <div className="flex min-h-0 flex-1 flex-col md:flex-row">- <ToolTabList selected={tools[0]} />- <div className="relative isolate grid min-h-0 min-w-0 flex-1 place-content-center justify-items-center gap-1.5 overflow-hidden bg-[radial-gradient(circle,#292929,#131313_55%)] p-6">- <Backdrop />- <Status state={state} onOpen={onOpen} />- {draft && <RecoverDraft {...draft} />}- </div>- <PlaceholderSidebar />- </div>+ <EditorFrame+ rail={<ToolTabList selected={tools[0]} />}+ tabs={<DockTabList selected={tools[0]} />}+ >+ <EditorLayout+ inert+ canvas={+ <div className="relative isolate grid min-h-0 min-w-0 flex-1 place-content-center justify-items-center gap-1.5 overflow-hidden bg-[radial-gradient(circle,#292929,#131313_55%)] p-6">+ <Backdrop />+ <Status state={state} onOpen={onOpen} />+ {draft && <RecoverDraft {...draft} />}+ </div>+ }+ panel={<PlaceholderSidebar />}+ dock={<AdjustDock />}+ />+ </EditorFrame></MaskToolProvider></RendererProvider></DocumentProvider>diff --git a/src/app/editor/export/index.tsx b/src/app/editor/export/index.tsxindex 5990d86..c858019 100644--- a/src/app/editor/export/index.tsx+++ b/src/app/editor/export/index.tsx@@ -8,7 +8,8 @@ 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, PanelBody, PanelHeader } from "@/components/editor/panel";+import { EditorLayout } from "@/components/editor/layout";+import { PanelBody, PanelHeader } from "@/components/editor/panel";import { useDocument, useScene } from "@/components/editor/session";import { EditorViewport, ViewportStage } from "@/components/editor/viewport";import type { Point } from "@/core/image/frame";@@ -241,14 +242,16 @@ export function ExportMode({ onClose }: { onClose: () => void }) {}};return (- <>- <EditorViewport size={encoded?.image.size ?? output}>- <ViewportStage>- {encoded && <Image image={encoded.image} />}- </ViewportStage>- {pending && <LoadingOverlay />}- </EditorViewport>- <EditorPanel>+ <EditorLayout+ canvas={+ <EditorViewport size={encoded?.image.size ?? output}>+ <ViewportStage>+ {encoded && <Image image={encoded.image} />}+ </ViewportStage>+ {pending && <LoadingOverlay />}+ </EditorViewport>+ }+ panel={<PanelBody header={<PanelHeader title="Export" onClose={onClose} />}><sectionaria-label="Image export"@@ -288,7 +291,7 @@ export function ExportMode({ onClose }: { onClose: () => void }) {</section><SaveScene /></PanelBody>- </EditorPanel>- </>+ }+ />);}diff --git a/src/app/editor/histogram.tsx b/src/app/editor/histogram.tsxindex 7fce910..8630233 100644--- a/src/app/editor/histogram.tsx+++ b/src/app/editor/histogram.tsx@@ -1,19 +1,32 @@-import { cn } from "cn";+import { cva } from "class-variance-authority";import { useRenderer } from "@/components/editor/pipeline";import { Histogram } from "@/features/histogram";import { ClippingControls } from "./clipping-controls";const colors = ["#f25445", "#6bd175", "#5c8ffa"] as const;-export function ImageHistogram({ className }: { className?: string }) {+const placement = cva("group shrink-0", {+ variants: {+ placement: {+ panel: "relative bg-level-2",+ // Anchored like the zoom control, at the canvas's other bottom corner.+ canvas:+ "absolute bottom-3 left-3 z-10 h-14 w-44 overflow-hidden rounded-md bg-level-4/80 backdrop-blur-sm",+ },+ },+});++/** The output histogram: a section of the sidebar, or floating over the canvas in the mobile layout. */+export function ImageHistogram({+ placement: where,+}: {+ placement: "panel" | "canvas";+}) {const renderer = useRenderer();return (<sectionaria-label="Image histogram"- className={cn(- "group relative shrink-0 bg-level-2 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:bg-level-4/80 max-md:backdrop-blur-sm",- className,- )}+ className={placement({ placement: where })}><ClippingControls /><Histogram@@ -21,7 +34,7 @@ export function ImageHistogram({ className }: { className?: string }) {subscribe={renderer.subscribe}colors={colors}fillOpacity={0.2}- className="block h-25 w-full max-md:h-full"+ className={where === "panel" ? "block h-25 w-full" : "block size-full"}aria-label="output histogram"/></section>diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsxindex 1ed743f..c394f8c 100644--- a/src/app/editor/index.tsx+++ b/src/app/editor/index.tsx@@ -4,6 +4,11 @@ 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 {+ EditorFrame,+ EditorLayout,+ useDesktopLayout,+} from "@/components/editor/layout";import { RendererProvider } from "@/components/editor/pipeline";import {DocumentProvider,@@ -21,8 +26,10 @@ import { useShortcuts } from "@/hooks/use-shortcuts";import { blurActive } from "@/lib/dom";import { ComparisonControl } from "./comparison-control";import { ComparisonDivider } from "./comparison-divider";+import { DockPanel, DockProvider, DockTabs } from "./dock";import { EmptyEditor, type Recovery } from "./empty";import { EditorHeader } from "./header";+import { ImageHistogram } from "./histogram";import { HistoryControls } from "./history";import { createMask } from "./layers";import { MaskOverlaySync } from "./mask-overlay";@@ -31,9 +38,14 @@ import { EditorSidebar } from "./sidebar";import { ToolRail } from "./tool-rail";import { exportTool, ToolProvider, tools, useTool } from "./tools";-/** A View replaces the canvas and sidebar; otherwise the tool's Canvas and Options join the shared canvas. */+/**+ * A View replaces the canvas and its controls; otherwise the tool's Canvas joins the shared canvas.+ * Its Options go in the bar over the canvas on desktop and in the dock on mobile, where the output+ * histogram floats over the canvas instead of heading the sidebar.+ */function ToolView() {const { tool, setTool } = useTool();+ const desktop = useDesktopLayout();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.@@ -55,18 +67,24 @@ function ToolView() {return <tool.View onClose={close} />;}return (- <>- <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 />- </>+ <EditorLayout+ canvas={+ <EditorViewport size={size}>+ <ViewportStage>+ <Image original="originalImage" />+ {"Canvas" in tool && <tool.Canvas key={tool.id} />}+ </ViewportStage>+ <ComparisonDivider />+ <CanvasToolbar>+ {desktop && "Options" in tool && <tool.Options />}+ </CanvasToolbar>+ {!desktop && <ImageHistogram placement="canvas" />}+ <MaskOverlaySync />+ </EditorViewport>+ }+ panel={<EditorSidebar />}+ dock={<DockPanel />}+ />);}@@ -152,10 +170,11 @@ function DocumentEditor({ file }: { file: string }) {<ComparisonControl /><ExportButton /></EditorHeader>- <div className="flex min-h-0 flex-1 flex-col md:flex-row">- <ToolRail />- <ToolView />- </div>+ <DockProvider>+ <EditorFrame rail={<ToolRail />} tabs={<DockTabs />}>+ <ToolView />+ </EditorFrame>+ </DockProvider></BrushProvider></HealingTools></MaskTools>diff --git a/src/app/editor/sidebar.tsx b/src/app/editor/sidebar.tsxindex 702e665..8deb451 100644--- a/src/app/editor/sidebar.tsx+++ b/src/app/editor/sidebar.tsx@@ -1,4 +1,3 @@-import { EditorPanel } from "@/components/editor/panel";import { useDocument } from "@/components/editor/session";import type { EffectLayer } from "@/core/document";import { findLayer } from "@/core/document";@@ -9,7 +8,7 @@ import { ImageHistogram } from "./histogram";import { createLayer, effectKinds } from "./layers";/** The layer stack with the effects the app offers; a new effect goes inside a selected root mask or above the selection. */-function EditorLayers() {+export function EditorLayers({ fill }: { fill?: boolean }) {const document = useDocument();function add(kind: EffectLayer["kind"]) {const scene = document.scene.getState();@@ -21,27 +20,27 @@ function EditorLayers() {: { above: selected };addLayer(document, createLayer(kind), placement);}- return <LayersControls effects={effectKinds} onAdd={add} />;+ return <LayersControls effects={effectKinds} onAdd={add} fill={fill} />;}-/** The editing sidebar, top to bottom; reorder the sections here. */+/** The editing sidebar's sections, top to bottom; reorder them here. */export function EditorSidebar() {return (- <EditorPanel>- <ImageHistogram />+ <>+ <ImageHistogram placement="panel" /><EditorLayers /><AdjustPanel />- </EditorPanel>+ </>);}-/** Before a document opens, the sidebar shows the same sections, dimmed, with an empty layer stack. */+/** Before a document opens, the sidebar shows the same sections with an empty layer stack. */export function PlaceholderSidebar() {return (- <EditorPanel inert>- <ImageHistogram className="max-md:hidden" />+ <>+ <ImageHistogram placement="panel" /><LayersSection /><AdjustPanel />- </EditorPanel>+ </>);}diff --git a/src/app/editor/tool-rail.tsx b/src/app/editor/tool-rail.tsxindex 710bee5..899c2ea 100644--- a/src/app/editor/tool-rail.tsx+++ b/src/app/editor/tool-rail.tsx@@ -1,10 +1,9 @@import { Tab, TabList, Tabs } from "@roprgm/ui/tabs";import { Tooltip, TooltipContent, TooltipTrigger } from "@roprgm/ui/tooltip";import { GithubIcon } from "@/components/icons/github";-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; tooltips carry the label and shortcut. Without a handler the tabs are inert. */+/** Icon tabs in a column at the window's left edge; tooltips carry the label and shortcut. Without a handler the tabs are inert. */export function ToolTabList({selected,onSelect,@@ -17,9 +16,9 @@ export function ToolTabList({<Tabsvalue={selected}onValueChange={onSelect}- className="flex shrink-0 gap-1 overflow-auto border-edge border-b surface-panel p-1.5 md:w-11 md:flex-col md:border-r md:border-b-0"+ className="flex w-11 shrink-0 flex-col gap-1 overflow-auto border-edge border-r surface-panel p-1.5">- <TabList aria-label="Tools" className="md:flex-col">+ <TabList aria-label="Tools" className="flex-col">{editing.map((entry) => (<Tooltip key={entry.id}><TooltipTrigger@@ -48,7 +47,7 @@ export function ToolTabList({target="_blank"rel="noreferrer"aria-label="OpenLight on GitHub"- className="ml-auto grid place-items-center rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-foreground md:mt-auto md:ml-0"+ className="mt-auto grid place-items-center rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-foreground"/>}>@@ -62,10 +61,5 @@ export function ToolTabList({export function ToolRail() {const { tool, setTool } = useTool();- useShortcuts(- Object.fromEntries(- tools.map((entry) => [entry.key, () => setTool(entry)] as const),- ),- );return <ToolTabList selected={tool} onSelect={setTool} />;}diff --git a/src/app/editor/tools.tsx b/src/app/editor/tools.tsxindex e2388da..bfa22f3 100644--- a/src/app/editor/tools.tsx+++ b/src/app/editor/tools.tsx@@ -21,6 +21,7 @@ import { BrushOptions } from "@/features/layers/brush-options";import { BrushOverlay } from "@/features/layers/brush-overlay";import { addLayer } from "@/features/layers/edits";import { GradientOverlay } from "@/features/layers/gradient-overlay";+import { useShortcuts } from "@/hooks/use-shortcuts";import { ExportMode } from "./export";import { createLayer } from "./layers";@@ -60,6 +61,7 @@ function HealCanvas() {const adjust = {id: "adjust",label: "Adjust",+ shortLabel: "Adjust",key: "a",Icon: AdjustIcon,group: "edit",@@ -68,6 +70,7 @@ const adjust = {export const exportTool = {id: "export",label: "Export",+ shortLabel: "Export",key: "e",Icon: ExportIcon,group: "output",@@ -85,6 +88,7 @@ export const tools = [{id: "brush",label: "Brush",+ shortLabel: "Brush",key: "b",Icon: BrushIcon,group: "edit",@@ -94,6 +98,7 @@ export const tools = [{id: "linear",label: "Linear gradient",+ shortLabel: "Linear",key: "l",Icon: LinearGradientIcon,group: "edit",@@ -102,6 +107,7 @@ export const tools = [{id: "radial",label: "Radial gradient",+ shortLabel: "Radial",key: "r",Icon: RadialGradientIcon,group: "edit",@@ -110,6 +116,7 @@ export const tools = [{id: "heal",label: "Healing",+ shortLabel: "Heal",key: "h",Icon: HealIcon,group: "edit",@@ -119,6 +126,7 @@ export const tools = [{id: "crop",label: "Crop",+ shortLabel: "Crop",key: "c",Icon: CropIcon,group: "edit",@@ -129,7 +137,13 @@ export const tools = [export type Tool = (typeof tools)[number];+/** Holds the active tool, and each tool's key selects it in either layout. */export function ToolProvider({ children }: { children: ReactNode }) {const [tool, setTool] = useState<Tool>(adjust);+ useShortcuts(+ Object.fromEntries(+ tools.map((entry) => [entry.key, () => setTool(entry)] as const),+ ),+ );return <ToolContext value={{ tool, setTool }}>{children}</ToolContext>;}diff --git a/src/components/editor/dock.tsx b/src/components/editor/dock.tsxnew file mode 100644index 0000000..6854b85--- /dev/null+++ b/src/components/editor/dock.tsx@@ -0,0 +1,121 @@+import { Chip } from "@roprgm/ui/chip";+import { cn } from "cn";+import { type ReactNode, useState } from "react";+import { DialRow, formatValue } from "@/components/ui/dial";+import type { Parameter } from "./parameter";++/**+ * The mobile layout's controls under the canvas, over the frame's tab bar. It takes its view's height,+ * up to half the editor, where a view that holds more scrolls. An inert dock dims its contents.+ */+export function EditorDock({+ inert,+ children,+}: {+ inert?: boolean;+ children: ReactNode;+}) {+ return (+ <div+ inert={inert}+ aria-hidden={inert}+ data-inert={inert}+ className="flex max-h-1/2 shrink-0 flex-col border-edge border-t surface-panel *:not-last:shadow-[inset_0_-1px_0_var(--color-edge)] data-[inert=true]:*:opacity-50"+ >+ {children}+ </div>+ );+}++/** A choice among a few views or modes, as flat chips in a pill. */+export function DockChips<T extends string>({+ label,+ items,+ value,+ onChange,+}: {+ label: string;+ items: readonly (readonly [T, string])[];+ value: T;+ onChange: (value: T) => void;+}) {+ return (+ <fieldset+ aria-label={label}+ className="flex max-w-full gap-0.5 overflow-fade-x rounded-full bg-field p-0.5"+ >+ {items.map(([id, name]) => (+ // Two names may share a value, as Original and 3:2 do on a 3:2 photo.+ <Chip+ key={name}+ aria-pressed={id === value}+ onClick={() => onChange(id)}+ >+ {name}+ </Chip>+ ))}+ </fieldset>+ );+}++function Readout({ parameter }: { parameter: Parameter }) {+ return (+ <p className="flex items-baseline gap-2 whitespace-nowrap">+ <span className="text-muted">{parameter.label}</span>+ <span className="font-medium text-foreground tabular-nums">+ {formatValue(parameter.value, parameter.step, parameter.format)}+ </span>+ </p>+ );+}++/**+ * A dock view: a centered header, such as chips, with an optional action at its end, over a row of+ * dials or other content. While a dial drags, its name and value take the header's place, above the finger.+ * Dials keep the dock low; `tall` raises it for a graph such as the curve, and the change eases.+ */+export function DockControls({+ header,+ action,+ parameters,+ tall,+ children,+}: {+ header?: ReactNode;+ action?: ReactNode;+ parameters?: readonly Parameter[];+ tall?: boolean;+ children?: ReactNode;+}) {+ const [scrub, setScrub] = useState<string | null>(null);+ const scrubbed = parameters?.find((parameter) => parameter.id === scrub);+ return (+ <section+ className={cn(+ "flex min-h-0 shrink-0 flex-col pb-3 transition-[height] duration-200 ease-out motion-reduce:transition-none",+ tall ? "h-60" : parameters && "h-36",+ )}+ >+ <div className="relative flex h-12 shrink-0 items-center justify-center px-3">+ <div className="flex min-w-0 max-w-full justify-center">+ {scrubbed ? <Readout parameter={scrubbed} /> : header}+ </div>+ {action && (+ <div className="absolute inset-y-0 right-3 flex items-center">+ {action}+ </div>+ )}+ </div>+ {parameters ? (+ // A new set of dials starts again from its first page.+ <DialRow+ key={parameters.map((parameter) => parameter.id).join()}+ dials={parameters}+ onScrub={setScrub}+ />+ ) : (+ children+ )}+ </section>+ );+}diff --git a/src/components/editor/layout.tsx b/src/components/editor/layout.tsxnew file mode 100644index 0000000..cc3564b--- /dev/null+++ b/src/components/editor/layout.tsx@@ -0,0 +1,65 @@+import { cn } from "cn";+import type { ReactNode } from "react";+import { useMediaQuery } from "@/hooks/use-media-query";+import { EditorDock } from "./dock";+import { EditorPanel } from "./panel";++/** Tailwind's `md` breakpoint, written as its media query, so an `md:` class and this switch agree. */+const desktopQuery = "(width >= 48rem)";++/** The one decision between the two layouts: a sidebar beside the canvas, or a dock under it. */+export function useDesktopLayout() {+ return useMediaQuery(desktopQuery);+}++/**+ * The editor's frame around every view: the tool rail at the left on desktop, the dock's tab bar at+ * the bottom on mobile. It outlives the views, so the rail and the tabs keep focus as tools change.+ */+export function EditorFrame({+ rail,+ tabs,+ children,+}: {+ rail: ReactNode;+ tabs: ReactNode;+ children: ReactNode;+}) {+ const desktop = useDesktopLayout();+ return (+ <div className={cn("flex min-h-0 flex-1", !desktop && "flex-col")}>+ {desktop && rail}+ {children}+ {!desktop && tabs}+ </div>+ );+}++/**+ * A view's canvas and controls in the frame: the sidebar beside the canvas on desktop, the dock under+ * it on mobile. The canvas comes first in both, so crossing the breakpoint moves it without mounting+ * it again; the sidebar and the dock swap. `dock` defaults to `panel`.+ */+export function EditorLayout({+ canvas,+ panel,+ dock = panel,+ inert,+}: {+ canvas: ReactNode;+ panel: ReactNode;+ dock?: ReactNode;+ inert?: boolean;+}) {+ const desktop = useDesktopLayout();+ return (+ <>+ {canvas}+ {desktop ? (+ <EditorPanel inert={inert}>{panel}</EditorPanel>+ ) : (+ <EditorDock inert={inert}>{dock}</EditorDock>+ )}+ </>+ );+}diff --git a/src/components/editor/panel.tsx b/src/components/editor/panel.tsxindex 1a933ba..1572058 100644--- a/src/components/editor/panel.tsx+++ b/src/components/editor/panel.tsx@@ -12,8 +12,8 @@ import { CloseIcon } from "@/components/icons/close";import { useEditorSession } from "./session";/**- * The resizable side panel, a bottom sheet on mobile. Its sections stack in the order written,- * with a line between each; give one a PanelBody to scroll. An inert panel dims its contents.+ * The resizable sidebar of the desktop layout. Its sections stack in the order written, with a line+ * between each; give one a PanelBody to scroll. An inert panel dims its contents.*/export function EditorPanel({inert,@@ -34,9 +34,8 @@ export function EditorPanel({// Inert content is already hidden from assistive technology; say so for tools that read ARIA only.aria-hidden={inert}data-inert={inert}- // An edge parts it from the canvas: along the top as a bottom sheet, on the left beside it.className={cn(- "relative flex h-[45%] min-h-0 w-full shrink-0 flex-col md:w-(--width) border-edge surface-panel max-md:border-t md:h-auto md:border-l data-[inert=true]:*:opacity-50",+ "relative flex min-h-0 w-(--width) shrink-0 flex-col border-edge border-l surface-panel data-[inert=true]:*:opacity-50",className,)}style={{ "--width": `${width}px` } as CSSProperties}diff --git a/src/components/editor/parameter.ts b/src/components/editor/parameter.tsnew file mode 100644index 0000000..338aacf--- /dev/null+++ b/src/components/editor/parameter.ts@@ -0,0 +1,9 @@+import type { DialItem } from "@/components/ui/dial";++/** A number a feature exposes once and each layout draws: a Slider in the sidebar, a Dial in the dock. */+export type Parameter = DialItem & {+ /** Colors painting a slider's bar. */+ stops?: readonly string[];+ /** A slider's minimum digit width, in characters. */+ valueWidth?: number;+};diff --git a/src/components/editor/toolbar-density.tsx b/src/components/editor/toolbar-density.tsxindex c789242..b3fdffb 100644--- a/src/components/editor/toolbar-density.tsx+++ b/src/components/editor/toolbar-density.tsx@@ -1,13 +1,16 @@import { createContext, useContext } from "react";-/** How much room the bar has: sliders with bars, fields only, or a column inside the overflow menu. */-export type BarDensity = "full" | "compact" | "menu";+/**+ * Where tool options draw and how much room they have: in the bar, sliders with bars or fields only;+ * a column inside its overflow menu; or dials in the mobile dock.+ */+export type BarDensity = "full" | "compact" | "menu" | "dock";export const Density = createContext<BarDensity>("full");export function useBarDensity() {return useContext(Density);}export function barSlider(density: BarDensity) {- if (density === "menu") {+ if (density === "menu" || density === "dock") {return "panel";}return density === "full" ? "toolbar" : "compact";diff --git a/src/components/icons/layers.tsx b/src/components/icons/layers.tsxnew file mode 100644index 0000000..4caa942--- /dev/null+++ b/src/components/icons/layers.tsx@@ -0,0 +1,10 @@+import { Icon, type IconProps } from "./icon";++export function LayersIcon(props: IconProps) {+ return (+ <Icon {...props}>+ <path d="m12 4 8 4-8 4-8-4 8-4Z" />+ <path d="m4 12 8 4 8-4M4 16l8 4 8-4" />+ </Icon>+ );+}diff --git a/src/components/ui/dial.tsx b/src/components/ui/dial.tsxnew file mode 100644index 0000000..a2f0cde--- /dev/null+++ b/src/components/ui/dial.tsx@@ -0,0 +1,416 @@+import { IconButton } from "@roprgm/ui/icon-button";+import { cn } from "cn";+import {+ type KeyboardEvent,+ type PointerEvent,+ useLayoutEffect,+ useRef,+ useState,+} from "react";++export type DialProps = {+ label: string;+ value: number;+ onChange: (value: number) => void;+ /** True while a pointer or key is down on it, so a caller can group its changes into one edit. */+ onEditingChange?: (editing: boolean) => void;+ /** True while a drag moves it, so a caller can show its value away from the finger. */+ onScrub?: (scrubbing: boolean) => void;+ min: number;+ max: number;+ step?: number;+ /** Restored by a double tap. */+ defaultValue?: number;+ /** Where the arc starts: `defaultValue`, or else `min`. */+ origin?: number;+ format?: (value: number) => string;+ /** A swatch in the middle names the dial, and the value moves below it. */+ color?: string;+};++const radius = 21;+const circumference = 2 * Math.PI * radius;+/** A drag across this many pixels sweeps the whole range. */+const sweep = 600;+const doubleTap = 300;++const keySteps: Record<string, number> = {+ ArrowRight: 1,+ ArrowUp: 1,+ ArrowLeft: -1,+ ArrowDown: -1,+ PageUp: 10,+ PageDown: -10,+};++/** The value as the dial writes it: to the step's decimals, then through `format`. */+export function formatValue(+ value: number,+ step = 1,+ format?: (value: number) => string,+) {+ const fixed = value.toFixed(`${step}`.split(".")[1]?.length ?? 0);+ return format?.(Number(fixed)) ?? fixed;+}++/** The arc from the origin to the value: clockwise from the top for more, the other way for less. */+function Arc({+ value,+ min,+ max,+ origin,+}: {+ value: number;+ min: number;+ max: number;+ origin: number;+}) {+ const centered = origin > min && origin < max;+ const reach = value >= origin ? max - origin : origin - min;+ const fraction = reach ? (value - origin) / reach : 0;+ const length = Math.abs(fraction) * circumference * (centered ? 0.5 : 1);+ return (+ <svg+ aria-hidden="true"+ viewBox="0 0 48 48"+ className="absolute inset-0 size-full fill-none stroke-[2.5]"+ >+ <circle className="stroke-hover" cx="24" cy="24" r={radius} />+ {length > 0.1 && (+ <circle+ className="stroke-muted group-data-[scrubbing=true]:stroke-foreground"+ cx="24"+ cy="24"+ r={radius}+ strokeLinecap="round"+ strokeDasharray={`${length} ${circumference}`}+ transform={`${fraction < 0 ? "scale(-1 1) translate(-48 0)" : ""} rotate(-90 24 24)`}+ />+ )}+ </svg>+ );+}++/**+ * A number set by dragging anywhere on it, for touch: right or up adds, left or down takes away.+ * A double tap restores the default, and the arrow keys step it.+ */+export function Dial({+ label,+ value,+ onChange,+ onEditingChange,+ onScrub,+ min,+ max,+ step = 1,+ defaultValue,+ origin = defaultValue ?? min,+ format,+ color,+}: DialProps) {+ const drag = useRef<{+ x: number;+ y: number;+ value: number;+ moved: boolean;+ } | null>(null);+ const lastTap = useRef(Number.NEGATIVE_INFINITY);+ const [scrubbing, setScrubbing] = useState(false);+ const decimals = `${step}`.split(".")[1]?.length ?? 0;+ const snap = (next: number) =>+ Math.min(+ max,+ Math.max(min, Number((Math.round(next / step) * step).toFixed(decimals))),+ );+ const text = formatValue(value, step, format);+ const edited = defaultValue !== undefined && value !== defaultValue;++ function pointerDown(event: PointerEvent<HTMLDivElement>) {+ if (event.button !== 0) {+ return;+ }+ event.currentTarget.setPointerCapture(event.pointerId);+ onEditingChange?.(true);+ if (event.timeStamp - lastTap.current < doubleTap) {+ lastTap.current = Number.NEGATIVE_INFINITY;+ if (defaultValue !== undefined) {+ onChange(defaultValue);+ }+ return;+ }+ lastTap.current = event.timeStamp;+ drag.current = {+ x: event.clientX,+ y: event.clientY,+ value,+ moved: false,+ };+ setScrubbing(true);+ onScrub?.(true);+ }+ function pointerMove(event: PointerEvent<HTMLDivElement>) {+ const current = drag.current;+ if (!current) {+ return;+ }+ const distance = event.clientX - current.x + current.y - event.clientY;+ current.x = event.clientX;+ current.y = event.clientY;+ current.moved ||= distance !== 0;+ current.value = Math.min(+ max,+ Math.max(min, current.value + (distance * (max - min)) / sweep),+ );+ const next = snap(current.value);+ if (next !== value) {+ onChange(next);+ }+ }+ function pointerUp() {+ // A drag is not the first tap of a double tap.+ if (drag.current?.moved) {+ lastTap.current = Number.NEGATIVE_INFINITY;+ }+ drag.current = null;+ setScrubbing(false);+ onScrub?.(false);+ onEditingChange?.(false);+ }+ function keyDown(event: KeyboardEvent) {+ const steps = keySteps[event.key];+ const next =+ event.key === "Home" ? min : event.key === "End" ? max : undefined;+ if (steps === undefined && next === undefined) {+ return;+ }+ event.preventDefault();+ onEditingChange?.(true);+ onChange(next ?? snap(value + steps * step * (event.shiftKey ? 10 : 1)));+ }++ return (+ <div+ role="slider"+ tabIndex={0}+ aria-label={label}+ aria-valuemin={min}+ aria-valuemax={max}+ aria-valuenow={value}+ aria-valuetext={text}+ data-scrubbing={scrubbing}+ onPointerDown={pointerDown}+ onPointerMove={pointerMove}+ onPointerUp={pointerUp}+ onPointerCancel={pointerUp}+ onKeyDown={keyDown}+ onKeyUp={() => onEditingChange?.(false)}+ onBlur={() => onEditingChange?.(false)}+ className="group flex cursor-move touch-none flex-col items-center gap-1.5 rounded-md select-none focus-ring"+ >+ <span+ className={cn(+ "relative grid place-items-center rounded-full surface-sunken tabular-nums transition group-data-[scrubbing=true]:scale-108",+ color ? "size-9" : "size-11.5",+ edited ? "text-foreground" : "text-faint",+ )}+ >+ <Arc value={value} min={min} max={max} origin={origin} />+ {color ? (+ <span+ className="size-4 rounded-full"+ style={{ backgroundColor: color }}+ />+ ) : (+ text+ )}+ </span>+ <span+ className={cn(+ "whitespace-nowrap text-muted group-data-[scrubbing=true]:text-foreground",+ color && "tabular-nums",+ )}+ >+ {color ? text : label}+ </span>+ </div>+ );+}++/**+ * Room each dial keeps beyond its circle or label, the most of a row's spare width each takes on, and+ * the fraction of a dial that peeks in when paged.+ */+const gaps = { dial: 12, swatch: 8 };+const maxShare = 28;+const peek = 0.4;+const padding = 8;++type RowLayout =+ | { width: number; paged: false; widths: number[] }+ | { width: number; paged: true; slot: number; perPage: number };++export type DialItem = DialProps & { id: string };++/**+ * Dials in one row that never scrolls under a finger, so a drag on a dial always moves its value.+ * Each takes its natural width plus a gap and a share of what is left, up to a limit, and the row+ * centers what it doesn't fill. When they don't fit they page, with the next one peeking in under+ * an arrow. Swatch dials sit closer.+ */+export function DialRow({+ dials,+ onScrub,+}: {+ dials: readonly DialItem[];+ /** The dial a drag is moving, or null. */+ onScrub?: (id: string | null) => void;+}) {+ const row = useRef<HTMLDivElement>(null);+ const cells = useRef(new Map<string, HTMLDivElement>());+ const [layout, setLayout] = useState<RowLayout | null>(null);+ const [page, setPage] = useState(0);+ const gap = dials.some((dial) => dial.color) ? gaps.swatch : gaps.dial;+ const ids = dials.map((dial) => dial.id).join();+ useLayoutEffect(() => {+ const element = row.current;+ if (!element) {+ return;+ }+ const order = ids.split(",");+ function measure(width: number) {+ const natural = order.map(+ (id) =>+ (cells.current.get(id)?.firstElementChild?.clientWidth ?? 0) + gap,+ );+ const inner = width - padding * 2;+ const total = natural.reduce((sum, next) => sum + next, 0);+ if (total <= inner) {+ const share = Math.min(maxShare, (inner - total) / order.length);+ setLayout({+ width,+ paged: false,+ widths: natural.map((w) => w + share),+ });+ return;+ }+ const perPage = Math.max(+ 1,+ Math.floor(width / Math.max(...natural) - peek),+ );+ setLayout({+ width,+ paged: true,+ perPage,+ slot: width / (perPage + peek),+ });+ }+ measure(element.clientWidth);+ const observer = new ResizeObserver(([entry]) =>+ measure(entry.contentRect.width),+ );+ observer.observe(element);+ return () => observer.disconnect();+ }, [ids, gap]);++ const count = dials.length;+ const pages = layout?.paged+ ? Math.ceil((count - layout.perPage) / layout.perPage) + 1+ : 1;+ const current = Math.min(page, pages - 1);+ const before = Boolean(layout?.paged) && current > 0;+ const after = Boolean(layout?.paged) && current < pages - 1;+ let shift = 0;+ let fade = 0;+ if (layout?.paged) {+ fade = layout.slot * peek;+ if (current === pages - 1) {+ shift = count * layout.slot - layout.width;+ } else if (current > 0) {+ shift = (current * layout.perPage - peek) * layout.slot;+ }+ }+ const mask = [+ before ? `transparent, #000 ${fade}px` : "#000",+ after ? `#000 calc(100% - ${fade}px), transparent` : "#000",+ ].join(", ");+ function width(index: number) {+ if (!layout) {+ return undefined;+ }+ return layout.paged ? layout.slot : layout.widths[index];+ }++ return (+ <div className="relative flex min-h-0 flex-1 items-center">+ <div+ ref={row}+ className="h-full w-full overflow-hidden"+ style={{ maskImage: `linear-gradient(to right, ${mask})` }}+ >+ <div+ className={cn(+ "flex h-full transition-transform duration-300",+ !layout?.paged && "justify-center px-2",+ )}+ style={{ transform: `translateX(${-shift}px)` }}+ >+ {dials.map(({ id, ...dial }, index) => (+ <div+ key={id}+ ref={(cell) => {+ if (cell) {+ cells.current.set(id, cell);+ } else {+ cells.current.delete(id);+ }+ }}+ className="flex shrink-0 items-center justify-center"+ style={{ width: width(index) }}+ >+ <Dial+ {...dial}+ onScrub={(scrubbing) => onScrub?.(scrubbing ? id : null)}+ />+ </div>+ ))}+ </div>+ </div>+ {before && (+ <IconButton+ label="Previous controls"+ className="absolute left-0"+ onClick={() => setPage(current - 1)}+ >+ <Chevron flip />+ </IconButton>+ )}+ {after && (+ <IconButton+ label="More controls"+ className="absolute right-0"+ onClick={() => setPage(current + 1)}+ >+ <Chevron />+ </IconButton>+ )}+ </div>+ );+}++function Chevron({ flip }: { flip?: boolean }) {+ return (+ <svg+ aria-hidden="true"+ viewBox="0 0 24 24"+ className={cn(+ "size-4 fill-none stroke-current stroke-2",+ flip && "-scale-x-100",+ )}+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="m9 18 6-6-6-6" />+ </svg>+ );+}diff --git a/src/core/renderer/graph.ts b/src/core/renderer/graph.tsindex 66aa0fc..e664b01 100644--- a/src/core/renderer/graph.ts+++ b/src/core/renderer/graph.ts@@ -44,9 +44,18 @@ function plan(outputs: readonly RenderImage[]) {return { order, uses, live };}+const sizeKey = (image: { size: readonly number[]; format: string }) =>+ `${image.size[0]}x${image.size[1]} ${image.format}`;+/** Owns effects, storage buffers, and transient targets for one renderer. */export function createRenderGraph(gpu: Gpu, timer?: Timer) {const pool: Target[] = [];+ /**+ * How many targets of each size the last two distinct sets of sizes used, most recent first. An+ * interactive proxy and the full image alternate between two such sets, and keeping both saves+ * reallocating full-size targets on every gesture, which a phone's GPU memory can't absorb.+ */+ let recent: Map<string, number>[] = [];const effects = new Map<string, Pass>();let passes: string[] = [];let disposed = false;@@ -88,11 +97,7 @@ export function createRenderGraph(gpu: Gpu, timer?: Timer) {}return pass.effect;}- function acquire(- node: RenderNode,- live: ReadonlySet<Target>,- written: ReadonlySet<Target>,- ) {+ function acquire(node: RenderNode, live: ReadonlySet<Target>) {const exact = pool.find((image) =>!live.has(image) &&@@ -103,15 +108,6 @@ export function createRenderGraph(gpu: Gpu, timer?: Timer) {if (exact) {return exact;}- // Resize only targets not referenced by commands in this frame.- const spare = pool.find(- (image) =>- !live.has(image) && !written.has(image) && image.format === node.format,- );- if (spare) {- spare.resize(node.size);- return spare;- }const image = target(gpu, { size: node.size, format: node.format });pool.push(image);return image;@@ -157,7 +153,7 @@ export function createRenderGraph(gpu: Gpu, timer?: Timer) {]),),});- const output = acquire(node, live, written);+ const output = acquire(node, live);live.add(output);written.add(output);frame.pass({ target: output, timer: timer?.span(node.name) }, pass);@@ -171,12 +167,43 @@ export function createRenderGraph(gpu: Gpu, timer?: Timer) {}}});- // Avoid retaining old crop sizes or the peak of a previously active effect.+ const used = new Map<string, number>();+ for (const image of written) {+ used.set(sizeKey(image), (used.get(sizeKey(image)) ?? 0) + 1);+ }+ // Sizes that one set contains of the other are the same mode with more or fewer effects: the new+ // counts replace the old, so the peak of an effect since turned off is let go.+ const contains = (a: Map<string, number>, b: Map<string, number>) =>+ [...b.keys()].every((key) => a.has(key));+ const sameMode = (counts: Map<string, number>) =>+ contains(counts, used) || contains(used, counts);+ recent = [used, ...recent.filter((counts) => !sameMode(counts))].slice(+ 0,+ 2,+ );+ // Past these counts, an idle target is an old crop size or an old peak.+ const kept = new Map<string, number>();+ for (const image of pool) {+ if (written.has(image) || live.has(image)) {+ kept.set(sizeKey(image), (kept.get(sizeKey(image)) ?? 0) + 1);+ }+ }for (let i = pool.length - 1; i >= 0; i--) {- if (!written.has(pool[i]) && !live.has(pool[i])) {- pool[i].color.dispose();- pool.splice(i, 1);+ const image = pool[i];+ if (written.has(image) || live.has(image)) {+ continue;}+ const key = sizeKey(image);+ const allowed = Math.max(+ ...recent.map((counts) => counts.get(key) ?? 0),+ );+ const count = kept.get(key) ?? 0;+ if (count < allowed) {+ kept.set(key, count + 1);+ continue;+ }+ image.color.dispose();+ pool.splice(i, 1);}passes = order.map((node) => node.name);return outputs.map(resolve);@@ -203,6 +230,7 @@ export function createRenderGraph(gpu: Gpu, timer?: Timer) {image.color.dispose();}pool.length = 0;+ recent = [];},};}diff --git a/src/features/adjustments/controls.tsx b/src/features/adjustments/controls.tsxindex aca1474..a6159c6 100644--- a/src/features/adjustments/controls.tsx+++ b/src/features/adjustments/controls.tsx@@ -1,7 +1,8 @@import { Slider } from "@roprgm/ui/slider";import type { ReactNode } from "react";+import type { Parameter } from "@/components/editor/parameter";import { useDocument } from "@/components/editor/session";-import type { Adjustments } from "@/core/document";+import type { Adjustments, EditorDocument } from "@/core/document";import { setAdjustments } from "./edits";import { adjustmentLimits, defaultAdjustments } from "./model";@@ -17,7 +18,7 @@ const stops: Partial<Record<keyof Adjustments, string[]>> = {],};-const tone = [+export const tone = [["exposure", "Exposure"],["contrast", "Contrast"],["highlights", "Highlights"],@@ -25,7 +26,7 @@ const tone = [["whites", "Whites"],["blacks", "Blacks"],] as const;-const color = [+export const color = [["incrementalTemperature", "Temp"],["incrementalTint", "Tint"],["vibrance", "Vibrance"],@@ -33,6 +34,25 @@ const color = [] as const;type Control = (typeof tone)[number] | (typeof color)[number];+export function adjustmentParameters(+ document: EditorDocument,+ id: string,+ adjustments: Readonly<Adjustments>,+ controls: readonly Control[],+): Parameter[] {+ return controls.map(([name, label]) => ({+ id: name,+ label,+ value: adjustments[name],+ step: name === "exposure" ? 0.01 : 1,+ stops: name === "vibrance" ? stops.saturation : stops[name],+ min: -adjustmentLimits[name],+ max: adjustmentLimits[name],+ defaultValue: defaultAdjustments[name],+ onChange: (value) => setAdjustments(document, { [name]: value }, id),+ }));+}+function AdjustmentSliders({id,adjustments,@@ -43,23 +63,9 @@ function AdjustmentSliders({controls: readonly Control[];}) {const document = useDocument();- return controls.map(([name, label]) => {- const step = name === "exposure" ? 0.01 : 1;- const gradient = name === "vibrance" ? stops.saturation : stops[name];- return (- <Slider- key={name}- label={label}- value={adjustments[name]}- step={step}- stops={gradient}- min={-adjustmentLimits[name]}- max={adjustmentLimits[name]}- defaultValue={defaultAdjustments[name]}- onChange={(value) => setAdjustments(document, { [name]: value }, id)}- />- );- });+ return adjustmentParameters(document, id, adjustments, controls).map(+ ({ id, ...parameter }) => <Slider key={id} {...parameter} />,+ );}/** The temperature slot replaces the incremental temperature and tint sliders. */diff --git a/src/features/color-mixer/controls.tsx b/src/features/color-mixer/controls.tsxindex c7bc520..d13d000 100644--- a/src/features/color-mixer/controls.tsx+++ b/src/features/color-mixer/controls.tsx@@ -3,8 +3,9 @@ import { Slider } from "@roprgm/ui/slider";import { Tab, TabList, TabPanel, Tabs } from "@roprgm/ui/tabs";import { Tooltip, TooltipContent, TooltipTrigger } from "@roprgm/ui/tooltip";import { useState } from "react";+import type { Parameter } from "@/components/editor/parameter";import { useDocument } from "@/components/editor/session";-import type { ColorMixer } from "@/core/document";+import type { ColorMixer, EditorDocument } from "@/core/document";import { setColorMixer } from "./edits";import { channels, colors, type MixerChannel } from "./model";@@ -18,51 +19,49 @@ function gradient(hue: number, channel: MixerChannel) {return [20, 55, 85].map((lightness) => `hsl(${hue} 65% ${lightness}%)`);}+/** One channel of every color range, each shown by its swatch. */+export function mixerParameters(+ document: EditorDocument,+ layerId: string,+ mixer: ColorMixer,+ channel: MixerChannel,+): Parameter[] {+ return colors.map((color, index) => ({+ id: color.id,+ label: `${color.label} ${channel}`,+ value: mixer[channel][index],+ min: -100,+ max: 100,+ defaultValue: 0,+ stops: gradient(color.hue, channel),+ color: `hsl(${color.hue} 65% 55%)`,+ onChange: (value) =>+ setColorMixer(document, color.id, { [channel]: value }, layerId),+ }));+}+function ColorSlider({- index,- channel,- value,- layerId,+ name,+ parameter: { id, ...parameter },}: {- index: number;- channel: MixerChannel;- value: number;- layerId: string;+ name: string;+ parameter: Parameter;}) {- const document = useDocument();- const color = colors[index];- const label = `${color.label} ${channel}`;- const change = (value: number) =>- setColorMixer(document, color.id, { [channel]: value }, layerId);return (<Tooltip><TooltipTriggerrender={<div className="flex min-w-0 flex-col items-center gap-1"><ScrubInput- aria-label={`${label} value`}+ {...parameter}+ aria-label={`${parameter.label} value`}className="w-full justify-center px-0 tracking-tight"- value={value}- defaultValue={0}- onChange={change}- min={-100}- max={100}- />- <Slider- orientation="vertical"- label={label}- value={value}- onChange={change}- min={-100}- max={100}- defaultValue={0}- stops={gradient(color.hue, channel)}- color={`hsl(${color.hue} 65% 55%)`}/>+ <Slider {...parameter} orientation="vertical" /></div>}/>- <TooltipContent>{color.label}</TooltipContent>+ <TooltipContent>{name}</TooltipContent></Tooltip>);}@@ -74,6 +73,7 @@ export function ColorMixerControls({id: string;mixer: ColorMixer;}) {+ const document = useDocument();const [channel, setChannel] = useState<MixerChannel>("hue");return (<Tabs@@ -95,15 +95,15 @@ export function ColorMixerControls({</TabList>{/* One panel shows every channel, so it follows the tab that's selected. */}<TabPanel value={channel} className="grid grid-cols-8">- {colors.map((color, index) => (- <ColorSlider- key={color.id}- index={index}- channel={channel}- value={mixer[channel][index]}- layerId={layerId}- />- ))}+ {mixerParameters(document, layerId, mixer, channel).map(+ (parameter, index) => (+ <ColorSlider+ key={parameter.id}+ name={colors[index].label}+ parameter={parameter}+ />+ ),+ )}</TabPanel></Tabs>);diff --git a/src/features/crop/view.tsx b/src/features/crop/view.tsxindex 0ea6c69..a4bd63e 100644--- a/src/features/crop/view.tsx+++ b/src/features/crop/view.tsx@@ -2,13 +2,16 @@ import { Button } from "@roprgm/ui/button";import { Select } from "@roprgm/ui/select";import { Slider } from "@roprgm/ui/slider";import { Tooltip, TooltipContent, TooltipTrigger } from "@roprgm/ui/tooltip";-import { useState } from "react";+import { type KeyboardEvent, useState } from "react";+import { DockChips, DockControls } from "@/components/editor/dock";import { Image } from "@/components/editor/image";-import { EditorPanel, PanelBody, PanelHeader } from "@/components/editor/panel";+import { EditorLayout } from "@/components/editor/layout";+import { PanelBody, PanelHeader } from "@/components/editor/panel";import { useDocument, useEditorSession } from "@/components/editor/session";import { EditorViewport, ViewportStage } from "@/components/editor/viewport";import { FlipIcon } from "@/components/icons/flip";import { RotateIcon } from "@/components/icons/rotate";+import { Dial } from "@/components/ui/dial";import { imageFrame, type Point } from "@/core/image/frame";import { useShortcuts } from "@/hooks/use-shortcuts";import { applyCrop } from "./edits";@@ -22,6 +25,45 @@ const actions = [{ label: "Flip vertical", flip: 1, transform: "rotate(90deg)" },] as const;+function ActionButton({+ action,+ onClick,+}: {+ action: (typeof actions)[number];+ onClick: () => void;+}) {+ const Icon = "turn" in action ? RotateIcon : FlipIcon;+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ aria-label={action.label}+ className="flex h-9 items-center justify-center gap-1 rounded-md px-1"+ onClick={onClick}+ >+ <Icon style={{ transform: action.transform }} />+ {"turn" in action && <span>90°</span>}+ </Button>+ }+ />+ <TooltipContent>{action.label}</TooltipContent>+ </Tooltip>+ );+}++/** Enter on a panel button is its click; elsewhere it applies the crop. */+function keepEnter(event: KeyboardEvent) {+ if (+ event.key === "Enter" &&+ event.target instanceof Element &&+ event.target.closest("button")+ ) {+ event.stopPropagation();+ }+}+export function CropEditor({ onClose }: { onClose: () => void }) {const document = useDocument();const { camera } = useEditorSession();@@ -90,103 +132,145 @@ export function CropEditor({ onClose }: { onClose: () => void }) {setFrame(flip(frame, action.flip));}}- return (- <>- <EditorViewport size={reference} constrain={false}>- <ViewportStage>- <Image image="fullImage" geometry={frame} />- <CropOverlay- frame={frame}- source={source}- ratio={ratio}- onChange={setFrame}+ const rotation = {+ label: "Rotation",+ min: -45,+ max: 45,+ step: 0.1,+ value: frame.angle,+ defaultValue: 0,+ onChange: (angle: number) => setFrame(rotate(frame, angle, source)),+ };+ const size = `${frame.size.map(Math.round).join(" × ")} px`;+ // On a phone the ratios are chips, rotation a dial between the turns and flips, and the actions a footer.+ const dock = (+ <fieldset+ aria-label="Crop"+ className="flex min-h-0 min-w-0 flex-1 flex-col"+ onKeyDown={keepEnter}+ >+ <DockControls+ header={+ <DockChips+ label="Aspect ratio"+ items={ratioOptions.map(+ ({ value, label }) => [value, label] as const,+ )}+ value={ratio === null ? "free" : `${ratio}`}+ onChange={changeRatio}/>- </ViewportStage>- </EditorViewport>- <EditorPanel- onKeyDown={(event) => {- // Enter on a panel button is its click; the crop handles still apply.- if (- event.key === "Enter" &&- event.target instanceof Element &&- event.target.closest("button")- ) {- event.stopPropagation();- }- }}+ }>- <PanelBody header={<PanelHeader title="Crop" onClose={onClose} />}>- <section aria-label="Crop tool" className="space-y-5 p-3.5">- <div className="flex items-center justify-between text-muted">- Aspect ratio- <Select- raised- aria-label="Aspect ratio"- value={ratio === null ? "free" : `${ratio}`}- items={ratioOptions}- className="w-24"- onValueChange={(value) => value !== null && changeRatio(value)}- />- </div>- <section- aria-label="Rotate and flip image"- className="grid grid-cols-4 items-center gap-2"- >- <h3 className="col-span-3 text-muted">Rotate & flip</h3>- <Button- variant="ghost"- size="sm"- className="justify-self-end"- onClick={reset}- >- Reset- </Button>- {actions.map((action) => {- const Icon = "turn" in action ? RotateIcon : FlipIcon;- return (- <Tooltip key={action.label}>- <TooltipTrigger- render={- <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>- }- />- <TooltipContent>{action.label}</TooltipContent>- </Tooltip>- );- })}- </section>- <Slider- label="Rotation"- min={-45}- max={45}- step={0.1}- value={frame.angle}- defaultValue={0}- onChange={(angle) => setFrame(rotate(frame, angle, source))}+ <section+ aria-label="Rotate and flip image"+ className="flex min-h-0 flex-1 items-center justify-center gap-2 pb-3"+ >+ {actions.slice(0, 2).map((action) => (+ <ActionButton+ key={action.label}+ action={action}+ onClick={() => applyAction(action)}+ />+ ))}+ <Dial {...rotation} format={(angle) => `${angle}°`} />+ {actions.slice(2).map((action) => (+ <ActionButton+ key={action.label}+ action={action}+ onClick={() => applyAction(action)}/>- <p className="text-muted">- 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-muted">- {frame.size.map(Math.round).join(" × ")} px- </p>- </section>- </PanelBody>- <div className="p-3">- <Button size="lg" className="w-full" onClick={apply}>- Apply crop+ ))}+ </section>+ <div className="flex items-center gap-1.5 px-2.5">+ <Button variant="ghost" size="sm" onClick={reset}>+ Reset+ </Button>+ <span className="flex-1 truncate text-center text-muted tabular-nums">+ {size}+ </span>+ <Button variant="ghost" size="sm" onClick={onClose}>+ Cancel+ </Button>+ <Button size="sm" onClick={apply}>+ Apply</Button></div>- </EditorPanel>- </>+ </DockControls>+ </fieldset>+ );+ return (+ <EditorLayout+ canvas={+ <EditorViewport size={reference} constrain={false}>+ <ViewportStage>+ <Image image="fullImage" geometry={frame} />+ <CropOverlay+ frame={frame}+ source={source}+ ratio={ratio}+ onChange={setFrame}+ />+ </ViewportStage>+ </EditorViewport>+ }+ panel={+ <fieldset+ aria-label="Crop"+ className="flex min-h-0 min-w-0 flex-1 flex-col *:not-last:shadow-[inset_0_-1px_0_var(--color-edge)]"+ onKeyDown={keepEnter}+ >+ <PanelBody header={<PanelHeader title="Crop" onClose={onClose} />}>+ <section aria-label="Crop tool" className="space-y-5 p-3.5">+ <div className="flex items-center justify-between text-muted">+ Aspect ratio+ <Select+ raised+ aria-label="Aspect ratio"+ value={ratio === null ? "free" : `${ratio}`}+ items={ratioOptions}+ className="w-24"+ onValueChange={(value) =>+ value !== null && changeRatio(value)+ }+ />+ </div>+ <section+ aria-label="Rotate and flip image"+ className="grid grid-cols-4 items-center gap-2"+ >+ <h3 className="col-span-3 text-muted">Rotate & flip</h3>+ <Button+ variant="ghost"+ size="sm"+ className="justify-self-end"+ onClick={reset}+ >+ Reset+ </Button>+ {actions.map((action) => (+ <ActionButton+ key={action.label}+ action={action}+ onClick={() => applyAction(action)}+ />+ ))}+ </section>+ <Slider {...rotation} />+ <p className="text-muted">+ 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-muted">{size}</p>+ </section>+ </PanelBody>+ <div className="p-3">+ <Button size="lg" className="w-full" onClick={apply}>+ Apply crop+ </Button>+ </div>+ </fieldset>+ }+ dock={dock}+ />);}diff --git a/src/features/details/controls.tsx b/src/features/details/controls.tsxindex e87dc5a..6824e19 100644--- a/src/features/details/controls.tsx+++ b/src/features/details/controls.tsx@@ -1,9 +1,33 @@import { Slider } from "@roprgm/ui/slider";+import type { Parameter } from "@/components/editor/parameter";import { useDocument } from "@/components/editor/session";-import type { Details } from "@/core/document";+import type { Details, EditorDocument } from "@/core/document";import { setDetails } from "./edits";import { defaultDetails, detailLimits } from "./model";+const controls = [+ ["clarity", "Clarity", 1],+ ["sharpening", "Sharpening", 1],+ ["sharpenRadius", "Radius", 0.1],+] as const;++export function detailsParameters(+ document: EditorDocument,+ id: string,+ details: Readonly<Details>,+): Parameter[] {+ return controls.map(([name, label, step]) => ({+ id: name,+ label,+ value: details[name],+ min: detailLimits[name][0],+ max: detailLimits[name][1],+ step,+ defaultValue: defaultDetails[name],+ onChange: (value) => setDetails(document, { [name]: value }, id),+ }));+}+export function DetailsControls({id,details,@@ -12,24 +36,10 @@ export function DetailsControls({details: Readonly<Details>;}) {const document = useDocument();- const controls = [- ["clarity", "Clarity", 1],- ["sharpening", "Sharpening", 1],- ["sharpenRadius", "Radius", 0.1],- ] as const;return (<section className="flex flex-col gap-1.5 p-3.5">- {controls.map(([name, label, step]) => (- <Slider- key={name}- label={label}- value={details[name]}- min={detailLimits[name][0]}- max={detailLimits[name][1]}- step={step}- defaultValue={defaultDetails[name]}- onChange={(value) => setDetails(document, { [name]: value }, id)}- />+ {detailsParameters(document, id, details).map(({ id, ...parameter }) => (+ <Slider key={id} {...parameter} />))}</section>);diff --git a/src/features/heal/options.tsx b/src/features/heal/options.tsxindex 7546ce4..41875bb 100644--- a/src/features/heal/options.tsx+++ b/src/features/heal/options.tsx@@ -2,6 +2,8 @@ import { Chip } from "@roprgm/ui/chip";import { Slider } from "@roprgm/ui/slider";import { Tooltip, TooltipContent, TooltipTrigger } from "@roprgm/ui/tooltip";import { useBrushTool } from "@/components/editor/brush-tool";+import { DockControls } from "@/components/editor/dock";+import type { Parameter } from "@/components/editor/parameter";import { useDocument, useSelectedLayer } from "@/components/editor/session";import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";import { setHealPatch } from "./edits";@@ -22,66 +24,74 @@ export function HealOptions() {layer?.kind === "heal"? layer.patches.find((patch) => patch.id === selectedPatch): undefined;- const variant = barSlider(useBarDensity());- const size = settings.size;+ const density = useBarDensity();const feather = selected?.feather ?? nextFeather;function changePatch(change: Parameters<typeof setHealPatch>[3]) {if (selected && layer?.kind === "heal") {setHealPatch(document, layer.id, selected.id, change);}}+ const parameters: Parameter[] = [+ {+ id: "size",+ label: "Size",+ value: settings.size,+ min: 1,+ max: maxSize,+ format: (value) => `${value}px`,+ valueWidth: `${maxSize}`.length,+ onEditingChange: setPreview,+ onChange: (value) => update({ size: Math.round(value) }),+ },+ {+ id: "feather",+ label: "Feather",+ value: feather * 100,+ min: 0,+ max: 100,+ format: (value) => `${value}%`,+ valueWidth: 3,+ onEditingChange: setPreview,+ onChange: (value) => {+ const feather = value / 100;+ setFeather(feather);+ changePatch({ feather });+ },+ },+ ];+ if (selected) {+ parameters.push({+ id: "opacity",+ label: "Opacity",+ value: selected.opacity * 100,+ min: 0,+ max: 100,+ format: (value) => `${value}%`,+ valueWidth: 3,+ onChange: (value) => changePatch({ opacity: value / 100 }),+ });+ }+ const automatic = source && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Chip onClick={() => setSource(undefined)}>Automatic source</Chip>+ }+ />+ <TooltipContent>+ Find each stroke's donor again; Alt-click sets one+ </TooltipContent>+ </Tooltip>+ );+ if (density === "dock") {+ return <DockControls header={automatic} parameters={parameters} />;+ }return (<>- <Slider- label="Size"- min={1}- max={maxSize}- format={(value) => `${value}px`}- valueWidth={`${maxSize}`.length}- variant={variant}- value={size}- onEditingChange={setPreview}- onChange={(value) => update({ size: Math.round(value) })}- />- <Slider- label="Feather"- value={feather * 100}- min={0}- max={100}- format={(value) => `${value}%`}- valueWidth={3}- variant={variant}- onEditingChange={setPreview}- onChange={(value) => {- const feather = value / 100;- setFeather(feather);- changePatch({ feather });- }}- />- {selected && (- <Slider- label="Opacity"- value={selected.opacity * 100}- min={0}- max={100}- format={(value) => `${value}%`}- valueWidth={3}- variant={variant}- onChange={(value) => changePatch({ opacity: value / 100 })}- />- )}- {source && (- <Tooltip>- <TooltipTrigger- render={- <Chip onClick={() => setSource(undefined)}>Automatic source</Chip>- }- />- <TooltipContent>- Find each stroke's donor again; Alt-click sets one- </TooltipContent>- </Tooltip>- )}+ {parameters.map(({ id, ...parameter }) => (+ <Slider key={id} {...parameter} variant={barSlider(density)} />+ ))}+ {automatic}</>);}diff --git a/src/features/histogram/histogram.ts b/src/features/histogram/histogram.tsindex 75f0603..91fddae 100644--- a/src/features/histogram/histogram.ts+++ b/src/features/histogram/histogram.ts@@ -1,8 +1,29 @@import { compute, type Gpu, type Target } from "vgpu";import shader from "./histogram.wgsl";+type Passes = {+ count: ReturnType<typeof compute>;+ finish: ReturnType<typeof compute>;+};++/** The counting passes, compiled once per GPU and shared, since a histogram mounts with each curve shown. */+const shared = new WeakMap<Gpu, Passes>();++function histogramPasses(gpu: Gpu) {+ let passes = shared.get(gpu);+ if (!passes) {+ passes = {+ count: compute(gpu, shader, { entry: "count" }),+ finish: compute(gpu, shader, { entry: "finish" }),+ };+ shared.set(gpu, passes);+ }+ return passes;+}+/** Counts an image into 256 bins per channel on the GPU and reads back normalized heights. */export function createHistogram(gpu: Gpu) {+ const { count, finish } = histogramPasses(gpu);const bins = gpu.device.createBuffer({size: 3072,usage: ["storage", "copy_dst"],@@ -11,18 +32,13 @@ export function createHistogram(gpu: Gpu) {size: 3072,usage: ["storage", "copy_src"],});- const count = compute(gpu, shader, { entry: "count", set: { bins } });- const finish = compute(gpu, shader, {- entry: "finish",- set: { bins, heights },- });const empty = new Uint32Array(768);return {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);+ count.set({ source: image.color, bins, params }).dispatch(32, 20);+ finish.set({ bins, heights, params }).dispatch(1);return new Float32Array(await heights.read(channels * 1024));},dispose() {diff --git a/src/features/layers/brush-options.tsx b/src/features/layers/brush-options.tsxindex 5b73463..091f2b2 100644--- a/src/features/layers/brush-options.tsx+++ b/src/features/layers/brush-options.tsx@@ -3,6 +3,8 @@ import { Slider } from "@roprgm/ui/slider";import { Tooltip, TooltipContent, TooltipTrigger } from "@roprgm/ui/tooltip";import { cn } from "cn";import { useBrushTool } from "@/components/editor/brush-tool";+import { DockChips, DockControls } from "@/components/editor/dock";+import type { Parameter } from "@/components/editor/parameter";import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";const modes = [@@ -10,13 +12,64 @@ const modes = [["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. */+/** The next stroke's mode, size, edge, and flow, in the bar over the canvas or the dock. Alt shows on the Erase chip. */export function BrushOptions() {const { settings, erase, maxSize, setPreview, update } = useBrushTool();const density = useBarDensity();const variant = barSlider(density);// In the overflow menu the group spans the column, so the two modes share it evenly.const menu = density === "menu";+ const parameters: Parameter[] = [+ {+ id: "size",+ label: "Size",+ value: settings.size,+ min: 1,+ max: maxSize,+ format: (value) => `${value}px`,+ valueWidth: `${maxSize}`.length,+ onEditingChange: setPreview,+ onChange: (size) => update({ size: Math.round(size) }),+ },+ {+ id: "feather",+ label: "Feather",+ value: Math.round(settings.feather * 100),+ min: 0,+ max: 100,+ defaultValue: 50,+ format: (value) => `${value}%`,+ valueWidth: 3,+ onEditingChange: setPreview,+ onChange: (value) => update({ feather: value / 100 }),+ },+ {+ id: "flow",+ label: "Flow",+ value: Math.round(settings.flow * 100),+ min: 1,+ max: 100,+ defaultValue: 100,+ format: (value) => `${value}%`,+ valueWidth: 3,+ onChange: (value) => update({ flow: value / 100 }),+ },+ ];+ if (density === "dock") {+ return (+ <DockControls+ header={+ <DockChips+ label="Brush mode"+ items={modes.map(([mode, label]) => [mode, label] as const)}+ value={erase ? "erase" : "paint"}+ onChange={(mode) => update({ erase: mode === "erase" })}+ />+ }+ parameters={parameters}+ />+ );+ }return (<><fieldset@@ -40,40 +93,9 @@ export function BrushOptions() {</Tooltip>))}</fieldset>- <Slider- label="Size"- value={settings.size}- min={1}- max={maxSize}- format={(value) => `${value}px`}- valueWidth={`${maxSize}`.length}- variant={variant}- onEditingChange={setPreview}- onChange={(size) => update({ size: Math.round(size) })}- />- <Slider- label="Feather"- value={Math.round(settings.feather * 100)}- min={0}- max={100}- defaultValue={50}- format={(value) => `${value}%`}- valueWidth={3}- variant={variant}- onEditingChange={setPreview}- onChange={(value) => update({ feather: value / 100 })}- />- <Slider- label="Flow"- value={Math.round(settings.flow * 100)}- min={1}- max={100}- defaultValue={100}- format={(value) => `${value}%`}- valueWidth={3}- variant={variant}- onChange={(value) => update({ flow: value / 100 })}- />+ {parameters.map(({ id, ...parameter }) => (+ <Slider key={id} {...parameter} variant={variant} />+ ))}</>);}diff --git a/src/features/layers/controls.tsx b/src/features/layers/controls.tsxindex eb92163..da14ab5 100644--- a/src/features/layers/controls.tsx+++ b/src/features/layers/controls.tsx@@ -3,6 +3,7 @@ import { ListItem, ListItemAction } from "@roprgm/ui/list-item";import { Menu, MenuContent, MenuItem, MenuTrigger } from "@roprgm/ui/menu";import { ScrollArea } from "@roprgm/ui/scroll-area";import { Tooltip, TooltipContent, TooltipTrigger } from "@roprgm/ui/tooltip";+import { cn } from "cn";import {type ComponentType,memo,@@ -225,21 +226,26 @@ const LayerRow = memo(function LayerRow({});/**- * The layers section: a fixed header over a list that scrolls. It holds three rows before it grows.- * The list reaches a pixel into the section's divider, so a last row that touches the bottom shares- * that line instead of doubling it.+ * The layers section: a fixed header over a list that scrolls. In the sidebar it holds three rows+ * before it grows; `fill` takes the height it is given instead. The list reaches a pixel into the+ * section's divider, so a last row that touches the bottom shares that line instead of doubling it.*/export function LayersSection({actions,+ fill,children,}: {actions?: ReactNode;+ fill?: boolean;children?: ReactNode;}) {return (<sectionaria-label="Layers"- className="grid max-h-1/2 min-h-41 shrink-0 grid-rows-[auto_minmax(0,1fr)]"+ className={cn(+ "grid grid-rows-[auto_minmax(0,1fr)]",+ fill ? "min-h-0 flex-1" : "max-h-1/2 min-h-41 shrink-0",+ )}><PanelHeader title="Layers">{actions}</PanelHeader><ScrollArea fade>{children}</ScrollArea>@@ -250,9 +256,11 @@ export function LayersSection({export function LayersControls({effects,onAdd,+ fill,}: {effects: readonly EffectKind[];onAdd: (kind: EffectLayer["kind"]) => void;+ fill?: boolean;}) {const document = useDocument();const layers = useScene((scene) => scene.layers);@@ -284,15 +292,12 @@ export function LayersControls({return (<LayersSection+ fill={fill}actions={<Menu><MenuTriggerrender={- <IconButton- label="Add effect"- size="icon"- className="pointer-coarse:size-10"- >+ <IconButton label="Add effect" size="icon"><Icon className="size-4"><path d="M12 4v16M4 12h16" /></Icon>diff --git a/src/features/tone-curves/tone-curves.tsx b/src/features/tone-curves/tone-curves.tsxindex 9729695..2fe1f75 100644--- a/src/features/tone-curves/tone-curves.tsx+++ b/src/features/tone-curves/tone-curves.tsx@@ -1,4 +1,5 @@import { Button } from "@roprgm/ui/button";+import { cn } from "cn";import type { ReactNode } from "react";import type { ToneCurve } from "@/core/document";import { defaultCurve } from "./curve";@@ -7,25 +8,42 @@ import { Graph } from "./graph";type ToneCurvesProps = {points: ToneCurve;onChange: (points: ToneCurve) => void;+ /** Only the graph, stretched to the height it is given; the caller places a reset. */+ fill?: boolean;children?: ReactNode;};-export function ToneCurves({ points, onChange, children }: ToneCurvesProps) {+export function ToneCurves({+ points,+ onChange,+ fill,+ children,+}: ToneCurvesProps) {return (- <section aria-label="Curves" className="space-y-2.5">- <div className="flex items-center justify-between">- <h2 className="text-muted">Curves</h2>- <Button- variant="ghost"- aria-label="Reset curve"- size="sm"- onClick={() => onChange(defaultCurve)}+ <section+ aria-label="Curves"+ className={cn("flex flex-col gap-2.5", fill && "h-full")}+ >+ {!fill && (+ <div className="flex items-center justify-between">+ <h2 className="text-muted">Curves</h2>+ <Button+ variant="ghost"+ aria-label="Reset curve"+ size="sm"+ onClick={() => onChange(defaultCurve)}+ >+ Reset+ </Button>+ </div>+ )}+ <div className={cn("px-0.5", fill && "min-h-0 flex-1")}>+ <div+ className={cn(+ "relative w-full rounded bg-field",+ fill ? "h-full" : "aspect-square max-h-45",+ )}>- Reset- </Button>- </div>- <div className="px-0.5">- <div className="relative aspect-square max-h-55 w-full rounded bg-field md:max-h-45">{children}<Graph onChange={onChange} points={points} /></div>diff --git a/src/features/vignette/controls.tsx b/src/features/vignette/controls.tsxindex f829fe7..aa41d7d 100644--- a/src/features/vignette/controls.tsx+++ b/src/features/vignette/controls.tsx@@ -1,9 +1,30 @@import { Slider } from "@roprgm/ui/slider";+import type { Parameter } from "@/components/editor/parameter";import { useDocument } from "@/components/editor/session";-import type { Vignette } from "@/core/document";+import type { EditorDocument, Vignette } from "@/core/document";import { setVignette } from "./edits";import { defaultVignette } from "./model";+export function vignetteParameters(+ document: EditorDocument,+ id: string,+ vignette: Vignette,+): Parameter[] {+ const controls = [+ ["intensity", "Intensity"],+ ["softness", "Softness"],+ ] as const;+ return controls.map(([name, label]) => ({+ id: name,+ label,+ value: vignette[name],+ min: 0,+ max: 100,+ defaultValue: defaultVignette[name],+ onChange: (value) => setVignette(document, { [name]: value }, id),+ }));+}+export function VignetteControls({id,vignette,@@ -14,22 +35,11 @@ export function VignetteControls({const document = useDocument();return (<section className="flex flex-col gap-1.5 p-3.5">- <Slider- label="Intensity"- value={vignette.intensity}- onChange={(intensity) => setVignette(document, { intensity }, id)}- min={0}- max={100}- defaultValue={defaultVignette.intensity}- />- <Slider- label="Softness"- value={vignette.softness}- onChange={(softness) => setVignette(document, { softness }, id)}- min={0}- max={100}- defaultValue={defaultVignette.softness}- />+ {vignetteParameters(document, id, vignette).map(+ ({ id, ...parameter }) => (+ <Slider key={id} {...parameter} />+ ),+ )}</section>);}diff --git a/src/features/white-balance/controls.tsx b/src/features/white-balance/controls.tsxindex cd0fb76..96a8fad 100644--- a/src/features/white-balance/controls.tsx+++ b/src/features/white-balance/controls.tsx@@ -1,8 +1,10 @@import { Slider } from "@roprgm/ui/slider";+import type { Parameter } from "@/components/editor/parameter";import { useDocument, useScene } from "@/components/editor/session";import { setWhiteBalance, whiteBalanceLimits } from "./edits";-export function WhiteBalanceControls() {+/** Temperature and tint from the camera's as-shot balance; null for an image that isn't RAW. */+export function useWhiteBalanceParameters(): Parameter[] | null {const document = useDocument();const source = useScene((scene) => scene.layers[0].source);const selected = useScene((scene) => scene.layers[0].whiteBalance);@@ -12,20 +14,42 @@ export function WhiteBalanceControls() {}const balance = selected ?? asShot;const limits = whiteBalanceLimits(asShot);+ return [+ {+ id: "temperature",+ label: "Temperature (K)",+ value: balance.temperature,+ ...limits.temperature,+ defaultValue: asShot.temperature,+ onChange: (temperature) => setWhiteBalance(document, { temperature }),+ },+ {+ id: "tint",+ label: "Tint",+ value: balance.tint,+ step: 0.1,+ ...limits.tint,+ defaultValue: asShot.tint,+ onChange: (tint) => setWhiteBalance(document, { tint }),+ },+ ];+}++export function WhiteBalanceControls() {+ const document = useDocument();+ const parameters = useWhiteBalanceParameters();+ if (!parameters) {+ return null;+ }+ const [temperature, tint] = parameters;return (<><div className="relative">- <Slider- label="Temperature (K)"- value={balance.temperature}- {...limits.temperature}- defaultValue={asShot.temperature}- onChange={(temperature) => setWhiteBalance(document, { temperature })}- />+ <Slider {...temperature} />{/* The slider's label row again, its text hidden, so As Shot follows the label without a row of its own. */}<div className="pointer-events-none absolute inset-x-0 top-0 z-20 flex items-center gap-2 py-0.5"><span aria-hidden className="invisible">- Temperature (K)+ {temperature.label}</span><buttontype="button"@@ -36,14 +60,7 @@ export function WhiteBalanceControls() {</button></div></div>- <Slider- label="Tint"- value={balance.tint}- step={0.1}- {...limits.tint}- defaultValue={asShot.tint}- onChange={(tint) => setWhiteBalance(document, { tint })}- />+ <Slider {...tint} /></>);}diff --git a/src/hooks/use-media-query.ts b/src/hooks/use-media-query.tsnew file mode 100644index 0000000..3ec6844--- /dev/null+++ b/src/hooks/use-media-query.ts@@ -0,0 +1,17 @@+import { useCallback, useSyncExternalStore } from "react";++/**+ * Whether a media query matches, read during render. The browser reports a change before it paints,+ * and a store update renders synchronously, so the tree switches in the same frame as CSS.+ */+export function useMediaQuery(query: string) {+ const subscribe = useCallback(+ (onChange: () => void) => {+ const list = matchMedia(query);+ list.addEventListener("change", onChange);+ return () => list.removeEventListener("change", onChange);+ },+ [query],+ );+ return useSyncExternalStore(subscribe, () => matchMedia(query).matches);+}diff --git a/tests/brush.e2e.ts b/tests/brush.e2e.tsindex 4fc31ea..8ab36c3 100644--- a/tests/brush.e2e.ts+++ b/tests/brush.e2e.ts@@ -294,8 +294,8 @@ test("a second finger during a touch stroke cancels it and pinches instead", asy.locator('input[type="file"]').setInputFiles("tests/fixtures/photo.svg");await expect(- page.getByRole("textbox", { name: "Exposure", exact: true }),- ).toHaveValue("0.00");+ page.getByRole("slider", { name: "Exposure", exact: true }),+ ).toHaveAttribute("aria-valuetext", "0.00");await page.getByRole("tab", { name: "Brush", exact: true }).click();const canvas = page.getByLabel("Brush canvas", { exact: true });await expect(canvas).toBeVisible();diff --git a/tests/editing.e2e.ts b/tests/editing.e2e.tsindex 41ac43e..f19a9d9 100644--- a/tests/editing.e2e.ts+++ b/tests/editing.e2e.ts@@ -1039,7 +1039,7 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportawait expect(panel).toBeHidden();});- await test.step("mobile slider targets accept taps above and below the visible track", async () => {+ await test.step("mobile dials take a finger's drag, and a double tap resets", async () => {const context = await browser.newContext({viewport: { width: 390, height: 844 },isMobile: true,@@ -1052,16 +1052,11 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportawait mobile.locator('input[type="file"]').setInputFiles("tests/fixtures/photo.svg");- const canvas = await box(- mobile.getByRole("region", { name: "Image canvas" }),- );+ const region = mobile.getByRole("region", { name: "Image canvas" });+ const canvas = await box(region);const histogram = await box(mobile.getByRole("region", { name: "Image histogram" }),);- const sidebar = mobile.locator("aside");- const sidebarBounds = await box(sidebar);- const editorBounds = await box(sidebar.locator(".."));- expect(sidebarBounds.height / editorBounds.height).toBeCloseTo(0.45, 2);expect(histogram.width).toBe(176);expect(histogram.height).toBe(56);expect(histogram.x).toBeCloseTo(canvas.x + 12, 0);@@ -1073,47 +1068,39 @@ test("edit a photo, inspect the preview and histograms, undo changes, and exportname: "Exposure",exact: true,});- await exposure.scrollIntoViewIfNeeded();- // The bar around each track takes the touch.- for (const slider of await mobile.getByRole("slider").all()) {- const bounds = await box(- slider- .locator('xpath=ancestor::*[@data-slot="slider-track"]')- .locator(".."),- );+ // Every dial takes a fingertip.+ for (const dial of await mobile.getByRole("slider").all()) {+ const bounds = await box(dial);expect(bounds.width).toBeGreaterThanOrEqual(44);expect(bounds.height).toBeGreaterThanOrEqual(44);- const track = await box(- slider.locator('xpath=ancestor::*[@data-slot="slider-track"]'),- );- expect(track.height).toBe(4);- expectCentered(bounds, track);}- const bounds = await box(- exposure- .locator('xpath=ancestor::*[@data-slot="slider-track"]')- .locator(".."),- );- await mobile.touchscreen.tap(- bounds.x + bounds.width - 2,- bounds.y + bounds.height / 2,- );- await expect(exposure).toHaveValue("5");- expect((await readImage(mobile)).center).toEqual([255, 255, 255, 255]);- await mobile.touchscreen.tap(bounds.x + 2, bounds.y + bounds.height / 2);- await expect(exposure).toHaveValue("-5");+ const bounds = await box(exposure);+ const [x, y] = [bounds.x + bounds.width / 2, bounds.y + 20];+ const touch = await context.newCDPSession(mobile);+ const send = (type: "touchStart" | "touchMove" | "touchEnd", at = [x]) =>+ touch.send("Input.dispatchTouchEvent", {+ type,+ touchPoints: type === "touchEnd" ? [] : at.map((x) => ({ x, y })),+ });+ await send("touchStart");+ for (let step = 1; step <= 6; step++) {+ await send("touchMove", [x + step * 10]);+ }+ await send("touchEnd");+ // Sixty pixels sweep a tenth of the range.+ await expect(exposure).toHaveAttribute("aria-valuetext", "1.00");+ expect((await readImage(mobile)).center).not.toEqual([+ 128, 128, 128, 255,+ ]);+ await mobile.touchscreen.tap(x, y);+ await mobile.touchscreen.tap(x, y);+ await expect(exposure).toHaveAttribute("aria-valuetext", "0.00");const undo = mobile.getByRole("button", { name: "Undo", exact: true });await undo.tap();- await expect(exposure).toHaveValue("5");+ await expect(exposure).toHaveAttribute("aria-valuetext", "1.00");await undo.tap();- await expect(exposure).toHaveValue("0");+ await expect(exposure).toHaveAttribute("aria-valuetext", "0.00");expect((await readImage(mobile)).center).toEqual([128, 128, 128, 255]);- const field = mobile.getByRole("textbox", {- name: "Exposure",- exact: true,- });- await field.tap();- await expect(field).toBeFocused();} finally {await context.close();}diff --git a/tests/layers.e2e.ts b/tests/layers.e2e.tsindex dda8cc3..cb03994 100644--- a/tests/layers.e2e.ts+++ b/tests/layers.e2e.ts@@ -424,6 +424,7 @@ test("draw a mask, edit its child effects, reorder layers and undo", async ({await zoom.click();await expect(zoom).toHaveText(fitted);await page.setViewportSize({ width: 390, height: 844 });+ await page.getByRole("tab", { name: "Layers", exact: true }).click();await page.getByRole("button", { name: "photo.svg", exact: true }).click();await page.keyboard.press("r");await expect(overlay).toHaveCSS("cursor", "crosshair");diff --git a/tests/layout.e2e.ts b/tests/layout.e2e.tsnew file mode 100644index 0000000..9687753--- /dev/null+++ b/tests/layout.e2e.ts@@ -0,0 +1,86 @@+import { expect, test } from "./fixtures";+import { box, drag } from "./pointer";++test("edit on a phone and carry the canvas across the breakpoint", async ({+ page,+}) => {+ const state = () => page.evaluate(() => window.openlight.getState());+ const canvas = page.getByRole("region", { name: "Image canvas" });+ await page.setViewportSize({ width: 1280, height: 800 });+ await page.goto("/");+ await page+ .locator('input[type="file"]')+ .setInputFiles("tests/fixtures/photo.svg");+ await expect(+ page.getByRole("textbox", { name: "Exposure", exact: true }),+ ).toHaveValue("0.00");++ await test.step("the canvas stays mounted while the layout switches", async () => {+ await canvas.locator("canvas").evaluate((element) => {+ element.dataset.mounted = "";+ });+ await page.setViewportSize({ width: 390, height: 844 });+ await expect(page.getByRole("tab", { name: "Layers" })).toBeVisible();+ await expect(+ page.getByRole("region", { name: "Layers", exact: true }),+ ).toHaveCount(0);+ await expect(canvas.locator("canvas[data-mounted]")).toHaveCount(1);+ await page.setViewportSize({ width: 1280, height: 800 });+ await expect(+ page.getByRole("region", { name: "Layers", exact: true }),+ ).toBeVisible();+ await expect(canvas.locator("canvas[data-mounted]")).toHaveCount(1);+ await page.setViewportSize({ width: 390, height: 844 });+ });++ await test.step("a drag on a dial is one edit", async () => {+ const contrast = page.getByRole("slider", {+ name: "Contrast",+ exact: true,+ });+ await expect(contrast).toBeVisible();+ const bounds = await box(contrast);+ const y = bounds.y + 20;+ await drag(+ page,+ [bounds.x + bounds.width / 2, y],+ [bounds.x + bounds.width / 2 + 60, y],+ );+ expect((await state()).adjustments.contrast).toBe(20);+ await page.getByRole("button", { name: "Undo" }).click();+ expect((await state()).adjustments.contrast).toBe(0);+ });++ await test.step("the stack is a tab, and an effect's dials follow the selection", async () => {+ await page.getByRole("tab", { name: "Layers" }).click();+ await page.getByRole("button", { name: "Add effect", exact: true }).click();+ await page.getByRole("menuitem", { name: "Details", exact: true }).click();+ await page.getByRole("tab", { name: "Adjust" }).click();+ await expect(+ page.getByRole("slider", { name: "Clarity", exact: true }),+ ).toBeVisible();+ });++ await test.step("a crop is chosen and applied from the dock", async () => {+ await page.getByRole("tab", { name: "Crop" }).click();+ await page.getByRole("button", { name: "Square", exact: true }).click();+ await page.getByRole("button", { name: "Apply", exact: true }).click();+ const [width, height] = (await state()).frame?.size ?? [];+ expect(width).toBe(height);+ await expect(+ page.getByRole("slider", { name: "Clarity", exact: true }),+ ).toBeVisible();+ });++ await test.step("tool options move from the canvas bar to the dock", async () => {+ await page.getByRole("tab", { name: "Brush" }).click();+ await expect(+ page.getByRole("slider", { name: "Size", exact: true }),+ ).toBeVisible();+ await expect(+ page.getByRole("region", { name: "Image canvas" }).getByRole("group", {+ name: "Brush mode",+ }),+ ).toHaveCount(0);+ });+});diff --git a/tests/render-graph.test.ts b/tests/render-graph.test.tsindex 43f607a..e192bd7 100644--- a/tests/render-graph.test.ts+++ b/tests/render-graph.test.ts@@ -97,19 +97,24 @@ test("a shared branch renders once and reuses effects, buffers, and temporary st]);expect(calls.createBuffer).toBe(buffers);expect(calls.createRenderPipeline).toBe(pipelines);- // Bypassing releases scratch storage; a changed output size reuses the remaining target.+ // Bypassing releases scratch storage.expect(graph.render([shared])[0]).toBe(saved);expect(graph.inspect().textures).toHaveLength(1);expect(() => output.color.view).toThrow("destroyed");- const small = merge(- { source, base: source },- node("shared", shader, {- ...options,- size: [4, 4],- }),- );- expect(graph.render([small])[0].size).toEqual([4, 4]);- expect(graph.inspect().textures).toHaveLength(1);+ const sized = (size: [number, number]) =>+ merge(+ { source, base: source },+ node("shared", shader, { ...options, size }),+ );+ // A proxy size and the full size alternate without reallocating; a third size lets the oldest go.+ const [proxy] = graph.render([sized([4, 4])]);+ expect(proxy.size).toEqual([4, 4]);+ expect(graph.inspect().textures).toHaveLength(2);+ expect(graph.render([shared])[0]).toBe(saved);+ expect(graph.render([sized([4, 4])])[0]).toBe(proxy);+ graph.render([sized([2, 2])]);+ expect(graph.inspect().textures).toHaveLength(2);+ expect(() => saved.color.view).toThrow("destroyed");// Removing a composition retires its cached effect so its name can be reused.graph.release("shared");const replacement = merge(