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>
This commit is contained in:
2026-11-21 06:35:24 +00:00
parent ab4a07a40f
commit ebe0c77f7e
35 changed files with 1844 additions and 150 deletions
+8 -4
View File
@@ -94,12 +94,16 @@ NFS_ADDR=
NFS_EXPORT=
NFS_VERSION=4
# Advanced editor bridge (optional). LUMENROOM_URL is the base URL of the
# separate Lumenroom deployment, e.g. http://edit.local:8787. BRIDGE_SECRET is a
# long random string shared with that deployment; without both the "Advanced"
# button reports that the editor is not configured.
# 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=
+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
+137 -9
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)
@@ -108,10 +109,19 @@ 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).
```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 shows it in the browser and prints it in the app log:
@@ -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
@@ -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.
@@ -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,6 +714,8 @@ 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)
@@ -610,12 +734,16 @@ 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:
and one command deploy both (add `--build` when the sources changed):
```bash
docker compose up -d --build
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
@@ -692,7 +820,7 @@ that the gallery shows.
│ ├── 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
+36 -7
View File
@@ -9,7 +9,7 @@
import crypto from 'node:crypto';
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
import { db, getPhoto, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
import { removeAsset } from './storage.mjs';
const VERSION = 'g1';
@@ -173,11 +173,17 @@ function photoRecordFrom(photo, eventId, sessionId, index) {
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: [],
edits: {},
// 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,
@@ -189,7 +195,7 @@ function photoRecordFrom(photo, eventId, sessionId, index) {
* 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 }) {
export async function importBridgeEvent({ serviceToken, sessionId, returnUrl }) {
const expiresAt =
Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000;
@@ -198,12 +204,35 @@ export async function importBridgeEvent({ serviceToken, 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);
const returnUrl = listing.editor?.returnUrl ?? null;
saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0);
// 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) => {
savePhoto(photoRecordFrom(photo, eventId, sessionId, 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,
@@ -211,7 +240,7 @@ export async function importBridgeEvent({ serviceToken, sessionId }) {
serviceToken,
GLENLOCH_URL,
listing.event.id,
returnUrl,
dashboardReturn,
expiresAt,
Date.now(),
);
+13 -1
View File
@@ -39,6 +39,7 @@ import {
findPreview,
findThumb,
removeAsset,
removeThumb,
storageBytes,
writeOriginal,
writePreview,
@@ -302,6 +303,7 @@ route('GET', '/api/bridge/login', async ({ req, res, url }) => {
const imported = await importBridgeEvent({
serviceToken: service.token,
sessionId: payload.sid,
returnUrl: service.returnUrl,
});
const sessionToken = createSession(row.id);
res.writeHead(302, {
@@ -459,7 +461,17 @@ route('POST', '/api/bridge/export', async ({ req, res }) => {
if (result.status >= 400) {
return error(res, result.status, result.body?.error || 'The edit could not be saved to the event');
}
return json(res, 200, result.body ?? { ok: true });
// 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 }) => {
+6
View File
@@ -70,6 +70,12 @@ export function findThumb(id) {
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())));
+9 -2
View File
@@ -653,15 +653,22 @@ export default function App() {
height: activePhoto.height,
}),
});
const data = (await res.json().catch(() => ({}))) as { error?: string };
const data = (await res.json().catch(() => ({}))) as {
error?: string;
thumbVersion?: number;
};
if (!res.ok) throw new Error(data.error || 'The photo could not be saved');
if (typeof data.thumbVersion === 'number') {
// Refresh the grid thumbnail so it shows this render, not the original.
updatePhoto(activePhoto.id, { thumbVersion: data.thumbVersion });
}
setToast(`Saved ${activePhoto.name} to the event`);
} catch (err) {
setToast(err instanceof Error ? err.message : 'The photo could not be saved');
} finally {
setBridgeBusy(false);
}
}, [activePhoto, bridgeEvent]);
}, [activePhoto, bridgeEvent, updatePhoto]);
const handleCloudLogin = useCallback(
async (email: string, password: string) => {
+2 -2
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits';
import { getBitmap } from '../lib/images';
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';
@@ -703,7 +703,7 @@ export default function Develop({
title={p.name}
>
<img
src={p.thumbUrl ?? p.thumb}
src={thumbSrc(p)}
alt={p.name}
loading="lazy"
draggable={false}
+2 -1
View File
@@ -1,6 +1,7 @@
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';
@@ -312,7 +313,7 @@ export default function LibraryGrid({
>
<div className="card-thumb">
<img
src={p.thumbUrl ?? p.thumb}
src={thumbSrc(p)}
alt={p.name}
loading="lazy"
draggable={false}
+2 -2
View File
@@ -4,7 +4,7 @@ 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 } from '../lib/images';
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';
@@ -653,7 +653,7 @@ export function NavigatorPanel({ photo }: { photo: PhotoRecord }) {
</div>
<div className="navigator-thumb">
<img
src={photo.thumbUrl ?? photo.thumb}
src={thumbSrc(photo)}
alt={photo.name}
style={{ transform: thumbTransform(photo) }}
/>
+1
View File
@@ -266,6 +266,7 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
decode: input.decode,
previewUrl: input.previewUrl,
thumbUrl: input.thumbUrl,
thumbVersion: input.thumbVersion,
name: input.name ?? 'Untitled',
width: input.width ?? 0,
height: input.height ?? 0,
+11
View File
@@ -4,6 +4,17 @@ 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`;
+3
View File
@@ -562,6 +562,9 @@ img {
overflow-y: auto;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
/* Keep every row at its natural height. Without this, a large library makes
the auto rows shrink to fit the viewport and the thumbnails collapse. */
grid-auto-rows: max-content;
gap: 12px;
padding: 14px;
align-content: start;
+2
View File
@@ -103,6 +103,8 @@ export interface PhotoRecord {
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 };
}
@@ -10,6 +10,7 @@ import {
} from "@/lib/event-photos";
import { mediaStorage } from "@/lib/media-storage";
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { advancedEditViewFor } from "@/lib/advanced-edit";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
@@ -64,9 +65,12 @@ export default async function EventFolderPage({
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-5">
@@ -104,6 +108,17 @@ export default async function EventFolderPage({
</a>
</Button>
)}
{editedCount > 0 && (
<Button asChild variant="outline" size="sm">
<a
href={`/api/events/${detail.event.id}/download?folderId=${detail.folder.id}&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>
)}
</div>
</div>
+5
View File
@@ -5,6 +5,7 @@ import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles";
import { getEventDetail, listAssignableUsers } 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";
@@ -17,6 +18,7 @@ import {
} 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";
@@ -99,6 +101,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`}>
@@ -2,6 +2,7 @@ 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";
@@ -36,5 +37,9 @@ export const POST = async (
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,
});
};
@@ -4,11 +4,17 @@ 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;
@@ -19,9 +25,10 @@ const MAX_JPEG_BYTES = 48 * 1024 * 1024;
* 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 becomes the photo's edited version (used by the gallery,
* thumbnails and delivery exports) and the recipe is kept so the editor can be
* reopened with its sliders intact.
* 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,
@@ -70,11 +77,11 @@ export const POST = async (
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const storedName = editedStoredNameForEventPhoto(
const advancedStoredName = advancedStoredNameForEventPhoto(
auth.session.eventId,
photo.id,
);
const target = eventPhotoPath(storage.root, storedName);
const target = eventPhotoPath(storage.root, advancedStoredName);
const temporary = `${target}.${randomUUID()}.tmp`;
try {
await mkdir(path.dirname(target), { recursive: true });
@@ -85,10 +92,40 @@ export const POST = async (
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: storedName,
editedSizeBytes: data.byteLength,
editedStoredName,
editedSizeBytes,
advancedEditJson: recipe,
editedBy: auth.user.id,
});
@@ -100,6 +137,6 @@ export const POST = async (
return jsonResponse({
ok: true,
editedAt,
editedSizeBytes: data.byteLength,
editedSizeBytes,
});
};
@@ -4,9 +4,9 @@ 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 sharp from "sharp";
import { authenticateBridge, getBridgePhoto } from "@/db/bridge";
import {
bridgeEditedThumbStoredNameForEventPhoto,
bridgeProxyStoredNameForEventPhoto,
bridgeThumbStoredNameForEventPhoto,
eventPhotoPath,
@@ -14,7 +14,7 @@ import {
import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
import { renderPhotoJpeg } from "@/lib/photo-render";
import { renderPhotoJpeg, renderPhotoThumbnail } from "@/lib/photo-render";
const PROXY_MAX_EDGE = 4000;
const THUMB_MAX_EDGE = 480;
@@ -31,14 +31,25 @@ function imageResponse(data: Buffer, contentType = "image/jpeg"): Response {
});
}
/** Reads a cached derivative or writes it atomically on first use. */
/**
* 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) return readFile(filePath);
if (
info.isFile() &&
info.size > 0 &&
(newerThan === undefined || info.mtimeMs >= newerThan)
) {
return readFile(filePath);
}
} catch {
// Not generated yet.
}
@@ -51,24 +62,12 @@ async function cached(
}
async function thumbFor(filePath: string, kind: "raw" | "image") {
if (kind === "raw") {
const rendered = await renderPhotoJpeg({
filePath,
kind,
adjustments: defaultPhotoAdjustments(),
maxDimension: THUMB_MAX_EDGE,
});
return rendered.data;
}
return sharp(filePath)
.resize({
width: THUMB_MAX_EDGE,
height: THUMB_MAX_EDGE,
fit: "inside",
withoutEnlargement: true,
})
.jpeg({ quality: 82, mozjpeg: true })
.toBuffer();
return renderPhotoThumbnail({
filePath,
kind,
maxDimension: THUMB_MAX_EDGE,
quality: 82,
});
}
/**
@@ -126,13 +125,33 @@ export const GET = async (
}
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 thumbPath = eventPhotoPath(
storage.root,
bridgeThumbStoredNameForEventPhoto(auth.session.eventId, photo.id),
);
const data = await cached(thumbPath, () =>
thumbFor(originalPath, photo.kind),
const data = await cached(
eventPhotoPath(storage.root, thumbName),
() => thumbFor(sourcePath, sourceKind),
editedMtime,
);
return imageResponse(data);
} catch {
@@ -10,6 +10,17 @@ 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,
@@ -77,6 +88,12 @@ export const GET = async (
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) },
});
+10 -3
View File
@@ -1,5 +1,6 @@
import { NextRequest } from "next/server";
import { gateSession } from "@/auth/api";
import { requestOrigin } from "@/auth/magic-link";
import { bridgeUser, createBridgeSession } from "@/db/bridge";
import { getEventAccess } from "@/db/events";
import { errorResponse, jsonResponse } from "@/lib/http";
@@ -7,7 +8,6 @@ import {
BRIDGE_LOGIN_TTL_SECONDS,
advancedEditorUrl,
bridgeConfigured,
bridgeReturnUrl,
signBridgeToken,
} from "@/lib/bridge";
@@ -19,7 +19,7 @@ import {
* dashboard session; the editor only ever sees the scoped token.
*/
export const POST = async (
_req: NextRequest,
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
@@ -45,6 +45,12 @@ export const POST = async (
eventId: id,
});
// This request comes from the user's browser, so its origin is the address
// that actually works for them. `NEXTAUTH_URL` cannot be trusted here: the
// compose default is http://localhost:3000 even when the app is served from
// a LAN address. PUBLIC_ORIGIN still wins inside requestOrigin().
const returnUrl = `${requestOrigin(req)}/events/${id}`;
const token = signBridgeToken({
sid: session.id,
eid: id,
@@ -53,11 +59,12 @@ export const POST = async (
name: user.name,
kind: "login",
exp: Math.floor(Date.now() / 1000) + BRIDGE_LOGIN_TTL_SECONDS,
ret: returnUrl,
});
return jsonResponse({
url: `${editor}/api/bridge/login?token=${encodeURIComponent(token)}`,
expiresAt: session.expiresAt,
returnUrl: bridgeReturnUrl(id),
returnUrl,
});
};
+34 -16
View File
@@ -17,10 +17,12 @@ import { mediaStorage } from "@/lib/media-storage";
* GET /api/events/:id/download
*
* Streams every photo on the event as one ZIP, preserving folder names. Saved
* edits are included beside their originals as `<name>-edited.jpg`. The
* archive is store-only: JPEGs and camera RAW files are already compressed, so
* deflating them would add CPU and latency without shrinking the download.
* Anyone assigned to the event (or a manager) can download it.
* edits are included beside their originals as `<name>-edited.jpg`. With
* `?edited=1` the archive contains only the saved edits, which is what a
* photographer wants to hand on after a grading pass. The archive is
* store-only: JPEGs and camera RAW files are already compressed, so deflating
* them would add CPU and latency without shrinking the download. Anyone
* assigned to the event (or a manager) can download it.
*/
export const GET = async (
req: NextRequest,
@@ -36,13 +38,22 @@ export const GET = async (
// `?folderId=` narrows the archive to one folder, so a photographer can pull
// just the shots they need without downloading the whole event.
const folderId = req.nextUrl.searchParams.get("folderId")?.trim() || null;
const onlyEdited = req.nextUrl.searchParams.get("edited") === "1";
const photos = (await listEventPhotosForArchive(id)).filter(
(photo) => !folderId || photo.folderId === folderId,
(photo) =>
(!folderId || photo.folderId === folderId) &&
(!onlyEdited || Boolean(photo.editedStoredName)),
);
if (photos.length === 0) {
return errorResponse(
404,
folderId ? "this folder has no photos" : "this event has no photos",
onlyEdited
? folderId
? "this folder has no edited photos"
: "this event has no edited photos"
: folderId
? "this folder has no photos"
: "this event has no photos",
);
}
@@ -55,13 +66,15 @@ export const GET = async (
filename: string;
storedName: string;
}[] = [];
for (const photo of photos) {
entries.push({
key: `${photo.id}:original`,
folderName: photo.folderName,
filename: photo.filename,
storedName: photo.storedName,
});
if (!onlyEdited) {
for (const photo of photos) {
entries.push({
key: `${photo.id}:original`,
folderName: photo.folderName,
filename: photo.filename,
storedName: photo.storedName,
});
}
}
for (const photo of photos) {
if (!photo.editedStoredName) continue;
@@ -124,9 +137,14 @@ export const GET = async (
"content-type": "application/zip",
"content-disposition": photoContentDisposition(
eventArchiveFilename(
folderId
? `${access.event.title} - ${photos[0].folderName}`
: access.event.title,
[
folderId
? `${access.event.title} - ${photos[0].folderName}`
: access.event.title,
onlyEdited ? "edited" : null,
]
.filter(Boolean)
.join(" - "),
),
false,
),
@@ -1,10 +1,11 @@
import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto";
import { mkdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import { copyFile, mkdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { gateSession } from "@/auth/api";
import { getEventPhotoAccess, updateEventPhotoEdit } from "@/db/events";
import {
advancedStoredNameForEventPhoto,
editedPhotoFilename,
editedStoredNameForEventPhoto,
eventPhotoPath,
@@ -12,18 +13,43 @@ import {
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { normalizePhotoAdjustments } from "@/lib/photo-adjustments";
import {
defaultPhotoAdjustments,
normalizePhotoAdjustments,
parseStoredPhotoAdjustments,
} from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
const MAX_EDIT_BODY_BYTES = 32 * 1024;
/** True when the advanced editor has left a recipe that describes its render. */
function hasAdvancedRecipe(json: string | null): boolean {
if (!json) return false;
try {
const parsed: unknown = JSON.parse(json);
return Boolean(
parsed && typeof parsed === "object" && Object.keys(parsed).length > 0,
);
} catch {
return false;
}
}
function isNeutral(adjustments: ReturnType<typeof defaultPhotoAdjustments>) {
return (
JSON.stringify(adjustments) === JSON.stringify(defaultPhotoAdjustments())
);
}
/**
* POST /api/events/:id/folders/:folderId/photos/:photoId/edit
* Body: { adjustments: PhotoAdjustments }
*
* Saves the recipe and renders a fresh full-resolution JPEG beside the
* original. The original file is never changed, so an edit can always be
* reopened and adjusted again.
* original. When the advanced editor has already rendered this photo, that
* render is the base and the simple recipe is layered on top, so saving here
* never throws the advanced edit away. The original is never changed, so an
* edit can always be reopened and adjusted again.
*/
export const POST = async (
req: NextRequest,
@@ -59,8 +85,12 @@ export const POST = async (
if (!storage.ok) return errorResponse(503, storage.message);
const body = (await req.json().catch(() => null)) as
| { adjustments?: unknown }
| { adjustments?: unknown; takeOver?: unknown }
| null;
// Taking over retires the advanced recipe: the sliders are rendered from the
// original file instead of on top of the advanced render, so the look is not
// applied twice.
const takeOver = body?.takeOver === true;
const adjustments = normalizePhotoAdjustments(body?.adjustments);
if (!adjustments) {
return errorResponse(400, "invalid photo adjustments");
@@ -80,11 +110,69 @@ export const POST = async (
);
const editedPath = eventPhotoPath(storage.root, editedStoredName);
// The advanced editor's render is the base for the simple recipe.
let renderPath = sourcePath;
let renderKind = access.photo.kind;
const advancedStoredName = advancedStoredNameForEventPhoto(
access.eventId,
access.photo.id,
);
const advancedPath = eventPhotoPath(storage.root, advancedStoredName);
if (!takeOver && hasAdvancedRecipe(access.photo.advancedEditJson)) {
let advancedInfo = await stat(advancedPath).catch(() => null);
if (!advancedInfo?.isFile()) {
// Rows saved before the advanced render had its own file kept it in the
// edited path; copy it aside once so layered renders never compound.
const previous = access.photo.editedStoredName;
if (previous && previous !== advancedStoredName) {
const legacyPath = eventPhotoPath(storage.root, previous);
const legacyInfo = await stat(legacyPath).catch(() => null);
if (legacyInfo?.isFile()) {
await mkdir(path.dirname(advancedPath), { recursive: true });
await copyFile(legacyPath, advancedPath).catch(() => undefined);
advancedInfo = await stat(advancedPath).catch(() => null);
}
}
}
if (advancedInfo?.isFile()) {
renderPath = advancedPath;
renderKind = "image";
}
// Nothing layered on top: keep the advanced render as the saved edit
// instead of re-rendering it. This is a save with no slider changes, so
// say so rather than claiming a new JPEG was written.
if (renderPath === advancedPath && isNeutral(adjustments)) {
const info = await stat(advancedPath);
const alreadySaved =
access.photo.editedStoredName === advancedStoredName &&
JSON.stringify(parseStoredPhotoAdjustments(access.photo.editJson)) ===
JSON.stringify(adjustments);
const updated = await updateEventPhotoEdit({
photoId: access.photo.id,
editJson: JSON.stringify(adjustments),
editedStoredName: advancedStoredName,
editedSizeBytes: info.size,
editedBy: gate.id,
clearAdvancedEdit: false,
});
if (!updated) return errorResponse(404, "unknown photo");
return jsonResponse({
ok: true,
unchanged: alreadySaved,
adjustments,
editedFilename: editedPhotoFilename(access.photo.filename),
editedSizeBytes: info.size,
editedAt: updated.editedAt,
});
}
}
let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>;
try {
rendered = await renderPhotoJpeg({
filePath: sourcePath,
kind: access.photo.kind,
filePath: renderPath,
kind: renderKind,
adjustments,
});
} catch (error) {
@@ -113,6 +201,7 @@ export const POST = async (
editedStoredName,
editedSizeBytes: rendered.data.byteLength,
editedBy: gate.id,
clearAdvancedEdit: takeOver,
});
if (!updated) {
await unlink(editedPath).catch(() => undefined);
@@ -127,6 +216,7 @@ export const POST = async (
editedAt: updated.editedAt,
width: rendered.width,
height: rendered.height,
tookOver: takeOver,
});
} catch (error) {
await unlink(editedPath).catch(() => undefined);
@@ -6,6 +6,7 @@ import { gateSession } from "@/auth/api";
import { deleteEventPhoto, getEventPhotoAccess } from "@/db/events";
import { canDeleteEventPhoto } from "@/lib/event-access";
import {
advancedStoredNameForEventPhoto,
editedPhotoFilename,
eventPhotoPath,
isBrowserRenderablePhoto,
@@ -19,8 +20,11 @@ import { mediaStorage } from "@/lib/media-storage";
*
* Streams the original bytes to anyone assigned to the event (or a manager).
* `variant=edited` serves the generated full-resolution JPEG instead, so the
* gallery can show the saved look without replacing the original. RAW files
* always download; `?download=1` forces an attachment for JPEGs too.
* gallery can show the saved look without replacing the original.
* `variant=advanced` serves the advanced editor's own render (without any
* simple-editor layer), which is the base the simple editor previews on top of
* so its sliders can be re-applied without baking them twice. RAW files always
* download; `?download=1` forces an attachment for JPEGs too.
*/
export const GET = async (
req: NextRequest,
@@ -43,7 +47,9 @@ export const GET = async (
return errorResponse(404, "unknown photo");
}
const wantsEdited = req.nextUrl.searchParams.get("variant") === "edited";
const variant = req.nextUrl.searchParams.get("variant");
const wantsEdited = variant === "edited";
const wantsAdvanced = variant === "advanced";
if (wantsEdited && !access.photo.editedStoredName) {
return errorResponse(404, "this photo has no saved edit");
}
@@ -51,13 +57,27 @@ export const GET = async (
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const filePath = eventPhotoPath(
storage.root,
wantsEdited
? access.photo.editedStoredName!
: access.photo.storedName,
);
const filename = wantsEdited
let servedStoredName = access.photo.storedName;
if (wantsEdited) {
servedStoredName = access.photo.editedStoredName!;
} else if (wantsAdvanced) {
const advancedName = advancedStoredNameForEventPhoto(id, access.photo.id);
const advancedInfo = await stat(
eventPhotoPath(storage.root, advancedName),
).catch(() => null);
if (advancedInfo?.isFile()) {
servedStoredName = advancedName;
} else if (access.photo.editedStoredName) {
// Rows saved before the advanced render had its own file kept it here.
servedStoredName = access.photo.editedStoredName;
} else {
return errorResponse(404, "this photo has no advanced edit");
}
}
const generated = wantsEdited || wantsAdvanced;
const filePath = eventPhotoPath(storage.root, servedStoredName);
const filename = generated
? editedPhotoFilename(access.photo.filename)
: access.photo.filename;
let size: number;
@@ -69,7 +89,7 @@ export const GET = async (
const inline =
req.nextUrl.searchParams.get("download") !== "1" &&
(wantsEdited || isBrowserRenderablePhoto(access.photo.filename));
(generated || isBrowserRenderablePhoto(access.photo.filename));
const stream = createReadStream(filePath);
return new Response(
@@ -77,7 +97,7 @@ export const GET = async (
{
status: 200,
headers: {
"content-type": wantsEdited ? "image/jpeg" : access.photo.mimeType,
"content-type": generated ? "image/jpeg" : access.photo.mimeType,
"content-length": String(size),
"content-disposition": photoContentDisposition(filename, inline),
"cache-control": "private, max-age=0, must-revalidate",
@@ -2,7 +2,6 @@ import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import { gateSession } from "@/auth/api";
import { getEventPhotoAccess } from "@/db/events";
import {
@@ -12,8 +11,7 @@ import {
} from "@/lib/event-photos";
import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
import { PhotoRenderError, renderPhotoThumbnail } from "@/lib/photo-render";
/**
* GET /api/events/:id/folders/:folderId/photos/:photoId/thumb
@@ -69,20 +67,15 @@ export const GET = async (
let data: Buffer;
try {
if (access.photo.kind === "raw") {
const rendered = await renderPhotoJpeg({
if (
access.photo.kind === "raw" ||
isBrowserRenderablePhoto(access.photo.filename)
) {
data = await renderPhotoThumbnail({
filePath: sourcePath,
kind: "raw",
adjustments: defaultPhotoAdjustments(),
kind: access.photo.kind,
maxDimension: 640,
});
data = rendered.data;
} else if (isBrowserRenderablePhoto(access.photo.filename)) {
data = await sharp(sourcePath, { failOn: "none", limitInputPixels: 500_000_000 })
.autoOrient()
.resize(640, 640, { fit: "inside", withoutEnlargement: true })
.jpeg({ quality: 72 })
.toBuffer();
} else {
return errorResponse(415, "this photo format has no thumbnail");
}
@@ -0,0 +1,63 @@
"use client";
import { useState } from "react";
import { Loader2, Wand2 } from "lucide-react";
import { Button } from "@/components/ui/button";
/**
* Opens the event in the advanced editor. The bridge URL is minted by the API
* with the normal dashboard session, so this is a POST followed by a redirect.
*/
export function AdvancedEditorButton({ eventId }: { eventId: string }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function open() {
setBusy(true);
setError(null);
try {
const res = await fetch(`/api/events/${eventId}/advanced`, {
method: "POST",
});
const data = (await res.json().catch(() => ({}))) as {
url?: string;
error?: string;
};
if (!res.ok || !data.url) {
throw new Error(data.error ?? "The advanced editor could not be opened.");
}
window.location.assign(data.url);
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: "The advanced editor could not be opened.",
);
setBusy(false);
}
}
return (
<span className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={busy}
onClick={open}
>
{busy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
) : (
<Wand2 className="h-3.5 w-3.5" aria-hidden="true" />
)}
Advanced editor
</Button>
{error && (
<span role="alert" className="text-xs text-destructive">
{error}
</span>
)}
</span>
);
}
+66 -16
View File
@@ -8,6 +8,40 @@ import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { PhotoViewer, type ViewerPhoto } from "./photo-viewer";
import type { PhotoAdjustments } from "@/lib/photo-adjustments";
import type { AdvancedEditView } from "@/lib/advanced-edit";
/**
* Grid image that degrades to a readable tile instead of a blank square when
* the thumbnail cannot be produced (damaged or unsupported RAW, missing file).
*/
function GalleryImage({ src, alt }: { src: string; alt: string }) {
const [failed, setFailed] = useState(false);
if (failed) {
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-1 px-2 text-center text-muted-foreground">
<FileImage className="h-8 w-8" aria-hidden="true" />
<span className="text-[11px] font-medium">Preview unavailable</span>
<span className="w-full truncate text-[10px]" title={alt}>
{alt}
</span>
</div>
);
}
return (
// Frames are private; the serving route sets the cache policy.
// eslint-disable-next-line @next/next/no-img-element
<img
src={src}
alt={alt}
loading="lazy"
decoding="async"
onError={() => setFailed(true)}
className="h-full w-full object-cover"
/>
);
}
export interface GalleryPhoto {
id: string;
@@ -19,6 +53,10 @@ export interface GalleryPhoto {
previewable: boolean;
editable: boolean;
adjustments: PhotoAdjustments;
/** The saved edit was produced by the advanced (Lumenroom) editor. */
advancedEdit: boolean;
/** Read-only view of the advanced recipe and a quick-editor seed. */
advancedSummary: AdvancedEditView | null;
editedAt: string | null;
editedSizeBytes: number | null;
}
@@ -303,15 +341,7 @@ export function PhotoGallery({
onClick={() => setViewing(photo)}
>
{photo.previewable || photo.editedAt || photo.kind === "raw" ? (
// Frames are private; the serving route sets the cache policy.
// eslint-disable-next-line @next/next/no-img-element
<img
src={displaySrc}
alt={photo.filename}
loading="lazy"
decoding="async"
className="h-full w-full object-cover"
/>
<GalleryImage src={displaySrc} alt={photo.filename} />
) : (
<div className="flex flex-col items-center gap-1 text-muted-foreground">
<FileImage className="h-8 w-8" aria-hidden="true" />
@@ -353,13 +383,31 @@ export function PhotoGallery({
{photo.uploaderName}
</p>
<div className="flex flex-wrap items-center gap-1">
<a
href={`${src}?download=1`}
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
>
<Download className="h-3 w-3" aria-hidden="true" />
Download
</a>
{photo.editedAt ? (
<>
<a
href={`${src}?variant=edited&download=1&v=${version}`}
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
>
<Download className="h-3 w-3" aria-hidden="true" />
Download edited
</a>
<a
href={`${src}?download=1`}
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-muted-foreground hover:underline"
>
Original
</a>
</>
) : (
<a
href={`${src}?download=1`}
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
>
<Download className="h-3 w-3" aria-hidden="true" />
Download
</a>
)}
{editable && (
<button
type="button"
@@ -400,6 +448,8 @@ export function PhotoGallery({
editedAt: viewing.editedAt,
editedSizeBytes: viewing.editedSizeBytes,
adjustments: viewing.adjustments,
advancedEdit: viewing.advancedEdit,
advancedSummary: viewing.advancedSummary,
} satisfies ViewerPhoto}
onClose={() => setViewing(null)}
onSaved={() => router.refresh()}
+298 -14
View File
@@ -39,6 +39,7 @@ import {
} from "@/lib/photo-geometry";
import { PHOTO_EXPORT_PRESETS } from "@/lib/photo-exports";
import { PHOTO_PRESETS, applyPhotoPreset } from "@/lib/photo-presets";
import type { AdvancedEditView, QuickNumericSetting } from "@/lib/advanced-edit";
export interface ViewerPhoto {
id: string;
@@ -47,6 +48,10 @@ export interface ViewerPhoto {
editedAt: string | null;
editedSizeBytes: number | null;
adjustments: PhotoAdjustments;
/** The saved edit came from the advanced editor; it cannot be re-applied here. */
advancedEdit: boolean;
/** Read-only view of the advanced recipe plus a quick-editor seed. */
advancedSummary: AdvancedEditView | null;
}
type EditorTab = "light" | "color" | "detail" | "geometry" | "presets";
@@ -390,12 +395,36 @@ export function PhotoViewer({
onNext?: () => void;
}) {
const src = `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`;
// An advanced edit is baked into its own render. The viewer previews that
// render and layers this editor's sliders on top, so both editors keep their
// work instead of the advanced look being replaced by a neutral render.
const showsAdvancedEdit = photo.advancedEdit && Boolean(photo.editedAt);
// A photo whose saved look is the advanced render and whose quick layer is
// untouched opens with the advanced settings already in the sliders, so the
// quick editor shows the same numbers the look was made with instead of a
// confusing row of zeros.
const advancedSeed = photo.advancedSummary?.seed ?? null;
const quickLayerIsNeutral =
JSON.stringify(photo.adjustments) === JSON.stringify(defaultPhotoAdjustments());
const autoSeed = showsAdvancedEdit && Boolean(advancedSeed) && quickLayerIsNeutral;
const [takeOverPending, setTakeOverPending] = useState(autoSeed);
const [advancedRetired, setAdvancedRetired] = useState(false);
const autoSeeded = useRef(autoSeed);
const showAdvancedPanel = showsAdvancedEdit && !advancedRetired;
// Once the sliders take over they render from the original file, so the
// preview must not keep the advanced render underneath them.
const basesOnAdvanced = showsAdvancedEdit && !takeOverPending;
const previewSrc = basesOnAdvanced
? `${src}?variant=advanced&v=${photo.editedAt ? Date.parse(photo.editedAt) : 0}`
: `${src}/preview`;
const canvasRef = useRef<HTMLCanvasElement>(null);
const rotatedRef = useRef<{ key: string; canvas: HTMLCanvasElement } | null>(
null,
);
const [adjustments, setAdjustments] = useState<PhotoAdjustments>(() =>
cloneAdjustments(photo.adjustments),
autoSeed && advancedSeed
? cloneAdjustments(advancedSeed)
: cloneAdjustments(photo.adjustments),
);
const [tab, setTab] = useState<EditorTab>("light");
const [source, setSource] = useState<HTMLImageElement | null>(null);
@@ -416,11 +445,22 @@ export function PhotoViewer({
editedSizeBytes: number;
width: number;
height: number;
/** Nothing was re-rendered because the saved edit is already this look. */
unchanged?: boolean;
} | null>(null);
const [savedVersion, setSavedVersion] = useState(() =>
photo.editedAt ? Date.parse(photo.editedAt) : 0,
);
const [recipeMessage, setRecipeMessage] = useState<string | null>(null);
const [takeOverMessage, setTakeOverMessage] = useState<string | null>(null);
const [hoverSetting, setHoverSetting] = useState<{
label: string;
key: QuickNumericSetting;
amount: number;
} | null>(null);
const inlineRef = useRef<HTMLCanvasElement>(null);
const inlineSourceRef = useRef<HTMLImageElement | null>(null);
const [inlineReady, setInlineReady] = useState(false);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
@@ -468,12 +508,12 @@ export function PhotoViewer({
"The preview could not be prepared. You can still try saving the edit.",
);
};
image.src = `${src}/preview`;
image.src = previewSrc;
return () => {
active = false;
image.src = "";
};
}, [src]);
}, [previewSrc]);
useEffect(() => {
if (!source) return;
@@ -559,6 +599,52 @@ export function PhotoViewer({
};
}, [adjustments, source, showOriginal]);
// The inline preview shows one advanced setting applied to the untouched
// original, so the summary reads as "what this control does" rather than a
// number on its own.
useEffect(() => {
if (!showAdvancedPanel) return;
let active = true;
const image = new Image();
image.onload = () => {
if (!active) return;
inlineSourceRef.current = image;
setInlineReady(true);
};
image.src = `${src}/preview`;
return () => {
active = false;
image.src = "";
};
}, [showAdvancedPanel, src]);
useEffect(() => {
const canvas = inlineRef.current;
const image = inlineSourceRef.current;
if (!canvas || !image || !hoverSetting) return;
const width = 240;
const height = Math.max(
1,
Math.round((width * image.naturalHeight) / Math.max(1, image.naturalWidth)),
);
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
const context = canvas.getContext("2d", { willReadFrequently: true });
if (!context) return;
context.drawImage(image, 0, 0, width, height);
const data = context.getImageData(0, 0, width, height);
applyPhotoAdjustmentsToRgba(
data.data,
width,
height,
{ ...defaultPhotoAdjustments(), [hoverSetting.key]: hoverSetting.amount },
4,
);
context.putImageData(data, 0, 0);
}, [hoverSetting, inlineReady]);
function update<K extends keyof PhotoAdjustments>(
key: K,
value: PhotoAdjustments[K],
@@ -635,6 +721,32 @@ export function PhotoViewer({
}
}
/**
* Seed the sliders from the advanced recipe. The look is already saved in the
* advanced render, so nothing is written until the photographer saves; the
* next save retires the advanced recipe and renders from the original.
*/
function takeOverFromAdvanced() {
const view = photo.advancedSummary;
if (!view) return;
setAdjustments(cloneAdjustments(view.seed));
setTakeOverPending(true);
setTab("light");
setSaveError(null);
setSaveResult(null);
setRecipeMessage(null);
setTakeOverMessage(
"Advanced settings loaded. Review the sliders, then save to make this editor the source of truth.",
);
}
function undoTakeOver() {
setAdjustments(cloneAdjustments(photo.adjustments));
setTakeOverPending(false);
setTakeOverMessage(null);
setSaveError(null);
}
async function save() {
setSaving(true);
setSaveError(null);
@@ -642,7 +754,10 @@ export function PhotoViewer({
const response = await fetch(`${src}/edit`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ adjustments }),
body: JSON.stringify({
adjustments,
...(takeOverPending ? { takeOver: true } : {}),
}),
});
const data = (await response.json().catch(() => ({}))) as {
error?: string;
@@ -650,6 +765,8 @@ export function PhotoViewer({
editedSizeBytes?: number;
width?: number;
height?: number;
unchanged?: boolean;
tookOver?: boolean;
};
if (!response.ok || !data.editedAt) {
setSaveError(data.error ?? "The edited JPEG could not be saved.");
@@ -660,8 +777,15 @@ export function PhotoViewer({
editedSizeBytes: data.editedSizeBytes ?? 0,
width: data.width ?? 0,
height: data.height ?? 0,
unchanged: data.unchanged === true,
});
setSavedVersion(Date.now());
if (data.tookOver === true) {
setAdvancedRetired(true);
setTakeOverMessage(
"Saved from the original file. The advanced recipe is retired and these sliders are now the saved look.",
);
}
onSaved();
} catch {
setSaveError("Network error while saving the edit.");
@@ -811,7 +935,9 @@ export function PhotoViewer({
<div className="flex flex-wrap items-center justify-between gap-2 px-3 pb-2 text-[11px] text-white/55">
<span>
{showOriginal
? "Original look with crop"
? basesOnAdvanced
? "Before your slider changes"
: "Original look with crop"
: "Live preview · saved at full resolution"}
</span>
{recipeMessage && <span>{recipeMessage}</span>}
@@ -852,6 +978,116 @@ export function PhotoViewer({
<Histogram histogram={histogram} />
</div>
{showAdvancedPanel && photo.advancedSummary && (
<details className="border-b border-border px-3 py-2">
<summary className="flex cursor-pointer items-center justify-between gap-2 text-xs font-medium">
<span>Advanced editor settings</span>
<span className="text-[11px] font-normal text-muted-foreground">
Read-only
</span>
</summary>
<div className="mt-2 space-y-2.5">
<div className="rounded-md border border-border bg-muted/20 p-1.5">
{/* Fixed height: a hover must not move the rows under the
cursor, or the preview would flicker on and off. */}
<div className="flex h-24 items-center justify-center overflow-hidden rounded bg-black/5">
<canvas
ref={inlineRef}
aria-label="Preview of the hovered advanced setting on the original photo"
className={`max-h-full max-w-full rounded ${hoverSetting ? "" : "hidden"}`}
/>
{!hoverSetting && (
<span className="px-2 text-center text-[10px] text-muted-foreground">
Hover a setting to preview it
</span>
)}
</div>
<p className="mt-1 h-7 text-[10px] leading-snug text-muted-foreground">
{hoverSetting
? `${hoverSetting.label} on the original file`
: "Each setting is shown on its own, applied to the original file."}
</p>
</div>
{photo.advancedSummary.sections.length === 0 && (
<p className="text-[11px] leading-snug text-muted-foreground">
The advanced editor saved this photo without changing any
tone or colour setting.
</p>
)}
{photo.advancedSummary.sections.map((section) => (
<div key={section.title}>
<p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
{section.title}
</p>
<dl className="mt-0.5 space-y-0.5">
{section.items.map((item) => (
<div
key={`${section.title}-${item.label}`}
className={`-mx-1 flex items-baseline justify-between gap-3 rounded px-1 text-[11px] ${
item.preview ? "cursor-help hover:bg-muted/70" : ""
}`}
onMouseEnter={() =>
setHoverSetting(
item.preview
? {
label: item.label,
key: item.preview.key,
amount: item.preview.amount,
}
: null,
)
}
onMouseLeave={() => setHoverSetting(null)}
>
<dt className="text-muted-foreground">{item.label}</dt>
<dd className="font-mono tabular-nums">{item.value}</dd>
</div>
))}
</dl>
</div>
))}
{photo.advancedSummary.onlyAdvanced.length > 0 && (
<p className="text-[11px] leading-snug text-muted-foreground">
Only in the advanced editor:{" "}
{photo.advancedSummary.onlyAdvanced.join(", ")}.
</p>
)}
{photo.advancedSummary.caveats.map((caveat) => (
<p
key={caveat}
className="text-[11px] leading-snug text-muted-foreground"
>
{caveat}
</p>
))}
{takeOverPending ? (
<p className="text-[11px] leading-snug text-muted-foreground">
{autoSeeded.current
? "The sliders already hold these settings, previewed on the original file. Saving makes them the saved look."
: "These settings are loaded in the sliders, previewed on the original file. Saving makes them the saved look."}
</p>
) : (
<>
<Button
type="button"
variant="outline"
size="sm"
className="h-8 w-full text-xs"
disabled={saving}
onClick={takeOverFromAdvanced}
>
Take over in the quick editor
</Button>
<p className="text-[11px] leading-snug text-muted-foreground">
Loads these values into the sliders. Saving then retires
the advanced recipe and renders from the original file.
</p>
</>
)}
</div>
</details>
)}
<div className="flex gap-1 overflow-x-auto border-b border-border px-2 py-2">
{TABS.map((item) => (
<button
@@ -1216,19 +1452,67 @@ export function PhotoViewer({
</p>
)}
{saveResult && (
<div
role="status"
className="space-y-1 rounded-md border border-border bg-muted/40 p-3 text-xs"
>
<p className="font-medium">Full-resolution JPEG saved.</p>
<p className="text-muted-foreground">
{saveResult.width} × {saveResult.height} ·{" "}
{formatBytes(saveResult.editedSizeBytes)}
{basesOnAdvanced && (
<p className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground">
The advanced editor&apos;s edit is kept as the base. Slider
changes here are saved on top of it, and saving in the advanced
editor again keeps this layer.
</p>
)}
{takeOverPending && (
<div className="space-y-1.5 rounded-md border border-border bg-muted/40 p-2">
<p className="text-[11px] leading-snug text-muted-foreground">
{autoSeeded.current
? "These sliders were filled from the advanced edit and are previewed on the original file."
: "These values came from the advanced edit and are previewed on the original file."}{" "}
Saving makes the quick editor the source of truth and retires
the advanced recipe.
</p>
<button
type="button"
className="text-[11px] font-medium text-primary hover:underline"
onClick={undoTakeOver}
>
Undo takeover
</button>
</div>
)}
{takeOverMessage && !saveError && (
<p
role="status"
className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground"
>
{takeOverMessage}
</p>
)}
{saveResult &&
(saveResult.unchanged ? (
<p
role="status"
className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground"
>
No changes to apply — the saved version is already the
advanced editor&apos;s render. Move a slider to save your own
adjustments on top of it.
</p>
) : (
<div
role="status"
className="space-y-1 rounded-md border border-border bg-muted/40 p-3 text-xs"
>
<p className="font-medium">Full-resolution JPEG saved.</p>
<p className="text-muted-foreground">
{saveResult.width > 0 && saveResult.height > 0
? `${saveResult.width} × ${saveResult.height} · `
: ""}
{formatBytes(saveResult.editedSizeBytes)}
</p>
</div>
))}
{hasSavedEdit && (
<div className="space-y-2 rounded-md border border-border bg-muted/20 p-3">
<p className="text-xs font-medium">Download JPEG</p>
+12
View File
@@ -112,6 +112,12 @@ export interface BridgePhotoRow {
sizeBytes: number;
storedName: string;
editedStoredName: string | null;
/** Recipe saved by the advanced editor, so a reopen can restore its sliders. */
advancedEditJson: string | null;
/** Recipe from the simple editor, layered on top of the advanced render. */
editJson: string | null;
/** When the saved edit was rendered; stamps the thumbnail cache. */
editedAt: Date | null;
createdAt: Date;
folderName: string;
}
@@ -128,6 +134,9 @@ export async function listBridgePhotos(
sizeBytes: eventPhotos.sizeBytes,
storedName: eventPhotos.storedName,
editedStoredName: eventPhotos.editedStoredName,
advancedEditJson: eventPhotos.advancedEditJson,
editJson: eventPhotos.editJson,
editedAt: eventPhotos.editedAt,
createdAt: eventPhotos.createdAt,
folderName: eventFolders.name,
})
@@ -150,6 +159,9 @@ export async function getBridgePhoto(
sizeBytes: eventPhotos.sizeBytes,
storedName: eventPhotos.storedName,
editedStoredName: eventPhotos.editedStoredName,
advancedEditJson: eventPhotos.advancedEditJson,
editJson: eventPhotos.editJson,
editedAt: eventPhotos.editedAt,
createdAt: eventPhotos.createdAt,
folderName: eventFolders.name,
})
+7
View File
@@ -73,6 +73,7 @@ export interface EventPhotoRow {
checksumSha256: string;
kind: "raw" | "image";
editJson: string | null;
advancedEditJson: string | null;
editedStoredName: string | null;
editedSizeBytes: number | null;
editedAt: Date | null;
@@ -374,6 +375,7 @@ export async function getFolderDetail(
checksumSha256: eventPhotos.checksumSha256,
kind: eventPhotos.kind,
editJson: eventPhotos.editJson,
advancedEditJson: eventPhotos.advancedEditJson,
editedStoredName: eventPhotos.editedStoredName,
editedSizeBytes: eventPhotos.editedSizeBytes,
editedAt: eventPhotos.editedAt,
@@ -672,11 +674,16 @@ export async function updateEventPhotoEdit(input: {
editedStoredName: string;
editedSizeBytes: number;
editedBy: string;
/** True when the quick editor takes the look over from the advanced render. */
clearAdvancedEdit?: boolean;
}) {
const [row] = await db
.update(eventPhotos)
.set({
// The simple recipe is applied on top of any advanced render, so the
// advanced recipe is kept and both editors stay in sync.
editJson: input.editJson,
...(input.clearAdvancedEdit ? { advancedEditJson: null } : {}),
editedStoredName: input.editedStoredName,
editedSizeBytes: input.editedSizeBytes,
editedAt: new Date(),
+125
View File
@@ -0,0 +1,125 @@
import { describe, expect, it } from "vitest";
import {
advancedEditViewFor,
advancedToQuickAdjustments,
parseAdvancedRecipe,
} from "./advanced-edit";
import { defaultPhotoAdjustments } from "./photo-adjustments";
const ADVANCED = {
exposure: 0.4,
contrast: 26,
highlights: -12,
shadows: 8,
whites: 10,
blacks: -14,
texture: 20,
clarity: 16,
dehaze: 0,
vibrance: 0,
saturation: 0,
temp: 6,
tint: -3,
bw: true,
bwFilter: "red",
bwFilterAmount: 100,
curve: {
rgb: [
{ x: 0, y: 0 },
{ x: 0.35, y: 0.42 },
{ x: 1, y: 1 },
],
red: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
green: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
blue: [
{ x: 0, y: 0 },
{ x: 1, y: 0.9 },
],
},
hsl: { hue: [0, 0, 0, 0, 0, 0, 0, 0], sat: [0, 0, 0, 0, 0, 0, 0, 0], lum: [0, 0, 0, 0, 0, 0, 0, 0] },
grading: { shadows: { h: 210, s: 0 }, highlights: { h: 45, s: 0 }, balance: 0 },
sharpen: { amount: 40, radius: 1.4, detail: 30 },
noise: { luminance: 12, detail: 50 },
vignette: { amount: -18, midpoint: 50, feather: 50 },
grain: { amount: 14, size: 30, roughness: 50 },
crop: { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: "original", flipH: false, flipV: false },
};
describe("advanced edit view", () => {
it("ignores photos without an advanced recipe", () => {
expect(advancedEditViewFor(null)).toBeNull();
expect(advancedEditViewFor("")).toBeNull();
expect(advancedEditViewFor("{}")).toBeNull();
expect(advancedEditViewFor("not json")).toBeNull();
});
it("maps the tone and colour sliders onto the quick recipe", () => {
const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify(ADVANCED))!);
expect(seed.exposure).toBe(0.4);
expect(seed.contrast).toBe(26);
expect(seed.highlights).toBe(-12);
expect(seed.whites).toBe(10);
expect(seed.blacks).toBe(-14);
expect(seed.clarity).toBe(16);
expect(seed.temperature).toBe(6);
expect(seed.tint).toBe(-3);
expect(seed.sharpen).toBe(40);
expect(seed.noiseReduction).toBe(12);
expect(seed.vignette).toBe(-18);
expect(seed.grain).toBe(14);
// A black-and-white advanced edit becomes the quick grey conversion.
expect(seed.saturation).toBe(-100);
});
it("samples the advanced master curve with anchors for the quick curve", () => {
const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify(ADVANCED))!);
expect(seed.curves[0].x).toBe(0);
expect(seed.curves[seed.curves.length - 1].x).toBe(1);
// The lifted midtone survives in the sampled curve.
const atMid = seed.curves.reduce((best, point) =>
Math.abs(point.x - 0.5) < Math.abs(best.x - 0.5) ? point : best,
);
expect(atMid.y).toBeGreaterThan(atMid.x);
});
it("lists the settings the quick editor cannot hold", () => {
const view = advancedEditViewFor(JSON.stringify(ADVANCED))!;
expect(view.onlyAdvanced).toEqual(
expect.arrayContaining([
"Texture",
"red black & white filter",
"Sharpening radius and detail",
"Per-channel curves",
]),
);
const flat = view.sections.flatMap((section) => section.items.map((item) => item.label));
expect(flat).toContain("Contrast");
expect(flat).toContain("Black & white");
expect(flat).not.toContain("Dehaze");
});
it("converts rotation and a crop into the quick geometry", () => {
const view = advancedEditViewFor(
JSON.stringify({
crop: { x: 0.1, y: 0, w: 0.8, h: 0.8, angle: 3, quarter: 1, aspect: "1:1", flipH: false, flipV: true },
}),
)!;
expect(view.seed.rotation).toBe(90);
expect(view.seed.straighten).toBe(3);
expect(view.seed.crop.aspect).toBe("1:1");
expect(view.seed.crop.zoom).toBeCloseTo(1.25, 3);
expect(view.onlyAdvanced).toContain("Flip");
expect(view.caveats.length).toBeGreaterThan(0);
});
it("leaves a neutral recipe with the neutral quick adjustments", () => {
const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify({ exposure: 0 }))!);
expect(seed).toEqual(defaultPhotoAdjustments());
});
});
+571
View File
@@ -0,0 +1,571 @@
/**
* Read the advanced (Lumenroom) recipe stored on an event photo.
*
* The two editors are separate applications with separate recipes. This module
* translates the advanced recipe into the quick editor's controls so the photo
* page can show what the advanced editor did, and so a photographer can hand
* the look over to the quick sliders. The translation is deliberately lossy:
* controls the quick editor has no equivalent for are reported instead of being
* silently dropped.
*/
import {
MAX_CURVE_POINTS,
PHOTO_ADJUSTMENT_LIMITS,
createCurveEvaluator,
defaultPhotoAdjustments,
normalizePhotoAdjustments,
type CurvePoint,
type PhotoAdjustments,
type PhotoCropAspect,
type PhotoRotation,
} from "./photo-adjustments";
export interface AdvancedRecipe {
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;
bwFilter: string;
curve: { rgb: CurvePoint[]; red: CurvePoint[]; green: CurvePoint[]; blue: CurvePoint[] };
hsl: { hue: number[]; sat: number[]; lum: number[] };
grading: { shadows: number; highlights: number };
sharpen: { amount: number; radius: number; detail: number };
noise: { luminance: number; detail: number };
vignette: { amount: number; midpoint: number; feather: number };
grain: { amount: number; size: number; roughness: number };
crop: {
x: number;
y: number;
w: number;
h: number;
angle: number;
quarter: number;
aspect: string;
flipH: boolean;
flipV: boolean;
};
}
/** Quick-editor controls that take a single number. */
export type QuickNumericSetting = Exclude<
keyof PhotoAdjustments,
"curves" | "crop" | "rotation"
>;
export interface AdvancedEditItem {
label: string;
value: string;
/** The quick-editor control that shows this setting on its own. */
preview?: { key: QuickNumericSetting; amount: number };
}
export interface AdvancedEditView {
/** Non-neutral settings, grouped for display. */
sections: { title: string; items: AdvancedEditItem[] }[];
/** Settings the quick editor has no control for. */
onlyAdvanced: string[];
/** Notes about values that were mapped approximately. */
caveats: string[];
/** Quick-editor recipe that reproduces the advanced look as closely as possible. */
seed: PhotoAdjustments;
}
const IDENTITY: CurvePoint[] = [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
];
function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value));
}
function round(value: number, places = 2): number {
const factor = 10 ** places;
return Math.round(value * factor) / factor;
}
function num(value: unknown, fallback: number, min: number, max: number): number {
return typeof value === "number" && Number.isFinite(value)
? clamp(value, min, max)
: fallback;
}
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" ? (value as Record<string, unknown>) : {};
}
function curvePoints(value: unknown): CurvePoint[] {
if (!Array.isArray(value)) return IDENTITY;
const points = value
.map((entry) => record(entry))
.filter((entry) => typeof entry.x === "number" && typeof entry.y === "number")
.map((entry) => ({
x: clamp(entry.x as number, 0, 1),
y: clamp(entry.y as number, 0, 1),
}))
.sort((a, b) => a.x - b.x);
return points.length >= 2 ? points : IDENTITY;
}
function bands(value: unknown): number[] {
if (!Array.isArray(value)) return [];
return value
.filter((entry): entry is number => typeof entry === "number" && Number.isFinite(entry))
.map((entry) => round(entry, 1));
}
function isNeutralBandList(values: number[]): boolean {
return values.every((value) => value === 0);
}
export function isIdentityCurve(points: readonly CurvePoint[]): boolean {
if (points.length !== 2) return false;
return (
Math.abs(points[0].x) < 1e-6 &&
Math.abs(points[0].y) < 1e-6 &&
Math.abs(points[1].x - 1) < 1e-6 &&
Math.abs(points[1].y - 1) < 1e-6
);
}
/** Parse the advanced recipe JSON; null when no recipe was saved. */
export function parseAdvancedRecipe(json: string | null | undefined): AdvancedRecipe | null {
if (!json) return null;
let parsed: unknown;
try {
parsed = JSON.parse(json);
} catch {
return null;
}
if (!parsed || typeof parsed !== "object" || Object.keys(parsed).length === 0) {
return null;
}
const raw = parsed as Record<string, unknown>;
const curve = record(raw.curve);
const hsl = record(raw.hsl);
const grading = record(raw.grading);
const gradingShadows = record(grading.shadows);
const gradingHighlights = record(grading.highlights);
const sharpen = record(raw.sharpen);
const noise = record(raw.noise);
const vignette = record(raw.vignette);
const grain = record(raw.grain);
const crop = record(raw.crop);
return {
temp: num(raw.temp, 0, -100, 100),
tint: num(raw.tint, 0, -100, 100),
exposure: num(raw.exposure, 0, -5, 5),
contrast: num(raw.contrast, 0, -100, 100),
highlights: num(raw.highlights, 0, -100, 100),
shadows: num(raw.shadows, 0, -100, 100),
whites: num(raw.whites, 0, -100, 100),
blacks: num(raw.blacks, 0, -100, 100),
texture: num(raw.texture, 0, -100, 100),
clarity: num(raw.clarity, 0, -100, 100),
dehaze: num(raw.dehaze, 0, -100, 100),
vibrance: num(raw.vibrance, 0, -100, 100),
saturation: num(raw.saturation, 0, -100, 100),
bw: raw.bw === true,
bwFilter: typeof raw.bwFilter === "string" ? raw.bwFilter : "none",
curve: {
rgb: curvePoints(curve.rgb),
red: curvePoints(curve.red),
green: curvePoints(curve.green),
blue: curvePoints(curve.blue),
},
hsl: {
hue: bands(hsl.hue),
sat: bands(hsl.sat),
lum: bands(hsl.lum),
},
grading: {
shadows: num(gradingShadows.s, 0, 0, 100),
highlights: num(gradingHighlights.s, 0, 0, 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: num(crop.x, 0, 0, 1),
y: num(crop.y, 0, 0, 1),
w: num(crop.w, 1, 0.02, 1),
h: num(crop.h, 1, 0.02, 1),
angle: num(crop.angle, 0, -45, 45),
quarter: num(crop.quarter, 0, 0, 3),
aspect: typeof crop.aspect === "string" ? crop.aspect : "original",
flipH: crop.flipH === true,
flipV: crop.flipV === true,
},
};
}
/**
* Sample the advanced master curve into the quick editor's format. The quick
* curve requires points at 0 and 1, and the advanced curve may not have them.
*/
function toQuickCurve(points: CurvePoint[]): CurvePoint[] {
if (isIdentityCurve(points)) return IDENTITY;
const padded = [...points];
if (padded[0].x > 1e-6) padded.unshift({ x: 0, y: padded[0].y });
if (padded[padded.length - 1].x < 1 - 1e-6) {
padded.push({ x: 1, y: padded[padded.length - 1].y });
}
const evaluate = createCurveEvaluator(padded);
const count = Math.min(MAX_CURVE_POINTS, Math.max(2, padded.length));
return Array.from({ length: count }, (_, index) => {
const x = count === 1 ? 0 : index / (count - 1);
return { x: round(x, 4), y: round(evaluate(x), 4) };
});
}
const CROP_ASPECT_RATIOS: { aspect: PhotoCropAspect; ratio: number }[] = [
{ aspect: "1:1", ratio: 1 },
{ aspect: "4:5", ratio: 4 / 5 },
{ aspect: "5:4", ratio: 5 / 4 },
{ aspect: "4:3", ratio: 4 / 3 },
{ aspect: "3:4", ratio: 3 / 4 },
{ aspect: "16:9", ratio: 16 / 9 },
{ aspect: "9:16", ratio: 9 / 16 },
];
function closestAspect(width: number, height: number): PhotoCropAspect {
if (width >= 0.999 && height >= 0.999) return "original";
const ratio = width / Math.max(1e-6, height);
let best: PhotoCropAspect = "original";
let bestDelta = Infinity;
for (const option of CROP_ASPECT_RATIOS) {
const delta = Math.abs(ratio - option.ratio) / option.ratio;
if (delta < bestDelta) {
best = option.aspect;
bestDelta = delta;
}
}
return bestDelta <= 0.03 ? best : "original";
}
function isDefaultCrop(crop: AdvancedRecipe["crop"]): boolean {
return (
crop.x === 0 &&
crop.y === 0 &&
crop.w >= 0.999 &&
crop.h >= 0.999 &&
crop.angle === 0 &&
crop.quarter === 0
);
}
/** Map the advanced look onto the quick editor's recipe. */
export function advancedToQuickAdjustments(recipe: AdvancedRecipe): PhotoAdjustments {
const limits = PHOTO_ADJUSTMENT_LIMITS;
const base = defaultPhotoAdjustments();
const quarter = ((Math.round(recipe.crop.quarter) % 4) + 4) % 4;
const zoom = clamp(1 / Math.max(0.02, Math.max(recipe.crop.w, recipe.crop.h)), 1, limits.cropZoom);
const offsetX = clamp(
(recipe.crop.x + recipe.crop.w / 2 - 0.5) / Math.max(1e-6, (1 - recipe.crop.w) / 2),
-1,
1,
);
const offsetY = clamp(
(recipe.crop.y + recipe.crop.h / 2 - 0.5) / Math.max(1e-6, (1 - recipe.crop.h) / 2),
-1,
1,
);
const adjustments: PhotoAdjustments = {
...base,
exposure: round(clamp(recipe.exposure, -limits.exposure, limits.exposure), 2),
contrast: Math.round(recipe.contrast),
shadows: Math.round(recipe.shadows),
highlights: Math.round(recipe.highlights),
whites: Math.round(recipe.whites),
blacks: Math.round(recipe.blacks),
brightness: 0,
clarity: Math.round(recipe.clarity),
dehaze: Math.round(recipe.dehaze),
temperature: Math.round(recipe.temp),
tint: Math.round(recipe.tint),
vibrance: Math.round(recipe.vibrance),
saturation: recipe.bw ? -100 : Math.round(recipe.saturation),
sharpen: Math.round(clamp(recipe.sharpen.amount, 0, limits.sharpen)),
noiseReduction: Math.round(clamp(recipe.noise.luminance, 0, limits.noiseReduction)),
vignette: Math.round(recipe.vignette.amount),
grain: Math.round(clamp(recipe.grain.amount, 0, limits.grain)),
curves: toQuickCurve(recipe.curve.rgb),
rotation: ((quarter * 90) % 360) as PhotoRotation,
straighten: round(clamp(recipe.crop.angle, -limits.straighten, limits.straighten), 2),
crop: {
aspect: closestAspect(recipe.crop.w, recipe.crop.h),
zoom: round(zoom, 3),
offsetX: round(offsetX, 3),
offsetY: round(offsetY, 3),
},
};
return normalizePhotoAdjustments(adjustments) ?? base;
}
function signed(value: number, suffix = ""): string {
return `${value > 0 ? "+" : ""}${value}${suffix}`;
}
function identityAll(curves: AdvancedRecipe["curve"]): boolean {
return (
isIdentityCurve(curves.rgb) &&
isIdentityCurve(curves.red) &&
isIdentityCurve(curves.green) &&
isIdentityCurve(curves.blue)
);
}
const BW_FILTER_NAMES: Record<string, string> = {
yellow: "yellow",
orange: "orange",
red: "red",
green: "green",
blue: "blue",
};
/** Build the read-only summary and the quick-editor seed for a stored recipe. */
export function advancedEditViewFor(
json: string | null | undefined,
): AdvancedEditView | null {
const recipe = parseAdvancedRecipe(json);
if (!recipe) return null;
const light: AdvancedEditItem[] = [];
const color: AdvancedEditItem[] = [];
const detail: AdvancedEditItem[] = [];
const geometry: AdvancedEditItem[] = [];
if (recipe.exposure !== 0) {
light.push({
label: "Exposure",
value: signed(recipe.exposure, " EV"),
preview: { key: "exposure", amount: recipe.exposure },
});
}
if (recipe.contrast !== 0) {
light.push({
label: "Contrast",
value: signed(recipe.contrast),
preview: { key: "contrast", amount: recipe.contrast },
});
}
if (recipe.highlights !== 0) {
light.push({
label: "Highlights",
value: signed(recipe.highlights),
preview: { key: "highlights", amount: recipe.highlights },
});
}
if (recipe.shadows !== 0) {
light.push({
label: "Shadows",
value: signed(recipe.shadows),
preview: { key: "shadows", amount: recipe.shadows },
});
}
if (recipe.whites !== 0) {
light.push({
label: "Whites",
value: signed(recipe.whites),
preview: { key: "whites", amount: recipe.whites },
});
}
if (recipe.blacks !== 0) {
light.push({
label: "Blacks",
value: signed(recipe.blacks),
preview: { key: "blacks", amount: recipe.blacks },
});
}
if (recipe.texture !== 0) light.push({ label: "Texture", value: signed(recipe.texture) });
if (recipe.clarity !== 0) {
light.push({
label: "Clarity",
value: signed(recipe.clarity),
preview: { key: "clarity", amount: recipe.clarity },
});
}
if (recipe.dehaze !== 0) {
light.push({
label: "Dehaze",
value: signed(recipe.dehaze),
preview: { key: "dehaze", amount: recipe.dehaze },
});
}
if (recipe.temp !== 0) {
color.push({
label: "Temperature",
value: signed(recipe.temp),
preview: { key: "temperature", amount: recipe.temp },
});
}
if (recipe.tint !== 0) {
color.push({
label: "Tint",
value: signed(recipe.tint),
preview: { key: "tint", amount: recipe.tint },
});
}
if (recipe.bw) {
color.push({
label: "Black & white",
value: "On",
preview: { key: "saturation", amount: -100 },
});
}
if (recipe.vibrance !== 0) {
color.push({
label: "Vibrance",
value: signed(recipe.vibrance),
preview: { key: "vibrance", amount: recipe.vibrance },
});
}
if (recipe.saturation !== 0) {
color.push({
label: "Saturation",
value: signed(recipe.saturation),
preview: { key: "saturation", amount: recipe.saturation },
});
}
if (!identityAll(recipe.curve)) color.push({ label: "Curve", value: "Edited" });
if (!isNeutralBandList(recipe.hsl.hue) || !isNeutralBandList(recipe.hsl.sat) || !isNeutralBandList(recipe.hsl.lum)) {
color.push({ label: "Colour mixer", value: "Edited" });
}
if (recipe.grading.shadows > 0 || recipe.grading.highlights > 0) {
color.push({ label: "Colour grading", value: "On" });
}
if (recipe.sharpen.amount !== 0) {
detail.push({
label: "Sharpen",
value: String(recipe.sharpen.amount),
preview: { key: "sharpen", amount: recipe.sharpen.amount },
});
}
if (recipe.noise.luminance !== 0) {
detail.push({
label: "Noise reduction",
value: String(recipe.noise.luminance),
preview: { key: "noiseReduction", amount: recipe.noise.luminance },
});
}
if (recipe.vignette.amount !== 0) {
detail.push({
label: "Vignette",
value: signed(recipe.vignette.amount),
preview: { key: "vignette", amount: recipe.vignette.amount },
});
}
if (recipe.grain.amount !== 0) {
detail.push({
label: "Grain",
value: String(recipe.grain.amount),
preview: { key: "grain", amount: recipe.grain.amount },
});
}
if (!isDefaultCrop(recipe.crop)) {
if (recipe.crop.quarter !== 0) {
geometry.push({ label: "Rotate", value: `${Math.round(recipe.crop.quarter) * 90}°` });
}
if (recipe.crop.angle !== 0) {
geometry.push({ label: "Straighten", value: signed(round(recipe.crop.angle, 1), "°") });
}
if (recipe.crop.w < 0.999 || recipe.crop.h < 0.999) {
geometry.push({
label: "Crop",
value: `${Math.round(recipe.crop.w * 100)}% × ${Math.round(recipe.crop.h * 100)}%`,
});
}
if (recipe.crop.flipH || recipe.crop.flipV) {
geometry.push({
label: "Flip",
value: recipe.crop.flipH && recipe.crop.flipV ? "Both" : recipe.crop.flipH ? "Horizontal" : "Vertical",
});
}
}
const onlyAdvanced: string[] = [];
if (recipe.texture !== 0) onlyAdvanced.push("Texture");
if (recipe.bw && recipe.bwFilter !== "none") {
onlyAdvanced.push(`${BW_FILTER_NAMES[recipe.bwFilter] ?? "Coloured"} black & white filter`);
}
if (recipe.sharpen.radius !== 1 || recipe.sharpen.detail !== 25) {
onlyAdvanced.push("Sharpening radius and detail");
}
if (recipe.noise.detail !== 50) onlyAdvanced.push("Noise detail");
if (recipe.vignette.midpoint !== 50 || recipe.vignette.feather !== 50) {
onlyAdvanced.push("Vignette midpoint and feather");
}
if (recipe.grain.size !== 25 || recipe.grain.roughness !== 50) {
onlyAdvanced.push("Grain size and roughness");
}
if (!isNeutralBandList(recipe.hsl.hue) || !isNeutralBandList(recipe.hsl.sat) || !isNeutralBandList(recipe.hsl.lum)) {
onlyAdvanced.push("Colour mixer");
}
if (recipe.grading.shadows > 0 || recipe.grading.highlights > 0) {
onlyAdvanced.push("Colour grading");
}
if (
!isIdentityCurve(recipe.curve.red) ||
!isIdentityCurve(recipe.curve.green) ||
!isIdentityCurve(recipe.curve.blue)
) {
onlyAdvanced.push("Per-channel curves");
}
if (recipe.crop.flipH || recipe.crop.flipV) onlyAdvanced.push("Flip");
const caveats: string[] = [];
if (recipe.crop.w < 0.999 || recipe.crop.h < 0.999) {
caveats.push("The crop becomes the closest quick-editor aspect and zoom; nudge it to match exactly.");
}
if (Math.abs(recipe.crop.angle) > PHOTO_ADJUSTMENT_LIMITS.straighten) {
caveats.push(`Straighten is limited to ±${PHOTO_ADJUSTMENT_LIMITS.straighten}° here.`);
}
const sections = [
{ title: "Light", items: light },
{ title: "Colour", items: color },
{ title: "Detail", items: detail },
{ title: "Crop", items: geometry },
].filter((section) => section.items.length > 0);
return {
sections,
onlyAdvanced,
caveats,
seed: advancedToQuickAdjustments(recipe),
};
}
+14 -2
View File
@@ -24,6 +24,12 @@ export interface BridgeTokenPayload {
kind: "login" | "service";
/** Unix seconds. */
exp: number;
/**
* Browser-facing URL to return to after editing. Captured from the request
* that opened the editor, because the server-to-server origin is not the
* address the user's browser used.
*/
ret?: string;
}
export const BRIDGE_LOGIN_TTL_SECONDS = 10 * 60;
@@ -108,9 +114,15 @@ export function verifyBridgeToken(
return payload as BridgeTokenPayload;
}
/** Where the advanced editor sends a user back to after finishing. */
/**
* Where the advanced editor sends a user back to after finishing. Prefer the
* configured public origin; `NEXTAUTH_URL` is only a fallback because compose
* defaults it to localhost.
*/
export function bridgeReturnUrl(eventId: string): string | null {
const origin = process.env.NEXTAUTH_URL?.trim();
const origin = (
process.env.PUBLIC_ORIGIN?.trim() || process.env.NEXTAUTH_URL?.trim()
);
if (!origin) return null;
return `${origin.replace(/\/+$/, "")}/events/${eventId}`;
}
+26
View File
@@ -160,6 +160,19 @@ export function editedStoredNameForEventPhoto(
return `events/${eventId}/edits/${photoId}.jpg`;
}
/**
* The advanced editor's own render. Kept apart from the final edited JPEG so
* the simple editor can layer its adjustments on top without compounding
* renders, and so re-saving in either editor keeps the other's work.
*/
export function advancedStoredNameForEventPhoto(
eventId: string,
photoId: string,
): string {
assertEventPhotoIds(eventId, photoId);
return `events/${eventId}/edits/${photoId}-advanced.jpg`;
}
/** Lazily generated small grid thumbnail of the untouched original. */
export function thumbStoredNameForEventPhoto(
eventId: string,
@@ -196,6 +209,19 @@ export function bridgeThumbStoredNameForEventPhoto(
return `events/${eventId}/previews/${photoId}-bridge-thumb.jpg`;
}
/**
* Cached grid thumbnail of a photo's saved edit. Kept apart from the original
* thumbnail so the editor can reopen either, and refreshed whenever the edited
* JPEG is re-rendered.
*/
export function bridgeEditedThumbStoredNameForEventPhoto(
eventId: string,
photoId: string,
): string {
assertEventPhotoIds(eventId, photoId);
return `events/${eventId}/previews/${photoId}-bridge-thumb-edited.jpg`;
}
function assertEventPhotoIds(eventId: string, photoId: string): void {
const safeId = /^[A-Za-z0-9_-]+$/;
if (!safeId.test(eventId) || !safeId.test(photoId)) {
+115 -1
View File
@@ -10,13 +10,14 @@
*/
import { execFile } from "node:child_process";
import { mkdtemp, rm } from "node:fs/promises";
import { mkdtemp, readdir, rm, symlink } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import sharp from "sharp";
import {
applyPhotoAdjustmentsToRgba,
defaultPhotoAdjustments,
type PhotoAdjustments,
} from "./photo-adjustments";
import { cropInterleavedRgb, cropRectForCanvas } from "./photo-geometry";
@@ -90,6 +91,119 @@ export interface RenderedPhoto {
height: number;
}
/**
* Cameras store one or more JPEG previews inside every RAW file; a full-size
* NEF preview is a ~1 MB JPEG written next to the symlink by exiv2 in about
* 10 ms. That is roughly seventy times faster than demosaicing the sensor data
* for a 640 px tile, so thumbnails try the preview first and only fall back to
* LibRaw when the camera embedded nothing big enough.
*/
async function extractEmbeddedPreview(
filePath: string,
minDimension: number,
): Promise<{ path: string; cleanup: () => Promise<void> } | null> {
const directory = await mkdtemp(path.join(tmpdir(), "glenloch-preview-"));
const cleanup = () => rm(directory, { recursive: true, force: true });
const link = path.join(
directory,
`source${path.extname(filePath) || ".raw"}`,
);
try {
// exiv2 writes the previews beside the file it is given. A symlink keeps
// the original (read-only) untouched and the output in the temp directory.
await symlink(filePath, link);
// A non-zero exit is normal when some embedded preview cannot be re-encoded
// (for example a TIFF thumbnail); the files that did land are inspected.
await execFileAsync("exiv2", ["-ep", link], { timeout: 30_000 }).catch(
() => undefined,
);
let best: { path: string; longEdge: number } | undefined;
for (const entry of await readdir(directory)) {
if (!/-preview\d+\.jpe?g$/i.test(entry)) continue;
const candidate = path.join(directory, entry);
try {
const metadata = await sharp(candidate, { failOn: "none" }).metadata();
const longEdge = Math.max(metadata.width ?? 0, metadata.height ?? 0);
if (longEdge < minDimension) continue;
if (!best || longEdge > best.longEdge) best = { path: candidate, longEdge };
} catch {
// Not a readable JPEG; try the next preview.
}
}
if (!best) {
await cleanup().catch(() => undefined);
return null;
}
return { path: best.path, cleanup };
} catch {
await cleanup().catch(() => undefined);
return null;
}
}
/**
* Small grid thumbnail. RAW files use the camera's embedded preview when it is
* large enough; everything else (and RAW files without one) goes through the
* regular render pipeline.
*/
export async function renderPhotoThumbnail(input: {
filePath: string;
kind: "raw" | "image";
maxDimension: number;
quality?: number;
}): Promise<Buffer> {
if (input.kind === "raw") {
const preview = await extractEmbeddedPreview(
input.filePath,
input.maxDimension,
);
if (preview) {
try {
return await sharp(preview.path, {
failOn: "none",
limitInputPixels: 500_000_000,
})
.autoOrient()
.toColourspace("srgb")
.resize({
width: input.maxDimension,
height: input.maxDimension,
fit: "inside",
withoutEnlargement: true,
})
.jpeg({ quality: input.quality ?? 72, mozjpeg: true })
.toBuffer();
} finally {
await preview.cleanup().catch(() => undefined);
}
}
}
if (input.kind === "image") {
return sharp(input.filePath, { failOn: "none", limitInputPixels: 500_000_000 })
.autoOrient()
.resize({
width: input.maxDimension,
height: input.maxDimension,
fit: "inside",
withoutEnlargement: true,
})
.jpeg({ quality: input.quality ?? 72 })
.toBuffer();
}
const rendered = await renderPhotoJpeg({
filePath: input.filePath,
kind: input.kind,
adjustments: defaultPhotoAdjustments(),
maxDimension: input.maxDimension,
});
return rendered.data;
}
/** Source dimensions after applying the EXIF orientation the browser sees. */
async function orientedDimensions(
filePath: string,