Free open-source image editor for the browser
Keep the document when an open fails, and add an Open action (#53)
Rodrigo Belfiore7341c32b86de
diff --git a/API.md b/API.mdindex bd3e67a..dc9f943 100644--- a/API.md+++ b/API.md@@ -34,7 +34,7 @@ These methods accept browser `File` objects and return `Promise<void>`. Await th| `loadUrl(url)` | Fetches an image from a same-origin URL and loads it. || `importXmp(file)` | Applies supported Camera Raw adjustments as one undoable edit. |-Loading calls are queued. XMP import is skipped if no document is ready; an invalid XMP import can reject without blocking later loads. Image and scene failures appear in the workspace's error state and do not reject the loading promise. Check `getState().documentId` to confirm success. Loading completion does not guarantee the preview has rendered.+Loading calls are queued. XMP import is skipped if no document is ready; an invalid XMP import can reject without blocking later loads. Image and scene failures do not reject the loading promise. Without a document open, a failure leaves the workspace in its error state; with one, that document stays open and keeps its history. Either way `getState().failure` names the file and the error, and settings loaded in the same batch are skipped. Check `getState().documentId` or `failure` to confirm success. Loading completion does not guarantee the preview has rendered.## Editing@@ -168,6 +168,6 @@ On a fresh load the start screen shows a notice in the viewport's corner with **## State-`getState()` returns a detached snapshot containing `file`, `documentId`, `scene`, `selectedLayerId`, `size`, `frame`, `adjustments`, `whiteBalance`, `details`, `toneCurve`, `colorMixer`, `vignette`, `preview`, and `history`. `scene` contains `frame` and the layer tree. The top-level adjustment, tone-curve, and white-balance values come from `scene.layers[0]`; details, color-mixer, and vignette values describe the first matching root layer from the bottom, or its defaults. `colorMixer` contains eight-value `hue`, `saturation`, and `luminance` arrays in the color order above, defaulting to zero. `whiteBalance` contains absolute temperature/tint for RAW sources and is undefined for other sources. `file` is the filename, and `history` contains `undoCount`, `redoCount`, and `editing`, which is true while a group is open.+`getState()` returns a detached snapshot containing `file`, `failure`, `documentId`, `scene`, `selectedLayerId`, `size`, `frame`, `adjustments`, `whiteBalance`, `details`, `toneCurve`, `colorMixer`, `vignette`, `preview`, and `history`. `scene` contains `frame` and the layer tree. The top-level adjustment, tone-curve, and white-balance values come from `scene.layers[0]`; details, color-mixer, and vignette values describe the first matching root layer from the bottom, or its defaults. `colorMixer` contains eight-value `hue`, `saturation`, and `luminance` arrays in the color order above, defaulting to zero. `whiteBalance` contains absolute temperature/tint for RAW sources and is undefined for other sources. `file` is the open document's filename, or without one the file loading or failed, `failure` is the last file that failed to open and its error until another opens or the notice is dismissed, and `history` contains `undoCount`, `redoCount`, and `editing`, which is true while a group is open.Without a document, `documentId`, `size`, `frame`, and `preview` are undefined. Adjustments, details, and the tone curve use their defaults, and history counts are zero. Mutating the snapshot does not edit the document.diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 4c8c47f..148cf75 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -8,7 +8,7 @@ Where the code lives and the rules that keep it in place. Keep this file true: w| --- | --- || `src/main.tsx` | Mounts the GPU provider and the app. || `app/index.tsx` | The app: workspace, file drop, draft notice. |-| `app/workspace` | The open document, its replacement, and loading state. |+| `app/workspace` | The open document, its replacement, and loading state. A replacement loads beside the open document and takes its place only once it opens; a failure leaves the open document in place. || `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). |diff --git a/DESIGN.md b/DESIGN.mdindex 0ba000c..0166471 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -5,13 +5,13 @@ OpenLight uses a small set of shared UI primitives so the editor reads as one ap| 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 and the dock; `aria-pressed` shows a toggle on. A segmented group is a `fieldset` of chips; `DockChips` is the dock's. |+| `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, and scrolls to the chip chosen. || `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. |+| `Dial`, `DialRow` | Numbers in the mobile dock: a drag anywhere on the dial sets it, right or up to add, a tap picks it for typing, and a double tap resets. A touch moves nothing until it drags past a few pixels. 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@@ -32,7 +32,7 @@ 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`.+- 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, and a tapped dial keeps them there as a field to type into until Done. Until someone first moves a dial, a hint floats above the dock, once per browser. 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 collections@@ -44,6 +44,7 @@ OpenLight uses a small set of shared UI primitives so the editor reads as one ap- Use shared components for repeated interaction and surface behavior. Keep feature-specific composition in the feature.- Use Tailwind tokens already present in the shared primitive for color, borders, shadows, focus, and pointer-coarse sizing. A caller chooses a documented variant instead of recreating the surface.+- On a coarse pointer, the header's controls grow to 40 px while their icons keep their size. The dock's tab bar keeps only its icons below 23rem, where the names no longer fit.- Anchor viewport-corner controls and messages 12 px from both edges. Tool overlays cover the full viewport; the camera preserves a 24 px margin around fitted content without shrinking that coordinate space.- Use `Notice` for a message floating over the viewport that must not block editing, such as a storage failure or an offer to recover a draft. Choose its `tone` (status or alert, which sets the ARIA role) and position it with classes, `fixed` over the window or `absolute` inside the editor viewport. Its message and buttons are `CardSection`s; when the user may close it, a `NoticeClose` goes in a `CardAction` beside the message.- Use `TextLink` for an underlined link inside running text. It renders an anchor with `href` and a button otherwise; the `muted` variant stays in the sentence's color for secondary actions such as Forget.diff --git a/src/app/controls.ts b/src/app/controls.tsindex 510ce7b..50d8794 100644--- a/src/app/controls.ts+++ b/src/app/controls.ts@@ -171,11 +171,19 @@ export function createControls(exportImage(gpu, workspace.getDocument(), options),exportScene: () => writeSceneFile(workspace.getDocument()),getState() {- const { file, document } = workspace.state.getState();+ const current = workspace.state.getState();+ const { file, document } = current;const scene = document?.scene.getState();const layers = scene?.layers ?? [];+ let failure: { file: string; error: string } | undefined;+ if (current.status === "error") {+ failure = { file: current.file, error: current.error };+ } else if (current.status === "ready") {+ failure = current.failure;+ }return structuredClone({file,+ failure,preview: document?.preview.getState(),documentId: document?.id,scene,diff --git a/src/app/editor/comparison-control.tsx b/src/app/editor/comparison-control.tsxindex 8c502d3..1fd04d6 100644--- a/src/app/editor/comparison-control.tsx+++ b/src/app/editor/comparison-control.tsx@@ -55,7 +55,7 @@ export function ComparisonControl() {shortcut="Hold \"size="icon"aria-pressed={comparison !== "edited"}- className="aria-pressed:bg-pressed aria-pressed:text-foreground"+ className="aria-pressed:bg-pressed aria-pressed:text-foreground pointer-coarse:size-10"onClick={() =>preview.setState({comparison: comparison === "split" ? "edited" : "split",diff --git a/src/app/editor/dock.tsx b/src/app/editor/dock.tsxindex 57bfe5e..2639549 100644--- a/src/app/editor/dock.tsx+++ b/src/app/editor/dock.tsx@@ -31,7 +31,8 @@ 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.+ * name. Below 23rem the names no longer fit and the tabs keep only their icons; past that, the row+ * scrolls with a fade. Without a handler the tabs are inert.*/export function DockTabList({selected,@@ -41,16 +42,22 @@ export function DockTabList({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";+ const tab =+ "h-13 min-w-12 flex-1 flex-col gap-0.5 px-2 @max-[23rem]:min-w-10 @max-[23rem]:px-0";+ const name = "@max-[23rem]:sr-only";return (- <Tabs value={selected} onValueChange={onSelect} className="surface-panel">+ <Tabs+ value={selected}+ onValueChange={onSelect}+ className="@container surface-panel"+ ><TabListaria-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]"+ className="gap-0.5 overflow-fade-x px-2 py-1.5 shadow-[inset_0_1px_0_var(--color-edge)]"><Tab value="layers" disabled={!onSelect} className={tab}><LayersIcon className="size-5" />- Layers+ <span className={name}>Layers</span></Tab>{editing.map((entry) => (<Tab@@ -61,7 +68,7 @@ export function DockTabList({className={tab}><entry.Icon className="size-5" />- {entry.shortLabel}+ <span className={name}>{entry.shortLabel}</span></Tab>))}</TabList>diff --git a/src/app/editor/empty.tsx b/src/app/editor/empty.tsxindex 7badf2f..a6a095f 100644--- a/src/app/editor/empty.tsx+++ b/src/app/editor/empty.tsx@@ -2,18 +2,14 @@ import { Button } from "@roprgm/ui/button";import { Notice } from "@roprgm/ui/notice";import { Section } from "@roprgm/ui/section";import { Spinner } from "@roprgm/ui/spinner";-import { useRef } from "react";import { type Gpu, target } from "vgpu";import { useGpu } from "vgpu-react";-import { sceneExtension } from "@/app/loaders/scene";import type { Workspace } from "@/app/workspace";import { 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";import { createDocument, createResources } from "@/core/document";import { createImageSource } from "@/core/image";-import { accept } from "@/core/image/decode";import { imageFrame } from "@/core/image/frame";import { MaskToolProvider } from "@/features/layers/mask-tool";import { useDisposable } from "@/hooks/use-disposable";@@ -22,6 +18,7 @@ import { Backdrop } from "./backdrop";import { DockTabList } from "./dock";import { EditorHeader } from "./header";import { createImageLayer } from "./layers";+import { OpenImage } from "./open";import { createEditorRenderer } from "./renderer";import { PlaceholderSidebar } from "./sidebar";import { ToolTabList } from "./tool-rail";@@ -29,30 +26,6 @@ import { tools } from "./tools";type OpenProps = { onOpen: (files: File[]) => void };-/** The drop hint doubles as the picker: "choose a file" opens the input. */-function OpenImage({ onOpen }: OpenProps) {- const input = useRef<HTMLInputElement>(null);- return (- <p className="mt-4 text-muted">- Drop an image here or{" "}- <TextLink onClick={() => input.current?.click()}>choose a file</TextLink>- <input- accept={`${accept},${sceneExtension}`}- hidden- multiple- onChange={(event) => {- const files = event.currentTarget.files;- if (files?.length) {- onOpen(Array.from(files));- }- }}- ref={input}- type="file"- />- </p>- );-}-type EmptyState = Exclude<ReturnType<Workspace["state"]["getState"]>,{ status: "ready" }diff --git a/src/app/editor/header.tsx b/src/app/editor/header.tsxindex 0fb5479..002254b 100644--- a/src/app/editor/header.tsx+++ b/src/app/editor/header.tsx@@ -1,28 +1,41 @@import { Tooltip, TooltipContent, TooltipTrigger } from "@roprgm/ui/tooltip";import type { ReactNode } from "react";-/** Identity on the left, document actions on the right; present in every editor state. */+/**+ * Identity on the left, with the file and what opens another beside its name; document actions on+ * the right. Present in every editor state.+ */export function EditorHeader({file,+ open,children,}: {file?: string;+ open?: ReactNode;children?: ReactNode;}) {return (<header className="flex h-11 shrink-0 items-center gap-3 border-edge border-b surface-panel px-3"><span className="flex items-center gap-2">- <img src="/logo.svg" alt="" className="size-5" />- <span className="font-medium text-foreground">OpenLight</span>+ <img src="/logo.svg" alt="" className="size-5 shrink-0" />+ {/* On a phone the logo alone names the app, leaving room for the file and its actions. */}+ <span className="font-medium text-foreground max-md:hidden">+ OpenLight+ </span>+ </span>+ <span className="flex min-w-0 items-center gap-1">+ {file && (+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="min-w-0 truncate text-muted">{file}</span>+ }+ />+ <TooltipContent>{file}</TooltipContent>+ </Tooltip>+ )}+ {open}</span>- {file && (- <Tooltip>- <TooltipTrigger- render={<span className="min-w-0 truncate text-muted">{file}</span>}- />- <TooltipContent>{file}</TooltipContent>- </Tooltip>- )}<div className="ml-auto flex items-center gap-1">{children}</div></header>);diff --git a/src/app/editor/history.tsx b/src/app/editor/history.tsxindex 391fe7d..8233ac2 100644--- a/src/app/editor/history.tsx+++ b/src/app/editor/history.tsx@@ -19,6 +19,7 @@ export function HistoryControls() {label="Undo"shortcut="Mod Z"size="icon"+ className="pointer-coarse:size-10"disabled={!undoCount}onClick={history.undo}>@@ -30,6 +31,7 @@ export function HistoryControls() {label="Redo"shortcut="Mod Shift Z"size="icon"+ className="pointer-coarse:size-10"disabled={!redoCount}onClick={history.redo}>diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsxindex c394f8c..6e489b0 100644--- a/src/app/editor/index.tsx+++ b/src/app/editor/index.tsx@@ -33,6 +33,7 @@ import { ImageHistogram } from "./histogram";import { HistoryControls } from "./history";import { createMask } from "./layers";import { MaskOverlaySync } from "./mask-overlay";+import { OpenButton, OpenStatus } from "./open";import { createEditorRenderer } from "./renderer";import { EditorSidebar } from "./sidebar";import { ToolRail } from "./tool-rail";@@ -97,7 +98,7 @@ function ExportButton() {render={<Buttonaria-pressed={exporting}- className="ml-1 px-4 aria-pressed:bg-raised-hover"+ className="ml-1 px-4 aria-pressed:bg-raised-hover pointer-coarse:h-10"onClick={() => setTool(exporting ? tools[0] : exportTool)}>Export@@ -155,13 +156,29 @@ function HealingTools({ children }: { children: ReactNode }) {);}-function DocumentEditor({ file }: { file: string }) {+type ReadyState = Extract<+ ReturnType<Workspace["state"]["getState"]>,+ { status: "ready" }+>;++function DocumentEditor({+ state,+ onOpen,+ onDismissFailure,+}: {+ state: ReadyState;+ onOpen: (files: File[]) => void;+ onDismissFailure: () => void;+}) {return (<ToolProvider><MaskTools><HealingTools><BrushProvider>- <EditorHeader file={file}>+ <EditorHeader+ file={state.file}+ open={<OpenButton onOpen={onOpen} />}+ ><HistoryControls /><hraria-orientation="vertical"@@ -175,6 +192,11 @@ function DocumentEditor({ file }: { file: string }) {<ToolView /></EditorFrame></DockProvider>+ <OpenStatus+ opening={state.opening}+ failure={state.failure}+ onDismiss={onDismissFailure}+ /></BrushProvider></HealingTools></MaskTools>@@ -185,16 +207,26 @@ function DocumentEditor({ file }: { file: string }) {type EditorProps = {state: ReturnType<Workspace["state"]["getState"]>;onOpen: (files: File[]) => void;+ onDismissFailure: () => void;draft?: Recovery;};-function EditorContent({ state, onOpen, draft }: EditorProps) {+function EditorContent({+ state,+ onOpen,+ onDismissFailure,+ draft,+}: EditorProps) {if (state.status !== "ready") {return <EmptyEditor state={state} onOpen={onOpen} draft={draft} />;}return (<DocumentProvider key={state.document.id} value={state.document}><RendererProvider createRenderer={createEditorRenderer}>- <DocumentEditor file={state.file} />+ <DocumentEditor+ state={state}+ onOpen={onOpen}+ onDismissFailure={onDismissFailure}+ /></RendererProvider></DocumentProvider>);diff --git a/src/app/editor/open.tsx b/src/app/editor/open.tsxnew file mode 100644index 0000000..9af0628--- /dev/null+++ b/src/app/editor/open.tsx@@ -0,0 +1,108 @@+import { IconButton } from "@roprgm/ui/icon-button";+import { Notice, NoticeClose } from "@roprgm/ui/notice";+import { Section, SectionAction } from "@roprgm/ui/section";+import { Spinner } from "@roprgm/ui/spinner";+import { type RefObject, useRef } from "react";+import { sceneExtension } from "@/app/loaders/scene";+import type { OpenFailure } from "@/app/workspace";+import { OpenIcon } from "@/components/icons/open";+import { TextLink } from "@/components/ui/text-link";+import { accept } from "@/core/image/decode";+import { useShortcuts } from "@/hooks/use-shortcuts";++type OpenProps = { onOpen: (files: File[]) => void };++/** The hidden picker for images and scenes; clearing it after each pick lets the same file open again. */+function FileInput({+ ref,+ onOpen,+}: OpenProps & { ref: RefObject<HTMLInputElement | null> }) {+ return (+ <input+ ref={ref}+ type="file"+ accept={`${accept},${sceneExtension}`}+ multiple+ hidden+ onChange={(event) => {+ const files = event.currentTarget.files;+ if (files?.length) {+ onOpen(Array.from(files));+ }+ event.currentTarget.value = "";+ }}+ />+ );+}++/** The drop hint doubles as the picker: "choose a file" opens the input. */+export function OpenImage({ onOpen }: OpenProps) {+ const input = useRef<HTMLInputElement>(null);+ return (+ <p className="mt-4 text-muted">+ Drop an image here or{" "}+ <TextLink onClick={() => input.current?.click()}>choose a file</TextLink>+ <FileInput ref={input} onOpen={onOpen} />+ </p>+ );+}++/** Opens another image or scene from the header, in place of the current document once it loads. */+export function OpenButton({ onOpen }: OpenProps) {+ const input = useRef<HTMLInputElement>(null);+ const open = () => input.current?.click();+ useShortcuts({ "mod+o": open });+ return (+ <>+ <IconButton+ label="Open an image or scene"+ shortcut="Mod O"+ size="icon"+ className="pointer-coarse:size-10"+ onClick={open}+ >+ <OpenIcon className="size-4" />+ </IconButton>+ <FileInput ref={input} onOpen={onOpen} />+ </>+ );+}++/** While another file opens, or after it fails, the current document stays and this says why. */+export function OpenStatus({+ opening,+ failure,+ onDismiss,+}: {+ opening?: string;+ failure?: OpenFailure;+ onDismiss: () => void;+}) {+ if (!opening && !failure) {+ return null;+ }+ return (+ <Notice+ tone={failure ? "alert" : "status"}+ className="fixed top-14 left-1/2 z-50 w-96 max-w-[calc(100%-1.5rem)] -translate-x-1/2"+ >+ <Section className="flex-row items-start gap-2">+ {failure ? (+ <>+ <p className="flex-1">+ Couldn't open {failure.file}: {failure.error}+ </p>+ <SectionAction>+ <NoticeClose onClick={onDismiss} />+ </SectionAction>+ </>+ ) : (+ <>+ <Spinner className="mt-0.5 size-4 shrink-0" />+ <p className="min-w-0 flex-1 truncate">Opening {opening}…</p>+ </>+ )}+ </Section>+ </Notice>+ );+}diff --git a/src/app/index.tsx b/src/app/index.tsxindex cd08ef4..ddcb3df 100644--- a/src/app/index.tsx+++ b/src/app/index.tsx@@ -17,7 +17,12 @@ export function App() {: undefined;return (<>- <Editor state={state} onOpen={controls.openFiles} draft={recovery} />+ <Editor+ state={state}+ onOpen={controls.openFiles}+ onDismissFailure={workspace.dismissFailure}+ draft={recovery}+ />{error && <DraftNotice error={error} onDismiss={drafts.dismiss} />}</>);diff --git a/src/app/loaders/image.ts b/src/app/loaders/image.tsindex 3f5bee3..800cfdf 100644--- a/src/app/loaders/image.ts+++ b/src/app/loaders/image.ts@@ -26,7 +26,7 @@ export function createImageLoader(gpu: Gpu, workspace: Workspace) {if (!(file instanceof File)) {throw new Error("loadImage requires a File.");}- await workspace.open(file.name, () => loadDocument(gpu, file));+ return workspace.open(file.name, () => loadDocument(gpu, file));},/** Enters the loading state before the fetch starts, so the empty state never shows. */loadUrl(url: string) {diff --git a/src/app/loaders/registry.ts b/src/app/loaders/registry.tsindex b7093bb..2b0502c 100644--- a/src/app/loaders/registry.ts+++ b/src/app/loaders/registry.ts@@ -1,15 +1,26 @@-export type FileLoader = {- kind: "document" | "settings";- accepts: (file: File) => boolean;- load: (file: File) => Promise<void>;-};+export type FileLoader =+ | {+ kind: "document";+ accepts: (file: File) => boolean;+ /** Resolves whether the file became the open document. */+ load: (file: File) => Promise<boolean>;+ }+ | {+ kind: "settings";+ accepts: (file: File) => boolean;+ load: (file: File) => Promise<void>;+ };type Job = { file: File; loader: FileLoader };+/** Settings apply to the batch's document, so they wait for it and skip a batch whose document failed. */async function loadBatch(jobs: Job[], ready: () => boolean) {const document = jobs.find(({ loader }) => loader.kind === "document");- if (document) {- await document.loader.load(document.file);+ if (+ document?.loader.kind === "document" &&+ !(await document.loader.load(document.file))+ ) {+ return;}if (!ready()) {return;diff --git a/src/app/loaders/scene.ts b/src/app/loaders/scene.tsindex a35f647..d35e280 100644--- a/src/app/loaders/scene.ts+++ b/src/app/loaders/scene.ts@@ -58,7 +58,7 @@ export function createSceneLoader(gpu: Gpu, workspace: Workspace): FileLoader {if (!(file instanceof File)) {throw new Error("loadScene requires a File.");}- await workspace.open(file.name, () =>+ return workspace.open(file.name, () =>openSceneFile(file, (source) => decode(gpu, source)),);},diff --git a/src/app/workspace/index.ts b/src/app/workspace/index.tsindex 877a5ed..3dbfd41 100644--- a/src/app/workspace/index.ts+++ b/src/app/workspace/index.ts@@ -1,11 +1,31 @@import { createStore } from "zustand/vanilla";import type { EditorDocument } from "@/core/document";+/** A file that could not be opened, and why. */+export type OpenFailure = { file: string; error: string };++/**+ * Without a document, opening shows loading and then an error. With one, the document stays while+ * another file opens, named by `opening`, and a failure to open it stays beside it until dismissed.+ */type WorkspaceState =| { status: "empty"; file?: undefined; document?: undefined }| { status: "loading"; file: string; document?: undefined }| { status: "error"; file: string; error: string; document?: undefined }- | { status: "ready"; file: string; document: EditorDocument };+ | {+ status: "ready";+ file: string;+ document: EditorDocument;+ opening?: string;+ failure?: OpenFailure;+ };++function withoutFailure({+ failure: _,+ ...ready+}: Extract<WorkspaceState, { status: "ready" }>) {+ return ready;+}/** Single-document policy; document instances remain independent of this session. */export function createWorkspace() {@@ -25,25 +45,55 @@ export function createWorkspace() {}return document;},+ /** Resolves whether the file became the open document; a later open wins over an earlier one. */async open(file: string, load: () => Promise<EditorDocument>) {if (closed) {throw new Error("Workspace is closed.");}const request = ++generation;- const previous = state.getState().document;- state.setState({ status: "loading", file }, true);- previous?.dispose();+ const current = state.getState();+ state.setState(+ current.status === "ready"+ ? { ...withoutFailure(current), opening: file }+ : { status: "loading", file },+ true,+ );try {const document = await load();if (request !== generation) {document.dispose();- return;+ return false;}+ const previous = state.getState().document;+ // Publishing the replacement first lets autosave flush the previous document's last edits.state.setState({ status: "ready", file, document }, true);+ previous?.dispose();+ return true;} catch (error) {- if (request === generation) {- state.setState({ status: "error", file, error: String(error) }, true);+ if (request !== generation) {+ return false;}+ const latest = state.getState();+ const failure = { file, error: String(error) };+ state.setState(+ latest.status === "ready"+ ? {+ status: "ready",+ file: latest.file,+ document: latest.document,+ failure,+ }+ : { status: "error", ...failure },+ true,+ );+ return false;+ }+ },+ /** Clears a failure shown beside the open document. */+ dismissFailure() {+ const current = state.getState();+ if (current.status === "ready" && current.failure) {+ state.setState(withoutFailure(current), true);}},dispose() {diff --git a/src/components/editor/dock.tsx b/src/components/editor/dock.tsxindex 6854b85..fbaa5fa 100644--- a/src/components/editor/dock.tsx+++ b/src/components/editor/dock.tsx@@ -1,9 +1,21 @@+import { Button } from "@roprgm/ui/button";import { Chip } from "@roprgm/ui/chip";+import { ScrubInput } from "@roprgm/ui/scrub-input";import { cn } from "cn";-import { type ReactNode, useState } from "react";+import {+ createContext,+ type ReactNode,+ useContext,+ useEffect,+ useRef,+ useState,+} from "react";import { DialRow, formatValue } from "@/components/ui/dial";import type { Parameter } from "./parameter";+/** Whether the dock is inert, as before a document opens, so its views teach nothing. */+const Inert = createContext(false);+/*** 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.@@ -22,12 +34,12 @@ export function EditorDock({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}+ <Inert value={Boolean(inert)}>{children}</Inert></div>);}-/** A choice among a few views or modes, as flat chips in a pill. */+/** A choice among a few views or modes, as flat chips in a pill that scrolls to the one chosen. */export function DockChips<T extends string>({label,items,@@ -39,15 +51,20 @@ export function DockChips<T extends string>({value: T;onChange: (value: T) => void;}) {+ const chosen = useRef<HTMLButtonElement>(null);+ // Each new value brings its chip into view, once the ref points at it.+ useEffect(() => {+ chosen.current?.scrollIntoView({ block: "nearest", inline: "nearest" });+ }, [value]);return (<fieldsetaria-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}+ key={id}+ ref={id === value ? chosen : undefined}aria-pressed={id === value}onClick={() => onChange(id)}>@@ -69,10 +86,47 @@ function Readout({ parameter }: { parameter: Parameter }) {);}+/** A tapped dial's name and value, which a tap on the value types into. */+function Picked({ parameter }: { parameter: Parameter }) {+ return (+ <p className="flex items-center gap-2 whitespace-nowrap">+ <span className="text-muted">{parameter.label}</span>+ <ScrubInput+ {...parameter}+ aria-label={parameter.label}+ className="font-medium text-foreground"+ />+ </p>+ );+}++const hintKey = "openlight:dial-hint";+/** Seen for this visit even where storage is unavailable, so the hint shows once per visit at most. */+let hintSeen = false;++function readHintSeen() {+ try {+ hintSeen ||= localStorage.getItem(hintKey) === "seen";+ } catch {+ // Without storage the hint shows again next visit.+ }+ return hintSeen;+}++function markHintSeen() {+ hintSeen = true;+ try {+ localStorage.setItem(hintKey, "seen");+ } catch {+ // Without storage the hint shows again next visit.+ }+}+/*** 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.+ * dials or other content. While a dial drags, its name and value take the header's place, above the+ * finger; a tapped dial keeps them there to type into, until Done. Until someone first moves a dial,+ * a hint floats above the dock. Dials keep the dock low; `tall` raises it for a graph such as the curve.*/export function DockControls({header,@@ -88,30 +142,69 @@ export function DockControls({children?: ReactNode;}) {const [scrub, setScrub] = useState<string | null>(null);- const scrubbed = parameters?.find((parameter) => parameter.id === scrub);+ const ids = parameters?.map((parameter) => parameter.id).join();+ // A pick belongs to one set of dials, so switching groups lets it go.+ const [pick, setPick] = useState<{ ids?: string; id: string } | null>(null);+ const inert = useContext(Inert);+ const [hint, setHint] = useState(+ () => !inert && Boolean(parameters) && !readHintSeen(),+ );+ const find = (id?: string | null) =>+ parameters?.find((parameter) => parameter.id === id);+ const scrubbed = find(scrub);+ const picked = pick?.ids === ids ? find(pick?.id) : undefined;+ function learned() {+ setHint(false);+ markHintSeen();+ }+ let top = header;+ if (scrubbed) {+ top = <Readout parameter={scrubbed} />;+ } else if (picked) {+ top = <Picked parameter={picked} />;+ }return (<sectionclassName={cn(- "flex min-h-0 shrink-0 flex-col pb-3 transition-[height] duration-200 ease-out motion-reduce:transition-none",+ "relative 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",)}>+ {hint && (+ // Above the histogram and zoom control, which sit in the canvas's bottom corners.+ <p className="pointer-events-none absolute bottom-full left-1/2 z-10 mb-21 w-72 max-w-[calc(100%-1.5rem)] -translate-x-1/2 rounded-md bg-level-4/80 px-3 py-1.5 text-center text-balance text-muted backdrop-blur-sm">+ Drag a dial to change it, double{"\u2011"}tap to reset, tap to type a+ value+ </p>+ )}<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="flex min-w-0 max-w-full justify-center">{top}</div>+ {(picked || action) && (<div className="absolute inset-y-0 right-3 flex items-center">- {action}+ {picked ? (+ <Button variant="ghost" size="sm" onClick={() => setPick(null)}>+ Done+ </Button>+ ) : (+ action+ )}</div>)}</div>{parameters ? (// A new set of dials starts again from its first page.<DialRow- key={parameters.map((parameter) => parameter.id).join()}+ key={ids}dials={parameters}- onScrub={setScrub}+ selected={picked?.id}+ onScrub={(id) => {+ setScrub(id);+ if (id) learned();+ }}+ onTap={(id) => {+ learned();+ setPick(picked?.id === id ? null : { ids, id });+ }}/>) : (childrendiff --git a/src/components/icons/open.tsx b/src/components/icons/open.tsxnew file mode 100644index 0000000..524577e--- /dev/null+++ b/src/components/icons/open.tsx@@ -0,0 +1,9 @@+import { Icon, type IconProps } from "./icon";++export function OpenIcon(props: IconProps) {+ return (+ <Icon viewBox="0 0 20 20" {...props}>+ <path d="M2.5 15.5v-11h5l2 2h8v9h-15Z" />+ </Icon>+ );+}diff --git a/src/components/ui/dial.tsx b/src/components/ui/dial.tsxindex a2f0cde..b8fa972 100644--- a/src/components/ui/dial.tsx+++ b/src/components/ui/dial.tsx@@ -16,6 +16,9 @@ export type DialProps = {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;+ /** A touch that lifts without dragging, such as to pick the dial for typing. */+ onTap?: () => void;+ selected?: boolean;min: number;max: number;step?: number;@@ -32,6 +35,8 @@ const radius = 21;const circumference = 2 * Math.PI * radius;/** A drag across this many pixels sweeps the whole range. */const sweep = 600;+/** How far a finger moves before a touch becomes a drag, so a tap's jitter changes nothing. */+const slop = 6;const doubleTap = 300;const keySteps: Record<string, number> = {@@ -78,7 +83,7 @@ function Arc({<circle className="stroke-hover" cx="24" cy="24" r={radius} />{length > 0.1 && (<circle- className="stroke-muted group-data-[scrubbing=true]:stroke-foreground"+ className="stroke-muted group-data-[scrubbing=true]:stroke-foreground group-data-[selected=true]:stroke-foreground"cx="24"cy="24"r={radius}@@ -101,6 +106,8 @@ export function Dial({onChange,onEditingChange,onScrub,+ onTap,+ selected,min,max,step = 1,@@ -110,6 +117,8 @@ export function Dial({color,}: DialProps) {const drag = useRef<{+ startX: number;+ startY: number;x: number;y: number;value: number;@@ -141,6 +150,8 @@ export function Dial({}lastTap.current = event.timeStamp;drag.current = {+ startX: event.clientX,+ startY: event.clientY,x: event.clientX,y: event.clientY,value,@@ -154,10 +165,17 @@ export function Dial({if (!current) {return;}+ current.moved ||=+ Math.hypot(+ event.clientX - current.startX,+ event.clientY - current.startY,+ ) > slop;+ if (!current.moved) {+ 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),@@ -167,7 +185,8 @@ export function Dial({onChange(next);}}- function pointerUp() {+ function end(lifted: boolean) {+ const tapped = lifted && drag.current !== null && !drag.current.moved;// A drag is not the first tap of a double tap.if (drag.current?.moved) {lastTap.current = Number.NEGATIVE_INFINITY;@@ -176,6 +195,9 @@ export function Dial({setScrubbing(false);onScrub?.(false);onEditingChange?.(false);+ if (tapped) {+ onTap?.();+ }}function keyDown(event: KeyboardEvent) {const steps = keySteps[event.key];@@ -199,10 +221,11 @@ export function Dial({aria-valuenow={value}aria-valuetext={text}data-scrubbing={scrubbing}+ data-selected={Boolean(selected)}onPointerDown={pointerDown}onPointerMove={pointerMove}- onPointerUp={pointerUp}- onPointerCancel={pointerUp}+ onPointerUp={() => end(true)}+ onPointerCancel={() => end(false)}onKeyDown={keyDown}onKeyUp={() => onEditingChange?.(false)}onBlur={() => onEditingChange?.(false)}@@ -227,7 +250,7 @@ export function Dial({</span><spanclassName={cn(- "whitespace-nowrap text-muted group-data-[scrubbing=true]:text-foreground",+ "whitespace-nowrap text-muted group-data-[scrubbing=true]:text-foreground group-data-[selected=true]:text-foreground",color && "tabular-nums",)}>@@ -250,7 +273,10 @@ type RowLayout =| { width: number; paged: false; widths: number[] }| { width: number; paged: true; slot: number; perPage: number };-export type DialItem = DialProps & { id: string };+/** A dial as a row holds it: the row wires the scrub, the tap, and the selection. */+export type DialItem = Omit<DialProps, "onScrub" | "onTap" | "selected"> & {+ id: string;+};/*** Dials in one row that never scrolls under a finger, so a drag on a dial always moves its value.@@ -261,10 +287,14 @@ export type DialItem = DialProps & { id: string };export function DialRow({dials,onScrub,+ selected,+ onTap,}: {dials: readonly DialItem[];/** The dial a drag is moving, or null. */onScrub?: (id: string | null) => void;+ selected?: string;+ onTap?: (id: string) => void;}) {const row = useRef<HTMLDivElement>(null);const cells = useRef(new Map<string, HTMLDivElement>());@@ -370,7 +400,9 @@ export function DialRow({><Dial{...dial}+ selected={id === selected}onScrub={(scrubbing) => onScrub?.(scrubbing ? id : null)}+ onTap={() => onTap?.(id)}/></div>))}diff --git a/src/features/crop/view.tsx b/src/features/crop/view.tsxindex a4bd63e..63f5b61 100644--- a/src/features/crop/view.tsx+++ b/src/features/crop/view.tsx@@ -53,6 +53,30 @@ function ActionButton({);}+/** Named ratios as width and height, so a quarter turn swaps them into another. */+const presets = [+ ["Square", 1, 1],+ ["4:3", 4, 3],+ ["3:2", 3, 2],+ ["16:9", 16, 9],+ ["4:5", 4, 5],+ ["9:16", 9, 16],+ ["3:4", 3, 4],+ ["2:3", 2, 3],+ ["5:4", 5, 4],+] as const;+type Preset = (typeof presets)[number][0];++/**+ * What the ratio control holds: the choice, not its number, so Original and 3:2 stay apart on a 3:2+ * photo. Current is the frame's own ratio when it matches no other.+ */+type Choice = "free" | "original" | "current" | Preset;++function preset(choice: Choice) {+ return presets.find(([name]) => name === choice);+}+/** Enter on a panel button is its click; elsewhere it applies the crop. */function keepEnter(event: KeyboardEvent) {if (@@ -69,19 +93,31 @@ export function CropEditor({ onClose }: { onClose: () => void }) {const { camera } = useEditorSession();const [frame, setFrame] = useState(() => document.scene.getState().frame);const [reference, setReference] = useState(frame.size);- const [ratio, setRatio] = useState<number | null>(- frame.size[0] / frame.size[1],- );const sourceId = document.scene.getState().layers[0].source;const [width, height] = document.resources.get(sourceId).image.size;const source: Point = [width, height];+ const original =+ frame.rotation % 180 ? source[1] / source[0] : source[0] / source[1];+ const [current, setCurrent] = useState(frame.size[0] / frame.size[1]);+ const [choice, setChoice] = useState<Choice>(() => {+ if (current === original) return "original";+ return presets.find(([, w, h]) => w / h === current)?.[0] ?? "current";+ });+ function ratioOf(choice: Choice) {+ if (choice === "free") return null;+ if (choice === "original") return original;+ if (choice === "current") return current;+ const [, w, h] = preset(choice) ?? [];+ return w && h ? w / h : null;+ }+ const ratio = ratioOf(choice);function fitView() {camera.setState(camera.getInitialState(), true);}function reset() {setFrame(imageFrame(source));setReference(source);- setRatio(source[0] / source[1]);+ setChoice("original");fitView();}function apply() {@@ -90,34 +126,17 @@ export function CropEditor({ onClose }: { onClose: () => void }) {onClose();}useShortcuts({ enter: apply, escape: onClose }, { inputs: true });- const original =- frame.rotation % 180 ? source[1] / source[0] : source[0] / source[1];- const ratios = {- Original: original,- Square: 1,- "4:3": 4 / 3,- "3:2": 3 / 2,- "16:9": 16 / 9,- "4:5": 4 / 5,- "9:16": 9 / 16,- "3:4": 3 / 4,- "2:3": 2 / 3,- "5:4": 5 / 4,- };- const custom = ratio !== null && !Object.values(ratios).includes(ratio);- const ratioOptions = [+ const ratioOptions: { value: Choice; label: string }[] = [{ value: "free", label: "Free" },- ...(custom && ratio !== null- ? [{ value: `${ratio}`, label: "Current" }]+ ...(choice === "current"+ ? [{ value: "current" as const, label: "Current" }]: []),- ...Object.entries(ratios).map(([label, value]) => ({- value: `${value}`,- label,- })),+ { value: "original", label: "Original" },+ ...presets.map(([name]) => ({ value: name, label: name })),];- function changeRatio(value: string) {- const ratio = Number(value) || null;- setRatio(ratio);+ function changeRatio(next: Choice) {+ setChoice(next);+ const ratio = ratioOf(next);if (ratio) {setFrame(fitRatio(frame, ratio));}@@ -127,7 +146,16 @@ export function CropEditor({ onClose }: { onClose: () => void }) {if ("turn" in action) {setFrame(turn(frame, action.turn));setReference([reference[1], reference[0]]);- setRatio(ratio && 1 / ratio);+ // Original follows the turned photo by itself; a named ratio swaps its sides, and Current inverts.+ const named = preset(choice);+ if (named) {+ const [, w, h] = named;+ setChoice(+ presets.find(([, tw, th]) => tw === h && th === w)?.[0] ?? choice,+ );+ } else if (choice === "current") {+ setCurrent(1 / current);+ }} else {setFrame(flip(frame, action.flip));}@@ -156,7 +184,7 @@ export function CropEditor({ onClose }: { onClose: () => void }) {items={ratioOptions.map(({ value, label }) => [value, label] as const,)}- value={ratio === null ? "free" : `${ratio}`}+ value={choice}onChange={changeRatio}/>}@@ -226,7 +254,7 @@ export function CropEditor({ onClose }: { onClose: () => void }) {<Selectraisedaria-label="Aspect ratio"- value={ratio === null ? "free" : `${ratio}`}+ value={choice}items={ratioOptions}className="w-24"onValueChange={(value) =>diff --git a/tests/layout.e2e.ts b/tests/layout.e2e.tsindex 9687753..9957927 100644--- a/tests/layout.e2e.ts+++ b/tests/layout.e2e.ts@@ -51,6 +51,17 @@ test("edit on a phone and carry the canvas across the breakpoint", async ({expect((await state()).adjustments.contrast).toBe(0);});+ await test.step("a tapped dial takes a typed value", async () => {+ await page.getByRole("slider", { name: "Exposure", exact: true }).click();+ const field = page.getByRole("textbox", { name: "Exposure", exact: true });+ await field.click();+ await field.fill("0.5");+ await field.press("Enter");+ expect((await state()).adjustments.exposure).toBe(0.5);+ await page.getByRole("button", { name: "Done", exact: true }).click();+ await expect(field).toHaveCount(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();@@ -63,7 +74,13 @@ test("edit on a phone and carry the canvas across the breakpoint", async ({await test.step("a crop is chosen and applied from the dock", async () => {await page.getByRole("tab", { name: "Crop" }).click();+ // On a 3:2 photo, Original and 3:2 match, but only the one chosen shows.+ const chosen = page+ .getByRole("group", { name: "Aspect ratio" })+ .locator('[aria-pressed="true"]');+ await expect(chosen).toHaveText(["Original"]);await page.getByRole("button", { name: "Square", exact: true }).click();+ await expect(chosen).toHaveText(["Square"]);await page.getByRole("button", { name: "Apply", exact: true }).click();const [width, height] = (await state()).frame?.size ?? [];expect(width).toBe(height);diff --git a/tests/loaders.e2e.ts b/tests/loaders.e2e.tsindex 908e60a..812441a 100644--- a/tests/loaders.e2e.ts+++ b/tests/loaders.e2e.ts@@ -38,6 +38,21 @@ test("decode an image, apply XMP, recover from failure, and replace a document d).toHaveValue("-1.00");const expected = await readImage(page);expect(expected.center[0]).toBeLessThan(baseline.center[0]);+ // A file that fails to open leaves the edited document open, with the failure beside it.+ const kept = await page.evaluate(() => window.openlight.getState());+ await page.evaluate(() =>+ window.openlight.loadImage(new File(["invalid"], "broken.png")),+ );+ const failure = page.getByText("Couldn't open broken.png:", {+ exact: false,+ });+ await expect(failure).toBeVisible();+ const afterFailure = await page.evaluate(() => window.openlight.getState());+ expect(afterFailure.documentId).toBe(kept.documentId);+ expect(afterFailure.failure?.file).toBe("broken.png");+ expect(afterFailure.adjustments.exposure).toBe(-1);+ await page.getByRole("button", { name: "Dismiss", exact: true }).click();+ await expect(failure).toBeHidden();const before = await page.evaluate(() => window.openlight.getState());await page.evaluate(() => {const frame = window.openlight.getState().frame;diff --git a/tests/loaders.test.ts b/tests/loaders.test.tsindex 2c336ec..799ab82 100644--- a/tests/loaders.test.ts+++ b/tests/loaders.test.ts@@ -146,12 +146,19 @@ test("file batches preserve ordering, group imports, recover from failures, and...defaultAdjustments,contrast: 20,});+ // A failed replacement keeps the open document and skips the settings meant for the failed file.+ const kept = workspace.getDocument();+ const keptAdjustments = kept.scene.getState().layers[0].adjustments;await registry.openFiles([exposure, new File([], "broken.png")]);+ expect(workspace.getDocument()).toBe(kept);expect(workspace.state.getState()).toMatchObject({- status: "error",- file: "broken.png",- error: "Error: Decode failed",+ status: "ready",+ file: "second.png",+ failure: { file: "broken.png", error: "Error: Decode failed" },});+ expect(kept.scene.getState().layers[0].adjustments).toBe(keptAdjustments);+ workspace.dismissFailure();+ expect(workspace.state.getState()).not.toHaveProperty("failure");await registry.openFiles([exposure, photo]);const recovered = workspace.getDocument();expect(recovered.scene.getState().layers[0].adjustments.exposure).toBe(