Initial commit: Luminary photo catalog and RAW editor

Browser-based photo catalog with an optional team server (SQLite + LibRaw).
Local database, uploaded photos, build output and dependencies are gitignored.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-23 15:19:25 +00:00
commit cd52a2f82f
121 changed files with 101872 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
node_modules
dist
.git
docs
.gitignore
server/data
.check
.smoke
*.log
.DS_Store
README.md
Dockerfile
.dockerignore
docker-compose.yml
+16
View File
@@ -0,0 +1,16 @@
node_modules/
dist/
# Local SQLite database and uploaded photo files
server/data/
# Local env / secrets
.env
.env.*
!.env.example
# Local scratch output
.check/
.smoke/
*.log
.DS_Store
+52
View File
@@ -0,0 +1,52 @@
# syntax=docker/dockerfile:1
# ---------------------------------------------------------------- dependencies
FROM node:24-bookworm-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# ---------------------------------------------------------------------- build
FROM deps AS build
WORKDIR /app
COPY tsconfig.json vite.config.ts index.html ./
COPY src ./src
# Vite copies public/ into dist/, so the served PDF (in-app Guide link) needs it here.
COPY public ./public
RUN npm run build
# ------------------------------------------------------- production node_modules
FROM node:24-bookworm-slim AS prod-deps
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
# -------------------------------------------------------------------- runtime
FROM node:24-bookworm-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production \
PORT=8787 \
HOST=0.0.0.0 \
LUMINARY_DATA=/data
COPY --from=prod-deps /app/node_modules ./node_modules
COPY package.json ./
COPY server ./server
COPY --from=build /app/dist ./dist
# Fail the build, not the first request, if the guide or the UI is missing.
RUN test -f dist/index.html && test -f dist/luminary-user-guide.pdf
# The catalog lives on a volume; it must be writable by the unprivileged user.
RUN mkdir -p /data && chown -R node:node /data /app
USER node
EXPOSE 8787
VOLUME ["/data"]
# node is guaranteed present, so no curl/wget needed in the image.
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||8787)+'/api/health').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server/index.mjs"]
+295
View File
@@ -0,0 +1,295 @@
# Luminary
A browser-based photo catalog and editor built for a small team: events, ratings,
filtering, and a non-destructive RAW-capable develop module.
Two ways to run it:
| Mode | Storage | Raw support |
| --- | --- | --- |
| Browser only (`npm run dev`) | IndexedDB on this device | No — raw files need the server |
| Team server (`npm run server` + `npm run dev`) | SQLite + files on disk under `server/data` | Yes — LibRaw demosaic for all vendors |
## Quick start
```bash
npm install
# browser-only library
npm run dev # http://localhost:5173
# with the team server (enables raw + sharing)
LUMINARY_INVITE=our-team npm run server # http://localhost:8787
npm run dev # proxies /api to the server
```
Open the **Local only / Sign in** pill in the top bar. The first account becomes
the admin. After that, invite people from **Administration → Invites**: each link
is single-use, can be locked to an email address, expires automatically and can
be revoked. Setting `LUMINARY_INVITE` also enables a shared code for people who
prefer to register from the sign-in panel. Until you sign in, the app keeps
working exactly as it did before — entirely local.
### Production
```bash
npm run build # type-checks, then bundles into dist/
npm start # serves dist/ and the API from one process
```
### Docker
The image builds the UI and runs one Node process that serves both the app and
the API. Only `/data` needs to persist.
```bash
docker build -t luminary .
docker run -d --name luminary \
-p 8787:8787 \
-e LUMINARY_INVITE=our-team \
-v lumenroom-data:/data \
luminary
```
The named volume deliberately keeps its original `lumenroom-data` name so an
existing Luminary catalog upgrades in place.
Or with Compose, which wires up the volume and env vars for you:
```bash
LUMINARY_INVITE=our-team docker compose up -d --build
```
The container runs as the unprivileged `node` user (uid 1000), ships a
`HEALTHCHECK` on `/api/health`, and exposes port 8787. To put it behind a TLS
proxy, forward `X-Forwarded-Proto: https` so session cookies are marked `Secure`.
Back up the catalog by copying the volume:
```bash
docker run --rm -v lumenroom-data:/data -v "$PWD":/backup alpine \
tar czf /backup/luminary-$(date +%F).tar.gz -C /data .
```
Environment variables:
| Variable | Default | Purpose |
| --- | --- | --- |
| `PORT` | `8787` | Server port |
| `LUMINARY_DATA` | `server/data` | Where originals, previews and the database live |
| `LUMINARY_INVITE` | *(empty)* | Optional shared invite code for new accounts; personal invite links work without it |
| `LUMINARY_MAX_UPLOAD` | `300 MB` | Upload ceiling (bytes) |
| `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable proxy generated for raws |
| `LUMINARY_RAW_WORKERS` | `4` (capped at cores−1) | Raws demosaiced at once; each worker holds a LibRaw instance |
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this, to hand memory back |
| `LUMINARY_QUOTA_BYTES` | `100 GiB` | Default per-account storage allowance (bytes) |
| `LUMINARY_QUOTA_WARN_RATIO` | `0.9` | Fraction of the quota that triggers the in-app and email warning |
| `LUMINARY_PUBLIC_URL` | *(empty)* | Public app URL included in notification emails |
| `LUMINARY_SMTP_USER` | *(empty)* | Gmail address used as the mail sender |
| `LUMINARY_SMTP_APP_PASSWORD` | *(empty)* | Gmail app password (not the normal account password) |
| `LUMINARY_SMTP_FROM` | sender address | Optional From address for notifications |
The pre-rebrand `LUMENROOM_*` environment variable names are still accepted as
fallbacks, so existing deployments can upgrade without changing their config.
## Bridge from the Media Team Hub
A separate dashboard can hand an event over to this editor without sharing
passwords or copying the library. The dashboard signs a short-lived token, sends
the browser to `/api/bridge/login?token=…`, and this server verifies it with the
shared `BRIDGE_SECRET`, creates or reuses a user by email, imports the event's
photo list and redirects into the app with that event open. Photo bytes are
proxied from the dashboard on demand, so the import is metadata only.
```bash
GLENLOCH_URL=https://media.example.org \
BRIDGE_SECRET=<same value as the dashboard> \
LUMINARY_INVITE=our-team \
docker compose up -d --build
```
| Variable | Default | Purpose |
| --- | --- | --- |
| `GLENLOCH_URL` | *(empty)* | Dashboard base URL; empty disables the bridge |
| `BRIDGE_SECRET` | *(empty)* | Shared HMAC secret for bridge tokens |
| `LUMINARY_BRIDGE_TTL_HOURS` | `12` | How long an imported bridge event survives |
The editor shows a banner with **Save to event** — it renders the open photo in
the browser and stores it on the dashboard event as the edited JPEG — and **Back
to dashboard**. Imported events and their catalog rows are temporary: expired
bridge events are swept on the next bridge login. Originals stay on the
dashboard's media storage; only previews and thumbnails are cached under
`LUMINARY_DATA`. RAW files are edited on a 4000 px JPEG proxy generated by the
dashboard and cached here; JPEG/PNG originals are streamed at full size. Bridge accounts have a random password hash, so they can only
be reached through the dashboard link, not the normal sign-in form.
## Features
**Library** — events in the sidebar (create, rename, delete, drag to reorder,
drop photos onto an event to move them), drag photos to reorder within a view,
star ratings, pick/reject flags, five color labels, filters (rating, unrated,
flag, labels, "edited only", free text over name/camera/lens/keywords), sorting
by capture date, import date, name, rating or manual order, multi-select with
shift-ranges and bulk actions. Right-click any photo for a menu with the star
rating, flags and color labels plus open, copy/paste settings, export and delete.
Deleted photos move to a Trash with restore, permanent delete and empty trash.
Select 2–4 photos and press **C** (or click Compare) for a full-screen survey;
double-click a frame to develop it. Selected photos can also be grouped into a
stack (`Stack`, or right-click → Stack selected): the grid collapses a stack to
one card with a count badge, and clicking the badge expands or collapses it.
Right-click → Unstack removes the grouping.
**Develop** — a WebGL2 multi-pass pipeline, per photo, non-destructive:
- white balance, exposure, contrast, highlights/shadows/whites/blacks
- texture, clarity, dehaze, vibrance, saturation, black & white mix
- RGB + per-channel tone curves
- 8-band HSL color mixer, split toning / color grading
- sharpening, luminance noise reduction
- vignette, grain
- crop with nine aspect ratios, straighten, 90° rotation, flips
- local adjustments (up to four layers): brush, linear gradient and radial
masks with feather, invert, luminance/hue/saturation ranges, and per-layer
exposure, contrast, highlights, shadows, temperature, tint and saturation;
masks follow crops, zoom, healing and lens correction, and Copy mask / Paste
mask carry one layer between photos
- full Lensfun lens profiles: distortion, transverse chromatic aberration and
vignetting from the official calibration database, with manual lens search,
"Match EXIF lens" auto-detection, per-correction switches and automatic
edge scaling; focal length and aperture are read from each photo. Save a
profile as the default for a camera + EXIF lens pair and matching imports
apply it automatically, the Optics panel can show a draggable before/after
split for the lens correction, and a Settings view lists and removes saved
camera-lens defaults
- manual perspective correction: vertical/horizontal keystone, fine rotation
and scale, applied while sampling the source
- spot healing brush (Q): click a blemish, drag to move it, Alt-drag the sample,
adjustable size and feather
- scroll-wheel zoom with a Fit / 100% readout, drag to pan, double-click to zoom
in or back out; right-click the canvas for zoom, crop, copy/paste and export
- histogram, presets (built-in + saved), history with undo, selective
copy/paste and batch sync, named snapshots, virtual copies, before/after
- on-device auto subject, sky and background masks (no model download), an
ISO/camera-aware noise starting point, edge-aware lens-softness compensation,
and an approximate paper soft-proof preview
- HDR merge with alignment, horizontal panorama stitching and focus stacking;
each result is added to the catalog as a new editable photo
- browser print layouts (A4, Letter, 5×7) rendered through the develop pipeline
**Proofing galleries** — turn any event into a public link (`/g/<token>`) from
**Share** in the top bar. Clients open it without an account, see only that
event's live photos, heart favourites, leave per-photo comments, mark a photo
approved or needing changes, and download the proof. Feedback appears on the
library grid and in the "Client picks", "Approved" and "Changes" filters.
Links can be revoked, which drops their picks and feedback.
**Team accounts** — the first signup becomes the admin. Admins create single-use
invite links (`/join/<token>`) with an optional email lock and 1–30 day expiry,
copy them from the admin panel, see who joined, and revoke a link at any time.
**Storage quotas and pruning** — every account starts with a 100 GB quota. At 90%
the user sees a warning in the app and receives at most one reminder email per
day. Admins can change a quota in **Administration → Quotas**, request the oldest
content be deleted, and schedule the cleanup. Scheduling sends the user a
warning email with the exact events and photos that will be removed, then waits
24 hours before deleting them. Content added after the warning is never included
in that prune. Email uses Gmail SMTP with a Google app password, configured in
the same tab or via the `LUMINARY_SMTP_*` variables above.
**Catalog workflow** — editable title, caption, creator, copyright and keyword
chips with a keyword library and reusable metadata presets. Save the current
filters and sort as a smart collection. Virtual copies share the master file
but keep independent edits; named snapshots preserve alternative looks.
**Export and print** — format (JPEG/PNG/WebP), quality, resize by long edge or
percent, filename template (`{name}`, `{date}`, `{time}`, `{index}`), saved
export recipes, output sharpening, watermark, embedded XMP metadata in JPEGs,
batch export as one ZIP (or separate files), and browser print layouts.
Full-resolution export runs through the same renderer.
## Lens profile data
Lens correction uses the official [Lensfun](https://lensfun.github.io/) database
and its WebAssembly build (`@neoanaloglabkk/lensfun-wasm`). The runtime assets
are served from `public/lensfun/`: the library is LGPL-3.0-or-later, the camera
and lens database is CC BY-SA 3.0, and the bundled notices and license texts sit
next to the assets. This is a non-commercial project; if the database is reused
or redistributed, keep the attribution and share-alike terms.
Profiles load lazily the first time the Optics panel needs one, so a library
that never uses them does not download the ~5 MB database.
## Raw support
The browser cannot decode camera raw, so the server does it:
1. The original file is stored byte-for-byte (`server/data/originals`).
2. LibRaw (`libraw-wasm`) demosaics it with the camera's white balance and
orientation, and `sharp` encodes an editable JPEG proxy (long edge
`LUMINARY_RAW_EDGE`).
3. If LibRaw cannot open a file, the largest JPEG embedded in the container is
used instead, so exotic or very new cameras still import. The grid marks such
photos `RAW` and the Info panel reports which engine produced the proxy.
Formats: CR2/CR3/CRW, NEF/NRW, ARW/SRF/SR2, ORF, RW2/RWL, RAF, PEF, DNG, SRW,
3FR, FFF, IIQ, X3F, ERF, K25/KDC, DCR, MOS, MRW, MEF.
**Parallel import.** Decoding runs in a small pool of LibRaw workers (default 4,
`LUMINARY_RAW_WORKERS`) and the browser uploads four files at a time, so a card
imports several times faster than one file after another. Measured on this repo
with 8 mixed raws (20 MP average):
| Workers | 8 files | Speedup | Peak memory |
| --- | --- | --- | --- |
| 1 (serial) | 19.2 s | 1.0× | — |
| 4 | 5.2 s | 3.7× | ~2.5 GB |
| 8 | 3.5 s | 5.4× | ~3.5 GB |
Raise the worker count on a big machine; keep it low on a small VPS, where each
worker can hold a few hundred MB while decoding. Workers idle for 90 s are
disposed and recreated on demand, so a burst of imports does not pin memory
forever. `GET /api/health` reports the pool size.
## Layout
```
src/
App.tsx state, filtering, sync, drag-and-drop, shortcuts
gl/renderer.ts WebGL2 pipeline (grade → blur → finish)
lib/lensfun.ts lazy Lensfun client, profile matching and CPU map math
lib/ db, api client, edits model, import/export, presets
components/ library grid, develop, panels, modals
public/lensfun/ vendored Lensfun WASM runtime, database and licenses
server/
index.mjs HTTP API + static hosting
db.mjs SQLite schema (node:sqlite, no native deps)
raw.mjs LibRaw decode + embedded-preview fallback
imaging.mjs sharp encoding, PNG fallback
```
## Limitations
- No cloud hosting or tethered capture. Compare is a still survey rather than a
synchronised zoom/pan view. Merge tools are translation-aligned and aimed at
bracketed, stacked or horizontal panorama sequences, not handheld multi-row
composites.
- Lens profiles are matched from the bundled Lensfun database. A photo whose
EXIF has no lens name needs a manual profile choice; a profile is built for
the photo's current focal length and aperture, not interpolated between
zoom positions. Camera defaults require both a camera and a lens name, and
only apply when the normalized EXIF pair matches one saved default.
- Raw editing works on the decoded proxy (6,000 px default), not the full sensor
mosaic; export size is bounded by the proxy.
- Temperature/tint are relative to the as-shot white balance.
- Auto masks are a lightweight on-device saliency/colour estimate, not a
downloaded segmentation model. They are a starting point that can be
feathered or inverted; complex hair and foliage edges still need a brush.
- Soft proofing approximates paper white, black point and a print gamut; it does
not apply a printer ICC profile. Use the browser print dialog for final ICC
handling.
- Denoise auto-profile is an ISO/camera-aware curve over the existing sliders,
not a calibrated per-sensor noise profile or a learned denoiser.
- Sync is whole-record: the last writer wins per photo. It is designed for a
handful of people sharing one catalog, not for concurrent batch workflows.
- Trash is a soft-delete inside the catalog; there is no automatic catalog
backup.
+38
View File
@@ -0,0 +1,38 @@
services:
luminary:
build: .
image: luminary:latest
container_name: luminary
restart: unless-stopped
ports:
- "${LUMINARY_PORT:-8787}:8787"
environment:
# LUMINARY_* settings; the server still accepts legacy LUMENROOM_* names.
# Invite code for every account after the first (admin) one.
LUMINARY_INVITE: ${LUMINARY_INVITE:-${LUMENROOM_INVITE:-}}
LUMINARY_MAX_UPLOAD: ${LUMINARY_MAX_UPLOAD:-${LUMENROOM_MAX_UPLOAD:-322122547}}
LUMINARY_RAW_EDGE: ${LUMINARY_RAW_EDGE:-${LUMENROOM_RAW_EDGE:-6000}}
# Per-account storage allowance and the fraction at which users are warned.
LUMINARY_QUOTA_BYTES: ${LUMINARY_QUOTA_BYTES:-107374182400}
LUMINARY_QUOTA_WARN_RATIO: ${LUMINARY_QUOTA_WARN_RATIO:-0.9}
# Optional URL shown in notification emails.
LUMINARY_PUBLIC_URL: ${LUMINARY_PUBLIC_URL:-}
# Optional Gmail SMTP fallback; admins can also set these in the UI.
LUMINARY_SMTP_USER: ${LUMINARY_SMTP_USER:-}
LUMINARY_SMTP_APP_PASSWORD: ${LUMINARY_SMTP_APP_PASSWORD:-}
LUMINARY_SMTP_FROM: ${LUMINARY_SMTP_FROM:-}
# Parallel raw decoders; each one holds a LibRaw worker (few hundred MB).
LUMINARY_RAW_WORKERS: ${LUMINARY_RAW_WORKERS:-${LUMENROOM_RAW_WORKERS:-4}}
# Bridge from the Media Team Hub: dashboard base URL and the shared HMAC
# secret (must match the dashboard's BRIDGE_SECRET). Empty disables it.
GLENLOCH_URL: ${GLENLOCH_URL:-}
BRIDGE_SECRET: ${BRIDGE_SECRET:-}
LUMINARY_BRIDGE_TTL_HOURS: ${LUMINARY_BRIDGE_TTL_HOURS:-${LUMENROOM_BRIDGE_TTL_HOURS:-12}}
volumes:
# Originals, previews, thumbnails and the SQLite catalog.
- lumenroom-data:/data
volumes:
# Retain the original volume name so an existing catalog can be upgraded in place.
lumenroom-data:
name: lumenroom-data
Binary file not shown.
+316
View File
@@ -0,0 +1,316 @@
# AI denoise — feasibility review and raw-decoder prototype
**Status:** review + prototype only. No application code was changed.
**Date:** 2026-11-22
**Scope:** could Luminary get a Lightroom-class AI denoise, and what stands in the way?
**Revisit when:** high-ISO raw material is available (see
[§8](#8-the-test-material-gap)).
---
## 1. What the app actually is
This matters because an earlier design assumed an Electron desktop app. It is not.
- **Front end:** React 18 + Vite, WebGL2. All editing happens in the browser on a
demosaiced proxy. `Edits` JSON (`src/types.ts`) is the non-destructive document.
- **Server:** plain `node:http` (`server/index.mjs`, ~1,310 lines, hand-rolled
router at `:284`), cookie sessions, SQLite catalog, deployed as
`node:24-bookworm-slim` in Docker as an unprivileged user.
- **Raw path:** `libraw-wasm` in a `worker_threads` pool (`server/libraw-pool.mjs`),
`open()` + `imageData()` → 8-bit sRGB JPEG proxy at `RAW_PREVIEW_EDGE = 6000`
long edge (`server/config.mjs:14`, `RAW_PREVIEW_EDGE`). `sharp` for JPEG ingest,
`lensfun-wasm` for lens correction.
- **Renderer:** `src/gl/renderer.ts`. `setImage()` uploads one `u_src` texture
(`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`.
- **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a
second place any new image stage must be wired, or exports silently omit it.
### What exists today under the name "noise reduction"
`Edits.noise = { luminance, detail, chroma, chromaDetail }` (`src/types.ts:164`),
UI in `DetailPanel` (`src/components/Panels.tsx:495`), defaults seeded from
`autoNoiseFor()` (`src/lib/noiseProfile.ts`) — an ISO→slider heuristic, not a
physical noise model.
The shaders are classical and coarse:
- Luminance (`renderer.ts:517`): `mix(c, mix(bs, bb, 0.5), nr * 0.6)` — a two-tap
blur blend.
- Chroma (`:545`): a 17-tap circular average on the chroma axes.
So AI denoise is not a marginal improvement here; it is a different category. Keep
the classical path as the instant/non-AI option rather than replacing it.
`noiseProfile.ts` gives the UI a starting point but is **not** a Poisson–Gaussian
model — a denoiser needs real per-camera `k`/`σ²` (see [§7](#7-what-is-still-unknown)).
---
## 2. Verdict
**Moderate-to-hard, and the difficulty is not where it looks.**
The integration seams are good: the server already owns the raw file, already has a
worker pool, and the renderer takes a texture cleanly. A two-week path to a working
raw-domain pipeline exists. The real risks are three:
1. **No trained model.** Independent track, measured in weeks. Nothing in this repo
or the earlier prototype has weights; `onnxruntime-node` has never actually run a
model end to end here.
2. **There is no mosaic→RGB path back.** LibRaw demosaics internally, so denoising
the mosaic means re-deriving RGB yourself. This is where colour drift appears.
3. **No GPU.** `onnxruntime-node` ships CPU + DirectML only; DML is Windows-only and
the server is a Linux container. Plan for the dual-Xeon CPU, ~30–90 s/frame.
Also: the editable proxy is an **8-bit JPEG at ≤6000 px**, so any denoise performed
*after* it is materially worse than Lightroom, which denoises the mosaic.
### Effort at a glance
| Piece | Size | Notes |
|---|---|---|
| Mosaic helper in `server/raw.mjs` | ½ d | ~180 ms/frame, leaves `demosaic()` untouched |
| Black-level + orientation calibration | 2–4 d | see §5, §6 — real work, not a one-liner |
| Denoise endpoint + asset cache | 1–2 d | `data/denoised/<id>.jpg`, keyed by raw hash + model version + params |
| Job progress channel | 1–2 d | **nothing exists**; every route is request/response |
| Raw-domain denoise (DNG round-trip) | 3–6 d | mosaic → VST → tiled ONNX → DNG → LibRaw → proxy |
| Renderer: second texture + `mix()` | ½ d | `u_den` + amount uniform at `renderer.ts:512` |
| Edit model, panel, history, presets | 1–2 d | `Edits.aiDenoise`, `normalizeEdits`, `DetailPanel` |
| Export path | ½ d | easy to forget → denoise missing from exports |
| **Model (train/obtain)** | **weeks** | independent; the long pole |
**≈1.5–2 weeks of plumbing**, excluding the model.
---
## 3. Three placement options
**A. Server-side, raw mosaic domain (the goal).** Best quality; matches what
Lightroom does. Requires a demosaic path (B or C below).
**B. DNG round-trip — recommended.** Write the denoised mosaic as a minimal DNG
(CFA pattern, black/white, `AsShotNeutral`, colour matrix) and hand it back to
`libraw-wasm.open()`. LibRaw then does its normal demosaic and colour handling, so
the denoised proxy matches the current proxy's tone exactly. `src/lib/tiff.ts`
already contains 16-bit TIFF writing.
**C. Own demosaic.** Malvar-He-Cutler is ~150 lines and removes the second decode,
but colour will not match LibRaw's output — visible as a shift when the Amount
slider sits mid-range, since the two textures are blended.
**D. Proxy domain (cheap, not the goal).** Denoise the 8-bit JPEG the client already
has. Fast to build, quality ceiling well below Lightroom.
---
## 4. Raw decoder prototype — what was verified
Run against the 37 sample raws in `server/data/originals/` (36 × Nikon D700 NEF,
1 × Canon 20D CR2) through the repo's own loader, so the worker shim and wasm module
resolve exactly as they do in production. Scripts were throwaway (`/tmp`), none of
this is committed.
### The mosaic path works
| | Nikon D700 | Canon 20D |
|---|---|---|
| mosaic frame | 4288 × 2844 | 3596 × 2348 |
| visible frame | 4284 × 2844 | 3522 × 2348 |
| margins (top, left) | 0, 2 | 12, 74 |
| `data.length` | 12,195,072 = `rawW × rawH` | 8,443,408 = `rawW × rawH` |
| element type | `Uint16Array` | `Uint16Array` |
| `color_data.maximum` | 16383 (14-bit) | 4095 (12-bit) |
| `meta.filters` | `0xB4B4B4B4` → RGGB | `0xB4B4B4B4` → RGGB |
| `meta.cdesc` / `meta.colors` | `RGBG` / 3 | `RGBG` / 3 |
| `color_data.cam_mul` | e.g. 436/256/355 | 1806/1015/1673 |
`data.length === raw_width * raw_height` in every file, so the buffer spans the
whole sensor and cropping to visible is exactly
`(top_margin, left_margin, width, height)` — no stride surprises.
Cost, measured on this machine:
| operation | D700 | 20D |
|---|---|---|
| `open()` | ~140 ms | — |
| `rawImageData()` | **32–38 ms** | ~30 ms |
| `imageData()` (current demosaic) | **~1,965 ms** | ~1,604 ms |
Mosaic access is ~60× cheaper than demosaicing. Memory: 24.4 MB per D700 frame as
`Uint16Array`.
### CFA decode
`meta.filters` is a dcraw bitmask: 8 rows × 2 columns of 2-bit colour codes.
```js
const FC = (filters, row, col) =>
(filters >> ((((row << 1) & 14) + (col & 1)) << 1)) & 3;
```
`0xB4B4B4B4` decodes to standard RGGB on both bodies:
```
R G R G R G R G
G B G B G B G B
...
```
---
## 5. Correction: the black level is not exposed and must be derived
`color_data.black` is **0** for both cameras, and `color_data.dng_levels.dng_black`
is 0 too. For the Canon that is false.
| | D700 | 20D |
|---|---|---|
| `color_data.black` | 0 | 0 |
| darkest 0.2 % quads, per CFA channel | 21.7 / 28.8 / 29.3 / 17.4 | **146.1 / 165.6 / 165.8 / 151.6** |
| darkest-quad sd | 6.4–6.5 | 3.2–4.5 |
| masked-border median | 770 | **128** |
The 20D carries an unsubtracted pedestal of ~128 DN with a **per-channel spread**
(R and B 15–20 DN above the greens) — the signature of Canon per-channel black that
dcraw keeps in `cblack`, which this libraw-wasm build does not surface. Feeding that
into an Anscombe VST without subtracting it biases the variance estimate and leaves
a DC lift.
The border is **not** a safe universal fallback: on the D700 the two "margin" columns
read 770 DN, brighter than the darkest visible pixels (p0 = 8.75), so they are
uncalibrated active pixels rather than masked ones.
**Working rule:** use the masked-border median only when
`borderMedian < visibleP01`; otherwise fall back to a per-camera constant, else 0.
This needs to be validated per body — it is calibration work, not a one-liner.
---
## 6. Correction: the mosaic is never flipped, the proxy always is
`rawImageData()` returns sensor orientation regardless of EXIF. `metadata()` reports
visible dims already swapped for rotated frames, and `imageData()` returns the
rotated frame (`userFlip: -1` in `DECODE_SETTINGS`, `server/raw.mjs:59`).
Correlating a 2×2-quad downsample of the mosaic against demosaiced luma:
| file | `flip` | matching orientation | r |
|---|---|---|---|
| `p_mwpnuqw4_de2ag7dq.nef` | 0 | none | 0.9437 |
| `p_mwpnuoyg_24j6va1c.nef` | 5 | **90° CCW** | 0.9512 |
| `p_mwpnv4gt_tffz1ydw.cr2` | 0 | none | 0.9592 |
r < 1 is expected: the mosaic quad mean is pre-white-balance, the demosaiced luma is
post-`cam_mul`.
**Consequence:** a denoised proxy written straight from the mosaic comes back
**sideways on every portrait frame**. Orientation is a pipeline step, not a detail.
`flip: 6` and `flip: 3` are still untested — no samples in the catalog.
---
## 7. What is still unknown
- **`flip` 6 / 3 / 8 mapping** — only `flip: 5` and `0` appear in the samples.
- **Per-camera black constants** — only D700 and 20D measured. Every body in real use
needs its own (empirical pedestal, per-channel offsets).
- **Whether a DNG round-trip preserves tone exactly** — the central assumption of
option B, untested.
- **Real Poisson–Gaussian `k`/`σ²`** — not derivable from ISO alone; needs
flat-field frames per body per ISO.
- **Denoise timings** — no model has ever run on this machine
(`onnxruntime-node` native binary could not be downloaded here).
- **Behaviour on bridged photos** — bridge-imported items may have no local original
(`server/storage.mjs:findOriginal`); denoise must fetch upstream or grey out.
- **Virtual copies** — `copyOf` shares the master's bytes; cache must key on the
master's raw hash, not the photo id.
---
## 8. The test material gap
**All 37 samples are ISO 100** (D700: 1/60 s, f/5.6, 44 mm). Nothing in this
catalogue exercises the range where denoise matters, so no denoise work can be
validated against it.
To revisit this properly, collect:
1. **A high-ISO ladder on one body** — e.g. 1600 / 3200 / 6400 / 12800 / 25600 of the
same static scene, tripod, dim tungsten light, some deep shadows.
2. **Flat field / lens-cap frames per ISO** — to derive per-channel black and the
noise model instead of guessing.
3. **A portrait-orientation frame** per body — to confirm the `flip: 6` mapping.
4. **At least one second vendor** — the catalogue is effectively Nikon-only; the
Canon black-level behaviour above shows vendor assumptions break fast.
5. **A reference render** — the same frame pushed through Lightroom AI Denoise at a
known strength, to have an objective target rather than an impression.
Synthetic noise added to the existing ISO 100 mosaics is fine for pipeline and
plumbing tests (tiling seams, orientation, cache keys) but cannot validate a model.
---
## 9. What carries over from the earlier reference implementation
Written previously in a different project directory for the (incorrect) Electron
assumption:
| file | status |
|---|---|
| `src/denoise/math.ts` — VST, Bayer packing, tiling, `blendMosaics` | **reuse** |
| `src/denoise/pipeline.ts` — tile runner with injected backend | **reuse** |
| `src/denoise/engine.ts` — ONNX Runtime adapter | **reuse** |
| `src/denoise/types.ts` — `RawMosaic` | reuse, but **extend** (see §1, §5) |
| `src/denoise/worker.ts` — `utilityProcess` | **discard** (Node worker_threads instead) |
| `src/main/*`, `src/preload/*` | **discard** (no Electron) |
| `src/renderer/denoise-notice.ts` | rewrite as a React component on `Panel`/`Slider` |
| tests (`node:test`, 19/19 passing) | port to **vitest** (`npm test` = `vitest run`) |
Key algorithmic finding to keep: the affine noise model `u/k + σ²/k²` is wrong in
0–1 normalised units (measured 664× noise amplification). The generalised Anscombe
VST is unit-agnostic — keep that.
---
## 10. Recommended next steps
1. **DNG round-trip spike** — take one sample's mosaic, write a minimal DNG, reopen it
in `libraw-wasm`, and diff the RGB against the current demosaic output. This
decides option B vs C and is the single highest-value unknown.
2. **Black-level calibration** — per-body, per-channel, with the border heuristic in
§5 validated across vendors.
3. **Server plan** — mosaic helper, orientation step, endpoint, job channel, cache
keying, export wiring, and worker-pool limits (`RAW_WORKERS` defaults to
`min(4, cores-1)`; a 14-thread denoise beside it will starve `/api/health`).
4. **Source the high-ISO material** in §8 before any model work.
---
## 11. Reproducing the probe
The throwaway scripts lived in `/tmp` (`rawprobe.mjs`, `rawmeta.mjs`, `rawalign.mjs`,
`raworient.mjs`). To rebuild, import the repo's own loader so the runtime shim is
installed and the wasm resolves:
```js
import { loadLibRaw } from '<repo>/server/libraw-pool.mjs';
const Ctor = await loadLibRaw();
const lib = new Ctor();
await lib.open(Buffer.from(rawBytes), {}); // note: open() detaches the buffer
const meta = await lib.metadata(true); // fullOutput — needed for color_data
const raw = await lib.rawImageData(); // { raw_width, raw_height,
// top_margin, left_margin,
// width, height, data: Uint16Array }
lib.dispose();
```
Gotchas confirmed during the prototype:
- `metadata()` **without** `true` omits `color_data` entirely; `filters`/`cdesc`/
`colors` are top-level either way.
- `open()` transfers the buffer to the worker and detaches it — hand it a copy if the
caller's bytes are needed again (`server/raw.mjs` already does this).
- `imageData({ noInterpolation: true })` returns 8-bit, pre-rotated, CFA-gap-zeroed
output. Useless as a mosaic source; `rawImageData()` is the only option.
+786
View File
@@ -0,0 +1,786 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Luminary — User Guide</title>
<style>
@page { size: A4; margin: 17mm 15mm 16mm; }
* { box-sizing: border-box; }
html { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
body {
margin: 0;
font: 10.2pt/1.58 "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #1b1f27;
background: #fff;
}
h1, h2, h3, h4 { margin: 0; font-weight: 650; letter-spacing: -0.01em; break-after: avoid; }
h1 { font-size: 23pt; margin: 0 0 4mm; }
h2 { font-size: 13.5pt; margin: 8mm 0 2.5mm; }
h3 { font-size: 11pt; margin: 5mm 0 1.5mm; }
p { margin: 0 0 3mm; }
a { color: #2f6fd0; text-decoration: none; }
ul, ol { margin: 0 0 3.5mm; padding-left: 5.2mm; }
li { margin-bottom: 1.4mm; }
code, kbd {
font-family: "SF Mono", "Cascadia Mono", Menlo, Consolas, monospace;
font-size: 0.88em;
}
code { background: #f1f3f7; border-radius: 2px; padding: 0.4mm 1.2mm; }
kbd {
display: inline-block;
background: #fff;
border: 0.4pt solid #c9cfda;
border-bottom-width: 1.4pt;
border-radius: 2.5px;
padding: 0.2mm 1.6mm;
font-size: 0.82em;
color: #22262f;
white-space: nowrap;
}
/* ---------- cover ---------- */
.cover {
height: 254mm;
background: #14161b;
color: #eef1f6;
padding: 22mm 20mm 16mm;
display: flex;
flex-direction: column;
justify-content: space-between;
border-radius: 3mm;
overflow: hidden;
}
.cover .mark { display: flex; align-items: center; gap: 3mm; font-size: 10pt; letter-spacing: 0.22em; text-transform: uppercase; color: #9aa6b8; }
.cover .dot { width: 4.6mm; height: 4.6mm; border-radius: 50%; background: #4c8dff; box-shadow: 0 0 0 1.6mm rgba(76,141,255,0.18); }
.cover h1 { font-size: 46pt; letter-spacing: -0.03em; margin: 0; color: #fff; }
.cover .sub { font-size: 14pt; color: #b9c4d4; margin-top: 3mm; max-width: 120mm; line-height: 1.4; }
.cover .top { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; }
.cover .hero { flex: 1 1 auto; min-height: 0; margin-top: 10mm; border-radius: 2mm; overflow: hidden; border: 0.4pt solid #2b3140; }
.cover .hero img { display: block; width: 100%; height: 100%; object-fit: cover; object-position: top center; }
.cover .foot { display: flex; justify-content: space-between; font-size: 8.6pt; color: #8b97a9; letter-spacing: 0.04em; }
.cover .rule { height: 0.4pt; background: #2b3140; margin: 6mm 0 4mm; }
/* ---------- structure ---------- */
.chapter { break-before: page; }
.kicker { font-size: 8.4pt; letter-spacing: 0.16em; text-transform: uppercase; color: #6c7688; margin-bottom: 1.6mm; }
.lede { font-size: 11.4pt; color: #3c4554; line-height: 1.5; margin-bottom: 5mm; }
.toc { columns: 2; column-gap: 10mm; margin-top: 4mm; }
.toc div { break-inside: avoid; padding: 1.6mm 0; border-bottom: 0.4pt dotted #ccd3df; font-size: 10pt; display: flex; gap: 2.5mm; }
.toc .n { color: #2f6fd0; font-weight: 650; min-width: 6mm; }
.toc .t { color: #1b1f27; }
figure { margin: 3mm 0 3.5mm; break-inside: avoid; }
figure img { display: block; max-width: 96%; max-height: 116mm; width: auto; margin: 0 auto; border: 0.4pt solid #cfd6e2; border-radius: 1.5mm; }
figcaption { font-size: 8.4pt; color: #5d6878; margin-top: 1.6mm; line-height: 1.4; }
figcaption b { color: #2b3140; }
table { width: 100%; border-collapse: collapse; margin: 2mm 0 5mm; font-size: 9pt; break-inside: auto; }
thead th {
text-align: left;
font-size: 7.8pt;
letter-spacing: 0.1em;
text-transform: uppercase;
color: #5d6878;
border-bottom: 0.8pt solid #b9c2d0;
padding: 1.4mm 2mm;
}
tbody td { border-bottom: 0.4pt solid #e2e7ef; padding: 1.5mm 2mm; vertical-align: top; }
tbody tr:nth-child(even) td { background: #f7f9fc; }
td.k { white-space: nowrap; }
.two { display: grid; grid-template-columns: 1fr 1fr; gap: 6mm; break-inside: avoid; }
.note {
background: #f3f7ff;
border-left: 2.2pt solid #4c8dff;
padding: 3mm 4mm;
margin: 4mm 0;
font-size: 9.2pt;
color: #263043;
break-inside: avoid;
}
.note b { color: #14417f; }
.warn { background: #fff8ec; border-left-color: #e0a02a; }
.warn b { color: #7a4c00; }
.steps { counter-reset: step; list-style: none; padding-left: 0; }
.steps > li { counter-increment: step; position: relative; padding-left: 8.5mm; margin-bottom: 2.4mm; }
.steps > li::before {
content: counter(step);
position: absolute; left: 0; top: 0.2mm;
width: 5.4mm; height: 5.4mm; border-radius: 50%;
background: #1b1f27; color: #fff;
font-size: 7.6pt; font-weight: 700;
display: flex; align-items: center; justify-content: center;
}
.glance { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4mm; margin: 4mm 0 2mm; }
.glance div { border: 0.4pt solid #d8dfea; border-radius: 1.5mm; padding: 3mm; break-inside: avoid; }
.glance strong { display: block; font-size: 9.4pt; margin-bottom: 1mm; }
.glance span { font-size: 8.4pt; color: #5d6878; line-height: 1.4; }
.end { border-top: 0.4pt solid #d8dfea; margin-top: 8mm; padding-top: 3mm; font-size: 8.4pt; color: #6c7688; }
</style>
</head>
<body>
<!-- ============================== COVER ============================== -->
<div class="cover">
<div class="top">
<div class="mark"><span class="dot"></span> Luminary</div>
<div style="margin-top:16mm">
<h1>User Guide</h1>
<div class="sub">Import, cull, develop and export raw photographs in the browser — a complete desktop-style workflow.</div>
</div>
<div class="hero"><img src="img/01-library.jpg" alt="The Luminary library"></div>
</div>
<div>
<div class="rule"></div>
<div class="foot">
<span>VERSION 1.0 · NOVEMBER 2026</span>
<span>SCREENSHOTS FROM THE RUNNING APPLICATION</span>
</div>
</div>
</div>
<!-- ============================== CONTENTS ============================== -->
<div class="chapter">
<div class="kicker">Contents</div>
<h1>What is in this guide</h1>
<p class="lede">Every panel, dialog and keyboard shortcut in the application, in the order you meet them during a real shoot: bring the card in, cull it down, develop the keepers, deliver the files.</p>
<div class="toc">
<div><span class="n">1</span><span class="t">Introduction</span></div>
<div><span class="n">2</span><span class="t">Getting started</span></div>
<div><span class="n">3</span><span class="t">Importing photos</span></div>
<div><span class="n">4</span><span class="t">The library</span></div>
<div><span class="n">5</span><span class="t">Culling a shoot</span></div>
<div><span class="n">6</span><span class="t">The Develop workspace</span></div>
<div><span class="n">7</span><span class="t">Light and white balance</span></div>
<div><span class="n">8</span><span class="t">Colour</span></div>
<div><span class="n">9</span><span class="t">Effects and Detail</span></div>
<div><span class="n">10</span><span class="t">Crop and straighten</span></div>
<div><span class="n">11</span><span class="t">Presets</span></div>
<div><span class="n">12</span><span class="t">History, copy and paste</span></div>
<div><span class="n">13</span><span class="t">Exporting</span></div>
<div><span class="n">14</span><span class="t">Keyboard reference</span></div>
<div><span class="n">15</span><span class="t">The team server</span></div>
<div><span class="n">16</span><span class="t">Troubleshooting and limits</span></div>
<div><span class="n">A</span><span class="t">Formats and badges</span></div>
</div>
<h2>How to read this guide</h2>
<p>Figures are real screenshots taken from the application with a family portrait session loaded. The photographs, file names and camera metadata are the uploaded originals; the cull, crop and grade shown were arranged for this guide, so every example is a real frame rather than a simulated colour field.</p>
<p>Keys are written for both platforms. <kbd>⌘</kbd> means Command on macOS; use <kbd>Ctrl</kbd> on Windows and Linux. Both are accepted everywhere <kbd>⌘ / Ctrl</kbd> appears, and on Windows the menu equivalents are in the right-click menu.</p>
<div class="glance">
<div><strong>Local first</strong><span>Originals, ratings and edits live in this browser. Nothing is uploaded unless you sign in to a server.</span></div>
<div><strong>Non-destructive</strong><span>Every adjustment is stored as parameters next to the file; the original pixels are never rewritten.</span></div>
<div><strong>Raw aware</strong><span>Camera raws are demosaiced by the optional Node server, then developed like any other frame.</span></div>
</div>
</div>
<!-- ============================== 1 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 1</div>
<h1>Introduction</h1>
<p class="lede">Luminary is a browser-based raw workflow: a catalogue, a culling surface and a full develop module backed by a WebGL renderer, with an optional team server for shared storage and raw decoding.</p>
<h2>The shape of the application</h2>
<p>There are two screens, and you move between them constantly.</p>
<p><b>Library</b> is the catalogue: a grid of every photo in the current view, a filter bar, and the filmstrip-free space you need to rate and reject quickly. <b>Develop</b> is the darkroom: one photo on a large canvas, a navigator and preset rail on the left, sliders and a histogram on the right, and the filmstrip along the bottom.</p>
<p>The switch at the top centre moves between them; <kbd>G</kbd> returns to the library from almost anywhere, and <kbd>Esc</kbd> in Develop does the same.</p>
<h2>What happens to your files</h2>
<p>When you import, Luminary reads the EXIF metadata, generates a small JPEG thumbnail, and stores both the original blob and the record in the browser's IndexedDB database. Edits are a plain JSON object attached to that record. Reopening the page reloads everything from disk-backed browser storage; there is no upload, no account and no network round trip in local mode.</p>
<p>If you start the team server and sign in, originals are also written to <code>server/data</code> and the library can be shared. The editing model does not change: the server stores files and records, the browser still does the rendering.</p>
<div class="note">
<b>Nothing is destructive.</b> Reset adjustments, copy settings and the History panel all rewrite the parameter object only. The original file is untouched until you export a new copy.
</div>
<h2>Requirements</h2>
<table>
<thead><tr><th style="width:32%">Item</th><th>Requirement</th></tr></thead>
<tbody>
<tr><td>Browser</td><td>A current Chromium (Chrome, Edge), Firefox or Safari with WebGL 2 enabled. Hardware acceleration is strongly recommended — every preview, thumbnail and export is rendered on the GPU.</td></tr>
<tr><td>Display</td><td>1280 × 800 or larger. The layout is designed for a laptop screen and expands to fill a desktop display.</td></tr>
<tr><td>Storage</td><td>Browser storage quota (typically a share of free disk). Large catalogues of raw files are better kept on the team server.</td></tr>
<tr><td>Raw files</td><td>Require the Node server, which demosaics with LibRaw. Without it, JPEG, PNG, WebP, AVIF and TIFF import directly.</td></tr>
</tbody>
</table>
</section>
<!-- ============================== 2 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 2</div>
<h1>Getting started</h1>
<p class="lede">Two commands get you a working catalogue. The first run of the app is empty — the grid shows its hint text until you import or drop something on it.</p>
<h2>Run it locally</h2>
<ol class="steps">
<li>Install the dependencies once: <code>npm install</code>.</li>
<li>For development, run <code>npm run dev</code> and open the address Vite prints.</li>
<li>For the full application — static build plus API and raw decoding — run <code>npm run build</code>, then <code>npm start</code>, and open <code>http://localhost:8787</code>.</li>
<li>To run it in a container, use <code>docker compose up</code>; the same port is published and <code>server/data</code> is mounted as a volume.</li>
</ol>
<p>The server also serves the built user interface, so <code>npm start</code> on its own is enough once <code>dist/</code> exists. Health and capabilities are available at <code>/api/health</code>.</p>
<h2>Bring in your first photos</h2>
<p>Press <kbd>⌘ / Ctrl</kbd> + <kbd>I</kbd>, click <b>Import photos</b> in the top right, or drag files from your file manager anywhere onto the window. The import dialog is described in the next chapter.</p>
<figure>
<img src="img/01-library.jpg" alt="The library with a three-photo selection">
<figcaption><b>Figure 1.</b> The library after the import and a first cull. The sidebar lists the catalogue and its event, the filter bar narrows the grid, the selection bar appears as soon as anything is selected, and each card carries its own rating, flag, colour label and file metadata.</figcaption>
</figure>
</section>
<!-- ============================== 3 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 3</div>
<h1>Importing photos</h1>
<p class="lede">Importing is a single dialog with three jobs: choose where the photos belong, collect the files, and report anything that could not be read.</p>
<figure>
<img src="img/10-import.jpg" alt="The import dialog with four files staged">
<figcaption><b>Figure 2.</b> The import dialog with four raw files staged. The event picker points at the existing <i>Family Portrait Session</i>; the summary counts the batch and flags the raw files, and the server is ready to demosaic them.</figcaption>
</figure>
<h2>Adding files</h2>
<ul>
<li><b>Drag anywhere onto the window.</b> A full-window drop target appears, and dropping opens the dialog with those files already staged. This works from the library and from Develop.</li>
<li><b>Click the drop zone</b> inside the dialog to open the file picker, or use <b>Import photos</b> in the top bar.</li>
<li>Files already staged are de-duplicated by name and size, so dropping the same card twice does not double the batch.</li>
</ul>
<h2>Choosing a destination</h2>
<p>The <b>Event / album</b> menu lists every event plus <b>+ New event…</b>, which reveals a name field. The event is metadata, not a folder: a photo can be moved between events later without touching the file.</p>
<h2>What can be imported</h2>
<table>
<thead><tr><th style="width:34%">Type</th><th>Behaviour</th></tr></thead>
<tbody>
<tr><td>JPEG, PNG, WebP, AVIF, TIFF</td><td>Decoded in the browser. EXIF camera, lens, ISO, aperture, shutter and focal length are read when present.</td></tr>
<tr><td>Camera raw — CR2, CR3, NEF, ARW, ORF, RW2, RAF, DNG, PEF, SRW, 3FR and more</td><td>Sent to the team server, demosaiced with LibRaw, and returned as an editable proxy plus a server-side original. Requires a signed-in session.</td></tr>
</tbody>
</table>
<p>During an import a progress bar reports the current file by name. If some files fail, the dialog lists each one with the reason and keeps the successes; a failed raw usually means the server is offline or the file is a format LibRaw cannot open.</p>
<div class="warn note">
<b>Raws without a server.</b> The browser cannot decode most camera raws. Stage them anyway and the dialog offers <b>Sign in to the server</b>; once connected, the same batch decodes normally. Server decoding runs a few files at a time, typically two to four seconds per frame.
</div>
</section>
<!-- ============================== 4 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 4</div>
<h1>The library</h1>
<p class="lede">The library is where you decide what is worth developing. It is built for speed: rating, flagging and filtering without ever opening a photo.</p>
<h2>The sidebar</h2>
<p><b>All photos</b> is the whole catalogue. <b>Unsorted</b> holds anything not yet assigned to an event. Below them, each event shows its photo count; the <b>+</b> next to the catalog header creates a new one. The footer reports the server state — whether one was detected, and whether you are signed in.</p>
<h2>The filter bar</h2>
<figure>
<img src="img/02-filters.jpg" alt="The filter bar">
<figcaption><b>Figure 3.</b> Rating and flag filters, colour label swatches, free-text search, the Edited toggle, sort order, and the count of visible photos.</figcaption>
</figure>
<ul>
<li><b>Rating</b> — <i>Any</i>, one to five stars, or <i>Unrated</i>. Filtering for 3★ and above is the usual first pass.</li>
<li><b>Flag</b> — <i>Any</i>, <i>Picked</i>, <i>Unflagged</i>, <i>Rejected</i>.</li>
<li><b>Label</b> — the six colour swatches. Click one to keep only that colour; click it again to clear.</li>
<li><b>Search</b> — matches file name, camera, lens and keywords as you type.</li>
<li><b>Edited</b> — shows only photos with develop adjustments.</li>
<li><b>Sort</b> — the field, with an arrow to reverse the direction. The right-hand count tells you how many photos survived the filters.</li>
</ul>
<p>Filters combine: Pick + 4★ + Edited is a valid view. They are view state, not a change to the photos, and clearing a filter restores the full grid instantly.</p>
<figure>
<img src="img/13-filtered.jpg" alt="The library filtered to picked photos">
<figcaption><b>Figure 4.</b> The same catalogue filtered to <i>Picked</i>: eight keepers from the 41-frame session. The count in the top bar and the grid agree; the filter chip stays lit so you can see why the view is short.</figcaption>
</figure>
<h2>The grid and its cards</h2>
<figure>
<img src="img/03-card.jpg" alt="A single card close-up">
<figcaption><b>Figure 5.</b> One card: the image is letterboxed inside a 3:2 tile, and the strip beneath carries the file name, metadata, rating and colour label.</figcaption>
</figure>
<p>Cards are laid out in rows that reflow with the window. Each one shows the photo oriented and cropped as it will be developed — a turned or straightened frame is turned in its thumbnail too, and preset previews follow the same crop.</p>
<ul>
<li><b>Badges</b> — <code>RAW</code> for camera raw, <code>✓</code> for picked, <code>✕</code> for rejected, <code>✎</code> when the photo has adjustments.</li>
<li><b>Colour strip</b> along the top edge shows the label colour.</li>
<li><b>Metadata line</b> shows camera, and the size and dimensions appear on hover.</li>
<li><b>Rating</b> is shown as stars under the file name.</li>
</ul>
<h2>Selecting</h2>
<p>Click to select one photo. <b>Shift-click</b> extends from the last anchor; <b>⌘ / Ctrl-click</b> toggles a single photo in or out. <b>Drag on empty space</b> to draw a rubber band — everything it touches is selected, and holding <b>Shift</b> adds to the existing selection. A plain click on empty space clears it.</p>
<p>With more than one photo selected, the selection bar becomes a batch editor: stars, pick and reject, colour labels, Export and Delete all apply to the whole selection at once.</p>
<h2>The right-click menu</h2>
<figure>
<img src="img/04-context-menu.jpg" alt="The context menu on a card">
<figcaption><b>Figure 6.</b> The context menu carries the same actions as the keyboard, including the shortcut printed beside each item so the menu teaches the keys.</figcaption>
</figure>
<p>It includes the star row, pick and reject, the colour labels, <b>Open in Develop</b>, copy and paste, syncing settings, reset, virtual copies, compare, stacking, merging, export, print and <b>Move to Trash</b>. Right-clicking a photo inside a multi-selection acts on the whole selection.</p>
<h2>Reordering and opening</h2>
<p>Drag one card onto another to reorder the catalogue; dragging a selection moves all of it. Double-click, or select and press <kbd>E</kbd>, to open the photo in Develop.</p>
</section>
<!-- ============================== 5 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 5</div>
<h1>Culling a shoot</h1>
<p class="lede">Culling is a keyboard loop: look, rate, flag, advance. Everything below works on the selection, so a batch of forty frames can be rated in one keystroke.</p>
<table>
<thead><tr><th style="width:30%">Keys</th><th>Action</th></tr></thead>
<tbody>
<tr><td class="k"><kbd>0</kbd> – <kbd>5</kbd></td><td>Set the star rating, from none to five.</td></tr>
<tr><td class="k"><kbd>6</kbd> <kbd>7</kbd> <kbd>8</kbd> <kbd>9</kbd></td><td>Colour label: red, yellow, green, blue.</td></tr>
<tr><td class="k"><kbd>P</kbd></td><td>Flag as picked. A second press keeps it picked, so it is safe to hold.</td></tr>
<tr><td class="k"><kbd>X</kbd></td><td>Flag as rejected — the fastest way to clear the frames that missed.</td></tr>
<tr><td class="k"><kbd>U</kbd></td><td>Remove the flag.</td></tr>
<tr><td class="k"><kbd>←</kbd> <kbd>→</kbd> <kbd>↑</kbd> <kbd>↓</kbd></td><td>Move the selection through the grid, one photo or one row at a time.</td></tr>
<tr><td class="k"><kbd>Shift</kbd> + arrows</td><td>Extend the selection as you move.</td></tr>
<tr><td class="k"><kbd>Home</kbd> / <kbd>End</kbd></td><td>First or last photo in the current view.</td></tr>
<tr><td class="k"><kbd>⌘ / Ctrl</kbd> + <kbd>A</kbd></td><td>Select every photo the filters are showing.</td></tr>
<tr><td class="k"><kbd>Delete</kbd> / <kbd>Backspace</kbd></td><td>Delete the selection, after confirmation.</td></tr>
<tr><td class="k"><kbd>Esc</kbd></td><td>Clear the selection.</td></tr>
</tbody>
</table>
<h2>A practical pass</h2>
<ol class="steps">
<li>Open the event and set the rating filter to <i>Unrated</i>.</li>
<li>Press <kbd>→</kbd> to walk the shoot. On a keeper, press <kbd>3</kbd> or <kbd>4</kbd>; on a miss, press <kbd>X</kbd>.</li>
<li>Switch the flag filter to <i>Rejected</i> and press <kbd>⌘ / Ctrl</kbd> + <kbd>A</kbd> then <kbd>Delete</kbd>.</li>
<li>Filter to <i>Picked</i>. This is the batch you develop.</li>
</ol>
<div class="note">
<b>Arrow navigation follows the rendered grid.</b> Up and down move by whole rows, whatever the window width or card count, and the selection scrolls into view as it moves.
</div>
<p>The filmstrip in Develop uses the same order, so a cull pass done here translates directly into the order you step through while developing.</p>
</section>
<!-- ============================== 6 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 6</div>
<h1>The Develop workspace</h1>
<p class="lede">Develop is a single-photo surface with three rails. Each one can be ignored until you need it; the canvas keeps its size as panels open and close.</p>
<figure>
<img src="img/05-develop.jpg" alt="The Develop workspace">
<figcaption><b>Figure 7.</b> Develop with a photo that has adjustments. Left: navigator and presets. Centre: canvas with the zoom controls. Right: histogram, then the Light and Presence panels. Bottom: filmstrip.</figcaption>
</figure>
<h2>The top strip</h2>
<p>From left to right: back to the library, the file name, the frame number in the filmstrip, the pixel dimensions, a clickable star row, pick and reject buttons, the colour labels, then <b>Before / After</b>, <b>Crop</b>, <b>Copy</b>, <b>Paste</b>, <b>Reset</b>, <b>Delete</b> and <b>Export</b>. Everything there also exists as a key.</p>
<h2>The canvas</h2>
<p>The photo is rendered by the WebGL pipeline, which applies crop, rotation, straighten, flips, tone, colour, grain, sharpening and noise reduction in a single pass. What you see is what the export writes.</p>
<ul>
<li><b>Zoom</b> — use the wheel over the canvas. It zooms toward the cursor, so the detail you are pointing at stays put. <kbd>Z</kbd> toggles between fit and 100%.</li>
<li><b>Pan</b> — drag with the mouse when zoomed in. Double-click also toggles the zoom level.</li>
<li><b>Before / after</b> — hold <kbd>\</kbd> to see the original, release to return. The top-bar button does the same without holding.</li>
<li><b>Zoom readout</b> — the buttons at the bottom right show fit, 100% and the current percentage.</li>
</ul>
<h2>The left rail</h2>
<p><b>Navigator</b> shows the whole frame with the current crop applied, the file name, and whether the file is raw or a standard image. It is the quickest way to confirm a photo is turned the right way before you start.</p>
<p>Below it, <b>Presets</b> (chapter 11) and, when opened from the panel header, <b>History</b>.</p>
<h2>The right rail</h2>
<figure>
<img src="img/07-panels.jpg" alt="The right-hand panel column">
<figcaption><b>Figure 8.</b> The right column. The histogram shows the three channels with the exposure metadata beneath it; panels below stack, collapse and remember their state.</figcaption>
</figure>
<p>A histogram sits at the top with ISO, aperture, shutter and focal length underneath. Panels follow: <b>Light</b>, <b>Tone curve</b>, <b>Color mixer</b>, <b>Color grading</b>, <b>Effects</b>, <b>Detail</b> and <b>Info</b>. Click a panel header to collapse or expand it; the chevron shows the state.</p>
<h2>The filmstrip</h2>
<p>Every photo in the current view, in order. Click to open one, or press <kbd>←</kbd> and <kbd>→</kbd>. The wheel over the strip scrolls it sideways, and the active frame scrolls itself into view when you move through the shoot. Ratings, flags and colour labels are visible on each film, so you can see where you are in the cull.</p>
</section>
<!-- ============================== 7 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 7</div>
<h1>Light and white balance</h1>
<p class="lede">The Light panel is the first thing to set on any photo, and the only panel most photos need.</p>
<h2>White balance</h2>
<p><b>Temp</b> moves the image between cool blue and warm amber; <b>Tint</b> between green and magenta. Both start at <b>As shot</b>, meaning the camera's recorded balance, and the <b>As shot</b> button in the panel header returns them there at any time without touching the tone controls.</p>
<h2>Tone</h2>
<table>
<thead><tr><th style="width:22%">Control</th><th style="width:20%">Range</th><th>What it does</th></tr></thead>
<tbody>
<tr><td>Exposure</td><td>−5.00 … +5.00 EV</td><td>Overall brightness in stops. The first move on an under- or over-exposed frame.</td></tr>
<tr><td>Contrast</td><td>−100 … +100</td><td>Separates or flattens the midtones, leaving the endpoints alone.</td></tr>
<tr><td>Highlights</td><td>−100 … +100</td><td>Pulls back bright skies and windows, or lifts them.</td></tr>
<tr><td>Shadows</td><td>−100 … +100</td><td>Opens dark areas, or deepens them for a moodier frame.</td></tr>
<tr><td>Whites</td><td>−100 … +100</td><td>Sets the white point; use it with the histogram rather than by eye.</td></tr>
<tr><td>Blacks</td><td>−100 … +100</td><td>Sets the black point and the depth of the shadows.</td></tr>
</tbody>
</table>
<p><b>Auto</b> analyses the photo's thumbnail and sets a starting tone curve in one click. It is a starting point, not a finish: adjust from there.</p>
<h2>Presence</h2>
<table>
<thead><tr><th style="width:22%">Control</th><th>What it does</th></tr></thead>
<tbody>
<tr><td>Texture</td><td>Medium-frequency detail — skin, fabric, foliage — without touching edges.</td></tr>
<tr><td>Clarity</td><td>Midtone contrast. Small amounts add punch; large amounts look metallic.</td></tr>
<tr><td>Dehaze</td><td>Cuts atmospheric haze and flattens or adds distance.</td></tr>
<tr><td>Vibrance</td><td>Saturation that protects already-saturated colours and skin tones.</td></tr>
<tr><td>Saturation</td><td>Uniform saturation across every colour.</td></tr>
</tbody>
</table>
<h2>Black and white</h2>
<p>Tick <b>Black &amp; white mix</b> to convert. A filter row appears — <b>None</b>, <b>Yellow</b>, <b>Orange</b>, <b>Red</b>, <b>Green</b>, <b>Blue</b> — with a strength slider. A filter darkens the colours it absorbs, so red drops a blue sky and green lifts foliage. The Color mixer below tunes individual hues on top of the conversion.</p>
</section>
<!-- ============================== 8 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 8</div>
<h1>Colour</h1>
<p class="lede">Three panels take over where the Light panel stops: a tone curve for precise contrast, a mixer for individual hues, and colour grading for split-toning shadows and highlights.</p>
<h2>Tone curve</h2>
<p>Four channels: <b>RGB</b> for luminance, then <b>R</b>, <b>G</b> and <b>B</b> for per-channel colour. Click on the curve to add a point and drag it; drag a point off the ends to remove it. <b>Reset</b> in the panel header returns the current channel to a straight line.</p>
<p>A gentle S — lift the highlights, drop the shadows — is the classic film contrast move. The per-channel curves are for casts that white balance cannot fix: lift the blue curve in the shadows to cool them without touching the midtones.</p>
<h2>Color mixer</h2>
<p>Eight hue ranges, from red through magenta. Pick a swatch, then adjust <b>Hue</b>, <b>Saturation</b> and <b>Luminance</b> for that range only. This is how you deepen a sky without changing the grass, or pull the orange out of skin while leaving a sunset alone.</p>
<p><b>Reset</b> clears all three values for every band, not just the selected one.</p>
<h2>Color grading</h2>
<p>Two wheels, expressed as sliders: <b>Shadows</b> and <b>Highlights</b>, each with a <b>Hue</b> (0–360°) and an <b>Amount</b>. <b>Balance</b> shifts the crossover between them.</p>
<p>Teal shadows with warm highlights is the standard cinematic grade; a small amount goes a long way. Grading is applied after the tone curve, so it tints the final luminance rather than the source colours.</p>
</section>
<!-- ============================== 9 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 9</div>
<h1>Effects and Detail</h1>
<p class="lede">The last two panels are where a render starts to look like a photograph rather than a file: vignette and grain on one side, sharpening and noise reduction on the other.</p>
<h2>Effects</h2>
<table>
<thead><tr><th style="width:22%">Control</th><th>What it does</th></tr></thead>
<tbody>
<tr><td>Vignette — Amount</td><td>Darkens (negative) or lightens (positive) the edges of the crop.</td></tr>
<tr><td>Vignette — Midpoint</td><td>How far from the centre the falloff begins.</td></tr>
<tr><td>Vignette — Feather</td><td>How soft the transition is. Low feather draws a visible ring.</td></tr>
<tr><td>Grain — Amount</td><td>Strength of the film grain.</td></tr>
<tr><td>Grain — Size</td><td>Grain cell size. Because it is resolution-independent, size is judged at 100%, not on the fitted preview.</td></tr>
<tr><td>Grain — Roughness</td><td>From smooth, even clumping to coarse, irregular structure.</td></tr>
</tbody>
</table>
<p>Under the grain sliders is a <b>100% patch</b>: a small window of the real crop rendered at actual pixels, and it is the only honest way to judge grain size before exporting. Drag the crop and the patch samples that part of the photo, so what you check is what you framed.</p>
<h2>Detail</h2>
<table>
<thead><tr><th style="width:26%">Control</th><th>What it does</th></tr></thead>
<tbody>
<tr><td>Sharpen — Amount</td><td>Edge contrast. Most photographs need a small amount after any resize.</td></tr>
<tr><td>Sharpen — Radius</td><td>The width of the edge being sharpened, in pixels.</td></tr>
<tr><td>Sharpen — Detail</td><td>How much fine structure is included; lower values protect smooth areas.</td></tr>
<tr><td>Noise reduction — Luminance</td><td>Smooths luminance noise, at the cost of fine detail if pushed.</td></tr>
<tr><td>Noise reduction — Detail</td><td>How much texture is preserved while noise is reduced.</td></tr>
</tbody>
</table>
<div class="note">
<b>Judge sharpening and noise at 100%.</b> Both are pixel-level operations; a fitted preview hides exactly the artefacts you are trying to control. Press <kbd>Z</kbd> and pan, then press it again to return to fit.
</div>
</section>
<!-- ============================== 10 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 10</div>
<h1>Crop and straighten</h1>
<p class="lede">Crop mode overlays the frame with a rule-of-thirds grid, eight handles and a 100% loupe, and every change is visible in the navigator, the filmstrip and the preset thumbnails as you make it.</p>
<figure>
<img src="img/06-crop.jpg" alt="Crop mode with the crop rectangle and loupe">
<figcaption><b>Figure 9.</b> Crop mode with a 5 × 4 crop and a 1.2° straighten on a real portrait. The crop panel shows the aspect presets and angle, and the hint bar at the bottom lists the keys.</figcaption>
</figure>
<h2>Entering and leaving</h2>
<p>Press <kbd>C</kbd> or use the <b>Crop</b> button in the top strip. <b>Enter</b> applies the crop and leaves crop mode; <b>Esc</b> cancels it. The hint bar at the bottom of the canvas always shows the current keys.</p>
<h2>Shaping the crop</h2>
<ul>
<li><b>Drag a corner or edge handle</b> to resize; drag inside the rectangle to move it.</li>
<li><b>Aspect presets</b> — Original, Free, 1×1, 4×5, 5×4, 4×3, 3×2, 16×9, 2×1, 9×16. Choosing one constrains the rectangle; <b>Free</b> releases it.</li>
<li><b>⟲ 90°</b> and <b>⟳ 90°</b> turn the frame in quarter steps. Thumbnails, the navigator and preset previews turn with it.</li>
<li><b>Angle</b> straightens the horizon, from −45° to +45° in 0.1° steps. The crop rectangle stays inside the rotated frame, so straightening never samples outside the image.</li>
<li><b>Flip H</b> and <b>Flip V</b> mirror the exported file. <b>Mirror view</b> mirrors only the preview, for checking a composition without changing the output.</li>
<li><b>Reset crop</b> returns to the full frame with no rotation or flips.</li>
</ul>
<figure>
<img src="img/12-crop-detail.jpg" alt="The crop loupe at 100%">
<figcaption><b>Figure 10.</b> The loupe has been dragged toward the lower-right of the crop and shows real pixels at 100%, so you can place the crop against detail that the fitted view cannot show.</figcaption>
</figure>
<h2>What the crop affects</h2>
<p>The crop is part of the photo's edit, not a separate export step. It changes the navigator, the filmstrip thumb, the grid thumbnail, every preset tile and the exported dimensions. Grain size is measured in output pixels, so cropping tighter makes existing grain appear larger in the final file — check the 100% patch in the Effects panel after a big crop.</p>
</section>
<!-- ============================== 11 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 11</div>
<h1>Presets</h1>
<p class="lede">Presets are starting points that render on your photo before you commit to one: every tile in the rail is the actual frame, with the current crop applied.</p>
<figure>
<img src="img/08-presets.jpg" alt="The preset rail" style="max-height:72mm">
<figcaption><b>Figure 11.</b> The preset rail, grouped by family, with the film variant row above it. The navigator and file details sit above the rail.</figcaption>
</figure>
<h2>Groups and variants</h2>
<p>Presets are grouped — <b>Essentials</b>, <b>Film</b>, <b>Warm</b>, <b>Cinematic</b> and the rest of the catalogue. The row above the tiles switches the whole rail between variants:</p>
<ul>
<li><b>Stock</b> — the preset as designed.</li>
<li><b>Push +1</b> / <b>Pull −1</b> — a stop brighter or darker, with the contrast shift that goes with it.</li>
<li><b>Warm split</b> / <b>Cool split</b> — the same look with the shadows and highlights graded in opposite directions.</li>
</ul>
<h2>Applying and saving</h2>
<p>Click a tile to apply it. A preset replaces the develop parameters — crop and rotation are left alone, because they belong to the frame, not the look. After applying, the sliders show the preset's values and can be adjusted further; the History panel records it as one step.</p>
<p>To save your own, adjust a photo and press <b>+</b> in the Presets header. Give it a name and it appears in the rail, rendering its own preview. User presets are stored with the rest of the catalogue.</p>
<div class="note">
<b>Previews are rendered, not cached bitmaps.</b> Each tile is the current photo through that preset, at the current crop, so choosing between looks is a comparison of your frame rather than of a stock image.
</div>
</section>
<!-- ============================== 12 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 12</div>
<h1>History, copy and paste</h1>
<p class="lede">Three ways to reuse work: step backwards through a photo's edits, copy a look to another photo, or start again from zero.</p>
<h2>History</h2>
<p>Every adjustment is recorded with a label and a timestamp. Open <b>History</b> from the left rail and click any entry to restore the photo to that exact state — the sliders follow. <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps back one entry at a time.</p>
<p>History is per photo and belongs to that photo's session. Switching photos does not lose it, and it is saved with the catalogue.</p>
<h2>Copy and paste settings</h2>
<p>With a developed photo open, press <kbd>⌘ / Ctrl</kbd> + <kbd>C</kbd> — or <b>Copy</b> in the top strip. Select another photo, in Develop or in the library, and press <kbd>⌘ / Ctrl</kbd> + <kbd>V</kbd>. The full develop state is pasted: white balance, tone, colour, effects, detail and crop.</p>
<p>This is the fastest way to match a series shot under the same light: develop one frame properly, copy it, then select the rest in the grid and paste once.</p>
<h2>Reset</h2>
<p><b>Reset</b> in the top strip, or <b>Reset adjustments</b> in the context menu, returns the photo to a neutral develop state. The original file is untouched and the reset itself is a history step, so it can be undone.</p>
<div class="note">
<b>Paste is the batch tool.</b> Select forty photos in the library, paste once, and all forty receive the copied settings — including the crop, which is why matching a series is a two-step job rather than forty.
</div>
</section>
<!-- ============================== 13 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 13</div>
<h1>Exporting</h1>
<p class="lede">Export writes new files. Nothing about the catalogue, the original or the edit changes; the dialog is a description of the file you want next to the file you have.</p>
<figure>
<img src="img/09-export.jpg" alt="The export dialog">
<figcaption><b>Figure 12.</b> The export dialog over Develop. The patches under the sample show the chosen output at half, full and double size, each at 100%, so grain and sharpening can be judged at the size that matters.</figcaption>
</figure>
<h2>The options</h2>
<table>
<thead><tr><th style="width:24%">Option</th><th>What it does</th></tr></thead>
<tbody>
<tr><td>Format</td><td>JPEG, PNG or WebP. JPEG and WebP expose a quality slider from 40 to 100; PNG is lossless and shows no quality control.</td></tr>
<tr><td>Resize</td><td><b>Full resolution</b>, <b>Long edge</b> in pixels, or <b>Percent</b> of the cropped size.</td></tr>
<tr><td>Quality</td><td>Encoder quality for the lossy formats. 90–95 is visually lossless for most photographs.</td></tr>
<tr><td>File name</td><td>A template with the tokens <code>{name}</code>, <code>{date}</code>, <code>{time}</code> and <code>{index}</code>. The first resulting file name is shown underneath as you type.</td></tr>
<tr><td>Summary</td><td>The number of photos in the batch and the output dimensions of the sample.</td></tr>
</tbody>
</table>
<h2>Judging the output</h2>
<p>The sample thumbnail is a rendered preview of the crop. Click anywhere on it to move the 100% patches to that point of the photo — the patches are three views of the same detail at half the chosen size, the chosen size and double it, each rendered on its own pixel grid, with the grain cell size for that output printed underneath. This is how you decide whether grain will survive a downscale, or whether a sharpen amount is too high for the delivery size.</p>
<h2>Running it</h2>
<p>Press <b>Export</b> and the files are written one after another with a progress bar. Each file is downloaded by the browser; allow multiple downloads if your browser asks. When the batch finishes the dialog closes and a confirmation appears.</p>
<p>Everything you see on the canvas is baked into the file: crop, rotation, straighten, flips, white balance, tone curve, colour mixer, grading, vignette, grain, sharpening and noise reduction. There is no sidecar and no second step.</p>
<div class="warn note">
<b>Exports reflect the crop.</b> The dimensions in the summary are the cropped dimensions, so a tight 2×1 crop of a 6000-pixel frame produces a 3000-pixel wide file at full resolution. Check the summary before a large batch.
</div>
</section>
<!-- ============================== 14 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 14</div>
<h1>Keyboard reference</h1>
<p class="lede">The full map. Press <kbd>?</kbd> at any time to see the same sheet inside the application.</p>
<figure>
<img src="img/11-shortcuts.jpg" alt="The in-app shortcut sheet">
<figcaption><b>Figure 13.</b> The shortcut sheet, grouped by where the keys apply. It closes with <kbd>Esc</kbd> or a click outside, and it is the reference the application ships with.</figcaption>
</figure>
<h2>Library</h2>
<table>
<thead><tr><th style="width:32%">Keys</th><th>Action</th></tr></thead>
<tbody>
<tr><td class="k"><kbd>G</kbd></td><td>Go to the library.</td></tr>
<tr><td class="k"><kbd>E</kbd> / double-click</td><td>Open the selected photo in Develop.</td></tr>
<tr><td class="k"><kbd>←</kbd> <kbd>→</kbd> <kbd>↑</kbd> <kbd>↓</kbd></td><td>Move the selection.</td></tr>
<tr><td class="k"><kbd>Shift</kbd> + arrows</td><td>Extend the selection.</td></tr>
<tr><td class="k"><kbd>Home</kbd> / <kbd>End</kbd></td><td>First or last photo.</td></tr>
<tr><td class="k"><kbd>⌘ / Ctrl</kbd> + <kbd>A</kbd></td><td>Select all shown.</td></tr>
<tr><td class="k"><kbd>Esc</kbd></td><td>Clear the selection.</td></tr>
<tr><td class="k"><kbd>0</kbd> – <kbd>5</kbd></td><td>Star rating.</td></tr>
<tr><td class="k"><kbd>6</kbd> – <kbd>9</kbd></td><td>Colour label: red, yellow, green, blue.</td></tr>
<tr><td class="k"><kbd>P</kbd> / <kbd>X</kbd> / <kbd>U</kbd></td><td>Pick · reject · unflag.</td></tr>
<tr><td class="k"><kbd>Delete</kbd> / <kbd>Backspace</kbd></td><td>Delete the selection.</td></tr>
<tr><td class="k"><kbd>⌘ / Ctrl</kbd> + <kbd>C</kbd> / <kbd>V</kbd></td><td>Copy · paste develop settings.</td></tr>
<tr><td class="k"><kbd>⌘ / Ctrl</kbd> + <kbd>I</kbd> / <kbd>E</kbd></td><td>Import · export.</td></tr>
<tr><td class="k"><kbd>?</kbd></td><td>Shortcut sheet.</td></tr>
</tbody>
</table>
<h2>Develop</h2>
<table>
<thead><tr><th style="width:32%">Keys</th><th>Action</th></tr></thead>
<tbody>
<tr><td class="k"><kbd>C</kbd></td><td>Crop mode on or off.</td></tr>
<tr><td class="k"><kbd>Enter</kbd></td><td>Apply the crop.</td></tr>
<tr><td class="k"><kbd>Esc</kbd></td><td>Leave crop mode, or return to the library.</td></tr>
<tr><td class="k"><kbd>Z</kbd></td><td>Fit ↔ 100%.</td></tr>
<tr><td class="k"><kbd>\</kbd> (hold)</td><td>Before / after.</td></tr>
<tr><td class="k"><kbd>←</kbd> <kbd>→</kbd></td><td>Previous · next photo.</td></tr>
<tr><td class="k">Wheel · drag</td><td>Zoom at the cursor · pan.</td></tr>
<tr><td class="k"><kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd></td><td>Undo the last adjustment.</td></tr>
<tr><td class="k"><kbd>⌘ / Ctrl</kbd> + <kbd>C</kbd> / <kbd>V</kbd></td><td>Copy · paste settings.</td></tr>
<tr><td class="k"><kbd>?</kbd></td><td>Shortcut sheet.</td></tr>
</tbody>
</table>
<h2>Mouse</h2>
<table>
<thead><tr><th style="width:32%">Gesture</th><th>Action</th></tr></thead>
<tbody>
<tr><td>Click · Shift-click · ⌘/Ctrl-click</td><td>Select · extend · toggle.</td></tr>
<tr><td>Drag on empty grid</td><td>Rubber-band select; <kbd>Shift</kbd> adds.</td></tr>
<tr><td>Right-click a card</td><td>Context menu for the selection.</td></tr>
<tr><td>Drag a card onto another</td><td>Reorder the catalogue.</td></tr>
<tr><td>Drag files onto the window</td><td>Import them.</td></tr>
<tr><td>Wheel over the filmstrip</td><td>Scroll the strip sideways.</td></tr>
</tbody>
</table>
<h2>Dialogs</h2>
<p><kbd>Esc</kbd> closes the import, export and team-server dialogs without touching the photo behind them. Clicking the darkened area outside a dialog closes it too, as does the <b>✕</b> in its header. While a dialog is open the library and Develop shortcuts are suspended, so a stray <kbd>X</kbd> cannot reject a photo you cannot see.</p>
</section>
<!-- ============================== 15 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 15</div>
<h1>The team server</h1>
<p class="lede">Everything in this guide works without a server. The server adds three things: shared storage, raw decoding, and an account so a team can work from the same catalogue.</p>
<h2>Starting it</h2>
<p>Run <code>npm run server</code> — or <code>npm start</code>, which serves the built interface from the same process. With Docker, <code>docker compose up</code> starts the same service and mounts <code>server/data</code> as a volume.</p>
<h2>Signing in</h2>
<p>Click <b>Sign in</b> in the top bar. On a fresh server the <b>Create admin</b> tab is shown: the first account becomes the owner, and the invite code set in <code>LUMINARY_INVITE</code> is what everyone else uses to join. If no server is reachable, the dialog says so and explains how to start one; the local library keeps working exactly as before.</p>
<h2>What the server does</h2>
<ul>
<li><b>Stores originals</b> in <code>server/data</code>, alongside thumbnails and photo records, so the catalogue survives a browser reset and can be opened from another machine.</li>
<li><b>Decodes raws</b> with LibRaw. The dialog reports whether the raw engine is available; when it is, raw files are demosaiced server-side and returned as editable proxies.</li>
<li><b>Reports capacity</b>: photos on the server, storage used, raw engine state and server version, all visible once signed in.</li>
</ul>
<h2>Syncing</h2>
<p><b>Sync library</b> pushes local records and pulls anything the server has that this browser does not. Ratings, flags, colour labels and develop settings travel with the record, so a cull done on a laptop is visible on a desktop.</p>
<div class="note">
<b>Local mode is not a degraded mode.</b> Without a server the app is a complete single-machine editor; the server is about sharing and raw decoding, not about features being switched off.
</div>
</section>
<!-- ============================== 16 ============================== -->
<section class="chapter">
<div class="kicker">Chapter 16</div>
<h1>Troubleshooting and limits</h1>
<p class="lede">The problems that come up in practice, and the things this application deliberately does not do yet.</p>
<h2>Common problems</h2>
<table>
<thead><tr><th style="width:34%">Symptom</th><th>Cause and fix</th></tr></thead>
<tbody>
<tr><td>Raw files will not import</td><td>Raws need the server. Start it, sign in, and the staged batch decodes; the import dialog offers the sign-in button directly.</td></tr>
<tr><td>The canvas is black or blank</td><td>WebGL 2 is unavailable or the GPU context was lost. Turn on hardware acceleration and reload.</td></tr>
<tr><td>Export downloads nothing</td><td>The browser blocked multiple downloads. Allow them for this site and run the export again.</td></tr>
<tr><td>Thumbnails stay grey</td><td>The bitmap for that photo has not been decoded yet, or it is a raw whose proxy never synced. Re-import or sync.</td></tr>
<tr><td>Storage quota errors</td><td>The browser storage is full. Delete rejected photos, or move the catalogue to the team server.</td></tr>
<tr><td>A photo looks different after reload</td><td>Edits are stored as parameters; the preview is re-rendered from the original. If the original changed, the render changes with it.</td></tr>
</tbody>
</table>
<h2>Current limits</h2>
<ul>
<li><b>No local masks.</b> There are no brushes, graduated or radial filters, and no subject or sky selection. Adjustments are global to the crop.</li>
<li><b>No print module and no soft proofing.</b> Delivery is a file export.</li>
<li><b>No tethered capture.</b> Files are imported after the fact.</li>
<li><b>No plugin or sidecar ecosystem.</b> Edits live in the catalogue record, not in XMP files next to the original.</li>
<li><b>Undo is linear.</b> <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps back; there is no separate redo stack. Use History to jump forward again.</li>
<li><b>Colour management is sRGB.</b> Exports are tagged for standard displays and are not converted to a print profile.</li>
</ul>
<div class="note">
<b>If something looks wrong, press <kbd>?</kbd> and compare.</b> The shortcut sheet is generated from the same map the keyboard uses, so if a key is listed there it is live.
</div>
<div class="end">Luminary User Guide · Version 1.0 · Screenshots captured from the running application at 1600 × 1000.</div>
</section>
<!-- ============================== APPENDIX ============================== -->
<section class="chapter">
<div class="kicker">Appendix A</div>
<h1>Formats and badges</h1>
<h2>Import formats</h2>
<table>
<thead><tr><th style="width:40%">Format</th><th>Decoded by</th></tr></thead>
<tbody>
<tr><td>JPEG (.jpg, .jpeg)</td><td>Browser</td></tr>
<tr><td>PNG (.png)</td><td>Browser</td></tr>
<tr><td>WebP (.webp)</td><td>Browser</td></tr>
<tr><td>AVIF (.avif)</td><td>Browser</td></tr>
<tr><td>TIFF (.tif, .tiff)</td><td>Browser</td></tr>
<tr><td>Camera raw: CR2, CR3, CRW, NEF, NRW, ARW, SRF, SR2, ORF, RW2, RWL, RAF, PEF, DNG, SRW, 3FR, FFF, IIQ, X3F, ERF, K25, KDC, DCR, MOS, MRW, MEF</td><td>Team server (LibRaw)</td></tr>
</tbody>
</table>
<h2>Export formats</h2>
<p>JPEG, PNG and WebP, at full resolution, a long-edge size, or a percentage of the cropped frame. Output dimensions always reflect the crop and any rotation.</p>
<h2>Badges on a card</h2>
<table>
<thead><tr><th style="width:26%">Badge</th><th>Meaning</th></tr></thead>
<tbody>
<tr><td><code>RAW</code></td><td>Camera raw. The tooltip says whether it is a demosaiced proxy or an embedded preview.</td></tr>
<tr><td><code>✓</code></td><td>Picked.</td></tr>
<tr><td><code>✕</code></td><td>Rejected. The card is dimmed.</td></tr>
<tr><td><code>✎</code></td><td>The photo has develop adjustments.</td></tr>
<tr><td>Colour strip</td><td>The colour label, along the top edge of the card.</td></tr>
</tbody>
</table>
<h2>Files the server writes</h2>
<p>Originals, thumbnails and the catalogue records live under <code>server/data</code>. Back that directory up and you have backed up the shared library; the browser copy is a cache of the same records plus the local-only photos.</p>
<div class="end">End of guide.</div>
</section>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 373 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 342 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark" />
<title>Luminary</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2856
View File
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
{
"name": "luminary",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"server": "node server/index.mjs",
"server:dev": "node --watch server/index.mjs",
"build": "tsc --noEmit && vite build",
"start": "node server/index.mjs",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
"exifr": "^7.1.3",
"libraw-wasm": "^1.6.0",
"nodemailer": "^7.0.13",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"sharp": "^0.35.5"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.6.3",
"vite": "^5.4.11",
"vitest": "^2.1.9"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 lex
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+10
View File
@@ -0,0 +1,10 @@
# Notices
This project bundles and/or links the following third-party components:
1. Lensfun library source code (`third_party/lensfun/libs`) under LGPL-3.0-or-later.
2. Lensfun camera/lens database (`third_party/lensfun/data/db`) under CC BY-SA 3.0.
3. tinyxml2 (`third_party/tinyxml2`) under zlib license.
4. utf8proc (`third_party/utf8proc`) under MIT license.
Refer to `THIRD_PARTY_LICENSES.md` for license texts and links.
+20
View File
@@ -0,0 +1,20 @@
# Third-Party Licenses
## Lensfun
- Repository: https://github.com/lensfun/lensfun
- Library license: GNU LGPL v3.0 or later
- Database license: Creative Commons Attribution-ShareAlike 3.0
- Copyright: Lensfun contributors
## tinyxml2
- Repository: https://github.com/leethomason/tinyxml2
- License: zlib
- Copyright: Lee Thomason
## utf8proc
- Repository: https://github.com/JuliaStrings/utf8proc
- License: MIT
- Copyright: utf8proc contributors
+23
View File
@@ -0,0 +1,23 @@
# Upstream Tracking
## Source of truth
- Upstream repo: https://github.com/lensfun/lensfun.git
- Integration mode: git submodule (`third_party/lensfun`)
- Current pinned commit: `655a9c4e3e53c25bc04843c853e7e7a0121359e7`
- Commit date: `2026-02-28`
- Commit subject: `Add tca data for Meike SL 35mm F1.8 STM PRO`
## Update policy
- Pin exact commits.
- Upgrade manually via PR.
- Run full build/test after each bump.
## Update steps
1. `scripts/sync-upstream.sh origin/master`
2. Review upstream diff impact (API, DB changes, compile behavior)
3. Rebuild wasm assets
4. Run tests
5. Update this file with new commit metadata
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
BIN
View File
Binary file not shown.
Binary file not shown.
+60
View File
@@ -0,0 +1,60 @@
import crypto from 'node:crypto';
import { SESSION_DAYS } from './config.mjs';
import { sessions, users } from './db.mjs';
const KEYLEN = 64;
export function hashPassword(password) {
const salt = crypto.randomBytes(16);
const hash = crypto.scryptSync(password, salt, KEYLEN);
return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`;
}
export function verifyPassword(password, stored) {
const [scheme, saltHex, hashHex] = String(stored).split('$');
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
const expected = Buffer.from(hashHex, 'hex');
const actual = crypto.scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length);
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
}
export function createSession(userId) {
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000;
sessions.purge();
sessions.create(token, userId, expiresAt);
return token;
}
export function publicUser(row) {
if (!row) return null;
return {
id: row.id,
email: row.email,
name: row.name ?? '',
role: row.role ?? 'member',
};
}
export function authenticate(req) {
const header = String(req.headers.authorization ?? '');
const token = header.startsWith('Bearer ') ? header.slice(7).trim() : '';
if (!token) return null;
const session = sessions.find(token);
if (!session) return null;
if (Number(session.expires_at) < Date.now()) {
sessions.destroy(token);
return null;
}
const user = users.byId(session.user_id);
if (!user || user.disabled) return null;
return publicUser(user);
}
export function normalizeEmail(value) {
return typeof value === 'string' ? value.trim().toLowerCase() : '';
}
export function validEmail(email) {
return /^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(email);
}
+265
View File
@@ -0,0 +1,265 @@
/**
* Bridge to the Media Team Hub dashboard.
*
* The dashboard signs a short-lived token scoped to one event; this module
* verifies it, exchanges it for a service token, mirrors the event's photo list
* into the local catalog, and proxies bytes/save-backs for as long as the
* bridge session lives. Nothing here is reachable without a valid token.
*/
import crypto from 'node:crypto';
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
import { removeAsset } from './storage.mjs';
const VERSION = 'g1';
/* ------------------------------------------------------------------- tokens */
export function bridgeConfigured() {
return Boolean(BRIDGE_SECRET && GLENLOCH_URL);
}
export function verifyBridgeToken(token, now = Date.now()) {
if (!BRIDGE_SECRET || typeof token !== 'string') return null;
const parts = token.split('.');
if (parts.length !== 3 || parts[0] !== VERSION) return null;
const [, body, signature] = parts;
const expected = crypto.createHmac('sha256', BRIDGE_SECRET).update(body).digest();
let supplied;
try {
supplied = Buffer.from(signature.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
} catch {
return null;
}
if (
supplied.length !== expected.length ||
!crypto.timingSafeEqual(supplied, expected)
) {
return null;
}
let payload;
try {
payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
} catch {
return null;
}
if (
!payload ||
typeof payload.sid !== 'string' ||
typeof payload.eid !== 'string' ||
typeof payload.uid !== 'string' ||
typeof payload.email !== 'string' ||
(payload.kind !== 'login' && payload.kind !== 'service') ||
typeof payload.exp !== 'number' ||
payload.exp * 1000 <= now
) {
return null;
}
return payload;
}
async function dashboardJson(url, token, init = {}) {
const res = await fetch(url, {
...init,
headers: {
...(init.headers ?? {}),
authorization: `Bearer ${token}`,
},
});
const text = await res.text();
let body = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
body = null;
}
if (!res.ok) {
throw new Error(body?.error || `Dashboard request failed (${res.status})`);
}
return body;
}
/** Swap the one browser-hop login token for a longer server-side token. */
export async function exchangeBridgeToken(loginToken, sessionId) {
return dashboardJson(
`${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}/exchange`,
loginToken,
{ method: 'POST' },
);
}
/* ------------------------------------------------------------------ storage */
const bridgeInsert = db.prepare(`
INSERT INTO bridge_events (event_id, session_id, token, glenloch_url, source_event_id, return_url, expires_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(event_id) DO UPDATE SET
session_id = excluded.session_id,
token = excluded.token,
glenloch_url = excluded.glenloch_url,
source_event_id = excluded.source_event_id,
return_url = excluded.return_url,
expires_at = excluded.expires_at,
created_at = excluded.created_at
`);
const bridgeGet = db.prepare('SELECT * FROM bridge_events WHERE event_id = ?');
const bridgeExpired = db.prepare('SELECT event_id FROM bridge_events WHERE expires_at < ?');
const bridgeDelete = db.prepare('DELETE FROM bridge_events WHERE event_id = ?');
const photosForEvent = db.prepare('SELECT id FROM photos WHERE event_id = ?');
export function bridgeEventId(sourceEventId) {
return `br-${sourceEventId}`;
}
export function bridgePhotoId(sourcePhotoId) {
return `br-${sourcePhotoId}`;
}
export function bridgeForEvent(eventId) {
return bridgeGet.get(eventId) ?? null;
}
/** Deletes an imported event, its rows and any cached previews/thumbnails. */
function dropBridgeEvent(eventId) {
for (const row of photosForEvent.all(eventId)) {
removePhoto(row.id);
removeAsset(row.id).catch(() => undefined);
}
removeEvent(eventId);
bridgeDelete.run(eventId);
}
/** Removes events whose bridge session has expired. Safe to call often. */
export function purgeExpiredBridges(now = Date.now()) {
for (const row of bridgeExpired.all(now)) {
dropBridgeEvent(row.event_id);
}
}
function eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt) {
const source = listing.event;
return {
id: eventId,
name: source.title || 'Advanced edit',
date: source.startsAt ? Date.parse(source.startsAt) : Date.now(),
createdAt: Date.now(),
notes: source.description ?? undefined,
bridge: {
sessionId,
sourceEventId: source.id,
dashboardUrl: returnUrl ?? `${GLENLOCH_URL}/events/${source.id}`,
expiresAt,
},
};
}
function photoRecordFrom(photo, eventId, sessionId, index) {
const id = bridgePhotoId(photo.id);
const raw = photo.kind === 'raw';
return {
id,
eventId,
order: index,
name: photo.filename,
width: photo.width || 0,
height: photo.height || 0,
size: photo.sizeBytes || 0,
mime: photo.mimeType || 'application/octet-stream',
addedAt: Date.now(),
takenAt: photo.takenAt ? Date.parse(photo.takenAt) : undefined,
meta: {},
thumb: '',
thumbUrl: `/api/photos/${id}/thumb`,
rating: 0,
flag: 'none',
color: '',
keywords: [],
edits: {},
history: [],
raw,
previewUrl: raw ? `/api/photos/${id}/preview` : undefined,
bridgeSource: { sessionId, sourceId: photo.id },
};
}
/**
* Mirrors one event into the local catalog. The photo bytes stay on the
* dashboard; only metadata, previews and thumbnails are temporary here.
*/
export async function importBridgeEvent({ serviceToken, sessionId, ownerId = '' }) {
const expiresAt =
Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000;
const listing = await dashboardJson(
`${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}`,
serviceToken,
);
const eventId = bridgeEventId(listing.event.id);
dropBridgeEvent(eventId);
const returnUrl = listing.editor?.returnUrl ?? null;
saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0, ownerId);
listing.photos.forEach((photo, index) => {
savePhoto(photoRecordFrom(photo, eventId, sessionId, index), Date.now(), ownerId);
});
bridgeInsert.run(
eventId,
sessionId,
serviceToken,
GLENLOCH_URL,
listing.event.id,
returnUrl,
expiresAt,
Date.now(),
);
return {
eventId,
photoCount: listing.photos.length,
sessionId,
expiresAt,
};
}
/* ----------------------------------------------------------------- proxying */
export function bridgeSourceUrl(row, sourcePhotoId, variant) {
const params = new URLSearchParams({ variant });
return `${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent(
row.session_id,
)}/photos/${encodeURIComponent(sourcePhotoId)}/source?${params}`;
}
export async function fetchBridgeImage(row, sourcePhotoId, variant) {
return fetch(bridgeSourceUrl(row, sourcePhotoId, variant), {
headers: { authorization: `Bearer ${row.token}` },
});
}
/** Forwards a browser-rendered JPEG and recipe to the dashboard. */
export async function forwardBridgeRender(row, sourcePhotoId, payload) {
const res = await fetch(
`${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent(
row.session_id,
)}/photos/${encodeURIComponent(sourcePhotoId)}/render`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${row.token}`,
},
body: JSON.stringify(payload),
},
);
const text = await res.text();
let body = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
body = null;
}
return { status: res.status, body };
}
+85
View File
@@ -0,0 +1,85 @@
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
export const ROOT = path.resolve(here, '..');
/** Read a Luminary setting, falling back to its pre-rebrand LUMENROOM_ name. */
function setting(name, fallback = '') {
return process.env[`LUMINARY_${name}`] || process.env[`LUMENROOM_${name}`] || fallback;
}
const dataDir = setting('DATA');
export const DATA_DIR = dataDir ? path.resolve(dataDir) : path.join(here, 'data');
export const ORIGINAL_DIR = path.join(DATA_DIR, 'originals');
export const PREVIEW_DIR = path.join(DATA_DIR, 'previews');
export const THUMB_DIR = path.join(DATA_DIR, 'thumbs');
// Keep the original filename so an existing catalog opens without a migration.
export const DB_PATH = path.join(DATA_DIR, 'lumenroom.db');
export const DIST_DIR = path.join(ROOT, 'dist');
export const PORT = Number(process.env.PORT || 8787);
export const HOST = process.env.HOST || '0.0.0.0';
/** Shared invite code required to register after the first account exists. */
export const INVITE = setting('INVITE');
/** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */
export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '');
/** Shared HMAC secret for bridge tokens; must match the dashboard's value. */
export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || '';
/** How long an imported bridge event survives without being reopened. */
export const BRIDGE_TTL_HOURS = Number(setting('BRIDGE_TTL_HOURS', '12'));
/** Upload ceiling in bytes (300 MB default, bigger than any consumer raw). */
export const MAX_UPLOAD = Number(setting('MAX_UPLOAD', String(300 * 1024 * 1024)));
/** Per-account storage allowance. 100 GiB unless the admin changes it. */
export const QUOTA_BYTES = Number(setting('QUOTA_BYTES', String(100 * 1024 * 1024 * 1024)));
/** Fraction of the quota at which the account is warned (0.9 = 90%). */
export const QUOTA_WARN_RATIO = Math.min(
0.99,
Math.max(0.5, Number(setting('QUOTA_WARN_RATIO', '0.9')) || 0.9),
);
/** Scheduled prunes always leave at least this much room below the cap. */
export const QUOTA_TARGET_RATIO = Math.min(
0.95,
Math.max(0.5, Number(setting('QUOTA_TARGET_RATIO', '0.8')) || 0.8),
);
/** Public URL used in notification emails. Empty falls back to localhost. */
export const PUBLIC_URL = setting('PUBLIC_URL').replace(/\/+$/, '');
/** Gmail SMTP defaults; the admin can override these in Administration. */
export const SMTP_HOST = setting('SMTP_HOST', 'smtp.gmail.com');
export const SMTP_PORT = Number(setting('SMTP_PORT', '465'));
export const SMTP_SECURE = setting('SMTP_SECURE', 'true') !== 'false';
export const SMTP_USER = setting('SMTP_USER');
export const SMTP_APP_PASSWORD = setting('SMTP_APP_PASSWORD');
export const SMTP_FROM = setting('SMTP_FROM', SMTP_USER);
/** Long edge used for the editable proxy of raw files. */
export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000'));
export const SESSION_DAYS = 30;
/** How many raws decode at once. One core is left for the HTTP server. */
export const RAW_WORKERS = Math.max(
1,
Number(
setting(
'RAW_WORKERS',
String(Math.min(4, Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1))),
),
),
);
/** Idle decoder workers are disposed after this long to release memory. */
export const RAW_IDLE_MS = Number(setting('RAW_IDLE_MS', '90000'));
+592
View File
@@ -0,0 +1,592 @@
import fs from 'node:fs';
import { DatabaseSync } from 'node:sqlite';
import { DATA_DIR, DB_PATH } from './config.mjs';
fs.mkdirSync(DATA_DIR, { recursive: true });
export const db = new DatabaseSync(DB_PATH);
db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL DEFAULT '',
pass_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member',
disabled INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL DEFAULT '',
sort_index REAL NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
data TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS photos (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL DEFAULT '',
event_id TEXT NOT NULL DEFAULT '',
sort_index REAL NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL,
raw INTEGER NOT NULL DEFAULT 0,
data TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS photos_event ON photos(event_id);
CREATE INDEX IF NOT EXISTS photos_updated ON photos(updated_at);
CREATE TABLE IF NOT EXISTS kv (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS gallery_picks (
token TEXT NOT NULL,
photo_id TEXT NOT NULL,
client_id TEXT NOT NULL,
client_name TEXT NOT NULL DEFAULT '',
picked INTEGER NOT NULL DEFAULT 1,
updated_at INTEGER NOT NULL,
PRIMARY KEY (token, photo_id, client_id)
);
CREATE INDEX IF NOT EXISTS gallery_picks_token ON gallery_picks(token);
CREATE TABLE IF NOT EXISTS gallery_comments (
id TEXT PRIMARY KEY,
token TEXT NOT NULL,
photo_id TEXT NOT NULL,
client_id TEXT NOT NULL,
client_name TEXT NOT NULL DEFAULT '',
body TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS gallery_comments_token ON gallery_comments(token);
CREATE TABLE IF NOT EXISTS gallery_reviews (
token TEXT NOT NULL,
photo_id TEXT NOT NULL,
client_id TEXT NOT NULL,
client_name TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (token, photo_id, client_id)
);
CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token);
CREATE TABLE IF NOT EXISTS invites (
token TEXT PRIMARY KEY,
email TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT 'member',
created_by TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
accepted_at INTEGER,
accepted_by TEXT,
revoked_at INTEGER
);
CREATE INDEX IF NOT EXISTS invites_created ON invites(created_at);
CREATE TABLE IF NOT EXISTS bridge_events (
event_id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
token TEXT NOT NULL,
glenloch_url TEXT NOT NULL,
source_event_id TEXT NOT NULL,
return_url TEXT,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS user_quota (
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
bytes_limit INTEGER NOT NULL DEFAULT 100 * 1024 * 1024 * 1024,
prune_at INTEGER,
prune_plan TEXT,
prune_notified_at INTEGER,
last_quota_email_at INTEGER
);
`);
/* Databases created before account disabling existed get the column in place. */
const userColumns = db.prepare('PRAGMA table_info(users)').all().map((c) => c.name);
if (!userColumns.includes('disabled')) {
db.exec('ALTER TABLE users ADD COLUMN disabled INTEGER NOT NULL DEFAULT 0');
}
/* Quota rows created before scheduled-prune plans were stored need the columns. */
const quotaColumns = db.prepare('PRAGMA table_info(user_quota)').all().map((c) => c.name);
if (!quotaColumns.includes('prune_plan')) {
db.exec('ALTER TABLE user_quota ADD COLUMN prune_plan TEXT');
}
if (!quotaColumns.includes('prune_notified_at')) {
db.exec('ALTER TABLE user_quota ADD COLUMN prune_notified_at INTEGER');
}
/**
* Workspaces arrived after the first shared library. Existing events and photos
* are handed to the oldest account (the admin who created them) once; new rows
* always carry the account that uploaded them.
*/
for (const table of ['events', 'photos']) {
const columns = db.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name);
if (columns.includes('owner_id')) continue;
db.exec(`ALTER TABLE ${table} ADD COLUMN owner_id TEXT NOT NULL DEFAULT ''`);
db.exec(`CREATE INDEX IF NOT EXISTS ${table}_owner ON ${table}(owner_id)`);
db.exec(
`UPDATE ${table} SET owner_id = COALESCE((SELECT id FROM users ORDER BY created_at ASC LIMIT 1), '') WHERE owner_id = ''`,
);
}
/* Proofing links arrived after the first release: events carry their token,
and every client pick is stored against that token. */
const eventColumns = db.prepare('PRAGMA table_info(events)').all().map((c) => c.name);
if (!eventColumns.includes('share_token')) {
db.exec('ALTER TABLE events ADD COLUMN share_token TEXT');
}
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS events_share_token ON events(share_token)');
const q = {
upsertEvent: db.prepare(`
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
sort_index = excluded.sort_index,
data = excluded.data,
owner_id = events.owner_id
`),
deleteEvent: db.prepare('DELETE FROM events WHERE id = ?'),
allEvents: db.prepare('SELECT data FROM events ORDER BY sort_index ASC, created_at ASC'),
allEventsByOwner: db.prepare(
'SELECT data FROM events WHERE owner_id = ? ORDER BY sort_index ASC, created_at ASC',
),
eventOwner: db.prepare('SELECT owner_id FROM events WHERE id = ?'),
eventByShare: db.prepare('SELECT id, owner_id, data FROM events WHERE share_token = ?'),
shareTokenFor: db.prepare('SELECT share_token FROM events WHERE id = ?'),
setShareToken: db.prepare('UPDATE events SET share_token = ? WHERE id = ?'),
clearPicks: db.prepare('DELETE FROM gallery_picks WHERE token = ?'),
clearComments: db.prepare('DELETE FROM gallery_comments WHERE token = ?'),
clearReviews: db.prepare('DELETE FROM gallery_reviews WHERE token = ?'),
commentsByToken: db.prepare(
'SELECT id, photo_id, client_id, client_name, body, created_at FROM gallery_comments WHERE token = ? ORDER BY created_at ASC',
),
commentsByOwner: db.prepare(`
SELECT e.id AS event_id, c.photo_id, c.client_name, c.body, c.created_at
FROM gallery_comments c JOIN events e ON e.share_token = c.token
WHERE e.owner_id = ? ORDER BY c.created_at ASC
`),
insertComment: db.prepare(`
INSERT INTO gallery_comments (id, token, photo_id, client_id, client_name, body, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
`),
deleteCommentsForPhoto: db.prepare('DELETE FROM gallery_comments WHERE photo_id = ?'),
reviewsByToken: db.prepare(
'SELECT photo_id, client_id, client_name, status, updated_at FROM gallery_reviews WHERE token = ?',
),
reviewsByOwner: db.prepare(`
SELECT e.id AS event_id, r.photo_id, r.client_name, r.status, r.updated_at
FROM gallery_reviews r JOIN events e ON e.share_token = r.token
WHERE e.owner_id = ?
`),
upsertReview: db.prepare(`
INSERT INTO gallery_reviews (token, photo_id, client_id, client_name, status, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(token, photo_id, client_id) DO UPDATE SET
client_name = excluded.client_name,
status = excluded.status,
updated_at = excluded.updated_at
`),
deleteReview: db.prepare('DELETE FROM gallery_reviews WHERE token = ? AND photo_id = ? AND client_id = ?'),
deleteReviewsForPhoto: db.prepare('DELETE FROM gallery_reviews WHERE photo_id = ?'),
picksByToken: db.prepare(
'SELECT photo_id, client_id, client_name, picked, updated_at FROM gallery_picks WHERE token = ?',
),
picksByOwner: db.prepare(`
SELECT e.id AS event_id, p.photo_id, p.client_id, p.client_name, p.picked, p.updated_at
FROM gallery_picks p JOIN events e ON e.share_token = p.token
WHERE e.owner_id = ?
`),
upsertPick: db.prepare(`
INSERT INTO gallery_picks (token, photo_id, client_id, client_name, picked, updated_at)
VALUES (?, ?, ?, ?, 1, ?)
ON CONFLICT(token, photo_id, client_id) DO UPDATE SET
client_name = excluded.client_name,
picked = 1,
updated_at = excluded.updated_at
`),
deletePick: db.prepare('DELETE FROM gallery_picks WHERE token = ? AND photo_id = ? AND client_id = ?'),
deletePicksForPhoto: db.prepare('DELETE FROM gallery_picks WHERE photo_id = ?'),
upsertPhoto: db.prepare(`
INSERT INTO photos (id, owner_id, event_id, sort_index, updated_at, raw, data) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
event_id = excluded.event_id,
sort_index = excluded.sort_index,
updated_at = excluded.updated_at,
raw = excluded.raw,
data = excluded.data,
owner_id = photos.owner_id
`),
deletedPhotoBytes: db.prepare(
`SELECT COALESCE(SUM(json_extract(data, '$.size')), 0) AS bytes
FROM photos WHERE owner_id = ? AND json_extract(data, '$.deletedAt') IS NOT NULL`,
),
deletePhoto: db.prepare('DELETE FROM photos WHERE id = ?'),
allPhotos: db.prepare('SELECT data FROM photos ORDER BY sort_index ASC, updated_at ASC'),
allPhotosByOwner: db.prepare(
'SELECT data FROM photos WHERE owner_id = ? ORDER BY sort_index ASC, updated_at ASC',
),
photoOwner: db.prepare('SELECT owner_id FROM photos WHERE id = ?'),
photo: db.prepare('SELECT data FROM photos WHERE id = ?'),
photoCount: db.prepare('SELECT COUNT(*) AS n FROM photos'),
findUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'),
insertUser: db.prepare(
'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)',
),
userCount: db.prepare('SELECT COUNT(*) AS n FROM users'),
findUserById: db.prepare('SELECT id, email, name, role, disabled, created_at FROM users WHERE id = ?'),
allUsers: db.prepare(
'SELECT id, email, name, role, disabled, created_at FROM users ORDER BY created_at ASC',
),
activeAdmins: db.prepare("SELECT COUNT(*) AS n FROM users WHERE role = 'admin' AND disabled = 0"),
setUserName: db.prepare('UPDATE users SET name = ? WHERE id = ?'),
setUserRole: db.prepare('UPDATE users SET role = ? WHERE id = ?'),
setUserDisabled: db.prepare('UPDATE users SET disabled = ? WHERE id = ?'),
setUserPassword: db.prepare('UPDATE users SET pass_hash = ? WHERE id = ?'),
deleteUser: db.prepare('DELETE FROM users WHERE id = ?'),
quotaForUser: db.prepare(
'SELECT user_id, bytes_limit, prune_at, prune_plan, prune_notified_at, last_quota_email_at FROM user_quota WHERE user_id = ?',
),
upsertQuota: db.prepare(`
INSERT INTO user_quota (user_id, bytes_limit, prune_at, prune_plan, prune_notified_at, last_quota_email_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
bytes_limit = excluded.bytes_limit,
prune_at = excluded.prune_at,
prune_plan = excluded.prune_plan,
prune_notified_at = excluded.prune_notified_at,
last_quota_email_at = excluded.last_quota_email_at
`),
photoIdsByEvent: db.prepare('SELECT id FROM photos WHERE event_id = ?'),
// Trashed photos are excluded everywhere a library total is shown: a photo in
// the trash is no longer part of the shoot, and its bytes are freed when the
// trash is emptied.
eventTotals: db.prepare(`
SELECT event_id, COUNT(*) AS n, COALESCE(SUM(json_extract(data, '$.size')), 0) AS bytes
FROM photos
WHERE json_extract(data, '$.deletedAt') IS NULL
GROUP BY event_id
`),
livePhotoCount: db.prepare(
"SELECT COUNT(*) AS n FROM photos WHERE json_extract(data, '$.deletedAt') IS NULL",
),
livePhotoBytes: db.prepare(`
SELECT COALESCE(SUM(json_extract(data, '$.size')), 0) AS bytes
FROM photos WHERE json_extract(data, '$.deletedAt') IS NULL
`),
livePhotoBytesByOwner: db.prepare(`
SELECT COALESCE(SUM(json_extract(data, '$.size')), 0) AS bytes
FROM photos WHERE owner_id = ? AND json_extract(data, '$.deletedAt') IS NULL
`),
allQuotas: db.prepare('SELECT * FROM user_quota'),
insertSession: db.prepare(
'INSERT INTO sessions (token, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)',
),
findSession: db.prepare('SELECT * FROM sessions WHERE token = ?'),
deleteSession: db.prepare('DELETE FROM sessions WHERE token = ?'),
deleteUserSessions: db.prepare('DELETE FROM sessions WHERE user_id = ?'),
purgeSessions: db.prepare('DELETE FROM sessions WHERE expires_at < ?'),
insertInvite: db.prepare(`
INSERT INTO invites (token, email, role, created_by, created_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?)
`),
findInvite: db.prepare('SELECT * FROM invites WHERE token = ?'),
allInvites: db.prepare('SELECT * FROM invites ORDER BY created_at DESC LIMIT 100'),
revokeInvite: db.prepare(
'UPDATE invites SET revoked_at = ? WHERE token = ? AND accepted_at IS NULL AND revoked_at IS NULL',
),
acceptInvite: db.prepare(`
UPDATE invites SET accepted_at = ?, accepted_by = ?
WHERE token = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?
`),
pendingInvites: db.prepare(
'SELECT COUNT(*) AS n FROM invites WHERE accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?',
),
kvGet: db.prepare('SELECT value FROM kv WHERE key = ?'),
kvSet: db.prepare(
'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
),
};
function parse(json) {
if (!json) return null;
try {
return JSON.parse(json);
} catch {
return null;
}
}
export function listEvents(ownerId = null) {
const rows = ownerId ? q.allEventsByOwner.all(ownerId) : q.allEvents.all();
return rows.map((r) => parse(r.data)).filter((r) => r !== null);
}
export function eventOwner(id) {
return q.eventOwner.get(id)?.owner_id ?? null;
}
export function saveEvent(record, sortIndex = 0, ownerId = '') {
q.upsertEvent.run(record.id, ownerId, sortIndex, record.createdAt ?? Date.now(), JSON.stringify(record));
}
export function removeEvent(id) {
q.deleteEvent.run(id);
}
export function shareTokenFor(id) {
return q.shareTokenFor.get(id)?.share_token ?? null;
}
export function eventByShareToken(token) {
const row = q.eventByShare.get(token);
if (!row) return null;
const record = parse(row.data);
if (!record) return null;
return { id: row.id, ownerId: row.owner_id, event: record };
}
/** Sets or clears the event's token; revoking also drops the picks made with it. */
export function setShareToken(id, token) {
const previous = shareTokenFor(id);
q.setShareToken.run(token, id);
if (token === null && previous) {
q.clearPicks.run(previous);
q.clearComments.run(previous);
q.clearReviews.run(previous);
}
return token;
}
export function picksForToken(token) {
return q.picksByToken.all(token).map((row) => ({
photoId: row.photo_id,
clientId: row.client_id,
clientName: row.client_name,
picked: Boolean(row.picked),
updatedAt: row.updated_at,
}));
}
export function picksByOwner(ownerId) {
return q.picksByOwner.all(ownerId).map((row) => ({
eventId: row.event_id,
photoId: row.photo_id,
clientId: row.client_id,
clientName: row.client_name,
picked: Boolean(row.picked),
updatedAt: row.updated_at,
}));
}
export function galleryPick(token, photoId, clientId, clientName, picked) {
if (!picked) {
q.deletePick.run(token, photoId, clientId);
return;
}
q.upsertPick.run(token, photoId, clientId, clientName, Date.now());
}
export function commentsForToken(token) {
return q.commentsByToken.all(token).map((row) => ({
id: row.id,
photoId: row.photo_id,
clientId: row.client_id,
clientName: row.client_name,
body: row.body,
createdAt: row.created_at,
}));
}
export function commentsByOwner(ownerId) {
return q.commentsByOwner.all(ownerId).map((row) => ({
eventId: row.event_id,
photoId: row.photo_id,
clientName: row.client_name,
body: row.body,
createdAt: row.created_at,
}));
}
export function addGalleryComment({ id, token, photoId, clientId, clientName, body }) {
q.insertComment.run(id, token, photoId, clientId, clientName, body, Date.now());
}
export function reviewsForToken(token) {
return q.reviewsByToken.all(token).map((row) => ({
photoId: row.photo_id,
clientId: row.client_id,
clientName: row.client_name,
status: row.status,
updatedAt: row.updated_at,
}));
}
export function reviewsByOwner(ownerId) {
return q.reviewsByOwner.all(ownerId).map((row) => ({
eventId: row.event_id,
photoId: row.photo_id,
clientName: row.client_name,
status: row.status,
updatedAt: row.updated_at,
}));
}
export function setGalleryReview({ token, photoId, clientId, clientName, status }) {
if (!status || status === 'none') {
q.deleteReview.run(token, photoId, clientId);
return;
}
q.upsertReview.run(token, photoId, clientId, clientName, status, Date.now());
}
export function listPhotos(ownerId = null) {
const rows = ownerId ? q.allPhotosByOwner.all(ownerId) : q.allPhotos.all();
return rows.map((r) => parse(r.data)).filter((r) => r !== null);
}
export function getPhoto(id) {
const row = q.photo.get(id);
return row ? parse(row.data) : null;
}
export function photoOwner(id) {
return q.photoOwner.get(id)?.owner_id ?? null;
}
export function savePhoto(record, updatedAt = Date.now(), ownerId = '') {
q.upsertPhoto.run(
record.id,
ownerId,
record.eventId ?? '',
typeof record.order === 'number' ? record.order : 0,
updatedAt,
record.raw ? 1 : 0,
JSON.stringify(record),
);
}
export function removePhoto(id) {
q.deletePhoto.run(id);
// A permanently deleted photo must not keep client feedback alive anywhere.
q.deletePicksForPhoto.run(id);
q.deleteCommentsForPhoto.run(id);
q.deleteReviewsForPhoto.run(id);
}
export function countPhotos() {
return Number(q.livePhotoCount.get()?.n ?? 0);
}
/** Bytes of live photo records, excluding anything sitting in the trash. */
export function livePhotoBytes() {
return Number(q.livePhotoBytes.get()?.bytes ?? 0);
}
/** Bytes of an account's photos that are sitting in the trash. */
export function deletedPhotoBytes(ownerId) {
return Number(q.deletedPhotoBytes.get(ownerId)?.bytes ?? 0);
}
export function livePhotoBytesByOwner(ownerId) {
const row = q.livePhotoBytesByOwner.get(ownerId);
return Number(row?.bytes ?? 0);
}
export function quotaRow(userId) {
return q.quotaForUser.get(userId) ?? null;
}
export function saveQuota(userId, patch = {}) {
const row = quotaRow(userId);
q.upsertQuota.run(
userId,
patch.bytesLimit ?? row?.bytes_limit ?? 100 * 1024 * 1024 * 1024,
patch.pruneAt !== undefined ? patch.pruneAt : (row?.prune_at ?? null),
patch.prunePlan !== undefined
? (patch.prunePlan === null ? null : JSON.stringify(patch.prunePlan))
: (row?.prune_plan ?? null),
patch.pruneNotifiedAt !== undefined ? patch.pruneNotifiedAt : (row?.prune_notified_at ?? null),
patch.lastQuotaEmailAt !== undefined ? patch.lastQuotaEmailAt : (row?.last_quota_email_at ?? null),
);
return quotaRow(userId);
}
export function allQuotaRows() {
return q.allQuotas.all();
}
export const users = {
count: () => Number(q.userCount.get()?.n ?? 0),
byEmail: (email) => q.findUserByEmail.get(String(email).toLowerCase()),
byId: (id) => q.findUserById.get(id),
list: () => q.allUsers.all().map((row) => ({ ...row, disabled: Boolean(row.disabled) })),
activeAdmins: () => Number(q.activeAdmins.get()?.n ?? 0),
create: (user) =>
q.insertUser.run(user.id, user.email.toLowerCase(), user.name, user.passHash, user.role, Date.now()),
update: (id, patch) => {
if (typeof patch.name === 'string') q.setUserName.run(patch.name, id);
if (typeof patch.role === 'string') q.setUserRole.run(patch.role, id);
if (typeof patch.disabled === 'boolean') q.setUserDisabled.run(patch.disabled ? 1 : 0, id);
if (typeof patch.passHash === 'string') q.setUserPassword.run(patch.passHash, id);
return q.findUserById.get(id);
},
remove: (id) => q.deleteUser.run(id),
photoIdsByEvent: (eventId) => q.photoIdsByEvent.all(eventId).map((row) => row.id),
eventTotals: () => q.eventTotals.all(),
};
export const invites = {
create: ({ token, email, role, createdBy, expiresAt }) =>
q.insertInvite.run(token, email, role, createdBy, Date.now(), expiresAt),
byToken: (token) => q.findInvite.get(token) ?? null,
all: () => q.allInvites.all(),
pendingCount: () => Number(q.pendingInvites.get(Date.now())?.n ?? 0),
revoke: (token) => q.revokeInvite.run(Date.now(), token).changes > 0,
accept: (token, userId) => q.acceptInvite.run(Date.now(), userId, token, Date.now()).changes > 0,
};
export const sessions = {
create: (token, userId, expiresAt) => q.insertSession.run(token, userId, Date.now(), expiresAt),
find: (token) => q.findSession.get(token),
destroy: (token) => q.deleteSession.run(token),
destroyForUser: (userId) => q.deleteUserSessions.run(userId),
purge: () => q.purgeSessions.run(Date.now()),
};
export const kv = {
get: (key) => {
const row = q.kvGet.get(key);
return row ? parse(row.value) : null;
},
set: (key, value) => q.kvSet.run(key, JSON.stringify(value)),
};
+62
View File
@@ -0,0 +1,62 @@
/**
* Denoise one proxy. Runs in a worker thread: this is seconds of solid CPU and
* the request thread is also serving the rest of the library.
*
* The proxy is decoded rather than the raw file, deliberately -- these are the
* exact pixels the editor edits, so the result lines up with the canvas and with
* the client's export path.
*/
import { parentPort, workerData } from 'node:worker_threads';
import fs from 'node:fs/promises';
import sharp from 'sharp';
import { denoiseRgb } from './denoise/rgbPipeline.ts';
import { guidedDenoiser } from './denoise/standin.ts';
try {
const { sourcePath, outPath } = workerData;
const buffer = await fs.readFile(sourcePath);
const { data, info } = await sharp(buffer)
.rotate()
.toColourspace('srgb')
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const { width, height, channels } = info;
const rgb = new Uint8Array(width * height * 3);
if (channels === 3) {
rgb.set(data);
} else {
for (let i = 0; i < width * height; i++) {
const s = i * channels;
rgb[i * 3] = data[s];
rgb[i * 3 + 1] = data[Math.min(s + 1, s + channels - 1)];
rgb[i * 3 + 2] = data[Math.min(s + 2, s + channels - 1)];
}
}
const started = performance.now();
// Always full strength: the Amount slider blends on the client, so one render
// serves every setting and the cache key does not move with the slider.
const out = await denoiseRgb({ rgb, width, height }, { amount: 1 }, guidedDenoiser());
// 4:4:4 so the chroma work is not immediately thrown away by the encoder.
const jpeg = await sharp(Buffer.from(out.rgb), { raw: { width, height, channels: 3 } })
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
.toBuffer();
await fs.writeFile(outPath, jpeg);
parentPort?.postMessage({
type: 'done',
ms: Math.round(performance.now() - started),
bytes: jpeg.length,
stats: {
amount: out.stats.amount,
autoGate: out.stats.autoGate,
gate: out.stats.gateCoverage,
noise: out.stats.noise.global,
baseWidth: out.stats.baseWidth,
},
});
} catch (error) {
parentPort?.postMessage({ type: 'error', error: error?.message ?? String(error) });
}
+157
View File
@@ -0,0 +1,157 @@
/**
* Job runner for the detail-preserving denoise.
*
* `server/denoise/` is a verbatim copy of the dependency-free pipeline from the
* raw-noise package. It reconstructs from a per-pixel crossfade between the
* source and a denoised base, so the result is bounded by the original pixels and
* cannot ring or overshoot; flat noise is replaced, structure is given back
* verbatim. The GPU's own `noise` sliders are a separate, much simpler path.
*
* Three things here are deliberate:
*
* - Amount belongs to the client. The worker always renders the full-strength
* denoise and the renderer applies the blend, so the slider is instant, one
* file serves every amount, and the amount cannot be applied twice.
* - The key carries a pipeline version. A change to `server/denoise/` has to
* re-key, or the old renders keep being served as if they were current.
* - Each run is seconds of solid CPU, so runs go through a capped queue and a
* second request for the same photo joins the run already in progress
* instead of starting an identical one.
*/
import crypto from 'node:crypto';
import os from 'node:os';
import { Worker } from 'node:worker_threads';
import { denoisedPath, findDenoised, removeDenoised } from './storage.mjs';
/** Lookup used by the download route; storage owns where the files live. */
export function findDenoisedFor(photoId, key) {
return findDenoised(photoId, key);
}
/** Drop the renders for a photo, e.g. when its edit is cleared. */
export function clearDenoised(photoId) {
return removeDenoised(photoId);
}
/**
* Bump whenever the copied modules under `server/denoise/` change output. The key
* is the only thing between a fixed pipeline and a stale cached file.
*/
const PIPELINE_VERSION = 'guided-5';
const MAX_JOBS = 40;
/**
* A burst of clicks must not pin every core: the raw decoders have their own
* budget and the request thread still has the rest of the library to serve.
*/
const MAX_WORKERS = Math.max(
1,
Math.min(4, Number(process.env.LUMINARY_DENOISE_WORKERS) || (os.cpus().length || 2) - 1),
);
const jobs = new Map();
/** key -> job that is queued or running, so a repeat request joins it. */
const byKey = new Map();
const queue = [];
let active = 0;
export function getDenoiseJob(id) {
return jobs.get(id) ?? null;
}
/** Stable for a photo and a pipeline version -- Amount is the client's business. */
export function denoiseKey(photoId) {
return crypto
.createHash('sha1')
.update(`${photoId}|${PIPELINE_VERSION}`)
.digest('hex')
.slice(0, 12);
}
export function startDenoise({ photoId, sourcePath }) {
const key = denoiseKey(photoId);
const joined = byKey.get(key);
if (joined) return joined;
const url = `/api/photos/${encodeURIComponent(photoId)}/denoised?v=${key}`;
const job = { id: crypto.randomUUID(), photoId, key, state: 'running', startedAt: Date.now() };
// Re-running after the edit was cleared, or a second browser, should not pay
// for the CPU again. The file is the cache; the job just reports it.
if (findDenoised(photoId, key)) {
job.state = 'done';
job.cached = true;
job.url = url;
jobs.set(job.id, job);
pruneJobs();
return job;
}
job.sourcePath = sourcePath;
job.url = url;
jobs.set(job.id, job);
byKey.set(key, job);
queue.push(job);
pruneJobs();
pump();
return job;
}
function pump() {
while (active < MAX_WORKERS && queue.length > 0) {
run(queue.shift());
}
}
function run(job) {
active += 1;
const outPath = denoisedPath(job.photoId, job.key);
const worker = new Worker(new URL('./denoise-worker.mjs', import.meta.url), {
workerData: { sourcePath: job.sourcePath, outPath },
});
worker.on('message', (message) => {
if (message?.type === 'done') {
job.state = 'done';
job.ms = message.ms;
job.bytes = message.bytes;
job.stats = message.stats;
// A version bump (or an older build) leaves its render behind; keep the
// current one and drop the rest so the folder cannot grow without bound.
try {
removeDenoised(job.photoId, job.key);
} catch {
/* cleanup is best effort -- never fail a finished job over it */
}
} else if (message?.type === 'error') {
job.state = 'error';
job.error = message.error;
}
});
worker.on('error', (error) => {
job.state = 'error';
job.error = error?.message ?? 'denoise worker failed';
});
worker.on('exit', () => {
// A crash inside the pipeline would otherwise leave the UI polling forever.
if (job.state === 'running') {
job.state = 'error';
job.error = 'denoise worker exited unexpectedly';
}
active -= 1;
byKey.delete(job.key);
job.sourcePath = null;
pump();
});
}
/** Keep the newest finished jobs; never drop one that is queued or running. */
function pruneJobs() {
if (jobs.size <= MAX_JOBS) return;
for (const [id, job] of jobs) {
if (jobs.size <= MAX_JOBS) break;
if (job.state === 'running') continue;
jobs.delete(id);
}
}
+56
View File
@@ -0,0 +1,56 @@
/**
* Interleaved RGB <-> luma/chroma, so luma and chroma can take different
* denoise paths.
*
* Chroma noise is low-frequency and the eye has little chroma acuity, so it is
* worth smoothing hard; luma carries all the detail and is the expensive,
* gated path. The transform is the standard sRGB-weighted one and round-trips
* to within rounding.
*/
export interface RgbImage {
/** Interleaved 8-bit RGB, `width * height * 3` bytes. */
rgb: Uint8Array;
width: number;
height: number;
}
export interface YccPlanes {
y: Float32Array;
cb: Float32Array;
cr: Float32Array;
}
export function toYcc(image: RgbImage): YccPlanes {
const { rgb, width, height } = image;
const n = width * height;
const y = new Float32Array(n);
const cb = new Float32Array(n);
const cr = new Float32Array(n);
for (let i = 0, p = 0; i < n; i++, p += 3) {
const r = rgb[p];
const g = rgb[p + 1];
const b = rgb[p + 2];
y[i] = 0.299 * r + 0.587 * g + 0.114 * b;
cb[i] = 128 - 0.168736 * r - 0.331264 * g + 0.5 * b;
cr[i] = 128 + 0.5 * r - 0.418688 * g - 0.081312 * b;
}
return { y, cb, cr };
}
export function fromYcc(planes: YccPlanes, width: number, height: number): Uint8Array {
const n = width * height;
const out = new Uint8Array(n * 3);
for (let i = 0, p = 0; i < n; i++, p += 3) {
const y = planes.y[i];
const cb = planes.cb[i] - 128;
const cr = planes.cr[i] - 128;
const r = y + 1.402 * cr;
const g = y - 0.344136 * cb - 0.714136 * cr;
const b = y + 1.772 * cb;
out[p] = r < 0 ? 0 : r > 255 ? 255 : r + 0.5;
out[p + 1] = g < 0 ? 0 : g > 255 ? 255 : g + 0.5;
out[p + 2] = b < 0 ? 0 : b > 255 ? 255 : b + 0.5;
}
return out;
}
+253
View File
@@ -0,0 +1,253 @@
/**
* Detail / structure separation.
*
* The whole feature rests on one idea: a denoiser may only remove things that
* do *not* look like structure. This module produces the map that decides
* that, from three cheap local measurements:
*
* 1. `detail` -- the high-frequency residual of an edge-preserving filter.
* 2. `sigma` -- the noise level expected at this luminance.
* 3. `coherence` -- how organised the local gradient is (a curve vs. grain).
*
* A pixel with detail well above the noise floor, or with a coherent edge
* through it, gets `gate -> 1` and its original values are restored verbatim
* after denoising. Flat grain gets `gate -> 0` and is replaced wholesale.
*/
import { boxBlur, clamp, clamp01, resample, smoothstep } from './planes.ts';
/**
* Guided filter (He et al.), O(1) per pixel.
*
* Used instead of a bilateral filter because it needs no per-pixel search:
* four box passes, and the edge-preserving behaviour is exactly what the
* base/detail split needs. `eps` is a variance, so it is the noise sigma
* squared, scaled by how aggressively we want to smooth.
*/
export function guidedFilter(
src: Float32Array,
width: number,
height: number,
radius: number,
eps: number,
): Float32Array {
const a = boxBlur(src, width, height, radius);
const b = new Float32Array(src.length);
for (let i = 0; i < src.length; i++) b[i] = src[i] * src[i];
boxBlur(b, width, height, radius, b);
// b <- a (the guided-filter gain), a <- mean * (1 - gain).
const e = Math.max(eps, 1e-6);
for (let i = 0; i < src.length; i++) {
const mean = a[i];
const variance = b[i] - mean * mean;
const gain = variance / (variance + e);
b[i] = gain;
a[i] = mean * (1 - gain);
}
boxBlur(b, width, height, radius, b);
boxBlur(a, width, height, radius, a);
const out = new Float32Array(src.length);
for (let i = 0; i < src.length; i++) out[i] = b[i] * src[i] + a[i];
return out;
}
export interface StructureMap {
/** 0 = isotropic (grain, flat), 1 = a clean line or edge. */
data: Float32Array;
width: number;
height: number;
}
/**
* Structure-tensor coherence, computed at reduced resolution.
*
* Coherence is a geometric property of edges and varies slowly across the
* frame, so measuring it at 1/`stride` and interpolating back is visually
* identical and ~`stride^2` cheaper in both time and memory.
*/
export function structureMap(
gray: Float32Array,
width: number,
height: number,
radius = 2,
stride = 2,
sigmaFloor = 1,
): StructureMap {
const sw = Math.max(2, Math.floor(width / stride));
const sh = Math.max(2, Math.floor(height / stride));
const small = resample(gray, width, height, sw, sh);
const gx = new Float32Array(sw * sh);
const gy = new Float32Array(sw * sh);
for (let y = 0; y < sh; y++) {
const y0 = clamp(y - 1, 0, sh - 1) * sw;
const y1 = clamp(y + 1, 0, sh - 1) * sw;
const row = y * sw;
for (let x = 0; x < sw; x++) {
const x0 = clamp(x - 1, 0, sw - 1);
const x1 = clamp(x + 1, 0, sw - 1);
// Scharr kernels: better rotational symmetry than Sobel at this size.
gx[row + x] =
(3 * (small[y0 + x1] - small[y0 + x0]) + 10 * (small[row + x1] - small[row + x0]) + 3 * (small[y1 + x1] - small[y1 + x0])) / 16;
gy[row + x] =
(3 * (small[y1 + x0] - small[y0 + x0]) + 10 * (small[y1 + x] - small[y0 + x]) + 3 * (small[y1 + x1] - small[y0 + x1])) / 16;
}
}
const jxx = new Float32Array(sw * sh);
const jyy = new Float32Array(sw * sh);
const jxy = new Float32Array(sw * sh);
for (let i = 0; i < gx.length; i++) {
jxx[i] = gx[i] * gx[i];
jyy[i] = gy[i] * gy[i];
jxy[i] = gx[i] * gy[i];
}
boxBlur(jxx, sw, sh, radius, jxx);
boxBlur(jyy, sw, sh, radius, jyy);
boxBlur(jxy, sw, sh, radius, jxy);
const data = new Float32Array(sw * sh);
const floor = sigmaFloor * sigmaFloor;
for (let i = 0; i < data.length; i++) {
const trace = jxx[i] + jyy[i];
const disc = Math.sqrt(Math.max(0, (jxx[i] - jyy[i]) * (jxx[i] - jyy[i]) + 4 * jxy[i] * jxy[i]));
if (trace <= floor) continue;
data[i] = clamp01(disc / trace);
}
return { data, width: sw, height: sh };
}
/**
* Mean |detail| of pure Gaussian noise, relative to sigma.
*
* The statistic compared against the threshold is a mean absolute value over
* the 3x3-smoothed high-pass of a noise field, which measures ~1.0 sigma when
* the noise model is correct. Calibrated against a flat ISO 6400 sky, where
* |detail|/sigma had median 1.05. Expressing the ramp in these units puts 1.0
* at "indistinguishable from grain" instead of at "one sigma", which is not
* the same thing at all.
*/
const NOISE_MAGNITUDE = 1.0;
export interface GateOptions {
/** Below this multiple of the expected noise magnitude, detail is noise. */
lo: number;
/** Above this multiple, detail is unambiguously signal. */
hi: number;
/**
* How much an organised edge lowers the amplitude needed to open the gate.
* 1.0 means a perfectly coherent line needs half the contrast of grain to be
* believed; 0 disables the structure term entirely.
*/
coherenceBoost: number;
/**
* Isolated points have no coherence, so the structure term cannot save them
* and the 3x3 magnitude average below shrinks them toward the noise floor. A
* pixel that is the local maximum of |detail| and clears this many noise
* magnitudes on its own opens the gate anyway.
*/
pointLo: number;
/** Above this multiple, an isolated point is unambiguously real. */
pointHi: number;
}
// 1.0 measured on three D700 frames with synthetic sigma=6: fine-texture
// retention 48/52/24% -> 78/79/45% against 0 (no structure term), edge
// retention up, global grain unchanged. 1.5 reaches 97-98% but at 14% gate
// coverage it starts keeping the grain that sits on the texture, which is not
// separable at this scale anyway -- 1.0 is the knee.
// pointLo/Hi measured by injecting 1 px sources into a real ISO 6400 sky. The
// old gate kept 8% of a 5-sigma point's contrast and 44% of an 8-sigma one.
//
// The threshold looks high for a reason: the rule is a *local maximum*, and the
// max of nine correlated grain samples routinely reaches ~2 sigma, so 2.2 both
// protected grain and failed the corpus guard (grain 0.55 -> 1.36). 3.0 is the
// lowest value that leaves grain and chroma unchanged across the guarded corpus
// while keeping 5-sigma points (~0.9 of their contrast) and 8-sigma points
// (~1.0). A 3-sigma point stays smoothed -- at this scale it is not separable
// from the brightest grain beside it, and pretending otherwise costs the frame.
export const DEFAULT_GATE: GateOptions = {
lo: 1.15,
hi: 2.1,
coherenceBoost: 1.0,
pointLo: 3.0,
pointHi: 4.0,
};
/**
* Per-pixel "how much of this pixel is real" map, 0..1.
* *`detail` is the signed residual, `sigma` the expected noise at each pixel.
* The detail magnitude is box-smoothed so a single stray pixel cannot open the
* gate on its own, and `coherence` scales the amplitude required to open it.
* The one exception is an isolated peak large enough to be a point source:
* smoothing would erase exactly the detail (stars, specular pinpoints) this
* feature exists to keep, so local maxima get their own path.
*/
export function detailGate(
detail: Float32Array,
width: number,
height: number,
sigma: Float32Array,
coherence: Float32Array,
options: GateOptions = DEFAULT_GATE,
): Float32Array {
const magnitude = new Float32Array(detail.length);
for (let i = 0; i < detail.length; i++) magnitude[i] = detail[i] < 0 ? -detail[i] : detail[i];
boxBlur(magnitude, width, height, 1, magnitude);
const gate = new Float32Array(detail.length);
const pointOn = options.pointHi > 0 && options.pointHi > options.pointLo;
for (let i = 0; i < detail.length; i++) {
const s = sigma[i] < 0.05 ? 0.05 : sigma[i];
// 1.0 means "exactly what a flat noisy patch measures", not "one sigma".
const ratio = magnitude[i] / (NOISE_MAGNITUDE * s);
// Coherence of pure noise measures ~0.49, so it cannot be applied linearly:
// that leaks ~0.12 of gate onto every grain pixel. Cubing it keeps ordinary
// noise at ~0.12 while a real edge (0.9) still reaches 0.73.
const organised = coherence[i] * coherence[i] * coherence[i];
// Coherence *lowers the bar*, it does not add to the answer. Adding an
// independent term (the previous form) meant an organised line still had to
// clear the full amplitude threshold on its own, so low-contrast 2-3 px
// texture -- which is exactly what "detail soft" looks like -- got nothing.
// Scaling the ratio instead says: a line needs less contrast to be believed,
// which is the same claim the threshold makes about grain.
const belief = 1 + options.coherenceBoost * organised;
let g = smoothstep(options.lo, options.hi, ratio * belief);
// Isolated-point path. The 3x3 average above shrinks a 1 px source toward
// the noise floor, so the crossfade replaced it with the softened base --
// measured: a 5-sigma point kept 8%, an 8-sigma point 44%. The threshold sits
// above the local maximum grain reaches (see DEFAULT_GATE). Ties pass so a
// 2 px highlight is not lost to the comparison.
if (pointOn) {
const a = detail[i] < 0 ? -detail[i] : detail[i];
const own = a / (NOISE_MAGNITUDE * s);
if (own > options.pointLo) {
const x = i % width;
const y = (i - x) / width;
if (x > 0 && y > 0 && x < width - 1 && y < height - 1) {
let peak = true;
for (let dy = -1; dy <= 1 && peak; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (dx === 0 && dy === 0) continue;
const n = detail[i + dy * width + dx];
if ((n < 0 ? -n : n) > a) {
peak = false;
break;
}
}
}
if (peak) {
const opened = smoothstep(options.pointLo, options.pointHi, own);
if (opened > g) g = opened;
}
}
}
}
gate[i] = g;
}
return gate;
}
+176
View File
@@ -0,0 +1,176 @@
/**
* Noise level estimation from a single finished image.
*
* The model is the Poisson-Gaussian one the rest of the pipeline assumes:
*
* var(luma) = shot * luma + read
*
* but measured in 8-bit sRGB units directly, because the thing we can actually
* see and measure is the finished proxy -- after demosaic, tone curve and JPEG.
* Fitting a sensor model and then pushing it through LibRaw's tone curve would
* be more principled and much less reliable.
*
* Two details make the estimate usable on real photographs:
*
* - The high-pass residual is taken over 16x16 blocks, and texture (which
* raises the local MAD) is kept out of the answer by a two-step statistic:
* a low quantile of the per-block sigmas sets the scale, blocks near it are
* kept, and the median of those is the estimate. See the comment at the
* computation for why neither statistic works alone.
* - A 3x3 box high-pass attenuates white noise by sqrt(8/9); that gain is
* divided back out, otherwise every sigma is 6% low.
*/
import { boxBlur, clamp, quantile } from './planes.ts';
/** White-noise gain of `I - boxBlur(I, 1)`; sqrt(1 - 2/9 + 1/9). */
const HP_NOISE_GAIN = Math.sqrt(8 / 9);
/** MAD -> sigma for a Gaussian. */
const MAD_TO_SIGMA = 1 / 0.6745;
/** Below this, an 8-bit sRGB image has no measurable noise. */
export const SIGMA_FLOOR = 0.35;
export type NoiseTrend = 'fit' | 'flat';
export interface NoiseModel {
/** sigma = a + b * luma, 8-bit units. */
a: number;
b: number;
/** Whether the luminance trend was trusted, or a flat floor was used. */
trend: NoiseTrend;
/** Per-bin measurements that produced the fit (diagnostics). */
bins: { luma: number; sigma: number; blocks: number }[];
/** Robust global floor, ignoring the luminance trend. */
global: number;
sigmaAt(luma: number): number;
}
export function createNoiseModel(
a: number,
b: number,
global: number,
bins: NoiseModel['bins'],
trend: NoiseTrend = 'flat',
): NoiseModel {
return {
a,
b,
global,
trend,
bins,
sigmaAt(luma: number): number {
const s = a + b * clamp(luma, 0, 255);
return s < SIGMA_FLOOR ? SIGMA_FLOOR : s;
},
};
}
export function estimateNoise(luma: Float32Array, width: number, height: number): NoiseModel {
const residual = boxBlur(luma, width, height, 1);
for (let i = 0; i < residual.length; i++) residual[i] = luma[i] - residual[i];
const BLOCK = 16;
const BINS = 16;
const perBin: number[][] = Array.from({ length: BINS }, () => []);
const all: number[] = [];
const scratch = new Float32Array(BLOCK * BLOCK);
for (let by = 0; by + BLOCK <= height; by += BLOCK) {
for (let bx = 0; bx + BLOCK <= width; bx += BLOCK) {
let sumLuma = 0;
let n = 0;
for (let y = 0; y < BLOCK; y++) {
const row = (by + y) * width + bx;
for (let x = 0; x < BLOCK; x++) {
sumLuma += luma[row + x];
const v = residual[row + x];
scratch[n++] = v < 0 ? -v : v;
}
}
const meanLuma = sumLuma / n;
// Clipped highlights and crushed blacks have no usable noise statistic.
if (meanLuma < 6 || meanLuma > 249) continue;
const sigma = quantile(scratch.subarray(0, n), 0.5) * MAD_TO_SIGMA / HP_NOISE_GAIN;
// A perfectly flat block measures exactly zero and must be *kept*: it is
// the strongest evidence of a clean frame. Dropping it left a frame that
// was half flat and half texture reported as uniformly noisy.
if (!Number.isFinite(sigma)) continue;
all.push(sigma);
const bin = clamp(Math.floor(meanLuma / (256 / BINS)), 0, BINS - 1);
perBin[bin].push(sigma);
}
}
if (all.length === 0) {
return createNoiseModel(SIGMA_FLOOR, 0, SIGMA_FLOOR, []);
}
// Two steps, because either statistic alone fails on a real frame:
//
// - the *median* is accurate on a homogeneous field but reads texture as
// noise when more than half the frame is detailed (a brick wall, a striping
// shirt, half a test chart), which can push sigma 30x high;
// - a low quantile ignores texture but sits in the low tail of the
// estimator's own sampling noise.
//
// So: a low quantile sets the scale, blocks near it are kept, and the median
// of those is the answer. At ~10k blocks the quantile's bias is a few percent
// and the median removes it.
const floor = Math.max(SIGMA_FLOOR, quantile(all, 0.25));
const cutoff = floor * 1.5;
const flatBlocks = all.filter((value) => value <= cutoff);
const global = Math.max(SIGMA_FLOOR, quantile(flatBlocks.length > 0 ? flatBlocks : all, 0.5));
const bins: NoiseModel['bins'] = [];
for (let i = 0; i < BINS; i++) {
const flat = perBin[i].filter((v) => v <= cutoff);
if (flat.length < 5) continue;
bins.push({
luma: (i + 0.5) * (256 / BINS),
sigma: quantile(flat, 0.5),
blocks: flat.length,
});
}
// A bin that is mostly texture reports texture, not noise: on a frame with a
// detailed foreground the low-luma bins can read several times the true
// floor. Fit only the bins that sit near the floor, then reject the whole
// trend if the resulting line leaves a physically plausible range. A flat
// sigma is a worse model than a good trend and a far better one than a bad
// trend, and this keeps the bad trend out.
const usable = bins.filter((bin) => bin.blocks >= 8 && bin.sigma <= global * 1.6);
if (usable.length >= 3) {
let sw = 0;
let sx = 0;
let sy = 0;
let sxx = 0;
let sxy = 0;
for (const bin of usable) {
const w = bin.blocks;
sw += w;
sx += w * bin.luma;
sy += w * bin.sigma;
sxx += w * bin.luma * bin.luma;
sxy += w * bin.luma * bin.sigma;
}
const det = sw * sxx - sx * sx;
if (Math.abs(det) > 1e-6) {
const b = (sw * sxy - sx * sy) / det;
const a = (sy - b * sx) / sw;
const low = a;
const high = a + b * 255;
const lo = global * 0.5;
const hi = global * 2.5;
if (
Number.isFinite(a) &&
Number.isFinite(b) &&
low >= lo && low <= hi &&
high >= lo && high <= hi
) {
return createNoiseModel(a, b, global, bins, 'fit');
}
}
}
return createNoiseModel(global, 0, global, bins);
}
+179
View File
@@ -0,0 +1,179 @@
/**
* Scalar float planes plus the resampling and box-filter primitives the
* detail-preserving denoise is built from.
*
* Everything here is plain `Float32Array` arithmetic with no allocation in the
* hot loops: the full-resolution stage runs at proxy size (up to 24 MP), and
* allocation churn is the difference between two seconds and six per photo.
*/
export interface Plane {
data: Float32Array;
width: number;
height: number;
}
export function createPlane(width: number, height: number): Plane {
return { data: new Float32Array(width * height), width, height };
}
export function clamp01(v: number): number {
return v < 0 ? 0 : v > 1 ? 1 : v;
}
export function clamp(v: number, lo: number, hi: number): number {
return v < lo ? lo : v > hi ? hi : v;
}
/** Hermite ramp: 0 below `lo`, 1 above `hi`. */
export function smoothstep(lo: number, hi: number, x: number): number {
if (hi <= lo) return x >= hi ? 1 : 0;
const t = clamp01((x - lo) / (hi - lo));
return t * t * (3 - 2 * t);
}
function edge(i: number, n: number): number {
return i < 0 ? 0 : i >= n ? n - 1 : i;
}
/**
* Scratch buffer for the separable passes, grown on demand.
*
* Safe because `boxBlur` is not reentrant: every caller finishes with the
* buffer before making another call, and the buffer is never handed out.
*/
let scratchBuffer: Float32Array | null = null;
function scratch(length: number): Float32Array {
if (!scratchBuffer || scratchBuffer.length < length) scratchBuffer = new Float32Array(length);
return scratchBuffer.subarray(0, length);
}
/**
* Separable box blur with clamped edges, O(1) per pixel.
*
* `out` may alias `src`: the horizontal pass goes through the shared scratch
* buffer, and only the vertical pass writes `out`, so an in-place call is
* safe. That aliasing is what keeps the guided filter allocation-light.
*/
export function boxBlur(
src: Float32Array,
width: number,
height: number,
radius: number,
out?: Float32Array,
): Float32Array {
const dst = out ?? new Float32Array(src.length);
if (src.length < width * height) {
throw new Error(`plane is ${src.length} values, expected ${width * height}`);
}
if (radius <= 0) {
if (dst !== src) dst.set(src);
return dst;
}
const tmp = scratch(width * height);
const norm = 1 / (2 * radius + 1);
// Horizontal pass: src -> tmp.
for (let y = 0; y < height; y++) {
const row = y * width;
let sum = 0;
for (let x = -radius; x <= radius; x++) sum += src[row + edge(x, width)];
for (let x = 0; x < width; x++) {
tmp[row + x] = sum * norm;
sum += src[row + edge(x + radius + 1, width)] - src[row + edge(x - radius, width)];
}
}
// Vertical pass: tmp -> dst.
for (let x = 0; x < width; x++) {
let sum = 0;
for (let y = -radius; y <= radius; y++) sum += tmp[edge(y, height) * width + x];
for (let y = 0; y < height; y++) {
dst[y * width + x] = sum * norm;
sum +=
tmp[edge(y + radius + 1, height) * width + x] -
tmp[edge(y - radius, height) * width + x];
}
}
return dst;
}
/**
* Bilinear resample. Used for the two-scale split: luma is reduced to the
* inference size, denoised, then brought back up so full-resolution detail can
* be re-injected on top.
*/
export function resample(
src: Float32Array,
sw: number,
sh: number,
dw: number,
dh: number,
): Float32Array {
if (sw === dw && sh === dh) return src.slice();
const out = new Float32Array(dw * dh);
const xRatio = sw / dw;
const yRatio = sh / dh;
for (let y = 0; y < dh; y++) {
// Sample at pixel centres so a downscale is a centred box, not a shifted one.
const sy = clamp((y + 0.5) * yRatio - 0.5, 0, sh - 1);
const y0 = Math.floor(sy);
const y1 = Math.min(y0 + 1, sh - 1);
const wy = sy - y0;
for (let x = 0; x < dw; x++) {
const sx = clamp((x + 0.5) * xRatio - 0.5, 0, sw - 1);
const x0 = Math.floor(sx);
const x1 = Math.min(x0 + 1, sw - 1);
const wx = sx - x0;
const top = src[y0 * sw + x0] * (1 - wx) + src[y0 * sw + x1] * wx;
const bot = src[y1 * sw + x0] * (1 - wx) + src[y1 * sw + x1] * wx;
out[y * dw + x] = top * (1 - wy) + bot * wy;
}
}
return out;
}
/**
* O(n) percentile for large non-negative arrays, by histogram.
*
* `quantile` sorts, which is correct and fine for a 256-value block but ruinous
* for an 18 MP plane: two sorts there cost 11.5 s against a 6.6 s denoise. Bins
* over [0, max] return a median accurate to ~0.2 on 8-bit data, far inside the
* noise being measured.
*
* `values` must be non-negative (magnitudes, gradients, residuals).
*/
export function fastPercentile(values: Float32Array, q: number, bins = 1024): number {
const n = values.length;
if (n === 0) return 0;
let max = 0;
for (let i = 0; i < n; i++) {
const v = values[i];
if (v > max) max = v;
}
if (!(max > 0)) return 0;
const hist = new Uint32Array(bins);
const scale = (bins - 1) / max;
for (let i = 0; i < n; i++) hist[(values[i] * scale) | 0]++;
const target = clamp(q, 0, 1) * (n - 1);
let seen = 0;
for (let b = 0; b < bins; b++) {
seen += hist[b];
if (seen > target) return b / scale;
}
return max;
}
/** Linear-interpolated quantile of a copy of `values`. `q` is 0..1. */
export function quantile(values: Float32Array | number[], q: number): number {
const n = values.length;
if (n === 0) return 0;
const sorted = Float32Array.from(values as ArrayLike<number>).sort();
const pos = clamp(q, 0, 1) * (n - 1);
const lo = Math.floor(pos);
const hi = Math.min(lo + 1, n - 1);
return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
}
+349
View File
@@ -0,0 +1,349 @@
/**
* The RGB proxy denoise pipeline: two scales, one gate.
*
* proxy -> YCbCr
* -> base: downscale RGB, run `runBase`, upscale
* -> luma: low-pass at the detail scale, gate per pixel
* -> reconstruct: crossfade luma to the base where the gate is closed,
* and take chroma from the base outright
*
* `runBase` is the only thing that knows how to denoise. Today it is a guided
* filter or NLM; when the ONNX session lands it is a tiled model runner and
* nothing else in this file changes. That is the seam the build plan is built
* around, and it is RGB so a colour-trained model is fed what it expects.
*
* The reconstruction invariant: output luma is a per-pixel crossfade between
* the untouched input (gate 1) and the denoised base (gate 0). It is bounded by
* its two inputs, so it cannot ring or overshoot, and where the gate opens the
* pixels are identical to the original.
*/
import { fromYcc, toYcc, type RgbImage } from './color.ts';
import {
DEFAULT_GATE,
detailGate,
structureMap,
type GateOptions,
} from './detail.ts';
import { estimateNoise, type NoiseModel } from './noise.ts';
import { boxBlur, clamp01, clamp, resample, smoothstep } from './planes.ts';
import type { BaseDenoiser, BaseImage } from './standin.ts';
export type DenoiserName = 'guided' | 'nlm' | 'onnx';
export interface DenoiseOptions {
/** 0..1 blend against the input, applied after reconstruction. */
amount: number;
/**
* Long edge of the plane the base denoiser runs on.
*
* Raising this on extreme-ISO frames looks like a free win on a detail metric
* (+0.07 retention at 3200 on 18 MP ISO 6400) but was rejected: the corpus
* guard measured grain 0.52 -> 1.30 and chroma 0.50 -> 1.20 at 3200. A sharper
* base is not more detail, it is grain the crossfade then has to keep.
*/
baseEdge: number;
/** Scale below which content is treated as detail worth protecting. */
detailRadius: number;
/**
* Radius of the second, coarser detail band. 0 disables it.
*
* The fine band (radius 2) is what the original gate judged, and it leaves
* near-isotropic 3-8 px texture unread: the texture that survives is the
* part that happens to be coherent at 2 px. The coarse band is the difference
* of two low-passes, so it sees that scale while rejecting both gradients and
* pixel-scale grain -- measured in docs/PLAN.md.
*/
coarseRadius: number;
/** Coarse-band thresholds, in fine-band noise units. */
coarseLo: number;
coarseHi: number;
/**
* Below this measured global grain the frame is clean and the pipeline tapers
* itself to an identity. Without it a base-ISO file loses real micro-texture
* to a denoise it never needed: measured at 36% of high-frequency energy on a
* clean ISO 100 D700 frame.
*/
cleanSigma: number;
gate: GateOptions;
}
export const DEFAULT_OPTIONS: DenoiseOptions = {
amount: 1,
baseEdge: 1600,
detailRadius: 2,
coarseRadius: 6,
coarseLo: 1.2,
coarseHi: 2.0,
cleanSigma: 2.5,
gate: DEFAULT_GATE,
};
export interface StageTimings {
noise: number;
base: number;
detail: number;
coarse: number;
structure: number;
reconstruct: number;
total: number;
}
export interface DenoiseStats {
width: number;
height: number;
baseWidth: number;
baseHeight: number;
/** How much the base plane was reduced, e.g. 3.25 for a 6000px proxy. */
backscale: number;
amount: number;
noise: { a: number; b: number; trend: 'fit' | 'flat'; global: number; atMid: number };
/** Mean gate value: the share of the frame given back as structure. */
gateCoverage: number;
/** How much of the requested amount survived the clean-image taper (0..1). */
autoGate: number;
timings: StageTimings;
}
export interface DenoiseOutput {
rgb: Uint8Array;
/** Luma of the denoised base, before detail re-injection, for inspection. */
base: { data: Float32Array; width: number; height: number };
stats: DenoiseStats;
}
const now = () => performance.now();
/**
* Prefiltered decimation of interleaved RGB to the base plane.
*
* The prefilter is load-bearing, and the coarse gate is what exposed it. A bare
* bilinear tap reads four of every ~42 source pixels at `backscale` 3.25, so
* pixel-scale grain is aliased into the base and comes back wherever the gate
* is closed. Measured on the three mid-ISO frames at sigma 6, with the coarse
* band on: grain 0.32/0.20/0.35 with bilinear against 0.22/0.20/0.22 with the
* box prefilter, for 1.9% less high-frequency energy. The gate protects detail
* and cannot protect grain out of an aliased base, so this belongs in the
* decimator rather than in a threshold.
*
* One channel at a time through the tested `resample`, so the peak extra memory
* is a single full-resolution plane, not three.
*/
function resampleRgb(
image: RgbImage,
width: number,
height: number,
prefilterRadius: number,
): BaseImage {
const out = new Float32Array(width * height * 3);
const src = new Float32Array(image.width * image.height);
for (let k = 0; k < 3; k++) {
for (let i = 0, p = k; i < src.length; i++, p += 3) src[i] = image.rgb[p];
if (prefilterRadius > 0) boxBlur(src, image.width, image.height, prefilterRadius, src);
const small = resample(src, image.width, image.height, width, height);
for (let i = 0, p = k; i < small.length; i++, p += 3) out[p] = small[i];
}
return { rgb: out, width, height };
}
/**
* Bilinear upscale of the base to full resolution, quantised to 8 bits so the
* tested `toYcc` can be reused rather than duplicating the colour maths here.
*/
function upsampleBase(base: BaseImage, width: number, height: number): RgbImage {
const rgb = new Uint8Array(width * height * 3);
const xRatio = base.width / width;
const yRatio = base.height / height;
for (let y = 0; y < height; y++) {
const sy = clamp((y + 0.5) * yRatio - 0.5, 0, base.height - 1);
const y0 = Math.floor(sy);
const y1 = Math.min(y0 + 1, base.height - 1);
const wy = sy - y0;
for (let x = 0; x < width; x++) {
const sx = clamp((x + 0.5) * xRatio - 0.5, 0, base.width - 1);
const x0 = Math.floor(sx);
const x1 = Math.min(x0 + 1, base.width - 1);
const wx = sx - x0;
const a = (y0 * base.width + x0) * 3;
const b = (y0 * base.width + x1) * 3;
const c = (y1 * base.width + x0) * 3;
const d = (y1 * base.width + x1) * 3;
const o = (y * width + x) * 3;
for (let k = 0; k < 3; k++) {
const top = base.rgb[a + k] * (1 - wx) + base.rgb[b + k] * wx;
const bot = base.rgb[c + k] * (1 - wx) + base.rgb[d + k] * wx;
const v = top * (1 - wy) + bot * wy;
rgb[o + k] = v < 0 ? 0 : v > 255 ? 255 : v + 0.5;
}
}
}
return { rgb, width, height };
}
export async function denoiseRgb(
image: RgbImage,
options: Partial<DenoiseOptions>,
runBase: BaseDenoiser,
): Promise<DenoiseOutput> {
const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } };
const started = now();
const { width, height } = image;
const pixels = width * height;
const { y, cb, cr } = toYcc(image);
let mark = now();
const noise: NoiseModel = estimateNoise(y, width, height);
const timings: StageTimings = {
noise: now() - mark,
base: 0,
detail: 0,
coarse: 0,
structure: 0,
reconstruct: 0,
total: 0,
};
// --- base: the inference scale -------------------------------------------
const longEdge = Math.max(width, height);
const scale = opts.baseEdge > 0 ? Math.min(1, opts.baseEdge / longEdge) : 1;
const baseWidth = Math.max(8, Math.round(width * scale));
const baseHeight = Math.max(8, Math.round(height * scale));
const backscale = width / baseWidth;
mark = now();
const prefilterRadius = backscale > 1.001 ? Math.max(0, Math.round((backscale - 1) / 2)) : 0;
const baseInput = resampleRgb(image, baseWidth, baseHeight, prefilterRadius);
// What the base denoiser is told about the noise it will see.
//
// The decimator is box(W) followed by the two bilinear taps. Along one axis
// the taps overlap in W-1 samples at weight 1/W each and contribute
// (1-t)^2 + t^2 at the two ends, which averages 2/3 over t, so the per-axis
// *variance* gain is (W - 1/3) / W^2. Both axes are equal, so the standard
// deviation falls by the same factor squared, i.e. by that number again:
// 0.296 at W=3 against 1/backscale = 0.373.
//
// The old `/ backscale` was a guess -- and with bare bilinear (W=1) the true
// figure is 2/3, which is why it read ~2x low. The classical stand-ins never
// noticed (`planeSigma` re-measures each plane), but a model consumes this as
// a prior, so it has to describe the filter that actually ran.
const prefilterWidth = 2 * prefilterRadius + 1;
const decimatedSigma =
backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1;
const baseSigma = noise.sigmaAt(110) * decimatedSigma;
const baseOut = await runBase(baseInput, baseSigma);
const baseUp = toYcc(upsampleBase(baseOut, width, height));
timings.base = now() - mark;
// --- detail gate at full resolution --------------------------------------
//
// The split filter is a plain low-pass, deliberately, and not an
// edge-preserving one. An edge-aware filter follows strong edges, which
// leaves them in the low band; the base cannot represent them after the
// downscale, and nothing would put them back -- measured as 41% of edge
// contrast lost. A low-pass pushes edges into `detail`, where the gate sees
// them as signal.
mark = now();
const smooth = boxBlur(y, width, height, opts.detailRadius);
const detail = new Float32Array(pixels);
for (let i = 0; i < pixels; i++) detail[i] = y[i] - smooth[i];
timings.detail = now() - mark;
mark = now();
// The tensor is measured on the *original* luma, not on `smooth`.
//
// `smooth` is the same 5x5 low-pass that defines the detail band, so 2-3 px
// texture has already been attenuated by the time the tensor sees it: the
// gate was judging fine texture with a measurement that could not see it, and
// coverage on a texture-rich frame came out *lower* than on a smooth one
// (3.8% vs 9.3%). `structureMap` resamples to half resolution first, which
// halves the noise while leaving 2 px structure intact, so this reads the
// scale it is being asked about.
const structure = structureMap(y, width, height, 2, 2, noise.global);
const coherence = resample(structure.data, structure.width, structure.height, width, height);
const sigmaMap = new Float32Array(pixels);
for (let i = 0; i < pixels; i++) sigmaMap[i] = noise.sigmaAt(smooth[i]);
timings.structure = now() - mark;
mark = now();
let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate);
// Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It
// rejects gradients (both low-passes follow them) and pixel-scale grain (both
// average it), so it can open on texture that the fine band reads as noise
// without opening on flat noisy sky. The isolated-point path is a fine-band
// instrument and is deliberately disabled here.
if (opts.coarseRadius > opts.detailRadius && opts.coarseHi > opts.coarseLo) {
const coarseSmooth = boxBlur(y, width, height, opts.coarseRadius);
const coarse = new Float32Array(pixels);
for (let i = 0; i < pixels; i++) coarse[i] = smooth[i] - coarseSmooth[i];
const coarseGate = detailGate(coarse, width, height, sigmaMap, coherence, {
...opts.gate,
lo: opts.coarseLo,
hi: opts.coarseHi,
pointHi: 0,
});
for (let i = 0; i < pixels; i++) if (coarseGate[i] > gate[i]) gate[i] = coarseGate[i];
timings.coarse = now() - mark;
}
// Clean frames get their amount tapered to nothing: 0.8 sigma of measured
// grain is quantisation, 2.5 is a genuinely noisy file.
const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1;
const amount = clamp01(opts.amount) * autoGate;
const outY = new Float32Array(pixels);
const outCb = new Float32Array(pixels);
const outCr = new Float32Array(pixels);
let gateSum = 0;
for (let i = 0; i < pixels; i++) {
gateSum += gate[i];
// Crossfade, never additive re-injection: additive detail lands on top of a
// base that already contains a softened copy of the same edge and overshoots
// by ~40%. A crossfade is bounded by its two inputs, so it cannot ring, and
// where the gate opens the pixels are bit-identical to the original.
outY[i] = y[i] + amount * (1 - gate[i]) * (baseUp.y[i] - y[i]);
// Chroma follows the same gate, for a different reason than luma does. The
// base carries chroma upsampled from `backscale` times smaller, so replacing
// it outright smears colour across every sharp edge: on a small aircraft
// against bright sky that is a magenta fringe along the wing and red/white
// paint that loses its boundary. Keeping the original chroma where the gate
// says "structure" keeps the paint edge registered with the luma edge it
// belongs to. Flat areas still take the base chroma, which is where the
// chroma noise lives.
outCb[i] = cb[i] + amount * (1 - gate[i]) * (baseUp.cb[i] - cb[i]);
outCr[i] = cr[i] + amount * (1 - gate[i]) * (baseUp.cr[i] - cr[i]);
}
const rgb = fromYcc({ y: outY, cb: outCb, cr: outCr }, width, height);
timings.reconstruct = now() - mark;
timings.total = now() - started;
const baseLuma = new Float32Array(baseWidth * baseHeight);
for (let i = 0, p = 0; i < baseLuma.length; i++, p += 3) {
baseLuma[i] = 0.299 * baseOut.rgb[p] + 0.587 * baseOut.rgb[p + 1] + 0.114 * baseOut.rgb[p + 2];
}
return {
rgb,
base: { data: baseLuma, width: baseWidth, height: baseHeight },
stats: {
width,
height,
baseWidth,
baseHeight,
backscale,
amount,
noise: {
a: noise.a,
b: noise.b,
trend: noise.trend,
global: noise.global,
atMid: noise.sigmaAt(110),
},
gateCoverage: gateSum / pixels,
autoGate,
timings,
},
};
}
+166
View File
@@ -0,0 +1,166 @@
/**
* Stand-in denoisers for the reduced-resolution base.
*
* These occupy exactly the slot the ONNX model occupies: take an interleaved
* RGB plane at inference scale plus the noise level there, return a denoised
* plane of the same shape. Having credible classical implementations in that
* slot is what lets the pipeline, the harness and the baselines be finished and
* measured before a model exists -- and they are the numbers the model has to
* beat.
*
* The seam is RGB, not luma, deliberately: a denoiser trained on colour images
* fed a replicated greyscale plane is out of distribution and underperforms a
* plain guided filter. Chroma also comes from this plane, so the model gets a
* say in colour noise, which is the part users actually complain about.
*
* `nlm` is the honest reference. `guided` is fast enough to iterate against.
*/
import { guidedFilter } from './detail.ts';
import { boxBlur } from './planes.ts';
export interface BaseImage {
/** Interleaved RGB, `width * height * 3`, 0..255. */
rgb: Float32Array;
width: number;
height: number;
}
/**
* Synchronous for the classical stand-ins, a promise for a model session.
* ONNX inference cannot be made synchronous, so the seam allows both and the
* pipeline awaits the result.
*/
export type BaseDenoiser = (image: BaseImage, sigma: number) => BaseImage | Promise<BaseImage>;
export function deinterleave(image: BaseImage): [Float32Array, Float32Array, Float32Array] {
const n = image.width * image.height;
const r = new Float32Array(n);
const g = new Float32Array(n);
const b = new Float32Array(n);
for (let i = 0, p = 0; i < n; i++, p += 3) {
r[i] = image.rgb[p];
g[i] = image.rgb[p + 1];
b[i] = image.rgb[p + 2];
}
return [r, g, b];
}
export function interleave(
r: Float32Array,
g: Float32Array,
b: Float32Array,
width: number,
height: number,
): BaseImage {
const rgb = new Float32Array(width * height * 3);
for (let i = 0, p = 0; i < r.length; i++, p += 3) {
rgb[p] = r[i];
rgb[p + 1] = g[i];
rgb[p + 2] = b[i];
}
return { rgb, width, height };
}
/**
* Robust sigma of one plane, from its own 3x3 high-pass.
*
* The caller's `sigma` is a luma figure, and per-channel noise differs a lot on
* a CFA sensor -- blue is the noisiest -- so filtering all three at the luma
* level over-smooths one channel and under-smooths another. Measuring each
* plane costs three cheap passes at base scale and removes the guesswork.
*/
function planeSigma(plane: Float32Array, width: number, height: number, fallback: number): number {
const smooth = boxBlur(plane, width, height, 1);
const residual = new Float32Array(plane.length);
for (let i = 0; i < plane.length; i++) residual[i] = Math.abs(plane[i] - smooth[i]);
const sorted = residual.sort();
const median = sorted[sorted.length >> 1] ?? 0;
const sigma = (median * 1.4826) / 0.943;
return sigma > 0.5 ? sigma : Math.max(1, fallback);
}
/** Guided filter per channel: cheap, edge-preserving, mildly waxy. */
export function guidedDenoiser(radius = 3, strength = 2.6): BaseDenoiser {
return (image, sigma) => {
const [r, g, b] = deinterleave(image);
const filter = (plane: Float32Array) => {
const s = planeSigma(plane, image.width, image.height, sigma);
return guidedFilter(plane, image.width, image.height, radius, (strength * s) ** 2);
};
return interleave(filter(r), filter(g), filter(b), image.width, image.height);
};
}
/**
* Non-local means, per channel. Slow, and deliberately so: it is the quality
* reference the neural model must beat, not a shipping path.
*/
export function nlmDenoiser(search = 2, patch = 1): BaseDenoiser {
const patchW = 2 * patch + 1;
const patchArea = patchW * patchW;
return (image) => {
const [r, g, b] = deinterleave(image);
const planes = [r, g, b].map(
(plane) => nlmPlane(plane, image.width, image.height, search, patch, patchW, patchArea),
);
return interleave(planes[0], planes[1], planes[2], image.width, image.height);
};
}
function nlmPlane(
plane: Float32Array,
width: number,
height: number,
search: number,
patch: number,
patchW: number,
patchArea: number,
): Float32Array {
const out = new Float32Array(plane.length);
const s = Math.max(1, search | 0);
const clampX = (v: number) => (v < 0 ? 0 : v >= width ? width - 1 : v);
const clampY = (v: number) => (v < 0 ? 0 : v >= height ? height - 1 : v);
let sumSq = 0;
let count = 0;
for (let i = 0; i < plane.length; i += 7) {
sumSq += plane[i] * plane[i];
count++;
}
const h = Math.max(2, Math.sqrt(sumSq / Math.max(1, count)) * 0.18);
const cutoff = 4 * h * h;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const centre = plane[y * width + x];
let acc = 0;
let weight = 0;
for (let dy = -s; dy <= s; dy++) {
for (let dx = -s; dx <= s; dx++) {
if (dx === 0 && dy === 0) continue;
const ny = y + dy;
const nx = x + dx;
if (ny < 0 || ny >= height || nx < 0 || nx >= width) continue;
let dist = 0;
for (let py = -patch; py <= patch; py++) {
const ay = clampY(y + py) * width;
const by = clampY(ny + py) * width;
for (let px = -patch; px <= patch; px++) {
const d = plane[ay + clampX(x + px)] - plane[by + clampX(nx + px)];
dist += d * d;
}
}
dist /= patchArea;
if (dist > cutoff) continue;
const w = Math.exp(-dist / (h * h));
acc += w * plane[ny * width + nx];
weight += w;
}
}
out[y * width + x] = (acc + centre) / (weight + 1);
}
}
return out;
}
+129
View File
@@ -0,0 +1,129 @@
import zlib from 'node:zlib';
import { RAW_PREVIEW_EDGE } from './config.mjs';
let sharpModule = null;
let sharpFailed = false;
/** sharp gives us JPEG encoding and resizing; without it we fall back to PNG. */
export async function loadSharp() {
if (sharpModule) return sharpModule;
if (sharpFailed) return null;
try {
const mod = await import('sharp');
sharpModule = mod.default;
return sharpModule;
} catch {
sharpFailed = true;
return null;
}
}
const CRC_TABLE = (() => {
const table = new Int32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c;
}
return table;
})();
function crc32(buf) {
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type, data) {
const out = Buffer.alloc(8 + data.length + 4);
out.writeUInt32BE(data.length, 0);
out.write(type, 4, 'ascii');
data.copy(out, 8);
out.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, 'ascii'), data])), 8 + data.length);
return out;
}
/** Minimal dependency-free 8-bit RGB PNG encoder (used only when sharp is absent). */
export function encodePng(rgb, width, height) {
const stride = width * 3;
const raw = Buffer.alloc((stride + 1) * height);
for (let y = 0; y < height; y++) {
raw[y * (stride + 1)] = 0;
Buffer.from(rgb.buffer, rgb.byteOffset + y * stride, stride).copy(raw, y * (stride + 1) + 1);
}
const idat = zlib.deflateSync(raw, { level: 6 });
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr[8] = 8;
ihdr[9] = 2;
ihdr[10] = 0;
ihdr[11] = 0;
ihdr[12] = 0;
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
chunk('IDAT', idat),
chunk('IEND', Buffer.alloc(0)),
]);
}
/** Encode an interleaved RGB byte buffer as JPEG (sharp) or PNG (fallback). */
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
const sharp = await loadSharp();
if (!sharp) {
return { data: encodePng(rgb, width, height), ext: 'png', width, height };
}
let img = sharp(Buffer.from(rgb.buffer, rgb.byteOffset, rgb.byteLength), {
raw: { width, height, channels: 3 },
});
if (maxEdge > 0 && Math.max(width, height) > maxEdge) img = img.resize({ width: width >= height ? maxEdge : null, height: height > width ? maxEdge : null, fit: 'inside' });
const data = await img.jpeg({ quality, chromaSubsampling: '4:4:4' }).toBuffer();
const meta = await sharp(data).metadata();
return { data, ext: 'jpg', width: Number(meta.width ?? width), height: Number(meta.height ?? height) };
}
export async function jpegInfo(buffer) {
const sharp = await loadSharp();
if (!sharp) return null;
try {
const meta = await sharp(buffer).metadata();
return { width: Number(meta.width ?? 0), height: Number(meta.height ?? 0), format: meta.format };
} catch {
return null;
}
}
/** Re-encode any decodable image to a normalised JPEG proxy. */
export async function toJpegProxy(buffer, maxEdge = RAW_PREVIEW_EDGE) {
const sharp = await loadSharp();
if (!sharp) return null;
try {
let img = sharp(buffer, { failOn: 'none' }).rotate();
const meta = await img.metadata();
const w = Number(meta.width ?? 0);
const h = Number(meta.height ?? 0);
if (!w || !h) return null;
if (maxEdge > 0 && Math.max(w, h) > maxEdge) img = img.resize({ width: maxEdge, height: maxEdge, fit: 'inside' });
const data = await img.jpeg({ quality: 92, chromaSubsampling: '4:4:4' }).toBuffer();
const outMeta = await sharp(data).metadata();
return { data, width: Number(outMeta.width ?? w), height: Number(outMeta.height ?? h), ext: 'jpg' };
} catch {
return null;
}
}
export async function makeThumb(buffer, edge = 512) {
const sharp = await loadSharp();
if (!sharp) return null;
try {
const data = await sharp(buffer, { failOn: 'none' })
.rotate()
.resize({ width: edge, height: edge, fit: 'inside', withoutEnlargement: true })
.jpeg({ quality: 82 })
.toBuffer();
return data;
} catch {
return null;
}
}
+1453
View File
File diff suppressed because it is too large Load Diff
+120
View File
@@ -0,0 +1,120 @@
import { RAW_IDLE_MS, RAW_WORKERS } from './config.mjs';
import { installLibrawRuntime } from './libraw-runtime.mjs';
let ctorPromise = null;
/** Load the decoder class once; installs the Node worker shim on first use. */
export function loadLibRaw() {
if (!ctorPromise) {
ctorPromise = (async () => {
await installLibrawRuntime();
const mod = await import('libraw-wasm');
const ctor = mod.default?.default ?? mod.default;
if (typeof ctor !== 'function') throw new Error('libraw-wasm did not export a constructor');
return ctor;
})();
}
return ctorPromise;
}
/**
* Bounded pool of decoder instances. Each instance owns one worker thread, so
* this caps how much demosaicing runs at the same time; extra jobs queue.
* Idle instances are disposed after RAW_IDLE_MS to give the memory back.
*/
class LibRawPool {
constructor(size = RAW_WORKERS) {
this.size = Math.max(1, Math.floor(size));
this.free = [];
this.total = 0;
this.waiters = [];
this.closed = false;
}
async acquire() {
const entry = this.free.pop();
if (entry) {
if (entry.timer) clearTimeout(entry.timer);
return entry.lib;
}
if (this.total < this.size) {
this.total++;
try {
const Ctor = await loadLibRaw();
return new Ctor();
} catch (err) {
this.total--;
throw err;
}
}
return new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
}
release(lib, healthy = true) {
if (this.closed || !healthy) {
this.discard(lib);
return;
}
const waiter = this.waiters.shift();
if (waiter) {
waiter.resolve(lib);
return;
}
const entry = { lib, timer: null };
entry.timer = setTimeout(() => {
const idx = this.free.indexOf(entry);
if (idx >= 0) {
this.free.splice(idx, 1);
this.discard(lib);
}
}, RAW_IDLE_MS);
entry.timer.unref?.();
this.free.push(entry);
}
discard(lib) {
try {
lib.dispose();
} catch {
/* worker already gone */
}
this.total = Math.max(0, this.total - 1);
const waiter = this.waiters.shift();
if (waiter) {
this.total++;
loadLibRaw()
.then((Ctor) => new Ctor())
.then(waiter.resolve, waiter.reject);
}
}
/** Run `fn` with a decoder instance; the instance returns to the pool after. */
async use(fn) {
const lib = await this.acquire();
let healthy = true;
try {
return await fn(lib);
} catch (err) {
// A dead worker keeps failing, so recycle it instead of handing it back.
if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false;
throw err;
} finally {
this.release(lib, healthy);
}
}
get stats() {
return {
size: this.size,
busy: this.total - this.free.length,
idle: this.free.length,
queued: this.waiters.length,
};
}
}
export const rawPool = new LibRawPool();
export function poolSupport() {
return { size: rawPool.size, workers: RAW_WORKERS };
}
+34
View File
@@ -0,0 +1,34 @@
/**
* libraw-wasm is browser-first: the wrapper spawns a Web Worker and the
* Emscripten build loads libraw.wasm with fetch(). Node has neither a global
* Worker nor file:// support in fetch, so the decoder runs in a worker_thread
* with a tiny browser-globals shim (see libraw-worker.mjs).
*
* This is a no-op in the browser, where the real Worker already exists.
*/
let installed = false;
export async function installLibrawRuntime() {
if (installed) return;
installed = true;
if (typeof globalThis.Worker === 'function') return;
const { Worker: NodeWorker } = await import('node:worker_threads');
const entry = new URL('./libraw-worker.mjs', import.meta.url);
class BrowserWorker {
constructor() {
this._worker = new NodeWorker(entry);
this._worker.on('message', (data) => this.onmessage?.({ data }));
this._worker.on('error', (err) => this.onerror?.(err));
}
postMessage(message, transfer) {
this._worker.postMessage(message, transfer);
}
terminate() {
return this._worker.terminate();
}
}
globalThis.Worker = BrowserWorker;
}
+31
View File
@@ -0,0 +1,31 @@
import { parentPort } from 'node:worker_threads';
import fs from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
// libraw-wasm targets browsers: emulate the worker globals its build expects.
globalThis.self = globalThis;
globalThis.WorkerGlobalScope = globalThis;
globalThis.postMessage = (msg, transfer) => parentPort.postMessage(msg, transfer);
globalThis.addEventListener = () => {};
// Emscripten loads libraw.wasm through fetch(); Node's fetch rejects file:// URLs.
const realFetch = globalThis.fetch;
globalThis.fetch = async (url, init) => {
const href = typeof url === 'string' ? url : url instanceof URL ? url.href : String(url);
if (href.startsWith('file:')) {
const buf = await fs.readFile(fileURLToPath(href));
return new Response(buf, { status: 200, headers: { 'content-type': 'application/wasm' } });
}
return realFetch(url, init);
};
// Buffer anything that arrives before the module registers `onmessage`.
const queue = [];
parentPort.on('message', (data) => {
if (typeof globalThis.onmessage === 'function') globalThis.onmessage({ data });
else queue.push(data);
});
await import('libraw-wasm/dist/worker.js');
for (const data of queue.splice(0)) globalThis.onmessage({ data });
+129
View File
@@ -0,0 +1,129 @@
import nodemailer from 'nodemailer';
import { kv } from './db.mjs';
import {
SMTP_APP_PASSWORD,
SMTP_FROM,
SMTP_HOST,
SMTP_PORT,
SMTP_SECURE,
SMTP_USER,
} from './config.mjs';
const SETTINGS_KEY = 'mailSettings';
function savedSettings() {
const value = kv.get(SETTINGS_KEY);
return value && typeof value === 'object' ? value : {};
}
/** Never returns the app password; `hasPassword` is enough for the admin UI. */
export function mailStatus() {
const saved = savedSettings();
const user = String(saved.user || SMTP_USER || '').trim();
const appPassword = String(saved.appPassword || SMTP_APP_PASSWORD || '');
const from = String(saved.from || SMTP_FROM || user).trim();
const host = String(saved.host || SMTP_HOST || 'smtp.gmail.com').trim();
const port = Number(saved.port || SMTP_PORT || 465);
const secure = typeof saved.secure === 'boolean' ? saved.secure : SMTP_SECURE;
return {
configured: Boolean(user && appPassword),
source: saved.user || saved.appPassword ? 'admin' : user || appPassword ? 'environment' : 'none',
host,
port,
secure,
user,
from,
hasPassword: Boolean(appPassword),
gmail: host === 'smtp.gmail.com',
};
}
function validateSettings(input) {
const current = savedSettings();
const user = String(input.user ?? current.user ?? SMTP_USER ?? '').trim();
const appPassword = String(
(input.appPassword && String(input.appPassword).trim()) ||
current.appPassword ||
SMTP_APP_PASSWORD ||
'',
).trim();
const from = String(input.from ?? current.from ?? SMTP_FROM ?? user).trim();
const host = String(input.host ?? current.host ?? SMTP_HOST ?? 'smtp.gmail.com').trim();
const port = Number(input.port ?? current.port ?? SMTP_PORT ?? 465);
const secure = typeof input.secure === 'boolean' ? input.secure : port === 465;
if (!/^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(user)) {
throw new Error('Enter the Gmail address that will send notifications');
}
if (!appPassword) throw new Error('Enter the Google app password for that Gmail account');
if (appPassword.length < 8) throw new Error('That app password looks too short');
if (from && !/^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(from)) {
throw new Error('The From address is not a valid email address');
}
if (!host) throw new Error('Enter an SMTP host');
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Enter a valid SMTP port');
}
return { user, appPassword, from: from || user, host, port, secure };
}
export function saveMailSettings(input) {
const next = validateSettings(input ?? {});
kv.set(SETTINGS_KEY, next);
return mailStatus();
}
export async function sendAppMail({ to, subject, text, html }) {
const settings = mailStatus();
if (!settings.configured) {
throw new Error(
'Email is not configured. Add the Gmail address and Google app password in Administration → Quotas.',
);
}
if (!to) throw new Error('A recipient email address is required');
const saved = savedSettings();
const appPassword = saved.appPassword || SMTP_APP_PASSWORD;
const transporter = nodemailer.createTransport({
host: settings.host,
port: settings.port,
secure: settings.secure,
auth: { user: settings.user, pass: appPassword },
connectionTimeout: 12_000,
greetingTimeout: 12_000,
socketTimeout: 20_000,
});
try {
return await transporter.sendMail({
from: settings.from || settings.user,
replyTo: settings.from || settings.user,
to,
subject,
text,
html,
});
} finally {
transporter.close();
}
}
export async function sendTestMail(to) {
return sendAppMail({
to,
subject: 'Luminary email notifications are working',
text:
'This is a test message from Luminary. Your Gmail app password is configured correctly, ' +
'so quota warnings and scheduled storage-prune notices can reach your team.\n\n' +
'— Luminary',
html: `
<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.55;color:#222">
<h2 style="margin:0 0 12px">Luminary email is working</h2>
<p>Your Gmail app password is configured correctly. Quota warnings and scheduled
storage-prune notices can now reach your team.</p>
<p style="color:#777;font-size:12px">— Luminary</p>
</div>
`,
});
}
+454
View File
@@ -0,0 +1,454 @@
import {
QUOTA_BYTES,
QUOTA_TARGET_RATIO,
QUOTA_WARN_RATIO,
PUBLIC_URL,
} from './config.mjs';
import {
allQuotaRows,
deletedPhotoBytes,
getPhoto,
listEvents,
listPhotos,
livePhotoBytesByOwner,
quotaRow,
removeEvent,
removePhoto,
saveQuota,
users,
} from './db.mjs';
import { removeAsset } from './storage.mjs';
import { clearDenoised } from './denoise.mjs';
import { mailStatus, sendAppMail } from './mail.mjs';
const GIB = 1024 ** 3;
const PRUNE_GRACE_MS = 24 * 60 * 60 * 1000;
const WARNING_COOLDOWN_MS = 24 * 60 * 60 * 1000;
const fmtBytes = (bytes) => {
if (bytes >= GIB) return `${(bytes / GIB).toFixed(1)} GB`;
if (bytes >= 1024 ** 2) return `${Math.round(bytes / 1024 ** 2)} MB`;
return `${Math.max(0, Math.round(bytes / 1024))} KB`;
};
const fmtDate = (ms) =>
new Date(ms).toLocaleString(undefined, {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
});
const appUrl = () => PUBLIC_URL || 'http://localhost:8787';
function safePlan(value) {
if (!value) return null;
if (typeof value === 'object') return value;
try {
return JSON.parse(value);
} catch {
return null;
}
}
function limitFor(userId) {
const row = quotaRow(userId);
return Math.max(1, Number(row?.bytes_limit) || QUOTA_BYTES);
}
/** Total bytes represented by an account's photo records, including Trash. */
export function quotaUsage(userId) {
return livePhotoBytesByOwner(userId) + deletedPhotoBytes(userId);
}
export function quotaState(userId) {
const row = quotaRow(userId);
const limit = limitFor(userId);
const used = quotaUsage(userId);
const ratio = limit > 0 ? used / limit : 0;
return {
userId,
limit,
used,
remaining: Math.max(0, limit - used),
ratio,
percent: Math.min(999, Math.round(ratio * 100)),
warn: used >= limit * QUOTA_WARN_RATIO,
over: used > limit,
warnAt: Math.round(limit * QUOTA_WARN_RATIO),
pruneAt: row?.prune_at ?? null,
prunePlan: safePlan(row?.prune_plan),
pruneNotifiedAt: row?.prune_notified_at ?? null,
lastWarningAt: row?.last_quota_email_at ?? null,
};
}
/**
* Oldest events are removed first. If the oldest events are not enough, loose
* photos are added oldest-first. The stored plan is what the warning email
* describes, so a later upload cannot silently get caught up in the prune.
*/
export function prunePlan(userId, limit = limitFor(userId)) {
const photos = listPhotos(userId);
const groups = new Map();
for (const photo of photos) {
const key = photo.eventId || '';
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(photo);
}
const events = listEvents(userId)
.map((event) => {
const members = groups.get(event.id) ?? [];
return {
id: event.id,
name: event.name || 'Untitled event',
createdAt: event.createdAt ?? 0,
photos: members.map((photo) => photo.id),
bytes: members.reduce((sum, photo) => sum + (Number(photo.size) || 0), 0),
};
})
.filter((event) => event.photos.length)
.sort((a, b) => a.createdAt - b.createdAt);
const target = Math.max(0, Math.floor(limit * QUOTA_TARGET_RATIO));
const used = photos.reduce((sum, photo) => sum + (Number(photo.size) || 0), 0);
let projected = used;
const chosenEvents = [];
const chosenPhotoIds = new Set();
for (const event of events) {
if (projected <= target) break;
chosenEvents.push(event);
event.photos.forEach((id) => chosenPhotoIds.add(id));
projected -= event.bytes;
}
const loosePhotos = [];
if (projected > target) {
const remaining = photos
.filter((photo) => !chosenPhotoIds.has(photo.id))
.filter((photo) => !events.some((event) => event.id === photo.eventId))
.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
for (const photo of remaining) {
if (projected <= target) break;
const bytes = Number(photo.size) || 0;
loosePhotos.push({ id: photo.id, name: photo.name || photo.id, bytes });
projected -= bytes;
}
}
return {
targetBytes: target,
usedBytes: used,
projectedBytes: Math.max(0, projected),
freedBytes: Math.max(0, used - Math.max(0, projected)),
events: chosenEvents,
photos: loosePhotos,
};
}
function planText(plan) {
const lines = [];
for (const event of plan.events) {
lines.push(`• ${event.name} — ${event.photos.length} photo${event.photos.length === 1 ? '' : 's'}, ${fmtBytes(event.bytes)}`);
}
if (plan.photos.length) {
lines.push(
`• ${plan.photos.length} loose photo${plan.photos.length === 1 ? '' : 's'} — ${fmtBytes(plan.photos.reduce((sum, photo) => sum + photo.bytes, 0))}`,
);
}
return lines.join('\n');
}
function planHtml(plan) {
const rows = plan.events
.map(
(event) =>
`<li><strong>${escapeHtml(event.name)}</strong> — ${event.photos.length} photo${event.photos.length === 1 ? '' : 's'}, ${fmtBytes(event.bytes)}</li>`,
)
.join('');
const loose = plan.photos.length
? `<li>${plan.photos.length} unassigned photo${plan.photos.length === 1 ? '' : 's'} — ${fmtBytes(plan.photos.reduce((sum, photo) => sum + photo.bytes, 0))}</li>`
: '';
return `<ul>${rows}${loose}</ul>`;
}
function escapeHtml(value) {
return String(value)
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
}
async function pruneWarningEmail(user, state, plan, pruneAt) {
const when = fmtDate(pruneAt);
const subject = `Luminary: ${fmtBytes(plan.freedBytes)} will be pruned in 24 hours`;
const text = [
`Hi ${user.name || user.email},`,
'',
`Your Luminary storage is ${state.percent}% full (${fmtBytes(state.used)} of ${fmtBytes(state.limit)}).`,
`An administrator scheduled a storage cleanup for ${when} — about 24 hours from now.`,
'',
'Unless you free space before then, Luminary will permanently remove the oldest content listed below:',
planText(plan) || '• No individual items were identified.',
'',
`This should free about ${fmtBytes(plan.freedBytes)} and leave your library around ${fmtBytes(plan.projectedBytes)}.`,
'',
`Review your library now: ${appUrl()}`,
'',
'Deleting photos or emptying Trash before the scheduled time will cancel or reduce the cleanup.',
'— Luminary',
].join('\n');
const html = `
<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.55;color:#222;max-width:640px">
<h2 style="margin:0 0 12px">Storage cleanup scheduled</h2>
<p>Hi ${escapeHtml(user.name || user.email)},</p>
<p>Your Luminary storage is <strong>${state.percent}% full</strong>
(${fmtBytes(state.used)} of ${fmtBytes(state.limit)}).</p>
<p style="padding:12px 14px;background:#fff4dd;border-left:4px solid #d99a20">
An administrator scheduled a storage cleanup for
<strong>${escapeHtml(when)}</strong> — about 24 hours from now.
</p>
<p>Unless you free space before then, Luminary will permanently remove the oldest content
listed below:</p>
${planHtml(plan) || '<p>No individual items were identified.</p>'}
<p>This should free about <strong>${fmtBytes(plan.freedBytes)}</strong> and leave your
library around ${fmtBytes(plan.projectedBytes)}.</p>
<p><a href="${escapeHtml(appUrl())}" style="display:inline-block;padding:9px 16px;background:#3d7eff;color:#fff;text-decoration:none;border-radius:6px">Review your library</a></p>
<p style="color:#777;font-size:12px">Deleting photos or emptying Trash before the scheduled
time will cancel or reduce the cleanup.<br>— Luminary</p>
</div>
`;
await sendAppMail({ to: user.email, subject, text, html });
}
async function quotaWarningEmail(user, state) {
const subject = `Luminary: your storage is ${state.percent}% full`;
const text = [
`Hi ${user.name || user.email},`,
'',
`You are nearing your Luminary storage quota: ${fmtBytes(state.used)} used of ${fmtBytes(state.limit)} (${state.percent}%).`,
'',
'Free some space by deleting photos you no longer need or emptying Trash. If the quota is exceeded, an administrator can schedule a 24-hour storage cleanup.',
'',
`Open Luminary: ${appUrl()}`,
'',
'— Luminary',
].join('\n');
const html = `
<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.55;color:#222;max-width:640px">
<h2 style="margin:0 0 12px">You are nearing your storage quota</h2>
<p>Hi ${escapeHtml(user.name || user.email)},</p>
<p>You have used <strong>${fmtBytes(state.used)}</strong> of your
<strong>${fmtBytes(state.limit)}</strong> Luminary quota (${state.percent}%).</p>
<p>Delete photos you no longer need or empty Trash to free space. If the quota is exceeded,
an administrator can schedule a 24-hour storage cleanup.</p>
<p><a href="${escapeHtml(appUrl())}" style="display:inline-block;padding:9px 16px;background:#3d7eff;color:#fff;text-decoration:none;border-radius:6px">Open Luminary</a></p>
<p style="color:#777;font-size:12px">— Luminary</p>
</div>
`;
await sendAppMail({ to: user.email, subject, text, html });
}
export async function schedulePrune(userId) {
const user = users.byId(userId);
if (!user) throw new Error('No such account');
if (!mailStatus().configured) {
throw new Error(
'Email notifications must be configured before a prune can be scheduled, so the 24-hour warning can reach the user.',
);
}
const state = quotaState(userId);
const plan = prunePlan(userId, state.limit);
if (plan.freedBytes <= 0) {
throw new Error('There is nothing old enough to prune. The account is already below the cleanup target.');
}
if (plan.projectedBytes > state.limit) {
throw new Error(
'The oldest content cannot bring this account under its quota. Raise the limit or remove large events manually.',
);
}
const pruneAt = Date.now() + PRUNE_GRACE_MS;
await pruneWarningEmail(user, state, plan, pruneAt);
saveQuota(userId, {
pruneAt,
prunePlan: plan,
pruneNotifiedAt: Date.now(),
});
return { pruneAt, plan, state: quotaState(userId), warningSent: true };
}
export function cancelPrune(userId) {
saveQuota(userId, { pruneAt: null, prunePlan: null, pruneNotifiedAt: null });
return quotaState(userId);
}
export async function warnUser(userId) {
const user = users.byId(userId);
if (!user) throw new Error('No such account');
const state = quotaState(userId);
if (!state.warn && !state.over) throw new Error('This account is below its warning threshold');
await quotaWarningEmail(user, state);
saveQuota(userId, { lastQuotaEmailAt: Date.now() });
return state;
}
export function setUserQuota(userId, bytes) {
if (!users.byId(userId)) throw new Error('No such account');
const limit = Number(bytes);
const min = GIB;
const max = 10_000 * GIB;
if (!Number.isFinite(limit) || limit < min || limit > max) {
throw new Error('Choose a quota between 1 GB and 10 TB');
}
saveQuota(userId, { bytesLimit: Math.round(limit) });
return quotaState(userId);
}
export function quotasForAdmin() {
return users.list().map((user) => {
const state = quotaState(user.id);
return {
...state,
user,
plan: state.prunePlan ?? prunePlan(user.id, state.limit),
};
});
}
export async function sendTestNotification(to) {
if (!mailStatus().configured) {
throw new Error('Add the Gmail address and app password first');
}
await sendAppMail({
to,
subject: 'Luminary email notifications are working',
text: 'This is a test message from Luminary. Quota warnings and prune notices are configured correctly.',
html: '<p>This is a test message from Luminary. Quota warnings and prune notices are configured correctly.</p>',
});
}
async function executePlan(userId, plan) {
let removedPhotos = 0;
let freedBytes = 0;
const eventIds = new Set();
for (const event of plan.events ?? []) eventIds.add(event.id);
for (const event of plan.events ?? []) {
for (const photoId of event.photos ?? []) {
const photo = getPhoto(photoId);
if (!photo) continue;
freedBytes += Number(photo.size) || 0;
removePhoto(photoId);
clearDenoised(photoId);
await removeAsset(photoId);
removedPhotos += 1;
}
}
for (const entry of plan.photos ?? []) {
const photo = getPhoto(entry.id);
if (!photo) continue;
freedBytes += Number(photo.size) || 0;
removePhoto(entry.id);
clearDenoised(entry.id);
await removeAsset(entry.id);
removedPhotos += 1;
}
for (const eventId of eventIds) {
if (!listPhotos(userId).some((photo) => photo.eventId === eventId)) removeEvent(eventId);
}
return { removedPhotos, freedBytes };
}
async function pruneDueAccounts() {
const now = Date.now();
for (const row of allQuotaRows()) {
if (!row.prune_at || Number(row.prune_at) > now) continue;
const user = users.byId(row.user_id);
const plan = safePlan(row.prune_plan);
if (!user || !plan) {
saveQuota(row.user_id, { pruneAt: null, prunePlan: null, pruneNotifiedAt: null });
continue;
}
try {
const before = quotaUsage(row.user_id);
const result = await executePlan(row.user_id, plan);
const after = quotaUsage(row.user_id);
saveQuota(row.user_id, {
pruneAt: null,
prunePlan: null,
pruneNotifiedAt: null,
});
const state = quotaState(row.user_id);
await sendAppMail({
to: user.email,
subject: 'Luminary: your scheduled storage cleanup is complete',
text: [
`Hi ${user.name || user.email},`,
'',
`The scheduled Luminary cleanup removed ${result.removedPhotos} photo${result.removedPhotos === 1 ? '' : 's'} and freed ${fmtBytes(before - after)}.`,
`Your library is now ${fmtBytes(after)} of ${fmtBytes(state.limit)} (${state.percent}%).`,
'',
`Open Luminary: ${appUrl()}`,
'',
'— Luminary',
].join('\n'),
html: `
<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.55;color:#222;max-width:640px">
<h2 style="margin:0 0 12px">Scheduled cleanup complete</h2>
<p>Hi ${escapeHtml(user.name || user.email)},</p>
<p>The scheduled Luminary cleanup removed
<strong>${result.removedPhotos} photo${result.removedPhotos === 1 ? '' : 's'}</strong>
and freed <strong>${fmtBytes(before - after)}</strong>.</p>
<p>Your library is now ${fmtBytes(after)} of ${fmtBytes(state.limit)} (${state.percent}%).</p>
<p style="color:#777;font-size:12px">— Luminary</p>
</div>
`,
}).catch((err) => console.error(`[luminary] prune email to ${user.email} failed: ${err.message}`));
} catch (err) {
console.error(`[luminary] prune for ${user.email} failed: ${err.message}`);
saveQuota(row.user_id, { pruneAt: null, prunePlan: null, pruneNotifiedAt: null });
}
}
}
async function sendQuotaWarnings() {
if (!mailStatus().configured) return;
const now = Date.now();
for (const user of users.list()) {
if (user.disabled) continue;
const row = quotaRow(user.id);
if (row?.prune_at) continue;
const state = quotaState(user.id);
if (!state.warn) continue;
if (row?.last_quota_email_at && now - Number(row.last_quota_email_at) < WARNING_COOLDOWN_MS) {
continue;
}
try {
await quotaWarningEmail(user, state);
saveQuota(user.id, { lastQuotaEmailAt: now });
} catch (err) {
console.error(`[luminary] quota warning to ${user.email} failed: ${err.message}`);
}
}
}
export function startQuotaWorker() {
const tick = () => {
void pruneDueAccounts().catch((err) =>
console.error(`[luminary] quota worker: ${err.message}`),
);
void sendQuotaWarnings().catch((err) =>
console.error(`[luminary] quota warning worker: ${err.message}`),
);
};
const timer = setInterval(tick, 5 * 60 * 1000);
timer.unref?.();
setTimeout(tick, 7000).unref?.();
}
+214
View File
@@ -0,0 +1,214 @@
import { RAW_PREVIEW_EDGE } from './config.mjs';
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs';
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
/** Every raw container the pipeline will attempt, grouped by vendor family. */
export const RAW_EXTENSIONS = new Set([
// Canon
'cr2', 'cr3', 'crw',
// Nikon
'nef', 'nrw',
// Sony
'arw', 'srf', 'sr2',
// Olympus / OM System
'orf',
// Panasonic / Leica
'rw2', 'raw', 'rwl',
// Fujifilm
'raf',
// Pentax / Ricoh
'pef', 'dng',
// Samsung, Hasselblad, Leaf, Phase One, Sigma, Epson, Kodak, Minolta
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', 'sraw',
]);
export function isRawName(name = '') {
const ext = name.split('.').pop()?.toLowerCase() ?? '';
return RAW_EXTENSIONS.has(ext);
}
/** True when the buffer starts with a container signature LibRaw can open. */
export function looksLikeRaw(buffer) {
if (!buffer || buffer.length < 64) return false;
const hex4 = buffer.subarray(0, 4).toString('hex');
const ascii = buffer.subarray(0, 16).toString('latin1');
if (hex4 === '49492a00' || hex4 === '4d4d002a') return true; // TIFF family
if (hex4 === '4949524f' || hex4 === '4d4d4f52') return true; // ORF
if (hex4 === '49495500') return true; // RW2
if (hex4 === '49494949') return true; // Phase One IIQ
if (ascii.startsWith('FUJIFILMCCD-RAW')) return true; // RAF
if (ascii.startsWith('FOVb')) return true; // X3F
if (buffer.subarray(4, 8).toString('latin1') === 'ftyp') return true; // CR3
return false;
}
let engineState = 'unloaded';
export async function rawEngine() {
if (engineState === 'unloaded') {
try {
await loadLibRaw();
engineState = 'ready';
} catch {
engineState = 'missing';
}
}
return engineState;
}
const DECODE_SETTINGS = {
outputBps: 8,
useCameraWb: true,
outputColor: 1, // sRGB
userQual: 3,
highlight: 0,
noAutoBright: false,
// Use the orientation stored in the raw container: phone and DSLR files often
// record the shot rotated (EXIF 6/8), and demosaicing without it produces a
// sideways proxy that no later step can fix without losing the original axes.
userFlip: -1,
useFujiRotate: -1,
};
/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */
function toRgb(img) {
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
const width = Number(img.width);
const height = Number(img.height);
const colors = Number(img.colors ?? 3);
const bits = Number(img.bits ?? 8);
const src = img.data;
const pixelCount = width * height;
const needed = pixelCount * colors * (bits > 8 ? 2 : 1);
if (src.length < needed) {
throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`);
}
const rgb = Buffer.alloc(pixelCount * 3);
if (bits > 8) {
const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2));
for (let i = 0; i < pixelCount; i++) {
const s = i * colors;
rgb[i * 3] = view[s] >> 8;
rgb[i * 3 + 1] = view[s + 1] >> 8;
rgb[i * 3 + 2] = view[s + 2] >> 8;
}
} else {
for (let i = 0; i < pixelCount; i++) {
const s = i * colors;
rgb[i * 3] = src[s];
rgb[i * 3 + 1] = src[s + 1];
rgb[i * 3 + 2] = src[s + 2];
}
}
return { rgb, width, height };
}
/**
* Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
* the pixels come from `imageData()`, which rejects when the camera is unsupported.
*/
async function demosaic(buffer) {
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
return rawPool.use(async (lib) => {
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it
// a copy so the caller's bytes survive for the embedded-preview fallback.
await lib.open(Buffer.from(buffer), DECODE_SETTINGS);
return toRgb(await lib.imageData());
});
}
const SOI = Buffer.from([0xff, 0xd8, 0xff]);
const EOI = Buffer.from([0xff, 0xd9]);
/** Pull the largest embedded JPEG straight out of a raw container. */
export function extractEmbeddedJpeg(buffer) {
let best = null;
let from = 0;
while (from < buffer.length - 3) {
const start = buffer.indexOf(SOI, from);
if (start < 0) break;
const end = buffer.indexOf(EOI, start + 3);
if (end < 0) break;
const length = end + 2 - start;
if (length > 4096 && (!best || length > best.length)) best = buffer.subarray(start, end + 2);
from = end + 2;
}
return best;
}
/** Camera preview, preferably the one LibRaw knows the offset and length of. */
async function embeddedPreview(buffer) {
if ((await rawEngine()) === 'ready') {
try {
const thumb = await rawPool.use(async (lib) => {
await lib.open(Buffer.from(buffer), { useCameraWb: true });
return lib.thumbnailData();
});
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
return Buffer.from(thumb.data);
}
} catch {
/* fall through to the byte scan */
}
}
return extractEmbeddedJpeg(buffer);
}
/**
* Convert a raw file into an editable JPEG. LibRaw demosaics where possible and
* falls back to the camera's own embedded preview when it cannot.
*/
export async function decodeRaw(buffer) {
let librawError = null;
if (looksLikeRaw(buffer)) {
try {
const { rgb, width, height } = await demosaic(buffer);
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
return {
jpeg: encoded.data,
width: encoded.width,
height: encoded.height,
engine: 'libraw',
ext: encoded.ext,
};
} catch (err) {
librawError = err instanceof Error ? err.message : String(err);
}
} else {
librawError = 'not a recognised raw container';
}
const embedded = await embeddedPreview(buffer);
if (embedded) {
const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE);
if (proxy) {
const size = await jpegInfo(proxy.data);
return {
jpeg: proxy.data,
width: size?.width || proxy.width,
height: size?.height || proxy.height,
engine: 'embedded',
ext: proxy.ext,
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
};
}
return { jpeg: embedded, width: 0, height: 0, engine: 'embedded', ext: 'jpg', note: librawError ?? undefined };
}
throw new Error(
`Could not decode this raw file. ${librawError ? `LibRaw said: ${librawError}.` : 'LibRaw is not installed.'}`,
);
}
export async function rawSupport() {
const engine = await rawEngine();
const sharp = await loadSharp();
return {
libraw: engine === 'ready',
sharp: Boolean(sharp),
workers: rawPool.size,
busy: rawPool.stats.busy,
formats: [...RAW_EXTENSIONS].sort(),
};
}
+325
View File
@@ -0,0 +1,325 @@
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import { DATA_DIR } from './config.mjs';
import { kv } from './db.mjs';
/**
* Where image files live. The database always stays in DATA_DIR; only the
* originals/previews/thumbs folders move when an admin picks another location.
*/
const SETTINGS_KEY = 'storageRoot';
const SUBDIRS = ['originals', 'previews', 'thumbs', 'proofs', 'proofThumbs', 'denoised'];
const SAFE = /^[A-Za-z0-9_-]{1,80}$/;
let cachedRoot = null;
export function defaultRoot() {
return DATA_DIR;
}
export function storageRoot() {
if (cachedRoot) return cachedRoot;
const saved = kv.get(SETTINGS_KEY);
cachedRoot = typeof saved === 'string' && saved.trim() ? path.resolve(saved) : DATA_DIR;
return cachedRoot;
}
export function isCustomRoot() {
return path.resolve(storageRoot()) !== path.resolve(DATA_DIR);
}
export function dirs(root = storageRoot()) {
return {
originals: path.join(root, 'originals'),
previews: path.join(root, 'previews'),
thumbs: path.join(root, 'thumbs'),
denoised: path.join(root, 'denoised'),
proofs: path.join(root, 'proofs'),
proofThumbs: path.join(root, 'proofThumbs'),
};
}
export function ensureDirs(root = storageRoot()) {
for (const dir of Object.values(dirs(root))) fs.mkdirSync(dir, { recursive: true });
}
ensureDirs();
function safeId(id) {
if (!SAFE.test(id)) throw new Error('Invalid asset id');
return id;
}
/**
* Reads are lookups: a malformed id simply has no file, so it must not throw a
* 500 out of the request handler. Writers keep the strict check.
*/
function lookupId(id) {
return typeof id === 'string' && SAFE.test(id) ? id : null;
}
function listFiles(dir) {
try {
return fs.readdirSync(dir);
} catch {
return [];
}
}
/** Original files keep their real extension so a raw can be recovered later. */
function originalPath(id, ext = 'bin') {
ensureDirs();
return path.join(
storageRoot(),
'originals',
`${safeId(id)}.${ext.replace(/[^a-z0-9]/gi, '') || 'bin'}`,
);
}
export async function writeOriginal(id, ext, data) {
const target = originalPath(id, ext);
await fsp.writeFile(target, data);
return target;
}
export function findOriginal(id) {
const safe = lookupId(id);
if (!safe) return null;
const { originals } = dirs();
const prefix = `${safe}.`;
for (const name of listFiles(originals)) {
if (name.startsWith(prefix)) return path.join(originals, name);
}
return null;
}
export async function writePreview(id, data, ext = 'jpg') {
ensureDirs();
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.${ext}`);
await fsp.writeFile(target, data);
return target;
}
export function findPreview(id) {
const safe = lookupId(id);
if (!safe) return null;
const { previews } = dirs();
for (const ext of ['jpg', 'png']) {
const p = path.join(previews, `${safe}.${ext}`);
if (fs.existsSync(p)) return p;
}
return null;
}
/**
* Denoised proxies, keyed by the hash of the parameters that produced them, so
* switching Amount back to a previous value reuses the file instead of spending
* another few seconds of CPU on an identical result.
*/
export function denoisedPath(id, key) {
ensureDirs();
const safeKey = String(key).replace(/[^a-z0-9]/gi, '');
return path.join(storageRoot(), 'denoised', `${safeId(id)}.${safeKey}.jpg`);
}
/** With no key, the most recently written result wins. */
export function findDenoised(id, key) {
const safe = lookupId(id);
if (!safe) return null;
const dir = path.join(storageRoot(), 'denoised');
if (key) {
const exact = denoisedPath(safe, key);
return fs.existsSync(exact) ? exact : null;
}
const names = listFiles(dir).filter((name) => name.startsWith(`${safe}.`));
if (names.length === 0) return null;
names.sort(
(a, b) =>
fs.statSync(path.join(dir, b)).mtimeMs - fs.statSync(path.join(dir, a)).mtimeMs,
);
return path.join(dir, names[0]);
}
/** Remove every denoised render for a photo, sparing `keepKey` if given. */
export function removeDenoised(id, keepKey) {
const safe = lookupId(id);
if (!safe) return 0;
const dir = path.join(storageRoot(), 'denoised');
const key = keepKey ? String(keepKey).replace(/[^a-z0-9]/gi, '') : null;
const keep = key ? `${safe}.${key}.jpg` : null;
let removed = 0;
for (const name of listFiles(dir)) {
if (!name.startsWith(`${safe}.`) || name === keep) continue;
fs.rmSync(path.join(dir, name), { force: true });
removed += 1;
}
return removed;
}
export async function writeThumb(id, data) {
ensureDirs();
const target = path.join(storageRoot(), 'thumbs', `${safeId(id)}.jpg`);
await fsp.writeFile(target, data);
return target;
}
export function findThumb(id) {
const safe = lookupId(id);
if (!safe) return null;
const p = path.join(storageRoot(), 'thumbs', `${safe}.jpg`);
return fs.existsSync(p) ? p : null;
}
/** Rendered proof used by client galleries; separate from the editable proxy. */
export async function writeProof(id, data) {
ensureDirs();
const target = path.join(storageRoot(), 'proofs', `${safeId(id)}.jpg`);
await fsp.writeFile(target, data);
return target;
}
export function findProof(id) {
const safe = lookupId(id);
if (!safe) return null;
const p = path.join(storageRoot(), 'proofs', `${safe}.jpg`);
return fs.existsSync(p) ? p : null;
}
export async function writeProofThumb(id, data) {
ensureDirs();
const target = path.join(storageRoot(), 'proofThumbs', `${safeId(id)}.jpg`);
await fsp.writeFile(target, data);
return target;
}
export function findProofThumb(id) {
const safe = lookupId(id);
if (!safe) return null;
const p = path.join(storageRoot(), 'proofThumbs', `${safe}.jpg`);
return fs.existsSync(p) ? p : null;
}
export async function removeAsset(id) {
const files = [
findOriginal(id),
findPreview(id),
findThumb(id),
findProof(id),
findProofThumb(id),
];
await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve())));
}
export function storageBytes(root = storageRoot()) {
let total = 0;
for (const dir of Object.values(dirs(root))) {
for (const name of listFiles(dir)) {
try {
total += fs.statSync(path.join(dir, name)).size;
} catch {
/* file vanished mid-scan */
}
}
}
return total;
}
/**
* Validates a destination and proves it is writable before anything moves.
* Returns the resolved absolute path.
*/
export async function checkRoot(input) {
if (typeof input !== 'string' || !input.trim()) throw new Error('Enter a folder path');
const raw = input.trim();
if (raw.includes('\0')) throw new Error('That path is not valid');
if (!path.isAbsolute(raw)) throw new Error('Use an absolute path, for example /srv/luminary-photos');
const root = path.resolve(raw);
if (root === path.parse(root).root) throw new Error('Pick a folder below the filesystem root');
const existing = await fsp.stat(root).catch(() => null);
if (existing && !existing.isDirectory()) throw new Error('That path is a file, not a folder');
await fsp.mkdir(root, { recursive: true });
const probe = path.join(root, `.luminary-write-test-${process.pid}-${Date.now()}`);
try {
await fsp.writeFile(probe, 'ok');
await fsp.rm(probe, { force: true });
} catch {
throw new Error('That folder is not writable by the Luminary server');
}
return root;
}
async function moveTree(from, to, moved) {
let files = 0;
let bytes = 0;
await fsp.mkdir(to, { recursive: true });
for (const name of listFiles(from)) {
const src = path.join(from, name);
const dst = path.join(to, name);
const stat = await fsp.stat(src).catch(() => null);
if (!stat || !stat.isFile()) continue;
try {
await fsp.rename(src, dst);
} catch {
// Different filesystem (EXDEV) or an existing target: copy over, then drop.
await fsp.copyFile(src, dst);
await fsp.rm(src, { force: true });
}
moved.push([src, dst]);
files += 1;
bytes += stat.size;
}
return { files, bytes };
}
/** Puts files back where they came from if a relocation fails partway. */
async function rollback(moved) {
for (const [src, dst] of [...moved].reverse()) {
try {
await fsp.rename(dst, src);
} catch {
try {
await fsp.copyFile(dst, src);
await fsp.rm(dst, { force: true });
} catch {
/* leave the copy in place rather than lose the file */
}
}
}
}
/**
* Points storage at a new folder, moving every existing image across so the
* library keeps working. Returns what moved and what was skipped.
*/
export async function setStorageRoot(input) {
const next = await checkRoot(input);
const current = storageRoot();
if (path.resolve(next) === path.resolve(current)) {
return { root: current, previous: current, files: 0, bytes: 0, moved: false };
}
const from = dirs(current);
const to = dirs(next);
const moved = [];
let files = 0;
let bytes = 0;
try {
for (const kind of SUBDIRS) {
const result = await moveTree(from[kind], to[kind], moved);
files += result.files;
bytes += result.bytes;
}
} catch {
await rollback(moved);
throw new Error('Could not move the existing images; the storage folder was left unchanged');
}
kv.set(SETTINGS_KEY, next);
cachedRoot = next;
ensureDirs();
return { root: next, previous: current, files, bytes, moved: true };
}
+123
View File
@@ -0,0 +1,123 @@
/**
* Minimal stored-ZIP writer for server-side gallery downloads. JPEGs are
* already compressed, so entries are stored rather than deflated.
*/
const MAX_ENTRIES = 0xffff;
const MAX_SIZE = 0xffffffff;
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[i] = c >>> 0;
}
return table;
})();
function crc32(bytes) {
let c = 0xffffffff;
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function dosStamp(date) {
const year = Math.min(2107, Math.max(1980, date.getFullYear()));
const time = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
const day = ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
return { time, day };
}
function uniqueName(name, used) {
const clean = String(name || 'photo.jpg')
.replace(/[\\/]+/g, '-')
.replace(/[\u0000-\u001f]/g, '')
.trim() || 'photo.jpg';
if (!used.has(clean.toLowerCase())) {
used.add(clean.toLowerCase());
return clean;
}
const dot = clean.lastIndexOf('.');
const stem = dot > 0 ? clean.slice(0, dot) : clean;
const ext = dot > 0 ? clean.slice(dot) : '';
let n = 2;
while (used.has(`${stem} (${n})${ext}`.toLowerCase())) n += 1;
const result = `${stem} (${n})${ext}`;
used.add(result.toLowerCase());
return result;
}
export function createZip(entries, date = new Date()) {
if (!entries.length) throw new Error('Nothing to archive');
if (entries.length > MAX_ENTRIES) throw new Error('Too many files for one ZIP archive');
const { time, day } = dosStamp(date);
const locals = [];
const central = [];
const used = new Set();
let offset = 0;
for (const entry of entries) {
if (!Buffer.isBuffer(entry.data)) throw new Error('ZIP entries must contain buffers');
const name = Buffer.from(uniqueName(entry.name, used), 'utf8');
const data = entry.data;
if (data.length > MAX_SIZE) throw new Error(`${entry.name} is too large for a ZIP archive`);
const crc = crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6);
local.writeUInt16LE(0, 8);
local.writeUInt16LE(time, 10);
local.writeUInt16LE(day, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(data.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(name.length, 26);
local.writeUInt16LE(0, 28);
locals.push(local, name, data);
central.push({ name, crc, size: data.length, offset });
offset += local.length + name.length + data.length;
}
const centralStart = offset;
let centralSize = 0;
for (const file of central) {
const record = Buffer.alloc(46);
record.writeUInt32LE(0x02014b50, 0);
record.writeUInt16LE(20, 4);
record.writeUInt16LE(20, 6);
record.writeUInt16LE(0x0800, 8);
record.writeUInt16LE(0, 10);
record.writeUInt16LE(time, 12);
record.writeUInt16LE(day, 14);
record.writeUInt32LE(file.crc, 16);
record.writeUInt32LE(file.size, 20);
record.writeUInt32LE(file.size, 24);
record.writeUInt16LE(file.name.length, 28);
record.writeUInt16LE(0, 30);
record.writeUInt16LE(0, 32);
record.writeUInt16LE(0, 34);
record.writeUInt16LE(0, 36);
record.writeUInt32LE(0, 38);
record.writeUInt32LE(file.offset, 42);
locals.push(record, file.name);
centralSize += record.length + file.name.length;
}
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(0, 4);
end.writeUInt16LE(0, 6);
end.writeUInt16LE(central.length, 8);
end.writeUInt16LE(central.length, 10);
end.writeUInt32LE(centralSize, 12);
end.writeUInt32LE(centralStart, 16);
end.writeUInt16LE(0, 20);
locals.push(end);
return Buffer.concat(locals);
}
+2187
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+203
View File
@@ -0,0 +1,203 @@
import { useEffect, useState } from 'react';
import type { Health, SessionUser } from '../lib/api';
interface Props {
health: Health | null;
user: SessionUser | null;
busy: boolean;
note: string | null;
error: string | null;
onLogin: (email: string, password: string) => void;
onRegister: (input: { email: string; password: string; name: string; invite: string }) => void;
onLogout: () => void;
onSync: () => void;
onAdmin: () => void;
onClose: () => void;
}
function fmtBytes(bytes: number) {
if (bytes > 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
if (bytes > 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)} MB`;
return `${Math.round(bytes / 1024)} KB`;
}
export default function CloudPanel({
health,
user,
busy,
note,
error,
onLogin,
onRegister,
onLogout,
onSync,
onAdmin,
onClose,
}: Props) {
const [mode, setMode] = useState<'signin' | 'signup'>('signin');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [invite, setInvite] = useState('');
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const submit = () => {
if (busy) return;
if (mode === 'signin') onLogin(email.trim(), password);
else onRegister({ email: email.trim(), password, name: name.trim(), invite: invite.trim() });
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal cloud-modal">
<header className="modal-head">
<h2>Team server</h2>
<button className="icon-btn" onClick={onClose}>
✕
</button>
</header>
<div className="modal-body">
{!health ? (
<div className="cloud-offline">
<strong>No server detected</strong>
<p className="muted small">
The library is running fully in this browser. To share photos with the team, start the
server and reload:
</p>
<pre className="code-block">npm run server</pre>
<p className="muted small">
Originals, edits and ratings are then stored on disk under <code>server/data</code>.
</p>
</div>
) : user ? (
<div className="cloud-account">
<div className="cloud-hero">
<div className="cloud-avatar">{(user.name || user.email).slice(0, 1).toUpperCase()}</div>
<div>
<strong>{user.name || user.email}</strong>
<div className="muted small">
{user.email} · {user.role}
</div>
</div>
</div>
<dl className="cloud-stats">
<div>
<dt>Photos on server</dt>
<dd>{health.photos}</dd>
</div>
<div>
<dt>Storage used</dt>
<dd>{fmtBytes(health.bytes)}</dd>
</div>
<div>
<dt>Raw engine</dt>
<dd>{health.raw.libraw ? 'LibRaw demosaic' : 'Embedded previews'}</dd>
</div>
<div>
<dt>Server version</dt>
<dd>{health.version}</dd>
</div>
</dl>
<div className="btn-row">
<button className="btn primary" onClick={onSync} disabled={busy}>
{busy ? 'Syncing…' : 'Sync library'}
</button>
<button className="btn ghost" onClick={onLogout} disabled={busy}>
Sign out
</button>
{user.role === 'admin' && (
<button className="btn ghost" onClick={onAdmin} disabled={busy}>
Administration
</button>
)}
</div>
{note && <div className="banner ok">{note}</div>}
</div>
) : (
<>
<div className="tabs">
<button className={`tab ${mode === 'signin' ? 'on' : ''}`} onClick={() => setMode('signin')}>
Sign in
</button>
<button className={`tab ${mode === 'signup' ? 'on' : ''}`} onClick={() => setMode('signup')}>
{health.needsSetup ? 'Create admin' : 'Join team'}
</button>
</div>
<label className="field">
<span>Email</span>
<input
type="email"
autoComplete="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && submit()}
/>
</label>
{mode === 'signup' && (
<label className="field">
<span>Display name</span>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="Optional" />
</label>
)}
<label className="field">
<span>Password</span>
<input
type="password"
autoComplete={mode === 'signin' ? 'current-password' : 'new-password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && submit()}
/>
</label>
{mode === 'signup' && !health.needsSetup && (
<label className="field">
<span>Invite link or code</span>
<input
value={invite}
onChange={(e) => setInvite(e.target.value)}
placeholder="Paste the link from your admin"
/>
</label>
)}
{mode === 'signup' && health.needsSetup && (
<p className="muted small">
The first account becomes the team admin. After that, create single-use invite links under
Administration → Invites.
</p>
)}
<button className="btn primary wide" onClick={submit} disabled={busy || !email || !password}>
{busy ? 'Working…' : mode === 'signin' ? 'Sign in' : 'Create account'}
</button>
</>
)}
{error && <div className="banner error">{error}</div>}
{health && (
<p className="muted small cloud-foot">
Server sharing the folder <code>{health.storage?.root ?? 'server/data'}</code> · raw formats:{' '}
{health.raw.formats.length} · {health.raw.sharp ? 'JPEG encoder ready' : 'PNG fallback'}
</p>
)}
</div>
</div>
</div>
);
}
+183
View File
@@ -0,0 +1,183 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { EventRecord, PhotoRecord } from '../types';
export interface PaletteAction {
id: string;
label: string;
hint?: string;
run: () => void;
}
interface Props {
events: EventRecord[];
photos: PhotoRecord[];
actions: PaletteAction[];
onOpenEvent: (id: string) => void;
onOpenPhoto: (id: string) => void;
onClose: () => void;
}
interface Result {
key: string;
label: string;
hint: string;
kind: 'event' | 'photo' | 'action';
thumb?: string;
run: () => void;
}
export default function CommandPalette({
events,
photos,
actions,
onOpenEvent,
onOpenPhoto,
onClose,
}: Props) {
const [query, setQuery] = useState('');
const [active, setActive] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
useEffect(() => {
setActive(0);
}, [query]);
const eventNames = useMemo(
() => new Map(events.map((event) => [event.id, event.name])),
[events],
);
const results = useMemo(() => {
const term = query.trim().toLowerCase();
const matches = (values: (string | undefined)[]) =>
!term || values.some((value) => value?.toLowerCase().includes(term));
const actionsFound: Result[] = actions
.filter((action) => matches([action.label, action.hint]))
.slice(0, 5)
.map((action) => ({
key: `action:${action.id}`,
label: action.label,
hint: action.hint ?? 'Action',
kind: 'action',
run: action.run,
}));
const eventsFound: Result[] = events
.filter((event) => matches([event.name]))
.slice(0, 6)
.map((event) => ({
key: `event:${event.id}`,
label: event.name,
hint: 'Event',
kind: 'event',
run: () => onOpenEvent(event.id),
}));
const photosFound: Result[] = photos
.filter((photo) =>
matches([
photo.name,
photo.title,
photo.caption,
photo.creator,
photo.meta.camera,
photo.meta.lens,
eventNames.get(photo.eventId),
...photo.keywords,
]),
)
.slice(0, 18)
.map((photo) => ({
key: `photo:${photo.id}`,
label: photo.title || photo.name,
hint: [eventNames.get(photo.eventId), photo.meta.camera].filter(Boolean).join(' · ') || 'Photo',
kind: 'photo',
thumb: photo.thumbUrl ?? photo.thumb,
run: () => onOpenPhoto(photo.id),
}));
return [...actionsFound, ...eventsFound, ...photosFound];
}, [actions, eventNames, events, onOpenEvent, onOpenPhoto, photos, query]);
useEffect(() => {
const item = listRef.current?.querySelector<HTMLElement>(`[data-index="${active}"]`);
item?.scrollIntoView({ block: 'nearest' });
}, [active]);
const choose = (result: Result | undefined) => {
if (!result) return;
result.run();
onClose();
};
return (
<div className="modal-backdrop command-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="command-palette" role="dialog" aria-modal="true" aria-label="Search Luminary">
<div className="command-input-row">
<span className="command-icon" aria-hidden="true">⌕</span>
<input
ref={inputRef}
value={query}
placeholder="Search photos, events, and actions…"
aria-label="Search photos, events, and actions"
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Escape') {
e.preventDefault();
onClose();
} else if (e.key === 'ArrowDown') {
e.preventDefault();
setActive((index) => Math.min(results.length - 1, index + 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setActive((index) => Math.max(0, index - 1));
} else if (e.key === 'Enter') {
e.preventDefault();
choose(results[active]);
}
}}
/>
<kbd>esc</kbd>
</div>
<div className="command-results" ref={listRef}>
{results.length ? (
results.map((result, index) => (
<button
key={result.key}
type="button"
data-index={index}
className={`command-result ${index === active ? 'active' : ''}`}
onMouseEnter={() => setActive(index)}
onClick={() => choose(result)}
>
{result.kind === 'photo' && result.thumb ? (
<img src={result.thumb} alt="" className="command-thumb" />
) : (
<span className={`command-kind ${result.kind}`}>
{result.kind === 'action' ? '⌘' : result.kind === 'event' ? '▤' : '▧'}
</span>
)}
<span className="command-result-main">
<strong>{result.label}</strong>
<small>{result.hint}</small>
</span>
<span className="command-result-kind">{result.kind}</span>
</button>
))
) : (
<div className="command-empty">No matches for “{query.trim()}”.</div>
)}
</div>
<div className="command-foot">
<span>↑↓ navigate</span>
<span>↵ open</span>
<span>esc close</span>
</div>
</div>
</div>
);
}
+162
View File
@@ -0,0 +1,162 @@
import { useEffect, useRef, useState } from 'react';
import { getBitmap } from '../lib/images';
import { rotatedBounds, Renderer } from '../gl/renderer';
import { buildLensCorrection, type LensCorrection } from '../lib/lensfun';
import type { PhotoRecord } from '../types';
interface Props {
photos: PhotoRecord[];
onClose: () => void;
onOpen: (id: string) => void;
}
function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: string) => void }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const boxRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<Renderer | null>(null);
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
const [box, setBox] = useState({ w: 0, h: 0 });
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
getBitmap(photo)
.then((next) => alive && setBitmap(next))
.catch((err) => alive && setError(err instanceof Error ? err.message : 'Could not load the photo'));
return () => {
alive = false;
};
}, [photo]);
useEffect(() => {
let alive = true;
if (!photo.edits.lens || !bitmap) {
setLensCorrection(null);
return;
}
buildLensCorrection(photo.edits.lens, {
width: bitmap.width,
height: bitmap.height,
meta: photo.meta,
})
.then((correction) => alive && setLensCorrection(correction))
.catch(() => alive && setLensCorrection(null));
return () => {
alive = false;
};
}, [bitmap, photo.edits.lens, photo.meta]);
useEffect(() => {
const el = boxRef.current;
if (!el) return;
const measure = () => setBox({ w: el.clientWidth, h: el.clientHeight });
measure();
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, []);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
try {
rendererRef.current = new Renderer(canvas);
} catch (err) {
setError(err instanceof Error ? err.message : 'The image engine could not start');
}
return () => {
rendererRef.current?.dispose();
rendererRef.current = null;
};
}, []);
useEffect(() => {
const renderer = rendererRef.current;
const canvas = canvasRef.current;
if (!renderer || !canvas || !bitmap || box.w < 30 || box.h < 30) return;
// Wait for the layout pass, then draw in a frame callback: uploading the
// source while the tile is still being measured can lose the first frame.
const raf = requestAnimationFrame(() => {
const frame = rotatedBounds(bitmap.width, bitmap.height, photo.edits.crop.angle, photo.edits.crop.quarter);
const aspect = (frame.w * photo.edits.crop.w) / Math.max(1, frame.h * photo.edits.crop.h);
let cssW = box.w;
let cssH = cssW / aspect;
if (cssH > box.h) {
cssH = box.h;
cssW = cssH * aspect;
}
cssW = Math.max(20, Math.round(cssW));
cssH = Math.max(20, Math.round(cssH));
canvas.style.width = `${cssW}px`;
canvas.style.height = `${cssH}px`;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cap = Math.min(1, 2200 / Math.max(cssW * dpr, cssH * dpr));
const opts = {
width: Math.max(1, Math.round(cssW * dpr * cap)),
height: Math.max(1, Math.round(cssH * dpr * cap)),
lens: lensCorrection,
};
try {
renderer.setImage(bitmap);
renderer.render(photo.edits, opts);
} catch (err) {
setError(err instanceof Error ? err.message : 'Rendering failed');
}
});
return () => cancelAnimationFrame(raf);
}, [bitmap, box, photo, lensCorrection]);
return (
<figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}>
<div className="compare-canvas" ref={boxRef}>
{error ? <div className="banner error">{error}</div> : <canvas ref={canvasRef} />}
</div>
<figcaption>
<span className="compare-name" title={photo.name}>
{photo.name}
</span>
<span className="compare-stars">{photo.rating ? '★'.repeat(photo.rating) : '—'}</span>
<button className="btn ghost small" onClick={() => onOpen(photo.id)}>
Develop
</button>
</figcaption>
</figure>
);
}
/** Side-by-side survey of 2–4 selected frames. */
export default function CompareView({ photos, onClose, onOpen }: Props) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [onClose]);
return (
<div className="compare-page" role="dialog" aria-label="Compare photos">
<header className="compare-head">
<div>
<strong>Compare</strong>
<span className="muted small">
{' '}
· {photos.length} photo{photos.length === 1 ? '' : 's'} · double-click a frame to edit
</span>
</div>
<button className="btn ghost" onClick={onClose}>
Close
</button>
</header>
<div className={`compare-grid count-${photos.length}`}>
{photos.map((photo) => (
<CompareTile key={photo.id} photo={photo} onOpen={onOpen} />
))}
</div>
</div>
);
}
+99
View File
@@ -0,0 +1,99 @@
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
export interface MenuAction {
label: string;
shortcut?: string;
onSelect: () => void;
disabled?: boolean;
danger?: boolean;
}
export type MenuEntry = MenuAction | 'separator';
interface Props {
x: number;
y: number;
entries: MenuEntry[];
header?: ReactNode;
onClose: () => void;
}
/**
* Right-click menu anchored to the pointer. Rendered in a portal so the app's
* scroll containers and panel overflow cannot clip it, and nudged inside the
* window when the cursor is close to an edge.
*/
export default function ContextMenu({ x, y, entries, header, onClose }: Props) {
const ref = useRef<HTMLDivElement>(null);
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const margin = 8;
setPos({
left: Math.max(margin, Math.min(x, window.innerWidth - rect.width - margin)),
top: Math.max(margin, Math.min(y, window.innerHeight - rect.height - margin)),
});
}, [x, y]);
useEffect(() => {
const onPointerDown = (e: PointerEvent) => {
if (ref.current && e.target instanceof Node && ref.current.contains(e.target)) return;
onClose();
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
onClose();
};
window.addEventListener('pointerdown', onPointerDown, true);
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('resize', onClose);
window.addEventListener('blur', onClose);
window.addEventListener('wheel', onClose, { passive: true });
return () => {
window.removeEventListener('pointerdown', onPointerDown, true);
window.removeEventListener('keydown', onKeyDown, true);
window.removeEventListener('resize', onClose);
window.removeEventListener('blur', onClose);
window.removeEventListener('wheel', onClose);
};
}, [onClose]);
return createPortal(
<div
ref={ref}
className="ctx-menu"
role="menu"
style={{ left: pos?.left ?? x, top: pos?.top ?? y, visibility: pos ? 'visible' : 'hidden' }}
onContextMenu={(e) => e.preventDefault()}
>
{header && <div className="ctx-header">{header}</div>}
{entries.map((entry, i) =>
entry === 'separator' ? (
<div className="ctx-sep" key={`sep-${i}`} />
) : (
<button
key={`${entry.label}-${i}`}
type="button"
role="menuitem"
className={`ctx-item ${entry.danger ? 'danger' : ''}`}
disabled={entry.disabled}
onClick={() => {
onClose();
entry.onSelect();
}}
>
<span>{entry.label}</span>
{entry.shortcut && <span className="ctx-key">{entry.shortcut}</span>}
</button>
),
)}
</div>,
document.body,
);
}
+268
View File
@@ -0,0 +1,268 @@
import { useEffect, useRef, useState, type PointerEvent } from 'react';
import { clamp } from '../lib/curves';
import { grainSampleWindow, Renderer } from '../gl/renderer';
import type { CropState, Edits } from '../types';
type Mode = 'move' | 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
/**
* Point (frame uv) the loupe sits on when dragged to `u`,`v` inside the crop
* rectangle, kept a half-box away from its edges so the patch stays inside.
*/
export function clampLoupe(
crop: { x: number; y: number; w: number; h: number },
u: number,
v: number,
halfU: number,
halfV: number,
) {
const cx = Math.min(1 - halfU, Math.max(halfU, Math.min(1, Math.max(0, u))));
const cy = Math.min(1 - halfV, Math.max(halfV, Math.min(1, Math.max(0, v))));
return { x: crop.x + cx * crop.w, y: crop.y + cy * crop.h };
}
interface Props {
crop: CropState;
frame: { w: number; h: number };
ratio: number | null;
bitmap: ImageBitmap | null;
edits: Edits;
onChange: (rect: Partial<CropState>) => void;
/** lets the preview hold the grain still while a handle is moving */
onDragChange?: (busy: boolean) => void;
}
const MIN = 0.04;
function clampRect(r: CropState): CropState {
let w = clamp(r.w, MIN, 1);
let h = clamp(r.h, MIN, 1);
const x = clamp(r.x, 0, 1 - w);
const y = clamp(r.y, 0, 1 - h);
return { ...r, x, y, w, h };
}
function applyDrag(
start: CropState,
mode: Mode,
dx: number,
dy: number,
ratio: number | null,
frame: { w: number; h: number },
): Partial<CropState> {
let { x, y, w, h } = start;
if (mode === 'move') {
x = clamp(x + dx, 0, 1 - w);
y = clamp(y + dy, 0, 1 - h);
return { x, y };
}
if (mode.includes('e')) w = clamp(w + dx, MIN, 1 - x);
if (mode.includes('s')) h = clamp(h + dy, MIN, 1 - y);
if (mode.includes('w')) {
const nx = clamp(x + dx, 0, x + w - MIN);
w += x - nx;
x = nx;
}
if (mode.includes('n')) {
const ny = clamp(y + dy, 0, y + h - MIN);
h += y - ny;
y = ny;
}
if (ratio) {
const frameRatio = frame.w / frame.h;
const dragsWidth = mode.includes('e') || mode.includes('w');
if (dragsWidth) {
const targetH = (w * frameRatio) / ratio;
if (mode.includes('n')) y = y + h - targetH;
h = targetH;
} else if (mode.includes('n') || mode.includes('s')) {
const targetW = (h * ratio) / frameRatio;
x += (w - targetW) / 2;
w = targetW;
}
if (w > 1) {
const k = 1 / w;
w *= k;
h *= k;
}
if (h > 1) {
const k = 1 / h;
w *= k;
h *= k;
}
if (mode.includes('w')) x = start.x + start.w - w;
if (mode.includes('n')) y = start.y + start.h - h;
x = clamp(x, 0, 1 - w);
y = clamp(y, 0, 1 - h);
}
return clampRect({ ...start, x, y, w, h });
}
export default function CropOverlay({ crop, frame, ratio, bitmap, edits, onChange, onDragChange }: Props) {
const ref = useRef<HTMLDivElement>(null);
const start = useRef<{ mode: Mode; x: number; y: number; rect: CropState } | null>(null);
const [dragging, setDragging] = useState(false);
const loupe = useRef<HTMLCanvasElement>(null);
const loupeRenderer = useRef<Renderer | null>(null);
/** where the patch is sampling, in frame uv; null = centre of the rectangle */
const [loupePoint, setLoupePoint] = useState<{ x: number; y: number } | null>(null);
/** pointer offset from the patch centre while it is being dragged */
const grab = useRef<{ x: number; y: number } | null>(null);
useEffect(
() => () => {
loupeRenderer.current?.dispose();
loupeRenderer.current = null;
},
[],
);
// A live 1:1 grain patch inside the crop rectangle: it samples whatever area the
// rectangle frames, so the rectangle can be judged as it is dragged.
useEffect(() => {
const canvas = loupe.current;
if (!canvas || !bitmap) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cssW = 120;
const cropPxW = Math.max(1, frame.w * crop.w);
const cropPxH = Math.max(1, frame.h * crop.h);
const cssH = Math.round(Math.min(96, Math.max(48, cssW * (cropPxH / cropPxW))));
const W = Math.max(1, Math.round(cssW * dpr));
const H = Math.max(1, Math.round(cssH * dpr));
canvas.style.width = `${cssW}px`;
canvas.style.height = `${cssH}px`;
if (canvas.width !== W) canvas.width = W;
if (canvas.height !== H) canvas.height = H;
try {
if (!loupeRenderer.current) loupeRenderer.current = new Renderer(canvas);
const r = loupeRenderer.current;
r.setImage(bitmap);
const view = grainSampleWindow(frame, crop, W, H, loupePoint);
r.render({ ...edits, crop }, { width: W, height: H, view });
} catch {
// The overlay still works if the engine cannot start a second context.
}
}, [bitmap, crop, edits, frame, loupePoint]);
const dpr = Math.min(typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1, 2);
const loupeCssW = 120;
const cropPxW = Math.max(1, frame.w * crop.w);
const cropPxH = Math.max(1, frame.h * crop.h);
const loupeCssH = Math.round(Math.min(96, Math.max(48, loupeCssW * (cropPxH / cropPxW))));
const loupeW = Math.max(1, Math.round(loupeCssW * dpr));
const loupeH = Math.max(1, Math.round(loupeCssH * dpr));
const view = grainSampleWindow(frame, crop, loupeW, loupeH, loupePoint);
const fits = crop.w > 0.16 && crop.h > 0.16;
const loupeAt = {
left: `${((view.x + view.w / 2 - crop.x) / crop.w) * 100}%`,
top: `${((view.y + view.h / 2 - crop.y) / crop.h) * 100}%`,
width: `${loupeCssW}px`,
height: `${loupeCssH}px`,
transform: 'translate(-50%, -50%)',
display: fits && bitmap ? 'block' : 'none',
};
const startLoupe = (e: PointerEvent<HTMLCanvasElement>) => {
e.preventDefault();
e.stopPropagation();
e.currentTarget.setPointerCapture(e.pointerId);
const box = e.currentTarget.parentElement?.getBoundingClientRect();
if (!box || !box.width || !box.height) return;
const cx = box.left + ((view.x + view.w / 2 - crop.x) / crop.w) * box.width;
const cy = box.top + ((view.y + view.h / 2 - crop.y) / crop.h) * box.height;
grab.current = { x: e.clientX - cx, y: e.clientY - cy };
};
const moveLoupe = (e: PointerEvent<HTMLCanvasElement>) => {
const g = grab.current;
if (!g) return;
const box = e.currentTarget.parentElement?.getBoundingClientRect();
if (!box || !box.width || !box.height) return;
const halfU = Math.min(0.5, loupeCssW / 2 / box.width);
const halfV = Math.min(0.5, loupeCssH / 2 / box.height);
setLoupePoint(
clampLoupe(
crop,
(e.clientX - g.x - box.left) / box.width,
(e.clientY - g.y - box.top) / box.height,
halfU,
halfV,
),
);
};
const endLoupe = () => {
grab.current = null;
};
const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
const el = e.target as HTMLElement;
const mode = (el.dataset.mode ?? 'move') as Mode;
e.preventDefault();
e.stopPropagation();
ref.current?.setPointerCapture(e.pointerId);
start.current = { mode, x: e.clientX, y: e.clientY, rect: { ...crop } };
setDragging(true);
onDragChange?.(true);
};
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const s = start.current;
const el = ref.current;
if (!s || !el) return;
const rect = el.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dx = (e.clientX - s.x) / rect.width;
const dy = (e.clientY - s.y) / rect.height;
onChange(applyDrag(s.rect, s.mode, dx, dy, ratio, frame));
};
const end = (e: React.PointerEvent<HTMLDivElement>) => {
if (ref.current?.hasPointerCapture(e.pointerId)) ref.current.releasePointerCapture(e.pointerId);
start.current = null;
setDragging(false);
onDragChange?.(false);
};
const style = {
left: `${crop.x * 100}%`,
top: `${crop.y * 100}%`,
width: `${crop.w * 100}%`,
height: `${crop.h * 100}%`,
};
return (
<div
ref={ref}
className={`crop-overlay ${dragging ? 'dragging' : ''}`}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={end}
onPointerCancel={end}
>
<div className="crop-rect" style={style}>
<div className="crop-grid" data-mode="move" />
{(['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as Mode[]).map((m) => (
<span key={m} className={`handle ${m}`} data-mode={m} />
))}
<canvas
ref={loupe}
className="crop-loupe"
style={loupeAt}
title="Grain at 100% · drag to sample any point in the crop"
onPointerDown={startLoupe}
onPointerMove={moveLoupe}
onPointerUp={endLoupe}
onPointerCancel={endLoupe}
/>
<span className="crop-size">
{Math.round(crop.w * 100)}% × {Math.round(crop.h * 100)}%
</span>
</div>
</div>
);
}
+122
View File
@@ -0,0 +1,122 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { buildSampler, clamp01 } from '../lib/curves';
import type { CurvePoint } from '../types';
interface Props {
points: CurvePoint[];
onChange: (points: CurvePoint[]) => void;
color: string;
}
export default function CurveEditor({ points, onChange, color }: Props) {
const svgRef = useRef<SVGSVGElement>(null);
const pointsRef = useRef(points);
const [drag, setDrag] = useState<number | null>(null);
const [hover, setHover] = useState<number | null>(null);
useEffect(() => {
pointsRef.current = points;
}, [points]);
const sampler = useMemo(() => buildSampler(points), [points]);
const path = useMemo(() => {
const segs: string[] = [];
for (let i = 0; i <= 80; i++) {
const x = i / 80;
const y = sampler(x);
segs.push(`${i === 0 ? 'M' : 'L'}${(x * 100).toFixed(2)},${((1 - y) * 100).toFixed(2)}`);
}
return segs.join(' ');
}, [sampler]);
const toNorm = useCallback((clientX: number, clientY: number) => {
const svg = svgRef.current;
if (!svg) return { x: 0, y: 0 };
const rect = svg.getBoundingClientRect();
return {
x: clamp01((clientX - rect.left) / rect.width),
y: clamp01(1 - (clientY - rect.top) / rect.height),
};
}, []);
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
e.preventDefault();
const idxAttr = (e.target as Element).getAttribute('data-idx');
let idx: number;
if (idxAttr !== null) {
idx = Number(idxAttr);
} else {
const p = toNorm(e.clientX, e.clientY);
const next = [...points, { x: p.x, y: p.y }].sort((a, b) => a.x - b.x);
idx = next.findIndex((pt) => pt.x === p.x && pt.y === p.y);
onChange(next);
}
setDrag(idx);
e.currentTarget.setPointerCapture(e.pointerId);
};
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => {
if (drag === null) return;
const pts = pointsRef.current;
const idx = drag;
if (!pts[idx]) return;
const p = toNorm(e.clientX, e.clientY);
const lo = idx > 0 ? pts[idx - 1].x + 0.01 : 0;
const hi = idx < pts.length - 1 ? pts[idx + 1].x - 0.01 : 1;
const next = pts.map((pt, i) => (i === idx ? { x: Math.min(hi, Math.max(lo, p.x)), y: p.y } : pt));
onChange(next);
};
const handleUp = () => setDrag(null);
const removePoint = (idx: number) => {
const pts = pointsRef.current;
if (pts.length <= 2) return;
onChange(pts.filter((_, i) => i !== idx));
setDrag(null);
};
return (
<div className="curve-wrap">
<svg
ref={svgRef}
className="curve"
viewBox="0 0 100 100"
preserveAspectRatio="none"
onPointerDown={handleDown}
onPointerMove={handleMove}
onPointerUp={handleUp}
onPointerCancel={handleUp}
onDoubleClick={(e) => {
const idxAttr = (e.target as Element).getAttribute('data-idx');
if (idxAttr !== null) removePoint(Number(idxAttr));
}}
>
<rect x="0" y="0" width="100" height="100" className="curve-bg" />
{[25, 50, 75].map((v) => (
<g key={v}>
<line x1={v} y1="0" x2={v} y2="100" className="curve-grid" />
<line x1="0" y1={v} x2="100" y2={v} className="curve-grid" />
</g>
))}
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" />
<path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
{points.map((p, i) => (
<circle
key={`${i}-${p.x.toFixed(3)}`}
data-idx={i}
cx={p.x * 100}
cy={(1 - p.y) * 100}
r={hover === i || drag === i ? 3 : 2.1}
className="curve-point"
fill={color}
onPointerEnter={() => setHover(i)}
onPointerLeave={() => setHover((h) => (h === i ? null : h))}
/>
))}
</svg>
<div className="curve-hint">Click to add a point · drag to shape · double-click a point to remove</div>
</div>
);
}
File diff suppressed because it is too large Load Diff
+263
View File
@@ -0,0 +1,263 @@
import { useState } from 'react';
import {
draggedEventId,
draggedPhotoIds,
endDrag,
EVENT_DRAG,
PHOTO_DRAG,
startEventDrag,
startPhotoDrag,
} from '../lib/drag';
import type { EventRecord, PhotoRecord, SmartCollection } from '../types';
interface Props {
collapsed?: boolean;
mobileOpen?: boolean;
events: EventRecord[];
photos: PhotoRecord[];
eventId: string;
onSelectEvent: (id: string) => void;
onCreate: (name: string) => Promise<void> | void;
onRename: (id: string, name: string) => void;
onDelete: (id: string) => void;
onReorderEvents: (dragId: string, targetId: string) => void;
onDropPhotos: (ids: string[], eventId: string) => void;
trashOpen: boolean;
trashCount: number;
onOpenTrash: () => void;
storageNote: string;
collections: SmartCollection[];
activeCollectionId: string | null;
onSelectCollection: (id: string) => void;
onDeleteCollection: (id: string) => void;
}
export default function EventSidebar({
collapsed = false,
mobileOpen = false,
events,
photos,
eventId,
onSelectEvent,
onCreate,
onRename,
onDelete,
onReorderEvents,
onDropPhotos,
trashOpen,
trashCount,
onOpenTrash,
storageNote,
collections,
activeCollectionId,
onSelectCollection,
onDeleteCollection,
}: Props) {
const [adding, setAdding] = useState(false);
const [name, setName] = useState('');
const [dropTarget, setDropTarget] = useState<string | null>(null);
const counts = new Map<string, number>();
let unsorted = 0;
for (const p of photos) {
if (!p.eventId) {
unsorted++;
continue;
}
counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1);
}
const submit = async () => {
if (!name.trim()) {
setAdding(false);
return;
}
await onCreate(name);
setName('');
setAdding(false);
};
const dropProps = (targetId: string) => ({
onDragOver: (e: React.DragEvent) => {
if (draggedPhotoIds().length) {
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
setDropTarget(targetId);
}
},
onDragLeave: () => setDropTarget((cur) => (cur === targetId ? null : cur)),
onDrop: (e: React.DragEvent) => {
const ids = draggedPhotoIds();
setDropTarget(null);
if (!ids.length) return;
e.preventDefault();
e.stopPropagation();
onDropPhotos(ids, targetId);
endDrag();
},
});
return (
<aside
id="library-sidebar"
className={`sidebar ${collapsed ? 'collapsed' : ''} ${mobileOpen ? 'mobile-open' : ''}`}
aria-hidden={collapsed && !mobileOpen}
>
<div className="sidebar-head">
<span>Catalog</span>
<button className="icon-btn" title="New event" onClick={() => setAdding((v) => !v)}>
+
</button>
</div>
<div className="catalog-links">
<button className={`event-item all ${eventId === 'all' ? 'active' : ''}`} onClick={() => onSelectEvent('all')}>
<span className="event-name">All photos</span>
<span className="event-count">{photos.length}</span>
</button>
{unsorted > 0 && (
<button
className={`event-item all ${eventId === 'unsorted' ? 'active' : ''}`}
onClick={() => onSelectEvent('unsorted')}
>
<span className="event-name">Unsorted</span>
<span className="event-count">{unsorted}</span>
</button>
)}
<button
className={`event-item all ${trashOpen ? 'active' : ''}`}
onClick={onOpenTrash}
title="Deleted photos stay here until you empty the trash"
>
<span className="event-name">Trash</span>
<span className="event-count">{trashCount}</span>
</button>
</div>
{collections.length > 0 && (
<>
<div className="sidebar-head sub">
<span>Collections</span>
<span className="muted small">{collections.length}</span>
</div>
<div className="collection-list">
{collections.map((collection) => (
<div
key={collection.id}
className={`event-item collection ${activeCollectionId === collection.id ? 'active' : ''}`}
>
<button className="event-main" onClick={() => onSelectCollection(collection.id)} title="Apply saved view">
<span className="event-name">{collection.name}</span>
<span className="collection-icon">◇</span>
</button>
<div className="event-tools">
<button
className="icon-btn danger"
title="Delete collection"
onClick={() => onDeleteCollection(collection.id)}
>
🗑
</button>
</div>
</div>
))}
</div>
</>
)}
<div className="sidebar-head sub">
<span>Events</span>
<span className="muted small">{events.length}</span>
</div>
{adding && (
<div className="new-event">
<input
autoFocus
value={name}
placeholder="Event name"
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void submit();
if (e.key === 'Escape') {
setAdding(false);
setName('');
}
}}
/>
<button className="btn primary small" onClick={() => void submit()}>
Add
</button>
</div>
)}
<div className="event-list">
{events.map((event) => (
<div
key={event.id}
className={`event-item ${eventId === event.id ? 'active' : ''} ${dropTarget === event.id ? 'drop' : ''}`}
draggable
onDragStart={(e) => {
startEventDrag(event.id);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(EVENT_DRAG, event.id);
}}
onDragEnd={() => endDrag()}
onDragOver={(e) => {
const eventDrag = draggedEventId();
if (eventDrag && eventDrag !== event.id) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
setDropTarget(event.id);
return;
}
dropProps(event.id).onDragOver(e);
}}
onDragLeave={() => setDropTarget((cur) => (cur === event.id ? null : cur))}
onDrop={(e) => {
const eventDrag = draggedEventId();
if (eventDrag && eventDrag !== event.id) {
e.preventDefault();
setDropTarget(null);
onReorderEvents(eventDrag, event.id);
endDrag();
return;
}
dropProps(event.id).onDrop(e);
}}
>
<button className="event-main" onClick={() => onSelectEvent(event.id)}>
<span className="event-name" title={event.name}>
{event.name}
</span>
<span className="event-count">{counts.get(event.id) ?? 0}</span>
</button>
<div className="event-tools">
<button
className="icon-btn"
title="Rename event"
onClick={() => {
const next = window.prompt('Rename event', event.name);
if (next) onRename(event.id, next);
}}
>
✎
</button>
<button className="icon-btn danger" title="Remove event" onClick={() => onDelete(event.id)}>
🗑
</button>
</div>
</div>
))}
{!events.length && (
<p className="muted small sidebar-hint">Create an event, then drag photos onto it.</p>
)}
</div>
<div className="sidebar-foot" {...dropProps('')}>
{dropTarget === '' ? <strong>Drop to move to Unsorted</strong> : storageNote}
</div>
</aside>
);
}
+569
View File
@@ -0,0 +1,569 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { ExportOptions, ExportFormat, ExportRecipe, ResizeMode, WatermarkPosition } from '../lib/export';
import { buildFileName, DEFAULT_EXPORT, exportPhotos } from '../lib/export';
import Slider from './Slider';
import { getBitmap } from '../lib/images';
import { frameToSource, grainCellPx, grainSampleWindow, outputSize, rotatedBounds, Renderer } from '../gl/renderer';
import type { PhotoRecord } from '../types';
interface Props {
photos: PhotoRecord[];
initial: ExportOptions;
recipes: ExportRecipe[];
onSaveRecipe: (name: string, options: ExportOptions) => void;
onDeleteRecipe: (id: string) => void;
onClose: () => void;
onDone: (message: string, options: ExportOptions) => void;
}
const FORMATS: { value: ExportFormat; label: string }[] = [
{ value: 'jpeg', label: 'JPEG' },
{ value: 'png', label: 'PNG (8-bit)' },
{ value: 'webp', label: 'WebP' },
{ value: 'tiff16', label: 'TIFF (16-bit)' },
];
/**
* Three 1:1 patches of the export at half, current and double the chosen size.
* Each patch is rendered on the export's own pixel grid, so it shows exactly the
* grain and detail that file will carry at 100%.
*/
function ExportDetailStrip({ photo, size }: { photo: PhotoRecord; size: { w: number; h: number } | null }) {
const tiles = useRef<(HTMLCanvasElement | null)[]>([]);
const pick = useRef<HTMLCanvasElement | null>(null);
const work = useRef<HTMLCanvasElement | null>(null);
const renderer = useRef<Renderer | null>(null);
const bitmap = useRef<ImageBitmap | null>(null);
const [ready, setReady] = useState(false);
const [point, setPoint] = useState<{ x: number; y: number } | null>(null);
const { crop } = photo.edits;
const srcW = Math.max(1, photo.width);
const srcH = Math.max(1, photo.height);
useEffect(() => {
let alive = true;
getBitmap(photo)
.then((bmp) => {
if (!alive) return;
bitmap.current = bmp;
setReady(true);
})
.catch(() => undefined);
return () => {
alive = false;
};
}, [photo.id]);
useEffect(
() => () => {
renderer.current?.dispose();
renderer.current = null;
},
[],
);
const steps = useMemo(() => {
if (!size) return [];
const long = Math.max(size.w, size.h);
return [Math.max(200, Math.round(long / 2)), long, Math.min(20000, long * 2)];
}, [size]);
useEffect(() => {
const bmp = bitmap.current;
if (!ready || !bmp || !size || !steps.length) return;
if (!work.current) work.current = document.createElement('canvas');
const workCanvas = work.current;
try {
if (!renderer.current) renderer.current = new Renderer(workCanvas);
const r = renderer.current;
r.setImage(bmp);
const frame = rotatedBounds(bmp.width, bmp.height, crop.angle, crop.quarter);
const cropPxW = Math.max(1, frame.w * crop.w);
const cropPxH = Math.max(1, frame.h * crop.h);
const PW = 132;
const PH = Math.round(Math.min(92, Math.max(56, PW * (cropPxH / cropPxW))));
const outLong = Math.max(1, Math.max(size.w, size.h));
steps.forEach((longEdge, i) => {
const tile = tiles.current[i];
if (!tile) return;
if (tile.width !== PW) tile.width = PW;
if (tile.height !== PH) tile.height = PH;
const scale = longEdge / outLong;
const pxPerSource = (size.w * scale) / cropPxW;
const view = grainSampleWindow(
frame,
crop,
Math.max(1, Math.round(PW / pxPerSource)),
Math.max(1, Math.round(PH / pxPerSource)),
point,
);
r.render(photo.edits, { width: PW, height: PH, view, upscale: pxPerSource > 1.05 });
const ctx = tile.getContext('2d');
if (ctx) ctx.drawImage(workCanvas, 0, 0);
});
// The picker shows the whole exported crop, oriented like the main view.
const pickCanvas = pick.current;
if (pickCanvas) {
const pickW = 132;
const pickH = Math.round(Math.min(112, Math.max(56, pickW * (cropPxH / cropPxW))));
r.render(photo.edits, { width: pickW, height: pickH, upscale: pickW / cropPxW > 1.05 });
const ctx = pickCanvas.getContext('2d');
if (ctx) {
if (pickCanvas.width !== pickW) pickCanvas.width = pickW;
if (pickCanvas.height !== pickH) pickCanvas.height = pickH;
ctx.imageSmoothingQuality = 'high';
ctx.clearRect(0, 0, pickW, pickH);
ctx.drawImage(workCanvas, 0, 0, pickW, pickH);
}
}
} catch {
// Keep the previous patches if the engine is unavailable.
}
}, [ready, photo, crop, size, steps, point]);
// Where the patch is, in photo terms, and how big a grain cell is in the file.
const info = useMemo(() => {
// The point lives in frame coordinates; the picker shows only the crop.
const p = point ?? { x: crop.x + crop.w / 2, y: crop.y + crop.h / 2 };
const at = frameToSource(p, srcW, srcH, crop.angle, crop.quarter, crop.flipH, crop.flipV);
return {
sx: at.x,
sy: at.y,
px: Math.round(at.x * 100),
py: Math.round(at.y * 100),
ux: (p.x - crop.x) / crop.w,
uy: (p.y - crop.y) / crop.h,
cell: size ? grainCellPx(photo.edits, srcW, srcH, size.w) : 0,
};
}, [point, crop, srcW, srcH, size, photo.edits]);
if (!size || !steps.length) return null;
return (
<>
<div className="export-detail-pick">
<div
className="pick-frame"
title="Choose the sample point for the 100% patches"
onPointerDown={(e) => {
const r = pick.current?.getBoundingClientRect();
if (!r || !r.width || !r.height) return;
const u = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
const v = Math.min(1, Math.max(0, (e.clientY - r.top) / r.height));
setPoint({ x: crop.x + u * crop.w, y: crop.y + v * crop.h });
}}
>
<canvas ref={pick} />
<span
className="pick-dot"
style={{ left: `${info.ux * 100}%`, top: `${info.uy * 100}%` }}
/>
</div>
<span className="hint">Click the photo to move the 100% patches</span>
</div>
<div className="export-detail">
{steps.map((longEdge, i) => (
<figure key={longEdge}>
<canvas ref={(el) => { tiles.current[i] = el; }} />
<figcaption>
{longEdge === steps[1] ? 'This export' : longEdge < steps[1] ? 'Half size' : 'Double size'} · {longEdge} px · 100%
</figcaption>
</figure>
))}
</div>
<p className="muted small export-detail-info">
Sample {info.px}% × {info.py}% of the photo ·{' '}
{photo.edits.grain.amount > 1
? `grain ${info.cell < 1 ? info.cell.toFixed(2) : info.cell.toFixed(1)} px cells${
info.cell < 0.9 ? ' (fades: finer than a pixel)' : ''
} at this size`
: 'grain off'}
</p>
</>
);
}
export default function ExportModal({ photos, initial, recipes, onSaveRecipe, onDeleteRecipe, onClose, onDone }: Props) {
const [opts, setOpts] = useState<ExportOptions>({ ...DEFAULT_EXPORT, ...initial });
const [recipeId, setRecipeId] = useState('');
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState({ done: 0, total: 0 });
const [stage, setStage] = useState<'render' | 'pack'>('render');
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Capture phase so Escape closes the dialog even with the photo open behind it.
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const patch = (p: Partial<ExportOptions>) => setOpts((prev) => ({ ...prev, ...p }));
const patchWatermark = (p: Partial<ExportOptions['watermark']>) =>
setOpts((prev) => ({ ...prev, watermark: { ...prev.watermark, ...p } }));
const sample = photos[0];
const previewSize = useMemo(() => {
if (!sample) return null;
// Use the renderer's exact crop/rotation calculation, not a rectangle-only
// estimate: straightening expands the frame and changes both dimensions.
const base = outputSize(sample.edits, sample.width || 1, sample.height || 1);
let k = 1;
if (opts.resize === 'longEdge' && opts.longEdge > 0 && Math.max(base.w, base.h) > opts.longEdge) {
k = opts.longEdge / Math.max(base.w, base.h);
} else if (opts.resize === 'percent') {
k = Math.min(2, Math.max(0.05, opts.percent / 100));
}
return { w: Math.max(1, Math.round(base.w * k)), h: Math.max(1, Math.round(base.h * k)) };
}, [sample, opts.resize, opts.longEdge, opts.percent]);
const sampleName = sample
? buildFileName(opts.nameTemplate, sample, 0, opts)
: `export.${opts.format === 'jpeg' ? 'jpg' : opts.format === 'tiff16' ? 'tif' : opts.format}`;
const run = async () => {
if (!photos.length || busy) return;
setBusy(true);
setError(null);
setStage('render');
try {
const { count, failed } = await exportPhotos(
photos,
opts,
(done, total) => setProgress({ done, total }),
setStage,
);
if (!count) {
setError(failed.length ? 'Nothing could be exported. Check the browser console.' : 'Nothing to export');
setBusy(false);
return;
}
onDone(`Exported ${count} photo${count === 1 ? '' : 's'}`, opts);
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Export failed');
setBusy(false);
}
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div className="modal export-modal">
<header className="modal-head">
<h2>Export</h2>
<button className="icon-btn" onClick={onClose} disabled={busy}>
✕
</button>
</header>
<div className="modal-body">
<div className="export-summary">
<strong>
{photos.length} photo{photos.length === 1 ? '' : 's'}
</strong>
{previewSize && (
<span className="muted small">
{previewSize.w} × {previewSize.h} px
</span>
)}
</div>
<div className="field-row">
<label className="field">
<span>Format</span>
<select
value={opts.format}
onChange={(e) => {
const format = e.target.value as ExportFormat;
patch({
format,
// Watermarking needs an 8-bit canvas pass; keep the option off
// rather than silently downgrading the 16-bit file.
...(format === 'tiff16' ? { watermark: { ...opts.watermark, enabled: false } } : {}),
});
}}
disabled={busy}
>
{FORMATS.map((f) => (
<option key={f.value} value={f.value}>
{f.label}
</option>
))}
</select>
</label>
<label className="field">
<span>Resize</span>
<select
value={opts.resize}
onChange={(e) => patch({ resize: e.target.value as ResizeMode })}
disabled={busy}
>
<option value="none">Full resolution</option>
<option value="longEdge">Long edge</option>
<option value="percent">Percent</option>
</select>
</label>
{opts.resize === 'longEdge' && (
<label className="field narrow">
<span>Pixels</span>
<input
type="number"
min={200}
max={20000}
step={100}
value={opts.longEdge}
onChange={(e) => patch({ longEdge: Number(e.target.value) || 0 })}
disabled={busy}
/>
</label>
)}
{opts.resize === 'percent' && (
<label className="field narrow">
<span>Percent</span>
<input
type="number"
min={5}
max={200}
value={opts.percent}
onChange={(e) => patch({ percent: Number(e.target.value) || 100 })}
disabled={busy}
/>
</label>
)}
{photos.length > 1 && (
<label className="field">
<span>Delivery</span>
<select
value={opts.zip ? 'zip' : 'files'}
onChange={(e) => patch({ zip: e.target.value === 'zip' })}
disabled={busy}
>
<option value="zip">One ZIP file</option>
<option value="files">Separate files</option>
</select>
</label>
)}
</div>
{(opts.format === 'jpeg' || opts.format === 'webp') && (
<label className="field">
<span>Quality · {opts.quality}</span>
<input
type="range"
min={40}
max={100}
value={opts.quality}
onChange={(e) => patch({ quality: Number(e.target.value) })}
disabled={busy}
/>
</label>
)}
{sample && <ExportDetailStrip photo={sample} size={previewSize} />}
<label className="field">
<span>File name</span>
<input
value={opts.nameTemplate}
onChange={(e) => patch({ nameTemplate: e.target.value })}
disabled={busy}
placeholder="{name}"
/>
</label>
<p className="muted small">
Tokens: <code>{'{name}'}</code> <code>{'{date}'}</code> <code>{'{time}'}</code>{' '}
<code>{'{index}'}</code> · first file: <code>{sampleName}</code>
</p>
<div className="export-recipes">
<label className="field">
<span>Recipe</span>
<select
value={recipeId}
onChange={(e) => {
const id = e.target.value;
setRecipeId(id);
const recipe = recipes.find((item) => item.id === id);
if (recipe) setOpts({ ...DEFAULT_EXPORT, ...recipe.options });
}}
disabled={busy || !recipes.length}
>
<option value="">Custom settings</option>
{recipes.map((recipe) => (
<option key={recipe.id} value={recipe.id}>
{recipe.name}
</option>
))}
</select>
</label>
<button
className="btn ghost small"
onClick={() => {
const name = window.prompt('Export recipe name', 'Client delivery');
if (name?.trim()) {
onSaveRecipe(name.trim(), opts);
setRecipeId('');
}
}}
disabled={busy}
>
Save recipe
</button>
{recipeId && (
<button
className="icon-btn danger"
title="Delete recipe"
onClick={() => {
onDeleteRecipe(recipeId);
setRecipeId('');
}}
>
🗑
</button>
)}
</div>
<div className="subhead">
<span>Output</span>
</div>
<Slider
label="Output sharpening"
min={0}
max={80}
value={opts.outputSharpen}
onChange={(v) => patch({ outputSharpen: v })}
format={(v) => `${Math.round(v)}`}
def={0}
/>
<label className="check-row">
<input
type="checkbox"
checked={opts.metadata}
onChange={(e) => patch({ metadata: e.target.checked })}
disabled={opts.format !== 'jpeg'}
/>
Embed title, caption, creator, copyright and keywords (JPEG)
</label>
<label className="check-row">
<input
type="checkbox"
checked={opts.embedProfile}
onChange={(e) => patch({ embedProfile: e.target.checked })}
disabled={opts.format === 'webp' || opts.format === 'png'}
/>
Embed sRGB profile (JPEG/TIFF)
</label>
<div className="subhead">
<span>Watermark</span>
<button
className={`chip tiny ${opts.watermark.enabled ? 'on' : ''}`}
disabled={opts.format === 'tiff16'}
onClick={() => patchWatermark({ enabled: !opts.watermark.enabled })}
>
{opts.watermark.enabled ? 'On' : 'Off'}
</button>
</div>
{opts.format === 'tiff16' && (
<p className="muted small">
16-bit TIFF is a delivery master; watermarking and JPEG metadata are not applied.
</p>
)}
{opts.watermark.enabled && (
<>
<label className="field">
<span>Text</span>
<input
value={opts.watermark.text}
onChange={(e) => patchWatermark({ text: e.target.value })}
placeholder="© Your studio"
disabled={busy}
/>
</label>
<div className="field-row">
<label className="field">
<span>Position</span>
<select
value={opts.watermark.position}
onChange={(e) => patchWatermark({ position: e.target.value as WatermarkPosition })}
disabled={busy}
>
<option value="br">Bottom right</option>
<option value="bl">Bottom left</option>
<option value="tr">Top right</option>
<option value="tl">Top left</option>
<option value="center">Centre</option>
</select>
</label>
<label className="field narrow">
<span>Size</span>
<input
type="number"
min={1}
max={20}
value={opts.watermark.size}
onChange={(e) => patchWatermark({ size: Number(e.target.value) || 1 })}
disabled={busy}
/>
</label>
<label className="field narrow">
<span>Opacity</span>
<input
type="number"
min={5}
max={100}
value={opts.watermark.opacity}
onChange={(e) => patchWatermark({ opacity: Number(e.target.value) || 5 })}
disabled={busy}
/>
</label>
</div>
</>
)}
{busy && progress.total > 0 && (
<div className="progress">
<div className="progress-bar">
<div
className="progress-fill"
style={{ width: `${(progress.done / progress.total) * 100}%` }}
/>
</div>
<div className="muted small">
{stage === 'pack'
? `Packing ${progress.total} photos into a ZIP…`
: `${progress.done} / ${progress.total}`}
</div>
</div>
)}
{error && <div className="banner error">{error}</div>}
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose} disabled={busy}>
Cancel
</button>
<button className="btn primary" onClick={() => void run()} disabled={busy || !photos.length}>
{busy
? stage === 'pack'
? 'Packing ZIP…'
: 'Exporting…'
: opts.zip && photos.length > 1
? `Export ${photos.length} as ZIP`
: `Export ${photos.length}`}
</button>
</footer>
</div>
</div>
);
}
+270
View File
@@ -0,0 +1,270 @@
import { COLOR_LABELS, isEdited } from '../lib/edits';
import { usePersistentState } from '../lib/usePersistentState';
import type { ColorLabel, Filters, Flag, PhotoRecord, SortKey } from '../types';
interface Props {
filters: Filters;
setFilters: (next: Filters) => void;
count: number;
total: number;
/** Photos in the current scope before the filter controls are applied. */
scopePhotos: PhotoRecord[];
reviewCounts: { approved: number; changes: number };
sort: SortKey;
setSort: (s: SortKey) => void;
asc: boolean;
setAsc: (v: boolean) => void;
/** photos in this scope that a client has picked */
proofCount: number;
onSaveCollection: () => void;
}
const FLAGS: { value: Flag | 'any'; label: string }[] = [
{ value: 'any', label: 'Any' },
{ value: 'pick', label: 'Picked' },
{ value: 'none', label: 'Unflagged' },
{ value: 'reject', label: 'Rejected' },
];
const EMPTY_FILTERS: Filters = {
minRating: 0,
flag: 'any',
colors: [],
text: '',
editedOnly: false,
unrated: false,
proofed: false,
clientStatus: 'any',
};
export default function FilterBar({
filters,
setFilters,
count,
total,
scopePhotos,
reviewCounts,
sort,
setSort,
asc,
setAsc,
proofCount,
onSaveCollection,
}: Props) {
const [collapsed, setCollapsed] = usePersistentState('library.filters.collapsed', false);
const patch = (p: Partial<Filters>) => setFilters({ ...filters, ...p });
const countWhere = (test: (photo: PhotoRecord) => boolean) =>
scopePhotos.reduce((sum, photo) => sum + (test(photo) ? 1 : 0), 0);
const ratingCounts = [0, 1, 2, 3, 4, 5].map((n) =>
n === 0 ? scopePhotos.length : countWhere((photo) => photo.rating >= n),
);
const unratedCount = countWhere((photo) => photo.rating === 0);
const flagCounts = FLAGS.map((flag) =>
flag.value === 'any'
? scopePhotos.length
: countWhere((photo) => photo.flag === flag.value),
);
const colorCounts = COLOR_LABELS.map((color) =>
countWhere((photo) => photo.color === color.value),
);
const editedCount = countWhere((photo) => isEdited(photo.edits));
const active =
filters.minRating > 0 ||
filters.flag !== 'any' ||
filters.colors.length > 0 ||
!!filters.text ||
filters.editedOnly ||
filters.unrated ||
filters.proofed ||
filters.clientStatus !== 'any';
const toggleColor = (color: ColorLabel) => {
const exists = filters.colors.includes(color);
patch({ colors: exists ? filters.colors.filter((c) => c !== color) : [...filters.colors, color] });
};
const summary = [
filters.minRating > 0 ? `${filters.minRating}★+` : '',
filters.unrated ? 'Unrated' : '',
filters.flag !== 'any' ? FLAGS.find((f) => f.value === filters.flag)?.label ?? '' : '',
filters.colors.length ? `${filters.colors.length} label${filters.colors.length === 1 ? '' : 's'}` : '',
filters.text ? `“${filters.text}”` : '',
filters.editedOnly ? 'Edited' : '',
filters.proofed ? 'Client picks' : '',
filters.clientStatus === 'approved' ? 'Approved' : filters.clientStatus === 'changes' ? 'Changes' : '',
]
.filter(Boolean)
.join(' · ');
return (
<div className={`filterbar ${collapsed ? 'collapsed' : ''}`}>
<button
className="filter-collapse"
onClick={() => setCollapsed((open) => !open)}
aria-expanded={!collapsed}
title={collapsed ? 'Expand filters' : 'Collapse filters'}
>
<span className="chev">{collapsed ? '▸' : '▾'}</span>
<span>Filters</span>
</button>
{collapsed ? (
<>
<span className={`filter-summary ${active ? '' : 'muted'}`}>
{active ? summary : 'No filters applied'}
</span>
{active && (
<button className="chip ghost" onClick={() => setFilters(EMPTY_FILTERS)}>
Clear
</button>
)}
</>
) : (
<>
<div className="filter-group">
<span className="filter-label">Rating</span>
<div className="rating-filter">
{[0, 1, 2, 3, 4, 5].map((n) => (
<button
key={n}
className={`chip ${filters.minRating === n ? 'on' : ''}`}
onClick={() => patch({ minRating: n, unrated: false })}
title={`${n === 0 ? 'Any rating' : `${n} stars and up`} · ${ratingCounts[n]} photo${ratingCounts[n] === 1 ? '' : 's'}`}
>
{n === 0 ? 'Any' : `${n}★+`}
<span className="chip-count">{ratingCounts[n]}</span>
</button>
))}
<button
className={`chip ${filters.unrated ? 'on' : ''}`}
onClick={() => patch({ unrated: !filters.unrated, minRating: 0 })}
title={`Only photos with no rating · ${unratedCount} photo${unratedCount === 1 ? '' : 's'}`}
>
Unrated
<span className="chip-count">{unratedCount}</span>
</button>
</div>
</div>
<div className="filter-group">
<span className="filter-label">Flag</span>
<div className="rating-filter">
{FLAGS.map((f, index) => (
<button
key={f.value}
className={`chip ${filters.flag === f.value ? 'on' : ''}`}
onClick={() => patch({ flag: f.value })}
title={`${f.label} · ${flagCounts[index]} photo${flagCounts[index] === 1 ? '' : 's'}`}
>
{f.label}
<span className="chip-count">{flagCounts[index]}</span>
</button>
))}
</div>
</div>
<div className="filter-group">
<span className="filter-label">Label</span>
<div className="color-filter">
{COLOR_LABELS.map((c, index) => (
<button
key={c.value}
className={`swatch ${filters.colors.includes(c.value) ? 'on' : ''}`}
style={{ background: c.hex }}
title={`${c.name} · ${colorCounts[index]} photo${colorCounts[index] === 1 ? '' : 's'}`}
aria-label={`${c.name} label, ${colorCounts[index]} photos`}
onClick={() => toggleColor(c.value)}
/>
))}
</div>
</div>
<div className="filter-group grow">
<input
className="search"
type="search"
placeholder="Search name, camera, lens, keywords…"
value={filters.text}
onChange={(e) => patch({ text: e.target.value })}
/>
</div>
<button
className={`chip ${filters.editedOnly ? 'on' : ''}`}
onClick={() => patch({ editedOnly: !filters.editedOnly })}
title={`Only show photos with develop adjustments · ${editedCount}`}
>
Edited
<span className="chip-count">{editedCount}</span>
</button>
{proofCount > 0 && (
<button
className={`chip proof-chip ${filters.proofed ? 'on' : ''}`}
onClick={() => patch({ proofed: !filters.proofed })}
title="Only show photos a client picked in the proofing gallery"
>
♥ Client picks {proofCount}
</button>
)}
<div className="filter-group">
<span className="filter-label">Review</span>
<div className="rating-filter">
<button
className={`chip ${filters.clientStatus === 'approved' ? 'on' : ''}`}
onClick={() => patch({ clientStatus: filters.clientStatus === 'approved' ? 'any' : 'approved' })}
title={`Photos a client approved in the proofing gallery · ${reviewCounts.approved}`}
>
Approved
<span className="chip-count">{reviewCounts.approved}</span>
</button>
<button
className={`chip ${filters.clientStatus === 'changes' ? 'on' : ''}`}
onClick={() => patch({ clientStatus: filters.clientStatus === 'changes' ? 'any' : 'changes' })}
title={`Photos a client marked for changes · ${reviewCounts.changes}`}
>
Changes
<span className="chip-count">{reviewCounts.changes}</span>
</button>
</div>
</div>
<div className="filter-group">
<span className="filter-label">Sort</span>
<select className="select" value={sort} onChange={(e) => setSort(e.target.value as SortKey)}>
<option value="taken">Capture date</option>
<option value="added">Import date</option>
<option value="name">File name</option>
<option value="rating">Rating</option>
<option value="custom">Manual order</option>
</select>
<button
className="icon-btn"
title={asc ? 'Ascending' : 'Descending'}
onClick={() => setAsc(!asc)}
disabled={sort === 'custom'}
>
{asc ? '↑' : '↓'}
</button>
</div>
<button className="chip ghost" onClick={onSaveCollection} title="Save the current filters and sort as a smart collection">
Save view
</button>
{active && (
<button className="chip ghost" onClick={() => setFilters(EMPTY_FILTERS)}>
Clear filters
</button>
)}
</>
)}
<div className="filter-count">
{count}
{count !== total ? ` / ${total}` : ''} shown
</div>
</div>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { useEffect, useRef } from 'react';
import type { Histogram as HistogramData } from '../gl/renderer';
export default function Histogram({
data,
version,
clipping,
onClipping,
}: {
data: HistogramData | null;
version: number;
clipping?: 'highlights' | 'shadows' | null;
onClipping?: (next: 'highlights' | 'shadows' | null) => void;
}) {
const ref = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = ref.current;
if (!canvas) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const rect = canvas.getBoundingClientRect();
const w = Math.max(1, Math.round(rect.width * dpr));
const h = Math.max(1, Math.round(rect.height * dpr));
if (canvas.width !== w) canvas.width = w;
if (canvas.height !== h) canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = '#121214';
ctx.fillRect(0, 0, w, h);
// grid
ctx.strokeStyle = 'rgba(255,255,255,0.06)';
ctx.lineWidth = 1;
for (let i = 1; i < 4; i++) {
const x = (i / 4) * w;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, h);
ctx.stroke();
}
if (!data) return;
let peak = 0;
for (let i = 1; i < 255; i++) {
peak = Math.max(peak, data.r[i], data.g[i], data.b[i]);
}
if (peak <= 0) return;
const scale = (v: number) => Math.pow(v / peak, 0.42);
const drawChannel = (bins: Uint32Array, color: string) => {
ctx.beginPath();
ctx.moveTo(0, h);
for (let i = 0; i < 256; i++) {
const x = (i / 255) * w;
const y = h - scale(bins[i]) * (h - 2);
ctx.lineTo(x, y);
}
ctx.lineTo(w, h);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
};
ctx.globalCompositeOperation = 'lighter';
drawChannel(data.r, 'rgba(220,64,64,0.55)');
drawChannel(data.g, 'rgba(64,200,96,0.55)');
drawChannel(data.b, 'rgba(72,120,240,0.55)');
ctx.globalCompositeOperation = 'source-over';
}, [data, version]);
return (
<div className="histo-box">
<canvas className="histogram" ref={ref} />
<button
className={`clip-tri shadows ${clipping === 'shadows' ? 'on' : ''}`}
title="Show shadow clipping (Shift+J)"
aria-pressed={clipping === 'shadows'}
onClick={() => onClipping?.(clipping === 'shadows' ? null : 'shadows')}
/>
<button
className={`clip-tri highlights ${clipping === 'highlights' ? 'on' : ''}`}
title="Show highlight clipping (J)"
aria-pressed={clipping === 'highlights'}
onClick={() => onClipping?.(clipping === 'highlights' ? null : 'highlights')}
/>
</div>
);
}
+307
View File
@@ -0,0 +1,307 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { CloudImport, ImportProgress } from '../lib/import';
import { importFiles, isSupportedFile } from '../lib/import';
import { isRawFile, RAW_ACCEPT } from '../lib/raw';
import type { EventRecord, PhotoRecord } from '../types';
interface Props {
events: EventRecord[];
initialEventId: string;
initialFiles: File[];
/** Records already in the catalog, used to skip accidental re-imports. */
existing: PhotoRecord[];
onClose: () => void;
onImported: (photos: PhotoRecord[], eventId: string) => void;
onCreateEvent: (name: string) => Promise<EventRecord>;
cloud?: CloudImport | null;
onNeedServer: () => void;
}
export default function ImportModal({
events,
initialEventId,
initialFiles,
existing,
onClose,
onImported,
onCreateEvent,
cloud,
onNeedServer,
}: Props) {
const startId = initialEventId !== 'all' && initialEventId !== 'unsorted' ? initialEventId : events[0]?.id ?? '__new';
const [eventId, setEventId] = useState(startId);
const [newName, setNewName] = useState('');
const [files, setFiles] = useState<File[]>(initialFiles);
const [dragOver, setDragOver] = useState(false);
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState<ImportProgress | null>(null);
const [failures, setFailures] = useState<string[]>([]);
const [allowDuplicates, setAllowDuplicates] = useState(false);
const [summary, setSummary] = useState<{
imported: number;
failed: number;
skipped: number;
cancelled: boolean;
} | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const abortRef = useRef<AbortController | null>(null);
const rawCount = files.filter(isRawFile).length;
const existingKeys = useMemo(
() => new Set(existing.map((photo) => `${photo.name.toLowerCase()}:${photo.size}`)),
[existing],
);
const duplicateFiles = useMemo(
() => files.filter((file) => existingKeys.has(`${file.name.toLowerCase()}:${file.size}`)),
[existingKeys, files],
);
const readyFiles = allowDuplicates ? files : files.filter((file) => !duplicateFiles.includes(file));
useEffect(() => {
// Capture phase: Escape closes this dialog even while a photo is open behind it.
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const addFiles = (list: FileList | null) => {
if (!list) return;
setSummary(null);
const incoming = Array.from(list).filter(isSupportedFile);
setFiles((prev) => {
const seen = new Set(prev.map((f) => `${f.name}:${f.size}`));
return [...prev, ...incoming.filter((f) => !seen.has(`${f.name}:${f.size}`))];
});
};
const run = async () => {
if (!readyFiles.length || busy) return;
setBusy(true);
setFailures([]);
setSummary(null);
const controller = new AbortController();
abortRef.current = controller;
try {
let targetId = eventId;
if (targetId === '__new') {
const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`);
targetId = created.id;
}
const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal);
if (result.photos.length) onImported(result.photos, targetId);
const skipped = allowDuplicates ? 0 : duplicateFiles.length;
setSummary({
imported: result.photos.length,
failed: result.failed.length,
skipped,
cancelled: Boolean(result.cancelled),
});
if (result.failed.length) setFailures(result.failed.map((f) => `${f.name} — ${f.reason}`));
} catch (err) {
setFailures([err instanceof Error ? err.message : 'Import failed']);
} finally {
setBusy(false);
setProgress(null);
abortRef.current = null;
}
};
const cancel = () => {
abortRef.current?.abort();
setProgress((current) =>
current ? { ...current, current: 'Cancelling after the files already in progress…' } : current,
);
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div className="modal">
<header className="modal-head">
<h2>Import photos</h2>
<button className="icon-btn" onClick={onClose} disabled={busy}>
✕
</button>
</header>
<div className="modal-body">
<label className="field">
<span>Event / album</span>
<select value={eventId} onChange={(e) => setEventId(e.target.value)} disabled={busy}>
{events.map((ev) => (
<option key={ev.id} value={ev.id}>
{ev.name}
</option>
))}
<option value="__new">+ New event…</option>
</select>
</label>
{eventId === '__new' && (
<label className="field">
<span>New event name</span>
<input
value={newName}
placeholder={`Event ${new Date().toLocaleDateString()}`}
onChange={(e) => setNewName(e.target.value)}
disabled={busy}
/>
</label>
)}
<div
className={`dropzone ${dragOver ? 'over' : ''}`}
onDragOver={(e) => {
e.preventDefault();
setDragOver(true);
}}
onDragLeave={() => setDragOver(false)}
onDrop={(e) => {
e.preventDefault();
setDragOver(false);
addFiles(e.dataTransfer.files);
}}
onClick={() => inputRef.current?.click()}
>
<div className="dropzone-icon">⤒</div>
<div>
<strong>Drop photos here</strong>
<p className="muted">
or click to choose files. JPEG, PNG, WebP, AVIF, TIFF and camera raw (CR2, CR3, NEF,
ARW, ORF, RW2, RAF, DNG, PEF…) — raw needs the team server.
</p>
</div>
<input
ref={inputRef}
type="file"
accept={`image/*,${RAW_ACCEPT}`}
multiple
hidden
onChange={(e) => addFiles(e.target.files)}
/>
</div>
{files.length > 0 && (
<div className="file-summary">
<span>
{readyFiles.length} file{readyFiles.length === 1 ? '' : 's'} ready ·{' '}
{(readyFiles.reduce((sum, f) => sum + f.size, 0) / (1024 * 1024)).toFixed(1)} MB
{rawCount > 0 ? ` · ${rawCount} raw` : ''}
</span>
<button className="link-btn" onClick={() => { setFiles([]); setSummary(null); }} disabled={busy}>
Clear
</button>
</div>
)}
{duplicateFiles.length > 0 && !summary && (
<div className="banner info import-duplicates">
<div>
<strong>
{duplicateFiles.length} file{duplicateFiles.length === 1 ? ' is' : 's are'} already in the catalog.
</strong>{' '}
{allowDuplicates
? 'They will be imported again as new copies.'
: 'They will be skipped unless you choose to include them.'}
</div>
<button
className="btn ghost small"
onClick={() => setAllowDuplicates((value) => !value)}
disabled={busy}
>
{allowDuplicates ? 'Skip duplicates' : 'Include anyway'}
</button>
</div>
)}
{rawCount > 0 && !cloud && (
<div className="banner warn">
<strong>
{rawCount} raw file{rawCount === 1 ? '' : 's'} cannot be read by the browser.
</strong>{' '}
They are decoded by the team server, so sign in before importing — or import them later
from the library.
<button className="btn primary small banner-action" onClick={onNeedServer} disabled={busy}>
Sign in to the server
</button>
</div>
)}
{rawCount > 0 && cloud && (
<div className="banner info">
Raw files are demosaiced by the server (LibRaw), a few at a time in parallel. Each file
usually takes 2–4 seconds.
</div>
)}
{progress && (
<div className="progress">
<div className="progress-bar">
<div
className="progress-fill"
style={{ width: `${progress.total ? (progress.done / progress.total) * 100 : 0}%` }}
/>
</div>
<div className="muted small">
{progress.done} / {progress.total} {progress.current ? `· ${progress.current}` : ''}
</div>
</div>
)}
{summary && (
<div className="import-summary">
<strong>
{summary.cancelled ? 'Import cancelled' : 'Import complete'}
</strong>
<span>
{summary.imported} imported
{summary.skipped ? ` · ${summary.skipped} duplicate${summary.skipped === 1 ? '' : 's'} skipped` : ''}
{summary.failed ? ` · ${summary.failed} failed` : ''}
</span>
<p className="muted small">
{summary.cancelled
? 'Files already in progress were allowed to finish. The imported photos are in the catalog.'
: 'New photos are selected in the library and ready to review.'}
</p>
</div>
)}
{failures.length > 0 && (
<div className="failures">
<strong>Some files could not be imported</strong>
<ul>
{failures.map((f) => (
<li key={f}>{f}</li>
))}
</ul>
</div>
)}
</div>
<footer className="modal-foot">
{summary ? (
<button className="btn primary" onClick={onClose}>
Done
</button>
) : (
<>
<button className="btn ghost" onClick={busy ? cancel : onClose}>
{busy ? 'Cancel import' : 'Cancel'}
</button>
<button
className="btn primary"
onClick={() => void run()}
disabled={busy || !readyFiles.length}
>
{busy ? 'Importing…' : `Import ${readyFiles.length || ''}`}
</button>
</>
)}
</footer>
</div>
</div>
);
}
+193
View File
@@ -0,0 +1,193 @@
import { useEffect, useState } from 'react';
import { ApiError, loadInvite, register } from '../lib/api';
import type { InviteInfo } from '../lib/api';
interface Props {
token: string;
}
const fmtDate = (ms: number | null) =>
ms ? new Date(ms).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : '';
const STATUS_COPY: Record<string, { title: string; body: string }> = {
accepted: {
title: 'This invite has already been used',
body: 'Each invite link works once. Sign in if the account is yours, or ask an admin for a fresh link.',
},
expired: {
title: 'This invite has expired',
body: 'Invite links are time-limited. Ask an admin to send you a new one.',
},
revoked: {
title: 'This invite was turned off',
body: 'An admin revoked this link. Ask them for a new invite if you still need access.',
},
};
/** Public signup screen reached from an admin's single-use invite link. */
export default function JoinPage({ token }: Props) {
const [invite, setInvite] = useState<InviteInfo | null>(null);
const [missing, setMissing] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [password, setPassword] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
loadInvite(token)
.then((next) => {
if (!alive) return;
setInvite(next);
setEmail(next.email);
})
.catch((err) => {
if (!alive) return;
if (err instanceof ApiError && err.status === 404) setMissing(true);
else setLoadError(err instanceof Error ? err.message : 'Could not check this invite');
});
return () => {
alive = false;
};
}, [token]);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (!invite || invite.status !== 'pending' || busy) return;
if (password.length < 8) {
setError('Use at least 8 characters for the password');
return;
}
setBusy(true);
setError(null);
try {
await register({
email: email.trim(),
password,
name: name.trim(),
inviteToken: token,
});
window.location.assign('/');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not create the account');
setBusy(false);
}
};
const state = missing ? 'missing' : invite?.status;
const lockedEmail = Boolean(invite?.email);
const copy =
state === 'missing'
? {
title: 'This invite link is not valid',
body: 'Check the link you were sent, or ask an admin for a new invite.',
}
: state && STATUS_COPY[state]
? STATUS_COPY[state]
: null;
return (
<div className="join-page">
<div className="join-brand">
<span className="brand-dot" />
LUMINARY
</div>
<main className="join-card">
{!invite && !missing && !loadError && <p className="muted small">Checking your invite…</p>}
{loadError && (
<>
<span className="join-eyebrow">Invite</span>
<h1>Can’t reach the server</h1>
<p className="muted">{loadError}</p>
<a className="btn ghost wide" href="/">
Go to Luminary
</a>
</>
)}
{copy && (
<>
<span className="join-eyebrow">Invite</span>
<h1>{copy.title}</h1>
<p className="muted">{copy.body}</p>
<a className="btn primary wide" href="/">
Go to sign in
</a>
</>
)}
{invite?.status === 'pending' && (
<>
<span className="join-eyebrow">You’re invited</span>
<h1>Join the studio</h1>
<p className="muted join-lead">
{lockedEmail
? `Create your account for ${invite.email}. This link works once.`
: 'Create your account to start editing, proofing and sharing photos. This link works once.'}
</p>
<form className="join-form" onSubmit={submit}>
<label className="field">
<span>Email</span>
<input
type="email"
required
autoComplete="username"
autoFocus={!lockedEmail}
readOnly={lockedEmail}
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@studio.com"
/>
</label>
<label className="field">
<span>Display name</span>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Optional"
autoComplete="name"
/>
</label>
<label className="field">
<span>Password</span>
<input
type="password"
required
autoComplete="new-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="At least 8 characters"
/>
</label>
{error && <div className="banner error">{error}</div>}
<button
className="btn primary wide"
type="submit"
disabled={busy || !email.trim() || password.length < 8}
>
{busy ? 'Creating account…' : 'Create account'}
</button>
</form>
<p className="join-meta">
You’ll join as a {invite.role === 'admin' ? 'administrator' : 'member'}
{invite.expiresAt ? ` · link expires ${fmtDate(invite.expiresAt)}` : ''}
</p>
<p className="join-foot">
Already have an account? <a href="/">Sign in</a>
</p>
</>
)}
</main>
</div>
);
}
+152
View File
@@ -0,0 +1,152 @@
import { useEffect, useState } from 'react';
import {
loadCameraLensDefaults,
removeCameraLensDefault,
type CameraLensDefault,
} from '../lib/lensDefaults';
interface Props {
onClose: () => void;
/** Called after a saved row is removed so an open Optics panel can refresh. */
onChanged?: () => void;
}
const correctionLabel = (entry: CameraLensDefault) => {
const corrections = entry.profile.corrections;
const enabled = [
corrections.distortion ? 'distortion' : '',
corrections.tca ? 'chromatic aberration' : '',
corrections.vignetting ? 'vignetting' : '',
].filter(Boolean);
return enabled.length ? enabled.join(' · ') : 'no corrections enabled';
};
export default function LensDefaultsModal({ onClose, onChanged }: Props) {
const [defaults, setDefaults] = useState<CameraLensDefault[] | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
loadCameraLensDefaults()
.then((saved) => alive && setDefaults(saved))
.catch((err) => {
if (!alive) return;
setDefaults([]);
setError(err instanceof Error ? err.message : 'Could not load saved defaults');
});
return () => {
alive = false;
};
}, []);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const remove = async (entry: CameraLensDefault) => {
const key = `${entry.camera}\u0000${entry.exifLens}`;
if (busy) return;
setBusy(key);
setError(null);
try {
await removeCameraLensDefault({ camera: entry.camera, lens: entry.exifLens });
setDefaults((current) =>
current?.filter(
(saved) => saved.camera !== entry.camera || saved.exifLens !== entry.exifLens,
) ?? [],
);
onChanged?.();
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not remove that default');
} finally {
setBusy(null);
}
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal lens-defaults-modal">
<header className="modal-head">
<div>
<span className="settings-kicker">Settings</span>
<h2>Camera lens defaults</h2>
</div>
<button className="icon-btn" onClick={onClose} title="Close">
✕
</button>
</header>
<div className="modal-body">
<p className="muted small lens-defaults-lead">
These profiles apply automatically on this browser when a new import has the same camera
and EXIF lens. Removing one only affects future imports.
</p>
{defaults === null ? (
<p className="muted small">Loading saved defaults…</p>
) : defaults.length === 0 ? (
<div className="lens-defaults-empty">
<strong>No camera-lens defaults saved</strong>
<p className="muted small">
Open the Optics panel in Develop, choose a lens profile, then use “Set as camera
default”.
</p>
</div>
) : (
<div className="lens-defaults-list">
{defaults.map((entry) => {
const key = `${entry.camera}\u0000${entry.exifLens}`;
return (
<article className="lens-default-item" key={key}>
<div className="lens-default-main">
<div className="lens-default-title">
<strong>
{entry.profile.maker} {entry.profile.model}
</strong>
<span className="muted small">crop {entry.profile.crop}×</span>
</div>
<p className="lens-default-match">
{entry.camera} <span className="muted">+</span> {entry.exifLens}
</p>
<p className="muted small lens-default-meta">
{correctionLabel(entry)} · saved{' '}
{new Date(entry.updatedAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
})}
</p>
</div>
<button
className="btn ghost small"
disabled={busy === key}
onClick={() => void remove(entry)}
>
{busy === key ? 'Removing…' : 'Remove'}
</button>
</article>
);
})}
</div>
)}
{error && <p className="small lens-error">{error}</p>}
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose}>
Done
</button>
</footer>
</div>
</div>
);
}
+520
View File
@@ -0,0 +1,520 @@
import { useEffect, useRef, useState } from 'react';
import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits';
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
import type { ColorLabel, Flag, PhotoRecord } from '../types';
import Stars, { ColorSwatches, FlagButtons } from './Stars';
interface Props {
photos: PhotoRecord[];
totalCount: number;
selected: string[];
onSelect: (id: string, e: React.MouseEvent) => void;
onContextMenu: (e: React.MouseEvent, id: string) => void;
onOpen: (id: string) => void;
onRate: (id: string, rating: number) => void;
onBulkRate: (rating: number) => void;
onBulkFlag: (flag: Flag) => void;
onBulkColor: (color: ColorLabel) => void;
onDelete: () => void;
onExport: () => void;
onCompare: () => void;
onStack: () => void;
onVirtualCopy: () => void;
onMerge: () => void;
onPrint: () => void;
stacks: Map<string, { count: number; expanded: boolean }>;
onToggleStack: (id: string) => void;
onImport: () => void;
onDropFiles: (files: File[]) => void;
onClearSelection: () => void;
onReorder: (ids: string[], targetId: string | null) => void;
/** rubber-band selection: the complete new selection */
onMarqueeSelect: (ids: string[]) => void;
/** client proofing picks per photo, shown as a badge */
proofCounts: Map<string, number>;
proofStatus: Map<string, { approved: number; changes: number; comments: number }>;
}
function fmtSize(bytes: number) {
if (bytes > 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
export default function LibraryGrid({
photos,
totalCount,
selected,
onSelect,
onContextMenu,
onOpen,
onRate,
onBulkRate,
onBulkFlag,
onBulkColor,
onDelete,
onExport,
onCompare,
onStack,
onVirtualCopy,
onMerge,
onPrint,
stacks,
onToggleStack,
onImport,
onDropFiles,
onClearSelection,
onReorder,
onMarqueeSelect,
proofCounts,
proofStatus,
}: Props) {
const gridRef = useRef<HTMLDivElement>(null);
const band = useRef<{ sx: number; sy: number; base: string[]; moved: boolean; box: DOMRect } | null>(null);
const [bandRect, setBandRect] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
const virtualize = photos.length > 140;
const [viewWindow, setViewWindow] = useState({
start: 0,
end: Math.min(photos.length, 140),
top: 0,
bottom: 0,
});
const selectedSet = new Set(selected);
useEffect(() => {
if (!virtualize) {
setViewWindow({ start: 0, end: photos.length, top: 0, bottom: 0 });
return;
}
const grid = gridRef.current;
if (!grid) return;
let frame = 0;
const measure = () => {
const card = grid.querySelector<HTMLElement>('.card');
if (!card) {
if (viewWindow.start >= photos.length) {
setViewWindow({ start: 0, end: Math.min(photos.length, 140), top: 0, bottom: 0 });
}
return;
}
const box = card.getBoundingClientRect();
const style = getComputedStyle(grid);
const gapX = Number.parseFloat(style.columnGap) || 12;
const gapY = Number.parseFloat(style.rowGap) || 12;
const horizontalPadding =
(Number.parseFloat(style.paddingLeft) || 0) + (Number.parseFloat(style.paddingRight) || 0);
const columns = Math.max(
1,
Math.round((grid.clientWidth - horizontalPadding + gapX) / (box.width + gapX)),
);
const rowStep = box.height + gapY;
const firstRow = Math.max(0, Math.floor(grid.scrollTop / rowStep) - 2);
const lastRow = Math.ceil((grid.scrollTop + grid.clientHeight) / rowStep) + 2;
const start = Math.min(photos.length, firstRow * columns);
const end = Math.min(photos.length, Math.max(start + columns, lastRow * columns));
const totalRows = Math.ceil(photos.length / columns);
const top = firstRow * rowStep;
const bottom = Math.max(0, totalRows - lastRow) * rowStep;
setViewWindow((current) =>
current.start === start &&
current.end === end &&
current.top === top &&
current.bottom === bottom
? current
: { start, end, top, bottom },
);
};
const schedule = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(measure);
};
const observer = new ResizeObserver(schedule);
observer.observe(grid);
grid.addEventListener('scroll', schedule, { passive: true });
schedule();
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
grid.removeEventListener('scroll', schedule);
};
}, [photos.length, virtualize, viewWindow.start]);
const someSelected = selected.length > 0;
const sharedRating = (() => {
if (!someSelected) return 0;
const rated = photos.filter((p) => selectedSet.has(p.id));
if (!rated.length) return 0;
const first = rated[0].rating;
return rated.every((p) => p.rating === first) ? first : 0;
})();
if (!photos.length) {
return (
<div
className="grid-empty"
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
const ids = draggedPhotoIds();
if (ids.length) { onReorder(ids, null);
endDrag();
return;
}
onDropFiles(Array.from(e.dataTransfer.files));
}}
ref={gridRef}
onPointerDown={(e) => {
const grid = gridRef.current;
// A band starts on empty grid space; cards keep their own click/drag.
if (!grid || e.button !== 0 || e.target !== grid) return;
e.preventDefault();
const box = grid.getBoundingClientRect();
band.current = {
sx: e.clientX,
sy: e.clientY,
base: e.shiftKey || e.metaKey || e.ctrlKey ? [...selected] : [],
moved: false,
box,
};
setBandRect({ x: e.clientX - box.left + grid.scrollLeft, y: e.clientY - box.top + grid.scrollTop, w: 0, h: 0 });
grid.setPointerCapture(e.pointerId);
}}
onPointerMove={(e) => {
const grid = gridRef.current;
const start = band.current;
if (!grid || !start) return;
const left = Math.min(start.sx, e.clientX);
const top = Math.min(start.sy, e.clientY);
const right = Math.max(start.sx, e.clientX);
const bottom = Math.max(start.sy, e.clientY);
if (Math.abs(e.clientX - start.sx) > 3 || Math.abs(e.clientY - start.sy) > 3) start.moved = true;
setBandRect({
x: left - start.box.left + grid.scrollLeft,
y: top - start.box.top + grid.scrollTop,
w: right - left,
h: bottom - top,
});
if (!start.moved) return;
const hits: string[] = [];
for (const el of grid.querySelectorAll<HTMLElement>('.card')) {
const r = el.getBoundingClientRect();
if (r.right > left && r.left < right && r.bottom > top && r.top < bottom) {
const id = el.dataset.id;
if (id) hits.push(id);
}
}
onMarqueeSelect([...start.base, ...hits.filter((id) => !start.base.includes(id))]);
}}
onPointerUp={(e) => {
const grid = gridRef.current;
const start = band.current;
band.current = null;
setBandRect(null);
if (!grid || !start) return;
if (grid.hasPointerCapture(e.pointerId)) grid.releasePointerCapture(e.pointerId);
if (!start.moved && !start.base.length) onClearSelection();
}}
onPointerCancel={() => {
band.current = null;
setBandRect(null);
}}
>
<div className="empty-card">
{totalCount > 0 ? (
<>
<h2>No photos match these filters</h2>
<p className="muted">Loosen the rating, flag or label filters to see more of this event.</p>
</>
) : (
<>
<h2>Your library is empty</h2>
<p className="muted">
Create an event and import a shoot. Photos are stored locally, or on your team server
when one is connected.
</p>
<ol className="quick-steps">
<li>Import a shoot into an event.</li>
<li>Rate and flag the keepers.</li>
<li>Double-click a photo to open Develop.</li>
<li>Press ? anytime for shortcuts.</li>
</ol>
<button className="btn primary" onClick={onImport}>
Import photos
</button>
<p className="muted small">
Drop JPEG, PNG, TIFF or camera raw files anywhere in this area.
</p>
</>
)}
</div>
</div>
);
}
return (
<div className="grid-area">
<div className="grid-toolbar">
{someSelected ? (
<>
<span className="selection-count">{selected.length} selected</span>
<Stars value={sharedRating} onChange={onBulkRate} size="md" title="Set rating for selection (0–5)" />
<FlagButtons value={'none'} onChange={onBulkFlag} />
<ColorSwatches value={''} onChange={onBulkColor} />
<div className="spacer" />
<button
className="btn ghost small"
onClick={onCompare}
disabled={selected.length < 2 || selected.length > 4}
title={selected.length > 4 ? 'Select 2–4 photos to compare' : 'Compare selected photos'}
>
Compare
</button>
<button className="btn ghost small" onClick={onStack} disabled={selected.length < 2}>
Stack
</button>
<button className="btn ghost small" onClick={onVirtualCopy} disabled={selected.length !== 1}>
Virtual copy
</button>
<button className="btn ghost small" onClick={onMerge} disabled={selected.length < 2}>
Merge
</button>
<button className="btn ghost small" onClick={onExport}>
Export
</button>
<button className="btn ghost small" onClick={onPrint}>
Print
</button>
<button className="btn ghost small danger" onClick={onDelete}>
Delete
</button>
<button className="icon-btn" title="Clear selection" onClick={onClearSelection}>
✕
</button>
</>
) : (
<>
<span className="muted small">
Click to select · drag on empty space to marquee · double-click to edit · 1–5 to rate ·{' '}
? for shortcuts
</span>
<div className="spacer" />
<span className="muted small">{photos.length} photos</span>
</>
)} </div>
<div className="grid"
onDragOver={(e) => {
if (draggedPhotoIds().length) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
}
}}
onDrop={(e) => {
e.preventDefault();
const ids = draggedPhotoIds();
if (ids.length) { onReorder(ids, null);
endDrag();
return;
}
onDropFiles(Array.from(e.dataTransfer.files));
}}
ref={gridRef}
onPointerDown={(e) => {
const grid = gridRef.current;
// A band starts on empty grid space; cards keep their own click/drag.
if (!grid || e.button !== 0 || e.target !== grid) return;
e.preventDefault();
const box = grid.getBoundingClientRect();
band.current = {
sx: e.clientX,
sy: e.clientY,
base: e.shiftKey || e.metaKey || e.ctrlKey ? [...selected] : [],
moved: false,
box,
};
setBandRect({ x: e.clientX - box.left + grid.scrollLeft, y: e.clientY - box.top + grid.scrollTop, w: 0, h: 0 });
grid.setPointerCapture(e.pointerId);
}}
onPointerMove={(e) => {
const grid = gridRef.current;
const start = band.current;
if (!grid || !start) return;
const left = Math.min(start.sx, e.clientX);
const top = Math.min(start.sy, e.clientY);
const right = Math.max(start.sx, e.clientX);
const bottom = Math.max(start.sy, e.clientY);
if (Math.abs(e.clientX - start.sx) > 3 || Math.abs(e.clientY - start.sy) > 3) start.moved = true;
setBandRect({
x: left - start.box.left + grid.scrollLeft,
y: top - start.box.top + grid.scrollTop,
w: right - left,
h: bottom - top,
});
if (!start.moved) return;
const hits: string[] = [];
for (const el of grid.querySelectorAll<HTMLElement>('.card')) {
const r = el.getBoundingClientRect();
if (r.right > left && r.left < right && r.bottom > top && r.top < bottom) {
const id = el.dataset.id;
if (id) hits.push(id);
}
}
onMarqueeSelect([...start.base, ...hits.filter((id) => !start.base.includes(id))]);
}}
onPointerUp={(e) => {
const grid = gridRef.current;
const start = band.current;
band.current = null;
setBandRect(null);
if (!grid || !start) return;
if (grid.hasPointerCapture(e.pointerId)) grid.releasePointerCapture(e.pointerId);
if (!start.moved && !start.base.length) onClearSelection();
}}
onPointerCancel={() => {
band.current = null;
setBandRect(null);
}}
>
{bandRect && (
<div
className="marquee"
style={{ left: bandRect.x, top: bandRect.y, width: bandRect.w, height: bandRect.h }}
/>
)}
{virtualize && viewWindow.top > 0 && (
<div className="grid-gap" style={{ height: viewWindow.top }} aria-hidden="true" />
)}
{photos.slice(viewWindow.start, viewWindow.end).map((p) => {
const color = COLOR_LABELS.find((c) => c.value === p.color);
const isDragging = draggedPhotoIds().includes(p.id);
return ( <figure
key={p.id}
data-id={p.id}
className={`card ${selectedSet.has(p.id) ? 'selected' : ''} ${p.flag === 'reject' ? 'rejected' : ''} ${isDragging ? 'dragging' : ''}`}
onClick={(e) => onSelect(p.id, e)}
onContextMenu={(e) => onContextMenu(e, p.id)}
onDoubleClick={() => onOpen(p.id)}
draggable
onDragStart={(e) => {
if ((e.target as HTMLElement).closest('.badge.stack')) {
e.preventDefault();
return;
}
const ids = selectedSet.has(p.id) && selected.length > 1 ? selected : [p.id];
startPhotoDrag(ids);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(PHOTO_DRAG, ids.join(','));
e.dataTransfer.setData('text/plain', ids.join(','));
e.currentTarget.classList.add('dragging');
}}
onDragEnd={(e) => {
e.currentTarget.classList.remove('dragging');
endDrag();
}}
onDragOver={(e) => {
if (!draggedPhotoIds().length) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
e.currentTarget.classList.add('drop-target');
}}
onDragLeave={(e) => e.currentTarget.classList.remove('drop-target')}
onDrop={(e) => {
const ids = draggedPhotoIds();
e.currentTarget.classList.remove('drop-target');
if (!ids.length) return;
e.preventDefault();
e.stopPropagation();
onReorder(ids, p.id);
endDrag();
}}
>
<div className="card-thumb">
<img
src={p.thumbUrl ?? p.thumb}
alt={p.name}
loading="lazy"
draggable={false}
style={{ transform: thumbTransform(p) }}
/>
<div className="card-badges">
{p.flag === 'pick' && <span className="badge pick">✓</span>}
{p.flag === 'reject' && <span className="badge reject">✕</span>}
{p.raw && (
<span className="badge raw" title={p.decode === 'embedded' ? 'Raw (camera preview)' : 'Raw (demosaiced)'}>
RAW
</span>
)}
{isEdited(p.edits) && (
<span className="badge edit" title="Has develop adjustments">
✎
</span>
)}
{p.copyOf && (
<span className="badge copy" title={p.copyName ?? 'Virtual copy'}>
VC
</span>
)}
{stacks.get(p.id) && (
<button
className={`badge stack ${stacks.get(p.id)?.expanded ? 'expanded' : ''}`}
title={
stacks.get(p.id)?.expanded
? 'Collapse stack'
: `Stack of ${stacks.get(p.id)?.count} — click to expand`
}
onClick={(e) => {
e.stopPropagation();
onToggleStack(p.id);
}}
onDoubleClick={(e) => e.stopPropagation()}
>
{stacks.get(p.id)?.expanded ? '▣' : '▤'} {stacks.get(p.id)?.count}
</button>
)}
{(proofCounts.get(p.id) ?? 0) > 0 && (
<span
className="badge proof"
title={`Picked by ${proofCounts.get(p.id)} client${proofCounts.get(p.id) === 1 ? '' : 's'}`}
>
♥ {(proofCounts.get(p.id) ?? 0) > 1 ? proofCounts.get(p.id) : ''}
</span>
)}
{proofStatus.get(p.id)?.approved ? (
<span className="badge review-approved" title="Approved by a client">✓</span>
) : null}
{proofStatus.get(p.id)?.changes ? (
<span className="badge review-changes" title="Client requested changes">!</span>
) : null}
{proofStatus.get(p.id)?.comments ? (
<span className="badge review-comment" title={`${proofStatus.get(p.id)?.comments} client comment(s)`}>
💬 {proofStatus.get(p.id)?.comments}
</span>
) : null}
</div>
{color && <span className="color-strip" style={{ background: color.hex }} />}
<div className="card-hover">
<span className="muted small">{fmtSize(p.size)}</span>
<span className="muted small">
{p.width}×{p.height}
</span>
</div>
</div>
<figcaption>
<div className="card-name" title={p.name}>
{p.name}
</div>
<div className="card-bottom">
<Stars value={p.rating} onChange={(n) => onRate(p.id, n)} />
{p.meta.camera && <span className="card-cam">{p.meta.camera}</span>}
</div>
</figcaption>
</figure>
);
})}
{virtualize && viewWindow.bottom > 0 && (
<div className="grid-gap" style={{ height: viewWindow.bottom }} aria-hidden="true" />
)}
</div>
</div>
);
}
+130
View File
@@ -0,0 +1,130 @@
import { useState } from 'react';
import type { PhotoRecord } from '../types';
import { mergePhotos, type MergeKind, type MergeResult } from '../lib/merge';
interface Props {
photos: PhotoRecord[];
onClose: () => void;
onDone: (result: MergeResult) => void;
}
const OPTIONS: { kind: MergeKind; title: string; hint: string }[] = [
{
kind: 'hdr',
title: 'HDR merge',
hint: 'Blend bracketed exposures with alignment and mid-tone weighting.',
},
{
kind: 'panorama',
title: 'Panorama',
hint: 'Stitch a horizontal sequence; overlap is detected automatically.',
},
{
kind: 'focus',
title: 'Focus stack',
hint: 'Choose the sharpest source at every pixel for extended depth of field.',
},
];
export default function MergeModal({ photos, onClose, onDone }: Props) {
const [kind, setKind] = useState<MergeKind>('hdr');
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState(0);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<MergeResult | null>(null);
const run = async () => {
setBusy(true);
setError(null);
setResult(null);
try {
const merged = await mergePhotos(photos, kind, (done, total) => setProgress(Math.round((done / total) * 100)));
setResult(merged);
} catch (err) {
setError(err instanceof Error ? err.message : 'The merge failed');
} finally {
setBusy(false);
}
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div className="modal merge-modal">
<header className="modal-head">
<div>
<h2>Merge photos</h2>
<p className="muted small">
{photos.length} source{photos.length === 1 ? '' : 's'} selected. The result becomes a new photo;
the originals stay untouched.
</p>
</div>
<button className="icon-btn" onClick={onClose} disabled={busy} aria-label="Close">
✕
</button>
</header>
<div className="modal-body">
<div className="merge-options">
{OPTIONS.map((option) => (
<button
key={option.kind}
className={`merge-option ${kind === option.kind ? 'on' : ''}`}
onClick={() => {
setKind(option.kind);
setResult(null);
}}
disabled={busy}
>
<strong>{option.title}</strong>
<span>{option.hint}</span>
</button>
))}
</div>
<div className="merge-sources">
{photos.map((photo) => (
<figure key={photo.id}>
<img src={photo.thumbUrl ?? photo.thumb} alt={photo.name} />
<figcaption title={photo.name}>{photo.name}</figcaption>
</figure>
))}
</div>
{error && <div className="banner error">{error}</div>}
{busy && (
<div className="progress">
<div className="progress-bar">
<div className="progress-fill" style={{ width: `${progress}%` }} />
</div>
<div className="muted small">Analysing and merging · {progress}%</div>
</div>
)}
{result && (
<div className="merge-result">
<img src={result.thumb} alt="Merged result" />
<div>
<strong>Merge ready</strong>
<p className="muted small">
{result.width} × {result.height} px. Add it to the catalog and continue editing it like any other photo.
</p>
</div>
</div>
)}
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose} disabled={busy}>
Cancel
</button>
{result ? (
<button className="btn primary" onClick={() => onDone(result)}>
Add to catalog
</button>
) : (
<button className="btn primary" onClick={() => void run()} disabled={busy || photos.length < 2}>
{busy ? 'Merging…' : 'Create merge'}
</button>
)}
</footer>
</div>
</div>
);
}
File diff suppressed because it is too large Load Diff
+97
View File
@@ -0,0 +1,97 @@
import { useState } from 'react';
import { defaultSections, EDIT_SECTIONS, type EditSectionId } from '../lib/editSections';
interface Props {
sourceName: string;
targetCount: number;
mode: 'paste' | 'sync';
onApply: (sections: EditSectionId[]) => void;
onClose: () => void;
}
export default function PasteSettingsModal({
sourceName,
targetCount,
mode,
onApply,
onClose,
}: Props) {
const [selected, setSelected] = useState<Set<EditSectionId>>(() => new Set(defaultSections()));
const toggle = (id: EditSectionId) => {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const all = selected.size === EDIT_SECTIONS.length;
const none = selected.size === 0;
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal paste-modal">
<header className="modal-head">
<h2>{mode === 'sync' ? 'Sync settings' : 'Paste settings'}</h2>
<button className="icon-btn" onClick={onClose} aria-label="Close">
✕
</button>
</header>
<div className="modal-body">
<p className="muted small">
{mode === 'sync' ? 'Sync from' : 'From'} <strong>{sourceName}</strong> to{' '}
<strong>{targetCount}</strong> photo{targetCount === 1 ? '' : 's'}. Choose what travels.
</p>
<div className="paste-actions">
<button
className="chip ghost"
onClick={() => setSelected(new Set(EDIT_SECTIONS.map((section) => section.id)))}
disabled={all}
>
Select all
</button>
<button className="chip ghost" onClick={() => setSelected(new Set())} disabled={none}>
Clear
</button>
<span className="spacer" />
<span className="muted small">{selected.size} of {EDIT_SECTIONS.length}</span>
</div>
<div className="paste-list">
{EDIT_SECTIONS.map((section) => (
<label key={section.id} className={`paste-row ${section.id === 'crop' || section.id === 'local' ? 'caution' : ''}`}>
<input
type="checkbox"
checked={selected.has(section.id)}
onChange={() => toggle(section.id)}
/>
<span>
<strong>{section.label}</strong>
<small>{section.hint}</small>
</span>
{(section.id === 'crop' || section.id === 'local' || section.id === 'healing') && (
<span className="paste-caution">often photo-specific</span>
)}
</label>
))}
</div>
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose}>
Cancel
</button>
<button
className="btn primary"
disabled={!selected.size}
onClick={() => onApply([...selected])}
>
{mode === 'sync' ? 'Sync to selection' : `Paste to ${targetCount}`}
</button>
</footer>
</div>
</div>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { useEffect, useState } from 'react';
import { normalizeEdits } from '../lib/edits';
import { getBitmap } from '../lib/images';
import { Renderer, rotatedBounds } from '../gl/renderer';
import type { PhotoRecord, Preset } from '../types';
/**
* Preset thumbnails are rendered once per photo/preset pair and cached as small
* JPEG data URLs. One shared Renderer does all of them: a WebGL context per tile
* would exhaust the browser's context limit long before 70 presets.
*/
const cache = new Map<string, string>();
const CACHE_LIMIT = 900;
const THUMB_EDGE = 200;
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`;
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
const [thumbs, setThumbs] = useState<Record<string, string>>({});
// Preset edits never change after creation, so a stable id list is enough to
// avoid re-running for every parent render.
const presetKey = presets.map((p) => p.id).join('|');
const crop = photo.edits.crop;
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
useEffect(() => {
let alive = true;
let renderer: Renderer | null = null;
const canvas = document.createElement('canvas');
const known: Record<string, string> = {};
for (const preset of presets) {
const hit = cache.get(keyOf(photo.id, preset.id, cropKey));
if (hit) known[preset.id] = hit;
}
setThumbs(known);
const pending = presets.filter((p) => !known[p.id]);
if (!pending.length) return;
(async () => {
try {
const bitmap = await getBitmap(photo);
if (!alive) return;
renderer = new Renderer(canvas);
// Every tile shows the photo as it is framed now, so a turned photo's
// presets are turned too.
const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter);
const cropW = Math.max(1, frame.w * crop.w);
const cropH = Math.max(1, frame.h * crop.h);
const scale = THUMB_EDGE / Math.max(cropW, cropH);
const width = Math.max(1, Math.round(cropW * scale));
const height = Math.max(1, Math.round(cropH * scale));
renderer.setImage(bitmap);
for (const preset of pending) {
if (!alive) break;
try {
renderer.render({ ...normalizeEdits(preset.edits), crop }, {
width,
height,
upscale: Math.max(width / cropW, height / cropH) > 1.05,
});
const url = canvas.toDataURL('image/jpeg', 0.72);
cache.set(keyOf(photo.id, preset.id, cropKey), url);
setThumbs((prev) => ({ ...prev, [preset.id]: url }));
} catch {
// One bad preset must not stop the rest of the grid.
}
// Yield between tiles so the panel fills in progressively.
await new Promise((resolve) => setTimeout(resolve, 0));
}
if (cache.size > CACHE_LIMIT) {
for (const key of [...cache.keys()].slice(0, cache.size - CACHE_LIMIT)) cache.delete(key);
}
} catch {
// No bitmap yet (raw not synced) or no WebGL: tiles keep their placeholders.
}
})();
return () => {
alive = false;
renderer?.dispose();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [photo.id, presetKey, cropKey]);
return thumbs;
}
+131
View File
@@ -0,0 +1,131 @@
import { useEffect, useMemo, useState } from 'react';
import type { PhotoRecord } from '../types';
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
interface Props {
photos: PhotoRecord[];
onClose: () => void;
}
type Paper = 'a4' | 'letter' | '5x7';
const PAPERS: Record<Paper, { label: string; width: string; height: string }> = {
a4: { label: 'A4', width: '210mm', height: '297mm' },
letter: { label: 'US Letter', width: '8.5in', height: '11in' },
'5x7': { label: '5 × 7 in', width: '5in', height: '7in' },
};
/**
* A browser print layout for the current selection. Images are rendered through
* the same develop pipeline as export, then placed on a paper-sized sheet. The
* browser's print dialog supplies the printer, margins and ICC handling.
*/
export default function PrintModal({ photos, onClose }: Props) {
const [paper, setPaper] = useState<Paper>('a4');
const [perPage, setPerPage] = useState(2);
const [captions, setCaptions] = useState(true);
const [urls, setUrls] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
const made: string[] = [];
(async () => {
try {
const next: Record<string, string> = {};
for (const photo of photos) {
const blob = await renderPhotoBlob(photo, {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 95,
resize: 'longEdge',
longEdge: 2200,
zip: false,
metadata: false,
outputSharpen: 18,
watermark: { ...DEFAULT_EXPORT.watermark, enabled: false },
});
const url = URL.createObjectURL(blob);
made.push(url);
next[photo.id] = url;
}
if (alive) setUrls(next);
} catch (err) {
if (alive) setError(err instanceof Error ? err.message : 'Could not render the print preview');
} finally {
if (alive) setBusy(false);
}
})();
return () => {
alive = false;
for (const url of made) URL.revokeObjectURL(url);
};
}, [photos]);
const pages = useMemo(() => {
const out: PhotoRecord[][] = [];
for (let i = 0; i < photos.length; i += perPage) out.push(photos.slice(i, i + perPage));
return out;
}, [photos, perPage]);
const width = PAPERS[paper].width;
const height = PAPERS[paper].height;
return (
<div className="modal-backdrop print-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal print-modal">
<header className="modal-head no-print">
<div>
<h2>Print</h2>
<p className="muted small">{photos.length} photo{photos.length === 1 ? '' : 's'} on {pages.length} page{pages.length === 1 ? '' : 's'}. Use your browser print dialog for the printer and ICC profile.</p>
</div>
<button className="icon-btn" onClick={onClose} aria-label="Close">✕</button>
</header>
<div className="print-toolbar no-print">
<label className="field">
<span>Paper</span>
<select value={paper} onChange={(e) => setPaper(e.target.value as Paper)}>
{Object.entries(PAPERS).map(([id, item]) => (
<option key={id} value={id}>{item.label}</option>
))}
</select>
</label>
<label className="field">
<span>Photos per page</span>
<select value={perPage} onChange={(e) => setPerPage(Number(e.target.value))}>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={4}>4</option>
</select>
</label>
<label className="check-row">
<input type="checkbox" checked={captions} onChange={(e) => setCaptions(e.target.checked)} />
File name caption
</label>
<span className="spacer" />
<button className="btn primary" onClick={() => window.print()} disabled={busy || !!error}>
{busy ? 'Rendering…' : 'Print'}
</button>
</div>
{error && <div className="banner error no-print">{error}</div>}
<div className="print-preview">
{pages.map((page, index) => (
<div
key={index}
className={`print-page per-${perPage}`}
style={{ width, height, ['--paper-w' as string]: width, ['--paper-h' as string]: height }}
>
{page.map((photo) => (
<figure key={photo.id} className="print-photo">
{urls[photo.id] ? <img src={urls[photo.id]} alt={photo.name} /> : <div className="print-placeholder" />}
{captions && <figcaption>{photo.title || photo.name}</figcaption>}
</figure>
))}
</div>
))}
</div>
</div>
</div>
);
}
+496
View File
@@ -0,0 +1,496 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
addGalleryComment,
galleryDownloadAllUrl,
galleryDownloadUrl,
loadGallery,
setGalleryPick,
setGalleryReview,
} from '../lib/api';
import type { GalleryPayload, GalleryPhoto } from '../lib/api';
/**
* The page a client opens from a proofing link. It is entirely session-free:
* the token in the URL is the only credential, and the API only ever returns
* the shared event's live photos.
*/
function clientIdentity() {
const key = 'lumenroom.proof.client';
let id = '';
let name = '';
try {
id = localStorage.getItem(`${key}.id`) ?? '';
name = localStorage.getItem(`${key}.name`) ?? '';
} catch {
/* private mode */
}
if (!id) {
id = `c-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
try {
localStorage.setItem(`${key}.id`, id);
} catch {
/* private mode */
}
}
return { id, name };
}
function fmtDate(ms: number | null) {
if (!ms) return '';
return new Date(ms).toLocaleDateString(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric',
});
}
function Heart({ filled }: { filled: boolean }) {
return (
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
<path
d="M12 20.4l-1.5-1.36C5.4 14.44 2 11.36 2 7.9 2 5.2 4.2 3 6.9 3c1.6 0 3.1.75 4.1 1.95A5.4 5.4 0 0 1 15.1 3C17.8 3 20 5.2 20 7.9c0 3.46-3.4 6.54-8.5 11.14L12 20.4z"
fill={filled ? 'currentColor' : 'none'}
stroke="currentColor"
strokeWidth="1.6"
strokeLinejoin="round"
/>
</svg>
);
}
export default function ProofingGallery({ token }: { token: string }) {
const identity = useRef(clientIdentity());
const nameRef = useRef<HTMLInputElement>(null);
const [clientName, setClientName] = useState(identity.current.name);
const [data, setData] = useState<GalleryPayload | null>(null);
const [loading, setLoading] = useState(true);
const [fatal, setFatal] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [picks, setPicks] = useState<Set<string>>(new Set());
const [counts, setCounts] = useState<Record<string, number>>({});
const [onlyPicks, setOnlyPicks] = useState(false);
const [lightbox, setLightbox] = useState<string | null>(null);
const [saving, setSaving] = useState<Set<string>>(new Set());
const [commentDraft, setCommentDraft] = useState('');
const [feedbackBusy, setFeedbackBusy] = useState(false);
const load = useCallback(async () => {
try {
const payload = await loadGallery(token, identity.current.id);
setData(payload);
setPicks(new Set(payload.photos.filter((p) => p.mine).map((p) => p.id)));
const next: Record<string, number> = {};
for (const photo of payload.photos) if (photo.pickCount) next[photo.id] = photo.pickCount;
setCounts(next);
setFatal(null);
setError(null);
} catch (err) {
setFatal(err instanceof Error ? err.message : 'Could not open this gallery');
} finally {
setLoading(false);
}
}, [token]);
useEffect(() => {
void load();
}, [load]);
useEffect(() => {
document.title = data ? `${data.event.name} — Proofing` : 'Proofing gallery';
return () => {
document.title = 'Luminary';
};
}, [data]);
const rememberName = (name: string) => {
setClientName(name);
try {
localStorage.setItem('lumenroom.proof.client.name', name);
} catch {
/* private mode */
}
};
const togglePick = useCallback(
async (photo: GalleryPhoto) => {
if (saving.has(photo.id)) return;
if (!clientName.trim()) {
nameRef.current?.focus();
setError('Add your name so the photographer knows whose picks these are.');
return;
}
const picked = !picks.has(photo.id);
// Optimistic: the heart responds immediately, then reconciles with the
// shared count once the server has recorded the pick.
setPicks((prev) => {
const next = new Set(prev);
if (picked) next.add(photo.id);
else next.delete(photo.id);
return next;
});
setCounts((prev) => {
const next = { ...prev };
const value = Math.max(0, (next[photo.id] ?? 0) + (picked ? 1 : -1));
if (value) next[photo.id] = value;
else delete next[photo.id];
return next;
});
setSaving((prev) => new Set(prev).add(photo.id));
try {
await setGalleryPick(token, {
photoId: photo.id,
picked,
clientId: identity.current.id,
clientName: clientName.trim(),
});
} catch {
setPicks((prev) => {
const next = new Set(prev);
if (picked) next.delete(photo.id);
else next.add(photo.id);
return next;
});
setCounts((prev) => {
const next = { ...prev };
const value = Math.max(0, (next[photo.id] ?? 0) + (picked ? -1 : 1));
if (value) next[photo.id] = value;
else delete next[photo.id];
return next;
});
setError('That pick did not save — check the connection and try again.');
setTimeout(() => setError(null), 4000);
} finally {
setSaving((prev) => {
const next = new Set(prev);
next.delete(photo.id);
return next;
});
}
},
[clientName, picks, saving, token],
);
const submitComment = useCallback(
async (photo: GalleryPhoto) => {
const body = commentDraft.trim();
if (!body || feedbackBusy) return;
setFeedbackBusy(true);
try {
await addGalleryComment(token, {
photoId: photo.id,
clientId: identity.current.id,
clientName: clientName.trim(),
body,
});
setCommentDraft('');
await load();
} catch {
setError('That comment did not save — check the connection and try again.');
} finally {
setFeedbackBusy(false);
}
},
[clientName, commentDraft, feedbackBusy, load, token],
);
const submitReview = useCallback(
async (photo: GalleryPhoto, status: 'approved' | 'changes' | 'none') => {
if (feedbackBusy) return;
if (!clientName.trim()) {
nameRef.current?.focus();
setError('Add your name before approving photos or requesting changes.');
return;
}
setFeedbackBusy(true);
try {
await setGalleryReview(token, {
photoId: photo.id,
clientId: identity.current.id,
clientName: clientName.trim(),
status,
});
await load();
} catch {
setError('That review did not save — check the connection and try again.');
} finally {
setFeedbackBusy(false);
}
},
[clientName, feedbackBusy, load, token],
);
const visible = useMemo(() => {
if (!data) return [];
return onlyPicks ? data.photos.filter((p) => picks.has(p.id)) : data.photos;
}, [data, onlyPicks, picks]);
const lightboxIndex = lightbox ? visible.findIndex((p) => p.id === lightbox) : -1;
const lightboxPhoto = lightboxIndex >= 0 ? visible[lightboxIndex] : null;
useEffect(() => {
if (!lightboxPhoto) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
setLightbox(null);
return;
}
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
const next = visible[lightboxIndex + (e.key === 'ArrowRight' ? 1 : -1)];
if (next) setLightbox(next.id);
return;
}
if (e.key === ' ') {
e.preventDefault();
void togglePick(lightboxPhoto);
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [lightboxIndex, lightboxPhoto, togglePick, visible]);
if (loading) {
return (
<div className="proof">
<div className="proof-splash">
<div className="logo large">Luminary</div>
<p>Loading your gallery…</p>
</div>
</div>
);
}
if (!data) {
return (
<div className="proof">
<div className="proof-splash">
<div className="logo large">Luminary</div>
<h1>This gallery isn’t available</h1>
<p>{fatal ?? 'The link may have expired, or the photographer turned it off.'}</p>
</div>
</div>
);
}
const pickedCount = picks.size;
return (
<div className="proof">
<header className="proof-head">
<div className="proof-head-main">
<div className="proof-brand">
<span className="dot" /> Luminary
</div>
<h1>{data.event.name}</h1>
<p className="proof-sub">
{fmtDate(data.event.date)}
{data.event.date ? ' · ' : ''}
{data.photos.length} photo{data.photos.length === 1 ? '' : 's'}
{data.event.notes ? ` · ${data.event.notes}` : ''}
</p>
</div>
<div className="proof-head-side">
<label className="proof-name">
<span>Your name</span>
<input
ref={nameRef}
value={clientName}
placeholder="Add your name"
maxLength={60}
onChange={(e) => rememberName(e.target.value)}
/>
</label>
<div className={`proof-count ${pickedCount ? 'on' : ''}`}>
<Heart filled={pickedCount > 0} />
{pickedCount} pick{pickedCount === 1 ? '' : 's'}
</div>
</div>
</header>
<div className="proof-intro">
<p>
Tap the heart on the photos you love. Your picks are saved as you go — no account
needed, and you can come back to this link any time.
</p>
<div className="proof-tools">
<button
className={`chip ${onlyPicks ? 'on' : ''}`}
onClick={() => setOnlyPicks((v) => !v)}
disabled={!pickedCount && !onlyPicks}
>
My picks {pickedCount ? `(${pickedCount})` : ''}
</button>
{pickedCount > 0 && (
<a
className="btn ghost small"
href={galleryDownloadAllUrl(token, identity.current.id)}
download
>
Download picks
</a>
)}
<span className="proof-subtle">
{data.picks.total
? `${data.picks.total} pick${data.picks.total === 1 ? '' : 's'} from ${
data.picks.clients
} client${data.picks.clients === 1 ? '' : 's'} so far`
: 'Be the first to choose'}
</span>
</div>
</div>
{error && <div className="proof-toast">{error}</div>}
{onlyPicks && !visible.length ? (
<div className="proof-empty">
<Heart filled={false} />
<h2>No picks yet</h2>
<p>Tap a heart on any photo and it will show up here.</p>
<button className="btn" onClick={() => setOnlyPicks(false)}>
Back to all photos
</button>
</div>
) : (
<div className="proof-grid">
{visible.map((photo, i) => {
const picked = picks.has(photo.id);
return (
<figure
key={photo.id}
className={`proof-card ${picked ? 'picked' : ''}`}
style={{ animationDelay: `${Math.min(i, 16) * 28}ms` }}
>
<button
className="proof-shot"
onClick={() => setLightbox(photo.id)}
title={photo.name}
>
<img
src={photo.thumbUrl}
alt={photo.name}
loading={i < 12 ? 'eager' : 'lazy'}
draggable={false}
/>
</button>
<button
className={`proof-heart ${picked ? 'on' : ''}`}
onClick={() => void togglePick(photo)}
aria-pressed={picked}
title={picked ? 'Remove from picks' : 'Pick this photo'}
>
<Heart filled={picked} />
{counts[photo.id] ? <span>{counts[photo.id]}</span> : null}
</button>
<div className="proof-feedback-badges">
{photo.reviewStatus === 'approved' && <span className="proof-review approved">✓ Approved</span>}
{photo.reviewStatus === 'changes' && <span className="proof-review changes">! Changes</span>}
{photo.comments.length > 0 && <span className="proof-comment-count">💬 {photo.comments.length}</span>}
</div>
</figure>
);
})}
</div>
)}
<footer className="proof-foot">
<span>Proofing gallery by Luminary</span>
<span>{clientName.trim() ? `Picks saved for ${clientName.trim()}` : 'Your picks save automatically'}</span>
</footer>
{lightboxPhoto && (
<div className="proof-lb" onClick={() => setLightbox(null)}>
<button className="proof-lb-close" onClick={() => setLightbox(null)} title="Close (Esc)">
×
</button>
<button
className="proof-lb-nav prev"
onClick={(e) => {
e.stopPropagation();
const prev = visible[lightboxIndex - 1];
if (prev) setLightbox(prev.id);
}}
disabled={lightboxIndex <= 0}
title="Previous"
>
‹
</button>
<div className="proof-lb-body" onClick={(e) => e.stopPropagation()}>
<img src={lightboxPhoto.previewUrl} alt={lightboxPhoto.name} draggable={false} />
<div className="proof-lb-bar">
<div className="proof-lb-title">
<span className="proof-lb-name">{lightboxPhoto.name}</span>
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
Download
</a>
</div>
<button
className={`proof-lb-pick ${picks.has(lightboxPhoto.id) ? 'on' : ''}`}
onClick={() => void togglePick(lightboxPhoto)}
>
<Heart filled={picks.has(lightboxPhoto.id)} />
{picks.has(lightboxPhoto.id) ? 'Picked' : 'Pick this photo'}
</button>
</div>
<div className="proof-review-bar">
<span className="muted small">Review</span>
<button
className={`chip ${lightboxPhoto.reviewStatus === 'approved' ? 'on' : ''}`}
onClick={() => void submitReview(lightboxPhoto, lightboxPhoto.reviewStatus === 'approved' ? 'none' : 'approved')}
disabled={feedbackBusy}
>
✓ Approve
</button>
<button
className={`chip ${lightboxPhoto.reviewStatus === 'changes' ? 'on' : ''}`}
onClick={() => void submitReview(lightboxPhoto, lightboxPhoto.reviewStatus === 'changes' ? 'none' : 'changes')}
disabled={feedbackBusy}
>
! Needs changes
</button>
</div>
<div className="proof-comments">
<div className="proof-comments-head">Comments · {lightboxPhoto.comments.length}</div>
{lightboxPhoto.comments.map((comment) => (
<div key={comment.id} className="proof-comment">
<strong>{comment.clientName || 'Client'}</strong>
<span>{comment.body}</span>
</div>
))}
<div className="proof-comment-add">
<input
value={commentDraft}
placeholder={clientName.trim() ? 'Add a note…' : 'Add your name above, then comment'}
maxLength={1200}
onChange={(e) => setCommentDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void submitComment(lightboxPhoto);
}}
disabled={!clientName.trim() || feedbackBusy}
/>
<button
className="btn primary small"
onClick={() => void submitComment(lightboxPhoto)}
disabled={!commentDraft.trim() || !clientName.trim() || feedbackBusy}
>
Send
</button>
</div>
</div>
</div>
<button
className="proof-lb-nav next"
onClick={(e) => {
e.stopPropagation();
const next = visible[lightboxIndex + 1];
if (next) setLightbox(next.id);
}}
disabled={lightboxIndex >= visible.length - 1}
title="Next"
>
›
</button>
</div>
)}
</div>
);
}
+321
View File
@@ -0,0 +1,321 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { createShare, getShare, pushProof, revokeShare } from '../lib/api';
import type { ShareState } from '../lib/api';
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
import type { ExportOptions } from '../lib/export';
import type { PhotoRecord } from '../types';
interface Props {
event: { id: string; name: string };
photos: PhotoRecord[];
onClose: () => void;
onToast: (message: string) => void;
/** Update the local record after a rendered proof is accepted by the server. */
onProofPublished?: (photoId: string, thumbUrl: string, proofAt: number) => void;
}
const PROOF_EXPORT: ExportOptions = {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 92,
resize: 'longEdge',
longEdge: 2800,
zip: false,
metadata: false,
outputSharpen: 8,
watermark: { ...DEFAULT_EXPORT.watermark, enabled: false },
};
function proofBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const value = typeof reader.result === 'string' ? reader.result : '';
resolve(value.includes(',') ? value.slice(value.indexOf(',') + 1) : value);
};
reader.onerror = () => reject(reader.error ?? new Error('Could not read the proof'));
reader.readAsDataURL(blob);
});
}
/**
* Owner-side control for a proofing link: turn it on, copy it, see who has
* picked what, and revoke it. Picks live on the server keyed by the link, so
* anyone with the URL can choose photos without an account.
*/
export default function ShareModal({ event, photos, onClose, onToast, onProofPublished }: Props) {
const [share, setShare] = useState<ShareState | null>(null);
const [busy, setBusy] = useState(false);
const [publishing, setPublishing] = useState(false);
const [published, setPublished] = useState(0);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const refresh = useCallback(async () => {
try {
setShare(await getShare(event.id));
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not read the proofing link');
}
}, [event.id]);
useEffect(() => {
void refresh();
}, [refresh]);
useEffect(() => {
if (!share?.token) return;
const timer = setInterval(() => void refresh(), 20000);
return () => clearInterval(timer);
}, [refresh, share?.token]);
const url = useMemo(() => {
if (!share?.token) return '';
return `${window.location.origin}/g/${share.token}`;
}, [share]);
const picksByPhoto = useMemo(() => {
const map = new Map<string, string[]>();
for (const pick of share?.picks ?? []) {
const names = map.get(pick.photoId) ?? [];
names.push(pick.clientName || 'Client');
map.set(pick.photoId, names);
}
return map;
}, [share]);
const names = useMemo(() => {
const set = new Set<string>();
for (const pick of share?.picks ?? []) set.add(pick.clientName || 'Client');
return [...set];
}, [share]);
const namesByPhoto = useMemo(() => new Map(photos.map((p) => [p.id, p.name])), [photos]);
const publishProofs = async () => {
if (!photos.length || publishing) return 0;
setPublishing(true);
setPublished(0);
setError(null);
let done = 0;
try {
for (const photo of photos) {
const blob = await renderPhotoBlob(photo, PROOF_EXPORT);
const result = await pushProof(photo.id, await proofBase64(blob));
onProofPublished?.(photo.id, result.thumbUrl, result.proofAt);
done += 1;
setPublished(done);
}
onToast(`Published ${done} edited proof${done === 1 ? '' : 's'}`);
return done;
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not publish the edited proofs');
return done;
} finally {
setPublishing(false);
}
};
const enable = async () => {
setBusy(true);
setError(null);
try {
await createShare(event.id);
await refresh();
// A gallery without rendered proofs would show the unedited originals.
await publishProofs();
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not create the link');
} finally {
setBusy(false);
}
};
const copy = async () => {
if (!url) return;
try {
await navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(() => setCopied(false), 1800);
} catch {
// Clipboard needs permission; selecting the text still lets them copy it.
setError('Could not copy automatically — select the link and copy it.');
}
};
const revoke = async () => {
if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) {
return;
}
setBusy(true);
try {
await revokeShare(event.id);
setShare({ token: null, picks: [] });
onToast('Proofing link turned off');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not turn off the link');
} finally {
setBusy(false);
}
};
return (
<div
className="modal-backdrop"
onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}
>
<div className="modal share-modal">
<header className="modal-head">
<div>
<h2>Client proofing</h2>
<p className="muted small">
Share “{event.name}” as a public gallery. Clients pick favourites without an
account, and their choices show up here and in the library.
</p>
</div>
<button className="icon-btn" onClick={onClose} title="Close">
×
</button>
</header>
<div className="modal-body">
{error && <div className="banner error">{error}</div>}
{!share ? (
<p className="muted">Reading the link…</p>
) : share.token ? (
<>
<div className="share-link-row">
<input value={url} readOnly spellCheck={false} onFocus={(e) => e.target.select()} />
<button className="btn primary" onClick={() => void copy()}>
{copied ? 'Copied' : 'Copy link'}
</button>
</div>
<p className="muted small">
Anyone with this link can view the {photos.length} photos in this event and pick
favourites. Links can be turned off at any time.
</p>
<div className="share-stats">
<div>
<strong>{share.picks.length}</strong>
<span>picks</span>
</div>
<div>
<strong>{names.length}</strong>
<span>{names.length === 1 ? 'client' : 'clients'}</span>
</div>
<div>
<strong>{new Set(share.picks.map((p) => p.photoId)).size}</strong>
<span>photos chosen</span>
</div>
</div>
<div className="share-publish">
<div>
<strong>Edited proofs</strong>
<p className="muted small">
Generate the gallery from the current crop, grade and retouching. The
originals and editable proxies stay untouched.
</p>
</div>
<button
className="btn primary small"
disabled={busy || publishing || !photos.length}
onClick={() => void publishProofs()}
>
{publishing ? `Publishing ${published}/${photos.length}…` : 'Publish edited proofs'}
</button>
</div>
{(share.feedback ?? []).length > 0 && (
<div className="share-feedback">
<div className="share-picks-head">
<span>Client feedback</span>
<button className="btn ghost small" onClick={() => void refresh()}>
Refresh
</button>
</div>
<ul>
{(share.feedback ?? []).slice(0, 40).map((item, index) => (
<li key={`${item.kind}:${item.photoId}:${item.createdAt}:${index}`}>
<span className="share-pick-name">
{namesByPhoto.get(item.photoId) ?? 'Photo'}
</span>
<span className={`share-feedback-kind ${item.kind}`}>
{item.kind === 'approved'
? 'Approved'
: item.kind === 'changes'
? 'Changes requested'
: item.clientName || 'Client'}
</span>
{item.body && <p>{item.body}</p>}
{item.kind === 'comment' && (
<span className="muted small">{item.clientName || 'Client'}</span>
)}
</li>
))}
</ul>
</div>
)}
{share.picks.length ? (
<div className="share-picks">
<div className="share-picks-head">
<span>Client picks</span>
<button className="btn ghost small" onClick={() => void refresh()}>
Refresh
</button>
</div>
<ul>
{[...picksByPhoto.entries()]
.sort((a, b) => b[1].length - a[1].length)
.map(([photoId, who]) => (
<li key={photoId}>
<span className="share-pick-name">
{namesByPhoto.get(photoId) ?? 'Photo'}
</span>
<span className="muted small">{who.join(', ')}</span>
</li>
))}
</ul>
</div>
) : (
<p className="muted small share-waiting">
No picks yet. Client hearts appear here as they work through the gallery.
</p>
)}
<div className="share-warning">
<button className="btn ghost small danger" disabled={busy} onClick={() => void revoke()}>
Turn off link
</button>
<span className="muted small">Clears the gallery and its picks.</span>
</div>
</>
) : (
<div className="share-empty">
<p>
This event has no proofing link yet. Creating one lets a client review the shoot
and mark favourites.
</p>
<button className="btn primary" disabled={busy} onClick={() => void enable()}>
{busy ? 'Creating…' : 'Create proofing link'}
</button>
</div>
)}
</div>
<footer className="modal-foot">
<span className="muted small">
Photos in the trash and develop settings stay private.
</span>
<button className="btn" onClick={onClose}>
Done
</button>
</footer>
</div>
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
import { useEffect } from 'react';
const GROUPS: { title: string; rows: [string, string][] }[] = [
{
title: 'Everywhere',
rows: [
['?', 'Show or hide this list'],
['⌘ / Ctrl + K', 'Search photos, events and actions'],
['⌘ / Ctrl + I', 'Import photos'],
['⌘ / Ctrl + E', 'Export'],
['Esc', 'Close a dialog'],
],
},
{
title: 'Library',
rows: [
['G', 'Library grid'],
['E', 'Open in Develop'],
['← → ↑ ↓', 'Move the selection'],
['Shift + arrows', 'Extend the selection'],
['⌘ / Ctrl + A', 'Select all shown'],
['C', 'Compare selected photos'],
['1 – 5', 'Star rating'],
['0', 'Clear rating'],
['6 – 9', 'Red, yellow, green, blue label'],
['P / X / U', 'Pick · reject · unflag'],
['Delete', 'Remove selected photos'],
['⌘ / Ctrl + C / V', 'Copy · paste develop settings'],
['Drag on empty space', 'Rubber-band select'],
],
},
{
title: 'Develop',
rows: [
['Z', 'Fit · 100%'],
['C', 'Crop & straighten'],
['Q', 'Spot healing brush'],
['M', 'Edit the selected local mask'],
['Enter', 'Apply the crop'],
['\\ (hold)', 'Before / after'],
['1 – 5', 'Star rating'],
['0', 'Clear rating'],
['6 – 9', 'Red, yellow, green, blue label'],
['P / X / U', 'Pick · reject · unflag'],
['J / Shift + J', 'Highlight · shadow clipping'],
['F', 'Full-screen loupe with rating and flags'],
['← →', 'Previous · next photo'],
['Scroll · drag', 'Zoom · pan'],
['⌘ / Ctrl + Z', 'Undo'],
['⌘ / Ctrl + Shift + Z', 'Redo'],
['⌘ / Ctrl + C / V', 'Copy · paste settings'],
['Esc', 'Back to library'],
],
},
];
export default function Shortcuts({ onClose }: { onClose: () => void }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
// Keep Escape from also closing the photo or crop behind the sheet.
e.stopImmediatePropagation();
onClose();
}
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [onClose]);
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal shortcuts-modal">
<header className="modal-head">
<h2>Keyboard shortcuts</h2>
<button className="icon-btn" onClick={onClose} title="Close">
✕
</button>
</header>
<div className="modal-body shortcut-grid">
{GROUPS.map((group) => (
<section key={group.title}>
<h3>{group.title}</h3>
{group.rows.map(([keys, what]) => (
<div className="shortcut-row" key={keys}>
<span className="shortcut-keys">{keys}</span>
<span className="shortcut-what">{what}</span>
</div>
))}
</section>
))}
<section className="shortcut-start">
<h3>Quick start</h3>
<p>Import a shoot, rate and pick frames in the library, then open Develop for the keepers.</p>
<p>Hover a panel seam to reveal its collapse tab. Press Tab to move focus, or ? for this list.</p>
<p>⌘K / Ctrl+K searches the whole catalog without changing your current filters.</p>
</section>
</div>
</div>
</div>
);
}
+93
View File
@@ -0,0 +1,93 @@
import { useEffect, useState } from 'react';
import { beginClipPreview } from '../lib/clipPreview';
export interface SliderProps {
label: string;
value: number;
min?: number;
max?: number;
step?: number;
def?: number;
onChange: (value: number) => void;
format?: (value: number) => string;
track?: string;
disabled?: boolean;
/** Ctrl held during a drag shows the channel clipping overlay */
previewClipping?: boolean;
}
function NumberField({ value, onChange, format }: { value: number; onChange: (v: number) => void; format?: (v: number) => string }) {
const [focused, setFocused] = useState(false);
const [text, setText] = useState('');
const display = focused ? text : format ? format(value) : String(Math.round(value));
useEffect(() => {
if (!focused) setText(format ? format(value) : String(Math.round(value)));
}, [value, focused, format]);
return (
<input
className="row-num"
inputMode="decimal"
value={display}
onFocus={() => {
setText(String(Math.round(value * 100) / 100));
setFocused(true);
}}
onBlur={() => setFocused(false)}
onChange={(e) => {
setText(e.target.value);
const v = parseFloat(e.target.value);
if (Number.isFinite(v)) onChange(v);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
}}
/>
);
}
export default function Slider({
label,
value,
min = -100,
max = 100,
step = 1,
def = 0,
onChange,
format,
track,
disabled,
previewClipping,
}: SliderProps) {
const pct = max === min ? 0 : ((value - min) / (max - min)) * 100;
return (
<div className={`row ${disabled ? 'disabled' : ''}`}>
<span
className="row-label"
title="Double-click to reset"
onDoubleClick={() => !disabled && onChange(def)}
>
{label}
</span>
<input
className="row-range"
type="range"
min={min}
max={max}
step={step}
value={value}
disabled={disabled}
style={{ '--pct': `${pct}%`, ...(track ? { '--track': track } : {}) } as React.CSSProperties}
onChange={(e) => onChange(parseFloat(e.target.value))}
onPointerDown={
previewClipping
? (e) => beginClipPreview(e.ctrlKey || e.metaKey)
: undefined
}
onDoubleClick={() => onChange(def)}
/>
<NumberField value={value} onChange={onChange} format={format} />
</div>
);
}
+75
View File
@@ -0,0 +1,75 @@
import type { ColorLabel, Flag } from '../types';
interface Props {
value: number;
onChange?: (rating: number) => void;
size?: 'sm' | 'md' | 'lg';
title?: string;
}
export default function Stars({ value, onChange, size = 'sm', title }: Props) {
return (
<div className={`stars ${size}`} title={title}>
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
type="button"
disabled={!onChange}
className={`star ${value >= n ? 'on' : ''}`}
aria-label={`${n} star${n === 1 ? '' : 's'}`}
onClick={(e) => {
e.stopPropagation();
onChange?.(value === n ? 0 : n);
}}
>
★
</button>
))}
</div>
);
}
export function FlagButtons({ value, onChange }: { value: Flag; onChange: (flag: Flag) => void }) {
return (
<div className="flag-buttons">
<button
className={`flag-btn pick ${value === 'pick' ? 'on' : ''}`}
title="Pick (P)"
onClick={() => onChange(value === 'pick' ? 'none' : 'pick')}
>
✓
</button>
<button
className={`flag-btn reject ${value === 'reject' ? 'on' : ''}`}
title="Reject (X)"
onClick={() => onChange(value === 'reject' ? 'none' : 'reject')}
>
✕
</button>
</div>
);
}
export function ColorSwatches({ value, onChange }: { value: ColorLabel; onChange: (color: ColorLabel) => void }) {
return (
<div className="color-filter">
{(
[
{ c: 'red' as ColorLabel, hex: '#e05252' },
{ c: 'yellow' as ColorLabel, hex: '#e0c04a' },
{ c: 'green' as ColorLabel, hex: '#56b268' },
{ c: 'blue' as ColorLabel, hex: '#4f86e0' },
{ c: 'purple' as ColorLabel, hex: '#9b6ede' },
] as const
).map(({ c, hex }) => (
<button
key={c}
className={`swatch ${value === c ? 'on' : ''}`}
style={{ background: hex }}
title={c}
onClick={() => onChange(value === c ? '' : c)}
/>
))}
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
import type { ViewMode } from '../types';
interface Props {
view: ViewMode;
eventName: string;
photoCount: number;
selectedCount: number;
cloudLabel: string;
cloudOn: boolean;
onViewChange: (view: ViewMode) => void;
onImport: () => void;
onExport: () => void;
onCloud: () => void;
onHelp: () => void;
onSearch: () => void;
onCatalog: () => void;
canShare: boolean;
onShare: () => void;
}
export default function TopBar({
view,
eventName,
photoCount,
selectedCount,
cloudLabel,
cloudOn,
onViewChange,
onImport,
onExport,
onCloud,
onHelp,
onSearch,
onCatalog,
canShare,
onShare,
}: Props) {
return (
<header className="topbar">
<div className="brand">
<span className="dot" />
Luminary
</div>
<button
type="button"
className="icon-btn mobile-only catalog-btn"
onClick={onCatalog}
title="Open catalog"
aria-label="Open catalog"
>
▤
</button>
<div className="topbar-title">
{eventName}
<span className="muted">
{' '}
· {photoCount} photo{photoCount === 1 ? '' : 's'}
{selectedCount > 1 ? ` · ${selectedCount} selected` : ''}
</span>
</div>
<nav className="module-bar">
<button className={view === 'grid' ? 'active' : ''} onClick={() => onViewChange('grid')}>
Library
</button>
<button className={view === 'develop' ? 'active' : ''} onClick={() => onViewChange('develop')}>
Develop
</button>
</nav>
<div className="topbar-actions">
<button className={`cloud-pill ${cloudOn ? 'on' : ''}`} onClick={onCloud} title="Team server">
<span className="cloud-dot" />
{cloudLabel}
</button>
{canShare && (
<button className="btn ghost" onClick={onShare} title="Share this event for client proofing">
Share
</button>
)}
<button className="btn ghost" onClick={onExport}>
Export
</button>
<button className="icon-btn search-btn" onClick={onSearch} title="Search everything (⌘K / Ctrl+K)" aria-label="Search everything">
⌕
</button>
<button className="icon-btn help-btn" onClick={onHelp} title="Keyboard shortcuts (?)">
?
</button>
<a
className="guide-btn"
href="/luminary-user-guide.pdf"
target="_blank"
rel="noreferrer"
title="User guide (PDF)"
>
Guide
</a>
<button className="btn primary" onClick={onImport}>
Import photos
</button>
</div>
</header>
);
}
+174
View File
@@ -0,0 +1,174 @@
import type { LocalLayer } from '../types';
import { MAX_LOCAL_LAYERS } from '../lib/edits';
/**
* Local masks are baked on the CPU into one RGBA texture, one layer per
* channel, so the grade shader can apply up to four adjustments in a single
* pass. The mask is source-space, which keeps brushes and gradients attached to
* the picture through crops, straightening, zoom and lens correction.
*/
export interface PackedMasks {
data: Uint8Array;
w: number;
h: number;
}
/** Only mask geometry invalidates the baked texture; sliders do not. */
export function maskSignature(layers: LocalLayer[], srcW: number, srcH: number) {
return JSON.stringify({
srcW,
srcH,
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
kind: layer.kind,
inverted: layer.inverted,
feather: layer.feather,
brush: layer.brush,
linear: layer.linear,
radial: layer.radial,
raster: layer.raster
? {
width: layer.raster.width,
height: layer.raster.height,
hash: rasterHash(layer.raster.data),
}
: null,
})),
});
}
function rasterHash(data: string) {
let hash = 2166136261;
for (let i = 0; i < data.length; i += 17) {
hash ^= data.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return `${data.length}:${hash >>> 0}`;
}
function drawRaster(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
const mask = layer.raster;
if (!mask) return;
try {
const binary = atob(mask.data);
const small = makeCanvas(mask.width, mask.height);
const sctx = small.getContext('2d');
if (!sctx) return;
const image = sctx.createImageData(mask.width, mask.height);
const count = Math.min(binary.length, mask.width * mask.height);
for (let i = 0; i < count; i++) {
const value = binary.charCodeAt(i) & 255;
image.data[i * 4] = 255;
image.data[i * 4 + 1] = 255;
image.data[i * 4 + 2] = 255;
image.data[i * 4 + 3] = value;
}
sctx.putImageData(image, 0, 0);
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(small, 0, 0, w, h);
} catch {
// A corrupted embedded mask leaves the layer empty rather than failing the render.
}
}
function makeCanvas(w: number, h: number) {
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
return canvas;
}
function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
const { cx, cy, rx, ry } = layer.radial;
ctx.save();
ctx.translate(cx * w, cy * h);
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
const inner = Math.max(0, Math.min(0.98, 1 - layer.feather / 100));
gradient.addColorStop(0, 'rgba(255,255,255,1)');
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(0, 0, 1, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
const { x1, y1, x2, y2 } = layer.linear;
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
gradient.addColorStop(0, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, w, h);
}
function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
for (const stroke of layer.brush.strokes) {
if (!stroke.points.length) continue;
const width = Math.max(1, stroke.size * 2 * w);
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
ctx.strokeStyle = 'rgba(255,255,255,1)';
ctx.fillStyle = 'rgba(255,255,255,1)';
ctx.lineWidth = width;
if (stroke.points.length === 1) {
ctx.beginPath();
ctx.arc(stroke.points[0].x * w, stroke.points[0].y * h, width / 2, 0, Math.PI * 2);
ctx.fill();
continue;
}
ctx.beginPath();
ctx.moveTo(stroke.points[0].x * w, stroke.points[0].y * h);
for (let i = 1; i < stroke.points.length; i++) {
ctx.lineTo(stroke.points[i].x * w, stroke.points[i].y * h);
}
ctx.stroke();
}
ctx.globalCompositeOperation = 'source-over';
}
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
const w = 800;
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
const out = new Uint8Array(w * h * 4);
const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
if (!count) return { data: out, w, h };
for (let index = 0; index < count; index++) {
const layer = layers[index];
const canvas = makeCanvas(w, h);
const ctx = canvas.getContext('2d');
if (!ctx) continue;
ctx.clearRect(0, 0, w, h);
if (layer.kind === 'radial') drawRadial(ctx, layer, w, h);
else if (layer.kind === 'linear') drawLinear(ctx, layer, w, h);
else if (layer.kind === 'raster') drawRaster(ctx, layer, w, h);
else drawBrush(ctx, layer, w, h);
let source = canvas;
if ((layer.kind === 'brush' || layer.kind === 'raster') && layer.feather > 0) {
const blur = makeCanvas(w, h);
const bctx = blur.getContext('2d');
if (bctx) {
bctx.filter = `blur(${Math.max(0.1, ((layer.feather / 100) * w) / 16)}px)`;
bctx.drawImage(canvas, 0, 0);
source = blur;
}
}
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
if (!pixels) continue;
const channel = index;
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) {
const alpha = pixels[p + 3];
out[o + channel] = layer.inverted ? 255 - alpha : alpha;
}
}
return { data: out, w, h };
}
+1739
View File
File diff suppressed because it is too large Load Diff
+83
View File
@@ -0,0 +1,83 @@
/**
* The published package's `types` entry points at a file that is not shipped in
* 0.1.3, so declare the small surface we use here.
*/
declare module '@neoanaloglabkk/lensfun-wasm' {
export interface LensfunInitOptions {
moduleFactory?: (options?: Record<string, unknown>) => Promise<unknown>;
moduleJsUrl?: string;
wasmUrl?: string;
dataUrl?: string;
dbPath?: string;
autoInitDb?: boolean;
locateFile?: (path: string, prefix: string) => string;
}
export interface LensMatch {
handle: number;
maker: string;
model: string;
score: number;
minFocal: number;
maxFocal: number;
minAperture: number;
maxAperture: number;
cropFactor: number;
}
export interface CameraMatch {
maker: string;
model: string;
variant: string;
mount: string;
cropFactor: number;
score: number;
}
export interface SearchLensesInput {
lensMaker?: string;
lensModel: string;
cameraMaker?: string;
cameraModel?: string;
searchFlags?: number;
}
export interface SearchCamerasInput {
maker?: string;
model?: string;
searchFlags?: number;
}
export interface CorrectionInput {
lensHandle: number;
width: number;
height: number;
focal: number;
crop: number;
step?: number;
reverse?: boolean;
includeTca?: boolean;
includeVignetting?: boolean;
aperture?: number;
distance?: number;
}
export interface CorrectionMaps {
gridWidth: number;
gridHeight: number;
step: number;
geometry: Float32Array;
tca?: Float32Array;
vignetting?: Float32Array;
}
export interface LensfunClient {
dispose(): void;
searchLenses(input: SearchLensesInput): LensMatch[];
searchCameras(input: SearchCamerasInput): CameraMatch[];
getAvailableModifications(lensHandle: number, crop: number): number;
buildCorrectionMaps(input: CorrectionInput): CorrectionMaps;
}
export function createLensfun(options?: LensfunInitOptions): Promise<LensfunClient>;
}
+585
View File
@@ -0,0 +1,585 @@
import type { EventRecord, PhotoRecord, Preset } from '../types';
export interface Health {
ok: boolean;
app: string;
version: string;
needsSetup: boolean;
registrationOpen: boolean;
photos: number;
bytes: number;
storage?: { root: string; custom: boolean };
raw: { libraw: boolean; sharp: boolean; formats: string[] };
}
export interface SessionUser {
id: string;
email: string;
name: string;
role: string;
}
export interface UploadResult {
raw: boolean;
engine?: 'libraw' | 'embedded';
width?: number;
height?: number;
mime?: string;
size?: number;
previewUrl?: string;
thumbUrl?: string;
note?: string | null;
}
export class ApiError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.status = status;
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(path, { credentials: 'same-origin', ...init });
} catch {
throw new ApiError('Cannot reach the Luminary server', 0);
}
if (!res.ok) {
let message = `Request failed (${res.status})`;
try {
const body = (await res.json()) as { error?: string };
if (body?.error) message = body.error;
} catch {
/* non-JSON error body */
}
throw new ApiError(message, res.status);
}
if (res.status === 204) return undefined as T;
return (await res.json()) as T;
}
function jsonBody(payload: unknown): RequestInit {
return {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
};
}
/** Returns null when the app is running without a server (pure browser library). */
export async function getHealth(): Promise<Health | null> {
try {
const res = await fetch('/api/health', { credentials: 'same-origin' });
if (!res.ok) return null;
const body = (await res.json()) as Health;
return body?.ok ? body : null;
} catch {
return null;
}
}
export async function register(input: {
email: string;
password: string;
name?: string;
invite?: string;
inviteToken?: string;
}): Promise<SessionUser> {
const res = await request<{ user: SessionUser }>('/api/auth/register', jsonBody(input));
return res.user;
}
export async function login(email: string, password: string): Promise<SessionUser> {
const res = await request<{ user: SessionUser }>('/api/auth/login', jsonBody({ email, password }));
return res.user;
}
export async function logout(): Promise<void> {
await request('/api/auth/logout', { method: 'POST' });
}
export async function currentUser(): Promise<SessionUser | null> {
try {
const res = await request<{ user: SessionUser }>('/api/auth/me');
return res.user;
} catch (err) {
if (err instanceof ApiError && err.status === 401) return null;
return null;
}
}
export interface ProofSummary {
photoId: string;
eventId: string;
count: number;
clients: string[];
comments?: number;
approved?: number;
changes?: number;
}
export interface SyncPayload {
user: SessionUser;
events: EventRecord[];
photos: PhotoRecord[];
presets: Preset[];
proofs?: ProofSummary[];
}
export function pullAll(): Promise<SyncPayload> {
return request<SyncPayload>('/api/sync');
}
export function pullProofs(): Promise<ProofSummary[]> {
return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []);
}
export function uploadOriginal(id: string, file: File | Blob, name: string): Promise<UploadResult> {
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: file,
});
}
export function pushPhoto(photo: PhotoRecord): Promise<PhotoRecord> {
return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(photo),
}).then((res) => res.photo);
}
export interface ProofUpload {
proofAt: number;
width: number | null;
height: number | null;
thumbUrl: string;
}
/** Upload a rendered (edited) proof for the client gallery and owner grid. */
export interface DenoiseJob {
id: string;
key: string;
state: 'running' | 'done' | 'error';
ms: number | null;
error: string | null;
url: string | null;
/** Reported by a job that found the render already on disk. */
cached?: boolean;
stats: { amount: number; autoGate: number; gate: number; noise: number; baseWidth: number } | null;
}
/** Starts a server-side denoise job; the work runs off the request thread. */
export function startDenoise(photoId: string): Promise<{ jobId: string }> {
return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, { method: 'POST' });
}
/** Drops the rendered files for a photo; the next run renders from scratch. */
export function clearDenoised(photoId: string): Promise<void> {
return request(`/api/photos/${encodeURIComponent(photoId)}/denoised`, { method: 'DELETE' });
}
export function getDenoiseJob(jobId: string): Promise<DenoiseJob> {
return request(`/api/denoise/jobs/${encodeURIComponent(jobId)}`);
}
export function pushProof(id: string, jpegBase64: string): Promise<ProofUpload> {
return request<ProofUpload>(`/api/photos/${encodeURIComponent(id)}/proof`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jpeg: jpegBase64 }),
});
}
export function deletePhotoRemote(id: string): Promise<void> {
return request(`/api/photos/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
export function pushEvent(event: EventRecord): Promise<EventRecord> {
return request<{ event: EventRecord }>(`/api/events/${encodeURIComponent(event.id)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event),
}).then((res) => res.event);
}
export function deleteEventRemote(id: string): Promise<void> {
return request(`/api/events/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
/* ------------------------------------------------------------ proofing api */
export interface ShareFeedback {
kind: 'comment' | 'approved' | 'changes';
photoId: string;
clientName: string;
body?: string;
createdAt: number;
}
export interface ShareState {
token: string | null;
picks: { photoId: string; clientName: string }[];
feedback?: ShareFeedback[];
}
export interface GalleryComment {
id: string;
clientName: string;
body: string;
createdAt: number;
}
export interface GalleryPhoto {
id: string;
name: string;
width: number;
height: number;
takenAt: number | null;
thumbUrl: string;
previewUrl: string;
pickCount: number;
mine: boolean;
comments: GalleryComment[];
reviewStatus: 'approved' | 'changes' | null;
}
export interface GalleryPayload {
event: { name: string; date: number | null; notes: string };
photographer: string;
photos: GalleryPhoto[];
picks: { total: number; clients: number };
}
export function getShare(eventId: string): Promise<ShareState> {
return request<ShareState>(`/api/events/${encodeURIComponent(eventId)}/share`);
}
export function createShare(eventId: string): Promise<string> {
return request<{ token: string }>(`/api/events/${encodeURIComponent(eventId)}/share`, {
method: 'POST',
}).then((res) => res.token);
}
export function galleryDownloadUrl(token: string, photoId: string): string {
return `/api/galleries/${encodeURIComponent(token)}/photos/${encodeURIComponent(photoId)}/download`;
}
export function galleryDownloadAllUrl(token: string, clientId: string): string {
const query = new URLSearchParams({ client: clientId });
return `/api/galleries/${encodeURIComponent(token)}/download-all?${query}`;
}
export function revokeShare(eventId: string): Promise<void> {
return request(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'DELETE' });
}
/** Public, session-free gallery load. */
export function loadGallery(token: string, clientId: string): Promise<GalleryPayload> {
const query = new URLSearchParams({ client: clientId });
return request<GalleryPayload>(`/api/galleries/${encodeURIComponent(token)}?${query}`);
}
export function setGalleryPick(
token: string,
input: { photoId: string; picked: boolean; clientId: string; clientName: string },
): Promise<void> {
return request(`/api/galleries/${encodeURIComponent(token)}/picks`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
});
}
export function addGalleryComment(
token: string,
input: { photoId: string; clientId: string; clientName: string; body: string },
): Promise<GalleryComment> {
return request<{ comment: GalleryComment }>(`/api/galleries/${encodeURIComponent(token)}/comments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
}).then((res) => res.comment);
}
export function setGalleryReview(
token: string,
input: {
photoId: string;
clientId: string;
clientName: string;
status: 'approved' | 'changes' | 'none';
},
): Promise<void> {
return request(`/api/galleries/${encodeURIComponent(token)}/reviews`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
});
}
/* --------------------------------------------------------------- admin api */
export interface AdminUser {
id: string;
email: string;
name: string;
role: string;
disabled: boolean;
createdAt: number | null;
}
export interface AdminEvent {
id: string;
name: string;
createdAt: number | null;
photos: number;
bytes: number;
ownerId: string;
ownerEmail: string;
}
export interface AdminInvite {
token: string;
email: string;
role: string;
status: 'pending' | 'accepted' | 'expired' | 'revoked';
createdAt: number | null;
expiresAt: number | null;
acceptedAt: number | null;
acceptedBy: string | null;
revokedAt: number | null;
}
export interface InviteInfo {
status: AdminInvite['status'];
email: string;
role: string;
expiresAt: number | null;
}
export interface QuotaPlanEvent {
id: string;
name: string;
createdAt: number;
photos: string[];
bytes: number;
}
export interface QuotaPlanPhoto {
id: string;
name: string;
bytes: number;
}
export interface QuotaPlan {
targetBytes: number;
usedBytes: number;
projectedBytes: number;
freedBytes: number;
events: QuotaPlanEvent[];
photos: QuotaPlanPhoto[];
}
export interface QuotaState {
userId: string;
limit: number;
used: number;
remaining: number;
ratio: number;
percent: number;
warn: boolean;
over: boolean;
warnAt: number;
pruneAt: number | null;
prunePlan: QuotaPlan | null;
pruneNotifiedAt: number | null;
lastWarningAt: number | null;
}
export interface AdminQuota extends QuotaState {
user: AdminUser;
plan: QuotaPlan;
}
export interface MailStatus {
configured: boolean;
source: 'admin' | 'environment' | 'none';
host: string;
port: number;
secure: boolean;
user: string;
from: string;
hasPassword: boolean;
gmail: boolean;
}
export interface AdminOverview {
users: AdminUser[];
events: AdminEvent[];
invites: AdminInvite[];
totals: { users: number; photos: number; bytes: number; pendingInvites: number };
storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number };
quotas: AdminQuota[];
mail: MailStatus;
}
export interface StorageChange {
root: string;
previous: string;
files: number;
bytes: number;
moved: boolean;
photos: number;
}
export function loadInvite(token: string): Promise<InviteInfo> {
return request<InviteInfo>(`/api/invites/${encodeURIComponent(token)}`);
}
export function adminCreateInvite(input: {
email: string;
role: string;
days: number;
}): Promise<AdminInvite> {
return request<{ invite: AdminInvite }>('/api/admin/invites', jsonBody(input)).then(
(res) => res.invite,
);
}
export function adminRevokeInvite(token: string): Promise<void> {
return request(`/api/admin/invites/${encodeURIComponent(token)}`, { method: 'DELETE' });
}
export function adminOverview(): Promise<AdminOverview> {
return request<AdminOverview>('/api/admin/overview');
}
export function adminCreateUser(input: {
email: string;
name: string;
password: string;
role: string;
}): Promise<AdminUser> {
return request<{ user: AdminUser }>('/api/admin/users', jsonBody(input)).then((res) => res.user);
}
export function adminUpdateUser(
id: string,
patch: { name?: string; role?: string; disabled?: boolean; password?: string },
): Promise<AdminUser> {
return request<{ user: AdminUser }>(`/api/admin/users/${encodeURIComponent(id)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch),
}).then((res) => res.user);
}
export function adminDeleteUser(id: string): Promise<void> {
return request(`/api/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
export function adminRenameEvent(id: string, name: string): Promise<void> {
return request(`/api/admin/events/${encodeURIComponent(id)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
});
}
export function adminDeleteEvent(id: string): Promise<{ photos: number }> {
return request<{ photos: number }>(`/api/admin/events/${encodeURIComponent(id)}`, {
method: 'DELETE',
});
}
export interface CatalogBackup {
kind: 'lumenroom-catalog';
version: number;
generatedAt: number;
events: EventRecord[];
photos: PhotoRecord[];
kv: Record<string, unknown>;
}
export function adminRestoreCatalog(
catalog: CatalogBackup,
): Promise<{ ok: boolean; events: number; photos: number }> {
return request('/api/admin/catalog', jsonBody(catalog));
}
export function adminStorage(): Promise<StorageChange & { defaultRoot: string; custom: boolean }> {
return request('/api/admin/storage');
}
export function getQuota(): Promise<QuotaState> {
return request<QuotaState>('/api/quota');
}
export function adminSetQuota(userId: string, bytes: number): Promise<QuotaState> {
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ bytes }),
}).then((res) => res.quota);
}
export function adminSchedulePrune(
userId: string,
): Promise<{ pruneAt: number; plan: QuotaPlan; warningSent: boolean }> {
return request(`/api/admin/quotas/${encodeURIComponent(userId)}/prune`, { method: 'POST' });
}
export function adminCancelPrune(userId: string): Promise<QuotaState> {
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}/prune`, {
method: 'DELETE',
}).then((res) => res.quota);
}
export function adminWarnUser(userId: string): Promise<QuotaState> {
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}/warn`, {
method: 'POST',
}).then((res) => res.quota);
}
export function adminGetMail(): Promise<MailStatus> {
return request<{ mail: MailStatus }>('/api/admin/mail').then((res) => res.mail);
}
export function adminSaveMail(input: {
user: string;
appPassword: string;
from: string;
host?: string;
port?: number;
}): Promise<MailStatus> {
return request<{ mail: MailStatus }>('/api/admin/mail', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
}).then((res) => res.mail);
}
export function adminTestMail(to?: string): Promise<{ ok: boolean; to: string }> {
return request('/api/admin/mail/test', jsonBody(to ? { to } : {}));
}
export function adminSetStorage(root: string): Promise<StorageChange> {
return request<StorageChange>('/api/admin/storage', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ root }),
});
}
export function pushPresets(presets: Preset[]): Promise<void> {
return request('/api/presets', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ presets }),
});
}
+73
View File
@@ -0,0 +1,73 @@
import type { Edits } from '../types';
import { clamp } from './curves';
interface Stats {
mean: number;
p05: number;
p95: number;
saturation: number;
}
async function analyze(thumb: string): Promise<Stats> {
const img = new Image();
img.src = thumb;
await img.decode();
const w = 96;
const h = Math.max(1, Math.round((img.height / img.width) * w)) || 96;
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas unavailable');
ctx.drawImage(img, 0, 0, w, h);
const { data } = ctx.getImageData(0, 0, w, h);
const hist = new Uint32Array(256);
let total = 0;
let lumaSum = 0;
let satSum = 0;
for (let i = 0; i < data.length; i += 4) {
const r = data[i] / 255;
const g = data[i + 1] / 255;
const b = data[i + 2] / 255;
const l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
hist[Math.round(l * 255)]++;
lumaSum += l;
satSum += Math.max(r, g, b) - Math.min(r, g, b);
total++;
}
const percentile = (p: number) => {
const target = total * p;
let acc = 0;
for (let i = 0; i < 256; i++) {
acc += hist[i];
if (acc >= target) return i / 255;
}
return 1;
};
return {
mean: lumaSum / total,
p05: percentile(0.05),
p95: percentile(0.95),
saturation: satSum / total,
};
}
/** Simple histogram based auto tone, in the spirit of Lightroom's Auto button. */
export async function computeAutoEdits(thumb: string): Promise<Partial<Edits>> {
try {
const s = await analyze(thumb);
const mean = clamp(s.mean, 0.03, 0.97);
const exposure = clamp(Math.log2(0.46 / mean), -2, 2);
return {
exposure: Math.round(exposure * 100) / 100,
contrast: s.p95 - s.p05 < 0.55 ? 18 : 10,
highlights: s.p95 > 0.94 ? -32 : 4,
shadows: s.p05 < 0.055 ? 32 : 4,
whites: s.p95 > 0.96 ? -8 : 10,
blacks: s.p05 < 0.03 ? 6 : -6,
vibrance: s.saturation < 0.18 ? 18 : 8,
};
} catch {
return { contrast: 12, shadows: 12, highlights: -12, vibrance: 8 };
}
}
+113
View File
@@ -0,0 +1,113 @@
import type { RasterMask } from '../types';
export type AutoMaskKind = 'subject' | 'sky' | 'background';
/**
* On-device mask estimation for the three selections that matter most in an
* event edit: the subject, the sky and the background around the subject.
*
* The estimator works from a downsampled preview. It combines distance from
* the border colour (the usual studio/event background) with a centre bias,
* saturation and a vertical sky prior. This is intentionally lightweight: it
* has no model download and produces a low-resolution raster that the normal
* mask pipeline feathers and scales. The output is editable like any brush
* mask, so a missed edge can be fixed without another model pass.
*/
export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Promise<RasterMask> {
const width = Math.max(128, Math.min(320, Math.round(bitmap.width / 16)));
const height = Math.max(48, Math.round((width * bitmap.height) / Math.max(1, bitmap.width)));
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) throw new Error('Could not analyse the image for a mask');
ctx.drawImage(bitmap, 0, 0, width, height);
const image = ctx.getImageData(0, 0, width, height);
const data = image.data;
const count = width * height;
const subject = new Float32Array(count);
const sky = new Float32Array(count);
const border = borderColor(data, width, height);
for (let y = 0; y < height; y++) {
const ny = y / Math.max(1, height - 1);
for (let x = 0; x < width; x++) {
const i = y * width + x;
const o = i * 4;
const r = data[o] / 255;
const g = data[o + 1] / 255;
const b = data[o + 2] / 255;
const dist = Math.min(1, Math.sqrt((r - border[0]) ** 2 + (g - border[1]) ** 2 + (b - border[2]) ** 2) / 1.35);
const center = 1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2));
const maxc = Math.max(r, g, b);
const minc = Math.min(r, g, b);
const sat = maxc > 0.001 ? (maxc - minc) / maxc : 0;
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
subject[i] = dist * 0.58 + center * 0.27 + sat * 0.1 + (1 - Math.abs(luma - 0.48)) * 0.05;
const blue = Math.max(0, b - (r + g) * 0.5);
sky[i] = blue * 2.5 + Math.max(0, luma - 0.4) * 0.5 + (1 - ny) * 0.28 - (1 - sat) * 0.08;
}
}
const raw = kind === 'sky' ? sky : subject;
const sorted = [...raw].sort((a, b) => a - b);
const median = sorted[Math.floor(sorted.length * 0.5)] ?? 0;
const high = sorted[Math.floor(sorted.length * 0.82)] ?? 1;
const threshold = kind === 'sky' ? Math.max(0.35, median) : Math.max(0.36, median + (high - median) * 0.22);
const mask = new Uint8Array(count);
for (let i = 0; i < count; i++) {
const on = raw[i] >= threshold;
mask[i] = (kind === 'background' ? !on : on) ? 255 : 0;
}
smooth(mask, width, height);
smooth(mask, width, height);
return { data: encodeBase64(mask), width, height };
}
function borderColor(data: Uint8ClampedArray, width: number, height: number): [number, number, number] {
let r = 0;
let g = 0;
let b = 0;
let n = 0;
const add = (x: number, y: number) => {
const o = (y * width + x) * 4;
r += data[o];
g += data[o + 1];
b += data[o + 2];
n++;
};
for (let x = 0; x < width; x++) {
add(x, 0);
add(x, height - 1);
}
for (let y = 1; y < height - 1; y++) {
add(0, y);
add(width - 1, y);
}
return [r / n / 255, g / n / 255, b / n / 255];
}
function smooth(mask: Uint8Array, width: number, height: number) {
const copy = new Uint8Array(mask);
for (let y = 1; y < height - 1; y++) {
for (let x = 1; x < width - 1; x++) {
const i = y * width + x;
let sum = 0;
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) sum += copy[i + dy * width + dx];
}
mask[i] = sum / 9 >= 128 ? 255 : 0;
}
}
}
function encodeBase64(bytes: Uint8Array): string {
let binary = '';
const chunk = 0x8000;
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
}
return btoa(binary);
}
+59
View File
@@ -0,0 +1,59 @@
/**
* Tracks the "hold Ctrl while dragging Exposure" clipping preview.
*
* The slider starts a session on pointer down; the overlay follows the
* modifier key for as long as the drag lasts, so Ctrl can be pressed or
* released mid-drag. Kept outside React so the pointer listeners are attached
* once and the renderer subscription stays cheap.
*/
type Listener = (active: boolean) => void;
let dragging = false;
let active = false;
const listeners = new Set<Listener>();
function emit() {
for (const listener of listeners) listener(active);
}
export function clipPreviewActive() {
return active;
}
export function subscribeClipPreview(listener: Listener) {
listeners.add(listener);
listener(active);
return () => {
listeners.delete(listener);
};
}
export function beginClipPreview(ctrlHeld: boolean) {
dragging = true;
active = Boolean(ctrlHeld);
emit();
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Control' && e.key !== 'Meta') return;
active = dragging && e.type === 'keydown';
emit();
};
const stop = () => {
dragging = false;
active = false;
emit();
window.removeEventListener('keydown', onKey, true);
window.removeEventListener('keyup', onKey, true);
window.removeEventListener('pointerup', stop, true);
window.removeEventListener('pointercancel', stop, true);
window.removeEventListener('blur', stop);
};
window.addEventListener('keydown', onKey, true);
window.addEventListener('keyup', onKey, true);
window.addEventListener('pointerup', stop, true);
window.addEventListener('pointercancel', stop, true);
window.addEventListener('blur', stop);
}
+71
View File
@@ -0,0 +1,71 @@
import type { CurvePoint } from '../types';
export const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
export const clamp01 = (v: number) => clamp(v, 0, 1);
export const round2 = (v: number) => Math.round(v * 100) / 100;
export type CurveSampler = (x: number) => number;
/** Monotone cubic (Fritsch-Carlson) interpolation through normalized curve points. */
export function buildSampler(input: CurvePoint[]): CurveSampler {
const pts = [...input].sort((a, b) => a.x - b.x);
if (pts.length < 2) return (x: number) => clamp01(x);
const xs = pts.map((p) => clamp01(p.x));
const ys = pts.map((p) => clamp01(p.y));
const n = xs.length;
const d: number[] = [];
for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / Math.max(1e-6, xs[i + 1] - xs[i]));
const m: number[] = new Array(n);
m[0] = d[0];
m[n - 1] = d[n - 2];
for (let i = 1; i < n - 1; i++) {
if (d[i - 1] * d[i] <= 0) m[i] = 0;
else m[i] = (d[i - 1] + d[i]) / 2;
}
for (let i = 0; i < n - 1; i++) {
if (d[i] === 0) {
m[i] = 0;
m[i + 1] = 0;
continue;
}
const a = m[i] / d[i];
const b = m[i + 1] / d[i];
const s = a * a + b * b;
if (s > 9) {
const t = 3 / Math.sqrt(s);
m[i] = t * a * d[i];
m[i + 1] = t * b * d[i];
}
}
return (x: number) => {
if (x <= xs[0]) return clamp01(ys[0] + (x - xs[0]) * m[0]);
if (x >= xs[n - 1]) return clamp01(ys[n - 1] + (x - xs[n - 1]) * m[n - 1]);
let i = 0;
while (i < n - 2 && x > xs[i + 1]) i++;
const h = xs[i + 1] - xs[i];
const t = (x - xs[i]) / h;
const t2 = t * t;
const t3 = t2 * t;
const h00 = 2 * t3 - 3 * t2 + 1;
const h10 = t3 - 2 * t2 + t;
const h01 = -2 * t3 + 3 * t2;
const h11 = t3 - t2;
return clamp01(h00 * ys[i] + h10 * h * m[i] + h01 * ys[i + 1] + h11 * h * m[i + 1]);
};
}
export function sanitizeCurve(input: unknown): CurvePoint[] {
const fallback: CurvePoint[] = [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
];
if (!Array.isArray(input)) return fallback;
const pts = input
.filter((p): p is CurvePoint => !!p && typeof p.x === 'number' && typeof p.y === 'number')
.map((p) => ({ x: clamp01(p.x), y: clamp01(p.y) }))
.sort((a, b) => a.x - b.x);
return pts.length >= 2 ? pts : fallback;
}
+91
View File
@@ -0,0 +1,91 @@
import type { EventRecord, PhotoRecord } from '../types';
const DB_NAME = 'lumenroom';
const DB_VERSION = 1;
let dbPromise: Promise<IDBDatabase> | null = null;
export function openDB(): Promise<IDBDatabase> {
if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains('photos')) {
const store = db.createObjectStore('photos', { keyPath: 'id' });
store.createIndex('eventId', 'eventId', { unique: false });
}
if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets');
if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' });
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error('Unable to open database'));
});
return dbPromise;
}
function wrap<T>(request: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'));
});
}
async function store(name: string, mode: IDBTransactionMode = 'readonly') {
const db = await openDB();
return db.transaction(name, mode).objectStore(name);
}
export async function getAllPhotos(): Promise<PhotoRecord[]> {
return wrap((await store('photos')).getAll() as IDBRequest<PhotoRecord[]>);
}
export async function putPhoto(photo: PhotoRecord): Promise<void> {
await wrap((await store('photos', 'readwrite')).put(photo));
}
export async function deletePhotoRecord(id: string): Promise<void> {
const db = await openDB();
const tx = db.transaction(['photos', 'assets'], 'readwrite');
tx.objectStore('photos').delete(id);
tx.objectStore('assets').delete(id);
await new Promise<void>((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
export async function putAsset(id: string, blob: Blob): Promise<void> {
await wrap((await store('assets', 'readwrite')).put(blob, id));
}
export async function getAsset(id: string): Promise<Blob | undefined> {
return wrap((await store('assets')).get(id) as IDBRequest<Blob | undefined>);
}
export async function getAllEvents(): Promise<EventRecord[]> {
return wrap((await store('events')).getAll() as IDBRequest<EventRecord[]>);
}
export async function putEvent(event: EventRecord): Promise<void> {
await wrap((await store('events', 'readwrite')).put(event));
}
export async function deleteEventRecord(id: string): Promise<void> {
await wrap((await store('events', 'readwrite')).delete(id));
}
export async function getKV<T>(key: string): Promise<T | undefined> {
return wrap((await store('kv')).get(key) as IDBRequest<T | undefined>);
}
export async function setKV(key: string, value: unknown): Promise<void> {
await wrap((await store('kv', 'readwrite')).put(value, key));
}
export async function estimateUsage(): Promise<{ usage: number; quota: number }> {
if (!navigator.storage?.estimate) return { usage: 0, quota: 0 };
const est = await navigator.storage.estimate();
return { usage: est.usage ?? 0, quota: est.quota ?? 0 };
}
+34
View File
@@ -0,0 +1,34 @@
/**
* Drag payloads live in a module variable because browsers only expose
* `dataTransfer.getData` on drop, not during dragover — and we need to know
* whether a photo (rather than an OS file) is being dragged while hovering.
*/
let photoIds: string[] = [];
let eventId: string | null = null;
export const PHOTO_DRAG = 'application/x-lumen-photos';
export const EVENT_DRAG = 'application/x-lumen-event';
export function startPhotoDrag(ids: string[]) {
photoIds = ids;
eventId = null;
}
export function draggedPhotoIds(): string[] {
return photoIds;
}
export function startEventDrag(id: string) {
eventId = id;
photoIds = [];
}
export function draggedEventId(): string | null {
return eventId;
}
export function endDrag() {
photoIds = [];
eventId = null;
}
+71
View File
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest';
import { defaultEdits, defaultLocalLayer } from './edits';
import { applyEditSections } from './editSections';
import { autoNoiseFor } from './noiseProfile';
describe('applyEditSections', () => {
it('copies only the selected panel groups', () => {
const source = defaultEdits();
source.exposure = 1.25;
source.saturation = 18;
source.crop = { ...source.crop, x: 0.1, w: 0.7 };
const target = defaultEdits();
target.crop = { ...target.crop, x: 0.4, w: 0.2 };
const next = applyEditSections(source, target, ['light']);
expect(next.exposure).toBe(1.25);
expect(next.saturation).toBe(18);
expect(next.crop.x).toBe(0.4);
expect(next.crop.w).toBe(0.2);
});
it('does not mutate either edit record', () => {
const source = defaultEdits();
source.exposure = 2;
const target = defaultEdits();
applyEditSections(source, target, ['light']);
expect(source.exposure).toBe(2);
expect(target.exposure).toBe(0);
});
it('can copy crop and local masks separately', () => {
const source = defaultEdits();
source.crop = { ...source.crop, angle: 4.5 };
source.local = [
{
...defaultLocalLayer('radial', 0),
id: 'mask-1',
name: 'Face',
},
];
const target = defaultEdits();
const cropped = applyEditSections(source, target, ['crop']);
expect(cropped.crop.angle).toBe(4.5);
expect(cropped.local).toHaveLength(0);
const masked = applyEditSections(source, target, ['local']);
expect(masked.local[0].name).toBe('Face');
expect(masked.crop.angle).toBe(0);
});
});
describe('autoNoiseFor', () => {
it('raises luminance and chroma smoothing with ISO', () => {
const low = autoNoiseFor({ iso: 100 });
const high = autoNoiseFor({ iso: 6400 });
expect(high.luminance).toBeGreaterThan(low.luminance);
expect(high.chroma).toBeGreaterThan(low.chroma);
expect(high.detail).toBeLessThanOrEqual(low.detail);
});
it('keeps every slider inside the editor range', () => {
const noise = autoNoiseFor({ iso: 204800 });
expect(noise.luminance).toBeGreaterThanOrEqual(0);
expect(noise.luminance).toBeLessThanOrEqual(100);
expect(noise.chroma).toBeGreaterThanOrEqual(0);
expect(noise.chroma).toBeLessThanOrEqual(100);
expect(noise.detail).toBeGreaterThanOrEqual(0);
expect(noise.chromaDetail).toBeLessThanOrEqual(100);
});
});
+126
View File
@@ -0,0 +1,126 @@
import type { Edits } from '../types';
export type EditSectionId =
| 'light'
| 'color'
| 'detail'
| 'effects'
| 'geometry'
| 'lens'
| 'crop'
| 'healing'
| 'local';
export interface EditSection {
id: EditSectionId;
label: string;
hint: string;
/** applied by default when pasting or syncing */
defaultOn: boolean;
}
/** The copy/paste contract is deliberately grouped the way the panels are. */
export const EDIT_SECTIONS: EditSection[] = [
{
id: 'light',
label: 'Light & tone',
hint: 'White balance, exposure, tone, presence',
defaultOn: true,
},
{
id: 'color',
label: 'Color',
hint: 'Curves, HSL, grading, black & white',
defaultOn: true,
},
{
id: 'detail',
label: 'Detail',
hint: 'Sharpening, noise reduction, defringe',
defaultOn: true,
},
{
id: 'effects',
label: 'Effects',
hint: 'Vignette and grain',
defaultOn: true,
},
{
id: 'geometry',
label: 'Geometry',
hint: 'Perspective, rotation and scale',
defaultOn: true,
},
{
id: 'lens',
label: 'Lens profile',
hint: 'Lensfun profile and correction switches',
defaultOn: true,
},
{
id: 'crop',
label: 'Crop & orientation',
hint: 'Crop, straighten, rotation and flips',
defaultOn: false,
},
{
id: 'healing',
label: 'Spot healing',
hint: 'Healing spots and source points',
defaultOn: false,
},
{
id: 'local',
label: 'Local masks',
hint: 'Brush, gradient and auto-mask layers',
defaultOn: false,
},
];
const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
light: [
'temp',
'tint',
'exposure',
'recovery',
'contrast',
'highlights',
'shadows',
'whites',
'blacks',
'texture',
'clarity',
'dehaze',
'vibrance',
'saturation',
],
color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'parametric', 'hsl', 'grading'],
detail: ['sharpen', 'noise', 'defringe'],
effects: ['vignette', 'grain', 'proof'],
geometry: ['geometry'],
lens: ['lens'],
crop: ['crop'],
healing: ['heal'],
local: ['local'],
};
/**
* Merge selected sections of one photo's edits into another.
*
* The source is never mutated. Nested groups are copied as whole values, which
* mirrors the checkboxes: choosing "Color" brings the curves, HSL and grading
* together, not half of each.
*/
export function applyEditSections(source: Edits, target: Edits, sections: EditSectionId[]): Edits {
const next: Edits = { ...target };
for (const section of sections) {
for (const key of GROUPS[section]) {
(next as unknown as Record<string, unknown>)[key] = source[key];
}
}
return next;
}
export function defaultSections(): EditSectionId[] {
return EDIT_SECTIONS.filter((section) => section.defaultOn).map((section) => section.id);
}
+540
View File
@@ -0,0 +1,540 @@
import type {
BwFilter,
ColorLabel,
CropState,
CurvePoint,
Edits,
Flag,
HealSpot,
LocalLayer,
LocalMaskKind,
LocalPoint,
LocalStroke,
LensCorrections,
LensProfile,
RasterMask,
PhotoRecord,
PhotoMeta,
} from '../types';
import { clamp, clamp01, sanitizeCurve } from './curves';
export interface HueBand {
key: string;
name: string;
center: number;
swatch: string;
}
export const HUE_BANDS: HueBand[] = [
{ key: 'red', name: 'Red', center: 0, swatch: '#e2453c' },
{ key: 'orange', name: 'Orange', center: 32, swatch: '#e88b3a' },
{ key: 'yellow', name: 'Yellow', center: 62, swatch: '#e3cd48' },
{ key: 'green', name: 'Green', center: 120, swatch: '#57a95a' },
{ key: 'aqua', name: 'Aqua', center: 180, swatch: '#48b3b8' },
{ key: 'blue', name: 'Blue', center: 230, swatch: '#4a72c9' },
{ key: 'purple', name: 'Purple', center: 280, swatch: '#8a63c6' },
{ key: 'magenta', name: 'Magenta', center: 320, swatch: '#c455a0' },
];
/**
* Photographic contrast filters for black & white: transmission per channel.
* A red filter passes red and blocks blue, so skies print almost black.
*/
export const BW_FILTERS: { id: BwFilter; label: string; rgb: [number, number, number] }[] = [
{ id: 'none', label: 'None', rgb: [1, 1, 1] },
{ id: 'yellow', label: 'Yellow', rgb: [1, 0.9, 0.28] },
{ id: 'orange', label: 'Orange', rgb: [1, 0.66, 0.13] },
{ id: 'red', label: 'Red', rgb: [1, 0.36, 0.05] },
{ id: 'green', label: 'Green', rgb: [0.42, 1, 0.45] },
{ id: 'blue', label: 'Blue', rgb: [0.35, 0.75, 1] },
];
export function bwFilterRgb(id: BwFilter): [number, number, number] {
return BW_FILTERS.find((f) => f.id === id)?.rgb ?? [1, 1, 1];
}
/**
* CSS transform that shows a grid thumbnail in the photo's *current* orientation.
* Uses the same order as the renderer: flips act on the photo, then the quarter
* turns and straighten rotate it, and the result is scaled so the rotated image
* still fills the card (a 90 degree turn of a 4:3 photo would otherwise leave gaps).
*/
export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
const { quarter, angle, flipH, flipV } = photo.edits.crop;
const deg = quarter * 90 + angle;
if (Math.abs(deg) < 1e-6 && !flipH && !flipV) return 'none';
const w = Math.max(1, photo.width || 1);
const h = Math.max(1, photo.height || 1);
const boxH = 1 / boxAspect;
// object-fit: cover — the photo already fills the card before any transform.
const cover = Math.max(1 / w, boxH / h);
const dw = w * cover;
const dh = h * cover;
const rad = (Math.abs(deg) * Math.PI) / 180;
const c = Math.abs(Math.cos(rad));
const s = Math.abs(Math.sin(rad));
// A rotated photo has to contain all four corners of the card, not just its
// bounding box: after un-rotating a card corner by -deg it sits at
// ((c + boxH*s)/2, (s + boxH*c)/2), so the photo must be at least that wide
// and tall. Fitting the bounding box instead leaves gaps on angle-only turns.
const coverFit = Math.max((c + boxH * s) / dw, (s + boxH * c) / dh);
// A thumbnail's rounded pixel size can differ from the record's ratio by a
// fraction of a percent; a hair of slack keeps it from showing a sliver at
// the edge. It is invisible at any real card size.
const fit = Math.abs(deg) > 1e-6 ? coverFit * 1.005 : coverFit;
const parts = [`rotate(${deg.toFixed(2)}deg)`];
// Round up: rounding the scale down would leave a hairline gap at the edge.
const rounded = Math.ceil(fit * 1e4) / 1e4;
if (Math.abs(rounded - 1) > 1e-4) parts.push(`scale(${rounded.toFixed(4)})`);
if (flipH) parts.push('scaleX(-1)');
if (flipV) parts.push('scaleY(-1)');
return parts.join(' ');
}
/** The shader carries a fixed spot array; more than this would silently drop. */
export const MAX_HEAL_SPOTS = 24;
/** Four masks are packed into one RGBA texture. */
export const MAX_LOCAL_LAYERS = 4;
export function defaultLocalAdjust(): LocalLayer['adjust'] {
return { exposure: 0, contrast: 0, highlights: 0, shadows: 0, temp: 0, tint: 0, saturation: 0 };
}
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
return {
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${index + 1}`,
kind,
inverted: false,
feather: 50,
brush: { strokes: [] },
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
adjust: defaultLocalAdjust(),
};
}
export const ASPECTS: { id: string; label: string; ratio: number | null }[] = [
{ id: 'original', label: 'Original', ratio: null },
{ id: 'free', label: 'Free', ratio: null },
{ id: '1:1', label: '1 × 1', ratio: 1 },
{ id: '4:5', label: '4 × 5', ratio: 4 / 5 },
{ id: '5:4', label: '5 × 4', ratio: 5 / 4 },
{ id: '4:3', label: '4 × 3', ratio: 4 / 3 },
{ id: '3:2', label: '3 × 2', ratio: 3 / 2 },
{ id: '16:9', label: '16 × 9', ratio: 16 / 9 },
{ id: '2:1', label: '2 × 1', ratio: 2 },
{ id: '9:16', label: '9 × 16', ratio: 9 / 16 },
];
export function defaultCrop(): CropState {
return { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original', flipH: false, flipV: false };
}
export function identityCurve(): CurvePoint[] {
return [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
];
}
export function defaultEdits(): Edits {
return {
temp: 0,
tint: 0,
exposure: 0,
recovery: 0,
contrast: 0,
highlights: 0,
shadows: 0,
whites: 0,
blacks: 0,
texture: 0,
clarity: 0,
dehaze: 0,
vibrance: 0,
saturation: 0,
bw: false,
bwFilter: 'none',
bwFilterAmount: 100,
curve: {
rgb: identityCurve(),
red: identityCurve(),
green: identityCurve(),
blue: identityCurve(),
},
parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 },
hsl: {
hue: HUE_BANDS.map(() => 0),
sat: HUE_BANDS.map(() => 0),
lum: HUE_BANDS.map(() => 0),
},
grading: {
shadows: { h: 210, s: 0 },
highlights: { h: 45, s: 0 },
balance: 0,
},
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 },
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false },
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
aiDenoise: { amount: 100, key: null, model: 'guided' },
defringe: { purple: 0, green: 0 },
heal: [],
local: [],
geometry: { distortion: 0, vertical: 0, horizontal: 0, rotate: 0, scale: 100 },
vignette: { amount: 0, midpoint: 50, feather: 50 },
grain: { amount: 0, size: 25, roughness: 50 },
crop: defaultCrop(),
};
}
/** Keeps stored spots inside the image and caps the count the shader accepts. */
function healSpots(input: unknown): HealSpot[] {
if (!Array.isArray(input)) return [];
const spots: HealSpot[] = [];
for (const raw of input.slice(0, MAX_HEAL_SPOTS)) {
if (!raw || typeof raw !== 'object') continue;
const s = raw as Partial<HealSpot>;
const x = clamp01(num(s.x, 0.5, 0, 1));
const y = clamp01(num(s.y, 0.5, 0, 1));
spots.push({
x,
y,
r: num(s.r, 0.02, 0.001, 0.35),
feather: num(s.feather, 50, 0, 100),
sx: clamp01(num(s.sx, x + 0.05, 0, 1)),
sy: clamp01(num(s.sy, y, 0, 1)),
});
}
return spots;
}
function clampPoint(input: unknown, fallback: LocalPoint): LocalPoint {
if (!input || typeof input !== 'object') return fallback;
const p = input as Partial<LocalPoint>;
return { x: clamp01(num(p.x, fallback.x, 0, 1)), y: clamp01(num(p.y, fallback.y, 0, 1)) };
}
function localStrokes(input: unknown): LocalStroke[] {
if (!Array.isArray(input)) return [];
const out: LocalStroke[] = [];
for (const raw of input.slice(-300)) {
if (!raw || typeof raw !== 'object') continue;
const stroke = raw as Partial<LocalStroke>;
if (!Array.isArray(stroke.points) || !stroke.points.length) continue;
const points = stroke.points
.slice(-4000)
.map((p) => clampPoint(p, { x: 0.5, y: 0.5 }));
out.push({
points,
size: num(stroke.size, 0.04, 0.002, 0.5),
erase: !!stroke.erase,
});
}
return out;
}
function rasterMask(input: unknown): RasterMask | undefined {
if (!input || typeof input !== 'object') return undefined;
const raw = input as Partial<RasterMask>;
if (typeof raw.data !== 'string' || !raw.data || raw.data.length > 2_000_000) return undefined;
const width = Math.round(num(raw.width, 0, 1, 1024));
const height = Math.round(num(raw.height, 0, 1, 1024));
if (!width || !height) return undefined;
return { data: raw.data, width, height };
}
function localLayers(input: unknown): LocalLayer[] {
if (!Array.isArray(input)) return [];
const out: LocalLayer[] = [];
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
if (!raw || typeof raw !== 'object') continue;
const layer = raw as Partial<LocalLayer>;
const kind: LocalMaskKind =
layer.kind === 'linear' || layer.kind === 'radial' || layer.kind === 'raster' ? layer.kind : 'brush';
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
const linear = (layer.linear ?? {}) as Partial<LocalLayer['linear']>;
const radial = (layer.radial ?? {}) as Partial<LocalLayer['radial']>;
out.push({
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
kind,
inverted: !!layer.inverted,
feather: num(layer.feather, 50, 0, 100),
brush: { strokes: localStrokes(layer.brush?.strokes) },
raster: kind === 'raster' ? rasterMask(layer.raster) : undefined,
linear: {
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
},
radial: {
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
rx: num(radial.rx, 0.25, 0.01, 1.5),
ry: num(radial.ry, 0.3, 0.01, 1.5),
},
range: {
enabled: !!range.enabled,
lumaMin: num(range.lumaMin, 0, 0, 100),
lumaMax: num(range.lumaMax, 100, 0, 100),
hue: num(range.hue, 30, 0, 360),
hueRange: num(range.hueRange, 180, 0, 180),
satMin: num(range.satMin, 0, 0, 100),
},
adjust: {
exposure: num(adjust.exposure, 0, -4, 4),
contrast: num(adjust.contrast, 0, -100, 100),
highlights: num(adjust.highlights, 0, -100, 100),
shadows: num(adjust.shadows, 0, -100, 100),
temp: num(adjust.temp, 0, -100, 100),
tint: num(adjust.tint, 0, -100, 100),
saturation: num(adjust.saturation, 0, -100, 100),
},
});
}
return out;
}
function bands(input: unknown): number[] {
const arr = Array.isArray(input) ? input : [];
return HUE_BANDS.map((_, i) => {
const v = arr[i];
return typeof v === 'number' && Number.isFinite(v) ? clamp(v, -100, 100) : 0;
});
}
function num(value: unknown, fallback: number, lo: number, hi: number): number {
return typeof value === 'number' && Number.isFinite(value) ? clamp(value, lo, hi) : fallback;
}
/** Deep-merge stored edits with the current defaults so older records keep working. */
function lensProfile(input: unknown): LensProfile | undefined {
if (!input || typeof input !== 'object') return undefined;
const raw = input as Partial<LensProfile>;
if (typeof raw.maker !== 'string' || typeof raw.model !== 'string') return undefined;
const maker = raw.maker.trim();
const model = raw.model.trim();
if (!maker || !model) return undefined;
const corrections = raw.corrections as Partial<LensCorrections> | undefined;
return {
maker,
model,
crop: num(raw.crop, 1, 0.3, 10),
cameraMaker: typeof raw.cameraMaker === 'string' ? raw.cameraMaker : undefined,
cameraModel: typeof raw.cameraModel === 'string' ? raw.cameraModel : undefined,
corrections: {
distortion: corrections?.distortion !== false,
tca: corrections?.tca !== false,
vignetting: corrections?.vignetting !== false,
},
distance: num(raw.distance, 1000, 0.1, 100000),
};
}
export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
const d = defaultEdits();
if (!input) return d;
const curve = (input.curve ?? {}) as Partial<Edits['curve']>;
const parametric = (input.parametric ?? {}) as Partial<Edits['parametric']>;
const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
const noise = (input.noise ?? {}) as Partial<Edits['noise']>;
const aiDenoise = (input.aiDenoise ?? {}) as Partial<Edits['aiDenoise']>;
const defringe = (input.defringe ?? {}) as Partial<Edits['defringe']>;
const vignette = (input.vignette ?? {}) as Partial<Edits['vignette']>;
const grain = (input.grain ?? {}) as Partial<Edits['grain']>;
const crop = (input.crop ?? {}) as Partial<CropState>;
return {
...d,
...input,
aiDenoise: {
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
model: 'guided',
},
temp: num(input.temp, 0, -100, 100),
tint: num(input.tint, 0, -100, 100),
exposure: num(input.exposure, 0, -5, 5),
recovery: num(input.recovery, 0, 0, 100),
contrast: num(input.contrast, 0, -100, 100),
highlights: num(input.highlights, 0, -100, 100),
shadows: num(input.shadows, 0, -100, 100),
whites: num(input.whites, 0, -100, 100),
blacks: num(input.blacks, 0, -100, 100),
texture: num(input.texture, 0, -100, 100),
clarity: num(input.clarity, 0, -100, 100),
dehaze: num(input.dehaze, 0, -100, 100),
vibrance: num(input.vibrance, 0, -100, 100),
saturation: num(input.saturation, 0, -100, 100),
bw: !!input.bw,
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
curve: {
rgb: sanitizeCurve(curve.rgb),
red: sanitizeCurve(curve.red),
green: sanitizeCurve(curve.green),
blue: sanitizeCurve(curve.blue),
},
parametric: {
highlights: num(parametric.highlights, 0, -100, 100),
lights: num(parametric.lights, 0, -100, 100),
darks: num(parametric.darks, 0, -100, 100),
blacks: num(parametric.blacks, 0, -100, 100),
},
hsl: {
hue: bands(input.hsl?.hue),
sat: bands(input.hsl?.sat),
lum: bands(input.hsl?.lum),
},
grading: {
shadows: {
h: num(grading.shadows?.h, d.grading.shadows.h, 0, 360),
s: num(grading.shadows?.s, 0, 0, 100),
},
highlights: {
h: num(grading.highlights?.h, d.grading.highlights.h, 0, 360),
s: num(grading.highlights?.s, 0, 0, 100),
},
balance: num(grading.balance, 0, -100, 100),
},
sharpen: {
amount: num(sharpen.amount, 0, 0, 150),
radius: num(sharpen.radius, 1, 0.5, 3),
detail: num(sharpen.detail, 25, 0, 100),
mask: num(sharpen.mask, 0, 0, 100),
lensSoftness: num(sharpen.lensSoftness, 0, 0, 100),
},
proof: {
enabled: !!input.proof?.enabled,
paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte',
blackPoint: num(input.proof?.blackPoint, 2, 0, 20),
gamut: !!input.proof?.gamut,
},
noise: {
luminance: num(noise.luminance, 0, 0, 100),
detail: num(noise.detail, 50, 0, 100),
chroma: num(noise.chroma, 0, 0, 100),
chromaDetail: num(noise.chromaDetail, 50, 0, 100),
},
defringe: {
purple: num(defringe.purple, 0, 0, 100),
green: num(defringe.green, 0, 0, 100),
},
heal: healSpots(input.heal),
local: localLayers(input.local),
geometry: {
distortion: num(input.geometry?.distortion, 0, -100, 100),
vertical: num(input.geometry?.vertical, 0, -100, 100),
horizontal: num(input.geometry?.horizontal, 0, -100, 100),
rotate: num(input.geometry?.rotate, 0, -15, 15),
scale: num(input.geometry?.scale, 100, 50, 200),
},
lens: lensProfile(input.lens),
vignette: {
amount: num(vignette.amount, 0, -100, 100),
midpoint: num(vignette.midpoint, 50, 0, 100),
feather: num(vignette.feather, 50, 0, 100),
},
grain: {
amount: num(grain.amount, 0, 0, 100),
size: num(grain.size, 25, 10, 100),
roughness: num(grain.roughness, 50, 0, 100),
},
crop: {
x: clamp01(num(crop.x, 0, 0, 1)),
y: clamp01(num(crop.y, 0, 0, 1)),
w: clamp01(num(crop.w, 1, 0.02, 1)),
h: clamp01(num(crop.h, 1, 0.02, 1)),
angle: num(crop.angle, 0, -45, 45),
quarter: typeof crop.quarter === 'number' && Number.isFinite(crop.quarter)
? ((Math.round(crop.quarter) % 4) + 4) % 4
: 0,
aspect: typeof crop.aspect === 'string' ? crop.aspect : 'original',
flipH: !!crop.flipH,
flipV: !!crop.flipV,
},
};
}
const editCache = new WeakMap<Edits, boolean>();
export function isEdited(edits: Edits): boolean {
const cached = editCache.get(edits);
if (cached !== undefined) return cached;
const d = defaultEdits();
const strip = (e: Edits) => JSON.stringify({ ...e, crop: { ...e.crop, aspect: undefined } });
const result = strip(edits) !== strip(d);
editCache.set(edits, result);
return result;
}
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
const edits = normalizeEdits(input.edits);
const addedAt = input.addedAt ?? Date.now();
const meta: PhotoMeta = input.meta ?? {};
return {
id: input.id,
eventId: input.eventId ?? '',
order: typeof input.order === 'number' ? input.order : undefined,
raw: !!input.raw,
workspace: input.workspace,
decode: input.decode,
previewUrl: input.previewUrl,
thumbUrl: input.thumbUrl,
proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
name: input.name ?? 'Untitled',
width: input.width ?? 0,
height: input.height ?? 0,
size: input.size ?? 0,
mime: input.mime ?? 'image/jpeg',
addedAt,
takenAt: input.takenAt,
meta,
thumb: input.thumb ?? '',
title: typeof input.title === 'string' ? input.title.slice(0, 200) : undefined,
caption: typeof input.caption === 'string' ? input.caption.slice(0, 4000) : undefined,
creator: typeof input.creator === 'string' ? input.creator.slice(0, 200) : undefined,
copyright: typeof input.copyright === 'string' ? input.copyright.slice(0, 300) : undefined,
copyOf: typeof input.copyOf === 'string' && input.copyOf ? input.copyOf : undefined,
copyName: typeof input.copyName === 'string' && input.copyName ? input.copyName.slice(0, 80) : undefined,
snapshots: Array.isArray(input.snapshots)
? input.snapshots
.filter((s) => s && typeof s === 'object' && typeof s.id === 'string' && typeof s.name === 'string')
.slice(-30)
.map((s) => ({ id: s.id, name: s.name.slice(0, 40), ts: Number(s.ts) || Date.now(), edits: normalizeEdits(s.edits) }))
: undefined,
merge: input.merge && (input.merge.kind === 'hdr' || input.merge.kind === 'panorama' || input.merge.kind === 'focus')
? { kind: input.merge.kind, sourceIds: Array.isArray(input.merge.sourceIds) ? input.merge.sourceIds : [] }
: undefined,
rating: clamp(Math.round(input.rating ?? 0), 0, 5),
deletedAt: typeof input.deletedAt === 'number' ? input.deletedAt : undefined,
stackId: typeof input.stackId === 'string' && input.stackId ? input.stackId : undefined,
stackIndex: typeof input.stackIndex === 'number' && Number.isFinite(input.stackIndex)
? Math.max(0, Math.round(input.stackIndex))
: undefined,
flag: (input.flag ?? 'none') as Flag,
color: (input.color ?? '') as ColorLabel,
keywords: Array.isArray(input.keywords) ? input.keywords : [],
edits,
history:
Array.isArray(input.history) && input.history.length
? input.history
: [{ label: 'Import', ts: addedAt, edits }],
};
}
export const COLOR_LABELS: { value: ColorLabel; name: string; hex: string }[] = [
{ value: 'red', name: 'Red', hex: '#e05252' },
{ value: 'yellow', name: 'Yellow', hex: '#e0c04a' },
{ value: 'green', name: 'Green', hex: '#56b268' },
{ value: 'blue', name: 'Blue', hex: '#4f86e0' },
{ value: 'purple', name: 'Purple', hex: '#9b6ede' },
];
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest';
import { outputSize } from '../gl/renderer';
import { defaultEdits } from './edits';
describe('export output dimensions', () => {
it('matches the source for an uncropped image', () => {
expect(outputSize(defaultEdits(), 6000, 4000)).toEqual({ w: 6000, h: 4000 });
});
it('swaps dimensions for a quarter turn', () => {
const edits = defaultEdits();
edits.crop.quarter = 1;
expect(outputSize(edits, 6000, 4000)).toEqual({ w: 4000, h: 6000 });
});
it('includes the triangular points added by straightening', () => {
const edits = defaultEdits();
edits.crop.angle = 45;
expect(outputSize(edits, 4000, 3000)).toEqual({ w: 4950, h: 4950 });
});
it('applies the crop after the rotated frame is calculated', () => {
const edits = defaultEdits();
edits.crop.angle = 45;
edits.crop.w = 0.5;
edits.crop.h = 0.5;
expect(outputSize(edits, 4000, 3000)).toEqual({ w: 2475, h: 2475 });
});
});
+365
View File
@@ -0,0 +1,365 @@
import type { Edits, PhotoRecord } from '../types';
import { getBitmap } from './images';
import { normalizeEdits } from './edits';
import { buildLensCorrection } from './lensfun';
import { outputSize, Renderer } from '../gl/renderer';
import { getDenoisedBitmap } from './images';
import { createZipBlob, zipFileName } from './zip';
import { srgbProfile } from './icc';
import { encodeTiff16 } from './tiff';
export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16';
export type ResizeMode = 'none' | 'longEdge' | 'percent';
export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center';
export interface ExportOptions {
format: ExportFormat;
quality: number;
resize: ResizeMode;
longEdge: number;
percent: number;
nameTemplate: string;
/** Bundle multiple photos into one downloadable archive. */
zip: boolean;
/** Extra capture sharpening applied only to the exported pixels. */
outputSharpen: number;
/** Write title/caption/creator/copyright/keywords into the file. */
metadata: boolean;
/** Embed the generated sRGB ICC profile in JPEG/TIFF files. */
embedProfile: boolean;
watermark: {
enabled: boolean;
text: string;
position: WatermarkPosition;
opacity: number;
size: number;
};
}
export interface ExportRecipe {
id: string;
name: string;
options: ExportOptions;
}
export const DEFAULT_EXPORT: ExportOptions = {
format: 'jpeg',
quality: 92,
resize: 'none',
longEdge: 3000,
percent: 100,
nameTemplate: '{name}',
zip: true,
outputSharpen: 0,
metadata: true,
embedProfile: true,
watermark: { enabled: false, text: '', position: 'br', opacity: 55, size: 4 },
};
const MIME: Record<ExportFormat, string> = {
jpeg: 'image/jpeg',
png: 'image/png',
webp: 'image/webp',
tiff16: 'image/tiff',
};
const EXT: Record<ExportFormat, string> = {
jpeg: 'jpg',
png: 'png',
webp: 'webp',
tiff16: 'tif',
};
function download(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 4000);
}
function pad(n: number) {
return String(n).padStart(2, '0');
}
export function buildFileName(template: string, photo: PhotoRecord, index: number, opts: ExportOptions) {
const stamp = new Date(photo.takenAt ?? photo.addedAt);
const base = photo.name.replace(/\.[^.]+$/, '') || 'export';
const name = (template || '{name}')
.replace(/\{name\}/g, base)
.replace(/\{date\}/g, `${stamp.getFullYear()}${pad(stamp.getMonth() + 1)}${pad(stamp.getDate())}`)
.replace(/\{time\}/g, `${pad(stamp.getHours())}${pad(stamp.getMinutes())}`)
.replace(/\{index\}/g, String(index + 1).padStart(3, '0'))
.replace(/[\\/:*?"<>|]+/g, '-')
.trim();
return `${name || 'export'}.${EXT[opts.format]}`;
}
function targetSize(photo: PhotoRecord, edits: Edits, bitmap: ImageBitmap, opts: ExportOptions) {
const size = outputSize(edits, bitmap.width, bitmap.height);
const longEdge = Math.max(size.w, size.h);
let scale = 1;
if (opts.resize === 'longEdge' && opts.longEdge > 0 && longEdge > opts.longEdge) {
scale = opts.longEdge / longEdge;
} else if (opts.resize === 'percent') {
scale = Math.min(2, Math.max(0.05, opts.percent / 100));
}
return {
w: Math.max(1, Math.round(size.w * scale)),
h: Math.max(1, Math.round(size.h * scale)),
};
}
export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions): Promise<Blob> {
const bitmap = await getBitmap(photo);
const base = normalizeEdits(photo.edits);
const edits = opts.outputSharpen > 0
? { ...base, sharpen: { ...base.sharpen, amount: Math.min(150, base.sharpen.amount + opts.outputSharpen) } }
: base;
const { w, h } = targetSize(photo, edits, bitmap, opts);
const native = outputSize(edits, bitmap.width, bitmap.height);
// Let the shader use its Catmull-Rom path when the crop is being enlarged,
// so an intentional 150–200% export does not turn into a bilinear blur.
const upscale = w > native.w * 1.05 || h > native.h * 1.05;
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
const renderer = new Renderer(canvas);
try {
renderer.setImage(bitmap);
// Forgetting this is how denoise silently goes missing from exports: the
// preview and the file would be graded from different pixels.
if (edits.aiDenoise.key) {
const denoised = await getDenoisedBitmap(photo, edits.aiDenoise.key);
renderer.setDenoised(denoised, edits.aiDenoise.amount / 100);
}
const lens = edits.lens
? await buildLensCorrection(edits.lens, { width: bitmap.width, height: bitmap.height, meta: photo.meta })
: null;
if (opts.format === 'tiff16') {
if (opts.watermark.enabled && opts.watermark.text.trim()) {
throw new Error('Watermarking is not available for 16-bit TIFF exports');
}
const pixels = renderer.render(edits, { width: w, height: h, lens, upscale, floatOut: true });
if (!pixels) throw new Error('Could not read the 16-bit render');
return encodeTiff16({
width: w,
height: h,
pixels,
icc: opts.embedProfile ? srgbProfile() : null,
});
}
renderer.render(edits, { width: w, height: h, lens, upscale });
renderer.finishGpu();
let output = canvas;
if (opts.watermark.enabled && opts.watermark.text.trim()) {
output = paintWatermark(canvas, photo, opts);
}
const mime = MIME[opts.format];
let blob = await new Promise<Blob | null>((resolve) =>
output.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))),
);
if (!blob) throw new Error('Export failed while encoding the image');
if (opts.format === 'jpeg') {
blob = await embedJpegMetadata(
blob,
opts.metadata ? buildXmp(photo) : '',
opts.embedProfile ? srgbProfile() : null,
);
}
return blob;
} finally {
renderer.dispose();
}
}
function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: ExportOptions) {
const canvas = document.createElement('canvas');
canvas.width = source.width;
canvas.height = source.height;
const ctx = canvas.getContext('2d');
if (!ctx) return source;
ctx.drawImage(source, 0, 0);
const longest = Math.max(canvas.width, canvas.height);
const size = Math.max(10, Math.round((longest * opts.watermark.size) / 100));
ctx.font = `600 ${size}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
ctx.textBaseline = 'middle';
const text = opts.watermark.text.trim();
const metrics = ctx.measureText(text);
const pad = Math.round(size * 0.55);
const x =
opts.watermark.position === 'bl' || opts.watermark.position === 'tl'
? pad
: opts.watermark.position === 'center'
? (canvas.width - metrics.width) / 2
: canvas.width - metrics.width - pad;
const y =
opts.watermark.position === 'tr' || opts.watermark.position === 'tl'
? pad + size / 2
: opts.watermark.position === 'center'
? canvas.height / 2
: canvas.height - pad - size / 2;
ctx.globalAlpha = Math.min(1, Math.max(0.05, opts.watermark.opacity / 100));
ctx.fillStyle = '#fff';
ctx.shadowColor = 'rgba(0,0,0,.65)';
ctx.shadowBlur = Math.max(1, size * 0.12);
ctx.shadowOffsetY = Math.max(1, size * 0.03);
ctx.fillText(text, x, y);
ctx.globalAlpha = 1;
return canvas;
}
function xmlEscape(value: string) {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function buildXmp(photo: PhotoRecord) {
const title = photo.title || photo.name;
const keywords = photo.keywords.map((word) => `<rdf:li>${xmlEscape(word)}</rdf:li>`).join('');
return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(title)}</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.caption ?? '')}</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>${xmlEscape(photo.creator ?? '')}</rdf:li></rdf:Seq></dc:creator><dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.copyright ?? '')}</rdf:li></rdf:Alt></dc:rights><dc:subject><rdf:Bag>${keywords}</rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(0, 65000);
}
function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null {
const length = header.length + payload.length + 2;
if (length > 65533) return null;
const segment = new Uint8Array(length + 2);
segment[0] = 0xff;
segment[1] = marker;
segment[2] = (length >> 8) & 255;
segment[3] = length & 255;
segment.set(header, 4);
segment.set(payload, 4 + header.length);
return segment;
}
async function embedJpegMetadata(blob: Blob, xmp: string, icc: Uint8Array | null): Promise<Blob> {
try {
const bytes = new Uint8Array(await blob.arrayBuffer());
if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return blob;
const chunks: Uint8Array[] = [bytes.subarray(0, 2)];
// Insert our own metadata immediately after SOI. Existing ICC APP2 blocks
// are dropped below: canvas encoders often add one already, and duplicated
// profiles can confuse colour-managed viewers.
if (icc) {
const header = new TextEncoder().encode('ICC_PROFILE\0');
const payload = new Uint8Array(2 + icc.length);
payload[0] = 1;
payload[1] = 1;
payload.set(icc, 2);
const segment = appSegment(0xe2, header, payload);
if (segment) chunks.push(segment);
}
if (xmp) {
const header = new TextEncoder().encode('http://ns.adobe.com/xap/1.0/\0');
const segment = appSegment(0xe1, header, new TextEncoder().encode(xmp));
if (segment) chunks.push(segment);
}
let at = 2;
while (at + 4 <= bytes.length) {
if (bytes[at] !== 0xff) {
// Not a marker (or malformed); keep the remaining bytes intact.
chunks.push(bytes.subarray(at));
at = bytes.length;
break;
}
const marker = bytes[at + 1];
if (marker === 0xda) {
chunks.push(bytes.subarray(at));
at = bytes.length;
break;
}
if (marker === 0xd8 || marker === 0xd9) {
chunks.push(bytes.subarray(at, at + 2));
at += 2;
continue;
}
const length = (bytes[at + 2] << 8) | bytes[at + 3];
const end = at + 2 + length;
if (end > bytes.length) {
chunks.push(bytes.subarray(at));
at = bytes.length;
break;
}
const isIcc =
marker === 0xe2 &&
bytes.subarray(at + 4, at + 16).every((value, index) => value === 'ICC_PROFILE\0'.charCodeAt(index));
if (!isIcc) chunks.push(bytes.subarray(at, end));
at = end;
}
if (at < bytes.length) chunks.push(bytes.subarray(at));
return new Blob(chunks as BlobPart[], { type: 'image/jpeg' });
} catch {
return blob;
}
}
export async function exportPhotos(
photos: PhotoRecord[],
opts: ExportOptions,
onProgress?: (done: number, total: number) => void,
onStage?: (stage: 'render' | 'pack') => void,
): Promise<{ count: number; failed: string[] }> {
const bundle = opts.zip && photos.length > 1;
const entries: { name: string; data: Blob }[] = [];
const failed: string[] = [];
let count = 0;
onStage?.('render');
for (let i = 0; i < photos.length; i++) {
const photo = photos[i];
try {
const blob = await renderPhotoBlob(photo, opts);
const name = buildFileName(opts.nameTemplate, photo, i, opts);
if (bundle) entries.push({ name, data: blob });
else {
download(blob, name);
count++;
}
} catch (err) {
console.error('Export failed for', photo.name, err);
failed.push(photo.name);
}
onProgress?.(i + 1, photos.length);
// Give the browser a beat so long batches keep the tab responsive.
await new Promise((r) => setTimeout(r, 0));
}
if (bundle && entries.length) {
// One good file needs no archive; hand it over directly.
if (entries.length === 1) {
download(entries[0].data, entries[0].name);
count = 1;
} else {
onStage?.('pack');
const archive = await createZipBlob(entries);
download(archive, zipFileName());
count = entries.length;
}
}
return { count, failed };
}
/** Backwards compatible single-photo export. */
export async function exportPhoto(photo: PhotoRecord, maxLongEdge = 0): Promise<void> {
const opts: ExportOptions = {
...DEFAULT_EXPORT,
resize: maxLongEdge > 0 ? 'longEdge' : 'none',
longEdge: maxLongEdge || DEFAULT_EXPORT.longEdge,
};
const blob = await renderPhotoBlob(photo, opts);
download(blob, buildFileName(opts.nameTemplate, photo, 0, opts));
}
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import { srgbProfile } from './icc';
describe('sRGB ICC profile', () => {
it('is a self-consistent v2 RGB display profile', () => {
const profile = srgbProfile();
const view = new DataView(profile.buffer);
expect(profile.length).toBeGreaterThan(2000);
expect(view.getUint32(0, false)).toBe(profile.length);
expect(String.fromCharCode(...profile.subarray(36, 40))).toBe('acsp');
expect(String.fromCharCode(...profile.subarray(16, 20))).toBe('RGB ');
expect(String.fromCharCode(...profile.subarray(20, 24))).toBe('XYZ ');
expect(view.getUint32(128, false)).toBeGreaterThan(5);
});
it('carries a readable description for colour-managed viewers', () => {
const profile = srgbProfile();
const view = new DataView(profile.buffer);
const count = view.getUint32(128, false);
let descriptionAt = -1;
for (let index = 0; index < count; index++) {
const at = 132 + index * 12;
if (String.fromCharCode(...profile.subarray(at, at + 4)) === 'desc') {
descriptionAt = view.getUint32(at + 4, false);
break;
}
}
expect(descriptionAt).toBeGreaterThan(0);
expect(String.fromCharCode(...profile.subarray(descriptionAt, descriptionAt + 4))).toBe('desc');
});
it('uses the sampled sRGB transfer curve rather than gamma 2.2', () => {
const profile = srgbProfile();
const view = new DataView(profile.buffer);
const count = view.getUint32(128, false);
let curveAt = -1;
for (let index = 0; index < count; index++) {
const at = 132 + index * 12;
if (String.fromCharCode(...profile.subarray(at, at + 4)) === 'rTRC') {
curveAt = view.getUint32(at + 4, false);
break;
}
}
expect(curveAt).toBeGreaterThan(0);
expect(String.fromCharCode(...profile.subarray(curveAt, curveAt + 4))).toBe('curv');
expect(view.getUint32(curveAt + 8, false)).toBe(1024);
expect(view.getUint16(curveAt + 12, false)).toBe(0);
expect(view.getUint16(curveAt + 12 + 2 * 1023, false)).toBe(65535);
const midpoint = view.getUint16(curveAt + 12 + 2 * 512, false);
expect(midpoint).toBeGreaterThan(13000);
expect(midpoint).toBeLessThan(15000);
});
});
+152
View File
@@ -0,0 +1,152 @@
/**
* A small, self-contained ICC v2 sRGB display profile.
*
* It is generated rather than shipped as a binary so the export pipeline can
* tag sRGB files without adding a third-party profile asset. The matrix and
* gamma describe the standard sRGB primaries; the browser already converted
* the working pixels into sRGB when it decoded the source image.
*/
let cached: Uint8Array | null = null;
function be32(out: DataView, offset: number, value: number) {
out.setUint32(offset, value >>> 0, false);
}
function be16(out: DataView, offset: number, value: number) {
out.setUint16(offset, value & 0xffff, false);
}
function s15(value: number) {
return Math.round(value * 65536) >>> 0;
}
function ascii(text: string) {
return new TextEncoder().encode(text);
}
function pad4(value: number) {
return (value + 3) & ~3;
}
function xyzTag(x: number, y: number, z: number) {
const data = new Uint8Array(20);
const view = new DataView(data.buffer);
data.set(ascii('XYZ '), 0);
be32(view, 8, s15(x));
be32(view, 12, s15(y));
be32(view, 16, s15(z));
return data;
}
function curveTag() {
// ICC v2 curveType with the piecewise sRGB transfer function sampled at
// 1024 points. A gamma-2.2 shortcut is close, but this is exact to the
// standard (within 16-bit quantisation) and still readable by old CMMs.
const samples = 1024;
const data = new Uint8Array(12 + samples * 2);
const view = new DataView(data.buffer);
data.set(ascii('curv'), 0);
be32(view, 8, samples);
for (let index = 0; index < samples; index++) {
const linear = index / (samples - 1);
const encoded =
linear <= 0.04045
? linear / 12.92
: ((linear + 0.055) / 1.055) ** 2.4;
be16(view, 12 + index * 2, Math.round(encoded * 65535));
}
return data;
}
function descTag(text: string) {
const value = new TextEncoder().encode(text);
const size = pad4(12 + value.length + 1 + 4 + 4);
const data = new Uint8Array(size);
const view = new DataView(data.buffer);
data.set(ascii('desc'), 0);
be32(view, 8, value.length + 1);
data.set(value, 12);
data[12 + value.length] = 0;
// Unicode language code and count are both zero.
return data;
}
function textTag(text: string) {
const value = new TextEncoder().encode(text);
const size = pad4(8 + value.length + 1);
const data = new Uint8Array(size);
const view = new DataView(data.buffer);
data.set(ascii('text'), 0);
data.set(value, 8);
data[8 + value.length] = 0;
return data;
}
export function srgbProfile(): Uint8Array {
if (cached) return cached;
// sRGB primaries adapted to the D50 profile connection space.
const tags: { sig: string; data: Uint8Array }[] = [
{ sig: 'desc', data: descTag('sRGB IEC61966-2.1 (Luminary)') },
{ sig: 'cprt', data: textTag('No copyright, use freely') },
{ sig: 'wtpt', data: xyzTag(0.9642, 1.0, 0.8249) },
{ sig: 'rXYZ', data: xyzTag(0.4360747, 0.2225045, 0.0139322) },
{ sig: 'gXYZ', data: xyzTag(0.3850649, 0.7168786, 0.0971045) },
{ sig: 'bXYZ', data: xyzTag(0.1430804, 0.0606169, 0.7141733) },
{ sig: 'rTRC', data: curveTag() },
{ sig: 'gTRC', data: curveTag() },
{ sig: 'bTRC', data: curveTag() },
];
const tableSize = 4 + tags.length * 12;
let offset = 128 + tableSize;
const placed = tags.map((tag) => {
offset = pad4(offset);
const at = offset;
offset += tag.data.length;
return { ...tag, at };
});
const total = pad4(offset);
const data = new Uint8Array(total);
const view = new DataView(data.buffer);
// Header. Date is fixed so identical exports have identical profile bytes.
be32(view, 0, total);
data.set(ascii('LNRM'), 4);
be32(view, 8, 0x02100000);
data.set(ascii('mntr'), 12);
data.set(ascii('RGB '), 16);
data.set(ascii('XYZ '), 20);
be16(view, 24, 2026);
be16(view, 26, 1);
be16(view, 28, 1);
be16(view, 30, 0);
be16(view, 32, 0);
be16(view, 34, 0);
data.set(ascii('acsp'), 36);
be32(view, 40, 0);
be32(view, 44, 0);
be32(view, 48, 0);
be32(view, 52, 0);
be32(view, 56, 0);
be32(view, 60, 0);
be32(view, 64, 0); // perceptual rendering intent
be32(view, 68, 0x0000f6d6); // D50 X 0.9642
be32(view, 72, 0x00010000); // D50 Y 1.0
be32(view, 76, 0x0000d32d); // D50 Z 0.8249
data.set(ascii('LNRM'), 80);
// bytes 84-127 (profile ID and reserved) remain zero.
be32(view, 128, placed.length);
placed.forEach((tag, index) => {
const at = 132 + index * 12;
data.set(ascii(tag.sig), at);
be32(view, at + 4, tag.at);
be32(view, at + 8, tag.data.length);
data.set(tag.data, tag.at);
});
cached = data;
return data;
}
+135
View File
@@ -0,0 +1,135 @@
import type { PhotoRecord } from '../types';
import { getAsset, putAsset } from './db';
const CACHE_LIMIT = 6;
const cache = new Map<string, ImageBitmap>();
/** Where to fetch the original (or raw proxy) when it is not cached on this device. */
export function remoteAssetUrl(photo: PhotoRecord): string {
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
return `/api/photos/${encodeURIComponent(photo.id)}/original`;
}
/** Virtual copies reuse the master's bytes when no local copy exists. */
async function copyAsset(photo: PhotoRecord, id: string): Promise<Blob | undefined> {
const own = await getAsset(photo.id);
if (own) {
if (photo.copyOf) await putAsset(id, own).catch(() => undefined);
return own;
}
if (!photo.copyOf) return undefined;
const master = await getAsset(photo.copyOf);
if (master) {
await putAsset(id, master).catch(() => undefined);
return master;
}
return undefined;
}
async function fetchRemoteCopy(photo: PhotoRecord): Promise<Blob | null> {
const direct = await fetchRemote(photo);
if (direct || !photo.copyOf) return direct;
// A virtual copy has no server file of its own; ask for the master's proxy.
try {
const master = { ...photo, id: photo.copyOf, copyOf: undefined };
const res = await fetch(remoteAssetUrl(master), { credentials: 'same-origin' });
if (!res.ok) return null;
const blob = await res.blob();
await putAsset(photo.id, blob).catch(() => undefined);
return blob;
} catch {
return null;
}
}
async function fetchRemote(photo: PhotoRecord): Promise<Blob | null> {
try {
const res = await fetch(remoteAssetUrl(photo), { credentials: 'same-origin' });
if (!res.ok) return null;
const blob = await res.blob();
// Cache it locally so the photo keeps working offline after the first look.
await putAsset(photo.id, blob).catch(() => undefined);
return blob;
} catch {
return null;
}
}
export async function getBitmap(photo: PhotoRecord): Promise<ImageBitmap> {
const hit = cache.get(photo.id);
if (hit) {
cache.delete(photo.id);
cache.set(photo.id, hit);
return hit;
}
let blob = await copyAsset(photo, photo.id);
if (!blob) blob = (await fetchRemoteCopy(photo)) ?? undefined;
if (!blob) {
throw new Error(
photo.raw
? 'This raw file has no editable proxy yet. Sign in to the server and sync to fetch it.'
: 'Original image data is missing from browser storage',
);
}
// Apply EXIF orientation so the pixels the editor works on are upright.
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
cache.set(photo.id, bitmap);
while (cache.size > CACHE_LIMIT) {
const first = cache.keys().next();
if (first.done) break;
const old = cache.get(first.value);
cache.delete(first.value);
old?.close();
}
return bitmap;
}
export function evictBitmap(photoId: string) {
const bmp = cache.get(photoId);
if (!bmp) return;
cache.delete(photoId);
bmp.close();
}
export function clearBitmapCache() {
for (const bmp of cache.values()) bmp.close();
cache.clear();
for (const bmp of denoisedCache.values()) bmp.close();
denoisedCache.clear();
}
const denoisedCache = new Map<string, ImageBitmap>();
/**
* The server-rendered denoised proxy for an edit's `aiDenoise.key`.
*
* These are separate files from the edit and cost a few seconds to produce, so
* they are cached by key and never re-fetched while the key stays the same.
* Returns null when the asset is gone (cache pruned, storage moved), which the
* caller treats as "no denoise".
*/
export async function getDenoisedBitmap(photo: PhotoRecord, key: string): Promise<ImageBitmap | null> {
const sig = `${photo.id}:${key}`;
const hit = denoisedCache.get(sig);
if (hit) return hit;
try {
const res = await fetch(
`/api/photos/${encodeURIComponent(photo.id)}/denoised?v=${encodeURIComponent(key)}`,
{ credentials: 'same-origin' },
);
if (!res.ok) return null;
const bitmap = await createImageBitmap(await res.blob(), { imageOrientation: 'from-image' });
denoisedCache.set(sig, bitmap);
while (denoisedCache.size > 4) {
const first = denoisedCache.keys().next();
if (first.done) break;
denoisedCache.get(first.value)?.close();
denoisedCache.delete(first.value);
}
return bitmap;
} catch {
return null;
}
}

Some files were not shown because too many files have changed in this diff Show More