5 Commits

Author SHA1 Message Date
bhursey 55239ef1e9 wip: checkpoint host working tree
Login-page gate, notification outbox dispatcher and cron, assignment
proposals/responses, coverage and training-guide updates, plus the generated
training PDFs. Checkpointed from the host before merging the invite-link fix.
2026-11-22 17:42:51 +00:00
bhursey fac9b96cca feat(events): show every photo on the event page without folders
CI / build (push) Has been cancelled
Folders were an implementation detail leaking into the event workflow: every
upload needed a folder first and photos were split across pages. Uploads now
land in a single implicit "Photos" folder and the event page renders one
gallery with the uploader and an edited-only download.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 14:37:57 +00:00
bhursey ebe0c77f7e feat(editor): finish the quick/advanced editor handoff
CI / build (push) Has been cancelled
Reopen advanced edits from their saved recipe, seed or take over the quick
editor from them, refresh thumbnails after a save, and add an edited-only
download. Also fixes the Lumenroom library collapsing to slivers on large
shoots and documents deploying both containers on a new host.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 06:35:24 +00:00
bhursey ab4a07a40f fix(editor): decode camera raws to PNG so previews and thumbs render
CI / build (push) Has been cancelled
ImageMagick 7 in the app image refuses to write TIFF from its LibRaw coder
("no encode delegate for this image format `NEF'"), so every RAW thumbnail,
preview and bridge proxy returned 415. The editor showed "The preview could
not be prepared" and the advanced editor had no editable proxy to open.

PNG is decoded reliably by the same build and read back by sharp.
2026-11-21 02:36:59 +00:00
bhursey 0cb315ea88 feat(editor): bridge the advanced photo editor into the event workflow
CI / build (push) Has been cancelled
Event photos can now be opened in Lumenroom, a WebGL2 develop module, from the
photo editor's Advanced button. The dashboard signs a short-lived token scoped
to one user and event; Lumenroom exchanges it, imports the event's photo list
and proxies bytes on demand, so nothing is copied and the temporary catalog
expires with the bridge session. Saving in Lumenroom renders the photo and
writes it back as the event's edited JPEG, with the advanced recipe kept in
event_photos.advanced_edit_json.

Lumenroom is vendored under lumenroom/ and built as a second compose service,
so one clone and `docker compose up -d --build` deploys both apps.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 01:34:20 +00:00
144 changed files with 31114 additions and 957 deletions
+11
View File
@@ -94,5 +94,16 @@ NFS_ADDR=
NFS_EXPORT=
NFS_VERSION=4
# Advanced editor bridge (optional). LUMENROOM_URL is the browser-facing base
# URL of Lumenroom, e.g. http://<lan-ip>:8787 or https://edit.example.org.
# BRIDGE_SECRET is a long random string shared by both containers; without both
# the "Advanced" button reports that the editor is not configured.
LUMENROOM_URL=
BRIDGE_SECRET=
# Compose-only host publishing for the Lumenroom container. Bind it to loopback
# when a reverse proxy in front of it terminates TLS.
LUMENROOM_PORT=8787
LUMENROOM_BIND=0.0.0.0
# Observability (declared; no Sentry integration is wired yet)
SENTRY_DSN=
+5
View File
@@ -2,6 +2,11 @@
# dependencies
/node_modules
/lumenroom/node_modules
# vendored advanced editor build output and local catalog data
/lumenroom/dist
/lumenroom/server/data
/.pnp
.pnp.*
.yarn/*
+1 -1
View File
@@ -10,7 +10,7 @@ ENV NODE_ENV=production
# ImageMagick's LibRaw delegate decodes camera RAW files for the in-app editor;
# sharp does the tone rendering and JPEG encode. The Postgres client provides
# pg_dump/psql for admin backups and restores; unzip reads restore packages.
RUN apk add --no-cache imagemagick libraw ffmpeg postgresql16-client unzip
RUN apk add --no-cache imagemagick libraw ffmpeg exiv2 postgresql16-client unzip
# pnpm is how this project is built (see package.json scripts).
RUN npm install -g pnpm@9.15.0
+224 -15
View File
@@ -13,6 +13,7 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It
- [Features](#features)
- [Stack](#stack)
- [Quick start (Docker)](#quick-start-docker)
- [Deploying the combined stack on another system](#deploying-the-combined-stack-on-another-system)
- [Local development](#local-development)
- [Configuration](#configuration)
- [Email delivery](#email-delivery)
@@ -67,9 +68,9 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It
### Events and media
- One-off events with a shot brief, location, times, photographer/editor assignments, and per-event shared folders.
- RAW and JPEG uploads streamed to disk, SHA-256 dedupe per folder, authenticated downloads, and manager-only event deletion with file cleanup.
- Photo gallery with cached grid thumbnails (RAW included), preview, non-destructive adjustments/presets, export, per-folder or whole-event ZIP download, and filing a finished event into a dated delivery folder with a manifest. Every photo and video byte lives on the configured media storage share — never in container-local storage.
- One-off events with a shot brief, location, times, photographer/editor assignments, and a single shared photo gallery per event.
- RAW and JPEG uploads streamed to disk, SHA-256 dedupe per event, authenticated downloads, and manager-only event deletion with file cleanup.
- Photo gallery with cached grid thumbnails (RAW included), preview, non-destructive adjustments/presets, export, whole-event or edited-only ZIP download, and filing a finished event into a dated delivery folder with a manifest. Every photo and video byte lives on the configured media storage share — never in container-local storage.
- Video upload with FFmpeg probe/transcode to web H.264/AAC, generated poster, non-destructive trim re-render, and retry after a failed encode.
- Media visibility: team-only, unlisted link, or public. Ready public videos get `/watch/<id>`, a minimal `/embed/<id>` iframe, and an oEmbed endpoint.
- Announcements feed with draft/publish/delete for coordinators and admins.
@@ -108,12 +109,21 @@ cp .env.example .env
docker compose up -d db
docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate # migrations + seed
docker compose up -d --build app
docker compose up -d --build app lumenroom
```
Open <http://localhost:3000>. The app publishes on host port `3000`; Postgres is published on `5433` but bound to `127.0.0.1` by default (set `POSTGRES_BIND=0.0.0.0` only if another host must reach it).
Open <http://localhost:3000>. The advanced photo editor (Lumenroom) is the
vendored second container and publishes on <http://localhost:8787>; it is
optional, and the **Advanced** button stays disabled until `BRIDGE_SECRET` and
`LUMENROOM_URL` are set in `.env` (see [step 15](#15-advanced-photo-editor-bridge-optional)).
The app publishes on host port `3000`; Postgres is published on `5433` but bound to `127.0.0.1` by default (set `POSTGRES_BIND=0.0.0.0` only if another host must reach it).
With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link shows it in the browser and prints it in the app log:
```bash
curl -fsS http://localhost:3000/api/health # dashboard
curl -fsS http://localhost:8787/api/health # advanced editor
```
With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link prints it in the app log:
```bash
docker compose logs -f app
@@ -123,6 +133,93 @@ Sign in with the seeded admin, `admin@glenloch.local`. Other seeded accounts: `c
Migrations are **not** run automatically by `docker compose up`. Re-run the `migrate` command after pulling schema changes. The seed is idempotent.
## Deploying the combined stack on another system
One clone deploys everything: the dashboard (`app`), the advanced photo editor
(`lumenroom`, vendored under `lumenroom/`) and PostgreSQL (`db`). The detailed
Ubuntu walkthrough below covers each step; this is the short version for moving
the stack to a new host.
**What the target host needs**
- Docker Engine 24+ with Compose v2, and sudo access.
- A DNS name per app (for example `media.example.org` and `edit.example.org`),
or the host's LAN IP if it is not exposed to the internet.
- Inbound TCP 80 and 443 only. Ports 3000, 5433 and 8787 stay on the private
interface (`APP_BIND`, `POSTGRES_BIND`, `LUMENROOM_BIND` = `127.0.0.1`).
- The media export mounted on the host for original photos and videos
([step 9](#9-media-storage-on-nfs-or-a-local-path-required-for-event-media)).
**Get the code and secrets**
```bash
git clone <repository-url> /opt/glenloch-media
cd /opt/glenloch-media
cp .env.example .env
chmod 600 .env
openssl rand -base64 32 # NEXTAUTH_SECRET
openssl rand -hex 32 # CRON_SECRET
openssl rand -hex 24 # POSTGRES_PASSWORD (hex avoids URL encoding)
openssl rand -hex 32 # BRIDGE_SECRET, shared by app and lumenroom
```
Minimum `.env` for both containers:
```dotenv
NEXTAUTH_URL=https://media.example.org
NEXTAUTH_SECRET=<base64 value>
PUBLIC_ORIGIN=https://media.example.org
APP_ORIGIN=https://media.example.org
APP_BIND=127.0.0.1
POSTGRES_BIND=127.0.0.1
POSTGRES_USER=media
POSTGRES_PASSWORD=<hex value>
POSTGRES_DB=media
DATABASE_URL=postgres://media:<hex value>@localhost:5433/media
CRON_SECRET=<hex value>
MEDIA_ARCHIVE_DIR=/mnt/glenloch-media
# Advanced editor bridge
LUMENROOM_URL=https://edit.example.org
LUMENROOM_BIND=127.0.0.1
BRIDGE_SECRET=<hex value>
```
`BRIDGE_SECRET` is passed to both services from this one value; they must match.
`LUMENROOM_URL` is the browser-facing editor address, while the app reaches
Lumenroom inside the Compose network by service name.
**Build, migrate, start**
```bash
docker compose config --quiet
docker compose up -d db
docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate
docker compose up -d --build app lumenroom
docker compose ps
curl -fsS http://127.0.0.1:3000/api/health
curl -fsS http://127.0.0.1:8787/api/health
```
Both `app` and `lumenroom` must be `healthy`. `docker compose up -d --build`
without a service name also works and builds both images; naming them is just an
explicit version of the same command.
**Finish and verify**
1. Complete first sign-in and admin bootstrap ([step 5](#5-first-sign-in-and-admin-bootstrap)).
2. Save the media share in Settings → Media storage ([step 9](#9-media-storage-on-nfs-or-a-local-path-required-for-event-media)).
3. Put both hostnames in the reverse proxy ([step 6](#6-reverse-proxy-and-tls-with-caddy)) and reload Caddy.
4. Open an event photo and click **Advanced**: the editor should open in a new tab, already signed in, with a banner showing **Save to event**. If it reports the editor is not configured, `BRIDGE_SECRET` or `LUMENROOM_URL` is missing or the two secrets differ.
**Moving an existing installation.** Run Admin → Backup & restore on the old
host, copy the ZIP and `.env` (especially `NEXTAUTH_SECRET`) to the new host,
bring the stack up as above, then restore through the same admin panel. Original
media comes from the ZIP or the share itself. The `lumenroom-data` volume holds
only temporary bridge data and does not need to move.
## Local development
```bash
@@ -168,7 +265,7 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `.
| `APP_ORIGIN` | Fallback application origin. |
| `CHURCH_TIMEZONE` | Display timezone; scheduling itself stores UTC instants and local dates. Defaults to `America/New_York`. |
| `AUTO_ACTIVATE_NEW_USERS` | `false` (default) sends unknown emails to `pending_approval`; `true` is for dev/test only. |
| `MAGIC_LINK_DEV_TRANSPORT` | Shows/prints the sign-in link instead of emailing it. Defaults on outside production; compose sets `true` for first login. |
| `MAGIC_LINK_DEV_TRANSPORT` | Returns/prints the sign-in link instead of emailing it; the login page never displays it. Defaults on outside production; compose sets `true` for first login. |
| `ALLOW_DEV_RESET` | Enables the destructive `POST /api/dev/reset` endpoint. Must stay `false` in real deployments. |
| `CRON_SECRET` | Bearer/query secret for the cron HTTP routes. Empty means session-only. |
| `POSTMARK_SERVER_TOKEN`, `POSTMARK_FROM` | Optional Postmark fallback and default sender. Admin email settings take precedence. |
@@ -176,6 +273,8 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `.
| `UPLOAD_DIR` | Training attachments only (`/tmp/uploads` in compose). Event photos and videos never live here. |
| `ARCHIVE_DIR`, `NFS_SHARE`, `ARCHIVE_FOLDER` | Mount path inside the container, the reported share, and the default folder. This is the primary storage for original event photos and videos; a named share plus a writable path is required or uploads and photo editing stay disabled. |
| `MEDIA_ARCHIVE_DIR` | **Compose-only host path** mounted at `/archive` for the NFS export. |
| `LUMENROOM_URL`, `BRIDGE_SECRET` | Advanced editor bridge: the browser-facing address of the Lumenroom container and the shared token secret. Both are required for the **Advanced** button; leave empty to run without the editor. |
| `LUMENROOM_PORT`, `LUMENROOM_BIND` | **Compose-only** host publishing for Lumenroom. Default `8787` on all interfaces; set `127.0.0.1` behind a reverse proxy. |
| `SENTRY_DSN` | Declared but not wired to any integration. |
Volumes in Compose: `pgdata`, `outbox-data`, `uploads-data`, and either `archive-data` or the host `MEDIA_ARCHIVE_DIR` bind mount (the latter is what holds original photos and videos). Back these up together.
@@ -327,6 +426,11 @@ MAGIC_LINK_DEV_TRANSPORT=true
CRON_SECRET=<hex value>
POSTMARK_FROM=media@example.org
# POSTMARK_SERVER_TOKEN=... # optional; Gmail can be configured in Admin instead
# Advanced photo editor (optional; omit to run without it)
LUMENROOM_URL=https://edit.example.org
LUMENROOM_BIND=127.0.0.1
BRIDGE_SECRET=<hex value>
```
Notes:
@@ -348,9 +452,10 @@ docker compose config --quiet
docker compose up -d db
docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate
docker compose up -d --build app
docker compose up -d --build app lumenroom
docker compose ps
curl -fsS http://127.0.0.1:3000/api/health
curl -fsS http://127.0.0.1:8787/api/health
```
Rebuild `migrate` as shown; `docker compose run` reuses the last built tools image, so without the build step an update can run stale seed code against a newer schema.
@@ -365,7 +470,7 @@ Keep the app on loopback and use an SSH tunnel for this step:
ssh -L 3000:127.0.0.1:3000 you@media.example.org
```
Open `http://localhost:3000/login`, request a link for `admin@glenloch.local`, and read it from the page or from `docker compose logs app`. Then:
Open `http://localhost:3000/login`, request a link for `admin@glenloch.local`, and read it from `docker compose logs app`. Then:
1. Admin → People: change the admin name and email to the real person, and create real accounts.
2. Admin → Services: set real service times, roles, and headcounts.
@@ -378,7 +483,7 @@ Only after that, set `MAGIC_LINK_DEV_TRANSPORT=false` in `.env` and restart:
docker compose up -d app
```
**Do not expose the app publicly while the dev transport is on:** it displays sign-in links in the browser. Keep `APP_BIND=127.0.0.1` until bootstrap is finished.
**Do not expose the app publicly while the dev transport is on:** it can return and log sign-in links during bootstrap. Keep `APP_BIND=127.0.0.1` until bootstrap is finished.
### 6. Reverse proxy and TLS with Caddy
@@ -401,8 +506,18 @@ media.example.org {
encode zstd gzip
reverse_proxy 127.0.0.1:3000
}
edit.example.org {
reverse_proxy 127.0.0.1:8787
}
```
The second site is the advanced editor. Give it the same pattern as the app:
set `LUMENROOM_BIND=127.0.0.1` and `LUMENROOM_URL=https://edit.example.org`, and
point DNS for that hostname at the server too. If you leave the editor out,
remove its site block and set no `BRIDGE_SECRET`; the **Advanced** button then
reports that the editor is not configured.
```bash
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
@@ -421,7 +536,7 @@ sudo ufw enable
sudo ufw status
```
`APP_BIND=127.0.0.1` and `POSTGRES_BIND=127.0.0.1` keep the app and database off the public interface.
`APP_BIND=127.0.0.1`, `LUMENROOM_BIND=127.0.0.1` and `POSTGRES_BIND=127.0.0.1` keep the app, the editor and the database off the public interface; only Caddy listens on 80/443.
### 8. Background jobs (cron)
@@ -541,6 +656,10 @@ Use Admin → Backup & restore to download a ZIP of the database dump, uploads,
At minimum, back up after every schedule/training/media milestone and before every upgrade. The database, uploads, and archive volumes live under Docker's volume directory; the application-level ZIP is the supported portable backup.
The `lumenroom-data` volume is different: it holds only Lumenroom's temporary
bridge catalog, cached previews and thumbnails, so it can be left out of backups
and rebuilt by opening events again.
### 12. Updating the deployment
Take a backup, then:
@@ -550,9 +669,10 @@ cd /opt/glenloch-media
git pull --ff-only
docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate
docker compose up -d --build app
docker compose up -d --build app lumenroom
docker compose ps
curl -fsS http://127.0.0.1:3000/api/health
curl -fsS http://127.0.0.1:8787/api/health
```
`migrate` is idempotent and also runs the seed, which does not duplicate authored lessons or existing rows. If a release is bad, rebuild the previous commit:
@@ -560,7 +680,7 @@ curl -fsS http://127.0.0.1:3000/api/health
```bash
git log --oneline -5
git checkout <previous-commit>
docker compose up -d --build app
docker compose up -d --build app lumenroom
# after fixing:
git switch main
```
@@ -578,6 +698,8 @@ git switch main
| Uploads/editing are disabled | Settings → Media storage needs a share name and a mounted path that UID 100 can write to; the banner states the exact failure. |
| Uploads are blocked with "not a network mount" | The export is not actually mounted: either add `docker-compose.nfs.yml` (`NFS_ADDR`/`NFS_EXPORT`) or mount it on the host and point `MEDIA_ARCHIVE_DIR` at that mount. `docker compose exec app grep ' /archive ' /proc/self/mounts` shows what the container really has. |
| Cron returns 401 | `CRON_SECRET` is set in `.env` and matches the value read by `/usr/local/bin/media-hub-cron`. |
| **Advanced** reports the editor is not configured | `LUMENROOM_URL` and `BRIDGE_SECRET` are set in the app's environment, and Lumenroom has the same `BRIDGE_SECRET`. Restart both: `docker compose up -d app lumenroom`. |
| Advanced opens but the editor fails to load or is blank | `docker compose ps` should show `lumenroom` as `healthy`; `curl -fsS http://127.0.0.1:8787/api/health`; check `LUMENROOM_URL` is reachable from users' browsers and the proxy forwards `edit.example.org` to `127.0.0.1:8787`. |
| Disk filling up | Docker log rotation is capped at 10 MB × 3 per service; remove old backups, exports, and unused media. |
### 14. Production checklist
@@ -592,8 +714,94 @@ git switch main
- [ ] Cron jobs installed and returning success.
- [ ] Backup downloaded, stored off-host, and restore tested once.
- [ ] Media storage share configured in Settings → Media storage and writable (required for event photos and videos).
- [ ] `LUMENROOM_BIND=127.0.0.1`, `LUMENROOM_URL` set to the editor's HTTPS origin, and `BRIDGE_SECRET` identical in both containers.
- [ ] `edit.example.org` (or the chosen editor hostname) proxies to `127.0.0.1:8787`, and **Advanced** opens the editor signed in.
- [ ] The `/api/dev/*` prefix is historical: the guards, not the URL, are the security boundary.
### 15. Advanced photo editor bridge (optional)
Event photos can also be opened in a separate Lumenroom deployment for a much
deeper develop module (WebGL2 tone/colour pipeline, HSL mixer, split toning,
per-channel curves, texture/dehaze/grain, history and presets). The simple
editor stays the default; the advanced one is reached from the photo editor's
**Advanced** button.
The two apps never share a database. The dashboard opens a scoped bridge
session, sends the browser to Lumenroom with a short-lived signed token, and
Lumenroom mirrors the event's photo list. Photo bytes are proxied on demand, so
nothing is copied at login; the imported event is temporary and is deleted when
that bridge session expires (12 hours by default).
**One deployment.** Lumenroom is vendored under `lumenroom/`, and
`docker-compose.yml` builds it as a second service next to the app. One clone
and one command deploy both (add `--build` when the sources changed):
```bash
docker compose up -d --build app lumenroom
```
Deployment steps are in [Deploying the combined stack on another
system](#deploying-the-combined-stack-on-another-system); the editor only needs
the extra `LUMENROOM_*` and `BRIDGE_SECRET` values shown there.
Values in `.env` (all optional except the secret):
```dotenv
# Browser-facing URL of the editor. Users' devices must reach it.
LUMENROOM_URL=http://<lan-ip>:8787
# One long random string, shared by both services.
BRIDGE_SECRET=<64+ random characters>
# Optional tuning
# GLENLOCH_URL=http://app:3000 # internal; the service default
# LUMENROOM_PORT=8787
# LUMENROOM_BIND=0.0.0.0 # set 127.0.0.1 behind a proxy
# LUMENROOM_BRIDGE_TTL_HOURS=12
# LUMENROOM_INVITE=our-team
```
`BRIDGE_SECRET` only signs bridge tokens; it is never sent to the browser as a
credential. The token minted when you click **Advanced** expires in 10 minutes
and is scoped to one user and one event. With `BRIDGE_SECRET` empty the button
is visible but reports that the editor is not configured.
`GLENLOCH_URL` is server-to-server inside the Compose network (default
`http://app:3000`), so it needs no TLS. `LUMENROOM_URL` is different: the user's
browser is redirected there, so it must be a reachable address — the host's LAN
IP for a local stack, or an HTTPS hostname in production.
**Reverse proxy.** Lumenroom's UI fetches `/api/...` from the root of its own
origin, so give it a hostname, not a path prefix:
```caddy
edit.example.org {
reverse_proxy lumenroom:8787
}
```
Then set `LUMENROOM_URL=https://edit.example.org` and
`LUMENROOM_BIND=127.0.0.1`. Putting both apps on the same site
(`media.example.org`, `edit.example.org`) keeps the redirect and its cookie
first-party.
**Data.** `lumenroom` keeps only temporary bridge data in the `lumenroom-data`
volume (SQLite catalog, cached previews and thumbnails); originals stay on the
media share and the edited JPEGs are written back there. That volume can be
left out of backups. To run the editor on its own instead, its
`lumenroom/docker-compose.yml` still works standalone.
**How it behaves.** Clicking **Advanced** in the photo editor opens the same
event in Lumenroom already signed in — no second password. Lumenroom shows a
banner with **Save to event** (renders the open photo at full size and stores it
as the event photo's edited JPEG, so thumbnails, delivery exports and the
`variant=edited` viewer use it) and **Back to dashboard**. Photos remain on the
media share; only the temporary catalog rows, thumbnails and previews live in
Lumenroom's data volume. RAW files get a 4000 px JPEG proxy generated by the dashboard's
RAW decoder (cached in Lumenroom) instead of the simple editor's 1800 px
preview, so advanced RAW exports are larger than the simple editor's.
The advanced recipe is stored in `event_photos.advanced_edit_json`, separate from
the simple editor's recipe; saving in either editor replaces the generated JPEG
that the gallery shows.
## Project structure
```text
@@ -602,6 +810,7 @@ git switch main
├── docs/ Product spec, architecture, build plan, current state
├── drizzle/ Migrations, snapshots, journal
├── e2e/ Playwright specs and shared helpers
├── lumenroom/ Advanced photo editor (Vite + Node), built by compose
├── public/ Static assets
├── src/
│ ├── app/ Pages, layouts, API route handlers
@@ -611,7 +820,7 @@ git switch main
│ ├── domain/ Pure, unit-tested business rules
│ └── lib/ Timezone, tokens, email, storage, media, backup helpers
├── Dockerfile Multi-stage build; tools stage for migrations
├── docker-compose.yml App + Postgres + one-shot migrate/seed
├── docker-compose.yml App + Lumenroom + Postgres + one-shot migrate/seed
├── drizzle.config.ts
├── next.config.ts
├── playwright.config.ts
@@ -628,7 +837,7 @@ git switch main
| `/schedule/print`, `/run-sheet/[instanceId]` | Printable roster and editable run sheet |
| `/availability` | Personal and team blackout management |
| `/coverage` | Swap/release requests and public intake |
| `/events`, `/events/[id]` | One-off events, briefs, photographers, folders |
| `/events`, `/events/[id]` | One-off events, briefs, photographers, photo gallery |
| `/media`, `/media/[id]` | Photo/video library and public video page |
| `/training`, `/training/guides/*` | Lessons, attachments, role guides |
| `/announcements` | Team feed |
+55
View File
@@ -62,6 +62,12 @@ services:
# as media storage once the app checks the configured share.
ARCHIVE_DIR: /archive
NFS_SHARE: ${NFS_SHARE:-}
# Advanced-editor bridge. Both must be set for "Advanced" in the photo
# editor to work; the secret must match Lumenroom's BRIDGE_SECRET.
BRIDGE_SECRET: ${BRIDGE_SECRET:-}
# Browser-facing URL of the vendored Lumenroom service below. On a LAN
# that is http://<lan-ip>:8787; behind TLS use https://edit.example.org.
LUMENROOM_URL: ${LUMENROOM_URL:-http://localhost:8787}
volumes:
- outbox-data:/tmp/outbox
- uploads-data:/tmp/uploads
@@ -85,6 +91,54 @@ services:
max-file: "3"
restart: unless-stopped
# Notification dispatcher. The app only queues mail in the outbox; this loop
# drains it through the CRON_SECRET endpoint, so assignment, publish and
# reminder emails go out without anyone pressing a button.
cron:
image: curlimages/curl:8.10.1
environment:
CRON_SECRET: ${CRON_SECRET:-}
depends_on:
app:
condition: service_healthy
entrypoint: ["sh", "-c"]
command:
- 'while true; do echo "cron tick"; curl -fsS --max-time 30 -H "Authorization: Bearer $$CRON_SECRET" http://app:3000/api/dev/cron/notifications || echo "notification tick failed"; echo; sleep 60; done'
restart: unless-stopped
logging:
options:
max-size: "10m"
max-file: "3"
# Advanced photo editor (Lumenroom), vendored under ./lumenroom so one clone
# and one `docker compose up -d --build` deploys both apps. Its catalog is
# temporary bridge data; originals stay on the app's media storage.
lumenroom:
build:
context: ./lumenroom
dockerfile: Dockerfile
environment:
NODE_ENV: production
# Internal address: only Lumenroom's server calls the dashboard.
GLENLOCH_URL: ${GLENLOCH_URL:-http://app:3000}
# Must match the app's BRIDGE_SECRET, or "Advanced" fails to sign in.
BRIDGE_SECRET: ${BRIDGE_SECRET:-}
LUMENROOM_BRIDGE_TTL_HOURS: ${LUMENROOM_BRIDGE_TTL_HOURS:-12}
LUMENROOM_INVITE: ${LUMENROOM_INVITE:-}
LUMENROOM_RAW_WORKERS: ${LUMENROOM_RAW_WORKERS:-4}
volumes:
# SQLite catalog, cached previews and thumbnails (safe to lose).
- lumenroom-data:/data
ports:
# The browser must reach this directly. Put it behind the same reverse
# proxy and bind it to loopback there, e.g. LUMENROOM_BIND=127.0.0.1.
- "${LUMENROOM_BIND:-0.0.0.0}:${LUMENROOM_PORT:-8787}:8787"
logging:
options:
max-size: "10m"
max-file: "3"
restart: unless-stopped
db:
image: postgres:16-alpine
environment:
@@ -125,3 +179,4 @@ volumes:
outbox-data:
uploads-data:
archive-data:
lumenroom-data:
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE "bridge_sessions" (
"id" text PRIMARY KEY NOT NULL,
"user_id" text NOT NULL,
"event_id" text NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "event_photos" ADD COLUMN "advanced_edit_json" text;--> statement-breakpoint
ALTER TABLE "bridge_sessions" ADD CONSTRAINT "bridge_sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "bridge_sessions" ADD CONSTRAINT "bridge_sessions_event_id_events_id_fk" FOREIGN KEY ("event_id") REFERENCES "public"."events"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "bridge_sessions_event_idx" ON "bridge_sessions" USING btree ("event_id");
+15
View File
@@ -0,0 +1,15 @@
CREATE TABLE "assignment_proposals" (
"id" text PRIMARY KEY NOT NULL,
"assignment_id" text NOT NULL,
"user_id" text NOT NULL,
"proposed_instance_id" text NOT NULL,
"note" text,
"status" text DEFAULT 'pending' NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_assignment_id_assignments_id_fk" FOREIGN KEY ("assignment_id") REFERENCES "public"."assignments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_proposed_instance_id_service_instances_id_fk" FOREIGN KEY ("proposed_instance_id") REFERENCES "public"."service_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "assignment_proposals_pending_assignment_idx" ON "assignment_proposals" USING btree ("assignment_id") WHERE "assignment_proposals"."status" = 'pending';--> statement-breakpoint
CREATE INDEX "assignment_proposals_status_idx" ON "assignment_proposals" USING btree ("status","created_at");
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+14
View File
@@ -155,6 +155,20 @@
"when": 1795141771191,
"tag": "0021_sparkling_exiles",
"breakpoints": true
},
{
"idx": 22,
"version": "7",
"when": 1795223283100,
"tag": "0022_fixed_squadron_supreme",
"breakpoints": true
},
{
"idx": 23,
"version": "7",
"when": 1795274972891,
"tag": "0023_assignment_proposals",
"breakpoints": true
}
]
}
+11 -22
View File
@@ -4,8 +4,8 @@ import { signInAs, resetDb, BASE } from "./dev";
/**
* Event photography (J/K slice): a coordinator creates an event and assigns two
* photographers; the first creates a folder and uploads an edited JPEG plus a
* RAW original; the second — not the uploader — downloads the untouched bytes.
* photographers; the first uploads a JPEG and a RAW original straight onto the
* event page; the second — not the uploader — downloads the untouched bytes.
* An unassigned volunteer cannot open the event at all.
*/
@@ -56,17 +56,13 @@ test.describe("event photo sharing", () => {
await expect(page.getByText("Sam Okafor").first()).toBeVisible();
});
test("an assigned photographer creates a folder and uploads files", async ({
test("an assigned photographer uploads files on the event page", async ({
page,
}) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "avery@glenloch.local");
await page.goto(eventUrl);
await page.getByLabel("New folder").fill("Originals");
await page.getByRole("button", { name: "Create folder" }).click();
await page.getByRole("link", { name: /Originals/ }).click();
await page.getByLabel("Choose photos to upload").setInputFiles([
{ name: PHOTO_NAME, mimeType: "image/jpeg", buffer: PHOTO },
{ name: "raw.CR3", mimeType: "application/octet-stream", buffer: RAW },
@@ -84,11 +80,9 @@ test.describe("event photo sharing", () => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "sam@glenloch.local");
await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
const [download] = await Promise.all([
page.waitForEvent("download"),
// Exact: the folder header also offers "Download folder (n)".
page.getByRole("link", { name: "Download", exact: true }).first().click(),
]);
const downloadPath = await download.path();
@@ -112,11 +106,11 @@ test.describe("event photo sharing", () => {
const zip = await readFile(downloadPath!);
expect(zip.subarray(0, 4).toString("binary")).toBe("PK\x03\x04");
// Store-only entries keep the original bytes and folder paths in the ZIP.
// Store-only entries keep the original bytes; uploads share one folder.
expect(zip.includes(PHOTO)).toBe(true);
expect(zip.includes(RAW)).toBe(true);
expect(zip.includes(Buffer.from(`Originals/${PHOTO_NAME}`))).toBe(true);
expect(zip.includes(Buffer.from("Originals/raw.CR3"))).toBe(true);
expect(zip.includes(Buffer.from(`Photos/${PHOTO_NAME}`))).toBe(true);
expect(zip.includes(Buffer.from("Photos/raw.CR3"))).toBe(true);
});
test("a photographer views a photo and saves a full-resolution edited JPEG", async ({
@@ -125,7 +119,6 @@ test.describe("event photo sharing", () => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "sam@glenloch.local");
await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
await page
.getByRole("button", { name: `View and edit ${PHOTO_NAME}` })
@@ -136,21 +129,18 @@ test.describe("event photo sharing", () => {
await page.getByLabel("Exposure").focus();
await page.getByLabel("Exposure").press("ArrowRight");
await page.getByRole("button", { name: "Save edited JPEG" }).click();
await expect(page.getByText("Full-resolution JPEG saved.")).toBeVisible({
timeout: 30_000,
});
// A successful save closes the editor and returns to the refreshed gallery.
await expect(page.getByRole("dialog")).toBeHidden({ timeout: 30_000 });
await expect(page.getByText("Edited", { exact: true })).toBeVisible();
const [download] = await Promise.all([
page.waitForEvent("download"),
page.getByRole("link", { name: "Download edited JPEG" }).click(),
page.getByRole("link", { name: "Download edited" }).click(),
]);
expect(download.suggestedFilename()).toBe("photo-edited.jpg");
const edited = await readFile((await download.path())!);
expect(edited.subarray(0, 3).toString("hex")).toBe("ffd8ff");
expect(edited.equals(PHOTO)).toBe(false);
await page.getByRole("button", { name: "Close photo editor" }).click();
await expect(page.getByText("Edited", { exact: true })).toBeVisible();
await expect(page.locator(`img[alt="${PHOTO_NAME}"]`)).toHaveAttribute(
"src",
/variant=edited/,
@@ -164,7 +154,7 @@ test.describe("event photo sharing", () => {
]);
const zip = await readFile((await zipDownload.path())!);
expect(zip.includes(edited)).toBe(true);
expect(zip.includes(Buffer.from("Originals/photo-edited.jpg"))).toBe(true);
expect(zip.includes(Buffer.from("Photos/photo-edited.jpg"))).toBe(true);
});
test("an unassigned volunteer cannot open the event", async ({ page }) => {
@@ -178,7 +168,6 @@ test.describe("event photo sharing", () => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
const photoHref = await page
.getByRole("link", { name: "Download", exact: true })
.first()
+4 -7
View File
@@ -158,14 +158,11 @@ test.describe("growth goals and maintenance", () => {
"No media storage share",
);
await page.goto(`${BASE}/events/${eventId}/folders/${folderId}`);
await expect(page.getByRole("alert").first()).toContainText(
"Photo uploads and editing are disabled",
);
await page.goto(`${BASE}/events/${eventId}`);
await expect(page.getByRole("alert").first()).toContainText(
"Photo and video uploads are disabled",
);
await expect(
page.getByText("Photo uploads and editing are disabled"),
).toBeVisible();
await expect(page.getByText("Photo and video uploads are disabled")).toBeVisible();
// A share name that reads like `host:/export` while the path is a local
// directory must block writes: media would silently land on local disk.
+1
View File
@@ -14,6 +14,7 @@ const eslintConfig = [
{
ignores: [
"node_modules/**",
"lumenroom/**",
".next/**",
"out/**",
"build/**",
+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
+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 \
LUMENROOM_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/lumenroom-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"]
+194
View File
@@ -0,0 +1,194 @@
# Lumenroom
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)
LUMENROOM_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; everyone else registers with `LUMENROOM_INVITE`. 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 lumenroom .
docker run -d --name lumenroom \
-p 8787:8787 \
-e LUMENROOM_INVITE=our-team \
-v lumenroom-data:/data \
lumenroom
```
Or with Compose, which wires up the volume and env vars for you:
```bash
LUMENROOM_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/lumenroom-$(date +%F).tar.gz -C /data .
```
Environment variables:
| Variable | Default | Purpose |
| --- | --- | --- |
| `PORT` | `8787` | Server port |
| `LUMENROOM_DATA` | `server/data` | Where originals, previews and the database live |
| `LUMENROOM_INVITE` | *(empty)* | Invite code for new accounts; empty closes registration |
| `LUMENROOM_MAX_UPLOAD` | `300 MB` | Upload ceiling (bytes) |
| `LUMENROOM_RAW_EDGE` | `6000` | Long edge of the editable proxy generated for raws |
| `LUMENROOM_RAW_WORKERS` | `4` (capped at cores−1) | Raws demosaiced at once; each worker holds a LibRaw instance |
| `LUMENROOM_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this, to hand memory back |
## 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> \
LUMENROOM_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 |
| `LUMENROOM_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
`LUMENROOM_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.
**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
- 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, copy/paste settings,
before/after
**Export** — format (JPEG/PNG/WebP), quality, resize by long edge or percent,
filename template (`{name}`, `{date}`, `{time}`, `{index}`), batch export of the
selection, full resolution through the same renderer.
## 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
`LUMENROOM_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,
`LUMENROOM_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/ db, api client, edits model, import/export, presets
components/ library grid, develop, panels, modals
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, masking/brushes, lens corrections, panoramas/HDR merge, or
tethered capture. Local adjustments are the biggest missing editor feature.
- 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.
- 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.
- File deletion is immediate; there is no trash or catalog backup.
+26
View File
@@ -0,0 +1,26 @@
services:
lumenroom:
build: .
image: lumenroom:latest
container_name: lumenroom
restart: unless-stopped
ports:
- "${LUMENROOM_PORT:-8787}:8787"
environment:
# Invite code for every account after the first (admin) one.
LUMENROOM_INVITE: ${LUMENROOM_INVITE:-}
LUMENROOM_MAX_UPLOAD: ${LUMENROOM_MAX_UPLOAD:-322122547}
LUMENROOM_RAW_EDGE: ${LUMENROOM_RAW_EDGE:-6000}
# Parallel raw decoders; each one holds a LibRaw worker (few hundred MB).
LUMENROOM_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:-}
LUMENROOM_BRIDGE_TTL_HOURS: ${LUMENROOM_BRIDGE_TTL_HOURS:-12}
volumes:
# Originals, previews, thumbnails and the SQLite catalog.
- lumenroom-data:/data
volumes:
lumenroom-data:
Binary file not shown.
+786
View File
@@ -0,0 +1,786 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lumenroom — 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> Lumenroom</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 Lumenroom 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 sample shoot loaded. The sample photographs are simple colour fields, so anything you see on them — grain, a crop, a graded shadow — is the renderer at work rather than a photograph hiding it.</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">Lumenroom 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, Lumenroom 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 an import. The sidebar lists the catalogue and its events, 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 files staged. The summary counts the batch and flags raw files; the warning appears because no server is signed in, so raws would have to wait.</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>. 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>, <b>Copy settings</b> and <b>Paste settings</b>, <b>Reset adjustments</b>, <b>Export…</b> and <b>Delete…</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. The rectangle has been pulled in from the corner, the crop panel shows the aspect presets and the straighten 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 sits at the centre 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>LUMENROOM_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">Lumenroom 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: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 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>Lumenroom</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2436
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "lumenroom",
"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"
},
"dependencies": {
"exifr": "^7.1.3",
"libraw-wasm": "^1.6.0",
"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"
}
}
Binary file not shown.
+58
View File
@@ -0,0 +1,58 @@
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;
}
return publicUser(users.byId(session.user_id));
}
export function normalizeEmail(value) {
return typeof value === 'string' ? value.trim().toLowerCase() : '';
}
export function validEmail(email) {
return /^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(email);
}
+294
View File
@@ -0,0 +1,294 @@
/**
* 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, getPhoto, 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`,
// Thumbnail of the saved edit; the timestamp keeps the browser from reusing
// a thumbnail rendered before the edit was saved.
thumbVersion: photo.editedAt ? Date.parse(photo.editedAt) || undefined : undefined,
rating: 0,
flag: 'none',
color: '',
keywords: [],
// The dashboard sends back the recipe saved for this photo, so reopening
// the advanced editor starts from the sliders the user left it with.
edits:
photo.edits && typeof photo.edits === 'object' ? photo.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, returnUrl }) {
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);
// Preserve anything still unsaved locally before the import replaces rows, so
// reopening the editor never discards work in progress.
const localEdits = new Map();
for (const row of photosForEvent.all(eventId)) {
const record = getPhoto(row.id);
if (record?.edits && Object.keys(record.edits).length > 0) {
localEdits.set(row.id, record);
}
}
dropBridgeEvent(eventId);
// The exchange hands back the dashboard address the browser actually used;
// the listing's value is a fallback derived from server configuration and may
// point at localhost in a LAN deployment.
const dashboardReturn =
typeof returnUrl === 'string' && /^https?:\/\//i.test(returnUrl)
? returnUrl
: listing.editor?.returnUrl ?? null;
saveEvent(eventRecordFrom(listing, eventId, sessionId, dashboardReturn, expiresAt), 0);
listing.photos.forEach((photo, index) => {
const record = photoRecordFrom(photo, eventId, sessionId, index);
const local = localEdits.get(record.id);
if (local) {
record.edits = local.edits;
if (Array.isArray(local.history) && local.history.length > 0) {
record.history = local.history;
}
}
savePhoto(record);
});
bridgeInsert.run(
eventId,
sessionId,
serviceToken,
GLENLOCH_URL,
listing.event.id,
dashboardReturn,
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 };
}
+51
View File
@@ -0,0 +1,51 @@
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, '..');
export const DATA_DIR = process.env.LUMENROOM_DATA
? path.resolve(process.env.LUMENROOM_DATA)
: 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');
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 = process.env.LUMENROOM_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(process.env.LUMENROOM_BRIDGE_TTL_HOURS || 12);
/** Upload ceiling in bytes (300 MB default, bigger than any consumer raw). */
export const MAX_UPLOAD = Number(process.env.LUMENROOM_MAX_UPLOAD || 300 * 1024 * 1024);
/** Long edge used for the editable proxy of raw files. */
export const RAW_PREVIEW_EDGE = Number(process.env.LUMENROOM_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(
process.env.LUMENROOM_RAW_WORKERS ||
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(process.env.LUMENROOM_RAW_IDLE_MS || 90_000);
+177
View File
@@ -0,0 +1,177 @@
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',
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,
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,
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 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
);
`);
const q = {
upsertEvent: db.prepare(`
INSERT INTO events (id, sort_index, created_at, data) VALUES (?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET sort_index = excluded.sort_index, data = excluded.data
`),
deleteEvent: db.prepare('DELETE FROM events WHERE id = ?'),
allEvents: db.prepare('SELECT data FROM events ORDER BY sort_index ASC, created_at ASC'),
upsertPhoto: db.prepare(`
INSERT INTO photos (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
`),
deletePhoto: db.prepare('DELETE FROM photos WHERE id = ?'),
allPhotos: db.prepare('SELECT data FROM photos ORDER BY sort_index ASC, updated_at ASC'),
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, created_at FROM users WHERE id = ?'),
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 = ?'),
purgeSessions: db.prepare('DELETE FROM sessions WHERE 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() {
return q.allEvents.all().map((r) => parse(r.data)).filter((r) => r !== null);
}
export function saveEvent(record, sortIndex = 0) {
q.upsertEvent.run(record.id, sortIndex, record.createdAt ?? Date.now(), JSON.stringify(record));
}
export function removeEvent(id) {
q.deleteEvent.run(id);
}
export function listPhotos() {
return q.allPhotos.all().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 savePhoto(record, updatedAt = Date.now()) {
q.upsertPhoto.run(
record.id,
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);
}
export function countPhotos() {
return Number(q.photoCount.get()?.n ?? 0);
}
export const users = {
count: () => Number(q.userCount.get()?.n ?? 0),
byEmail: (email) => q.findUserByEmail.get(String(email).toLowerCase()),
byId: (id) => q.findUserById.get(id),
create: (user) =>
q.insertUser.run(user.id, user.email.toLowerCase(), user.name, user.passHash, user.role, Date.now()),
};
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),
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)),
};
+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;
}
}
+603
View File
@@ -0,0 +1,603 @@
import http from 'node:http';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';
import {
DATA_DIR,
DIST_DIR,
HOST,
INVITE,
MAX_UPLOAD,
PORT,
RAW_PREVIEW_EDGE,
} from './config.mjs';
import {
authenticate,
createSession,
hashPassword,
normalizeEmail,
publicUser,
validEmail,
verifyPassword,
} from './auth.mjs';
import {
countPhotos,
getPhoto,
kv,
listEvents,
listPhotos,
removeEvent,
removePhoto,
saveEvent,
savePhoto,
sessions,
users,
} from './db.mjs';
import {
findOriginal,
findPreview,
findThumb,
removeAsset,
removeThumb,
storageBytes,
writeOriginal,
writePreview,
writeThumb,
} from './storage.mjs';
import { decodeRaw, isRawName, rawSupport } from './raw.mjs';
import {
bridgeConfigured,
bridgeForEvent,
exchangeBridgeToken,
fetchBridgeImage,
forwardBridgeRender,
importBridgeEvent,
purgeExpiredBridges,
verifyBridgeToken,
} from './bridge.mjs';
import { jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs';
const VERSION = '1.0.0';
const COOKIE = 'lumen_session';
/* ------------------------------------------------------------------ helpers */
function json(res, status, payload, extraHeaders = {}) {
const body = Buffer.from(JSON.stringify(payload));
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': body.length,
'Cache-Control': 'no-store',
...extraHeaders,
});
res.end(body);
}
function error(res, status, message) {
json(res, status, { error: message });
}
function parseCookies(req) {
const out = {};
for (const part of String(req.headers.cookie ?? '').split(';')) {
const idx = part.indexOf('=');
if (idx < 0) continue;
out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim());
}
return out;
}
function sessionCookie(req, token, maxAge) {
const secure = req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : '';
return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`;
}
function currentUser(req) {
const cookieToken = parseCookies(req)[COOKIE];
if (cookieToken) {
const row = sessions.find(cookieToken);
if (row && Number(row.expires_at) > Date.now()) return publicUser(users.byId(row.user_id));
}
return authenticate(req);
}
function readBody(req, limit = MAX_UPLOAD) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > limit) {
reject(new Error(`Upload exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => resolve(Buffer.concat(chunks)));
req.on('error', reject);
});
}
async function readJson(req, limit = 8 * 1024 * 1024) {
const raw = await readBody(req, limit);
if (!raw.length) return {};
try {
return JSON.parse(raw.toString('utf8'));
} catch {
throw new Error('Request body is not valid JSON');
}
}
function match(pathname, pattern) {
const p = pattern.split('/');
const a = pathname.split('/');
if (p.length !== a.length) return null;
const params = {};
for (let i = 0; i < p.length; i++) {
if (p[i].startsWith(':')) {
params[p[i].slice(1)] = decodeURIComponent(a[i]);
} else if (p[i] !== a[i]) {
return null;
}
}
return params;
}
function sendBuffer(res, data, type, cache = 'private, max-age=3600') {
res.writeHead(200, {
'Content-Type': type,
'Content-Length': data.length,
'Cache-Control': cache,
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
});
res.end(data);
}
/** The bridge row and source id for a photo imported from the dashboard. */
function bridgeLinkForPhoto(photoId) {
const photo = getPhoto(photoId);
if (!photo?.eventId) return null;
const bridge = bridgeForEvent(photo.eventId);
if (!bridge) return null;
const sourceId = photo.bridgeSource?.sourceId ?? photoId.replace(/^br-/, '');
return { photo, bridge, sourceId };
}
async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400') {
if (!filePath) return error(res, 404, 'Not found');
try {
const stat = await fsp.stat(filePath);
res.writeHead(200, {
'Content-Type': type,
'Content-Length': stat.size,
'Cache-Control': cache,
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
});
if (req.method === 'HEAD') return res.end();
fs.createReadStream(filePath).pipe(res);
} catch {
error(res, 404, 'Not found');
}
}
function decodeDataUrl(value) {
if (typeof value !== 'string') return null;
const m = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=\s]+)$/.exec(value);
if (!m) return null;
return { mime: `image/${m[1]}`, data: Buffer.from(m[2], 'base64') };
}
/* --------------------------------------------------------------------- api */
const routes = [];
function route(method, pattern, handler) {
routes.push({ method, pattern, handler });
}
route('GET', '/api/health', async ({ res }) => {
const raw = await rawSupport();
json(res, 200, {
ok: true,
app: 'lumenroom',
version: VERSION,
needsSetup: users.count() === 0,
registrationOpen: users.count() === 0 || Boolean(INVITE),
photos: countPhotos(),
bytes: storageBytes(),
raw,
});
});
route('POST', '/api/auth/register', async ({ req, res }) => {
const body = await readJson(req, 64 * 1024);
const email = normalizeEmail(body.email);
const password = typeof body.password === 'string' ? body.password : '';
const name = typeof body.name === 'string' ? body.name.trim().slice(0, 80) : '';
if (!validEmail(email)) return error(res, 400, 'Enter a valid email address');
if (password.length < 8) return error(res, 400, 'Use at least 8 characters for the password');
if (users.byEmail(email)) return error(res, 409, 'That email is already registered');
const first = users.count() === 0;
if (!first) {
if (!INVITE) return error(res, 403, 'Registration is closed. Ask an admin for an invite code.');
if (String(body.invite ?? '') !== INVITE) return error(res, 403, 'Invite code is not correct');
}
const id = crypto.randomUUID();
users.create({
id,
email,
name: name || email.split('@')[0],
passHash: hashPassword(password),
role: first ? 'admin' : 'member',
});
const token = createSession(id);
json(
res,
201,
{ token, user: publicUser(users.byId(id)) },
{ 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) },
);
});
route('POST', '/api/auth/login', async ({ req, res }) => {
const body = await readJson(req, 64 * 1024);
const email = normalizeEmail(body.email);
const password = typeof body.password === 'string' ? body.password : '';
const row = users.byEmail(email);
if (!row || !verifyPassword(password, row.pass_hash)) return error(res, 401, 'Email or password is not correct');
const token = createSession(row.id);
json(
res,
200,
{ token, user: publicUser(users.byId(row.id)) },
{ 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) },
);
});
route('POST', '/api/auth/logout', async ({ req, res }) => {
const token = parseCookies(req)[COOKIE];
if (token) sessions.destroy(token);
json(res, 200, { ok: true }, { 'Set-Cookie': `${COOKIE}=; Path=/; HttpOnly; Max-Age=0` });
});
route('GET', '/api/auth/me', async ({ req, res }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
json(res, 200, { user });
});
route('GET', '/api/bridge/login', async ({ req, res, url }) => {
if (!bridgeConfigured()) {
return error(res, 503, 'The advanced editor bridge is not configured');
}
const token = url.searchParams.get('token') || '';
const payload = verifyBridgeToken(token);
if (!payload || payload.kind !== 'login') {
return error(res, 401, 'This advanced-editor link is invalid or has expired');
}
try {
const service = await exchangeBridgeToken(token, payload.sid);
const email = normalizeEmail(payload.email);
if (!validEmail(email)) {
return error(res, 400, 'The dashboard account has no usable email address');
}
let row = users.byEmail(email);
if (!row) {
const id = crypto.randomUUID();
users.create({
id,
email,
name: payload.name || email.split('@')[0],
passHash: hashPassword(crypto.randomBytes(24).toString('hex')),
role: 'member',
});
row = users.byId(id);
}
purgeExpiredBridges();
const imported = await importBridgeEvent({
serviceToken: service.token,
sessionId: payload.sid,
returnUrl: service.returnUrl,
});
const sessionToken = createSession(row.id);
res.writeHead(302, {
Location: `/?bridge=${encodeURIComponent(imported.eventId)}`,
'Set-Cookie': sessionCookie(req, sessionToken, 30 * 24 * 3600),
'Cache-Control': 'no-store',
});
res.end();
} catch (err) {
return error(
res,
502,
err instanceof Error ? err.message : 'Could not open the advanced editor',
);
}
});
route('GET', '/api/sync', async ({ req, res }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
json(res, 200, {
user,
events: listEvents(),
photos: listPhotos(),
presets: kv.get('presets') ?? [],
});
});
route('PUT', '/api/events/:id', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
const body = await readJson(req, 256 * 1024);
const record = { ...body, id: params.id };
saveEvent(record, typeof body.order === 'number' ? body.order : Number(body.createdAt ?? Date.now()));
json(res, 200, { event: record });
});
route('DELETE', '/api/events/:id', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
removeEvent(params.id);
json(res, 200, { ok: true });
});
route('PUT', '/api/presets', async ({ req, res }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
const body = await readJson(req, 512 * 1024);
kv.set('presets', Array.isArray(body.presets) ? body.presets : []);
json(res, 200, { ok: true });
});
/**
* Store the original file. Raw files are demosaiced here so every browser can
* edit them; ordinary images are kept byte-for-byte and previewed client-side.
*/
route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
const url = new URL(req.url ?? '/', 'http://localhost');
const name = url.searchParams.get('name') || 'upload';
const mime = url.searchParams.get('mime') || 'application/octet-stream';
const drop = url.searchParams.get('drop') === '1';
const data = await readBody(req);
if (!data.length) return error(res, 400, 'Empty upload');
const ext = (name.split('.').pop() || 'bin').toLowerCase();
await writeOriginal(params.id, ext, data);
if (isRawName(name) || drop) {
try {
const decoded = await decodeRaw(data);
await writePreview(params.id, decoded.jpeg, decoded.ext);
const info = await jpegInfo(decoded.jpeg);
return json(res, 201, {
raw: true,
engine: decoded.engine,
width: info?.width || decoded.width,
height: info?.height || decoded.height,
mime: 'image/jpeg',
previewUrl: `/api/photos/${params.id}/preview`,
thumbUrl: `/api/photos/${params.id}/thumb`,
note: decoded.note ?? null,
maxEdge: RAW_PREVIEW_EDGE,
});
} catch (err) {
return error(res, 422, err instanceof Error ? err.message : 'Could not decode this raw file');
}
}
return json(res, 201, { raw: false, mime, size: data.length });
});
route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => {
const thumb = findThumb(params.id);
if (thumb) return sendFile(req, res, thumb, 'image/jpeg');
const linked = bridgeLinkForPhoto(params.id);
if (!linked) return error(res, 404, 'Not found');
const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'thumb');
if (!upstream.ok) return error(res, 404, 'Thumbnail unavailable');
const data = Buffer.from(await upstream.arrayBuffer());
await writeThumb(params.id, data);
return sendBuffer(res, data, 'image/jpeg');
});
route('GET', '/api/photos/:id/preview', async ({ req, res, params }) => {
const preview = findPreview(params.id);
if (preview) return sendFile(req, res, preview, preview.endsWith('.png') ? 'image/png' : 'image/jpeg');
const linked = bridgeLinkForPhoto(params.id);
if (linked) {
const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'proxy');
if (!upstream.ok) return error(res, 404, 'Preview unavailable');
const data = Buffer.from(await upstream.arrayBuffer());
await writePreview(params.id, data);
const info = await jpegInfo(data);
if (info?.width && info?.height) {
savePhoto({ ...linked.photo, width: info.width, height: info.height, mime: 'image/jpeg', size: data.length });
}
return sendBuffer(res, data, 'image/jpeg');
}
return sendFile(req, res, findOriginal(params.id), 'application/octet-stream');
});
route('GET', '/api/photos/:id/original', async ({ req, res, params }) => {
const original = findOriginal(params.id);
if (original) return sendFile(req, res, original, 'application/octet-stream', 'private, max-age=3600');
const linked = bridgeLinkForPhoto(params.id);
if (!linked) return error(res, 404, 'Not found');
const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'original');
if (!upstream.ok) return error(res, 404, 'Original unavailable');
const data = Buffer.from(await upstream.arrayBuffer());
return sendBuffer(res, data, linked.photo.mime || 'application/octet-stream');
});
route('POST', '/api/bridge/export', async ({ req, res }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
const body = await readJson(req, 64 * 1024 * 1024);
if (typeof body.photoId !== 'string' || typeof body.jpeg !== 'string') {
return error(res, 400, 'A photo id and a rendered JPEG are required');
}
const linked = bridgeLinkForPhoto(body.photoId);
if (!linked) return error(res, 404, 'This photo is not part of an advanced edit');
const result = await forwardBridgeRender(linked.bridge, linked.sourceId, {
jpeg: body.jpeg,
edits: body.edits ?? {},
});
if (result.status >= 400) {
return error(res, result.status, result.body?.error || 'The edit could not be saved to the event');
}
// The grid now shows the dashboard's thumbnail of this render, so drop the
// cached copy and bump the URL the browser asks for.
await removeThumb(body.photoId).catch(() => undefined);
const thumbVersion = Date.now();
const stored = getPhoto(body.photoId);
if (stored) {
stored.thumbVersion = thumbVersion;
savePhoto(stored);
}
return json(res, 200, { ...(result.body ?? { ok: true }), thumbVersion });
});
route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
const body = await readJson(req);
if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL');
const record = { ...body, id: params.id };
const thumb = decodeDataUrl(record.thumb);
if (thumb) {
await writeThumb(params.id, thumb.data);
delete record.thumb;
}
if (record.raw) {
record.previewUrl = `/api/photos/${params.id}/preview`;
const preview = findPreview(params.id);
if (!preview) {
const original = findOriginal(params.id);
if (original) {
const proxy = await toJpegProxy(await fsp.readFile(original));
if (proxy) await writePreview(params.id, proxy.data, proxy.ext);
}
}
}
record.thumbUrl = `/api/photos/${params.id}/thumb`;
savePhoto(record);
json(res, 200, { photo: record });
});
route('DELETE', '/api/photos/:id', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
removePhoto(params.id);
await removeAsset(params.id);
json(res, 200, { ok: true });
});
/* ---------------------------------------------------------------- static ui */
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.pdf': 'application/pdf',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.map': 'application/json; charset=utf-8',
};
async function serveStatic(req, res, url) {
const pathname = decodeURIComponent(url.pathname);
const candidate = path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname);
if (candidate.startsWith(DIST_DIR)) {
try {
const stat = await fsp.stat(candidate);
if (stat.isFile()) {
const ext = path.extname(candidate).toLowerCase();
const immutable = pathname.startsWith('/assets/');
return sendFile(
req,
res,
candidate,
MIME[ext] ?? 'application/octet-stream',
immutable ? 'public, max-age=31536000, immutable' : 'no-cache',
);
}
} catch {
/* fall through to the SPA entry */
}
}
const index = path.join(DIST_DIR, 'index.html');
if (!fs.existsSync(index)) {
return error(
res,
503,
'The web build is missing. Run "npm run build" (or use "npm run dev" with the Vite dev server).',
);
}
return sendFile(req, res, index, MIME['.html'], 'no-cache');
}
/* ------------------------------------------------------------------ server */
const server = http.createServer(async (req, res) => {
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('Referrer-Policy', 'same-origin');
try {
if (url.pathname.startsWith('/api/')) {
for (const r of routes) {
if (r.method !== req.method) continue;
const params = match(url.pathname, r.pattern);
if (!params) continue;
return await r.handler({ req, res, params, url });
}
return error(res, 404, `No route for ${req.method} ${url.pathname}`);
}
return await serveStatic(req, res, url);
} catch (err) {
const message = err instanceof Error ? err.message : 'Unexpected error';
console.error(`[lumenroom] ${req.method} ${url.pathname} → ${message}`);
if (!res.headersSent) return error(res, 500, message);
res.end();
}
});
server.listen(PORT, HOST, async () => {
const raw = await rawSupport();
console.log(`Lumenroom server listening on http://localhost:${PORT}`);
console.log(` data: ${DATA_DIR}`);
console.log(
` raw: libraw ${raw.libraw ? `ready (${raw.workers} parallel worker${raw.workers === 1 ? '' : 's'})` : 'missing'} · jpeg ${raw.sharp ? 'sharp' : 'png fallback'}`,
);
console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' — first signup becomes admin' : ''}`);
if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)');
});
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, () => {
server.close(() => process.exit(0));
});
}
+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 });
+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(),
};
}
+96
View File
@@ -0,0 +1,96 @@
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import { ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR } from './config.mjs';
for (const dir of [ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR]) fs.mkdirSync(dir, { recursive: true });
const SAFE = /^[A-Za-z0-9_-]{1,80}$/;
function safeId(id) {
if (!SAFE.test(id)) throw new Error('Invalid asset id');
return id;
}
/** Original files keep their real extension so a raw can be recovered later. */
function originalPath(id, ext = 'bin') {
return path.join(ORIGINAL_DIR, `${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;
}
/**
* 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;
}
export function findOriginal(id) {
const safe = lookupId(id);
if (!safe) return null;
const prefix = `${safe}.`;
for (const name of fs.readdirSync(ORIGINAL_DIR)) {
if (name.startsWith(prefix)) return path.join(ORIGINAL_DIR, name);
}
return null;
}
export async function writePreview(id, data, ext = 'jpg') {
const target = path.join(PREVIEW_DIR, `${safeId(id)}.${ext}`);
await fsp.writeFile(target, data);
return target;
}
export function findPreview(id) {
const safe = lookupId(id);
if (!safe) return null;
for (const ext of ['jpg', 'png']) {
const p = path.join(PREVIEW_DIR, `${safe}.${ext}`);
if (fs.existsSync(p)) return p;
}
return null;
}
export async function writeThumb(id, data) {
const target = path.join(THUMB_DIR, `${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(THUMB_DIR, `${safe}.jpg`);
return fs.existsSync(p) ? p : null;
}
/** Drops the cached grid thumbnail so the next request refetches it. */
export async function removeThumb(id) {
const thumb = findThumb(id);
if (thumb) await fsp.rm(thumb, { force: true });
}
export async function removeAsset(id) {
const files = [findOriginal(id), findPreview(id), findThumb(id)];
await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve())));
}
export function storageBytes() {
let total = 0;
for (const dir of [ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR]) {
for (const name of fs.readdirSync(dir)) {
try {
total += fs.statSync(path.join(dir, name)).size;
} catch {
/* file vanished mid-scan */
}
}
}
return total;
}
File diff suppressed because it is too large Load Diff
+196
View File
@@ -0,0 +1,196 @@
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;
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,
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>
</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 code</span>
<input
value={invite}
onChange={(e) => setInvite(e.target.value)}
placeholder="From your admin"
/>
</label>
)}
{mode === 'signup' && health.needsSetup && (
<p className="muted small">
The first account becomes the team admin. Share the invite code you set in{' '}
<code>LUMENROOM_INVITE</code> with everyone else.
</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>server/data</code> · raw formats:{' '}
{health.raw.formats.length} · {health.raw.sharp ? 'JPEG encoder ready' : 'PNG fallback'}
</p>
)}
</div>
</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>
);
}
+736
View File
@@ -0,0 +1,736 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits';
import { getBitmap, thumbSrc } from '../lib/images';
import { rotatedBounds, Renderer } from '../gl/renderer';
import type { Edits, EventRecord, PhotoRecord, Preset } from '../types';
import ContextMenu, { type MenuEntry } from './ContextMenu';
import CropOverlay from './CropOverlay';
import Histogram from './Histogram';
import {
BasicPanel,
ColorGradingPanel,
CropPanel,
CurvePanel,
DetailPanel,
EffectsPanel,
HistoryPanel,
HslPanel,
MetadataPanel,
NavigatorPanel,
PresetsPanel,
} from './Panels';
import Stars, { ColorSwatches, FlagButtons } from './Stars';
/** Zoom is expressed as a percentage of actual pixels, like Lightroom's readout. */
const MAX_ZOOM = 400;
const clampNum = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
interface Rect {
x: number;
y: number;
w: number;
h: number;
}
interface Geometry {
fitScale: number;
fitPct: number;
frameW: number;
frameH: number;
zoomFactor: number;
availW: number;
availH: number;
content: Rect;
view: Rect;
}
const EMPTY_GEO: Geometry = {
fitScale: 0,
fitPct: 100,
frameW: 1,
frameH: 1,
zoomFactor: 1,
availW: 0,
availH: 0,
content: { x: 0, y: 0, w: 1, h: 1 },
view: { x: 0, y: 0, w: 1, h: 1 },
};
interface Props {
photo: PhotoRecord;
photos: PhotoRecord[];
events: EventRecord[];
onSelect: (id: string) => void;
onExit: () => void;
onUpdate: (id: string, patch: Partial<PhotoRecord>, historyLabel?: string) => void;
onNavigate: (dir: -1 | 1) => void;
clipboard: Edits | null;
onCopy: () => void;
onPaste: () => void;
onExport: () => void;
presets: Preset[];
onSavePreset: (name: string, edits: Edits) => void;
onDelete: () => void;
}
export default function Develop({
photo,
photos,
events,
onSelect,
onExit,
onUpdate,
onNavigate,
clipboard,
onCopy,
onPaste,
onExport,
presets,
onSavePreset,
onDelete,
}: Props) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
const stripRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<Renderer | null>(null);
const histRef = useRef<Renderer['histogram'] | null>(null);
const geoRef = useRef<Geometry>(EMPTY_GEO);
const panRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null);
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
const [stage, setStage] = useState({ w: 0, h: 0 });
const [cropMode, setCropMode] = useState(false);
const [cropDrag, setCropDrag] = useState(false);
const [showOriginal, setShowOriginal] = useState(false);
const [histVersion, setHistVersion] = useState(0);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [zoom, setZoom] = useState<{ pct: number | 'fit'; cx: number; cy: number }>({
pct: 'fit',
cx: 0.5,
cy: 0.5,
});
const [panning, setPanning] = useState(false);
const [readout, setReadout] = useState({ shown: 100, fit: 100 });
const [menu, setMenu] = useState<{ x: number; y: number; kind: 'canvas' | 'film' } | null>(null);
const edits = photo.edits;
const zoomed = zoom.pct !== 'fit';
const setEdits = useCallback(
(patch: Partial<Edits>, label: string) => {
onUpdate(photo.id, { edits: { ...photo.edits, ...patch } }, label);
},
[onUpdate, photo.id, photo.edits],
);
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 el = stageRef.current;
if (!el) return;
setStage({ w: el.clientWidth, h: el.clientHeight });
const ro = new ResizeObserver((entries) => {
const rect = entries[0].contentRect;
setStage({ w: Math.round(rect.width), h: Math.round(rect.height) });
});
ro.observe(el);
return () => ro.disconnect();
}, [cropMode]);
useEffect(() => {
let alive = true;
setLoading(true);
getBitmap(photo)
.then((bmp) => {
if (!alive) return;
setBitmap(bmp);
setLoading(false);
})
.catch((err) => {
if (!alive) return;
setError(err instanceof Error ? err.message : 'Could not load the original image');
setLoading(false);
});
return () => {
alive = false;
};
}, [photo.id, photo.raw, photo.previewUrl]);
// A new photo, a crop change or entering crop mode all invalidate the current view.
useEffect(() => {
setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 });
}, [photo.id, cropMode, edits.crop]);
// Leaving crop mode mid-drag must not leave the grain frozen.
useEffect(() => {
if (!cropMode) setCropDrag(false);
}, [cropMode]);
const drawPreview = useCallback(() => {
const renderer = rendererRef.current;
const canvas = canvasRef.current;
if (!renderer || !canvas || !bitmap) return;
if (stage.w < 40 || stage.h < 40) return;
const activeEdits = showOriginal ? { ...defaultEdits(), crop: edits.crop } : edits;
const frame = rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter);
const content: Rect = cropMode
? { x: 0, y: 0, w: 1, h: 1 }
: { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h };
const contentW = Math.max(1, frame.w * content.w);
const contentH = Math.max(1, frame.h * content.h);
const availW = Math.max(60, stage.w - 48);
const availH = Math.max(60, stage.h - 48);
const fitScale = Math.min(availW / contentW, availH / contentH);
const fitPct = Math.min(100, fitScale * 100);
const zoomFactor = zoom.pct === 'fit' ? 1 : Math.max(1, zoom.pct / 100 / fitScale);
let view: Rect = content;
let cssW = Math.max(40, Math.round(contentW * fitScale));
let cssH = Math.max(40, Math.round(contentH * fitScale));
if (zoomFactor > 1.0001) {
// The visible window keeps the stage's aspect, so the canvas is stage sized
// and the shader maps it onto a sub-rect of the frame. Cost stays constant
// no matter how far you zoom, and detail comes from the source bitmap.
const vw = Math.min(1, availW / (fitScale * zoomFactor) / frame.w);
const vh = Math.min(1, availH / (fitScale * zoomFactor) / frame.h);
const cx =
vw >= content.w
? content.x + content.w / 2
: clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2);
const cy =
vh >= content.h
? content.y + content.h / 2
: clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2);
view = { x: cx - vw / 2, y: cy - vh / 2, w: vw, h: vh };
cssW = Math.round(availW);
cssH = Math.round(availH);
}
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cap = Math.min(1, 3200 / Math.max(1, Math.max(cssW * dpr, cssH * dpr)));
const pxW = Math.max(1, Math.round(cssW * dpr * cap));
const pxH = Math.max(1, Math.round(cssH * dpr * cap));
canvas.style.width = `${cssW}px`;
canvas.style.height = `${cssH}px`;
geoRef.current = {
fitScale,
fitPct,
frameW: frame.w,
frameH: frame.h,
zoomFactor,
availW,
availH,
content,
view,
};
const shown = Math.round(fitScale * zoomFactor * 100);
const fit = Math.round(fitPct);
setReadout((prev) => (prev.shown === shown && prev.fit === fit ? prev : { shown, fit }));
try {
renderer.setImage(bitmap);
renderer.render(activeEdits, {
width: pxW,
height: pxH,
cropPreview: cropMode,
// The histogram describes the whole photo, so it is only refreshed at fit.
histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001,
view: zoomFactor <= 1.0001 ? undefined : view,
// Holding the grain still keeps the noise from crawling while a crop
// handle moves; the new crop-relative scale applies on release.
freezeGrain: cropDrag,
// One source pixel per device pixel is the crossover: below it mipmaps
// resample cleanly, above it bicubic keeps magnified detail from squaring off.
upscale: dpr * cap * fitScale * zoomFactor > 1.1,
});
histRef.current = renderer.histogram;
setHistVersion((v) => v + 1);
} catch (err) {
setError(err instanceof Error ? err.message : 'Rendering failed');
}
}, [bitmap, edits, cropMode, showOriginal, stage, zoom, cropDrag]);
useEffect(() => {
if (!bitmap) return;
const raf = requestAnimationFrame(drawPreview);
return () => cancelAnimationFrame(raf);
}, [bitmap, drawPreview]);
/* ------------------------------------------------------------ zoom & pan */
const applyZoom = useCallback((rawPct: number | 'fit', point?: { x: number; y: number }) => {
const geo = geoRef.current;
if (!geo.fitScale) return;
const fitPct = geo.fitPct;
if (rawPct === 'fit' || rawPct <= fitPct * 1.015 || fitPct >= 99.5) {
setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 });
return;
}
const next = clampNum(rawPct, fitPct * 1.02, MAX_ZOOM);
const zNow = Math.max(1, geo.zoomFactor);
const zNext = Math.max(1, next / fitPct);
const centerX = geo.view.x + geo.view.w / 2;
const centerY = geo.view.y + geo.view.h / 2;
let cx = centerX;
let cy = centerY;
if (point) {
// Keep the frame point under the cursor fixed while the scale changes.
const rect = canvasRef.current?.getBoundingClientRect();
if (rect) {
const dx = point.x - (rect.left + rect.width / 2);
const dy = point.y - (rect.top + rect.height / 2);
const pointX = centerX + dx / (geo.fitScale * zNow) / geo.frameW;
const pointY = centerY + dy / (geo.fitScale * zNow) / geo.frameH;
cx = pointX - dx / (geo.fitScale * zNext) / geo.frameW;
cy = pointY - dy / (geo.fitScale * zNext) / geo.frameH;
}
}
const vw = geo.availW / (geo.fitScale * zNext) / geo.frameW;
const vh = geo.availH / (geo.fitScale * zNext) / geo.frameH;
const c = geo.content;
cx = vw >= c.w ? c.x + c.w / 2 : clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2);
cy = vh >= c.h ? c.y + c.h / 2 : clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2);
setZoom({ pct: next, cx, cy });
}, []);
// Filmstrip: the wheel browses photos sideways, and the current one is kept
// in view as you move through the shoot.
useEffect(() => {
const el = stripRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
e.preventDefault();
el.scrollLeft += e.deltaY;
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
useEffect(() => {
stripRef.current?.querySelector('.film.active')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}, [photo.id]);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (cropMode) return;
const geo = geoRef.current;
if (!geo.fitScale) return;
if (!e.ctrlKey && Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
e.preventDefault();
const base = geo.fitPct * Math.max(1, geo.zoomFactor);
applyZoom(base * Math.exp(-e.deltaY * 0.0022), { x: e.clientX, y: e.clientY });
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, [cropMode, applyZoom]);
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (cropMode || !zoomed || e.button !== 0) return;
const geo = geoRef.current;
panRef.current = {
x: e.clientX,
y: e.clientY,
cx: geo.view.x + geo.view.w / 2,
cy: geo.view.y + geo.view.h / 2,
};
e.currentTarget.setPointerCapture(e.pointerId);
setPanning(true);
};
const movePan = (e: React.PointerEvent<HTMLCanvasElement>) => {
const start = panRef.current;
if (!start) return;
const geo = geoRef.current;
const z = Math.max(1, geo.zoomFactor);
const dx = (e.clientX - start.x) / (geo.fitScale * z * geo.frameW);
const dy = (e.clientY - start.y) / (geo.fitScale * z * geo.frameH);
const c = geo.content;
const cx =
geo.view.w >= c.w
? c.x + c.w / 2
: clampNum(start.cx - dx, c.x + geo.view.w / 2, c.x + c.w - geo.view.w / 2);
const cy =
geo.view.h >= c.h
? c.y + c.h / 2
: clampNum(start.cy - dy, c.y + geo.view.h / 2, c.y + c.h - geo.view.h / 2);
setZoom((prev) => ({ pct: prev.pct, cx, cy }));
};
const endPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!panRef.current) return;
panRef.current = null;
setPanning(false);
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
};
const toggleZoom = (x?: number, y?: number) => {
if (cropMode) return;
if (zoomed) applyZoom('fit');
else applyZoom(100, x !== undefined && y !== undefined ? { x, y } : undefined);
};
const undo = useCallback(() => {
const hist = photo.history;
if (hist.length < 2) return;
const idx = hist.findIndex((h) => h.edits === photo.edits);
const target = idx > 0 ? hist[idx - 1] : hist[hist.length - 2];
if (target) onUpdate(photo.id, { edits: target.edits });
}, [photo.history, photo.edits, photo.id, onUpdate]);
useEffect(() => {
const down = (e: KeyboardEvent) => {
const target = e.target as HTMLElement | null;
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return;
if (e.key === '\\') {
setShowOriginal(true);
return;
}
if (e.key === 'ArrowRight') {
onNavigate(1);
e.preventDefault();
} else if (e.key === 'ArrowLeft') {
onNavigate(-1);
e.preventDefault();
} else if (e.key.toLowerCase() === 'c' && !e.metaKey && !e.ctrlKey) {
setCropMode((v) => !v);
} else if (e.key.toLowerCase() === 'z' && !e.metaKey && !e.ctrlKey) {
toggleZoom();
e.preventDefault();
} else if (e.key === 'Enter' && cropMode) {
setCropMode(false);
} else if (e.key === 'Escape') {
if (cropMode) setCropMode(false);
else onExit();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {
undo();
e.preventDefault();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c') {
onCopy();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'v') {
onPaste();
}
};
const up = (e: KeyboardEvent) => {
if (e.key === '\\') setShowOriginal(false);
};
window.addEventListener('keydown', down);
window.addEventListener('keyup', up);
return () => {
window.removeEventListener('keydown', down);
window.removeEventListener('keyup', up);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cropMode, onExit, onNavigate, onCopy, onPaste, undo, applyZoom, zoomed]);
const applyPreset = useCallback(
(preset: Preset) => {
const next: Edits =
preset.id === 'original'
? { ...defaultEdits(), crop: photo.edits.crop }
: { ...photo.edits, ...preset.edits, crop: photo.edits.crop };
onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`);
},
[onUpdate, photo.id, photo.edits],
);
const frame = bitmap
? rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter)
: { w: 1, h: 1 };
const lockedRatio = useMemo(() => {
const def = ASPECTS.find((a) => a.id === edits.crop.aspect);
return def?.ratio ?? null;
}, [edits.crop.aspect]);
const applyAspect = useCallback(
(id: string) => {
const def = ASPECTS.find((a) => a.id === id);
if (!def) return;
const f = bitmap
? rotatedBounds(bitmap.width, bitmap.height, photo.edits.crop.angle, photo.edits.crop.quarter)
: { w: 1, h: 1 };
let w = 1;
let h = 1;
if (def.ratio) {
const frameRatio = f.w / f.h;
if (def.ratio > frameRatio) {
w = 1;
h = frameRatio / def.ratio;
} else {
h = 1;
w = def.ratio / frameRatio;
}
}
setEdits(
{ crop: { ...photo.edits.crop, x: (1 - w) / 2, y: (1 - h) / 2, w, h, aspect: id } },
def.ratio ? `Crop ${def.label}` : 'Crop',
);
},
[bitmap, photo.edits.crop, setEdits],
);
const rotate = useCallback(
(dir: -1 | 1) => {
const c = photo.edits.crop;
const quarter = ((c.quarter + dir) % 4 + 4) % 4;
const rect =
dir === 1
? { x: 1 - (c.y + c.h), y: c.x, w: c.h, h: c.w }
: { x: c.y, y: 1 - (c.x + c.w), w: c.h, h: c.w };
setEdits(
{ crop: { ...c, quarter, ...rect } },
dir === 1 ? 'Rotate 90° right' : 'Rotate 90° left',
);
},
[photo.edits.crop, setEdits],
);
const resetAll = () => {
if (!window.confirm('Reset all develop settings for this photo?')) return;
onUpdate(photo.id, { edits: { ...defaultEdits(), crop: photo.edits.crop } }, 'Reset');
};
const canvasMenu: MenuEntry[] = [
{ label: 'Zoom to Fit', shortcut: 'Z', onSelect: () => applyZoom('fit') },
{ label: 'Zoom to 100%', onSelect: () => applyZoom(100) },
'separator',
{ label: 'Crop & Straighten', shortcut: 'C', onSelect: () => setCropMode((v) => !v) },
{ label: 'Before / After', shortcut: '\\', onSelect: () => setShowOriginal((v) => !v) },
'separator',
{ label: 'Copy settings', shortcut: '⌘C', onSelect: onCopy },
{ label: 'Paste settings', shortcut: '⌘V', onSelect: onPaste, disabled: !clipboard },
{ label: 'Reset settings', onSelect: resetAll },
'separator',
{ label: 'Export…', onSelect: onExport },
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
];
const filmMenu: MenuEntry[] = [
{ label: 'Copy settings', onSelect: onCopy },
{ label: 'Paste settings', onSelect: onPaste, disabled: !clipboard },
{ label: 'Reset settings', onSelect: resetAll },
'separator',
{ label: 'Export…', onSelect: onExport },
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
];
const index = photos.findIndex((p) => p.id === photo.id);
return (
<div className={`develop ${cropMode ? 'cropping' : ''}`}>
<div className="dev-toolbar">
<button className="btn ghost small" onClick={onExit}>
← Library
</button>
<div className="dev-title">
<strong title={photo.name}>{photo.name}</strong>
<span className="muted small">
{index >= 0 ? `${index + 1} / ${photos.length}` : ''} · {photo.width}×{photo.height}
</span>
</div>
<Stars value={photo.rating} onChange={(r) => onUpdate(photo.id, { rating: r })} size="md" />
<FlagButtons value={photo.flag} onChange={(f) => onUpdate(photo.id, { flag: f })} />
<ColorSwatches value={photo.color} onChange={(c) => onUpdate(photo.id, { color: c })} />
<div className="spacer" />
<button
className={`btn ghost small ${showOriginal ? 'on' : ''}`}
onClick={() => setShowOriginal((v) => !v)}
title="Toggle before / after (hold \)"
>
Before / After
</button>
<button className={`btn ghost small ${cropMode ? 'on' : ''}`} onClick={() => setCropMode((v) => !v)} title="Crop & straighten (C)">
Crop
</button>
<button className="btn ghost small" onClick={onCopy} title="Copy develop settings (⌘C)">
Copy
</button>
<button className="btn ghost small" onClick={onPaste} disabled={!clipboard} title="Paste develop settings (⌘V)">
Paste
</button>
<button className="btn ghost small" onClick={resetAll}>
Reset
</button>
<button className="btn ghost small danger" onClick={onDelete}>
Delete
</button>
<button className="btn primary small" onClick={onExport}>
Export
</button>
</div>
<div className="dev-body">
<aside className="dev-left">
<NavigatorPanel photo={photo} />
<PresetsPanel
presets={presets}
photo={photo}
onApply={applyPreset}
onSave={(name) => onSavePreset(name, photo.edits)}
/>
<HistoryPanel history={photo.history} onRestore={(next) => onUpdate(photo.id, { edits: next })} />
</aside>
<div
className={`canvas-stage ${zoomed ? 'zoomed' : ''} ${panning ? 'panning' : ''}`}
ref={stageRef}
onContextMenu={(e) => {
e.preventDefault();
setMenu({ x: e.clientX, y: e.clientY, kind: 'canvas' });
}}
>
{error ? (
<div className="banner error">{error}</div>
) : (
<div className="canvas-wrap">
<canvas
ref={canvasRef}
className={`preview ${zoomed ? 'zoomed' : ''}`}
onPointerDown={beginPan}
onPointerMove={movePan}
onPointerUp={endPan}
onPointerCancel={endPan}
onDoubleClick={(e) => toggleZoom(e.clientX, e.clientY)}
/>
{cropMode && bitmap && (
<CropOverlay
crop={photo.edits.crop}
frame={frame}
ratio={lockedRatio}
bitmap={bitmap}
edits={edits}
onChange={(rect) => setEdits({ crop: { ...photo.edits.crop, ...rect } }, 'Crop')}
onDragChange={setCropDrag}
/>
)}
</div>
)}
{loading && <div className="canvas-loading">Loading original…</div>}
{cropMode && <div className="crop-hint">Drag the edges to crop · Enter to apply · Esc to cancel</div>}
{!cropMode && !error && (
<div className="zoom-bar">
<button
className={`zoom-btn ${zoomed ? '' : 'on'}`}
onClick={() => applyZoom('fit')}
title="Fit to window (Z)"
>
Fit
</button>
<button
className={`zoom-btn ${zoomed && readout.shown === 100 ? 'on' : ''}`}
onClick={() => applyZoom(100)}
disabled={readout.fit >= 100}
title="Actual pixels"
>
100%
</button>
<span className="zoom-pct">{readout.shown}%</span>
</div>
)}
{zoomed && !cropMode && <div className="crop-hint">Drag to pan · scroll to zoom · double-click to fit</div>}
{showOriginal && <div className="before-badge">Before</div>}
</div>
<aside className="dev-right">
<div className="histo-wrap">
<Histogram data={histRef.current} version={histVersion} />
<div className="histo-legend">
<span>ISO {photo.meta.iso ?? '—'}</span>
<span>{photo.meta.aperture ? `f/${photo.meta.aperture}` : '—'}</span>
<span>{photo.meta.shutter ?? '—'}</span>
<span>{photo.meta.focal ? `${photo.meta.focal}mm` : '—'}</span>
</div>
</div>
<div className="panel-scroll">
{cropMode && (
<CropPanel
edits={edits}
set={setEdits}
frame={frame}
onAspect={applyAspect}
onRotate={rotate}
onFlipPreview={() =>
setEdits({ crop: { ...edits.crop, flipH: !edits.crop.flipH } }, 'Flip horizontal')
}
mirrored={edits.crop.flipH}
/>
)}
<BasicPanel edits={edits} photo={photo} set={setEdits} />
<CurvePanel edits={edits} photo={photo} set={setEdits} />
<HslPanel edits={edits} photo={photo} set={setEdits} />
<ColorGradingPanel edits={edits} photo={photo} set={setEdits} />
<EffectsPanel edits={edits} photo={photo} set={setEdits} grainFreeze={cropDrag} />
<DetailPanel edits={edits} photo={photo} set={setEdits} />
<MetadataPanel photo={photo} events={events} />
</div>
</aside>
</div>
<div className="filmstrip" ref={stripRef}>
{photos.map((p) => (
<button
key={p.id}
className={`film ${p.id === photo.id ? 'active' : ''}`}
onClick={() => onSelect(p.id)}
onContextMenu={(e) => {
e.preventDefault();
if (p.id !== photo.id) onSelect(p.id);
setMenu({ x: e.clientX, y: e.clientY, kind: 'film' });
}}
title={p.name}
>
<img
src={thumbSrc(p)}
alt={p.name}
loading="lazy"
draggable={false}
style={{ transform: thumbTransform(p, 3 / 2) }}
/>
{p.rating > 0 && <span className="film-rating">{'★'.repeat(p.rating)}</span>}
</button>
))}
</div>
{menu && (
<ContextMenu
x={menu.x}
y={menu.y}
onClose={() => setMenu(null)}
header={
menu.kind === 'film' ? (
<div className="ctx-rows">
<Stars value={photo.rating} onChange={(r) => onUpdate(photo.id, { rating: r })} size="md" />
<FlagButtons value={photo.flag} onChange={(f) => onUpdate(photo.id, { flag: f })} />
<ColorSwatches value={photo.color} onChange={(c) => onUpdate(photo.id, { color: c })} />
</div>
) : undefined
}
entries={menu.kind === 'canvas' ? canvasMenu : filmMenu}
/>
)}
</div>
);
}
+202
View File
@@ -0,0 +1,202 @@
import { useState } from 'react';
import {
draggedEventId,
draggedPhotoIds,
endDrag,
EVENT_DRAG,
PHOTO_DRAG,
startEventDrag,
startPhotoDrag,
} from '../lib/drag';
import type { EventRecord, PhotoRecord } from '../types';
interface Props {
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;
storageNote: string;
}
export default function EventSidebar({
events,
photos,
eventId,
onSelectEvent,
onCreate,
onRename,
onDelete,
onReorderEvents,
onDropPhotos,
storageNote,
}: 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 className="sidebar">
<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>
)}
</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>
);
}
+385
View File
@@ -0,0 +1,385 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { ExportOptions, ExportFormat, ResizeMode } from '../lib/export';
import { buildFileName, DEFAULT_EXPORT, exportPhotos } from '../lib/export';
import { getBitmap } from '../lib/images';
import { frameToSource, grainCellPx, grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
import type { PhotoRecord } from '../types';
interface Props {
photos: PhotoRecord[];
initial: ExportOptions;
onClose: () => void;
onDone: (message: string, options: ExportOptions) => void;
}
const FORMATS: { value: ExportFormat; label: string }[] = [
{ value: 'jpeg', label: 'JPEG' },
{ value: 'png', label: 'PNG' },
{ value: 'webp', label: 'WebP' },
];
/**
* 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, onClose, onDone }: Props) {
const [opts, setOpts] = useState<ExportOptions>({ ...DEFAULT_EXPORT, ...initial });
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState({ done: 0, total: 0 });
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 sample = photos[0];
const previewSize = useMemo(() => {
if (!sample) return null;
const w = sample.width || 1;
const h = sample.height || 1;
const crop = sample.edits.crop;
const swapped = Math.round(crop.quarter) % 2 === 1;
const frameW = swapped ? h : w;
const frameH = swapped ? w : h;
const baseW = Math.max(1, Math.round(frameW * crop.w));
const baseH = Math.max(1, Math.round(frameH * crop.h));
let k = 1;
if (opts.resize === 'longEdge' && opts.longEdge > 0 && Math.max(baseW, baseH) > opts.longEdge) {
k = opts.longEdge / Math.max(baseW, baseH);
} else if (opts.resize === 'percent') {
k = Math.min(2, Math.max(0.05, opts.percent / 100));
}
return { w: Math.round(baseW * k), h: Math.round(baseH * k) };
}, [sample, opts.resize, opts.longEdge, opts.percent]);
const sampleName = sample
? buildFileName(opts.nameTemplate, sample, 0, opts)
: `export.${opts.format === 'jpeg' ? 'jpg' : opts.format}`;
const run = async () => {
if (!photos.length || busy) return;
setBusy(true);
setError(null);
try {
const { count, failed } = await exportPhotos(photos, opts, (done, total) =>
setProgress({ done, total }),
);
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) => patch({ format: e.target.value as ExportFormat })}
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>
)}
</div>
{opts.format !== 'png' && (
<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>
{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">
{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 ? 'Exporting…' : `Export ${photos.length}`}
</button>
</footer>
</div>
</div>
);
}
+140
View File
@@ -0,0 +1,140 @@
import { COLOR_LABELS } from '../lib/edits';
import type { ColorLabel, Filters, Flag, SortKey } from '../types';
interface Props {
filters: Filters;
setFilters: (next: Filters) => void;
count: number;
total: number;
sort: SortKey;
setSort: (s: SortKey) => void;
asc: boolean;
setAsc: (v: boolean) => void;
}
const FLAGS: { value: Flag | 'any'; label: string }[] = [
{ value: 'any', label: 'Any' },
{ value: 'pick', label: 'Picked' },
{ value: 'none', label: 'Unflagged' },
{ value: 'reject', label: 'Rejected' },
];
export default function FilterBar({ filters, setFilters, count, total, sort, setSort, asc, setAsc }: Props) {
const patch = (p: Partial<Filters>) => setFilters({ ...filters, ...p });
const active = filters.minRating > 0 || filters.flag !== 'any' || filters.colors.length > 0 || !!filters.text || filters.editedOnly || filters.unrated;
const toggleColor = (color: ColorLabel) => {
const exists = filters.colors.includes(color);
patch({ colors: exists ? filters.colors.filter((c) => c !== color) : [...filters.colors, color] });
};
return (
<div className="filterbar">
<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`}
>
{n === 0 ? 'Any' : `${n}★+`}
</button>
))}
<button
className={`chip ${filters.unrated ? 'on' : ''}`}
onClick={() => patch({ unrated: !filters.unrated, minRating: 0 })}
title="Only photos with no rating"
>
Unrated
</button>
</div>
</div>
<div className="filter-group">
<span className="filter-label">Flag</span>
<div className="rating-filter">
{FLAGS.map((f) => (
<button
key={f.value}
className={`chip ${filters.flag === f.value ? 'on' : ''}`}
onClick={() => patch({ flag: f.value })}
>
{f.label}
</button>
))}
</div>
</div>
<div className="filter-group">
<span className="filter-label">Label</span>
<div className="color-filter">
{COLOR_LABELS.map((c) => (
<button
key={c.value}
className={`swatch ${filters.colors.includes(c.value) ? 'on' : ''}`}
style={{ background: c.hex }}
title={c.name}
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"
>
Edited
</button>
<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>
{active && (
<button
className="chip ghost"
onClick={() =>
setFilters({ minRating: 0, flag: 'any', colors: [], text: '', editedOnly: false, unrated: false })
}
>
Clear filters
</button>
)}
<div className="filter-count">
{count}
{count !== total ? ` / ${total}` : ''} shown
</div>
</div>
);
}
+63
View File
@@ -0,0 +1,63 @@
import { useEffect, useRef } from 'react';
import type { Histogram as HistogramData } from '../gl/renderer';
export default function Histogram({ data, version }: { data: HistogramData | null; version: number }) {
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 <canvas className="histogram" ref={ref} />;
}
+224
View File
@@ -0,0 +1,224 @@
import { useEffect, 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[];
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,
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 inputRef = useRef<HTMLInputElement>(null);
const rawCount = files.filter(isRawFile).length;
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;
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 (!files.length || busy) return;
setBusy(true);
setFailures([]);
try {
let targetId = eventId;
if (targetId === '__new') {
const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`);
targetId = created.id;
}
const result = await importFiles(files, targetId, [], setProgress, cloud ?? null);
if (result.photos.length) onImported(result.photos, targetId);
if (result.failed.length) {
setFailures(result.failed.map((f) => `${f.name} — ${f.reason}`));
setBusy(false);
setFiles([]);
setProgress(null);
if (result.photos.length) setTimeout(onClose, 1200);
} else {
onClose();
}
} catch (err) {
setFailures([err instanceof Error ? err.message : 'Import failed']);
setBusy(false);
}
};
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>
{files.length} file{files.length === 1 ? '' : 's'} ready ·{' '}
{(files.reduce((sum, f) => sum + f.size, 0) / (1024 * 1024)).toFixed(1)} MB
{rawCount > 0 ? ` · ${rawCount} raw` : ''}
</span>
<button className="link-btn" onClick={() => setFiles([])} disabled={busy}>
Clear
</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>
)}
{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">
<button className="btn ghost" onClick={onClose} disabled={busy}>
Cancel
</button>
<button className="btn primary" onClick={() => void run()} disabled={busy || !files.length}>
{busy ? 'Importing…' : `Import ${files.length || ''}`}
</button>
</footer>
</div>
</div>
);
}
+359
View File
@@ -0,0 +1,359 @@
import { useRef, useState } from 'react';
import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits';
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
import { thumbSrc } from '../lib/images';
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;
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;
}
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,
onImport,
onDropFiles,
onClearSelection,
onReorder,
onMarqueeSelect,
}: 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 selectedSet = new Set(selected);
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>
<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={onExport}>
Export
</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 }}
/>
)}
{photos.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) => {
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={thumbSrc(p)}
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>
)}
</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>
);
})}
</div>
</div>
);
}
+700
View File
@@ -0,0 +1,700 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, thumbTransform } from '../lib/edits';
import { computeAutoEdits } from '../lib/auto';
import { clamp } from '../lib/curves';
import type { CurveChannel, Edits, EventRecord, HistoryEntry, PhotoRecord, Preset } from '../types';
import CurveEditor from './CurveEditor';
import { getBitmap, thumbSrc } from '../lib/images';
import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
import { applyFilmVariant, FILM_VARIANTS, type FilmVariant } from '../lib/presets';
import { usePresetThumbs } from './PresetThumbs';
import Slider from './Slider';
export function Panel({
title,
children,
defaultOpen = true,
right,
}: {
title: string;
children: React.ReactNode;
defaultOpen?: boolean;
right?: React.ReactNode;
}) {
const [open, setOpen] = useState(defaultOpen);
return (
<section className={`panel ${open ? 'open' : ''}`}>
<div className="panel-head">
<button className="panel-toggle" onClick={() => setOpen((o) => !o)}>
<span className="chev">{open ? '▾' : '▸'}</span>
{title}
</button>
{right}
</div>
{open && <div className="panel-body">{children}</div>}
</section>
);
}
export interface PanelSetProps {
edits: Edits;
photo: PhotoRecord;
set: (patch: Partial<Edits>, label: string) => void;
}
const HUE_TRACK = 'linear-gradient(90deg,#ff4d4d,#ffd24d,#6dff6d,#4dfff0,#4d8bff,#c44dff,#ff4dd2,#ff4d4d)';
export function BasicPanel({ edits, photo, set }: PanelSetProps) {
const [autoBusy, setAutoBusy] = useState(false);
const auto = async () => {
setAutoBusy(true);
try {
const partial = await computeAutoEdits(photo.thumb);
set(partial, 'Auto tone');
} finally {
setAutoBusy(false);
}
};
return (
<Panel title="Light">
<div className="subhead">
<span>White balance</span>
<button className="link-btn" onClick={() => set({ temp: 0, tint: 0 }, 'As shot')}>
As shot
</button>
</div>
<Slider
label="Temp"
value={edits.temp}
onChange={(v) => set({ temp: v }, 'Temperature')}
track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)"
/>
<Slider
label="Tint"
value={edits.tint}
onChange={(v) => set({ tint: v }, 'Tint')}
track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)"
/>
<div className="subhead">
<span>Tone</span>
<button className="link-btn" onClick={() => void auto()} disabled={autoBusy}>
{autoBusy ? 'Analyzing…' : 'Auto'}
</button>
</div>
<Slider
label="Exposure"
min={-5}
max={5}
step={0.01}
value={edits.exposure}
onChange={(v) => set({ exposure: v }, 'Exposure')}
format={(v) => v.toFixed(2)}
/>
<Slider label="Contrast" value={edits.contrast} onChange={(v) => set({ contrast: v }, 'Contrast')} />
<Slider label="Highlights" value={edits.highlights} onChange={(v) => set({ highlights: v }, 'Highlights')} />
<Slider label="Shadows" value={edits.shadows} onChange={(v) => set({ shadows: v }, 'Shadows')} />
<Slider label="Whites" value={edits.whites} onChange={(v) => set({ whites: v }, 'Whites')} />
<Slider label="Blacks" value={edits.blacks} onChange={(v) => set({ blacks: v }, 'Blacks')} />
<div className="subhead">
<span>Presence</span>
</div>
<Slider label="Texture" value={edits.texture} onChange={(v) => set({ texture: v }, 'Texture')} />
<Slider label="Clarity" value={edits.clarity} onChange={(v) => set({ clarity: v }, 'Clarity')} />
<Slider label="Dehaze" value={edits.dehaze} onChange={(v) => set({ dehaze: v }, 'Dehaze')} />
<Slider label="Vibrance" value={edits.vibrance} onChange={(v) => set({ vibrance: v }, 'Vibrance')} />
<Slider label="Saturation" value={edits.saturation} onChange={(v) => set({ saturation: v }, 'Saturation')} />
<label className="toggle">
<input type="checkbox" checked={edits.bw} onChange={(e) => set({ bw: e.target.checked }, 'Black & white')} />
<span>Black &amp; white mix</span>
</label>
{edits.bw && (
<>
<div className="subhead">
<span>B&amp;W filter</span>
</div>
<div className="bw-filters">
{BW_FILTERS.map((f) => (
<button
key={f.id}
className={`bw-filter ${edits.bwFilter === f.id ? 'on' : ''}`}
title={`${f.label} filter`}
onClick={() => set({ bwFilter: f.id }, `B&W filter · ${f.label}`)}
>
{f.label}
</button>
))}
</div>
{edits.bwFilter !== 'none' && (
<Slider
label="Filter strength"
value={edits.bwFilterAmount}
onChange={(v) => set({ bwFilterAmount: v }, 'B&W filter strength')}
/>
)}
<div className="muted small">
A filter darkens the colors it absorbs: red drops blue skies, green lifts foliage. The color mixer
below tunes individual hues on top.
</div>
</>
)}
</Panel>
);
}
const CURVE_COLORS: Record<CurveChannel, string> = {
rgb: '#e9e9ec',
red: '#e06a6a',
green: '#6ecf7d',
blue: '#6f9de8',
};
export function CurvePanel({ edits, set }: PanelSetProps) {
const [channel, setChannel] = useState<CurveChannel>('rgb');
const points = edits.curve[channel];
const update = (next: typeof points) => set({ curve: { ...edits.curve, [channel]: next } }, `Curve ${channel.toUpperCase()}`);
return (
<Panel
title="Tone curve"
defaultOpen={false}
right={
<button className="link-btn" onClick={() => update(identityCurve())}>
Reset
</button>
}
>
<div className="tabs">
{(['rgb', 'red', 'green', 'blue'] as CurveChannel[]).map((c) => (
<button key={c} className={`tab ${channel === c ? 'on' : ''}`} onClick={() => setChannel(c)}>
{c === 'rgb' ? 'RGB' : c === 'red' ? 'R' : c === 'green' ? 'G' : 'B'}
</button>
))}
</div>
<CurveEditor points={points} onChange={update} color={CURVE_COLORS[channel]} />
</Panel>
);
}
export function HslPanel({ edits, set }: PanelSetProps) {
const [band, setBand] = useState(0);
const active = HUE_BANDS[band];
const setBandValue = (kind: 'hue' | 'sat' | 'lum', value: number) => {
const arr = [...edits.hsl[kind]];
arr[band] = value;
const label = kind === 'hue' ? 'Hue' : kind === 'sat' ? 'Saturation' : 'Luminance';
set({ hsl: { ...edits.hsl, [kind]: arr } }, `${label} · ${active.name}`);
};
return (
<Panel
title="Color mixer"
defaultOpen={false}
right={
<button
className="link-btn"
onClick={() =>
set(
{ hsl: { hue: HUE_BANDS.map(() => 0), sat: HUE_BANDS.map(() => 0), lum: HUE_BANDS.map(() => 0) } },
'Reset color mixer',
)
}
>
Reset
</button>
}
>
<div className="band-row">
{HUE_BANDS.map((b, i) => (
<button
key={b.key}
className={`band-swatch ${band === i ? 'on' : ''}`}
style={{ background: b.swatch }}
title={b.name}
onClick={() => setBand(i)}
/>
))}
</div>
<div className="band-title">{active.name}</div>
<Slider label="Hue" value={edits.hsl.hue[band]} onChange={(v) => setBandValue('hue', v)} track={HUE_TRACK} />
<Slider label="Saturation" value={edits.hsl.sat[band]} onChange={(v) => setBandValue('sat', v)} />
<Slider label="Luminance" value={edits.hsl.lum[band]} onChange={(v) => setBandValue('lum', v)} />
<div className="muted small">Shift, saturate or brighten one color range without touching the rest.</div>
</Panel>
);
}
export function ColorGradingPanel({ edits, set }: PanelSetProps) {
return (
<Panel title="Color grading" defaultOpen={false}>
<div className="subhead">
<span>Shadows</span>
<span className="swatch-mini" style={{ background: `hsl(${edits.grading.shadows.h} 80% 55%)` }} />
</div>
<Slider
label="Hue"
min={0}
max={360}
value={edits.grading.shadows.h}
onChange={(v) => set({ grading: { ...edits.grading, shadows: { ...edits.grading.shadows, h: v } } }, 'Grading shadows hue')}
track={HUE_TRACK}
/>
<Slider
label="Amount"
min={0}
max={100}
value={edits.grading.shadows.s}
onChange={(v) => set({ grading: { ...edits.grading, shadows: { ...edits.grading.shadows, s: v } } }, 'Grading shadows')}
/>
<div className="subhead">
<span>Highlights</span>
<span className="swatch-mini" style={{ background: `hsl(${edits.grading.highlights.h} 80% 55%)` }} />
</div>
<Slider
label="Hue"
min={0}
max={360}
value={edits.grading.highlights.h}
onChange={(v) =>
set({ grading: { ...edits.grading, highlights: { ...edits.grading.highlights, h: v } } }, 'Grading highlights hue')
}
track={HUE_TRACK}
/>
<Slider
label="Amount"
min={0}
max={100}
value={edits.grading.highlights.s}
onChange={(v) => set({ grading: { ...edits.grading, highlights: { ...edits.grading.highlights, s: v } } }, 'Grading highlights')}
/>
<Slider
label="Balance"
value={edits.grading.balance}
onChange={(v) => set({ grading: { ...edits.grading, balance: v } }, 'Grading balance')}
/>
</Panel>
);
}
/**
* 1:1 loupe of the grain. A small window of the real crop is rendered at actual
* pixels, which is the only way to judge a resolution independent grain size
* without exporting: this is what the file looks like at 100%.
*/
function GrainPatch({
photo,
edits,
freezeGrain,
}: {
photo: PhotoRecord;
edits: Edits;
freezeGrain?: boolean;
}) {
const ref = useRef<HTMLCanvasElement>(null);
const renderer = useRef<Renderer | null>(null);
const bitmap = useRef<ImageBitmap | null>(null);
const [ready, setReady] = useState(false);
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;
},
[],
);
useEffect(() => {
const canvas = ref.current;
const bmp = bitmap.current;
if (!canvas || !bmp) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const frame = rotatedBounds(bmp.width, bmp.height, edits.crop.angle, edits.crop.quarter);
// The patch takes the shape of the framed area, so it reads as a window onto
// the crop rather than a generic swatch.
const cropPxW = Math.max(1, frame.w * edits.crop.w);
const cropPxH = Math.max(1, frame.h * edits.crop.h);
const cssW = 148;
const cssH = Math.round(Math.min(148, Math.max(64, 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 (!renderer.current) renderer.current = new Renderer(canvas);
const r = renderer.current;
r.setImage(bmp);
// One source pixel per device pixel, centred on whatever the crop frames:
// drag the crop rectangle and the patch samples that part of the photo.
const view = grainSampleWindow(frame, edits.crop, W, H);
r.render(edits, { width: W, height: H, view, freezeGrain });
} catch {
// Keep the last good frame rather than blanking the patch.
}
}, [photo.id, ready, edits, freezeGrain]);
return (
<figure className="grain-patch">
<canvas ref={ref} />
<span>Grain at 100% · inside the crop</span>
</figure>
);
}
export function EffectsPanel({ edits, photo, set, grainFreeze }: PanelSetProps & { grainFreeze?: boolean }) {
return (
<Panel title="Effects" defaultOpen={false}>
<div className="subhead">
<span>Vignette</span>
</div>
<Slider
label="Amount"
value={edits.vignette.amount}
onChange={(v) => set({ vignette: { ...edits.vignette, amount: v } }, 'Vignette amount')}
/>
<Slider
label="Midpoint"
min={0}
max={100}
value={edits.vignette.midpoint}
onChange={(v) => set({ vignette: { ...edits.vignette, midpoint: v } }, 'Vignette midpoint')}
/>
<Slider
label="Feather"
min={0}
max={100}
value={edits.vignette.feather}
onChange={(v) => set({ vignette: { ...edits.vignette, feather: v } }, 'Vignette feather')}
/>
<div className="subhead">
<span>Grain</span>
</div>
<Slider
label="Amount"
min={0}
max={100}
value={edits.grain.amount}
onChange={(v) => set({ grain: { ...edits.grain, amount: v } }, 'Grain amount')}
/>
<Slider
label="Size"
min={10}
max={100}
value={edits.grain.size}
onChange={(v) => set({ grain: { ...edits.grain, size: v } }, 'Grain size')}
/>
<Slider
label="Roughness"
min={0}
max={100}
value={edits.grain.roughness}
onChange={(v) => set({ grain: { ...edits.grain, roughness: v } }, 'Grain roughness')}
/>
<GrainPatch photo={photo} edits={edits} freezeGrain={grainFreeze} />
</Panel>
);
}
export function DetailPanel({ edits, set }: PanelSetProps) {
return (
<Panel title="Detail" defaultOpen={false}>
<div className="subhead">
<span>Sharpening</span>
</div>
<Slider
label="Amount"
min={0}
max={150}
value={edits.sharpen.amount}
onChange={(v) => set({ sharpen: { ...edits.sharpen, amount: v } }, 'Sharpen amount')}
/>
<Slider
label="Radius"
min={0.5}
max={3}
step={0.1}
value={edits.sharpen.radius}
onChange={(v) => set({ sharpen: { ...edits.sharpen, radius: v } }, 'Sharpen radius')}
format={(v) => v.toFixed(1)}
def={1}
/>
<Slider
label="Detail"
min={0}
max={100}
value={edits.sharpen.detail}
def={25}
onChange={(v) => set({ sharpen: { ...edits.sharpen, detail: v } }, 'Sharpen detail')}
/>
<div className="subhead">
<span>Noise reduction</span>
</div>
<Slider
label="Luminance"
min={0}
max={100}
value={edits.noise.luminance}
onChange={(v) => set({ noise: { ...edits.noise, luminance: v } }, 'Noise reduction')}
/>
<Slider
label="Detail"
min={0}
max={100}
value={edits.noise.detail}
def={50}
onChange={(v) => set({ noise: { ...edits.noise, detail: v } }, 'Noise detail')}
/>
</Panel>
);
}
const BRAND_PREFIX = /^(Kodak|Fujifilm|Ilford|Agfa|CineStill|Lomography) /;
export function PresetsPanel({
presets,
photo,
onApply,
onSave,
}: {
presets: Preset[];
photo: PhotoRecord;
onApply: (preset: Preset) => void;
onSave: (name: string) => void;
}) {
const [variant, setVariant] = useState<FilmVariant>('base');
// Variants are derived on the fly, so every stock gets push/pull and split
// grade versions without tripling the catalogue.
const shown = useMemo(() => presets.map((p) => applyFilmVariant(p, variant)), [presets, variant]);
const groups = new Map<string, Preset[]>();
for (const preset of shown) {
const arr = groups.get(preset.group) ?? [];
arr.push(preset);
groups.set(preset.group, arr);
}
const thumbs = usePresetThumbs(photo, shown);
return (
<div className="panel-stack">
<div className="dev-panel-head">
<span>Presets</span>
<button
className="icon-btn"
title="Save current settings as a preset"
onClick={() => {
const name = window.prompt('Preset name');
if (name && name.trim()) onSave(name.trim());
}}
>
+
</button>
</div>
<div className="variant-row">
{FILM_VARIANTS.map((v) => (
<button
key={v.id}
className={`variant-btn ${variant === v.id ? 'on' : ''}`}
title={v.hint}
onClick={() => setVariant(v.id)}
>
{v.label}
</button>
))}
</div>
{[...groups.entries()].map(([group, items]) => (
<div key={group} className="preset-group">
<div className="preset-group-name">{group}</div>
<div className="preset-grid">
{items.map((preset) => {
const src = thumbs[preset.id];
return (
<button
key={preset.id}
className="preset-tile"
onClick={() => onApply(preset)}
title={`${preset.name}${src ? '' : ' — rendering preview…'}`}
>
{src ? (
<img src={src} alt={preset.name} loading="lazy" draggable={false} />
) : (
<span className="preset-tile-blank" />
)}
<span className="preset-tile-name">{preset.name.replace(BRAND_PREFIX, '')}</span>
</button>
);
})}
</div>
</div>
))}
</div>
);
}
export function HistoryPanel({ history, onRestore }: { history: HistoryEntry[]; onRestore: (edits: Edits) => void }) {
return (
<div className="panel-stack history">
<div className="dev-panel-head">
<span>History</span>
<span className="muted small">{history.length}</span>
</div>
<div className="history-list">
{[...history].reverse().map((entry, i) => (
<button key={`${entry.ts}-${i}`} className="history-item" onClick={() => onRestore(entry.edits)}>
<span className="history-label">{entry.label}</span>
<span className="muted small">{new Date(entry.ts).toLocaleTimeString()}</span>
</button>
))}
</div>
</div>
);
}
export function CropPanel({
edits,
set,
onAspect,
onRotate,
onFlipPreview,
mirrored,
}: {
edits: Edits;
set: PanelSetProps['set'];
frame: { w: number; h: number };
onAspect: (id: string) => void;
onRotate: (dir: -1 | 1) => void;
onFlipPreview?: () => void;
mirrored?: boolean;
}) {
const crop = edits.crop;
return (
<Panel title="Crop & straighten">
<div className="btn-row rotate-row">
<button className="btn ghost small" onClick={() => onRotate(-1)} title="Rotate 90° left">
⟲ 90°
</button>
<button className="btn ghost small" onClick={() => onRotate(1)} title="Rotate 90° right">
⟳ 90°
</button>
{onFlipPreview && (
<button
className={`btn ghost small ${mirrored ? 'on' : ''}`}
onClick={onFlipPreview}
title="Mirror the crop preview without changing the export"
>
{mirrored ? 'Mirror on' : 'Mirror view'}
</button>
)}
</div>
<div className="aspect-grid">
{ASPECTS.map((a) => (
<button key={a.id} className={`chip small ${crop.aspect === a.id ? 'on' : ''}`} onClick={() => onAspect(a.id)}>
{a.label}
</button>
))}
</div>
<Slider
label="Angle"
min={-45}
max={45}
step={0.1}
value={crop.angle}
onChange={(v) => set({ crop: { ...crop, angle: v } }, 'Straighten')}
format={(v) => `${v.toFixed(1)}°`}
/>
<div className="btn-row">
<button className="btn ghost small" onClick={() => set({ crop: { ...crop, flipH: !crop.flipH } }, 'Flip horizontal')}>
Flip H
</button>
<button className="btn ghost small" onClick={() => set({ crop: { ...crop, flipV: !crop.flipV } }, 'Flip vertical')}>
Flip V
</button>
<button
className="btn ghost small"
onClick={() =>
set(
{ crop: { ...crop, x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original' } },
'Reset crop',
)
}
>
Reset crop
</button>
</div>
</Panel>
);
}
export function NavigatorPanel({ photo }: { photo: PhotoRecord }) {
return (
<div className="panel-stack navigator">
<div className="dev-panel-head">
<span>Navigator</span>
<span className="muted small">Fit</span>
</div>
<div className="navigator-thumb">
<img
src={thumbSrc(photo)}
alt={photo.name}
style={{ transform: thumbTransform(photo) }}
/>
</div>
<div className="navigator-name" title={photo.name}>
{photo.name}
</div>
<div className="muted small navigator-meta">
{photo.raw ? (photo.decode === 'embedded' ? 'Raw · camera preview' : 'Raw · demosaiced') : 'JPEG/PNG'}{' '}
· {photo.width}×{photo.height}
</div>
</div>
);
}
export function MetadataPanel({ photo, events }: { photo: PhotoRecord; events: EventRecord[] }) {
const event = events.find((e) => e.id === photo.eventId);
const rows: [string, string][] = [
['File', photo.name],
['Dimensions', `${photo.width} × ${photo.height}`],
['Size', `${(photo.size / (1024 * 1024)).toFixed(2)} MB`],
['Camera', photo.meta.camera ?? '—'],
['Lens', photo.meta.lens ?? '—'],
['ISO', photo.meta.iso ? String(photo.meta.iso) : '—'],
['Aperture', photo.meta.aperture ? `f/${photo.meta.aperture}` : '—'],
['Shutter', photo.meta.shutter ?? '—'],
['Focal', photo.meta.focal ? `${photo.meta.focal} mm` : '—'],
['Captured', photo.takenAt ? new Date(photo.takenAt).toLocaleString() : '—'],
['Imported', new Date(photo.addedAt).toLocaleDateString()],
['Event', event?.name ?? 'Unsorted'],
];
return (
<Panel title="Info" defaultOpen={false}>
<dl className="meta">
{rows.map(([key, value]) => (
<div key={key} className="meta-row">
<dt>{key}</dt>
<dd title={value}>{value}</dd>
</div>
))}
</dl>
</Panel>
);
}
+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;
}
+85
View File
@@ -0,0 +1,85 @@
import { useEffect } from 'react';
const GROUPS: { title: string; rows: [string, string][] }[] = [
{
title: 'Everywhere',
rows: [
['?', 'Show or hide this list'],
['⌘ / 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'],
['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'],
['Enter', 'Apply the crop'],
['\\ (hold)', 'Before / after'],
['← →', 'Previous · next photo'],
['Scroll · drag', 'Zoom · pan'],
['⌘ / Ctrl + Z', 'Undo'],
['⌘ / 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>
))}
</div>
</div>
</div>
);
}
+84
View File
@@ -0,0 +1,84 @@
import { useEffect, useState } from 'react';
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;
}
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,
}: 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))}
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>
);
}
+81
View File
@@ -0,0 +1,81 @@
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;
}
export default function TopBar({
view,
eventName,
photoCount,
selectedCount,
cloudLabel,
cloudOn,
onViewChange,
onImport,
onExport,
onCloud,
onHelp,
}: Props) {
return (
<header className="topbar">
<div className="brand">
<span className="dot" />
Lumenroom
</div>
<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>
<button className="btn ghost" onClick={onExport}>
Export
</button>
<button className="icon-btn help-btn" onClick={onHelp} title="Keyboard shortcuts (?)">
?
</button>
<a
className="guide-btn"
href="/lumenroom-user-guide.pdf"
target="_blank"
rel="noreferrer"
title="User guide (PDF)"
>
Guide
</a>
<button className="btn primary" onClick={onImport}>
Import photos
</button>
</div>
</header>
);
}
+970
View File
@@ -0,0 +1,970 @@
import type { Edits } from '../types';
import { buildSampler, clamp01 } from '../lib/curves';
import { bwFilterRgb } from '../lib/edits';
const VERT = `#version 300 es
layout(location = 0) in vec2 a_pos;
out vec2 v_uv;
void main(){
v_uv = a_pos * 0.5 + 0.5;
gl_Position = vec4(a_pos, 0.0, 1.0);
}`;
const GRADE_FRAG = `#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 outColor;
uniform sampler2D u_src;
uniform sampler2D u_curve;
uniform vec2 u_srcSize;
uniform vec2 u_frameSize;
uniform vec4 u_crop;
uniform vec4 u_valid;
uniform float u_angle;
uniform int u_quarter;
uniform vec2 u_flip;
uniform float u_upscale;
uniform float u_temp;
uniform float u_tint;
uniform float u_exposure;
uniform float u_contrast;
uniform float u_highlights;
uniform float u_shadows;
uniform float u_whites;
uniform float u_blacks;
uniform float u_vibrance;
uniform float u_saturation;
uniform float u_bw;
uniform vec3 u_bwFilter;
uniform float u_bwFilterAmt;
uniform float u_hue[8];
uniform float u_sat[8];
uniform float u_lum[8];
uniform float u_gSh;
uniform float u_gSs;
uniform float u_gHi;
uniform float u_gHs;
uniform float u_gBal;
const float HUE_CENTERS[8] = float[8](0.0, 32.0, 62.0, 120.0, 180.0, 230.0, 280.0, 320.0);
float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
vec3 toLinear(vec3 c){
c = max(c, vec3(0.0));
return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
}
vec3 toSRGB(vec3 c){
c = max(c, vec3(0.0));
return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
}
vec3 rgb2hsv(vec3 c){
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10;
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
vec3 hsv2rgb(vec3 c){
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
// Catmull-Rom weights for one axis; t is the fraction inside a texel.
vec4 cubicWeights(float t){
float t2 = t * t;
float t3 = t2 * t;
return vec4(
-0.5 * t3 + t2 - 0.5 * t,
1.5 * t3 - 2.5 * t2 + 1.0,
-1.5 * t3 + 2.0 * t2 + 0.5 * t,
0.5 * t3 - 0.5 * t2
);
}
// Bicubic magnification. Bilinear leaves texel-sized squares with hard edges
// once a photo is zoomed past 1:1, which reads as blocky rather than soft.
vec3 sampleBicubic(sampler2D tex, vec2 uv, vec2 size){
vec2 coord = uv * size - 0.5;
vec2 base = floor(coord);
vec2 f = coord - base;
vec4 wx = cubicWeights(f.x);
vec4 wy = cubicWeights(f.y);
float ax[4] = float[4](wx.x, wx.y, wx.z, wx.w);
float ay[4] = float[4](wy.x, wy.y, wy.z, wy.w);
vec3 sum = vec3(0.0);
for (int j = 0; j < 4; j++){
for (int i = 0; i < 4; i++){
vec2 p = (base + vec2(float(i) - 1.0, float(j) - 1.0) + 0.5) / size;
sum += texture(tex, clamp(p, vec2(0.0), vec2(1.0))).rgb * ax[i] * ay[j];
}
}
return sum;
}
void main(){
vec2 frame = mix(u_crop.xy, u_crop.xy + u_crop.zw, vec2(v_uv.x, 1.0 - v_uv.y));
// Only the cropped area carries picture data; the rest is letterbox when the
// view is zoomed out or the window aspect differs from the photo.
if (frame.x < u_valid.x || frame.y < u_valid.y ||
frame.x > u_valid.x + u_valid.z || frame.y > u_valid.y + u_valid.w) {
outColor = vec4(0.035, 0.035, 0.04, 1.0);
return;
}
vec2 p = (frame - 0.5) * u_frameSize;
float a = -(u_angle + float(u_quarter) * 1.57079632679);
float ca = cos(a);
float sa = sin(a);
vec2 rp = vec2(p.x * ca - p.y * sa, p.x * sa + p.y * ca);
vec2 s = rp / u_srcSize + 0.5;
s = (s - 0.5) * u_flip + 0.5;
if (s.x < 0.0 || s.x > 1.0 || s.y < 0.0 || s.y > 1.0) {
outColor = vec4(0.035, 0.035, 0.04, 1.0);
return;
}
// s is already in the texture's own top-down row order, so it is sampled as
// it stands: negating y here would mirror the photo top to bottom.
vec2 uv = s;
vec3 src = u_upscale > 0.5
? sampleBicubic(u_src, uv, u_srcSize)
: texture(u_src, uv).rgb;
vec3 col = toLinear(clamp(src, 0.0, 1.0));
// White balance (relative to as-shot)
float t = u_temp / 100.0;
float ti = u_tint / 100.0;
vec3 wb = vec3(1.0 + 0.30 * t + 0.06 * ti, 1.0 - 0.16 * ti, 1.0 - 0.26 * t + 0.06 * ti);
col *= wb / max(0.05, luma(wb));
// Exposure
col *= exp2(u_exposure);
// Tonal range
float lm = clamp(luma(col), 0.0, 1.0);
col += (u_shadows / 100.0) * 0.45 * pow(1.0 - lm, 3.0);
col += (u_highlights / 100.0) * 0.50 * pow(lm, 2.0);
col += (u_whites / 100.0) * 0.34 * smoothstep(0.55, 1.0, lm);
col += (u_blacks / 100.0) * 0.13 * smoothstep(0.30, 0.0, lm);
vec3 srgb = clamp(toSRGB(col), 0.0, 1.0);
// Contrast
srgb = clamp((srgb - 0.5) * (1.0 + (u_contrast / 100.0) * 1.1) + 0.5, 0.0, 1.0);
// Tone curve (composite baked with per-channel curves)
srgb = vec3(
texture(u_curve, vec2(clamp(srgb.r, 0.0, 1.0), 0.5)).r,
texture(u_curve, vec2(clamp(srgb.g, 0.0, 1.0), 0.5)).g,
texture(u_curve, vec2(clamp(srgb.b, 0.0, 1.0), 0.5)).b
);
// HSL bands
vec3 hsv = rgb2hsv(srgb);
float hdeg = hsv.x * 360.0;
float hueWeight = smoothstep(0.02, 0.18, hsv.y);
float hShift = 0.0;
float sShift = 0.0;
float lShift = 0.0;
float wsum = 0.0;
for (int i = 0; i < 8; i++) {
float d = abs(hdeg - HUE_CENTERS[i]);
d = min(d, 360.0 - d);
float w = smoothstep(52.0, 0.0, d);
hShift += w * u_hue[i];
sShift += w * u_sat[i];
lShift += w * u_lum[i];
wsum += w;
}
float norm = max(wsum, 0.0001);
hShift = (hShift / norm) * hueWeight;
sShift = sShift / norm;
lShift = lShift / norm;
hsv.x = fract(hsv.x + (hShift / 100.0) * 0.08 + 1.0);
float satMul = sShift >= 0.0 ? 1.0 + (sShift / 100.0) * 0.8 : 1.0 + sShift / 100.0;
hsv.y = clamp(hsv.y * satMul, 0.0, 1.0);
hsv.z = clamp(hsv.z * (1.0 + (lShift / 100.0) * 0.5), 0.0, 1.0);
srgb = hsv2rgb(hsv);
if (u_bw > 0.5) {
// A colored filter over the lens changes which hues turn dark in the print:
// red drops blue skies, green lifts foliage, blue opens up shadows. The
// strength blends the transmission back towards a neutral filter.
vec3 bwTint = mix(vec3(1.0), u_bwFilter, clamp(u_bwFilterAmt, 0.0, 1.0));
float wl = max(0.05, luma(bwTint));
srgb = vec3(luma(srgb * bwTint) / wl);
}
// Vibrance and saturation
vec3 satRgb = clamp(srgb, 0.0, 1.0);
float mx = max(max(satRgb.r, satRgb.g), satRgb.b);
float mn = min(min(satRgb.r, satRgb.g), satRgb.b);
float curSat = mx - mn;
float gray = luma(satRgb);
srgb = mix(vec3(gray), satRgb, clamp(1.0 + (u_vibrance / 100.0) * (1.0 - curSat) * 0.9, 0.0, 3.0));
srgb = mix(vec3(luma(srgb)), srgb, clamp(1.0 + u_saturation / 100.0, 0.0, 3.0));
// Color grading
float gl = clamp(luma(srgb), 0.0, 1.0);
float bal = u_gBal / 100.0;
float sMask = pow(1.0 - gl, 2.0 + bal);
float hMask = pow(gl, 2.0 - bal);
vec3 shCol = hsv2rgb(vec3(u_gSh, 1.0, 1.0));
shCol -= vec3(luma(shCol));
vec3 hiCol = hsv2rgb(vec3(u_gHi, 1.0, 1.0));
hiCol -= vec3(luma(hiCol));
srgb += shCol * (u_gSs / 100.0) * 0.45 * sMask;
srgb += hiCol * (u_gHs / 100.0) * 0.45 * hMask;
outColor = vec4(clamp(srgb, 0.0, 1.0), 1.0);
}`;
const BLUR_FRAG = `#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 outColor;
uniform sampler2D u_tex;
uniform vec2 u_dir;
void main(){
vec3 s = texture(u_tex, v_uv).rgb * 0.2270270270;
s += texture(u_tex, v_uv + u_dir * 1.3846153846).rgb * 0.3162162162;
s += texture(u_tex, v_uv - u_dir * 1.3846153846).rgb * 0.3162162162;
s += texture(u_tex, v_uv + u_dir * 3.2307692308).rgb * 0.0702702703;
s += texture(u_tex, v_uv - u_dir * 3.2307692308).rgb * 0.0702702703;
outColor = vec4(s, 1.0);
}`;
const FINISH_FRAG = `#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 outColor;
uniform sampler2D u_graded;
uniform sampler2D u_blurSmall;
uniform sampler2D u_blurBig;
uniform float u_texture;
uniform float u_clarity;
uniform float u_dehaze;
uniform float u_sharpen;
uniform float u_nr;
uniform float u_vigAmt;
uniform float u_vigMid;
uniform float u_vigFeather;
uniform float u_grainAmt;
uniform float u_grainSize;
uniform float u_grainRough;
uniform vec4 u_crop;
uniform vec4 u_grainFrame;
uniform vec2 u_grainSpace;
uniform vec2 u_outSize;
uniform vec2 u_frameSize;
uniform vec2 u_grainFlip;
uniform float u_grainRot;
uniform float u_grainUnits;
uniform float u_aspect;
float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
// Integer hash (Dave Hoskins). A sin-based hash correlates at whole-pixel
// lattice points, which is exactly what drew diagonal streaks through grain.
float hash(vec2 p){
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
// Smooth value noise: interpolates between lattice samples instead of hashing
// whole blocks, so neighbouring pixels never sit at identical values.
float valueNoise(vec2 p){
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(
mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x),
u.y
);
}
void main(){
vec3 c = texture(u_graded, v_uv).rgb;
vec3 bs = texture(u_blurSmall, v_uv).rgb;
vec3 bb = texture(u_blurBig, v_uv).rgb;
// Noise reduction blends towards a smoothed version first.
float nr = clamp(u_nr / 100.0, 0.0, 1.0);
vec3 base = mix(c, mix(bs, bb, 0.5), nr * 0.6);
// Local contrast / detail work on gamma encoded values.
vec3 detailSmall = c - bs;
vec3 detailBig = base - bb;
vec3 col = base;
col += detailSmall * ((u_texture / 100.0) * 0.9 + (u_sharpen / 100.0) * 1.35);
col += detailBig * (u_clarity / 100.0) * 1.25;
// Dehaze
float d = u_dehaze / 100.0;
if (d > 0.0) {
float veil = luma(bb);
col = (col - d * 0.32 * veil * vec3(0.95, 0.98, 1.02)) / max(0.05, 1.0 - d * 0.28);
} else if (d < 0.0) {
col = mix(col, bb * 0.85 + vec3(0.09), -d * 0.55);
}
// Vignette
float amt = u_vigAmt / 100.0;
if (abs(amt) > 0.001) {
vec2 q = (v_uv - 0.5) * vec2(u_aspect, 1.0);
float r = length(q) / max(0.05, length(vec2(u_aspect, 1.0) * 0.5));
float mid = mix(0.18, 1.05, u_vigMid / 100.0);
float feather = mix(0.05, 1.0, u_vigFeather / 100.0);
float v = smoothstep(mid, mid + feather * 0.6, r);
float strength = abs(amt) * v;
if (amt < 0.0) col *= 1.0 - strength * 0.92;
else col = mix(col, vec3(1.0), strength * 0.6);
}
// Grain: film-like noise laid down in image space. Measured in output pixels
// a 6000 px export came out four times finer than the 1500 px preview, so the
// pattern is generated from the frame instead and every octave is band limited:
// nothing here depends on how many pixels the target happens to have.
float ga = u_grainAmt / 100.0;
if (ga > 0.001) {
float cell = mix(1.0, 3.0, clamp((u_grainSize - 10.0) / 90.0, 0.0, 1.0));
vec2 frameUv = mix(u_crop.xy, u_crop.xy + u_crop.zw, vec2(v_uv.x, 1.0 - v_uv.y));
// Grain lives on the photo, not on the output frame: the coordinates go
// through the same rotation/quarter/flip the frame uses, so straightening
// and rotating carry the texture along with the pixels instead of shifting
// it underneath them.
vec2 p = (frameUv - 0.5) * u_frameSize;
float ca = cos(u_grainRot);
float sa = sin(u_grainRot);
vec2 rp = vec2(p.x * ca - p.y * sa, p.x * sa + p.y * ca) * u_grainFlip;
vec2 px = rp * u_grainUnits;
float pxPerUnit = length(u_outSize) / max(1.0, length(u_grainSpace * (u_crop.zw / u_grainFrame.zw)));
// Grain below a pixel cannot be drawn: it would either moire or read as a
// different, coarser pattern, so fade it out instead of rescaling it.
float vis = smoothstep(0.45, 1.0, cell * max(pxPerUnit, 1e-4));
// Roughness adds a finer octave on top of the clumps: cream at 0, bite at 100.
float w = clamp(u_grainRough / 100.0, 0.0, 1.0) * 0.85;
float fineCell = max(cell * 0.45, 1.25 / max(pxPerUnit, 1e-4));
float n = (valueNoise(px / cell) - 0.5)
+ (valueNoise(px / fineCell + 11.7) - 0.5) * w;
n *= vis * inversesqrt(1.0 + w * w);
float mask = 1.0 - abs(clamp(luma(col), 0.0, 1.0) * 2.0 - 1.0);
col += n * ga * 0.20 * (0.6 + mask * 0.4);
}
outColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}`;
export interface Histogram {
r: Uint32Array;
g: Uint32Array;
b: Uint32Array;
l: Uint32Array;
}
interface Target {
tex: WebGLTexture;
fbo: WebGLFramebuffer;
w: number;
h: number;
}
function makeHistogram(): Histogram {
return {
r: new Uint32Array(256),
g: new Uint32Array(256),
b: new Uint32Array(256),
l: new Uint32Array(256),
};
}
export function rotatedBounds(imgW: number, imgH: number, angleDeg: number, quarter = 0) {
const swap = (((Math.round(quarter) % 4) + 4) % 4) % 2 === 1;
const w0 = swap ? imgH : imgW;
const h0 = swap ? imgW : imgH;
const a = (angleDeg * Math.PI) / 180;
const c = Math.abs(Math.cos(a));
const s = Math.abs(Math.sin(a));
return {
w: Math.max(1, w0 * c + h0 * s),
h: Math.max(1, w0 * s + h0 * c),
};
}
export function outputSize(edits: Edits, imgW: number, imgH: number) {
const frame = rotatedBounds(imgW, imgH, edits.crop.angle, edits.crop.quarter);
return {
w: Math.max(1, Math.round(frame.w * edits.crop.w)),
h: Math.max(1, Math.round(frame.h * edits.crop.h)),
};
}
/**
* Frame-uv window for a loupe that tracks the crop: a `pxW` x `pxH` source-pixel
* window (pass the export's span for output-size patches), centred on the crop or
* on an explicit point, and clamped so it never samples outside the crop.
*/
export function grainSampleWindow(
frame: { w: number; h: number },
crop: { x: number; y: number; w: number; h: number },
pxW: number,
pxH: number,
point?: { x: number; y: number } | null,
) {
const w = Math.min(crop.w, pxW / Math.max(1, frame.w));
const h = Math.min(crop.h, pxH / Math.max(1, frame.h));
const cx = point ? Math.min(Math.max(point.x, crop.x), crop.x + crop.w) : crop.x + crop.w / 2;
const cy = point ? Math.min(Math.max(point.y, crop.y), crop.y + crop.h) : crop.y + crop.h / 2;
return {
x: Math.min(Math.max(cx - w / 2, crop.x), crop.x + crop.w - w),
y: Math.min(Math.max(cy - h / 2, crop.y), crop.y + crop.h - h),
w,
h,
};
}
function frameAngle(angle: number, quarter: number) {
return -((angle * Math.PI) / 180 + (quarter * Math.PI) / 2);
}
/**
* Photo coordinates (0-1 over the untouched file) to frame coordinates, through
* the same rotate / quarter turn / flip the renderer applies. Lets a click on an
* unrotated thumbnail pick the point that lands there in the straightened crop.
*/
export function sourceToFrame(
p: { x: number; y: number },
srcW: number,
srcH: number,
angle: number,
quarter: number,
flipH = false,
flipV = false,
) {
const b = rotatedBounds(srcW, srcH, angle, quarter);
// Frame uv grows the same way as the photo's pixels (y down, as the canvas
// draws them), so only a flip mirror the offset.
const sx = (p.x - 0.5) * srcW * (flipH ? -1 : 1);
const sy = (p.y - 0.5) * srcH * (flipV ? -1 : 1);
const a = frameAngle(angle, quarter);
const ca = Math.cos(-a);
const sa = Math.sin(-a);
return {
x: (sx * ca - sy * sa) / b.w + 0.5,
y: (sx * sa + sy * ca) / b.h + 0.5,
};
}
/** The inverse of `sourceToFrame`, for drawing a marker back onto the thumbnail. */
export function frameToSource(
p: { x: number; y: number },
srcW: number,
srcH: number,
angle: number,
quarter: number,
flipH = false,
flipV = false,
) {
const b = rotatedBounds(srcW, srcH, angle, quarter);
const dx = (p.x - 0.5) * b.w;
const dy = (p.y - 0.5) * b.h;
const a = frameAngle(angle, quarter);
const ca = Math.cos(a);
const sa = Math.sin(a);
const sx = (dx * ca - dy * sa) * (flipH ? -1 : 1);
const sy = (dx * sa + dy * ca) * (flipV ? -1 : 1);
return { x: sx / srcW + 0.5, y: sy / srcH + 0.5 };
}
/**
* Size of one grain cell in exported pixels, using the renderer's own scale:
* 1200 cells across the crop's long edge, cell size 1-3 units from the slider.
*/
export function grainCellPx(
edits: {
crop: { x: number; y: number; w: number; h: number; angle: number; quarter: number };
grain: { size: number };
},
srcW: number,
srcH: number,
outW: number,
) {
const { crop } = edits;
const base = rotatedBounds(srcW, srcH, 0, crop.quarter);
const unitsPerPx = 1200 / Math.max(1, base.w * crop.w, base.h * crop.h);
const frame = rotatedBounds(srcW, srcH, crop.angle, crop.quarter);
const pxPerSource = outW / Math.max(1, frame.w * crop.w);
const cell = 1 + 2 * Math.min(1, Math.max(0, (edits.grain.size - 10) / 90));
return (cell / unitsPerPx) * pxPerSource;
}
/** Builds a 256px LUT with the composite curve baked together with each channel curve. */
export function buildCurveLUT(edits: Edits): Uint8Array {
const rgb = buildSampler(edits.curve.rgb);
const red = buildSampler(edits.curve.red);
const green = buildSampler(edits.curve.green);
const blue = buildSampler(edits.curve.blue);
const data = new Uint8Array(256 * 4);
for (let i = 0; i < 256; i++) {
const base = rgb(i / 255);
data[i * 4 + 0] = Math.round(clamp01(red(base)) * 255);
data[i * 4 + 1] = Math.round(clamp01(green(base)) * 255);
data[i * 4 + 2] = Math.round(clamp01(blue(base)) * 255);
data[i * 4 + 3] = 255;
}
return data;
}
class Prog {
private cache = new Map<string, WebGLUniformLocation | null>();
constructor(private gl: WebGL2RenderingContext, public program: WebGLProgram) {}
loc(name: string): WebGLUniformLocation | null {
if (!this.cache.has(name)) this.cache.set(name, this.gl.getUniformLocation(this.program, name));
return this.cache.get(name) ?? null;
}
f(name: string, v: number) {
const l = this.loc(name);
if (l) this.gl.uniform1f(l, v);
}
i(name: string, v: number) {
const l = this.loc(name);
if (l) this.gl.uniform1i(l, v);
}
v2(name: string, a: number, b: number) {
const l = this.loc(name);
if (l) this.gl.uniform2f(l, a, b);
}
v4(name: string, a: number, b: number, c: number, d: number) {
const l = this.loc(name);
if (l) this.gl.uniform4f(l, a, b, c, d);
}
v3(name: string, a: number, b: number, c: number) {
const l = this.loc(name);
if (l) this.gl.uniform3f(l, a, b, c);
}
fv(name: string, values: Float32Array) {
const l = this.loc(`${name}[0]`) ?? this.loc(name);
if (l) this.gl.uniform1fv(l, values);
}
tex(name: string, texture: WebGLTexture, unit: number) {
const l = this.loc(name);
if (!l) return;
this.gl.activeTexture(this.gl.TEXTURE0 + unit);
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
this.gl.uniform1i(l, unit);
}
}
function compile(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader {
const shader = gl.createShader(type);
if (!shader) throw new Error('Unable to create shader');
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error(`Shader compile error: ${log}`);
}
return shader;
}
function link(gl: WebGL2RenderingContext, vsSource: string, fsSource: string): WebGLProgram {
const vs = compile(gl, gl.VERTEX_SHADER, vsSource);
const fs = compile(gl, gl.FRAGMENT_SHADER, fsSource);
const program = gl.createProgram();
if (!program) throw new Error('Unable to create program');
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
gl.deleteShader(vs);
gl.deleteShader(fs);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const log = gl.getProgramInfoLog(program);
gl.deleteProgram(program);
throw new Error(`Program link error: ${log}`);
}
return program;
}
export class Renderer {
readonly canvas: HTMLCanvasElement;
private gl: WebGL2RenderingContext;
private grade: Prog;
private blur: Prog;
private finish: Prog;
private quad: WebGLBuffer;
private vao: WebGLVertexArrayObject;
private srcTex: WebGLTexture;
private srcBitmap: ImageBitmap | null = null;
private srcW = 1;
private srcH = 1;
private curveTex: WebGLTexture;
private targets: { graded?: Target; smallA?: Target; smallB?: Target; bigA?: Target; bigB?: Target } = {};
private histTarget: Target | null = null;
private histW = 160;
private histH = 112;
private grainRef: { x: number; y: number; w: number; h: number; sx: number; sy: number; units: number } | null = null;
histogram: Histogram = makeHistogram();
constructor(canvas: HTMLCanvasElement) {
this.canvas = canvas;
const gl = canvas.getContext('webgl2', {
alpha: false,
antialias: false,
depth: false,
stencil: false,
preserveDrawingBuffer: false,
powerPreference: 'high-performance',
});
if (!gl) throw new Error('This browser does not support WebGL2, which the editor needs.');
this.gl = gl;
this.grade = new Prog(gl, link(gl, VERT, GRADE_FRAG));
this.blur = new Prog(gl, link(gl, VERT, BLUR_FRAG));
this.finish = new Prog(gl, link(gl, VERT, FINISH_FRAG));
const quad = gl.createBuffer();
if (!quad) throw new Error('Unable to create buffer');
this.quad = quad;
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
const vao = gl.createVertexArray();
if (!vao) throw new Error('Unable to create vertex array');
this.vao = vao;
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
const srcTex = gl.createTexture();
if (!srcTex) throw new Error('Unable to create texture');
this.srcTex = srcTex;
gl.bindTexture(gl.TEXTURE_2D, srcTex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
const curveTex = gl.createTexture();
if (!curveTex) throw new Error('Unable to create texture');
this.curveTex = curveTex;
gl.bindTexture(gl.TEXTURE_2D, curveTex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.disable(gl.BLEND);
gl.disable(gl.DEPTH_TEST);
}
static isSupported(): boolean {
try {
const c = document.createElement('canvas');
return !!c.getContext('webgl2');
} catch {
return false;
}
}
setImage(bitmap: ImageBitmap) {
if (this.srcBitmap === bitmap) return;
this.grainRef = null;
const gl = this.gl;
this.srcBitmap = bitmap;
this.srcW = bitmap.width;
this.srcH = bitmap.height;
gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
// Mipmaps: a 6000 px proxy shown fitted is a 4-8x minification, which shimmers
// badly with plain bilinear sampling.
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
}
private makeTarget(w: number, h: number): Target {
const gl = this.gl;
const tex = gl.createTexture();
const fbo = gl.createFramebuffer();
if (!tex || !fbo) throw new Error('Unable to allocate render target');
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return { tex, fbo, w, h };
}
private freeTarget(target?: Target) {
if (!target) return;
this.gl.deleteTexture(target.tex);
this.gl.deleteFramebuffer(target.fbo);
}
private ensureTargets(w: number, h: number) {
const t = this.targets;
if (!t.graded || t.graded.w !== w || t.graded.h !== h) {
this.freeTarget(t.graded);
this.freeTarget(t.smallA);
this.freeTarget(t.smallB);
this.freeTarget(t.bigA);
this.freeTarget(t.bigB);
const sw = Math.max(1, Math.ceil(w / 2));
const sh = Math.max(1, Math.ceil(h / 2));
const bw = Math.max(1, Math.ceil(w / 4));
const bh = Math.max(1, Math.ceil(h / 4));
this.targets = {
graded: this.makeTarget(w, h),
smallA: this.makeTarget(sw, sh),
smallB: this.makeTarget(sw, sh),
bigA: this.makeTarget(bw, bh),
bigB: this.makeTarget(bw, bh),
};
}
}
private drawQuad() {
const gl = this.gl;
gl.bindVertexArray(this.vao);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.bindVertexArray(null);
}
private uploadCurve(edits: Edits) {
const gl = this.gl;
const data = buildCurveLUT(edits);
gl.bindTexture(gl.TEXTURE_2D, this.curveTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
}
render(
edits: Edits,
opts: {
width: number;
height: number;
cropPreview?: boolean;
histogram?: boolean;
/** visible sub-rect of the frame, normalized; defaults to the whole crop */
view?: { x: number; y: number; w: number; h: number };
/** sample bicubically, for when the view magnifies the source beyond 1:1 */
upscale?: boolean;
/** hold the grain pattern still, e.g. while a crop handle is being dragged */
freezeGrain?: boolean;
},
) {
const gl = this.gl;
if (!this.srcBitmap) return;
const w = Math.max(1, Math.round(opts.width));
const h = Math.max(1, Math.round(opts.height));
if (this.canvas.width !== w) this.canvas.width = w;
if (this.canvas.height !== h) this.canvas.height = h;
this.ensureTargets(w, h);
const t = this.targets;
if (!t.graded || !t.smallA || !t.smallB || !t.bigA || !t.bigB) return;
this.uploadCurve(edits);
const bounds = rotatedBounds(this.srcW, this.srcH, edits.crop.angle, edits.crop.quarter);
const valid = opts.cropPreview
? { x: 0, y: 0, w: 1, h: 1 }
: { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h };
const crop = opts.view ?? valid;
// Pass 1: white balance, tone, curve, color
gl.bindFramebuffer(gl.FRAMEBUFFER, t.graded.fbo);
gl.viewport(0, 0, w, h);
const g = this.grade;
gl.useProgram(g.program);
g.tex('u_src', this.srcTex, 0);
g.tex('u_curve', this.curveTex, 1);
g.v2('u_srcSize', this.srcW, this.srcH);
g.v2('u_frameSize', bounds.w, bounds.h);
g.v4('u_crop', crop.x, crop.y, crop.w, crop.h);
g.v4('u_valid', valid.x, valid.y, valid.w, valid.h);
g.f('u_angle', (edits.crop.angle * Math.PI) / 180);
g.i('u_quarter', edits.crop.quarter);
g.v2('u_flip', edits.crop.flipH ? -1 : 1, edits.crop.flipV ? -1 : 1);
g.f('u_upscale', opts.upscale ? 1 : 0);
g.f('u_temp', edits.temp);
g.f('u_tint', edits.tint);
g.f('u_exposure', edits.exposure);
g.f('u_contrast', edits.contrast);
g.f('u_highlights', edits.highlights);
g.f('u_shadows', edits.shadows);
g.f('u_whites', edits.whites);
g.f('u_blacks', edits.blacks);
g.f('u_vibrance', edits.vibrance);
g.f('u_saturation', edits.saturation);
g.f('u_bw', edits.bw ? 1 : 0);
const bwFilter = bwFilterRgb(edits.bwFilter);
g.v3('u_bwFilter', bwFilter[0], bwFilter[1], bwFilter[2]);
g.f('u_bwFilterAmt', clamp01(edits.bwFilterAmount / 100));
g.fv('u_hue', new Float32Array(edits.hsl.hue));
g.fv('u_sat', new Float32Array(edits.hsl.sat));
g.fv('u_lum', new Float32Array(edits.hsl.lum));
g.f('u_gSh', edits.grading.shadows.h / 360);
g.f('u_gSs', edits.grading.shadows.s);
g.f('u_gHi', edits.grading.highlights.h / 360);
g.f('u_gHs', edits.grading.highlights.s);
g.f('u_gBal', edits.grading.balance);
this.drawQuad();
// Passes 2-3: small blur (detail) and large blur (clarity) from the graded image
const blurPass = (from: Target, to: Target, dx: number, dy: number, srcTex: WebGLTexture) => {
const gl2 = this.gl;
gl2.bindFramebuffer(gl2.FRAMEBUFFER, to.fbo);
gl2.viewport(0, 0, to.w, to.h);
gl2.useProgram(this.blur.program);
this.blur.tex('u_tex', srcTex, 0);
this.blur.v2('u_dir', dx, dy);
this.drawQuad();
};
gl.bindFramebuffer(gl.FRAMEBUFFER, t.smallA.fbo);
gl.viewport(0, 0, t.smallA.w, t.smallA.h);
gl.useProgram(this.blur.program);
this.blur.tex('u_tex', t.graded.tex, 0);
this.blur.v2('u_dir', (edits.sharpen.radius / t.smallA.w) * 0.75, 0);
this.drawQuad();
blurPass(t.smallA, t.smallB, 0, (edits.sharpen.radius / t.smallB.h) * 0.75, t.smallA.tex);
gl.bindFramebuffer(gl.FRAMEBUFFER, t.bigA.fbo);
gl.viewport(0, 0, t.bigA.w, t.bigA.h);
gl.useProgram(this.blur.program);
this.blur.tex('u_tex', t.graded.tex, 0);
this.blur.v2('u_dir', 2.0 / t.bigA.w, 0);
this.drawQuad();
blurPass(t.bigA, t.bigB, 0, 2.0 / t.bigB.h, t.bigA.tex);
// Grain cells are counted across the crop's long edge: the same slider value
// covers the same share of the picture at every resolution and crop. While a
// handle is being dragged the reference is held, so the noise stands still.
const GRAIN_UNITS = 1200;
// Scaled from the un-straightened frame: straightening grows the rotating
// bounding box, which would otherwise resize the grain along with it.
const base = rotatedBounds(this.srcW, this.srcH, 0, edits.crop.quarter);
const cropW = Math.max(1, base.w * valid.w);
const cropH = Math.max(1, base.h * valid.h);
const grainUnits = GRAIN_UNITS / Math.max(cropW, cropH);
if (!opts.freezeGrain || !this.grainRef) {
this.grainRef = {
x: valid.x,
y: valid.y,
w: valid.w,
h: valid.h,
sx: cropW * grainUnits,
sy: cropH * grainUnits,
units: grainUnits,
};
}
const grain = this.grainRef;
const grainRot = -((edits.crop.angle * Math.PI) / 180 + (edits.crop.quarter * Math.PI) / 2);
// Pass 4: detail, effects, grain -> canvas
const finishDraw = (target: Target | null) => {
const gl2 = this.gl;
if (target) {
gl2.bindFramebuffer(gl2.FRAMEBUFFER, target.fbo);
gl2.viewport(0, 0, target.w, target.h);
} else {
gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
gl2.viewport(0, 0, w, h);
}
gl2.useProgram(this.finish.program);
this.finish.tex('u_graded', t.graded!.tex, 0);
this.finish.tex('u_blurSmall', t.smallB!.tex, 1);
this.finish.tex('u_blurBig', t.bigB!.tex, 2);
this.finish.f('u_texture', edits.texture);
this.finish.f('u_clarity', edits.clarity);
this.finish.f('u_dehaze', edits.dehaze);
this.finish.f('u_sharpen', edits.sharpen.amount);
this.finish.f('u_nr', edits.noise.luminance);
this.finish.f('u_vigAmt', edits.vignette.amount);
this.finish.f('u_vigMid', edits.vignette.midpoint);
this.finish.f('u_vigFeather', edits.vignette.feather);
this.finish.f('u_grainAmt', edits.grain.amount);
this.finish.f('u_grainSize', edits.grain.size);
this.finish.f('u_grainRough', edits.grain.roughness);
this.finish.v4('u_crop', crop.x, crop.y, crop.w, crop.h);
this.finish.v4('u_grainFrame', grain.x, grain.y, grain.w, grain.h);
this.finish.v2('u_grainSpace', grain.sx, grain.sy);
this.finish.f('u_grainUnits', grain.units);
this.finish.v2('u_frameSize', bounds.w, bounds.h);
this.finish.f('u_grainRot', grainRot);
this.finish.v2('u_grainFlip', edits.crop.flipH ? -1 : 1, edits.crop.flipV ? -1 : 1);
this.finish.v2('u_outSize', target ? target.w : w, target ? target.h : h);
this.finish.f('u_aspect', w / h);
this.drawQuad();
};
finishDraw(null);
if (opts.histogram) {
if (!this.histTarget) this.histTarget = this.makeTarget(this.histW, this.histH);
finishDraw(this.histTarget);
const pixels = new Uint8Array(this.histW * this.histH * 4);
gl.readPixels(0, 0, this.histW, this.histH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
const hist = this.histogram;
hist.r.fill(0);
hist.g.fill(0);
hist.b.fill(0);
hist.l.fill(0);
for (let i = 0; i < pixels.length; i += 4) {
const r = pixels[i];
const gg = pixels[i + 1];
const b = pixels[i + 2];
hist.r[r]++;
hist.g[gg]++;
hist.b[b]++;
hist.l[Math.round(0.2126 * r + 0.7152 * gg + 0.0722 * b)]++;
}
}
}
dispose() {
const gl = this.gl;
this.freeTarget(this.targets.graded);
this.freeTarget(this.targets.smallA);
this.freeTarget(this.targets.smallB);
this.freeTarget(this.targets.bigA);
this.freeTarget(this.targets.bigB);
this.freeTarget(this.histTarget ?? undefined);
gl.deleteTexture(this.srcTex);
gl.deleteTexture(this.curveTex);
gl.deleteBuffer(this.quad);
gl.deleteVertexArray(this.vao);
gl.deleteProgram(this.grade.program);
gl.deleteProgram(this.blur.program);
gl.deleteProgram(this.finish.program);
// Release the context slot so switching between library and develop does not
// exhaust the browser's WebGL context limit.
const ext = gl.getExtension('WEBGL_lose_context');
ext?.loseContext();
}
}
+161
View File
@@ -0,0 +1,161 @@
import type { EventRecord, PhotoRecord, Preset } from '../types';
export interface Health {
ok: boolean;
app: string;
version: string;
needsSetup: boolean;
registrationOpen: boolean;
photos: number;
bytes: number;
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 Lumenroom 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;
}): 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 SyncPayload {
user: SessionUser;
events: EventRecord[];
photos: PhotoRecord[];
presets: Preset[];
}
export function pullAll(): Promise<SyncPayload> {
return request<SyncPayload>('/api/sync');
}
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 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' });
}
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 };
}
}
+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;
}
+297
View File
@@ -0,0 +1,297 @@
import type { BwFilter, ColorLabel, CropState, CurvePoint, Edits, Flag, 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(' ');
}
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,
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(),
},
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 },
noise: { luminance: 0, detail: 50 },
vignette: { amount: 0, midpoint: 50, feather: 50 },
grain: { amount: 0, size: 25, roughness: 50 },
crop: defaultCrop(),
};
}
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. */
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 grading = (input.grading ?? {}) as Partial<Edits['grading']>;
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
const noise = (input.noise ?? {}) as Partial<Edits['noise']>;
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,
temp: num(input.temp, 0, -100, 100),
tint: num(input.tint, 0, -100, 100),
exposure: num(input.exposure, 0, -5, 5),
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),
},
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),
},
noise: {
luminance: num(noise.luminance, 0, 0, 100),
detail: num(noise.detail, 50, 0, 100),
},
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,
decode: input.decode,
previewUrl: input.previewUrl,
thumbUrl: input.thumbUrl,
thumbVersion: input.thumbVersion,
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 ?? '',
rating: clamp(Math.round(input.rating ?? 0), 0, 5),
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' },
];
+137
View File
@@ -0,0 +1,137 @@
import type { Edits, PhotoRecord } from '../types';
import { getBitmap } from './images';
import { normalizeEdits } from './edits';
import { outputSize, Renderer } from '../gl/renderer';
export type ExportFormat = 'jpeg' | 'png' | 'webp';
export type ResizeMode = 'none' | 'longEdge' | 'percent';
export interface ExportOptions {
format: ExportFormat;
quality: number;
resize: ResizeMode;
longEdge: number;
percent: number;
nameTemplate: string;
}
export const DEFAULT_EXPORT: ExportOptions = {
format: 'jpeg',
quality: 92,
resize: 'none',
longEdge: 3000,
percent: 100,
nameTemplate: '{name}',
};
const MIME: Record<ExportFormat, string> = {
jpeg: 'image/jpeg',
png: 'image/png',
webp: 'image/webp',
};
const EXT: Record<ExportFormat, string> = {
jpeg: 'jpg',
png: 'png',
webp: 'webp',
};
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 edits = normalizeEdits(photo.edits);
const { w, h } = targetSize(photo, edits, bitmap, opts);
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
const renderer = new Renderer(canvas);
try {
renderer.setImage(bitmap);
renderer.render(edits, { width: w, height: h });
const mime = MIME[opts.format];
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))),
);
if (!blob) throw new Error('Export failed while encoding the image');
return blob;
} finally {
renderer.dispose();
}
}
export async function exportPhotos(
photos: PhotoRecord[],
opts: ExportOptions,
onProgress?: (done: number, total: number) => void,
): Promise<{ count: number; failed: string[] }> {
let count = 0;
const failed: string[] = [];
for (let i = 0; i < photos.length; i++) {
const photo = photos[i];
try {
const blob = await renderPhotoBlob(photo, opts);
download(blob, buildFileName(opts.nameTemplate, photo, i, opts));
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));
}
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));
}
+78
View File
@@ -0,0 +1,78 @@
import type { PhotoRecord } from '../types';
import { getAsset, putAsset } from './db';
const CACHE_LIMIT = 6;
const cache = new Map<string, ImageBitmap>();
/**
* Grid/filmstrip thumbnail URL. The version stamp changes when the saved edit is
* re-rendered, so the browser does not keep showing the pre-edit thumbnail.
*/
export function thumbSrc(photo: PhotoRecord): string {
if (!photo.thumbUrl) return photo.thumb;
return photo.thumbVersion
? `${photo.thumbUrl}?v=${photo.thumbVersion}`
: photo.thumbUrl;
}
/** 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`;
}
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 getAsset(photo.id);
if (!blob) blob = (await fetchRemote(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();
}
+240
View File
@@ -0,0 +1,240 @@
import exifr from 'exifr';
import type { UploadResult } from './api';
import type { PhotoMeta, PhotoRecord } from '../types';
import { putAsset, putPhoto } from './db';
import { defaultEdits, normalizePhoto } from './edits';
import { isRawFile, RAW_EXTENSIONS } from './raw';
export interface ImportProgress {
done: number;
total: number;
current: string;
}
export interface ImportResult {
photos: PhotoRecord[];
failed: { name: string; reason: string }[];
}
/** Provided by the app when a Lumenroom server is connected. */
export interface CloudImport {
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>;
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
}
/** Files imported at once; the server bounds how many raws decode in parallel. */
const IMPORT_CONCURRENCY = 4;
export function uid(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
}
function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void[]> {
let cursor = 0;
const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
for (;;) {
const index = cursor++;
if (index >= items.length) return;
await fn(items[index], index);
}
});
return Promise.all(runners);
}
function formatShutter(time: unknown): string | undefined {
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
return `1/${Math.round(1 / time)}s`;
}
async function readMeta(file: File): Promise<{ meta: PhotoMeta; takenAt?: number }> {
try {
const data = (await exifr.parse(file, {
tiff: true,
exif: true,
gps: false,
interop: false,
translateValues: false,
reviveValues: true,
})) as Record<string, unknown> | undefined;
if (!data) return { meta: {} };
const make = typeof data.Make === 'string' ? data.Make.trim() : '';
const model = typeof data.Model === 'string' ? data.Model.trim() : '';
const meta: PhotoMeta = {
camera: [make, model].filter(Boolean).join(' ').replace(/\s+/g, ' ') || undefined,
lens: typeof data.LensModel === 'string' ? data.LensModel.trim() : undefined,
iso: typeof data.ISO === 'number' ? data.ISO : undefined,
aperture: typeof data.FNumber === 'number' ? data.FNumber : undefined,
shutter: formatShutter(data.ExposureTime),
focal: typeof data.FocalLength === 'number' ? Math.round(data.FocalLength) : undefined,
};
const taken = data.DateTimeOriginal ?? data.CreateDate ?? data.ModifyDate;
const takenAt = taken instanceof Date && !Number.isNaN(taken.getTime()) ? taken.getTime() : undefined;
return { meta, takenAt };
} catch {
return { meta: {} };
}
}
async function makeThumb(bitmap: ImageBitmap): Promise<string> {
const max = 560;
const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height));
const w = Math.max(1, Math.round(bitmap.width * scale));
const h = Math.max(1, Math.round(bitmap.height * scale));
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas 2D is unavailable');
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(bitmap, 0, 0, w, h);
return canvas.toDataURL('image/jpeg', 0.82);
}
export function isSupportedFile(file: File): boolean {
if (file.type.startsWith('image/')) return true;
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
return RAW_EXTENSIONS.has(ext) || /^(jpe?g|png|webp|avif|gif|bmp|tiff?)$/.test(ext);
}
/**
* Raw files cannot be decoded by the browser, so they are sent to the server,
* demosaiced there, and represented locally by the returned editable proxy.
*/
async function importRaw(file: File, eventId: string, keywords: string[], cloud: CloudImport): Promise<PhotoRecord> {
const id = uid();
const upload = await cloud.uploadOriginal(id, file, file.name);
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
const res = await fetch(previewUrl, { credentials: 'same-origin' });
if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
const blob = await res.blob();
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
const thumb = await makeThumb(bitmap);
const { meta, takenAt } = await readMeta(file);
const width = upload.width ?? bitmap.width;
const height = upload.height ?? bitmap.height;
bitmap.close();
const record = normalizePhoto({
id,
eventId,
name: file.name,
width,
height,
size: file.size,
mime: 'image/jpeg',
addedAt: Date.now(),
takenAt: takenAt ?? file.lastModified,
meta,
thumb,
rating: 0,
flag: 'none',
color: '',
keywords,
edits: defaultEdits(),
history: [{ label: 'Import', ts: Date.now(), edits: defaultEdits() }],
raw: true,
decode: upload.engine,
previewUrl,
});
await putPhoto(record);
// No local blob: the multi-megabyte raw stays on the server.
const saved = await cloud.push(record);
const merged = normalizePhoto({ ...record, ...saved });
await putPhoto(merged);
return merged;
}
async function importStandard(
file: File,
eventId: string,
keywords: string[],
cloud?: CloudImport | null,
): Promise<PhotoRecord> {
// Camera JPEGs carry their orientation in EXIF; ask for it to be applied so
// the thumbnail and the edited proxy agree with what the camera shot.
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
const thumb = await makeThumb(bitmap);
const { meta, takenAt } = await readMeta(file);
const id = uid();
let record = normalizePhoto({
id,
eventId,
name: file.name,
width: bitmap.width,
height: bitmap.height,
size: file.size,
mime: file.type || 'image/jpeg',
addedAt: Date.now(),
takenAt: takenAt ?? file.lastModified,
meta,
thumb,
rating: 0,
flag: 'none',
color: '',
keywords,
edits: defaultEdits(),
history: [{ label: 'Import', ts: Date.now(), edits: defaultEdits() }],
});
await putAsset(id, file);
bitmap.close();
if (cloud) {
// Originals are mirrored to the server; failures fall back to a local-only import.
try {
await cloud.uploadOriginal(id, file, file.name);
const saved = await cloud.push(record);
record = normalizePhoto({ ...record, ...saved });
} catch (err) {
console.warn('Could not copy the original to the server', file.name, err);
}
}
await putPhoto(record);
return record;
}
export async function importFiles(
files: File[],
eventId: string,
keywords: string[] = [],
onProgress?: (p: ImportProgress) => void,
cloud?: CloudImport | null,
): Promise<ImportResult> {
const result: ImportResult = { photos: [], failed: [] };
const images = files.filter(isSupportedFile);
const total = images.length;
if (!total) return result;
const collected: { index: number; photo: PhotoRecord }[] = [];
let done = 0;
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
try {
const photo = isRawFile(file)
? cloud
? await importRaw(file, eventId, keywords, cloud)
: (() => {
throw new Error('Raw files need the Lumenroom server. Sign in, then import again.');
})()
: await importStandard(file, eventId, keywords, cloud);
collected.push({ index, photo });
} catch (err) {
result.failed.push({
name: file.name,
reason: err instanceof Error ? err.message : 'Unsupported image format',
});
} finally {
done += 1;
onProgress?.({ done, total, current: file.name });
}
});
// Keep the shoot in capture/selection order regardless of which finished first.
collected.sort((a, b) => a.index - b.index);
result.photos = collected.map((c) => c.photo);
onProgress?.({ done: total, total, current: '' });
return result;
}
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
/** Raw containers the server can demosaic (LibRaw) or fall back to previews for. */
export const RAW_EXTENSIONS = new Set([
'cr2', 'cr3', 'crw',
'nef', 'nrw',
'arw', 'srf', 'sr2',
'orf',
'rw2', 'raw', 'rwl',
'raf',
'pef', 'dng',
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef',
]);
export function isRawFile(file: File): boolean {
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
return RAW_EXTENSIONS.has(ext);
}
export const RAW_ACCEPT = [...RAW_EXTENSIONS].map((e) => `.${e}`).join(',');
+7
View File
@@ -0,0 +1,7 @@
import { createRoot } from 'react-dom/client';
import App from './App';
import './styles.css';
const root = document.getElementById('root');
if (!root) throw new Error('root element missing');
createRoot(root).render(<App />);
File diff suppressed because it is too large Load Diff
+147
View File
@@ -0,0 +1,147 @@
export type ViewMode = 'grid' | 'develop';
export type Flag = 'none' | 'pick' | 'reject';
export type ColorLabel = '' | 'red' | 'yellow' | 'green' | 'blue' | 'purple';
/** Contrast filter placed over the lens when shooting black & white film. */
export type BwFilter = 'none' | 'yellow' | 'orange' | 'red' | 'green' | 'blue';
export type CurveChannel = 'rgb' | 'red' | 'green' | 'blue';
export interface CurvePoint {
x: number;
y: number;
}
export interface CropState {
/** normalized crop rect inside the straightened frame, origin top-left */
x: number;
y: number;
w: number;
h: number;
/** straighten angle in degrees */
angle: number;
/** extra 90° turns applied before the straighten angle, 0–3 */
quarter: number;
/** locked aspect preset id, "free" or "original" */
aspect: string;
flipH: boolean;
flipV: boolean;
}
export interface Edits {
temp: number;
tint: number;
exposure: number;
contrast: number;
highlights: number;
shadows: number;
whites: number;
blacks: number;
texture: number;
clarity: number;
dehaze: number;
vibrance: number;
saturation: number;
bw: boolean;
/** colored filter simulated in black & white mode */
bwFilter: BwFilter;
/** how strongly that filter acts, 0–100 */
bwFilterAmount: number;
curve: Record<CurveChannel, CurvePoint[]>;
hsl: { hue: number[]; sat: number[]; lum: number[] };
grading: {
shadows: { h: number; s: number };
highlights: { h: number; s: number };
balance: number;
};
sharpen: { amount: number; radius: number; detail: number };
noise: { luminance: number; detail: number };
vignette: { amount: number; midpoint: number; feather: number };
/** roughness leans from creamy clumps (0) to crisp per-pixel bite (100) */
grain: { amount: number; size: number; roughness: number };
crop: CropState;
}
export interface PhotoMeta {
camera?: string;
lens?: string;
iso?: number;
aperture?: number;
shutter?: string;
focal?: number;
}
export interface HistoryEntry {
label: string;
ts: number;
edits: Edits;
}
export interface PhotoRecord {
id: string;
eventId: string;
/** manual sort position inside the event */
order?: number;
name: string;
width: number;
height: number;
size: number;
mime: string;
addedAt: number;
takenAt?: number;
meta: PhotoMeta;
thumb: string;
rating: number;
flag: Flag;
color: ColorLabel;
keywords: string[];
edits: Edits;
history: HistoryEntry[];
/** true when the original is a camera raw decoded by the server */
raw?: boolean;
/** how the editable proxy was produced */
decode?: 'libraw' | 'embedded';
/** server URL for the editable proxy (raw only) */
previewUrl?: string;
/** server URL for the grid thumbnail */
thumbUrl?: string;
/** bumps the thumbnail URL whenever the saved edit is re-rendered */
thumbVersion?: number;
/** Set when the photo is proxied from a dashboard bridge session. */
bridgeSource?: { sessionId: string; sourceId: string };
}
export interface EventRecord {
id: string;
name: string;
date?: number;
createdAt: number;
notes?: string;
/** sidebar position */
order?: number;
/** Set when this event is a temporary import from the dashboard bridge. */
bridge?: {
sessionId: string;
sourceEventId: string;
/** Where "Back to dashboard" goes. */
dashboardUrl: string;
expiresAt: number;
};
}
export interface Filters {
minRating: number;
flag: Flag | 'any';
colors: ColorLabel[];
text: string;
editedOnly: boolean;
unrated: boolean;
}
export type SortKey = 'taken' | 'added' | 'name' | 'rating' | 'custom';
export interface Preset {
id: string;
name: string;
group: string;
edits: Partial<Omit<Edits, 'crop'>>;
custom?: boolean;
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["src", "vite.config.ts"]
}
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
/** Dev server proxies /api to the Lumenroom server on its default port. */
const API_TARGET = 'http://127.0.0.1:8787';
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
'/api': { target: API_TARGET, changeOrigin: false },
},
},
});
Binary file not shown.
Binary file not shown.
Binary file not shown.
+61 -2
View File
@@ -4,7 +4,11 @@ import { Download, Printer } from "lucide-react";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listPendingCoverageRequests } from "@/db/coverage";
import {
listPendingAlternativeProposals,
listPendingCoverageRequests,
} from "@/db/coverage";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import { listCoverageIntakes } from "@/db/intake";
import { rankedCandidatesForSlot } from "@/db/rankedCandidates";
import { Button } from "@/components/ui/button";
@@ -24,9 +28,10 @@ export default async function CoveragePage() {
if (!user?.id) return null;
if (!hasPermission(user.systemRole, "schedule.publish")) redirect("/home");
const [requests, intakes] = await Promise.all([
const [requests, intakes, alternatives] = await Promise.all([
listPendingCoverageRequests(),
listCoverageIntakes("new"),
listPendingAlternativeProposals(),
]);
const views: CoverageRequestView[] = await Promise.all(
@@ -96,6 +101,60 @@ export default async function CoveragePage() {
<CoverageBoard requests={views} intakes={intakeViews} />
{alternatives.length > 0 && (
<section className="rounded-md border border-border">
<div className="border-b border-border bg-muted/30 px-3 py-2">
<h2 className="text-sm font-semibold">Proposed another Sunday</h2>
<p className="text-xs text-muted-foreground">
These volunteers cannot serve their proposed date but offered an
alternative. Reassign them from the schedule, then clear the seat.
</p>
</div>
<ul className="divide-y divide-border">
{alternatives.map((proposal) => (
<li key={proposal.id} className="space-y-1 px-3 py-2 text-sm">
<p>
<span className="font-medium">{proposal.requesterName}</span>{" "}
({proposal.roleName}) can serve{" "}
<span className="font-medium">
{formatInTimezone(
proposal.proposedStartsAt,
CHURCH_TIMEZONE,
{
timeZone: CHURCH_TIMEZONE,
weekday: "short",
month: "short",
day: "numeric",
},
)}
</span>{" "}
instead of{" "}
{formatInTimezone(
proposal.currentStartsAt,
CHURCH_TIMEZONE,
{
timeZone: CHURCH_TIMEZONE,
weekday: "short",
month: "short",
day: "numeric",
},
)}
.
</p>
{proposal.note && (
<p className="text-xs text-muted-foreground">
“{proposal.note}”
</p>
)}
<p className="text-xs text-muted-foreground">
{proposal.requesterEmail}
</p>
</li>
))}
</ul>
</section>
)}
<p className="text-xs text-muted-foreground">
Share the public request form at{" "}
<Link href="/request-coverage" className="font-medium underline">
@@ -1,126 +0,0 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft, Download } from "lucide-react";
import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles";
import { getFolderDetail } from "@/db/events";
import {
isBrowserRenderablePhoto,
isEditableEventPhoto,
} from "@/lib/event-photos";
import { mediaStorage } from "@/lib/media-storage";
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
PhotoGallery,
type GalleryPhoto,
} from "@/components/app/events/photo-gallery";
const KIND_LABELS: Record<string, string> = {
originals: "RAW / originals",
edited: "Edited exports",
mixed: "Mixed",
};
function sizeLabel(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
if (bytes < 1024 * 1024 * 1024) {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
/**
* A folder's gallery. Every assigned photographer can see and download every
* file; only the uploader or an event manager can delete one.
*/
export default async function EventFolderPage({
params,
}: {
params: Promise<{ id: string; folderId: string }>;
}) {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) redirect("/login");
const { id, folderId } = await params;
const detail = await getFolderDetail(folderId, user.id, user.systemRole);
if (!detail || detail.event.id !== id) notFound();
// Photos live only on the configured media storage share, so the uploader and
// editor stay disabled (with the reason) until that destination is ready.
const storage = await mediaStorage();
const photos: GalleryPhoto[] = detail.photos.map((photo) => ({
id: photo.id,
filename: photo.filename,
sizeBytes: photo.sizeBytes,
kind: photo.kind,
uploaderId: photo.uploaderId,
uploaderName: photo.uploaderName,
previewable: isBrowserRenderablePhoto(photo.filename),
editable: isEditableEventPhoto(photo.filename),
adjustments: parseStoredPhotoAdjustments(photo.editJson),
editedAt: photo.editedAt ? photo.editedAt.toISOString() : null,
editedSizeBytes: photo.editedSizeBytes,
}));
return (
<div className="space-y-5">
<div>
<Link
href={`/events/${detail.event.id}`}
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
{detail.event.title}
</Link>
</div>
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-xl font-semibold tracking-tight">
{detail.folder.name}
</h1>
<p className="text-sm text-muted-foreground">
{detail.photos.length} photo{detail.photos.length === 1 ? "" : "s"}{" "}
· {sizeLabel(detail.folder.totalBytes)}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary">
{KIND_LABELS[detail.folder.kind] ?? detail.folder.kind}
</Badge>
{detail.photos.length > 0 && (
<Button asChild variant="outline" size="sm">
<a
href={`/api/events/${detail.event.id}/download?folderId=${detail.folder.id}`}
>
<Download className="h-3.5 w-3.5" aria-hidden="true" />
Download folder ({detail.photos.length})
</a>
</Button>
)}
</div>
</div>
<PhotoGallery
eventId={detail.event.id}
folderId={detail.folder.id}
photos={photos}
canContribute={detail.canContribute}
canManage={detail.canManage}
currentUserId={user.id}
storageReady={storage.ok}
storageMessage={
storage.ok
? ""
: storage.message
}
/>
</div>
);
}
+80 -54
View File
@@ -1,10 +1,23 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft, Camera, Download, Film, FolderOpen, MapPin, Play } from "lucide-react";
import {
ArrowLeft,
Camera,
Download,
Film,
Image as ImageIcon,
MapPin,
Play,
} from "lucide-react";
import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles";
import { getEventDetail, listAssignableUsers } from "@/db/events";
import {
getEventDetail,
listAssignableUsers,
listEventPhotos,
} from "@/db/events";
import { listEventVideos } from "@/db/videos";
import { bridgeConfigured } from "@/lib/bridge";
import { formatVideoDuration } from "@/lib/event-videos";
import { getStorageSettings } from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage";
@@ -15,17 +28,21 @@ import {
PhotographerPanel,
type EventPhotographer,
} from "@/components/app/events/photographer-panel";
import { FolderCreateForm } from "@/components/app/events/folder-create-form";
import { DeleteEventButton } from "@/components/app/events/delete-event-button";
import { AdvancedEditorButton } from "@/components/app/events/advanced-editor-button";
import { ArchiveEventButton } from "@/components/app/events/archive-event-button";
import { VideoUploadForm } from "@/components/app/media/video-upload-form";
import { Button } from "@/components/ui/button";
const KIND_LABELS: Record<string, string> = {
originals: "RAW / originals",
edited: "Edited exports",
mixed: "Mixed",
};
import {
PhotoGallery,
type GalleryPhoto,
} from "@/components/app/events/photo-gallery";
import {
isBrowserRenderablePhoto,
isEditableEventPhoto,
} from "@/lib/event-photos";
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { advancedEditViewFor } from "@/lib/advanced-edit";
function when(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
@@ -48,9 +65,9 @@ function sizeLabel(bytes: number): string {
}
/**
* One event: brief, assigned photographers, and the shared folders. Managers
* assign people; any assignee can create folders. Folder pages own uploads;
* the event header downloads every photo as one ZIP.
* One event: brief, assigned photographers, and every photo in a single
* gallery. Managers assign people; any assignee can upload here. The header
* downloads every photo (or only the edited ones) as one ZIP.
*/
export default async function EventDetailPage({
params,
@@ -79,6 +96,25 @@ export default async function EventDetailPage({
role: person.role,
}),
);
const photos: GalleryPhoto[] = (await listEventPhotos(event.event.id)).map(
(photo) => ({
id: photo.id,
folderId: photo.folderId,
filename: photo.filename,
sizeBytes: photo.sizeBytes,
kind: photo.kind,
uploaderId: photo.uploaderId,
uploaderName: photo.uploaderName,
previewable: isBrowserRenderablePhoto(photo.filename),
editable: isEditableEventPhoto(photo.filename),
adjustments: parseStoredPhotoAdjustments(photo.editJson),
advancedEdit: Boolean(photo.advancedEditJson),
advancedSummary: advancedEditViewFor(photo.advancedEditJson),
editedAt: photo.editedAt ? photo.editedAt.toISOString() : null,
editedSizeBytes: photo.editedSizeBytes,
}),
);
const editedCount = photos.filter((photo) => photo.editedAt).length;
return (
<div className="space-y-6">
@@ -99,6 +135,9 @@ export default async function EventDetailPage({
</h1>
<Badge variant="outline">{event.event.eventType}</Badge>
<div className="ml-auto flex flex-wrap items-center justify-end gap-2">
{bridgeConfigured() && (
<AdvancedEditorButton eventId={event.event.id} />
)}
{event.event.photoCount > 0 && (
<Button asChild variant="outline" size="sm">
<a href={`/api/events/${event.event.id}/download`}>
@@ -107,6 +146,17 @@ export default async function EventDetailPage({
</a>
</Button>
)}
{editedCount > 0 && (
<Button asChild variant="outline" size="sm">
<a
href={`/api/events/${event.event.id}/download?edited=1`}
title="Download only the photos with a saved edit, as full-resolution JPEGs"
>
<Download className="h-3.5 w-3.5" aria-hidden="true" />
Download edited ({editedCount})
</a>
</Button>
)}
{event.canManage && archiveStatus.ok && (
<ArchiveEventButton
eventId={event.event.id}
@@ -175,50 +225,26 @@ export default async function EventDetailPage({
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<FolderOpen className="h-4 w-4" aria-hidden="true" />
Folders
<ImageIcon className="h-4 w-4" aria-hidden="true" />
Photos
{photos.length > 0 && (
<span className="text-sm font-normal text-muted-foreground">
{photos.length}
{editedCount > 0 ? ` · ${editedCount} edited` : ""}
</span>
)}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{event.folders.length === 0 ? (
<p className="text-sm text-muted-foreground">
No folders yet. Create one for originals, dumps, or edited selects.
</p>
) : (
<ul className="grid gap-3 sm:grid-cols-2">
{event.folders.map((folder) => (
<li key={folder.id}>
<Link
href={`/events/${event.event.id}/folders/${folder.id}`}
className="block rounded-md border border-border p-3 transition-colors hover:border-primary/60 hover:bg-muted/30"
>
<div className="flex items-start justify-between gap-2">
<p className="truncate text-sm font-medium">
{folder.name}
</p>
<Badge variant="secondary">
{KIND_LABELS[folder.kind] ?? folder.kind}
</Badge>
</div>
<p className="mt-1 text-xs text-muted-foreground">
{folder.photoCount} photo
{folder.photoCount === 1 ? "" : "s"} ·{" "}
{sizeLabel(folder.totalBytes)}
</p>
</Link>
</li>
))}
</ul>
)}
{event.canContribute ? (
<FolderCreateForm eventId={event.event.id} />
) : (
<p className="text-xs text-muted-foreground">
Only assigned photographers, coordinators and admins can add
folders or upload.
</p>
)}
<CardContent>
<PhotoGallery
eventId={event.event.id}
photos={photos}
canContribute={event.canContribute}
canManage={event.canManage}
currentUserId={user.id}
storageReady={archiveStatus.ok}
storageMessage={archiveStatus.ok ? "" : archiveStatus.message}
/>
</CardContent>
</Card>
+4 -4
View File
@@ -235,8 +235,8 @@ export default async function MediaPage() {
Photos
</h2>
<p className="text-xs text-muted-foreground">
Every photo in the event folders you can open. Download originals
from the event folder.
Every photo in the events you can open. Download originals from
the event page.
</p>
</div>
<span className="text-xs text-muted-foreground">
@@ -264,7 +264,7 @@ export default async function MediaPage() {
return (
<Link
key={photo.id}
href={`/events/${photo.eventId}/folders/${photo.folderId}`}
href={`/events/${photo.eventId}`}
className="group overflow-hidden rounded-md border border-border bg-background transition-colors hover:border-primary/60"
>
<div className="flex aspect-square items-center justify-center bg-muted/40">
@@ -292,7 +292,7 @@ export default async function MediaPage() {
{photo.filename}
</p>
<p className="truncate text-[11px] text-muted-foreground">
{photo.eventTitle} · {photo.folderName}
{photo.eventTitle}
</p>
<p className="text-[10px] text-muted-foreground">
{bytesLabel(photo.sizeBytes)}
+32 -11
View File
@@ -109,10 +109,13 @@ export default function AdminGuidePage() {
/>
<GuideCallout title="Draft versus published" tone="note">
<p>
New service instances start as drafts. Volunteers only see the
week, and only receive assignment email, after you publish it. A
draft is safe to edit; a published week should be changed carefully
because people have already been told about it.
New service instances start as drafts, and volunteers do not see a
draft on their schedule. Assigning a seat still sends the proposed
email immediately so the volunteer can accept, decline, or propose
another Sunday. Publishing makes the week visible and queues the
published/reminder mail for every live assignment. A draft is safe
to edit; a published week should be changed carefully because people
have already been told about it.
</p>
</GuideCallout>
</GuideSection>
@@ -374,7 +377,9 @@ export default function AdminGuidePage() {
</GuideStep>
<GuideStep>
Press <strong>Publish</strong> when the week is ready. Publishing
queues assignment email and reminder rules for that instance.
makes the week visible and queues the published/reminder mail for
live assignments. Assignments made later still send their proposed
email immediately.
</GuideStep>
<GuideStep>
Unpublish only when you intend to withdraw the week; volunteers may
@@ -443,6 +448,20 @@ export default function AdminGuidePage() {
</p>
</GuideCallout>
<h3 className="pt-2 text-base font-semibold">
Volunteers who propose another Sunday
</h3>
<p className="text-sm leading-6">
The proposed email also offers <strong>Propose another Sunday</strong>.
That link records a pending proposal for a coordinator but leaves the
original assignment live, so the seat remains covered while you
decide. Pending proposals appear on <strong>Coverage</strong> under{" "}
<strong>Proposed another Sunday</strong>. This queue is read-only for
now: review the date and note, then change the schedule yourself
(assign a replacement or clear the seat) and confirm the change with
the volunteer.
</p>
<h3 className="pt-2 text-base font-semibold">Requests from outside the team</h3>
<p className="text-sm leading-6">
Ministry leaders can submit the public form at{" "}
@@ -450,7 +469,7 @@ export default function AdminGuidePage() {
rate-limited and appear under Coverage as new requests. Read the brief,
then either <strong>Create event</strong> (which opens an event with
the requester and ministry attached) or <strong>Decline</strong>. The
event is where you assign photographers and folders.
event page is where you assign photographers and upload photos.
</p>
</GuideSection>
@@ -704,12 +723,14 @@ export default function AdminGuidePage() {
admins can remove them.
</GuideStep>
</GuideSteps>
<GuideCallout title="The two long guides are built in" tone="tip">
<GuideCallout title="Role guides are built in" tone="tip">
<p>
The Platform administration guide and the Volunteer guide appear at
the top of Training as web pages with screenshots and as downloadable
PDFs. They are documentation for this deployment, not editable
lessons, so they stay consistent for every admin.
Training shows the guide for the signed-in role: the Platform
administration guide for admins, the Coordinator guide for
coordinators, and the Volunteer guide for volunteers and trainees.
The admin and volunteer guides also have downloadable PDFs. These
are documentation for this deployment, not editable lessons, so they
stay consistent for everyone.
</p>
</GuideCallout>
</GuideSection>
@@ -0,0 +1,393 @@
import type { Metadata } from "next";
import {
GuideCallout,
GuideFields,
GuideFigure,
GuideSection,
GuideShell,
GuideStep,
GuideSteps,
} from "@/components/app/training/guide";
export const metadata: Metadata = {
title: "Coordinator guide",
};
const SECTIONS = [
{ id: "role", title: "Your coordinator role" },
{ id: "week", title: "Build and publish a week" },
{ id: "replies", title: "Assignment emails and replies" },
{ id: "coverage", title: "Coverage and swaps" },
{ id: "run-sheets", title: "Run sheets" },
{ id: "events", title: "Events and media" },
{ id: "announcements", title: "Announcements and training" },
{ id: "exports", title: "Print and CSV exports" },
{ id: "troubleshooting", title: "Troubleshooting" },
];
export default function CoordinatorGuidePage() {
return (
<GuideShell
title="Coordinator guide"
audience="Coordinators"
intro="The working guide for coordinating the media team: building and publishing the schedule, responding to assignment replies, resolving coverage, preparing run sheets, keeping events moving, and getting the week onto paper or into a spreadsheet."
pdfHref="/training/media-team-coordinator-guide.pdf"
pdfLabel="Download coordinator PDF"
sections={SECTIONS}
>
<GuideSection id="role" title="1. Your coordinator role">
<p className="text-sm leading-6">
Coordinators run the week. You can edit and publish the schedule,
handle coverage and swaps, edit run sheets, manage events, author
announcements, and use the print and CSV exports. You do not need the
Admin tab for any of that.
</p>
<GuideFields
rows={[
{
label: "You can",
value:
"Dashboard, Coverage, schedule assignment and publishing, auto-fill, run sheets, events and media, announcements, training viewing, print, and schedule/history CSV downloads.",
},
{
label: "Admins handle",
value:
"People and access, skill verification, positions and requirements, service templates, email credentials, reminder rules, backups, and training authoring. Ask an admin when one of those needs to change.",
},
{
label: "Everyone serves",
value:
"Coordinators can hold a seat too. Your own assignment, availability, profile, and notification settings work exactly like a volunteer’s.",
},
]}
/>
<GuideFigure
src="/training/screens/admin-dashboard.png"
alt="Coverage dashboard with filled and open seats and the next service summary"
caption="Open Dashboard before planning a week: it shows open seats and unconfirmed assignments at a glance."
/>
</GuideSection>
<GuideSection id="week" title="2. Build and publish a week">
<p className="text-sm leading-6">
The week view is the only editable schedule lens. Month and year are
read-only overviews. A week starts as a draft; publishing makes it
visible to volunteers and starts the published/reminder mail.
</p>
<GuideFigure
src="/training/screens/admin-schedule.png"
alt="Week schedule grid with position columns and assignment controls"
caption="Each column is a position and each row is a service. Press an empty seat to assign someone."
/>
<GuideSteps>
<GuideStep>
Open <strong>Schedule</strong> and use the arrows to reach the week
you are building.
</GuideStep>
<GuideStep>
Press an empty seat and choose a volunteer. The candidate list is
ranked by skills, availability, and conflicts.
</GuideStep>
<GuideStep>
Use <strong>Auto-fill</strong> for a first pass over open seats, then
review every suggestion. The ranking does not know the relational
context or the last-minute holiday.
</GuideStep>
<GuideStep>
Read any conflict before saving. A hard conflict blocks the
assignment; a soft warning, such as exceeding a monthly cap, can be
overridden.
</GuideStep>
<GuideStep>
Press <strong>Publish</strong> when the week is ready. Publishing
makes the schedule visible and queues the published/reminder mail for
the people already on it.
</GuideStep>
</GuideSteps>
<GuideCallout title="Assigning sends mail before publish" tone="note">
<p>
A proposed assignment sends its “Can you serve on …?” email as soon
as you create it, even while the week is still a draft. Publishing
does not send that email again; it adds the published/reminder mail
for seats that are already filled. Draft weeks stay hidden from the
volunteer schedule until you publish.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="replies" title="3. Assignment emails and replies">
<p className="text-sm leading-6">
Every proposed seat gets an email with three single-use links. The
volunteer does not need an account or a login to use them.
</p>
<GuideFields
rows={[
{
label: "Confirm",
value:
"The volunteer accepts the seat. The assignment moves to confirmed and the schedule shows it immediately.",
},
{
label: "Can’t make it",
value:
"The volunteer declines. The seat needs a replacement; use the schedule or Coverage to fill it.",
},
{
label: "Propose another Sunday",
value:
"Records a pending request for a different date. It does not release the original seat or change the assignment by itself.",
},
]}
/>
<p className="text-sm leading-6">
Links are good for 14 days and work once. If a volunteer says the link
expired or was already used, do not forward someone else’s link; ask an
admin to help with the account or create the assignment again.
</p>
<GuideCallout title="What the volunteer sees" tone="tip">
<p>
The subject reads “Can you serve on [position] — [date]?” and the
body shows the service, call time, and location, followed by the
three buttons. The same reply buttons also appear on the{" "}
<code>/respond</code> page the link opens.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="coverage" title="4. Coverage and swaps">
<p className="text-sm leading-6">
Coverage is the working queue for changes. A pending request never
removes the volunteer: they stay responsible until you approve a
replacement or release the seat.
</p>
<GuideFigure
src="/training/screens/admin-coverage.png"
alt="Coverage page with pending swap requests and ranked replacements"
caption="Approve with a replacement, approve and release the seat, or decline and leave the volunteer in place."
/>
<h3 className="pt-2 text-base font-semibold">Handle a swap request</h3>
<GuideSteps>
<GuideStep>
Open <strong>Coverage</strong> and read the volunteer, seat, date,
and reason.
</GuideStep>
<GuideStep>
Review the ranked replacements and their warnings. Pick someone who
fits the skills and availability, not just the top score.
</GuideStep>
<GuideStep>
Choose <strong>Approve with replacement</strong> to cancel the
original assignment and place the replacement as proposed. The new
person receives the same accept/decline/propose email.
</GuideStep>
<GuideStep>
Choose <strong>Approve and release</strong> when nobody can take it.
The seat becomes open and the original assignment is kept in history.
</GuideStep>
<GuideStep>
Choose <strong>Decline</strong> when the request should not be
granted; the original volunteer stays on the seat.
</GuideStep>
</GuideSteps>
<h3 className="pt-2 text-base font-semibold">
Volunteers who propose another Sunday
</h3>
<p className="text-sm leading-6">
Proposals from the assignment email appear on Coverage under{" "}
<strong>Proposed another Sunday</strong>. The queue is read-only: it
records the volunteer, the current date, the proposed date, and any
note. Review it, then make the change yourself — assign a replacement,
move the seat, or clear it — and confirm the arrangement with the
volunteer. The original assignment stays live until you do.
</p>
<h3 className="pt-2 text-base font-semibold">
Requests from outside the team
</h3>
<p className="text-sm leading-6">
Ministry leaders can submit the public form at{" "}
<code>/request-coverage</code> without an account. Accepted requests
become events: choose <strong>Create event</strong> to open one with
the requester and ministry attached, or <strong>Decline</strong> if it
is not a fit.
</p>
</GuideSection>
<GuideSection id="run-sheets" title="5. Run sheets">
<p className="text-sm leading-6">
Every service instance has one run sheet: speaker, message title,
stream and slides links, team notes, an ordered cue list, and a
pre/post checklist. Coordinators edit the details and cues; every
signed-in volunteer can tick checklist items.
</p>
<GuideFigure
src="/training/screens/admin-run-sheet.png"
alt="Run sheet editor with service details, cue list, and checklist"
caption="Prepare the sheet before the weekend, then let the team tick items as the service runs."
/>
<GuideSteps>
<GuideStep>
Open the run sheet from the schedule, Dashboard, or your own
next-serve card.
</GuideStep>
<GuideStep>
Fill in speaker, message title, stream link, slides link, and team
notes, then press <strong>Save details</strong>.
</GuideStep>
<GuideStep>
Edit cues inline and save each row. Add a cue at the bottom when the
service needs one.
</GuideStep>
<GuideStep>
Add pre-service or post-service checklist items for this service.
Defaults are seeded only once, so your edits stick.
</GuideStep>
<GuideStep>
Press <strong>Print</strong> for a clean booth copy.
</GuideStep>
</GuideSteps>
</GuideSection>
<GuideSection id="events" title="6. Events and media">
<p className="text-sm leading-6">
Events cover photoshoots, weddings, outreach nights, and other
coverage outside the weekly services. As a coordinator you see every
event and can assign photographers and editors; assigned volunteers see
only their events.
</p>
<GuideFigure
src="/training/screens/user-events.png"
alt="Events list with upcoming event cards and assignment counts"
caption="Open an event to see its brief, team, folders, and files."
/>
<GuideSteps>
<GuideStep>
Create the event with its date, time, location, and brief, or create
one from an accepted outside coverage request.
</GuideStep>
<GuideStep>
Assign the photographers and editors. Only assigned people and
managers can open the event and its files.
</GuideStep>
<GuideStep>
Create folders for originals and edited exports so the handoff is
obvious.
</GuideStep>
<GuideStep>
After the event, confirm the selects are uploaded and the folder is
ready. Archive the event when the work is finished; archived events
stay readable but stop accepting uploads.
</GuideStep>
</GuideSteps>
<GuideCallout title="Original files live on the media share" tone="note">
<p>
Event originals are stored on the configured church media share, not
in the database. The Media page is a convenience view and still
follows event assignment, so do not treat a copied link as public.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="announcements" title="7. Announcements and training">
<p className="text-sm leading-6">
Coordinators can write announcements. Training lessons are authored by
admins, but everyone can read the published lessons and the guide for
their role.
</p>
<GuideSteps>
<GuideStep>
Open <strong>Announcements</strong> and write a title and plain-text
message.
</GuideStep>
<GuideStep>
Keep <strong>Published</strong> ticked, or untick it to save a draft.
</GuideStep>
<GuideStep>
Use the row actions to publish, unpublish, or delete a post.
</GuideStep>
<GuideStep>
Open <strong>Training</strong> to read the coordinator guide and the
published lessons. If a lesson needs a correction, ask an admin.
</GuideStep>
</GuideSteps>
<GuideCallout title="Your guide is selected automatically" tone="tip">
<p>
Training shows the guide for your role. Admins see the Platform
administration guide, coordinators see this guide, and volunteers and
trainees see the Volunteer guide.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="exports" title="8. Print and CSV exports">
<GuideFields
rows={[
{
label: "Printable roster",
value:
"Open /schedule/print from Dashboard or Coverage. It prints the current week by service with call times and confirmation state, without the app navigation.",
},
{
label: "Schedule CSV",
value:
"GET /api/export/schedule downloads assignments for a date range (four weeks by default).",
},
{
label: "Serving history CSV",
value:
"GET /api/export/history downloads completed and no-show assignments for reviews and fairness checks.",
},
]}
/>
<GuideFigure
src="/training/screens/admin-print.png"
alt="Printable weekly roster with services, roles, and call times"
caption="The print view is deliberately plain: no navigation, no controls, just the roster."
/>
</GuideSection>
<GuideSection id="troubleshooting" title="9. Troubleshooting">
<GuideFields
rows={[
{
label: "A volunteer did not get the assignment email",
value:
"Ask them to check spam and confirm the address on their profile. Ask an admin to check the notification log; failed messages show the provider error and can be retried after the cause is fixed.",
},
{
label: "A confirmation link does not work",
value:
"The links are single-use and expire after 14 days. Do not forward another person’s link; ask an admin for help with the account, or recreate the assignment.",
},
{
label: "A seat will not accept an assignment",
value:
"Read the conflict. A blackout, duplicate service assignment, or missing core skill is a hard block. A monthly cap is a soft warning you may override.",
},
{
label: "A volunteer cannot see the week",
value:
"Confirm the instance is published. Draft weeks are hidden from the volunteer schedule, even though the proposed email may already have gone out.",
},
{
label: "A proposed Sunday is not on the schedule",
value:
"The proposal queue is read-only. Review it on Coverage, then change the schedule yourself and confirm the new arrangement with the volunteer.",
},
{
label: "A coverage request disappeared",
value:
"Check whether the seat was cleared directly from the schedule. Approval keeps the cancelled assignment in history; a direct clear removes it.",
},
]}
/>
<p className="text-sm leading-6">
When something looks wrong, note the date and service, take a
screenshot, and include the exact error text. That is far more useful
than “it didn’t work”.
</p>
</GuideSection>
</GuideShell>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { redirect } from "next/navigation";
import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles";
import { trainingGuideForRole } from "@/lib/training-guides";
/** `/training/guides` opens the guide for the signed-in person's role. */
export default async function TrainingGuidesPage() {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)
?.systemRole;
redirect(trainingGuideForRole(role).href);
}
+28 -9
View File
@@ -128,6 +128,15 @@ export default function VolunteerGuidePage() {
the top for the two things volunteers change most often.
</GuideStep>
</GuideSteps>
<GuideCallout title="Replying from email" tone="tip">
<p>
A proposed seat arrives by email with three links:{" "}
<strong>Confirm</strong>, <strong>Can’t make it</strong>, and{" "}
<strong>Propose another Sunday</strong>. No login is needed and each
link works once. If you propose another Sunday, the coordinator sees
the request but the seat stays yours until they change it.
</p>
</GuideCallout>
<GuideFigure
src="/training/screens/user-home-mobile.png"
alt="Home page at phone width with the scrollable tab bar"
@@ -171,9 +180,11 @@ export default function VolunteerGuidePage() {
/>
<GuideCallout title="Draft weeks are invisible" tone="note">
<p>
A week that has not been published does not appear on your schedule
and does not generate assignment email. If you expected a date and
cannot see it, the week is probably still a draft.
A week that has not been published does not appear on your schedule.
Assigning a seat can still send you a proposed email while the week
is a draft, so reply to that email even if the date is not on the
schedule yet. Publishing is what makes the week visible and triggers
the published and reminder mail.
</p>
</GuideCallout>
</GuideSection>
@@ -258,6 +269,14 @@ export default function VolunteerGuidePage() {
You will see the change on Home once it is resolved.
</p>
</GuideCallout>
<h3 className="pt-2 text-base font-semibold">Propose another Sunday</h3>
<p className="text-sm leading-6">
If you cannot serve the date but could serve a different Sunday, use{" "}
<strong>Propose another Sunday</strong> in the assignment email (or the
alternative link on the respond page). Tell the coordinator which date
works and why. This does not release the original seat: it stays yours
until a coordinator acts on the proposal and confirms the change.
</p>
<p className="text-sm leading-6">
Ministry leaders outside the team can request coverage through the
public form at <code>/request-coverage</code>. If you are asked to
@@ -395,24 +414,24 @@ export default function VolunteerGuidePage() {
</p>
<GuideFigure
src="/training/screens/user-training.png"
alt="Training page with the two full guides at the top and published lessons below"
caption="Start with the two full guides, then use the shorter lessons for specific skills."
alt="Training page with the guide for your role at the top and published lessons below"
caption="The guide for your role is at the top; use the shorter lessons for specific skills."
/>
<GuideSteps>
<GuideStep>
Open <strong>Training</strong> from the navigation.
</GuideStep>
<GuideStep>
Read the <strong>Volunteer guide</strong> once end to end; it covers
every screen in this app.
Read the guide at the top of the page once end to end; it is chosen
for your role and covers every screen you can use.
</GuideStep>
<GuideStep>
Open an attachment to read or download it. Links open in a new tab so
you do not lose your place.
</GuideStep>
<GuideStep>
Use the PDF download on either guide for an offline copy you can keep
on your phone.
Use the PDF download when the guide offers one, or print the page for
an offline copy you can keep on your phone.
</GuideStep>
</GuideSteps>
<GuideCallout title="Read the run sheet lesson before your first serve" tone="tip">
+39 -53
View File
@@ -4,20 +4,36 @@ import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listLessons } from "@/db/training";
import { trainingBodyToHtml } from "@/lib/rich-text";
import { trainingGuideForRole } from "@/lib/training-guides";
import { TrainingPanel } from "@/components/app/training-panel";
import { BookOpenCheck, Download, ShieldCheck, UserRound } from "lucide-react";
import {
BookOpenCheck,
ClipboardList,
Download,
ShieldCheck,
UserRound,
} from "lucide-react";
export const metadata = { title: "Training" };
/**
* Training content. Volunteers see published lessons and attachments; admins
* can author, publish, upload, and delete. Content is stored in Postgres and
* can author, publish, upload, and delete. The full guide shown at the top is
* chosen from the signed-in person's role. Content is stored in Postgres and
* attachments under the uploads volume, so it is editable with no deploy.
*/
export default async function TrainingPage() {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole;
const role = (session?.user as { systemRole?: SystemRole } | undefined)
?.systemRole;
const canEdit = hasPermission(role, "training.author");
const guide = trainingGuideForRole(role);
const GuideIcon =
guide.key === "admin"
? ShieldCheck
: guide.key === "coordinator"
? ClipboardList
: UserRound;
const lessons = (await listLessons({ includeUnpublished: canEdit })).map(
(lesson) => ({
...lesson,
@@ -36,67 +52,37 @@ export default async function TrainingPage() {
<section aria-labelledby="full-guides" className="space-y-3">
<div>
<h2 id="full-guides" className="text-base font-semibold tracking-tight">
Full guides
Your guide
</h2>
<p className="text-sm text-muted-foreground">
Complete, illustrated walkthroughs with screenshots. Read them here
or download the PDF for printing and offline use.
The complete, illustrated walkthrough for your role. Read it here or
download the PDF where one is available.
</p>
</div>
<div className="grid gap-3 md:grid-cols-2">
<div className="flex flex-col rounded-md border border-border p-4">
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
<ShieldCheck className="h-4 w-4" aria-hidden="true" />
Admins
</div>
<h3 className="mt-2 text-base font-semibold">
Platform administration guide
</h3>
<p className="mt-1 flex-1 text-sm leading-6 text-muted-foreground">
People and access, skill verification, positions, services and
publishing, coverage, run sheets, email, notifications, backups,
and exports.
</p>
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
<Link href="/training/guides/admin" className="text-primary underline">
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
Read the guide
</Link>
<a
href="/training/media-team-admin-guide.pdf"
download
className="inline-flex items-center gap-1 text-primary underline"
>
<Download className="h-4 w-4" aria-hidden="true" />
Download PDF
</a>
</div>
<div className="rounded-md border border-border p-4">
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
<GuideIcon className="h-4 w-4" aria-hidden="true" />
{guide.audience}
</div>
<div className="flex flex-col rounded-md border border-border p-4">
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
<UserRound className="h-4 w-4" aria-hidden="true" />
Volunteers &amp; trainees
</div>
<h3 className="mt-2 text-base font-semibold">Volunteer guide</h3>
<p className="mt-1 flex-1 text-sm leading-6 text-muted-foreground">
Signing in, your next serve, the schedule, availability, swaps,
run sheets, events and media, training, profile, and reminders.
</p>
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
<Link href="/training/guides/user" className="text-primary underline">
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
Read the guide
</Link>
<h3 className="mt-2 text-base font-semibold">{guide.title}</h3>
<p className="mt-1 text-sm leading-6 text-muted-foreground">
{guide.description}
</p>
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
<Link href={guide.href} className="text-primary underline">
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
Read your guide
</Link>
{guide.pdfHref && guide.pdfLabel ? (
<a
href="/training/media-team-user-guide.pdf"
href={guide.pdfHref}
download
className="inline-flex items-center gap-1 text-primary underline"
>
<Download className="h-4 w-4" aria-hidden="true" />
Download PDF
{guide.pdfLabel}
</a>
</div>
) : null}
</div>
</div>
</section>
@@ -8,11 +8,13 @@ const bodySchema = z.object({ action: z.enum(["confirm", "decline"]) });
function errorStatus(code: RespondError["code"]): number {
switch (code) {
case "unknown_assignment":
case "unknown_instance":
return 404;
case "wrong_volunteer":
return 403;
case "not_actionable":
case "already_used":
case "invalid_alternative":
return 409;
}
}
+13 -8
View File
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
import { z } from "zod";
import { and, eq, inArray } from "drizzle-orm";
import { auth } from "@/auth/config";
import { requestOrigin } from "@/auth/magic-link";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { db } from "@/db";
@@ -16,8 +17,10 @@ import {
AssignFactError,
resolveAssignFacts,
} from "@/db/assignments";
import { cancelAssignmentNotifications } from "@/db/outbox";
import { enqueuePublishNotifications } from "@/db/outbox";
import {
cancelAssignmentNotifications,
enqueueAssignmentProposed,
} from "@/db/outbox";
import { enqueueRemindersForInstance } from "@/db/reminders";
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
import { uuidv7 } from "@/lib/uuid";
@@ -195,6 +198,8 @@ export const POST = async (req: NextRequest) => {
.limit(1);
const assignmentId = uuidv7();
const now = new Date();
const appOrigin = requestOrigin(req);
await db.transaction(async (tx) => {
await tx.insert(assignments).values({
id: assignmentId,
@@ -203,7 +208,7 @@ export const POST = async (req: NextRequest) => {
status: "proposed",
source: "manual",
assignedBy: actorId,
assignedAt: new Date(),
assignedAt: now,
});
await tx
.update(slots)
@@ -224,12 +229,12 @@ export const POST = async (req: NextRequest) => {
}),
);
// A published week's mail is written at publish time; a seat added later
// would otherwise never be announced. Both enqueues are idempotent on
// dedupe_key, so existing rows are untouched.
// The proposed email always goes out, whether the week is draft or
// published: the volunteer has to accept, decline, or propose another
// Sunday. On a published week only the reminders need topping up.
await enqueueAssignmentProposed(tx, assignmentId, { now, appOrigin });
if (instance?.status === "published") {
await enqueuePublishNotifications(tx, instance.id, { now: new Date() });
await enqueueRemindersForInstance(tx, instance.id, { now: new Date() });
await enqueueRemindersForInstance(tx, instance.id, { now, appOrigin });
}
});
@@ -0,0 +1,45 @@
import { NextRequest } from "next/server";
import { authenticateBridge } from "@/db/bridge";
import {
BRIDGE_SESSION_TTL_SECONDS,
bridgeReturnUrl,
signBridgeToken,
} from "@/lib/bridge";
import { errorResponse, jsonResponse } from "@/lib/http";
/**
* POST /api/bridge/sessions/:sessionId/exchange
*
* The login token is deliberately short-lived because it travels in a URL.
* The editor exchanges it once for a service token it keeps server-side; that
* token authorizes the photo proxy and the save-back calls.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> },
) => {
const { sessionId } = await params;
const auth = await authenticateBridge(req, sessionId, "login");
if (!auth) return errorResponse(401, "invalid or expired bridge token");
const token = signBridgeToken({
sid: auth.session.id,
eid: auth.session.eventId,
uid: auth.user.id,
email: auth.user.email,
name: auth.user.name,
kind: "service",
exp: Math.floor(Date.now() / 1000) + BRIDGE_SESSION_TTL_SECONDS,
});
return jsonResponse({
token,
sessionId: auth.session.id,
eventId: auth.session.eventId,
expiresAt: auth.session.expiresAt,
// Carried from the browser-facing request that opened the editor so the
// editor can link back to the address the user actually reached.
returnUrl:
auth.payload.ret ?? bridgeReturnUrl(auth.session.eventId) ?? null,
});
};
@@ -0,0 +1,142 @@
import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto";
import { mkdir, rename, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { authenticateBridge, getBridgePhoto, saveBridgeRender } from "@/db/bridge";
import {
advancedStoredNameForEventPhoto,
editedStoredNameForEventPhoto,
eventPhotoPath,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import {
defaultPhotoAdjustments,
parseStoredPhotoAdjustments,
} from "@/lib/photo-adjustments";
import { renderPhotoJpeg } from "@/lib/photo-render";
const MAX_BODY_BYTES = 64 * 1024 * 1024;
const MAX_RECIPE_BYTES = 512 * 1024;
const MAX_JPEG_BYTES = 48 * 1024 * 1024;
/**
* POST /api/bridge/sessions/:sessionId/photos/:photoId/render
* Body: { jpeg: <base64>, edits: <advanced recipe>, width, height }
*
* The advanced editor renders in the browser, so the server only has to store
* the result. The JPEG is kept as the photo's advanced render (its own file, so
* the simple editor can layer on top) and the recipe is kept so the editor can
* be reopened with its sliders intact. Any simple-editor layer is rebuilt on
* top of the new render, so the two editors never disagree.
*/
export const POST = async (
req: NextRequest,
{
params,
}: {
params: Promise<{ sessionId: string; photoId: string }>;
},
) => {
const { sessionId, photoId } = await params;
const auth = await authenticateBridge(req, sessionId);
if (!auth) return errorResponse(401, "invalid or expired bridge session");
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) {
return errorResponse(413, "the rendered image is too large");
}
const photo = await getBridgePhoto(auth.session.eventId, photoId);
if (!photo) return errorResponse(404, "unknown photo");
const body = (await req.json().catch(() => null)) as
| { jpeg?: unknown; edits?: unknown }
| null;
if (!body || typeof body.jpeg !== "string") {
return errorResponse(400, "a base64 JPEG is required");
}
let data: Buffer;
try {
data = Buffer.from(body.jpeg, "base64");
} catch {
return errorResponse(400, "the image could not be decoded");
}
if (data.byteLength < 4 || data[0] !== 0xff || data[1] !== 0xd8) {
return errorResponse(400, "the image is not a JPEG");
}
if (data.byteLength > MAX_JPEG_BYTES) {
return errorResponse(413, "the rendered image is too large");
}
const recipe = JSON.stringify(body.edits ?? {});
if (recipe.length > MAX_RECIPE_BYTES) {
return errorResponse(413, "the edit recipe is too large");
}
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const advancedStoredName = advancedStoredNameForEventPhoto(
auth.session.eventId,
photo.id,
);
const target = eventPhotoPath(storage.root, advancedStoredName);
const temporary = `${target}.${randomUUID()}.tmp`;
try {
await mkdir(path.dirname(target), { recursive: true });
await writeFile(temporary, data);
await rename(temporary, target);
} catch {
await unlink(temporary).catch(() => undefined);
return errorResponse(500, "the edited image could not be saved");
}
// A photo the simple editor also adjusted keeps that layer: re-render it on
// the new advanced render so the saved JPEG still shows both recipes.
const quick = parseStoredPhotoAdjustments(photo.editJson);
const hasQuickLayer =
JSON.stringify(quick) !== JSON.stringify(defaultPhotoAdjustments());
let editedStoredName = advancedStoredName;
let editedSizeBytes = data.byteLength;
if (hasQuickLayer) {
editedStoredName = editedStoredNameForEventPhoto(auth.session.eventId, photo.id);
const layered = eventPhotoPath(storage.root, editedStoredName);
try {
const rendered = await renderPhotoJpeg({
filePath: target,
kind: "image",
adjustments: quick,
});
await mkdir(path.dirname(layered), { recursive: true });
const layeredTemporary = `${layered}.${randomUUID()}.tmp`;
await writeFile(layeredTemporary, rendered.data);
await rename(layeredTemporary, layered);
editedSizeBytes = rendered.data.byteLength;
} catch (error) {
console.error("simple edit layer rebuild failed", error);
return errorResponse(
500,
"the simple editor's adjustments could not be rebuilt on the new render",
);
}
}
const editedAt = await saveBridgeRender({
photoId: photo.id,
editedStoredName,
editedSizeBytes,
advancedEditJson: recipe,
editedBy: auth.user.id,
});
if (!editedAt) {
await unlink(target).catch(() => undefined);
return errorResponse(404, "unknown photo");
}
return jsonResponse({
ok: true,
editedAt,
editedSizeBytes,
});
};
@@ -0,0 +1,184 @@
import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
import { authenticateBridge, getBridgePhoto } from "@/db/bridge";
import {
bridgeEditedThumbStoredNameForEventPhoto,
bridgeProxyStoredNameForEventPhoto,
bridgeThumbStoredNameForEventPhoto,
eventPhotoPath,
} from "@/lib/event-photos";
import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
import { renderPhotoJpeg, renderPhotoThumbnail } from "@/lib/photo-render";
const PROXY_MAX_EDGE = 4000;
const THUMB_MAX_EDGE = 480;
function imageResponse(data: Buffer, contentType = "image/jpeg"): Response {
return new Response(new Uint8Array(data), {
status: 200,
headers: {
"content-type": contentType,
"content-length": String(data.byteLength),
"cache-control": "private, max-age=3600",
"x-content-type-options": "nosniff",
},
});
}
/**
* Reads a cached derivative or writes it atomically on first use. When
* `newerThan` is given, a cache older than that timestamp is rebuilt, so a
* thumbnail of a re-rendered edit never goes stale.
*/
async function cached(
filePath: string,
produce: () => Promise<Buffer>,
newerThan?: number,
): Promise<Buffer> {
try {
const info = await stat(filePath);
if (
info.isFile() &&
info.size > 0 &&
(newerThan === undefined || info.mtimeMs >= newerThan)
) {
return readFile(filePath);
}
} catch {
// Not generated yet.
}
const data = await produce();
await mkdir(path.dirname(filePath), { recursive: true });
const temporary = `${filePath}.${randomUUID()}.tmp`;
await writeFile(temporary, data);
await rename(temporary, filePath);
return data;
}
async function thumbFor(filePath: string, kind: "raw" | "image") {
return renderPhotoThumbnail({
filePath,
kind,
maxDimension: THUMB_MAX_EDGE,
quality: 82,
});
}
/**
* GET /api/bridge/sessions/:sessionId/photos/:photoId/source?variant=original|proxy|thumb
*
* `original` streams the untouched bytes (the editor decodes RAW itself);
* `proxy` is a 4000 px JPEG, used when the editor only needs a browser image;
* `thumb` is a small grid preview. Derivatives are cached beside the original
* so repeated opens are free.
*/
export const GET = async (
req: NextRequest,
{
params,
}: {
params: Promise<{ sessionId: string; photoId: string }>;
},
) => {
const { sessionId, photoId } = await params;
const auth = await authenticateBridge(req, sessionId);
if (!auth) return errorResponse(401, "invalid or expired bridge session");
const photo = await getBridgePhoto(auth.session.eventId, photoId);
if (!photo) return errorResponse(404, "unknown photo");
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const originalPath = eventPhotoPath(storage.root, photo.storedName);
const variant = req.nextUrl.searchParams.get("variant") ?? "original";
if (variant === "original") {
let size: number;
try {
const info = await stat(originalPath);
if (!info.isFile()) throw new Error("missing");
size = info.size;
} catch {
return errorResponse(404, "the file is missing from storage");
}
const stream = createReadStream(originalPath);
return new Response(
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
{
status: 200,
headers: {
"content-type": photo.mimeType || "application/octet-stream",
"content-length": String(size),
"content-disposition": "inline",
"cache-control": "private, max-age=3600",
"x-content-type-options": "nosniff",
},
},
);
}
if (variant === "thumb") {
// With a saved edit, the grid should show the photo as it was developed —
// the editor's own look — not the untouched original.
let sourcePath = originalPath;
let sourceKind: "raw" | "image" = photo.kind;
let thumbName = bridgeThumbStoredNameForEventPhoto(
auth.session.eventId,
photo.id,
);
let editedMtime: number | undefined;
if (photo.editedStoredName) {
const editedPath = eventPhotoPath(storage.root, photo.editedStoredName);
const edited = await stat(editedPath).catch(() => null);
if (edited?.isFile()) {
sourcePath = editedPath;
sourceKind = "image";
editedMtime = edited.mtimeMs;
thumbName = bridgeEditedThumbStoredNameForEventPhoto(
auth.session.eventId,
photo.id,
);
}
}
try {
const data = await cached(
eventPhotoPath(storage.root, thumbName),
() => thumbFor(sourcePath, sourceKind),
editedMtime,
);
return imageResponse(data);
} catch {
return errorResponse(422, "the thumbnail could not be generated");
}
}
if (variant === "proxy") {
try {
const proxyPath = eventPhotoPath(
storage.root,
bridgeProxyStoredNameForEventPhoto(auth.session.eventId, photo.id),
);
const data = await cached(proxyPath, async () => {
const rendered = await renderPhotoJpeg({
filePath: originalPath,
kind: photo.kind,
adjustments: defaultPhotoAdjustments(),
maxDimension: PROXY_MAX_EDGE,
});
return rendered.data;
});
return imageResponse(data);
} catch {
return errorResponse(422, "the editable preview could not be generated");
}
}
return errorResponse(400, "unknown source variant");
};
@@ -0,0 +1,100 @@
import { NextRequest } from "next/server";
import {
authenticateBridge,
getBridgeEventSummary,
listBridgePhotos,
} from "@/db/bridge";
import { bridgeReturnUrl } from "@/lib/bridge";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { eventPhotoPath } from "@/lib/event-photos";
import sharp from "sharp";
/** The advanced editor's saved slider recipe, or null when it cannot be read. */
function savedRecipe(json: string | null): unknown {
if (!json) return null;
try {
const parsed = JSON.parse(json) as unknown;
return parsed && typeof parsed === "object" ? parsed : null;
} catch {
return null;
}
}
/** Reads the header dimensions without decoding the whole file. */
async function imageSize(
path: string,
): Promise<{ width: number; height: number } | null> {
try {
const meta = await sharp(path).metadata();
if (!meta.width || !meta.height) return null;
return { width: meta.width, height: meta.height };
} catch {
return null;
}
}
/**
* GET /api/bridge/sessions/:sessionId
*
* Everything the advanced editor needs to mirror one event: its title, dates
* and photo list. Photo bytes are fetched separately, one at a time, so opening
* a large event does not transfer gigabytes up front.
*/
export const GET = async (
req: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> },
) => {
const { sessionId } = await params;
const auth = await authenticateBridge(req, sessionId);
if (!auth) return errorResponse(401, "invalid or expired bridge session");
const event = await getBridgeEventSummary(auth.session.eventId);
if (!event) return errorResponse(404, "unknown event");
const rows = await listBridgePhotos(auth.session.eventId);
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
// Dimensions are only known for browser images; RAW dimensions arrive with
// the proxy the editor builds from the original.
const sizes = new Map<string, { width: number; height: number }>();
for (const row of rows) {
if (row.kind !== "image") continue;
const size = await imageSize(
eventPhotoPath(storage.root, row.storedName),
).catch(() => null);
if (size) sizes.set(row.id, size);
}
return jsonResponse({
session: { id: auth.session.id, expiresAt: auth.session.expiresAt },
event: {
id: event.id,
title: event.title,
eventType: event.eventType,
startsAt: event.startsAt,
endsAt: event.endsAt,
location: event.location,
description: event.description,
},
photos: rows.map((row) => ({
id: row.id,
filename: row.filename,
mimeType: row.mimeType,
kind: row.kind,
sizeBytes: row.sizeBytes,
folderName: row.folderName,
width: sizes.get(row.id)?.width ?? 0,
height: sizes.get(row.id)?.height ?? 0,
takenAt: row.createdAt,
// Reopening the editor restores the sliders exactly as they were saved;
// the editor falls back to neutral when this is null.
edits: savedRecipe(row.advancedEditJson),
// Stamps the thumbnail URL so a newly saved edit is not masked by a
// cached grid thumbnail from before it was rendered.
editedAt: row.editedAt,
})),
editor: { returnUrl: bridgeReturnUrl(auth.session.eventId) },
});
};

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