diff --git a/.env.example b/.env.example index 143315e..4c22ebd 100644 --- a/.env.example +++ b/.env.example @@ -94,5 +94,12 @@ 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. +LUMENROOM_URL= +BRIDGE_SECRET= + # Observability (declared; no Sentry integration is wired yet) SENTRY_DSN= diff --git a/.gitignore b/.gitignore index 5dba376..82ec281 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,11 @@ # dependencies /node_modules +/lumenroom/node_modules + +# vendored advanced editor build output and local catalog data +/lumenroom/dist +/lumenroom/server/data /.pnp .pnp.* .yarn/* diff --git a/README.md b/README.md index 7b9ac4f..dd28deb 100644 --- a/README.md +++ b/README.md @@ -594,6 +594,86 @@ git switch main - [ ] Media storage share configured in Settings → Media storage and writable (required for event photos and videos). - [ ] The `/api/dev/*` prefix is historical: the guards, not the URL, are the security boundary. +### 15. Advanced photo editor bridge (optional) + +Event photos can also be opened in a separate Lumenroom deployment for a much +deeper develop module (WebGL2 tone/colour pipeline, HSL mixer, split toning, +per-channel curves, texture/dehaze/grain, history and presets). The simple +editor stays the default; the advanced one is reached from the photo editor's +**Advanced** button. + +The two apps never share a database. The dashboard opens a scoped bridge +session, sends the browser to Lumenroom with a short-lived signed token, and +Lumenroom mirrors the event's photo list. Photo bytes are proxied on demand, so +nothing is copied at login; the imported event is temporary and is deleted when +that bridge session expires (12 hours by default). + +**One deployment.** Lumenroom is vendored under `lumenroom/`, and +`docker-compose.yml` builds it as a second service next to the app. One clone +and one command deploy both: + +```bash +docker compose up -d --build +``` + +Values in `.env` (all optional except the secret): + +```dotenv +# Browser-facing URL of the editor. Users' devices must reach it. +LUMENROOM_URL=http://:8787 +# One long random string, shared by both services. +BRIDGE_SECRET=<64+ random characters> +# Optional tuning +# GLENLOCH_URL=http://app:3000 # internal; the service default +# LUMENROOM_PORT=8787 +# LUMENROOM_BIND=0.0.0.0 # set 127.0.0.1 behind a proxy +# LUMENROOM_BRIDGE_TTL_HOURS=12 +# LUMENROOM_INVITE=our-team +``` + +`BRIDGE_SECRET` only signs bridge tokens; it is never sent to the browser as a +credential. The token minted when you click **Advanced** expires in 10 minutes +and is scoped to one user and one event. With `BRIDGE_SECRET` empty the button +is visible but reports that the editor is not configured. + +`GLENLOCH_URL` is server-to-server inside the Compose network (default +`http://app:3000`), so it needs no TLS. `LUMENROOM_URL` is different: the user's +browser is redirected there, so it must be a reachable address — the host's LAN +IP for a local stack, or an HTTPS hostname in production. + +**Reverse proxy.** Lumenroom's UI fetches `/api/...` from the root of its own +origin, so give it a hostname, not a path prefix: + +```caddy +edit.example.org { + reverse_proxy lumenroom:8787 +} +``` + +Then set `LUMENROOM_URL=https://edit.example.org` and +`LUMENROOM_BIND=127.0.0.1`. Putting both apps on the same site +(`media.example.org`, `edit.example.org`) keeps the redirect and its cookie +first-party. + +**Data.** `lumenroom` keeps only temporary bridge data in the `lumenroom-data` +volume (SQLite catalog, cached previews and thumbnails); originals stay on the +media share and the edited JPEGs are written back there. That volume can be +left out of backups. To run the editor on its own instead, its +`lumenroom/docker-compose.yml` still works standalone. + +**How it behaves.** Clicking **Advanced** in the photo editor opens the same +event in Lumenroom already signed in — no second password. Lumenroom shows a +banner with **Save to event** (renders the open photo at full size and stores it +as the event photo's edited JPEG, so thumbnails, delivery exports and the +`variant=edited` viewer use it) and **Back to dashboard**. Photos remain on the +media share; only the temporary catalog rows, thumbnails and previews live in +Lumenroom's data volume. RAW files get a 4000 px JPEG proxy generated by the dashboard's +RAW decoder (cached in Lumenroom) instead of the simple editor's 1800 px +preview, so advanced RAW exports are larger than the simple editor's. +The advanced recipe is stored in `event_photos.advanced_edit_json`, separate from +the simple editor's recipe; saving in either editor replaces the generated JPEG +that the gallery shows. + ## Project structure ```text @@ -602,6 +682,7 @@ git switch main ├── docs/ Product spec, architecture, build plan, current state ├── drizzle/ Migrations, snapshots, journal ├── e2e/ Playwright specs and shared helpers +├── lumenroom/ Advanced photo editor (Vite + Node), built by compose ├── public/ Static assets ├── src/ │ ├── app/ Pages, layouts, API route handlers diff --git a/docker-compose.yml b/docker-compose.yml index ff9b5ff..4c3d389 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -62,6 +62,12 @@ services: # as media storage once the app checks the configured share. ARCHIVE_DIR: /archive NFS_SHARE: ${NFS_SHARE:-} + # Advanced-editor bridge. Both must be set for "Advanced" in the photo + # editor to work; the secret must match Lumenroom's BRIDGE_SECRET. + BRIDGE_SECRET: ${BRIDGE_SECRET:-} + # Browser-facing URL of the vendored Lumenroom service below. On a LAN + # that is http://:8787; behind TLS use https://edit.example.org. + LUMENROOM_URL: ${LUMENROOM_URL:-http://localhost:8787} volumes: - outbox-data:/tmp/outbox - uploads-data:/tmp/uploads @@ -85,6 +91,35 @@ services: max-file: "3" restart: unless-stopped + # Advanced photo editor (Lumenroom), vendored under ./lumenroom so one clone + # and one `docker compose up -d --build` deploys both apps. Its catalog is + # temporary bridge data; originals stay on the app's media storage. + lumenroom: + build: + context: ./lumenroom + dockerfile: Dockerfile + environment: + NODE_ENV: production + # Internal address: only Lumenroom's server calls the dashboard. + GLENLOCH_URL: ${GLENLOCH_URL:-http://app:3000} + # Must match the app's BRIDGE_SECRET, or "Advanced" fails to sign in. + BRIDGE_SECRET: ${BRIDGE_SECRET:-} + LUMENROOM_BRIDGE_TTL_HOURS: ${LUMENROOM_BRIDGE_TTL_HOURS:-12} + LUMENROOM_INVITE: ${LUMENROOM_INVITE:-} + LUMENROOM_RAW_WORKERS: ${LUMENROOM_RAW_WORKERS:-4} + volumes: + # SQLite catalog, cached previews and thumbnails (safe to lose). + - lumenroom-data:/data + ports: + # The browser must reach this directly. Put it behind the same reverse + # proxy and bind it to loopback there, e.g. LUMENROOM_BIND=127.0.0.1. + - "${LUMENROOM_BIND:-0.0.0.0}:${LUMENROOM_PORT:-8787}:8787" + logging: + options: + max-size: "10m" + max-file: "3" + restart: unless-stopped + db: image: postgres:16-alpine environment: @@ -125,3 +160,4 @@ volumes: outbox-data: uploads-data: archive-data: + lumenroom-data: diff --git a/drizzle/0022_fixed_squadron_supreme.sql b/drizzle/0022_fixed_squadron_supreme.sql new file mode 100644 index 0000000..cd81f8b --- /dev/null +++ b/drizzle/0022_fixed_squadron_supreme.sql @@ -0,0 +1,12 @@ +CREATE TABLE "bridge_sessions" ( + "id" text PRIMARY KEY NOT NULL, + "user_id" text NOT NULL, + "event_id" text NOT NULL, + "expires_at" timestamp with time zone NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "event_photos" ADD COLUMN "advanced_edit_json" text;--> statement-breakpoint +ALTER TABLE "bridge_sessions" ADD CONSTRAINT "bridge_sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "bridge_sessions" ADD CONSTRAINT "bridge_sessions_event_id_events_id_fk" FOREIGN KEY ("event_id") REFERENCES "public"."events"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "bridge_sessions_event_idx" ON "bridge_sessions" USING btree ("event_id"); \ No newline at end of file diff --git a/drizzle/meta/0022_snapshot.json b/drizzle/meta/0022_snapshot.json new file mode 100644 index 0000000..63be412 --- /dev/null +++ b/drizzle/meta/0022_snapshot.json @@ -0,0 +1,4891 @@ +{ + "id": "c7302dfd-ebb7-4d72-8cc7-fa900b7a4c58", + "prevId": "561f3bde-9a83-4c13-aafc-1601409119d3", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "published": { + "name": "published", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "announcements_published_created_idx": { + "name": "announcements_published_created_idx", + "columns": [ + { + "expression": "published", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "announcements_created_by_users_id_fk": { + "name": "announcements_created_by_users_id_fk", + "tableFrom": "announcements", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_settings": { + "name": "app_settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.assignments": { + "name": "assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slot_id": { + "name": "slot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'proposed'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "responded_at": { + "name": "responded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confirmed_via": { + "name": "confirmed_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_count": { + "name": "reminder_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "uq_active_assignment": { + "name": "uq_active_assignment", + "columns": [ + { + "expression": "slot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"assignments\".\"status\" IN ('proposed','confirmed','completed')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "assignments_user_idx": { + "name": "assignments_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assignments_slot_id_slots_id_fk": { + "name": "assignments_slot_id_slots_id_fk", + "tableFrom": "assignments", + "tableTo": "slots", + "columnsFrom": [ + "slot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assignments_user_id_users_id_fk": { + "name": "assignments_user_id_users_id_fk", + "tableFrom": "assignments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_log": { + "name": "audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_ip_hash": { + "name": "actor_ip_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "before_json": { + "name": "before_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "after_json": { + "name": "after_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_log_created_idx": { + "name": "audit_log_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.bridge_sessions": { + "name": "bridge_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "bridge_sessions_event_idx": { + "name": "bridge_sessions_event_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "bridge_sessions_user_id_users_id_fk": { + "name": "bridge_sessions_user_id_users_id_fk", + "tableFrom": "bridge_sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "bridge_sessions_event_id_events_id_fk": { + "name": "bridge_sessions_event_id_events_id_fk", + "tableFrom": "bridge_sessions", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.coverage_intakes": { + "name": "coverage_intakes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "requester_name": { + "name": "requester_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requester_email": { + "name": "requester_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requester_phone": { + "name": "requester_phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ministry": { + "name": "ministry", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'coverage'" + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'new'" + }, + "created_event_id": { + "name": "created_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reviewed_by": { + "name": "reviewed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "coverage_intakes_status_idx": { + "name": "coverage_intakes_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "coverage_intakes_starts_idx": { + "name": "coverage_intakes_starts_idx", + "columns": [ + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "coverage_intakes_created_event_id_events_id_fk": { + "name": "coverage_intakes_created_event_id_events_id_fk", + "tableFrom": "coverage_intakes", + "tableTo": "events", + "columnsFrom": [ + "created_event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "coverage_intakes_reviewed_by_users_id_fk": { + "name": "coverage_intakes_reviewed_by_users_id_fk", + "tableFrom": "coverage_intakes", + "tableTo": "users", + "columnsFrom": [ + "reviewed_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.coverage_requests": { + "name": "coverage_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "assignment_id": { + "name": "assignment_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "replacement_user_id": { + "name": "replacement_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_by": { + "name": "resolved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "coverage_requests_pending_assignment_idx": { + "name": "coverage_requests_pending_assignment_idx", + "columns": [ + { + "expression": "assignment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"coverage_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "coverage_requests_status_idx": { + "name": "coverage_requests_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "coverage_requests_requester_idx": { + "name": "coverage_requests_requester_idx", + "columns": [ + { + "expression": "requested_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "coverage_requests_assignment_id_assignments_id_fk": { + "name": "coverage_requests_assignment_id_assignments_id_fk", + "tableFrom": "coverage_requests", + "tableTo": "assignments", + "columnsFrom": [ + "assignment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "coverage_requests_requested_by_users_id_fk": { + "name": "coverage_requests_requested_by_users_id_fk", + "tableFrom": "coverage_requests", + "tableTo": "users", + "columnsFrom": [ + "requested_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "coverage_requests_replacement_user_id_users_id_fk": { + "name": "coverage_requests_replacement_user_id_users_id_fk", + "tableFrom": "coverage_requests", + "tableTo": "users", + "columnsFrom": [ + "replacement_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "coverage_requests_resolved_by_users_id_fk": { + "name": "coverage_requests_resolved_by_users_id_fk", + "tableFrom": "coverage_requests", + "tableTo": "users", + "columnsFrom": [ + "resolved_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_folders": { + "name": "event_folders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'originals'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_folders_event_name_idx": { + "name": "event_folders_event_name_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_folders_event_idx": { + "name": "event_folders_event_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_folders_event_id_events_id_fk": { + "name": "event_folders_event_id_events_id_fk", + "tableFrom": "event_folders", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "event_folders_created_by_users_id_fk": { + "name": "event_folders_created_by_users_id_fk", + "tableFrom": "event_folders", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_photographers": { + "name": "event_photographers", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'photographer'" + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_photographers_user_idx": { + "name": "event_photographers_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_photographers_event_id_events_id_fk": { + "name": "event_photographers_event_id_events_id_fk", + "tableFrom": "event_photographers", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "event_photographers_user_id_users_id_fk": { + "name": "event_photographers_user_id_users_id_fk", + "tableFrom": "event_photographers", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "event_photographers_assigned_by_users_id_fk": { + "name": "event_photographers_assigned_by_users_id_fk", + "tableFrom": "event_photographers", + "tableTo": "users", + "columnsFrom": [ + "assigned_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_photographers_pk": { + "name": "event_photographers_pk", + "columns": [ + "event_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_photos": { + "name": "event_photos", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uploader_id": { + "name": "uploader_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "stored_name": { + "name": "stored_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checksum_sha256": { + "name": "checksum_sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "edit_json": { + "name": "edit_json", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "advanced_edit_json": { + "name": "advanced_edit_json", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "edited_stored_name": { + "name": "edited_stored_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "edited_size_bytes": { + "name": "edited_size_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "edited_at": { + "name": "edited_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "edited_by": { + "name": "edited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_photos_folder_checksum_idx": { + "name": "event_photos_folder_checksum_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "checksum_sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_photos_folder_idx": { + "name": "event_photos_folder_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_photos_folder_id_event_folders_id_fk": { + "name": "event_photos_folder_id_event_folders_id_fk", + "tableFrom": "event_photos", + "tableTo": "event_folders", + "columnsFrom": [ + "folder_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "event_photos_uploader_id_users_id_fk": { + "name": "event_photos_uploader_id_users_id_fk", + "tableFrom": "event_photos", + "tableTo": "users", + "columnsFrom": [ + "uploader_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "event_photos_edited_by_users_id_fk": { + "name": "event_photos_edited_by_users_id_fk", + "tableFrom": "event_photos", + "tableTo": "users", + "columnsFrom": [ + "edited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "event_photos_stored_name_unique": { + "name": "event_photos_stored_name_unique", + "nullsNotDistinct": false, + "columns": [ + "stored_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_videos": { + "name": "event_videos", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uploader_id": { + "name": "uploader_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "checksum_sha256": { + "name": "checksum_sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "original_stored_name": { + "name": "original_stored_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "archive_folder": { + "name": "archive_folder", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "trim_start_ms": { + "name": "trim_start_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "trim_end_ms": { + "name": "trim_end_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "web_stored_name": { + "name": "web_stored_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "poster_stored_name": { + "name": "poster_stored_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'processing'" + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'team'" + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_videos_event_checksum_idx": { + "name": "event_videos_event_checksum_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "checksum_sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_videos_event_created_idx": { + "name": "event_videos_event_created_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_videos_status_idx": { + "name": "event_videos_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_videos_event_id_events_id_fk": { + "name": "event_videos_event_id_events_id_fk", + "tableFrom": "event_videos", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "event_videos_uploader_id_users_id_fk": { + "name": "event_videos_uploader_id_users_id_fk", + "tableFrom": "event_videos", + "tableTo": "users", + "columnsFrom": [ + "uploader_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "event_videos_original_stored_name_unique": { + "name": "event_videos_original_stored_name_unique", + "nullsNotDistinct": false, + "columns": [ + "original_stored_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'photoshoot'" + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "events_starts_at_idx": { + "name": "events_starts_at_idx", + "columns": [ + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "events_created_by_idx": { + "name": "events_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "events_created_by_users_id_fk": { + "name": "events_created_by_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.functions": { + "name": "functions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "functions_slug_idx": { + "name": "functions_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "functions_active_idx": { + "name": "functions_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "functions_category_idx": { + "name": "functions_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "functions_category_id_skill_categories_id_fk": { + "name": "functions_category_id_skill_categories_id_fk", + "tableFrom": "functions", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "functions_slug_unique": { + "name": "functions_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.growth_goals": { + "name": "growth_goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_level": { + "name": "target_level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_date": { + "name": "target_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'requested'" + }, + "mentor_user_id": { + "name": "mentor_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "shadow_count": { + "name": "shadow_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "growth_goals_user_skill_idx": { + "name": "growth_goals_user_skill_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "growth_goals_status_idx": { + "name": "growth_goals_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "growth_goals_user_id_users_id_fk": { + "name": "growth_goals_user_id_users_id_fk", + "tableFrom": "growth_goals", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "growth_goals_skill_id_skills_id_fk": { + "name": "growth_goals_skill_id_skills_id_fk", + "tableFrom": "growth_goals", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "growth_goals_mentor_user_id_users_id_fk": { + "name": "growth_goals_mentor_user_id_users_id_fk", + "tableFrom": "growth_goals", + "tableTo": "users", + "columnsFrom": [ + "mentor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notification_preferences": { + "name": "notification_preferences", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email_enabled": { + "name": "email_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "sms_enabled": { + "name": "sms_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sms_consent_at": { + "name": "sms_consent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sms_consent_source": { + "name": "sms_consent_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sms_consent_ip": { + "name": "sms_consent_ip", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_lead_days": { + "name": "reminder_lead_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 7 + }, + "quiet_hours_start": { + "name": "quiet_hours_start", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'21:00'" + }, + "quiet_hours_end": { + "name": "quiet_hours_end", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'08:00'" + }, + "digest_only": { + "name": "digest_only", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": {}, + "foreignKeys": { + "notification_preferences_user_id_users_id_fk": { + "name": "notification_preferences_user_id_users_id_fk", + "tableFrom": "notification_preferences", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notification_rules": { + "name": "notification_rules", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event": { + "name": "event", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'assignment.created'" + }, + "offset_days": { + "name": "offset_days", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "send_at_local_time": { + "name": "send_at_local_time", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'09:00'" + }, + "channel_set": { + "name": "channel_set", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'email'" + }, + "applies_to_service_id": { + "name": "applies_to_service_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "notification_rules_active_idx": { + "name": "notification_rules_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "notification_rules_applies_to_service_id_services_id_fk": { + "name": "notification_rules_applies_to_service_id_services_id_fk", + "tableFrom": "notification_rules", + "tableTo": "services", + "columnsFrom": [ + "applies_to_service_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "notification_rules_key_unique": { + "name": "notification_rules_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": { + "chk_notification_rules_channel": { + "name": "chk_notification_rules_channel", + "value": "\"notification_rules\".\"channel_set\" IN ('email','sms','email+sms')" + } + }, + "isRLSEnabled": false + }, + "public.notifications": { + "name": "notifications", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'email'" + }, + "template_key": { + "name": "template_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rule_key": { + "name": "rule_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assignment_id": { + "name": "assignment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "slot_id": { + "name": "slot_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "to_address": { + "name": "to_address", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_status": { + "name": "provider_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "notifications_status_scheduled_idx": { + "name": "notifications_status_scheduled_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scheduled_for", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "notifications_user_idx": { + "name": "notifications_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "notifications_assignment_idx": { + "name": "notifications_assignment_idx", + "columns": [ + { + "expression": "assignment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "notifications_user_id_users_id_fk": { + "name": "notifications_user_id_users_id_fk", + "tableFrom": "notifications", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "notifications_assignment_id_assignments_id_fk": { + "name": "notifications_assignment_id_assignments_id_fk", + "tableFrom": "notifications", + "tableTo": "assignments", + "columnsFrom": [ + "assignment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "notifications_slot_id_slots_id_fk": { + "name": "notifications_slot_id_slots_id_fk", + "tableFrom": "notifications", + "tableTo": "slots", + "columnsFrom": [ + "slot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "notifications_dedupe_key_unique": { + "name": "notifications_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.position_skills": { + "name": "position_skills", + "schema": "", + "columns": { + "position_id": { + "name": "position_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "weight": { + "name": "weight", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "required_level": { + "name": "required_level", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_core": { + "name": "is_core", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "position_skills_skill_idx": { + "name": "position_skills_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "position_skills_position_id_roles_id_fk": { + "name": "position_skills_position_id_roles_id_fk", + "tableFrom": "position_skills", + "tableTo": "roles", + "columnsFrom": [ + "position_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "position_skills_skill_id_skills_id_fk": { + "name": "position_skills_skill_id_skills_id_fk", + "tableFrom": "position_skills", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "position_skills_pk": { + "name": "position_skills_pk", + "columns": [ + "position_id", + "skill_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.roles": { + "name": "roles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "call_time_offset_minutes": { + "name": "call_time_offset_minutes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "requires_certification": { + "name": "requires_certification", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "default_headcount": { + "name": "default_headcount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "roles_slug_idx": { + "name": "roles_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "roles_active_idx": { + "name": "roles_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "roles_slug_unique": { + "name": "roles_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.run_sheet_items": { + "name": "run_sheet_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "time_label": { + "name": "time_label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner": { + "name": "owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "run_sheet_items_instance_idx": { + "name": "run_sheet_items_instance_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "run_sheet_items_service_instance_id_service_instances_id_fk": { + "name": "run_sheet_items_service_instance_id_service_instances_id_fk", + "tableFrom": "run_sheet_items", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_checklist_items": { + "name": "service_checklist_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pre'" + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "done_at": { + "name": "done_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "done_by": { + "name": "done_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "service_checklist_instance_label_idx": { + "name": "service_checklist_instance_label_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "phase", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "label", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "service_checklist_instance_idx": { + "name": "service_checklist_instance_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "phase", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "service_checklist_items_service_instance_id_service_instances_id_fk": { + "name": "service_checklist_items_service_instance_id_service_instances_id_fk", + "tableFrom": "service_checklist_items", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "service_checklist_items_done_by_users_id_fk": { + "name": "service_checklist_items_done_by_users_id_fk", + "tableFrom": "service_checklist_items", + "tableTo": "users", + "columnsFrom": [ + "done_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_instances": { + "name": "service_instances", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_id": { + "name": "service_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "occurs_on": { + "name": "occurs_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_special": { + "name": "is_special", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "title_override": { + "name": "title_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_by": { + "name": "published_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "si_service_starts_at_idx": { + "name": "si_service_starts_at_idx", + "columns": [ + { + "expression": "service_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_occurs_on_idx": { + "name": "si_occurs_on_idx", + "columns": [ + { + "expression": "occurs_on", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_status_idx": { + "name": "si_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "service_instances_service_id_services_id_fk": { + "name": "service_instances_service_id_services_id_fk", + "tableFrom": "service_instances", + "tableTo": "services", + "columnsFrom": [ + "service_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_run_sheets": { + "name": "service_run_sheets", + "schema": "", + "columns": { + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "speaker": { + "name": "speaker", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sermon_title": { + "name": "sermon_title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stream_url": { + "name": "stream_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "slides_url": { + "name": "slides_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "service_run_sheets_service_instance_id_service_instances_id_fk": { + "name": "service_run_sheets_service_instance_id_service_instances_id_fk", + "tableFrom": "service_run_sheets", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "service_run_sheets_updated_by_users_id_fk": { + "name": "service_run_sheets_updated_by_users_id_fk", + "tableFrom": "service_run_sheets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.services": { + "name": "services", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "rrule": { + "name": "rrule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_time_local": { + "name": "start_time_local", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 75 + }, + "doors_open_minutes_before": { + "name": "doors_open_minutes_before", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "services_active_idx": { + "name": "services_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "services_name_unique": { + "name": "services_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_assessments": { + "name": "skill_assessments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assessor_id": { + "name": "assessor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'admin'" + }, + "level_from": { + "name": "level_from", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "level_to": { + "name": "level_to", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "comfort_at_time": { + "name": "comfort_at_time", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_assessments_user_created_idx": { + "name": "skill_assessments_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_assessments_skill_idx": { + "name": "skill_assessments_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_assessments_user_id_users_id_fk": { + "name": "skill_assessments_user_id_users_id_fk", + "tableFrom": "skill_assessments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_assessments_skill_id_skills_id_fk": { + "name": "skill_assessments_skill_id_skills_id_fk", + "tableFrom": "skill_assessments", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_assessments_assessor_id_users_id_fk": { + "name": "skill_assessments_assessor_id_users_id_fk", + "tableFrom": "skill_assessments", + "tableTo": "users", + "columnsFrom": [ + "assessor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_categories": { + "name": "skill_categories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "skill_categories_slug_idx": { + "name": "skill_categories_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_categories_active_idx": { + "name": "skill_categories_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "skill_categories_slug_unique": { + "name": "skill_categories_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skills": { + "name": "skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "technology_id": { + "name": "technology_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "function_id": { + "name": "function_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mentor_min_level": { + "name": "mentor_min_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'expert'" + }, + "stale_after_days": { + "name": "stale_after_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 120 + }, + "recert_required": { + "name": "recert_required", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "skills_slug_idx": { + "name": "skills_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skills_active_idx": { + "name": "skills_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skills_category_idx": { + "name": "skills_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skills_category_id_skill_categories_id_fk": { + "name": "skills_category_id_skill_categories_id_fk", + "tableFrom": "skills", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "skills_technology_id_technologies_id_fk": { + "name": "skills_technology_id_technologies_id_fk", + "tableFrom": "skills", + "tableTo": "technologies", + "columnsFrom": [ + "technology_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "skills_function_id_functions_id_fk": { + "name": "skills_function_id_functions_id_fk", + "tableFrom": "skills", + "tableTo": "functions", + "columnsFrom": [ + "function_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "skills_slug_unique": { + "name": "skills_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "skills_dedupe_key_unique": { + "name": "skills_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slots": { + "name": "slots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slot_index": { + "name": "slot_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "call_time": { + "name": "call_time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "slot_note": { + "name": "slot_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_trainee_slot": { + "name": "is_trainee_slot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "paired_with_user_id": { + "name": "paired_with_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "slots_instance_role_idx": { + "name": "slots_instance_role_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "role_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "slot_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slots_status_idx": { + "name": "slots_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slots_service_instance_id_service_instances_id_fk": { + "name": "slots_service_instance_id_service_instances_id_fk", + "tableFrom": "slots", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slots_role_id_roles_id_fk": { + "name": "slots_role_id_roles_id_fk", + "tableFrom": "slots", + "tableTo": "roles", + "columnsFrom": [ + "role_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "slots_paired_with_user_id_users_id_fk": { + "name": "slots_paired_with_user_id_users_id_fk", + "tableFrom": "slots", + "tableTo": "users", + "columnsFrom": [ + "paired_with_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chk_slots_single_parent": { + "name": "chk_slots_single_parent", + "value": "(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)" + }, + "chk_shadow_paired": { + "name": "chk_shadow_paired", + "value": "not is_trainee_slot or paired_with_user_id is not null" + } + }, + "isRLSEnabled": false + }, + "public.technologies": { + "name": "technologies", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "vendor_id": { + "name": "vendor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model_number": { + "name": "model_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version_label": { + "name": "version_label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "docs_url": { + "name": "docs_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "purchased_on": { + "name": "purchased_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "serial_number": { + "name": "serial_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "retired_at": { + "name": "retired_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "successor_technology_id": { + "name": "successor_technology_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "technologies_slug_idx": { + "name": "technologies_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_active_idx": { + "name": "technologies_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_vendor_idx": { + "name": "technologies_vendor_idx", + "columns": [ + { + "expression": "vendor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_category_idx": { + "name": "technologies_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "technologies_vendor_id_vendors_id_fk": { + "name": "technologies_vendor_id_vendors_id_fk", + "tableFrom": "technologies", + "tableTo": "vendors", + "columnsFrom": [ + "vendor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "technologies_category_id_skill_categories_id_fk": { + "name": "technologies_category_id_skill_categories_id_fk", + "tableFrom": "technologies", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "technologies_slug_unique": { + "name": "technologies_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.training_lessons": { + "name": "training_lessons", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "published": { + "name": "published", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "training_lessons_published_idx": { + "name": "training_lessons_published_idx", + "columns": [ + { + "expression": "published", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.training_resources": { + "name": "training_resources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "lesson_id": { + "name": "lesson_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "stored_name": { + "name": "stored_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "training_resources_lesson_idx": { + "name": "training_resources_lesson_idx", + "columns": [ + { + "expression": "lesson_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "training_resources_lesson_id_training_lessons_id_fk": { + "name": "training_resources_lesson_id_training_lessons_id_fk", + "tableFrom": "training_resources", + "tableTo": "training_lessons", + "columnsFrom": [ + "lesson_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.unavailability": { + "name": "unavailability", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'blackout'" + }, + "starts_on": { + "name": "starts_on", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "ends_on": { + "name": "ends_on", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "all_day": { + "name": "all_day", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rrule": { + "name": "rrule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "uq_unavailability_range": { + "name": "uq_unavailability_range", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_on", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ends_on", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"unavailability\".\"status\" = 'active'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "unavailability_user_idx": { + "name": "unavailability_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "unavailability_user_id_users_id_fk": { + "name": "unavailability_user_id_users_id_fk", + "tableFrom": "unavailability", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chk_unavailability_span": { + "name": "chk_unavailability_span", + "value": "\"unavailability\".\"ends_on\" >= \"unavailability\".\"starts_on\"" + }, + "chk_unavailability_max_span": { + "name": "chk_unavailability_max_span", + "value": "\"unavailability\".\"ends_on\" - \"unavailability\".\"starts_on\" <= 365" + } + }, + "isRLSEnabled": false + }, + "public.used_magic_tokens": { + "name": "used_magic_tokens", + "schema": "", + "columns": { + "jti": { + "name": "jti", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.used_tokens": { + "name": "used_tokens", + "schema": "", + "columns": { + "jti": { + "name": "jti", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "assignment_id": { + "name": "assignment_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "used_tokens_assignment_id_assignments_id_fk": { + "name": "used_tokens_assignment_id_assignments_id_fk", + "tableFrom": "used_tokens", + "tableTo": "assignments", + "columnsFrom": [ + "assignment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_skills": { + "name": "user_skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "self_comfort": { + "name": "self_comfort", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "self_rated_at": { + "name": "self_rated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "verified_level": { + "name": "verified_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "verified_by": { + "name": "verified_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "mentor_opt_in": { + "name": "mentor_opt_in", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "mentor_approved_at": { + "name": "mentor_approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "mentor_approved_by": { + "name": "mentor_approved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_served_on": { + "name": "last_served_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_skills_user_skill_idx": { + "name": "user_skills_user_skill_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_skills_skill_idx": { + "name": "user_skills_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_skills_user_id_users_id_fk": { + "name": "user_skills_user_id_users_id_fk", + "tableFrom": "user_skills", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_skills_skill_id_skills_id_fk": { + "name": "user_skills_skill_id_skills_id_fk", + "tableFrom": "user_skills", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "phone_e164": { + "name": "phone_e164", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_role": { + "name": "system_role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'volunteer'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending_approval'" + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "calendar_feed_token": { + "name": "calendar_feed_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "emergency_contact": { + "name": "emergency_contact", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_by": { + "name": "approved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reliability_score": { + "name": "reliability_score", + "type": "numeric(5, 2)", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "deactivated_at": { + "name": "deactivated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "users_email_lower_key": { + "name": "users_email_lower_key", + "columns": [ + { + "expression": "lower(\"email\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_username_lower_key": { + "name": "users_username_lower_key", + "columns": [ + { + "expression": "lower(\"username\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_calendar_feed_token_key": { + "name": "users_calendar_feed_token_key", + "columns": [ + { + "expression": "calendar_feed_token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_status_idx": { + "name": "users_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_system_role_idx": { + "name": "users_system_role_idx", + "columns": [ + { + "expression": "system_role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.vendors": { + "name": "vendors", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "support_url": { + "name": "support_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "support_phone": { + "name": "support_phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "vendors_slug_idx": { + "name": "vendors_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "vendors_active_idx": { + "name": "vendors_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "vendors_slug_unique": { + "name": "vendors_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 71b4ecd..ff9f43c 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -155,6 +155,13 @@ "when": 1795141771191, "tag": "0021_sparkling_exiles", "breakpoints": true + }, + { + "idx": 22, + "version": "7", + "when": 1795223283100, + "tag": "0022_fixed_squadron_supreme", + "breakpoints": true } ] } \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index 719cea2..26d6947 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -14,6 +14,7 @@ const eslintConfig = [ { ignores: [ "node_modules/**", + "lumenroom/**", ".next/**", "out/**", "build/**", diff --git a/lumenroom/.dockerignore b/lumenroom/.dockerignore new file mode 100644 index 0000000..c71fdab --- /dev/null +++ b/lumenroom/.dockerignore @@ -0,0 +1,14 @@ +node_modules +dist +.git +docs +.gitignore +server/data +.check +.smoke +*.log +.DS_Store +README.md +Dockerfile +.dockerignore +docker-compose.yml diff --git a/lumenroom/Dockerfile b/lumenroom/Dockerfile new file mode 100644 index 0000000..1ebd3be --- /dev/null +++ b/lumenroom/Dockerfile @@ -0,0 +1,52 @@ +# syntax=docker/dockerfile:1 + +# ---------------------------------------------------------------- dependencies +FROM node:24-bookworm-slim AS deps +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci + +# ---------------------------------------------------------------------- build +FROM deps AS build +WORKDIR /app +COPY tsconfig.json vite.config.ts index.html ./ +COPY src ./src +# Vite copies public/ into dist/, so the served PDF (in-app Guide link) needs it here. +COPY public ./public +RUN npm run build + +# ------------------------------------------------------- production node_modules +FROM node:24-bookworm-slim AS prod-deps +WORKDIR /app +ENV NODE_ENV=production +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev && npm cache clean --force + +# -------------------------------------------------------------------- runtime +FROM node:24-bookworm-slim AS runtime +WORKDIR /app +ENV NODE_ENV=production \ + PORT=8787 \ + HOST=0.0.0.0 \ + LUMENROOM_DATA=/data + +COPY --from=prod-deps /app/node_modules ./node_modules +COPY package.json ./ +COPY server ./server +COPY --from=build /app/dist ./dist + +# Fail the build, not the first request, if the guide or the UI is missing. +RUN test -f dist/index.html && test -f dist/lumenroom-user-guide.pdf + +# The catalog lives on a volume; it must be writable by the unprivileged user. +RUN mkdir -p /data && chown -R node:node /data /app +USER node + +EXPOSE 8787 +VOLUME ["/data"] + +# node is guaranteed present, so no curl/wget needed in the image. +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||8787)+'/api/health').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" + +CMD ["node", "server/index.mjs"] diff --git a/lumenroom/README.md b/lumenroom/README.md new file mode 100644 index 0000000..e6ec8fe --- /dev/null +++ b/lumenroom/README.md @@ -0,0 +1,194 @@ +# Lumenroom + +A browser-based photo catalog and editor built for a small team: events, ratings, +filtering, and a non-destructive RAW-capable develop module. + +Two ways to run it: + +| Mode | Storage | Raw support | +| --- | --- | --- | +| Browser only (`npm run dev`) | IndexedDB on this device | No — raw files need the server | +| Team server (`npm run server` + `npm run dev`) | SQLite + files on disk under `server/data` | Yes — LibRaw demosaic for all vendors | + +## Quick start + +```bash +npm install + +# browser-only library +npm run dev # http://localhost:5173 + +# with the team server (enables raw + sharing) +LUMENROOM_INVITE=our-team npm run server # http://localhost:8787 +npm run dev # proxies /api to the server +``` + +Open the **Local only / Sign in** pill in the top bar. The first account becomes +the admin; everyone else registers with `LUMENROOM_INVITE`. Until you sign in, +the app keeps working exactly as it did before — entirely local. + +### Production + +```bash +npm run build # type-checks, then bundles into dist/ +npm start # serves dist/ and the API from one process +``` + +### Docker + +The image builds the UI and runs one Node process that serves both the app and +the API. Only `/data` needs to persist. + +```bash +docker build -t lumenroom . +docker run -d --name lumenroom \ + -p 8787:8787 \ + -e LUMENROOM_INVITE=our-team \ + -v lumenroom-data:/data \ + lumenroom +``` + +Or with Compose, which wires up the volume and env vars for you: + +```bash +LUMENROOM_INVITE=our-team docker compose up -d --build +``` + +The container runs as the unprivileged `node` user (uid 1000), ships a +`HEALTHCHECK` on `/api/health`, and exposes port 8787. To put it behind a TLS +proxy, forward `X-Forwarded-Proto: https` so session cookies are marked `Secure`. + +Back up the catalog by copying the volume: + +```bash +docker run --rm -v lumenroom-data:/data -v "$PWD":/backup alpine \ + tar czf /backup/lumenroom-$(date +%F).tar.gz -C /data . +``` + +Environment variables: + +| Variable | Default | Purpose | +| --- | --- | --- | +| `PORT` | `8787` | Server port | +| `LUMENROOM_DATA` | `server/data` | Where originals, previews and the database live | +| `LUMENROOM_INVITE` | *(empty)* | Invite code for new accounts; empty closes registration | +| `LUMENROOM_MAX_UPLOAD` | `300 MB` | Upload ceiling (bytes) | +| `LUMENROOM_RAW_EDGE` | `6000` | Long edge of the editable proxy generated for raws | +| `LUMENROOM_RAW_WORKERS` | `4` (capped at cores−1) | Raws demosaiced at once; each worker holds a LibRaw instance | +| `LUMENROOM_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this, to hand memory back | + +## Bridge from the Media Team Hub + +A separate dashboard can hand an event over to this editor without sharing +passwords or copying the library. The dashboard signs a short-lived token, sends +the browser to `/api/bridge/login?token=…`, and this server verifies it with the +shared `BRIDGE_SECRET`, creates or reuses a user by email, imports the event's +photo list and redirects into the app with that event open. Photo bytes are +proxied from the dashboard on demand, so the import is metadata only. + +```bash +GLENLOCH_URL=https://media.example.org \ +BRIDGE_SECRET= \ +LUMENROOM_INVITE=our-team \ + docker compose up -d --build +``` + +| Variable | Default | Purpose | +| --- | --- | --- | +| `GLENLOCH_URL` | *(empty)* | Dashboard base URL; empty disables the bridge | +| `BRIDGE_SECRET` | *(empty)* | Shared HMAC secret for bridge tokens | +| `LUMENROOM_BRIDGE_TTL_HOURS` | `12` | How long an imported bridge event survives | + +The editor shows a banner with **Save to event** — it renders the open photo in +the browser and stores it on the dashboard event as the edited JPEG — and **Back +to dashboard**. Imported events and their catalog rows are temporary: expired +bridge events are swept on the next bridge login. Originals stay on the +dashboard's media storage; only previews and thumbnails are cached under +`LUMENROOM_DATA`. RAW files are edited on a 4000 px JPEG proxy generated by the +dashboard and cached here; JPEG/PNG originals are streamed at full size. Bridge accounts have a random password hash, so they can only +be reached through the dashboard link, not the normal sign-in form. + +## Features + +**Library** — events in the sidebar (create, rename, delete, drag to reorder, +drop photos onto an event to move them), drag photos to reorder within a view, +star ratings, pick/reject flags, five color labels, filters (rating, unrated, +flag, labels, "edited only", free text over name/camera/lens/keywords), sorting +by capture date, import date, name, rating or manual order, multi-select with +shift-ranges and bulk actions. Right-click any photo for a menu with the star +rating, flags and color labels plus open, copy/paste settings, export and delete. + +**Develop** — a WebGL2 multi-pass pipeline, per photo, non-destructive: + +- white balance, exposure, contrast, highlights/shadows/whites/blacks +- texture, clarity, dehaze, vibrance, saturation, black & white mix +- RGB + per-channel tone curves +- 8-band HSL color mixer, split toning / color grading +- sharpening, luminance noise reduction +- vignette, grain +- crop with nine aspect ratios, straighten, 90° rotation, flips +- scroll-wheel zoom with a Fit / 100% readout, drag to pan, double-click to zoom + in or back out; right-click the canvas for zoom, crop, copy/paste and export +- histogram, presets (built-in + saved), history with undo, copy/paste settings, + before/after + +**Export** — format (JPEG/PNG/WebP), quality, resize by long edge or percent, +filename template (`{name}`, `{date}`, `{time}`, `{index}`), batch export of the +selection, full resolution through the same renderer. + +## Raw support + +The browser cannot decode camera raw, so the server does it: + +1. The original file is stored byte-for-byte (`server/data/originals`). +2. LibRaw (`libraw-wasm`) demosaics it with the camera's white balance and + orientation, and `sharp` encodes an editable JPEG proxy (long edge + `LUMENROOM_RAW_EDGE`). +3. If LibRaw cannot open a file, the largest JPEG embedded in the container is + used instead, so exotic or very new cameras still import. The grid marks such + photos `RAW` and the Info panel reports which engine produced the proxy. + +Formats: CR2/CR3/CRW, NEF/NRW, ARW/SRF/SR2, ORF, RW2/RWL, RAF, PEF, DNG, SRW, +3FR, FFF, IIQ, X3F, ERF, K25/KDC, DCR, MOS, MRW, MEF. + +**Parallel import.** Decoding runs in a small pool of LibRaw workers (default 4, +`LUMENROOM_RAW_WORKERS`) and the browser uploads four files at a time, so a card +imports several times faster than one file after another. Measured on this repo +with 8 mixed raws (20 MP average): + +| Workers | 8 files | Speedup | Peak memory | +| --- | --- | --- | --- | +| 1 (serial) | 19.2 s | 1.0× | — | +| 4 | 5.2 s | 3.7× | ~2.5 GB | +| 8 | 3.5 s | 5.4× | ~3.5 GB | + +Raise the worker count on a big machine; keep it low on a small VPS, where each +worker can hold a few hundred MB while decoding. Workers idle for 90 s are +disposed and recreated on demand, so a burst of imports does not pin memory +forever. `GET /api/health` reports the pool size. + +## Layout + +``` +src/ + App.tsx state, filtering, sync, drag-and-drop, shortcuts + gl/renderer.ts WebGL2 pipeline (grade → blur → finish) + lib/ db, api client, edits model, import/export, presets + components/ library grid, develop, panels, modals +server/ + index.mjs HTTP API + static hosting + db.mjs SQLite schema (node:sqlite, no native deps) + raw.mjs LibRaw decode + embedded-preview fallback + imaging.mjs sharp encoding, PNG fallback +``` + +## Limitations + +- No cloud hosting, masking/brushes, lens corrections, panoramas/HDR merge, or + tethered capture. Local adjustments are the biggest missing editor feature. +- Raw editing works on the decoded proxy (6,000 px default), not the full sensor + mosaic; export size is bounded by the proxy. +- Temperature/tint are relative to the as-shot white balance. +- Sync is whole-record: the last writer wins per photo. It is designed for a + handful of people sharing one catalog, not for concurrent batch workflows. +- File deletion is immediate; there is no trash or catalog backup. diff --git a/lumenroom/docker-compose.yml b/lumenroom/docker-compose.yml new file mode 100644 index 0000000..8f87231 --- /dev/null +++ b/lumenroom/docker-compose.yml @@ -0,0 +1,26 @@ +services: + lumenroom: + build: . + image: lumenroom:latest + container_name: lumenroom + restart: unless-stopped + ports: + - "${LUMENROOM_PORT:-8787}:8787" + environment: + # Invite code for every account after the first (admin) one. + LUMENROOM_INVITE: ${LUMENROOM_INVITE:-} + LUMENROOM_MAX_UPLOAD: ${LUMENROOM_MAX_UPLOAD:-322122547} + LUMENROOM_RAW_EDGE: ${LUMENROOM_RAW_EDGE:-6000} + # Parallel raw decoders; each one holds a LibRaw worker (few hundred MB). + LUMENROOM_RAW_WORKERS: ${LUMENROOM_RAW_WORKERS:-4} + # Bridge from the Media Team Hub: dashboard base URL and the shared HMAC + # secret (must match the dashboard's BRIDGE_SECRET). Empty disables it. + GLENLOCH_URL: ${GLENLOCH_URL:-} + BRIDGE_SECRET: ${BRIDGE_SECRET:-} + LUMENROOM_BRIDGE_TTL_HOURS: ${LUMENROOM_BRIDGE_TTL_HOURS:-12} + volumes: + # Originals, previews, thumbnails and the SQLite catalog. + - lumenroom-data:/data + +volumes: + lumenroom-data: diff --git a/lumenroom/docs/Lumenroom-User-Guide.pdf b/lumenroom/docs/Lumenroom-User-Guide.pdf new file mode 100644 index 0000000..3fadfac Binary files /dev/null and b/lumenroom/docs/Lumenroom-User-Guide.pdf differ diff --git a/lumenroom/docs/user-guide/guide.html b/lumenroom/docs/user-guide/guide.html new file mode 100644 index 0000000..6ed98c4 --- /dev/null +++ b/lumenroom/docs/user-guide/guide.html @@ -0,0 +1,786 @@ + + + + +Lumenroom — User Guide + + + + + +
+
+
Lumenroom
+
+

User Guide

+
Import, cull, develop and export raw photographs in the browser — a complete desktop-style workflow.
+
+
The Lumenroom library
+
+
+
+
+ VERSION 1.0 · NOVEMBER 2026 + SCREENSHOTS FROM THE RUNNING APPLICATION +
+
+
+ + +
+
Contents
+

What is in this guide

+

Every panel, dialog and keyboard shortcut in the application, in the order you meet them during a real shoot: bring the card in, cull it down, develop the keepers, deliver the files.

+
+
1Introduction
+
2Getting started
+
3Importing photos
+
4The library
+
5Culling a shoot
+
6The Develop workspace
+
7Light and white balance
+
8Colour
+
9Effects and Detail
+
10Crop and straighten
+
11Presets
+
12History, copy and paste
+
13Exporting
+
14Keyboard reference
+
15The team server
+
16Troubleshooting and limits
+
AFormats and badges
+
+ +

How to read this guide

+

Figures are real screenshots taken from the application with a sample shoot loaded. The sample photographs are simple colour fields, so anything you see on them — grain, a crop, a graded shadow — is the renderer at work rather than a photograph hiding it.

+

Keys are written for both platforms. ⌘ means Command on macOS; use Ctrl on Windows and Linux. Both are accepted everywhere ⌘ / Ctrl appears, and on Windows the menu equivalents are in the right-click menu.

+ +
+
Local firstOriginals, ratings and edits live in this browser. Nothing is uploaded unless you sign in to a server.
+
Non-destructiveEvery adjustment is stored as parameters next to the file; the original pixels are never rewritten.
+
Raw awareCamera raws are demosaiced by the optional Node server, then developed like any other frame.
+
+
+ + +
+
Chapter 1
+

Introduction

+

Lumenroom is a browser-based raw workflow: a catalogue, a culling surface and a full develop module backed by a WebGL renderer, with an optional team server for shared storage and raw decoding.

+ +

The shape of the application

+

There are two screens, and you move between them constantly.

+

Library is the catalogue: a grid of every photo in the current view, a filter bar, and the filmstrip-free space you need to rate and reject quickly. Develop is the darkroom: one photo on a large canvas, a navigator and preset rail on the left, sliders and a histogram on the right, and the filmstrip along the bottom.

+

The switch at the top centre moves between them; G returns to the library from almost anywhere, and Esc in Develop does the same.

+ +

What happens to your files

+

When you import, Lumenroom reads the EXIF metadata, generates a small JPEG thumbnail, and stores both the original blob and the record in the browser's IndexedDB database. Edits are a plain JSON object attached to that record. Reopening the page reloads everything from disk-backed browser storage; there is no upload, no account and no network round trip in local mode.

+

If you start the team server and sign in, originals are also written to server/data and the library can be shared. The editing model does not change: the server stores files and records, the browser still does the rendering.

+ +
+ Nothing is destructive. Reset adjustments, copy settings and the History panel all rewrite the parameter object only. The original file is untouched until you export a new copy. +
+ +

Requirements

+ + + + + + + + +
ItemRequirement
BrowserA current Chromium (Chrome, Edge), Firefox or Safari with WebGL 2 enabled. Hardware acceleration is strongly recommended — every preview, thumbnail and export is rendered on the GPU.
Display1280 × 800 or larger. The layout is designed for a laptop screen and expands to fill a desktop display.
StorageBrowser storage quota (typically a share of free disk). Large catalogues of raw files are better kept on the team server.
Raw filesRequire the Node server, which demosaics with LibRaw. Without it, JPEG, PNG, WebP, AVIF and TIFF import directly.
+
+ + +
+
Chapter 2
+

Getting started

+

Two commands get you a working catalogue. The first run of the app is empty — the grid shows its hint text until you import or drop something on it.

+ +

Run it locally

+
    +
  1. Install the dependencies once: npm install.
  2. +
  3. For development, run npm run dev and open the address Vite prints.
  4. +
  5. For the full application — static build plus API and raw decoding — run npm run build, then npm start, and open http://localhost:8787.
  6. +
  7. To run it in a container, use docker compose up; the same port is published and server/data is mounted as a volume.
  8. +
+

The server also serves the built user interface, so npm start on its own is enough once dist/ exists. Health and capabilities are available at /api/health.

+ +

Bring in your first photos

+

Press ⌘ / Ctrl + I, click Import photos in the top right, or drag files from your file manager anywhere onto the window. The import dialog is described in the next chapter.

+ +
+ The library with a three-photo selection +
Figure 1. The library after an import. The sidebar lists the catalogue and its events, the filter bar narrows the grid, the selection bar appears as soon as anything is selected, and each card carries its own rating, flag, colour label and file metadata.
+
+
+ + +
+
Chapter 3
+

Importing photos

+

Importing is a single dialog with three jobs: choose where the photos belong, collect the files, and report anything that could not be read.

+ +
+ The import dialog with four files staged +
Figure 2. The import dialog with four files staged. The summary counts the batch and flags raw files; the warning appears because no server is signed in, so raws would have to wait.
+
+ +

Adding files

+
    +
  • Drag anywhere onto the window. A full-window drop target appears, and dropping opens the dialog with those files already staged. This works from the library and from Develop.
  • +
  • Click the drop zone inside the dialog to open the file picker, or use Import photos in the top bar.
  • +
  • Files already staged are de-duplicated by name and size, so dropping the same card twice does not double the batch.
  • +
+ +

Choosing a destination

+

The Event / album menu lists every event plus + New event…, which reveals a name field. The event is metadata, not a folder: a photo can be moved between events later without touching the file.

+ +

What can be imported

+ + + + + + +
TypeBehaviour
JPEG, PNG, WebP, AVIF, TIFFDecoded in the browser. EXIF camera, lens, ISO, aperture, shutter and focal length are read when present.
Camera raw — CR2, CR3, NEF, ARW, ORF, RW2, RAF, DNG, PEF, SRW, 3FR and moreSent to the team server, demosaiced with LibRaw, and returned as an editable proxy plus a server-side original. Requires a signed-in session.
+

During an import a progress bar reports the current file by name. If some files fail, the dialog lists each one with the reason and keeps the successes; a failed raw usually means the server is offline or the file is a format LibRaw cannot open.

+ +
+ Raws without a server. The browser cannot decode most camera raws. Stage them anyway and the dialog offers Sign in to the server; once connected, the same batch decodes normally. Server decoding runs a few files at a time, typically two to four seconds per frame. +
+
+ + +
+
Chapter 4
+

The library

+

The library is where you decide what is worth developing. It is built for speed: rating, flagging and filtering without ever opening a photo.

+ +

The sidebar

+

All photos is the whole catalogue. Unsorted holds anything not yet assigned to an event. Below them, each event shows its photo count; the + next to the catalog header creates a new one. The footer reports the server state — whether one was detected, and whether you are signed in.

+ +

The filter bar

+
+ The filter bar +
Figure 3. Rating and flag filters, colour label swatches, free-text search, the Edited toggle, sort order, and the count of visible photos.
+
+
    +
  • Rating — Any, one to five stars, or Unrated. Filtering for 3★ and above is the usual first pass.
  • +
  • Flag — Any, Picked, Unflagged, Rejected.
  • +
  • Label — the six colour swatches. Click one to keep only that colour; click it again to clear.
  • +
  • Search — matches file name, camera, lens and keywords as you type.
  • +
  • Edited — shows only photos with develop adjustments.
  • +
  • Sort — the field, with an arrow to reverse the direction. The right-hand count tells you how many photos survived the filters.
  • +
+

Filters combine: Pick + 4★ + Edited is a valid view. They are view state, not a change to the photos, and clearing a filter restores the full grid instantly.

+ +
+ The library filtered to picked photos +
Figure 4. The same catalogue filtered to Picked. The count in the top bar and the grid agree; the filter chip stays lit so you can see why the view is short.
+
+ +

The grid and its cards

+
+ A single card close-up +
Figure 5. One card: the image is letterboxed inside a 3:2 tile, and the strip beneath carries the file name, metadata, rating and colour label.
+
+

Cards are laid out in rows that reflow with the window. Each one shows the photo oriented and cropped as it will be developed — a turned or straightened frame is turned in its thumbnail too, and preset previews follow the same crop.

+
    +
  • Badges — RAW for camera raw, ✓ for picked, ✕ for rejected, ✎ when the photo has adjustments.
  • +
  • Colour strip along the top edge shows the label colour.
  • +
  • Metadata line shows camera, and the size and dimensions appear on hover.
  • +
  • Rating is shown as stars under the file name.
  • +
+ +

Selecting

+

Click to select one photo. Shift-click extends from the last anchor; ⌘ / Ctrl-click toggles a single photo in or out. Drag on empty space to draw a rubber band — everything it touches is selected, and holding Shift adds to the existing selection. A plain click on empty space clears it.

+

With more than one photo selected, the selection bar becomes a batch editor: stars, pick and reject, colour labels, Export and Delete all apply to the whole selection at once.

+ +

The right-click menu

+
+ The context menu on a card +
Figure 6. The context menu carries the same actions as the keyboard, including the shortcut printed beside each item so the menu teaches the keys.
+
+

It includes the star row, pick and reject, the colour labels, Open in Develop, Copy settings and Paste settings, Reset adjustments, Export… and Delete…. Right-clicking a photo inside a multi-selection acts on the whole selection.

+ +

Reordering and opening

+

Drag one card onto another to reorder the catalogue; dragging a selection moves all of it. Double-click, or select and press E, to open the photo in Develop.

+
+ + +
+
Chapter 5
+

Culling a shoot

+

Culling is a keyboard loop: look, rate, flag, advance. Everything below works on the selection, so a batch of forty frames can be rated in one keystroke.

+ + + + + + + + + + + + + + + + +
KeysAction
0 – 5Set the star rating, from none to five.
6 7 8 9Colour label: red, yellow, green, blue.
PFlag as picked. A second press keeps it picked, so it is safe to hold.
XFlag as rejected — the fastest way to clear the frames that missed.
URemove the flag.
← → ↑ ↓Move the selection through the grid, one photo or one row at a time.
Shift + arrowsExtend the selection as you move.
Home / EndFirst or last photo in the current view.
⌘ / Ctrl + ASelect every photo the filters are showing.
Delete / BackspaceDelete the selection, after confirmation.
EscClear the selection.
+ +

A practical pass

+
    +
  1. Open the event and set the rating filter to Unrated.
  2. +
  3. Press → to walk the shoot. On a keeper, press 3 or 4; on a miss, press X.
  4. +
  5. Switch the flag filter to Rejected and press ⌘ / Ctrl + A then Delete.
  6. +
  7. Filter to Picked. This is the batch you develop.
  8. +
+ +
+ Arrow navigation follows the rendered grid. Up and down move by whole rows, whatever the window width or card count, and the selection scrolls into view as it moves. +
+ +

The filmstrip in Develop uses the same order, so a cull pass done here translates directly into the order you step through while developing.

+
+ + +
+
Chapter 6
+

The Develop workspace

+

Develop is a single-photo surface with three rails. Each one can be ignored until you need it; the canvas keeps its size as panels open and close.

+ +
+ The Develop workspace +
Figure 7. Develop with a photo that has adjustments. Left: navigator and presets. Centre: canvas with the zoom controls. Right: histogram, then the Light and Presence panels. Bottom: filmstrip.
+
+ +

The top strip

+

From left to right: back to the library, the file name, the frame number in the filmstrip, the pixel dimensions, a clickable star row, pick and reject buttons, the colour labels, then Before / After, Crop, Copy, Paste, Reset, Delete and Export. Everything there also exists as a key.

+ +

The canvas

+

The photo is rendered by the WebGL pipeline, which applies crop, rotation, straighten, flips, tone, colour, grain, sharpening and noise reduction in a single pass. What you see is what the export writes.

+
    +
  • Zoom — use the wheel over the canvas. It zooms toward the cursor, so the detail you are pointing at stays put. Z toggles between fit and 100%.
  • +
  • Pan — drag with the mouse when zoomed in. Double-click also toggles the zoom level.
  • +
  • Before / after — hold \ to see the original, release to return. The top-bar button does the same without holding.
  • +
  • Zoom readout — the buttons at the bottom right show fit, 100% and the current percentage.
  • +
+ +

The left rail

+

Navigator shows the whole frame with the current crop applied, the file name, and whether the file is raw or a standard image. It is the quickest way to confirm a photo is turned the right way before you start.

+

Below it, Presets (chapter 11) and, when opened from the panel header, History.

+ +

The right rail

+
+ The right-hand panel column +
Figure 8. The right column. The histogram shows the three channels with the exposure metadata beneath it; panels below stack, collapse and remember their state.
+
+

A histogram sits at the top with ISO, aperture, shutter and focal length underneath. Panels follow: Light, Tone curve, Color mixer, Color grading, Effects, Detail and Info. Click a panel header to collapse or expand it; the chevron shows the state.

+ +

The filmstrip

+

Every photo in the current view, in order. Click to open one, or press ← and →. The wheel over the strip scrolls it sideways, and the active frame scrolls itself into view when you move through the shoot. Ratings, flags and colour labels are visible on each film, so you can see where you are in the cull.

+
+ + +
+
Chapter 7
+

Light and white balance

+

The Light panel is the first thing to set on any photo, and the only panel most photos need.

+ +

White balance

+

Temp moves the image between cool blue and warm amber; Tint between green and magenta. Both start at As shot, meaning the camera's recorded balance, and the As shot button in the panel header returns them there at any time without touching the tone controls.

+ +

Tone

+ + + + + + + + + + +
ControlRangeWhat it does
Exposure−5.00 … +5.00 EVOverall brightness in stops. The first move on an under- or over-exposed frame.
Contrast−100 … +100Separates or flattens the midtones, leaving the endpoints alone.
Highlights−100 … +100Pulls back bright skies and windows, or lifts them.
Shadows−100 … +100Opens dark areas, or deepens them for a moodier frame.
Whites−100 … +100Sets the white point; use it with the histogram rather than by eye.
Blacks−100 … +100Sets the black point and the depth of the shadows.
+

Auto analyses the photo's thumbnail and sets a starting tone curve in one click. It is a starting point, not a finish: adjust from there.

+ +

Presence

+ + + + + + + + + +
ControlWhat it does
TextureMedium-frequency detail — skin, fabric, foliage — without touching edges.
ClarityMidtone contrast. Small amounts add punch; large amounts look metallic.
DehazeCuts atmospheric haze and flattens or adds distance.
VibranceSaturation that protects already-saturated colours and skin tones.
SaturationUniform saturation across every colour.
+ +

Black and white

+

Tick Black & white mix to convert. A filter row appears — None, Yellow, Orange, Red, Green, Blue — with a strength slider. A filter darkens the colours it absorbs, so red drops a blue sky and green lifts foliage. The Color mixer below tunes individual hues on top of the conversion.

+ +
+ + +
+
Chapter 8
+

Colour

+

Three panels take over where the Light panel stops: a tone curve for precise contrast, a mixer for individual hues, and colour grading for split-toning shadows and highlights.

+ +

Tone curve

+

Four channels: RGB for luminance, then R, G and B for per-channel colour. Click on the curve to add a point and drag it; drag a point off the ends to remove it. Reset in the panel header returns the current channel to a straight line.

+

A gentle S — lift the highlights, drop the shadows — is the classic film contrast move. The per-channel curves are for casts that white balance cannot fix: lift the blue curve in the shadows to cool them without touching the midtones.

+ +

Color mixer

+

Eight hue ranges, from red through magenta. Pick a swatch, then adjust Hue, Saturation and Luminance for that range only. This is how you deepen a sky without changing the grass, or pull the orange out of skin while leaving a sunset alone.

+

Reset clears all three values for every band, not just the selected one.

+ +

Color grading

+

Two wheels, expressed as sliders: Shadows and Highlights, each with a Hue (0–360°) and an Amount. Balance shifts the crossover between them.

+

Teal shadows with warm highlights is the standard cinematic grade; a small amount goes a long way. Grading is applied after the tone curve, so it tints the final luminance rather than the source colours.

+
+ + +
+
Chapter 9
+

Effects and Detail

+

The last two panels are where a render starts to look like a photograph rather than a file: vignette and grain on one side, sharpening and noise reduction on the other.

+ +

Effects

+ + + + + + + + + + +
ControlWhat it does
Vignette — AmountDarkens (negative) or lightens (positive) the edges of the crop.
Vignette — MidpointHow far from the centre the falloff begins.
Vignette — FeatherHow soft the transition is. Low feather draws a visible ring.
Grain — AmountStrength of the film grain.
Grain — SizeGrain cell size. Because it is resolution-independent, size is judged at 100%, not on the fitted preview.
Grain — RoughnessFrom smooth, even clumping to coarse, irregular structure.
+

Under the grain sliders is a 100% patch: a small window of the real crop rendered at actual pixels, and it is the only honest way to judge grain size before exporting. Drag the crop and the patch samples that part of the photo, so what you check is what you framed.

+ +

Detail

+ + + + + + + + + +
ControlWhat it does
Sharpen — AmountEdge contrast. Most photographs need a small amount after any resize.
Sharpen — RadiusThe width of the edge being sharpened, in pixels.
Sharpen — DetailHow much fine structure is included; lower values protect smooth areas.
Noise reduction — LuminanceSmooths luminance noise, at the cost of fine detail if pushed.
Noise reduction — DetailHow much texture is preserved while noise is reduced.
+ +
+ Judge sharpening and noise at 100%. Both are pixel-level operations; a fitted preview hides exactly the artefacts you are trying to control. Press Z and pan, then press it again to return to fit. +
+
+ + +
+
Chapter 10
+

Crop and straighten

+

Crop mode overlays the frame with a rule-of-thirds grid, eight handles and a 100% loupe, and every change is visible in the navigator, the filmstrip and the preset thumbnails as you make it.

+ +
+ Crop mode with the crop rectangle and loupe +
Figure 9. Crop mode. The rectangle has been pulled in from the corner, the crop panel shows the aspect presets and the straighten angle, and the hint bar at the bottom lists the keys.
+
+ +

Entering and leaving

+

Press C or use the Crop button in the top strip. Enter applies the crop and leaves crop mode; Esc cancels it. The hint bar at the bottom of the canvas always shows the current keys.

+ +

Shaping the crop

+
    +
  • Drag a corner or edge handle to resize; drag inside the rectangle to move it.
  • +
  • Aspect presets — Original, Free, 1×1, 4×5, 5×4, 4×3, 3×2, 16×9, 2×1, 9×16. Choosing one constrains the rectangle; Free releases it.
  • +
  • ⟲ 90° and ⟳ 90° turn the frame in quarter steps. Thumbnails, the navigator and preset previews turn with it.
  • +
  • Angle straightens the horizon, from −45° to +45° in 0.1° steps. The crop rectangle stays inside the rotated frame, so straightening never samples outside the image.
  • +
  • Flip H and Flip V mirror the exported file. Mirror view mirrors only the preview, for checking a composition without changing the output.
  • +
  • Reset crop returns to the full frame with no rotation or flips.
  • +
+ +
+ The crop loupe at 100% +
Figure 10. The loupe sits at the centre of the crop and shows real pixels at 100%, so you can place the crop against detail that the fitted view cannot show.
+
+ +

What the crop affects

+

The crop is part of the photo's edit, not a separate export step. It changes the navigator, the filmstrip thumb, the grid thumbnail, every preset tile and the exported dimensions. Grain size is measured in output pixels, so cropping tighter makes existing grain appear larger in the final file — check the 100% patch in the Effects panel after a big crop.

+
+ + +
+
Chapter 11
+

Presets

+

Presets are starting points that render on your photo before you commit to one: every tile in the rail is the actual frame, with the current crop applied.

+ +
+ The preset rail +
Figure 11. The preset rail, grouped by family, with the film variant row above it. The navigator and file details sit above the rail.
+
+ +

Groups and variants

+

Presets are grouped — Essentials, Film, Warm, Cinematic and the rest of the catalogue. The row above the tiles switches the whole rail between variants:

+
    +
  • Stock — the preset as designed.
  • +
  • Push +1 / Pull −1 — a stop brighter or darker, with the contrast shift that goes with it.
  • +
  • Warm split / Cool split — the same look with the shadows and highlights graded in opposite directions.
  • +
+ +

Applying and saving

+

Click a tile to apply it. A preset replaces the develop parameters — crop and rotation are left alone, because they belong to the frame, not the look. After applying, the sliders show the preset's values and can be adjusted further; the History panel records it as one step.

+

To save your own, adjust a photo and press + in the Presets header. Give it a name and it appears in the rail, rendering its own preview. User presets are stored with the rest of the catalogue.

+ +
+ Previews are rendered, not cached bitmaps. Each tile is the current photo through that preset, at the current crop, so choosing between looks is a comparison of your frame rather than of a stock image. +
+
+ + +
+
Chapter 12
+

History, copy and paste

+

Three ways to reuse work: step backwards through a photo's edits, copy a look to another photo, or start again from zero.

+ +

History

+

Every adjustment is recorded with a label and a timestamp. Open History from the left rail and click any entry to restore the photo to that exact state — the sliders follow. ⌘ / Ctrl + Z steps back one entry at a time.

+

History is per photo and belongs to that photo's session. Switching photos does not lose it, and it is saved with the catalogue.

+ +

Copy and paste settings

+

With a developed photo open, press ⌘ / Ctrl + C — or Copy in the top strip. Select another photo, in Develop or in the library, and press ⌘ / Ctrl + V. The full develop state is pasted: white balance, tone, colour, effects, detail and crop.

+

This is the fastest way to match a series shot under the same light: develop one frame properly, copy it, then select the rest in the grid and paste once.

+ +

Reset

+

Reset in the top strip, or Reset adjustments in the context menu, returns the photo to a neutral develop state. The original file is untouched and the reset itself is a history step, so it can be undone.

+ +
+ Paste is the batch tool. Select forty photos in the library, paste once, and all forty receive the copied settings — including the crop, which is why matching a series is a two-step job rather than forty. +
+
+ + +
+
Chapter 13
+

Exporting

+

Export writes new files. Nothing about the catalogue, the original or the edit changes; the dialog is a description of the file you want next to the file you have.

+ +
+ The export dialog +
Figure 12. The export dialog over Develop. The patches under the sample show the chosen output at half, full and double size, each at 100%, so grain and sharpening can be judged at the size that matters.
+
+ +

The options

+ + + + + + + + + +
OptionWhat it does
FormatJPEG, PNG or WebP. JPEG and WebP expose a quality slider from 40 to 100; PNG is lossless and shows no quality control.
ResizeFull resolution, Long edge in pixels, or Percent of the cropped size.
QualityEncoder quality for the lossy formats. 90–95 is visually lossless for most photographs.
File nameA template with the tokens {name}, {date}, {time} and {index}. The first resulting file name is shown underneath as you type.
SummaryThe number of photos in the batch and the output dimensions of the sample.
+ +

Judging the output

+

The sample thumbnail is a rendered preview of the crop. Click anywhere on it to move the 100% patches to that point of the photo — the patches are three views of the same detail at half the chosen size, the chosen size and double it, each rendered on its own pixel grid, with the grain cell size for that output printed underneath. This is how you decide whether grain will survive a downscale, or whether a sharpen amount is too high for the delivery size.

+ +

Running it

+

Press Export and the files are written one after another with a progress bar. Each file is downloaded by the browser; allow multiple downloads if your browser asks. When the batch finishes the dialog closes and a confirmation appears.

+

Everything you see on the canvas is baked into the file: crop, rotation, straighten, flips, white balance, tone curve, colour mixer, grading, vignette, grain, sharpening and noise reduction. There is no sidecar and no second step.

+ +
+ Exports reflect the crop. The dimensions in the summary are the cropped dimensions, so a tight 2×1 crop of a 6000-pixel frame produces a 3000-pixel wide file at full resolution. Check the summary before a large batch. +
+
+ + +
+
Chapter 14
+

Keyboard reference

+

The full map. Press ? at any time to see the same sheet inside the application.

+ +
+ The in-app shortcut sheet +
Figure 13. The shortcut sheet, grouped by where the keys apply. It closes with Esc or a click outside, and it is the reference the application ships with.
+
+ +

Library

+ + + + + + + + + + + + + + + + + + +
KeysAction
GGo to the library.
E / double-clickOpen the selected photo in Develop.
← → ↑ ↓Move the selection.
Shift + arrowsExtend the selection.
Home / EndFirst or last photo.
⌘ / Ctrl + ASelect all shown.
EscClear the selection.
0 – 5Star rating.
6 – 9Colour label: red, yellow, green, blue.
P / X / UPick · reject · unflag.
Delete / BackspaceDelete the selection.
⌘ / Ctrl + C / VCopy · paste develop settings.
⌘ / Ctrl + I / EImport · export.
?Shortcut sheet.
+ +

Develop

+ + + + + + + + + + + + + + +
KeysAction
CCrop mode on or off.
EnterApply the crop.
EscLeave crop mode, or return to the library.
ZFit ↔ 100%.
\ (hold)Before / after.
← →Previous · next photo.
Wheel · dragZoom at the cursor · pan.
⌘ / Ctrl + ZUndo the last adjustment.
⌘ / Ctrl + C / VCopy · paste settings.
?Shortcut sheet.
+ +

Mouse

+ + + + + + + + + + +
GestureAction
Click · Shift-click · ⌘/Ctrl-clickSelect · extend · toggle.
Drag on empty gridRubber-band select; Shift adds.
Right-click a cardContext menu for the selection.
Drag a card onto anotherReorder the catalogue.
Drag files onto the windowImport them.
Wheel over the filmstripScroll the strip sideways.
+ +

Dialogs

+

Esc closes the import, export and team-server dialogs without touching the photo behind them. Clicking the darkened area outside a dialog closes it too, as does the ✕ in its header. While a dialog is open the library and Develop shortcuts are suspended, so a stray X cannot reject a photo you cannot see.

+
+ + +
+
Chapter 15
+

The team server

+

Everything in this guide works without a server. The server adds three things: shared storage, raw decoding, and an account so a team can work from the same catalogue.

+ +

Starting it

+

Run npm run server — or npm start, which serves the built interface from the same process. With Docker, docker compose up starts the same service and mounts server/data as a volume.

+ +

Signing in

+

Click Sign in in the top bar. On a fresh server the Create admin tab is shown: the first account becomes the owner, and the invite code set in LUMENROOM_INVITE is what everyone else uses to join. If no server is reachable, the dialog says so and explains how to start one; the local library keeps working exactly as before.

+ +

What the server does

+
    +
  • Stores originals in server/data, alongside thumbnails and photo records, so the catalogue survives a browser reset and can be opened from another machine.
  • +
  • Decodes raws with LibRaw. The dialog reports whether the raw engine is available; when it is, raw files are demosaiced server-side and returned as editable proxies.
  • +
  • Reports capacity: photos on the server, storage used, raw engine state and server version, all visible once signed in.
  • +
+ +

Syncing

+

Sync library pushes local records and pulls anything the server has that this browser does not. Ratings, flags, colour labels and develop settings travel with the record, so a cull done on a laptop is visible on a desktop.

+ +
+ Local mode is not a degraded mode. Without a server the app is a complete single-machine editor; the server is about sharing and raw decoding, not about features being switched off. +
+
+ + +
+
Chapter 16
+

Troubleshooting and limits

+

The problems that come up in practice, and the things this application deliberately does not do yet.

+ +

Common problems

+ + + + + + + + + + +
SymptomCause and fix
Raw files will not importRaws need the server. Start it, sign in, and the staged batch decodes; the import dialog offers the sign-in button directly.
The canvas is black or blankWebGL 2 is unavailable or the GPU context was lost. Turn on hardware acceleration and reload.
Export downloads nothingThe browser blocked multiple downloads. Allow them for this site and run the export again.
Thumbnails stay greyThe bitmap for that photo has not been decoded yet, or it is a raw whose proxy never synced. Re-import or sync.
Storage quota errorsThe browser storage is full. Delete rejected photos, or move the catalogue to the team server.
A photo looks different after reloadEdits are stored as parameters; the preview is re-rendered from the original. If the original changed, the render changes with it.
+ +

Current limits

+
    +
  • No local masks. There are no brushes, graduated or radial filters, and no subject or sky selection. Adjustments are global to the crop.
  • +
  • No print module and no soft proofing. Delivery is a file export.
  • +
  • No tethered capture. Files are imported after the fact.
  • +
  • No plugin or sidecar ecosystem. Edits live in the catalogue record, not in XMP files next to the original.
  • +
  • Undo is linear. ⌘ / Ctrl + Z steps back; there is no separate redo stack. Use History to jump forward again.
  • +
  • Colour management is sRGB. Exports are tagged for standard displays and are not converted to a print profile.
  • +
+ +
+ If something looks wrong, press ? and compare. The shortcut sheet is generated from the same map the keyboard uses, so if a key is listed there it is live. +
+ +
Lumenroom User Guide · Version 1.0 · Screenshots captured from the running application at 1600 × 1000.
+
+ + +
+
Appendix A
+

Formats and badges

+ +

Import formats

+ + + + + + + + + + +
FormatDecoded by
JPEG (.jpg, .jpeg)Browser
PNG (.png)Browser
WebP (.webp)Browser
AVIF (.avif)Browser
TIFF (.tif, .tiff)Browser
Camera raw: CR2, CR3, CRW, NEF, NRW, ARW, SRF, SR2, ORF, RW2, RWL, RAF, PEF, DNG, SRW, 3FR, FFF, IIQ, X3F, ERF, K25, KDC, DCR, MOS, MRW, MEFTeam server (LibRaw)
+ +

Export formats

+

JPEG, PNG and WebP, at full resolution, a long-edge size, or a percentage of the cropped frame. Output dimensions always reflect the crop and any rotation.

+ +

Badges on a card

+ + + + + + + + + +
BadgeMeaning
RAWCamera raw. The tooltip says whether it is a demosaiced proxy or an embedded preview.
✓Picked.
✕Rejected. The card is dimmed.
✎The photo has develop adjustments.
Colour stripThe colour label, along the top edge of the card.
+ +

Files the server writes

+

Originals, thumbnails and the catalogue records live under server/data. Back that directory up and you have backed up the shared library; the browser copy is a cache of the same records plus the local-only photos.

+ +
End of guide.
+
+ + + diff --git a/lumenroom/docs/user-guide/img/01-library.jpg b/lumenroom/docs/user-guide/img/01-library.jpg new file mode 100644 index 0000000..7564b79 Binary files /dev/null and b/lumenroom/docs/user-guide/img/01-library.jpg differ diff --git a/lumenroom/docs/user-guide/img/02-filters.jpg b/lumenroom/docs/user-guide/img/02-filters.jpg new file mode 100644 index 0000000..925ef4d Binary files /dev/null and b/lumenroom/docs/user-guide/img/02-filters.jpg differ diff --git a/lumenroom/docs/user-guide/img/03-card.jpg b/lumenroom/docs/user-guide/img/03-card.jpg new file mode 100644 index 0000000..0338f7a Binary files /dev/null and b/lumenroom/docs/user-guide/img/03-card.jpg differ diff --git a/lumenroom/docs/user-guide/img/04-context-menu.jpg b/lumenroom/docs/user-guide/img/04-context-menu.jpg new file mode 100644 index 0000000..e5729c1 Binary files /dev/null and b/lumenroom/docs/user-guide/img/04-context-menu.jpg differ diff --git a/lumenroom/docs/user-guide/img/05-develop.jpg b/lumenroom/docs/user-guide/img/05-develop.jpg new file mode 100644 index 0000000..3bb33d4 Binary files /dev/null and b/lumenroom/docs/user-guide/img/05-develop.jpg differ diff --git a/lumenroom/docs/user-guide/img/06-crop.jpg b/lumenroom/docs/user-guide/img/06-crop.jpg new file mode 100644 index 0000000..9e35552 Binary files /dev/null and b/lumenroom/docs/user-guide/img/06-crop.jpg differ diff --git a/lumenroom/docs/user-guide/img/07-panels.jpg b/lumenroom/docs/user-guide/img/07-panels.jpg new file mode 100644 index 0000000..00737a1 Binary files /dev/null and b/lumenroom/docs/user-guide/img/07-panels.jpg differ diff --git a/lumenroom/docs/user-guide/img/08-presets.jpg b/lumenroom/docs/user-guide/img/08-presets.jpg new file mode 100644 index 0000000..fcfcdba Binary files /dev/null and b/lumenroom/docs/user-guide/img/08-presets.jpg differ diff --git a/lumenroom/docs/user-guide/img/09-export.jpg b/lumenroom/docs/user-guide/img/09-export.jpg new file mode 100644 index 0000000..46b1ef6 Binary files /dev/null and b/lumenroom/docs/user-guide/img/09-export.jpg differ diff --git a/lumenroom/docs/user-guide/img/10-import.jpg b/lumenroom/docs/user-guide/img/10-import.jpg new file mode 100644 index 0000000..1a2a7ca Binary files /dev/null and b/lumenroom/docs/user-guide/img/10-import.jpg differ diff --git a/lumenroom/docs/user-guide/img/11-shortcuts.jpg b/lumenroom/docs/user-guide/img/11-shortcuts.jpg new file mode 100644 index 0000000..f431c6a Binary files /dev/null and b/lumenroom/docs/user-guide/img/11-shortcuts.jpg differ diff --git a/lumenroom/docs/user-guide/img/12-crop-detail.jpg b/lumenroom/docs/user-guide/img/12-crop-detail.jpg new file mode 100644 index 0000000..8db22d9 Binary files /dev/null and b/lumenroom/docs/user-guide/img/12-crop-detail.jpg differ diff --git a/lumenroom/docs/user-guide/img/13-filtered.jpg b/lumenroom/docs/user-guide/img/13-filtered.jpg new file mode 100644 index 0000000..9177607 Binary files /dev/null and b/lumenroom/docs/user-guide/img/13-filtered.jpg differ diff --git a/lumenroom/index.html b/lumenroom/index.html new file mode 100644 index 0000000..62dd980 --- /dev/null +++ b/lumenroom/index.html @@ -0,0 +1,13 @@ + + + + + + + Lumenroom + + +
+ + + diff --git a/lumenroom/package-lock.json b/lumenroom/package-lock.json new file mode 100644 index 0000000..c850c5c --- /dev/null +++ b/lumenroom/package-lock.json @@ -0,0 +1,2436 @@ +{ + "name": "lumenroom", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "lumenroom", + "version": "0.1.0", + "dependencies": { + "exifr": "^7.1.3", + "libraw-wasm": "^1.6.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "sharp": "^0.35.5" + }, + "devDependencies": { + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.6.3", + "vite": "^5.4.11" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.15.tgz", + "integrity": "sha512-gNWJUX0FlevflramOkaInywOMhU1lkln38gAC7TFZv2tsWbLYbN/2WZFGcq8zbX0Z55e4vGa27IB/NaeZoauWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.15", + "@babel/types": "^7.29.15", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz", + "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.15.tgz", + "integrity": "sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.15.tgz", + "integrity": "sha512-l+ezV2czw3t2d2ELq+3CwPL4WLKK5O8IywBXb9/gpmbCOVZFmRYJPmHVqSCv2k+8iKbE30Zf54siOoIZ52XOxA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.15.tgz", + "integrity": "sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.15" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.15.tgz", + "integrity": "sha512-ZfawBo2i8vvt+BTt37dWDKBPjUfm/H+bw+ltwsCRhW7gPtyNVwUXuNo54eO2Xo+P4VXpalPFfFISbBTRKC8SOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.15", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.15", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.15.tgz", + "integrity": "sha512-/XKpKDakL//LZ66bq1XsZOswuqeI5MZqPLDu18o3XdkU1fNJ7bdPtzgnc4ZNS+bBGHV0FJG8jjb8SwcC3nNVQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.15", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.7.tgz", + "integrity": "sha512-ZL7MgOeMUiBum1bjzzyBotE3DuHVz+UUxcDVlLL7gpdhDM4RpjG4bZOIly7ensIcXw9jhWl7HTIIQ9KsgjykGQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.7.tgz", + "integrity": "sha512-cKZ2Hz/xt5DLY/vdUmMXEn3gnjLgwdeB/npHagbdTljLvBE6b/xKcPCcRWTiT0pHeVf8akl5Cb9K7ylRxbtHng==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.7.tgz", + "integrity": "sha512-P9vs1uCC2drepKKuiXrhY+r7ry/jtDCrBS8SUCYm2Rr7rVTR9eFH6XVAmD9TdfYFlDgRe5r1eH8tLQVuz+l/VA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.7.tgz", + "integrity": "sha512-Lgu2AV7jbOTNNhkQ/OurNm7Snqu1Ux/3y7k8q47fbpPa3q63aIzKKp1xFzax5KH4pcdUzbnX/riuFsxKflsF+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.7.tgz", + "integrity": "sha512-wKo6rOzla+/3rN8QBqTgcrsQMfyqwa3y14TvCTotLLib/ACWTxX1zWDTYze90s2RWtYiSfTlavHLmZv0Jsafrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.7.tgz", + "integrity": "sha512-vAeCwbFyEu/vBt9O/uHCHJSvwtOpTSssnM/PoZgn8rmvAkS+9ixaUfJZ2IP3ltom+rvpuQQEIEqltPY7qhC9lQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.7.tgz", + "integrity": "sha512-HvjSxOKI+6Si4ytmaoCEpjwDMrH/1s0uWeTAhdE5oXY8/RMI92hCePI/psZuJtY5EHWoT7MfyvTz0HBDZb1ZwQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.7.tgz", + "integrity": "sha512-nz/Eu1sag3w5gPiKLJhAbKa4D9hUUJpDc9XzKXxGNHZqwgT2AbuVS2e4k9CIoLQp5dPhSN9ntiEVuz2jTzu1Gg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.7.tgz", + "integrity": "sha512-05CEv2G/kI261A1WQBZL8gx6xXULjPfVnTKAkfnV/0uqHeLo+dNEOeUzMaiK/HDGR0Z1Nn7KJjm/34bNbNcfTA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.7.tgz", + "integrity": "sha512-wrqk3EkxQt98lTdiYhjcaWmFHwvKiSgHFi7XmPTSF4X8+uGUTBOAc0CaynEvpUhBgkPRbwASrYoU/5uJPF+LFA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.7.tgz", + "integrity": "sha512-DnuEUWvzeSxHxzu5lvrN+I/UzrcQkR/fQ4Bibetdp73Rf7aP0XgFpalSDuHmVWsCLETE+Lrl3GVOqIvFP7rcjw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.7.tgz", + "integrity": "sha512-n0sr2s+rzVw8ntRucOxGhWeJ9lEl9KxCRzF3RmnZLE/tRnfKiloLuK8UqWrKFqVigEAh0IkRkPz5LVaV9/ZfvA==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.7.tgz", + "integrity": "sha512-qDVJyMCbh7ekjt1kM9CZsyCFZvv5UW1QTIx3YfJ/gh8LkqpoPNpl9dCeYeOa+bsDOGTWZiMG2riXuoFSRISimQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.7.tgz", + "integrity": "sha512-GiIOHHIzgpMoR5DT1pA1b9qMk5i0Ngg2FRj4D6XFSBC8e/axHuIdB7K/OBozO2RtCVAMnH1rXcuJrGScg+bvzA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.7.tgz", + "integrity": "sha512-B132V2fwDl7UGLhvK6s3Ay7eNQ4dmDSDgsBm/Wwbz+Wgnunz0le4R2wzDp6TL5ExMu3MC1auJIrVtk2gOyxbyw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.7.tgz", + "integrity": "sha512-3NueHQilbssjxgJMx9hXBV+U5keb3CBzmW5WhoBG3iSLFcmz9U2FVoG4MUYpZoZ+KSNMQPN2AA79dTxlEF0VxQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.7.tgz", + "integrity": "sha512-8XRwbf76oAF1zZzg6OT8EY3swvCptZnLmiqMgO5+STyhTZ9s7rXa+tY8jESZW9IDyKACcVBGqa/RACDaLzRVjQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.7.tgz", + "integrity": "sha512-pvqqfjNdxVLvmovH681K5cPIL9DXj5n1RROaa0vb9JrtHddiScLrkHPRKj5flTKHF1M7xvRy0SS2yTRIc2TO0Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.7.tgz", + "integrity": "sha512-rsTjTf5HAm6F4sI6uUfJf2pc+7AWBKxgc2RveGvwB2OvVa1GezSSCDD1rtXPuFhcg3itPv7iHgcZsq/RwWvJ4Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.7.tgz", + "integrity": "sha512-VNLvsYMD5+zLCi5SohwDdL8PpicC9PnArLwyMJXXUcAduzrM3k9aZT9XiHw+mn5dOWr3UEyfyqJbOvxwJ2fCWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.7.tgz", + "integrity": "sha512-7aOjdahkwiECWWOmjAemPd21yeQ18TW59DUiLWttzolMe5tDwHyBhlOfmxRUHOQnepTNkZ2Qwp1T6LxFZ5v7yQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.7.tgz", + "integrity": "sha512-BnNkTwE4FMCAoz3UYiJ6D6Y3pGozYIYZ2W+onH64uhiTI2iwD3KOaNSlkuHYfupZVemls3YTlvbPnuKwHsraiQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.7.tgz", + "integrity": "sha512-OH8tGWsJcRW6Vn0dmndyWJGdQa46bH2/2/PVfleBGUWuBd5/HVkIvw2UslgBwUZdtV78bJaoCNBmYI5+bcTJ4A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.7.tgz", + "integrity": "sha512-SpYx5X9+2JOF3hXe1cRaiFn562h4AMJhfgxkyHyiuh9dJ7PanPm7FTp8GJReSbS9N+TfjRiBbKacVk1g35kKxg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.7.tgz", + "integrity": "sha512-0ncKtQ55fqElV9Sk4cZ/4tiXVGlWxaH5PvDOlx1Sx8GuHIpSWgYrTcyrO51JnVFfy7LvAJiffkEg63ZHKwTMag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.7.tgz", + "integrity": "sha512-XY9DYHO5UxxVR8G6AErXDlccQmDpvGTLgKHFpvkgsyjwG/PrQuInRjQQfpEzBRuT+bhBtwfS8yDe9sPhVcq/9A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.31", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz", + "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.7", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz", + "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^18.0.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.39", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz", + "integrity": "sha512-Q9buOYhr2ggrEZpImICecZTJHCCd8yXkRUokFlUEQ8uiD6oP82F4W4jWnhOHZYV+wlvrC51V7Wy0ULyWjil5Wg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.6", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", + "integrity": "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.37", + "caniuse-lite": "^1.0.30001826", + "electron-to-chromium": "^1.5.486", + "node-releases": "^2.0.64", + "update-browserslist-db": "^1.4.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.492", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.492.tgz", + "integrity": "sha512-4uMs7omhajKiud0GqALLTazS/zyvHLTLmDWVTR+e6BnyJo5bSNrph/JoRWEFJJmY75ct9hCiSGsbFF9fLe5gDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/exifr": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/exifr/-/exifr-7.1.3.tgz", + "integrity": "sha512-g/aje2noHivrRSLbAUtBPWFbxKdKhgj/xr1vATDdUXPOFYJlQ62Ft0oy+72V6XLIpDJfHs6gXLbBLAolqOXYRw==", + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/libraw-wasm": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/libraw-wasm/-/libraw-wasm-1.6.0.tgz", + "integrity": "sha512-VfvWq2XGGkc07wexymRLn1H82j6smmC1LAbVl41vnW2Z5RrEPLN+YHi1Hmga2TbxxrY4rOjmTwHwSyTZmypE1g==", + "license": "ISC" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.65", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.65.tgz", + "integrity": "sha512-PfvofsGQ+MiOQIPkX9fU8ELUWmy5zL74CdQaph/ismKszfFkfwXaw0cGiwbwym2hT9k5+mdyl8O5WQ1MD8EHmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.7.tgz", + "integrity": "sha512-CxhzUIc+ocxPAWxHuff+PAluoW1otD6dHqqPK2h2Q38WA1VYk+3gizX6NEg5t2a8yNGQaiHM1R7V+qdwWuvp5Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.7", + "@rollup/rollup-android-arm64": "4.68.7", + "@rollup/rollup-android-x64": "4.68.7", + "@rollup/rollup-darwin-arm64": "4.68.7", + "@rollup/rollup-darwin-x64": "4.68.7", + "@rollup/rollup-freebsd-arm64": "4.68.7", + "@rollup/rollup-freebsd-x64": "4.68.7", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.7", + "@rollup/rollup-linux-arm-musleabihf": "4.68.7", + "@rollup/rollup-linux-arm64-gnu": "4.68.7", + "@rollup/rollup-linux-arm64-musl": "4.68.7", + "@rollup/rollup-linux-loong64-gnu": "4.68.7", + "@rollup/rollup-linux-loong64-musl": "4.68.7", + "@rollup/rollup-linux-ppc64-gnu": "4.68.7", + "@rollup/rollup-linux-ppc64-musl": "4.68.7", + "@rollup/rollup-linux-riscv64-gnu": "4.68.7", + "@rollup/rollup-linux-riscv64-musl": "4.68.7", + "@rollup/rollup-linux-s390x-gnu": "4.68.7", + "@rollup/rollup-linux-x64-gnu": "4.68.7", + "@rollup/rollup-linux-x64-musl": "4.68.7", + "@rollup/rollup-openbsd-x64": "4.68.7", + "@rollup/rollup-openharmony-arm64": "4.68.7", + "@rollup/rollup-win32-arm64-msvc": "4.68.7", + "@rollup/rollup-win32-ia32-msvc": "4.68.7", + "@rollup/rollup-win32-x64-gnu": "4.68.7", + "@rollup/rollup-win32-x64-msvc": "4.68.7", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.4.0.tgz", + "integrity": "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/lumenroom/package.json b/lumenroom/package.json new file mode 100644 index 0000000..15212a7 --- /dev/null +++ b/lumenroom/package.json @@ -0,0 +1,29 @@ +{ + "name": "lumenroom", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "server": "node server/index.mjs", + "server:dev": "node --watch server/index.mjs", + "build": "tsc --noEmit && vite build", + "start": "node server/index.mjs", + "preview": "vite preview", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "exifr": "^7.1.3", + "libraw-wasm": "^1.6.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "sharp": "^0.35.5" + }, + "devDependencies": { + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.6.3", + "vite": "^5.4.11" + } +} diff --git a/lumenroom/public/lumenroom-user-guide.pdf b/lumenroom/public/lumenroom-user-guide.pdf new file mode 100644 index 0000000..3fadfac Binary files /dev/null and b/lumenroom/public/lumenroom-user-guide.pdf differ diff --git a/lumenroom/server/auth.mjs b/lumenroom/server/auth.mjs new file mode 100644 index 0000000..fcb41ec --- /dev/null +++ b/lumenroom/server/auth.mjs @@ -0,0 +1,58 @@ +import crypto from 'node:crypto'; +import { SESSION_DAYS } from './config.mjs'; +import { sessions, users } from './db.mjs'; + +const KEYLEN = 64; + +export function hashPassword(password) { + const salt = crypto.randomBytes(16); + const hash = crypto.scryptSync(password, salt, KEYLEN); + return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`; +} + +export function verifyPassword(password, stored) { + const [scheme, saltHex, hashHex] = String(stored).split('$'); + if (scheme !== 'scrypt' || !saltHex || !hashHex) return false; + const expected = Buffer.from(hashHex, 'hex'); + const actual = crypto.scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length); + return expected.length === actual.length && crypto.timingSafeEqual(expected, actual); +} + +export function createSession(userId) { + const token = crypto.randomBytes(32).toString('hex'); + const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000; + sessions.purge(); + sessions.create(token, userId, expiresAt); + return token; +} + +export function publicUser(row) { + if (!row) return null; + return { + id: row.id, + email: row.email, + name: row.name ?? '', + role: row.role ?? 'member', + }; +} + +export function authenticate(req) { + const header = String(req.headers.authorization ?? ''); + const token = header.startsWith('Bearer ') ? header.slice(7).trim() : ''; + if (!token) return null; + const session = sessions.find(token); + if (!session) return null; + if (Number(session.expires_at) < Date.now()) { + sessions.destroy(token); + return null; + } + return publicUser(users.byId(session.user_id)); +} + +export function normalizeEmail(value) { + return typeof value === 'string' ? value.trim().toLowerCase() : ''; +} + +export function validEmail(email) { + return /^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(email); +} diff --git a/lumenroom/server/bridge.mjs b/lumenroom/server/bridge.mjs new file mode 100644 index 0000000..4256b07 --- /dev/null +++ b/lumenroom/server/bridge.mjs @@ -0,0 +1,265 @@ +/** + * Bridge to the Media Team Hub dashboard. + * + * The dashboard signs a short-lived token scoped to one event; this module + * verifies it, exchanges it for a service token, mirrors the event's photo list + * into the local catalog, and proxies bytes/save-backs for as long as the + * bridge session lives. Nothing here is reachable without a valid token. + */ + +import crypto from 'node:crypto'; +import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs'; +import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs'; +import { removeAsset } from './storage.mjs'; + +const VERSION = 'g1'; + +/* ------------------------------------------------------------------- tokens */ + +export function bridgeConfigured() { + return Boolean(BRIDGE_SECRET && GLENLOCH_URL); +} + +export function verifyBridgeToken(token, now = Date.now()) { + if (!BRIDGE_SECRET || typeof token !== 'string') return null; + const parts = token.split('.'); + if (parts.length !== 3 || parts[0] !== VERSION) return null; + const [, body, signature] = parts; + + const expected = crypto.createHmac('sha256', BRIDGE_SECRET).update(body).digest(); + let supplied; + try { + supplied = Buffer.from(signature.replace(/-/g, '+').replace(/_/g, '/'), 'base64'); + } catch { + return null; + } + if ( + supplied.length !== expected.length || + !crypto.timingSafeEqual(supplied, expected) + ) { + return null; + } + + let payload; + try { + payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')); + } catch { + return null; + } + if ( + !payload || + typeof payload.sid !== 'string' || + typeof payload.eid !== 'string' || + typeof payload.uid !== 'string' || + typeof payload.email !== 'string' || + (payload.kind !== 'login' && payload.kind !== 'service') || + typeof payload.exp !== 'number' || + payload.exp * 1000 <= now + ) { + return null; + } + return payload; +} + +async function dashboardJson(url, token, init = {}) { + const res = await fetch(url, { + ...init, + headers: { + ...(init.headers ?? {}), + authorization: `Bearer ${token}`, + }, + }); + const text = await res.text(); + let body = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = null; + } + if (!res.ok) { + throw new Error(body?.error || `Dashboard request failed (${res.status})`); + } + return body; +} + +/** Swap the one browser-hop login token for a longer server-side token. */ +export async function exchangeBridgeToken(loginToken, sessionId) { + return dashboardJson( + `${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}/exchange`, + loginToken, + { method: 'POST' }, + ); +} + +/* ------------------------------------------------------------------ storage */ + +const bridgeInsert = db.prepare(` + INSERT INTO bridge_events (event_id, session_id, token, glenloch_url, source_event_id, return_url, expires_at, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(event_id) DO UPDATE SET + session_id = excluded.session_id, + token = excluded.token, + glenloch_url = excluded.glenloch_url, + source_event_id = excluded.source_event_id, + return_url = excluded.return_url, + expires_at = excluded.expires_at, + created_at = excluded.created_at +`); +const bridgeGet = db.prepare('SELECT * FROM bridge_events WHERE event_id = ?'); +const bridgeExpired = db.prepare('SELECT event_id FROM bridge_events WHERE expires_at < ?'); +const bridgeDelete = db.prepare('DELETE FROM bridge_events WHERE event_id = ?'); +const photosForEvent = db.prepare('SELECT id FROM photos WHERE event_id = ?'); + +export function bridgeEventId(sourceEventId) { + return `br-${sourceEventId}`; +} + +export function bridgePhotoId(sourcePhotoId) { + return `br-${sourcePhotoId}`; +} + +export function bridgeForEvent(eventId) { + return bridgeGet.get(eventId) ?? null; +} + +/** Deletes an imported event, its rows and any cached previews/thumbnails. */ +function dropBridgeEvent(eventId) { + for (const row of photosForEvent.all(eventId)) { + removePhoto(row.id); + removeAsset(row.id).catch(() => undefined); + } + removeEvent(eventId); + bridgeDelete.run(eventId); +} + +/** Removes events whose bridge session has expired. Safe to call often. */ +export function purgeExpiredBridges(now = Date.now()) { + for (const row of bridgeExpired.all(now)) { + dropBridgeEvent(row.event_id); + } +} + +function eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt) { + const source = listing.event; + return { + id: eventId, + name: source.title || 'Advanced edit', + date: source.startsAt ? Date.parse(source.startsAt) : Date.now(), + createdAt: Date.now(), + notes: source.description ?? undefined, + bridge: { + sessionId, + sourceEventId: source.id, + dashboardUrl: returnUrl ?? `${GLENLOCH_URL}/events/${source.id}`, + expiresAt, + }, + }; +} + +function photoRecordFrom(photo, eventId, sessionId, index) { + const id = bridgePhotoId(photo.id); + const raw = photo.kind === 'raw'; + return { + id, + eventId, + order: index, + name: photo.filename, + width: photo.width || 0, + height: photo.height || 0, + size: photo.sizeBytes || 0, + mime: photo.mimeType || 'application/octet-stream', + addedAt: Date.now(), + takenAt: photo.takenAt ? Date.parse(photo.takenAt) : undefined, + meta: {}, + thumb: '', + thumbUrl: `/api/photos/${id}/thumb`, + rating: 0, + flag: 'none', + color: '', + keywords: [], + edits: {}, + history: [], + raw, + previewUrl: raw ? `/api/photos/${id}/preview` : undefined, + bridgeSource: { sessionId, sourceId: photo.id }, + }; +} + +/** + * Mirrors one event into the local catalog. The photo bytes stay on the + * dashboard; only metadata, previews and thumbnails are temporary here. + */ +export async function importBridgeEvent({ serviceToken, sessionId }) { + const expiresAt = + Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000; + + const listing = await dashboardJson( + `${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}`, + serviceToken, + ); + const eventId = bridgeEventId(listing.event.id); + dropBridgeEvent(eventId); + + const returnUrl = listing.editor?.returnUrl ?? null; + saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0); + listing.photos.forEach((photo, index) => { + savePhoto(photoRecordFrom(photo, eventId, sessionId, index)); + }); + bridgeInsert.run( + eventId, + sessionId, + serviceToken, + GLENLOCH_URL, + listing.event.id, + returnUrl, + expiresAt, + Date.now(), + ); + + return { + eventId, + photoCount: listing.photos.length, + sessionId, + expiresAt, + }; +} + +/* ----------------------------------------------------------------- proxying */ + +export function bridgeSourceUrl(row, sourcePhotoId, variant) { + const params = new URLSearchParams({ variant }); + return `${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent( + row.session_id, + )}/photos/${encodeURIComponent(sourcePhotoId)}/source?${params}`; +} + +export async function fetchBridgeImage(row, sourcePhotoId, variant) { + return fetch(bridgeSourceUrl(row, sourcePhotoId, variant), { + headers: { authorization: `Bearer ${row.token}` }, + }); +} + +/** Forwards a browser-rendered JPEG and recipe to the dashboard. */ +export async function forwardBridgeRender(row, sourcePhotoId, payload) { + const res = await fetch( + `${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent( + row.session_id, + )}/photos/${encodeURIComponent(sourcePhotoId)}/render`, + { + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: `Bearer ${row.token}`, + }, + body: JSON.stringify(payload), + }, + ); + const text = await res.text(); + let body = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = null; + } + return { status: res.status, body }; +} diff --git a/lumenroom/server/config.mjs b/lumenroom/server/config.mjs new file mode 100644 index 0000000..52311ff --- /dev/null +++ b/lumenroom/server/config.mjs @@ -0,0 +1,51 @@ +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); + +export const ROOT = path.resolve(here, '..'); +export const DATA_DIR = process.env.LUMENROOM_DATA + ? path.resolve(process.env.LUMENROOM_DATA) + : path.join(here, 'data'); + +export const ORIGINAL_DIR = path.join(DATA_DIR, 'originals'); +export const PREVIEW_DIR = path.join(DATA_DIR, 'previews'); +export const THUMB_DIR = path.join(DATA_DIR, 'thumbs'); +export const DB_PATH = path.join(DATA_DIR, 'lumenroom.db'); +export const DIST_DIR = path.join(ROOT, 'dist'); + +export const PORT = Number(process.env.PORT || 8787); +export const HOST = process.env.HOST || '0.0.0.0'; + +/** Shared invite code required to register after the first account exists. */ +export const INVITE = process.env.LUMENROOM_INVITE || ''; + +/** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */ +export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, ''); + +/** Shared HMAC secret for bridge tokens; must match the dashboard's value. */ +export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || ''; + +/** How long an imported bridge event survives without being reopened. */ +export const BRIDGE_TTL_HOURS = Number(process.env.LUMENROOM_BRIDGE_TTL_HOURS || 12); + +/** Upload ceiling in bytes (300 MB default, bigger than any consumer raw). */ +export const MAX_UPLOAD = Number(process.env.LUMENROOM_MAX_UPLOAD || 300 * 1024 * 1024); + +/** Long edge used for the editable proxy of raw files. */ +export const RAW_PREVIEW_EDGE = Number(process.env.LUMENROOM_RAW_EDGE || 6000); + +export const SESSION_DAYS = 30; + +/** How many raws decode at once. One core is left for the HTTP server. */ +export const RAW_WORKERS = Math.max( + 1, + Number( + process.env.LUMENROOM_RAW_WORKERS || + Math.min(4, Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1)), + ), +); + +/** Idle decoder workers are disposed after this long to release memory. */ +export const RAW_IDLE_MS = Number(process.env.LUMENROOM_RAW_IDLE_MS || 90_000); diff --git a/lumenroom/server/db.mjs b/lumenroom/server/db.mjs new file mode 100644 index 0000000..2a58c1a --- /dev/null +++ b/lumenroom/server/db.mjs @@ -0,0 +1,177 @@ +import fs from 'node:fs'; +import { DatabaseSync } from 'node:sqlite'; +import { DATA_DIR, DB_PATH } from './config.mjs'; + +fs.mkdirSync(DATA_DIR, { recursive: true }); + +export const db = new DatabaseSync(DB_PATH); + +db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA foreign_keys = ON; + + CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + email TEXT NOT NULL UNIQUE, + name TEXT NOT NULL DEFAULT '', + pass_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'member', + created_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS events ( + id TEXT PRIMARY KEY, + sort_index REAL NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + data TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS photos ( + id TEXT PRIMARY KEY, + event_id TEXT NOT NULL DEFAULT '', + sort_index REAL NOT NULL DEFAULT 0, + updated_at INTEGER NOT NULL, + raw INTEGER NOT NULL DEFAULT 0, + data TEXT NOT NULL + ); + + CREATE INDEX IF NOT EXISTS photos_event ON photos(event_id); + CREATE INDEX IF NOT EXISTS photos_updated ON photos(updated_at); + + CREATE TABLE IF NOT EXISTS kv ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS bridge_events ( + event_id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + token TEXT NOT NULL, + glenloch_url TEXT NOT NULL, + source_event_id TEXT NOT NULL, + return_url TEXT, + expires_at INTEGER NOT NULL, + created_at INTEGER NOT NULL + ); +`); + +const q = { + upsertEvent: db.prepare(` + INSERT INTO events (id, sort_index, created_at, data) VALUES (?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET sort_index = excluded.sort_index, data = excluded.data + `), + deleteEvent: db.prepare('DELETE FROM events WHERE id = ?'), + allEvents: db.prepare('SELECT data FROM events ORDER BY sort_index ASC, created_at ASC'), + + upsertPhoto: db.prepare(` + INSERT INTO photos (id, event_id, sort_index, updated_at, raw, data) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + event_id = excluded.event_id, + sort_index = excluded.sort_index, + updated_at = excluded.updated_at, + raw = excluded.raw, + data = excluded.data + `), + deletePhoto: db.prepare('DELETE FROM photos WHERE id = ?'), + allPhotos: db.prepare('SELECT data FROM photos ORDER BY sort_index ASC, updated_at ASC'), + photo: db.prepare('SELECT data FROM photos WHERE id = ?'), + photoCount: db.prepare('SELECT COUNT(*) AS n FROM photos'), + + findUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'), + insertUser: db.prepare( + 'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)', + ), + userCount: db.prepare('SELECT COUNT(*) AS n FROM users'), + findUserById: db.prepare('SELECT id, email, name, role, created_at FROM users WHERE id = ?'), + + insertSession: db.prepare( + 'INSERT INTO sessions (token, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)', + ), + findSession: db.prepare('SELECT * FROM sessions WHERE token = ?'), + deleteSession: db.prepare('DELETE FROM sessions WHERE token = ?'), + purgeSessions: db.prepare('DELETE FROM sessions WHERE expires_at < ?'), + + kvGet: db.prepare('SELECT value FROM kv WHERE key = ?'), + kvSet: db.prepare( + 'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value', + ), +}; + +function parse(json) { + if (!json) return null; + try { + return JSON.parse(json); + } catch { + return null; + } +} + +export function listEvents() { + return q.allEvents.all().map((r) => parse(r.data)).filter((r) => r !== null); +} + +export function saveEvent(record, sortIndex = 0) { + q.upsertEvent.run(record.id, sortIndex, record.createdAt ?? Date.now(), JSON.stringify(record)); +} + +export function removeEvent(id) { + q.deleteEvent.run(id); +} + +export function listPhotos() { + return q.allPhotos.all().map((r) => parse(r.data)).filter((r) => r !== null); +} + +export function getPhoto(id) { + const row = q.photo.get(id); + return row ? parse(row.data) : null; +} + +export function savePhoto(record, updatedAt = Date.now()) { + q.upsertPhoto.run( + record.id, + record.eventId ?? '', + typeof record.order === 'number' ? record.order : 0, + updatedAt, + record.raw ? 1 : 0, + JSON.stringify(record), + ); +} + +export function removePhoto(id) { + q.deletePhoto.run(id); +} + +export function countPhotos() { + return Number(q.photoCount.get()?.n ?? 0); +} + +export const users = { + count: () => Number(q.userCount.get()?.n ?? 0), + byEmail: (email) => q.findUserByEmail.get(String(email).toLowerCase()), + byId: (id) => q.findUserById.get(id), + create: (user) => + q.insertUser.run(user.id, user.email.toLowerCase(), user.name, user.passHash, user.role, Date.now()), +}; + +export const sessions = { + create: (token, userId, expiresAt) => q.insertSession.run(token, userId, Date.now(), expiresAt), + find: (token) => q.findSession.get(token), + destroy: (token) => q.deleteSession.run(token), + purge: () => q.purgeSessions.run(Date.now()), +}; + +export const kv = { + get: (key) => { + const row = q.kvGet.get(key); + return row ? parse(row.value) : null; + }, + set: (key, value) => q.kvSet.run(key, JSON.stringify(value)), +}; diff --git a/lumenroom/server/imaging.mjs b/lumenroom/server/imaging.mjs new file mode 100644 index 0000000..eacb214 --- /dev/null +++ b/lumenroom/server/imaging.mjs @@ -0,0 +1,129 @@ +import zlib from 'node:zlib'; +import { RAW_PREVIEW_EDGE } from './config.mjs'; + +let sharpModule = null; +let sharpFailed = false; + +/** sharp gives us JPEG encoding and resizing; without it we fall back to PNG. */ +export async function loadSharp() { + if (sharpModule) return sharpModule; + if (sharpFailed) return null; + try { + const mod = await import('sharp'); + sharpModule = mod.default; + return sharpModule; + } catch { + sharpFailed = true; + return null; + } +} + +const CRC_TABLE = (() => { + const table = new Int32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c; + } + return table; +})(); + +function crc32(buf) { + let c = 0xffffffff; + for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function chunk(type, data) { + const out = Buffer.alloc(8 + data.length + 4); + out.writeUInt32BE(data.length, 0); + out.write(type, 4, 'ascii'); + data.copy(out, 8); + out.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, 'ascii'), data])), 8 + data.length); + return out; +} + +/** Minimal dependency-free 8-bit RGB PNG encoder (used only when sharp is absent). */ +export function encodePng(rgb, width, height) { + const stride = width * 3; + const raw = Buffer.alloc((stride + 1) * height); + for (let y = 0; y < height; y++) { + raw[y * (stride + 1)] = 0; + Buffer.from(rgb.buffer, rgb.byteOffset + y * stride, stride).copy(raw, y * (stride + 1) + 1); + } + const idat = zlib.deflateSync(raw, { level: 6 }); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; + ihdr[9] = 2; + ihdr[10] = 0; + ihdr[11] = 0; + ihdr[12] = 0; + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', ihdr), + chunk('IDAT', idat), + chunk('IEND', Buffer.alloc(0)), + ]); +} + +/** Encode an interleaved RGB byte buffer as JPEG (sharp) or PNG (fallback). */ +export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) { + const sharp = await loadSharp(); + if (!sharp) { + return { data: encodePng(rgb, width, height), ext: 'png', width, height }; + } + let img = sharp(Buffer.from(rgb.buffer, rgb.byteOffset, rgb.byteLength), { + raw: { width, height, channels: 3 }, + }); + if (maxEdge > 0 && Math.max(width, height) > maxEdge) img = img.resize({ width: width >= height ? maxEdge : null, height: height > width ? maxEdge : null, fit: 'inside' }); + const data = await img.jpeg({ quality, chromaSubsampling: '4:4:4' }).toBuffer(); + const meta = await sharp(data).metadata(); + return { data, ext: 'jpg', width: Number(meta.width ?? width), height: Number(meta.height ?? height) }; +} + +export async function jpegInfo(buffer) { + const sharp = await loadSharp(); + if (!sharp) return null; + try { + const meta = await sharp(buffer).metadata(); + return { width: Number(meta.width ?? 0), height: Number(meta.height ?? 0), format: meta.format }; + } catch { + return null; + } +} + +/** Re-encode any decodable image to a normalised JPEG proxy. */ +export async function toJpegProxy(buffer, maxEdge = RAW_PREVIEW_EDGE) { + const sharp = await loadSharp(); + if (!sharp) return null; + try { + let img = sharp(buffer, { failOn: 'none' }).rotate(); + const meta = await img.metadata(); + const w = Number(meta.width ?? 0); + const h = Number(meta.height ?? 0); + if (!w || !h) return null; + if (maxEdge > 0 && Math.max(w, h) > maxEdge) img = img.resize({ width: maxEdge, height: maxEdge, fit: 'inside' }); + const data = await img.jpeg({ quality: 92, chromaSubsampling: '4:4:4' }).toBuffer(); + const outMeta = await sharp(data).metadata(); + return { data, width: Number(outMeta.width ?? w), height: Number(outMeta.height ?? h), ext: 'jpg' }; + } catch { + return null; + } +} + +export async function makeThumb(buffer, edge = 512) { + const sharp = await loadSharp(); + if (!sharp) return null; + try { + const data = await sharp(buffer, { failOn: 'none' }) + .rotate() + .resize({ width: edge, height: edge, fit: 'inside', withoutEnlargement: true }) + .jpeg({ quality: 82 }) + .toBuffer(); + return data; + } catch { + return null; + } +} diff --git a/lumenroom/server/index.mjs b/lumenroom/server/index.mjs new file mode 100644 index 0000000..c280634 --- /dev/null +++ b/lumenroom/server/index.mjs @@ -0,0 +1,591 @@ +import http from 'node:http'; +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { + DATA_DIR, + DIST_DIR, + HOST, + INVITE, + MAX_UPLOAD, + PORT, + RAW_PREVIEW_EDGE, +} from './config.mjs'; +import { + authenticate, + createSession, + hashPassword, + normalizeEmail, + publicUser, + validEmail, + verifyPassword, +} from './auth.mjs'; +import { + countPhotos, + getPhoto, + kv, + listEvents, + listPhotos, + removeEvent, + removePhoto, + saveEvent, + savePhoto, + sessions, + users, +} from './db.mjs'; +import { + findOriginal, + findPreview, + findThumb, + removeAsset, + storageBytes, + writeOriginal, + writePreview, + writeThumb, +} from './storage.mjs'; +import { decodeRaw, isRawName, rawSupport } from './raw.mjs'; +import { + bridgeConfigured, + bridgeForEvent, + exchangeBridgeToken, + fetchBridgeImage, + forwardBridgeRender, + importBridgeEvent, + purgeExpiredBridges, + verifyBridgeToken, +} from './bridge.mjs'; +import { jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs'; + +const VERSION = '1.0.0'; +const COOKIE = 'lumen_session'; + +/* ------------------------------------------------------------------ helpers */ + +function json(res, status, payload, extraHeaders = {}) { + const body = Buffer.from(JSON.stringify(payload)); + res.writeHead(status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': body.length, + 'Cache-Control': 'no-store', + ...extraHeaders, + }); + res.end(body); +} + +function error(res, status, message) { + json(res, status, { error: message }); +} + +function parseCookies(req) { + const out = {}; + for (const part of String(req.headers.cookie ?? '').split(';')) { + const idx = part.indexOf('='); + if (idx < 0) continue; + out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim()); + } + return out; +} + +function sessionCookie(req, token, maxAge) { + const secure = req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : ''; + return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`; +} + +function currentUser(req) { + const cookieToken = parseCookies(req)[COOKIE]; + if (cookieToken) { + const row = sessions.find(cookieToken); + if (row && Number(row.expires_at) > Date.now()) return publicUser(users.byId(row.user_id)); + } + return authenticate(req); +} + +function readBody(req, limit = MAX_UPLOAD) { + return new Promise((resolve, reject) => { + const chunks = []; + let size = 0; + req.on('data', (chunk) => { + size += chunk.length; + if (size > limit) { + reject(new Error(`Upload exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`)); + req.destroy(); + return; + } + chunks.push(chunk); + }); + req.on('end', () => resolve(Buffer.concat(chunks))); + req.on('error', reject); + }); +} + +async function readJson(req, limit = 8 * 1024 * 1024) { + const raw = await readBody(req, limit); + if (!raw.length) return {}; + try { + return JSON.parse(raw.toString('utf8')); + } catch { + throw new Error('Request body is not valid JSON'); + } +} + +function match(pathname, pattern) { + const p = pattern.split('/'); + const a = pathname.split('/'); + if (p.length !== a.length) return null; + const params = {}; + for (let i = 0; i < p.length; i++) { + if (p[i].startsWith(':')) { + params[p[i].slice(1)] = decodeURIComponent(a[i]); + } else if (p[i] !== a[i]) { + return null; + } + } + return params; +} + +function sendBuffer(res, data, type, cache = 'private, max-age=3600') { + res.writeHead(200, { + 'Content-Type': type, + 'Content-Length': data.length, + 'Cache-Control': cache, + ...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}), + }); + res.end(data); +} + +/** The bridge row and source id for a photo imported from the dashboard. */ +function bridgeLinkForPhoto(photoId) { + const photo = getPhoto(photoId); + if (!photo?.eventId) return null; + const bridge = bridgeForEvent(photo.eventId); + if (!bridge) return null; + const sourceId = photo.bridgeSource?.sourceId ?? photoId.replace(/^br-/, ''); + return { photo, bridge, sourceId }; +} + +async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400') { + if (!filePath) return error(res, 404, 'Not found'); + try { + const stat = await fsp.stat(filePath); + res.writeHead(200, { + 'Content-Type': type, + 'Content-Length': stat.size, + 'Cache-Control': cache, + ...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}), + }); + if (req.method === 'HEAD') return res.end(); + fs.createReadStream(filePath).pipe(res); + } catch { + error(res, 404, 'Not found'); + } +} + +function decodeDataUrl(value) { + if (typeof value !== 'string') return null; + const m = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=\s]+)$/.exec(value); + if (!m) return null; + return { mime: `image/${m[1]}`, data: Buffer.from(m[2], 'base64') }; +} + +/* --------------------------------------------------------------------- api */ + +const routes = []; +function route(method, pattern, handler) { + routes.push({ method, pattern, handler }); +} + +route('GET', '/api/health', async ({ res }) => { + const raw = await rawSupport(); + json(res, 200, { + ok: true, + app: 'lumenroom', + version: VERSION, + needsSetup: users.count() === 0, + registrationOpen: users.count() === 0 || Boolean(INVITE), + photos: countPhotos(), + bytes: storageBytes(), + raw, + }); +}); + +route('POST', '/api/auth/register', async ({ req, res }) => { + const body = await readJson(req, 64 * 1024); + const email = normalizeEmail(body.email); + const password = typeof body.password === 'string' ? body.password : ''; + const name = typeof body.name === 'string' ? body.name.trim().slice(0, 80) : ''; + if (!validEmail(email)) return error(res, 400, 'Enter a valid email address'); + if (password.length < 8) return error(res, 400, 'Use at least 8 characters for the password'); + if (users.byEmail(email)) return error(res, 409, 'That email is already registered'); + + const first = users.count() === 0; + if (!first) { + if (!INVITE) return error(res, 403, 'Registration is closed. Ask an admin for an invite code.'); + if (String(body.invite ?? '') !== INVITE) return error(res, 403, 'Invite code is not correct'); + } + + const id = crypto.randomUUID(); + users.create({ + id, + email, + name: name || email.split('@')[0], + passHash: hashPassword(password), + role: first ? 'admin' : 'member', + }); + const token = createSession(id); + json( + res, + 201, + { token, user: publicUser(users.byId(id)) }, + { 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) }, + ); +}); + +route('POST', '/api/auth/login', async ({ req, res }) => { + const body = await readJson(req, 64 * 1024); + const email = normalizeEmail(body.email); + const password = typeof body.password === 'string' ? body.password : ''; + const row = users.byEmail(email); + if (!row || !verifyPassword(password, row.pass_hash)) return error(res, 401, 'Email or password is not correct'); + const token = createSession(row.id); + json( + res, + 200, + { token, user: publicUser(users.byId(row.id)) }, + { 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) }, + ); +}); + +route('POST', '/api/auth/logout', async ({ req, res }) => { + const token = parseCookies(req)[COOKIE]; + if (token) sessions.destroy(token); + json(res, 200, { ok: true }, { 'Set-Cookie': `${COOKIE}=; Path=/; HttpOnly; Max-Age=0` }); +}); + +route('GET', '/api/auth/me', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + json(res, 200, { user }); +}); + +route('GET', '/api/bridge/login', async ({ req, res, url }) => { + if (!bridgeConfigured()) { + return error(res, 503, 'The advanced editor bridge is not configured'); + } + const token = url.searchParams.get('token') || ''; + const payload = verifyBridgeToken(token); + if (!payload || payload.kind !== 'login') { + return error(res, 401, 'This advanced-editor link is invalid or has expired'); + } + + try { + const service = await exchangeBridgeToken(token, payload.sid); + const email = normalizeEmail(payload.email); + if (!validEmail(email)) { + return error(res, 400, 'The dashboard account has no usable email address'); + } + + let row = users.byEmail(email); + if (!row) { + const id = crypto.randomUUID(); + users.create({ + id, + email, + name: payload.name || email.split('@')[0], + passHash: hashPassword(crypto.randomBytes(24).toString('hex')), + role: 'member', + }); + row = users.byId(id); + } + + purgeExpiredBridges(); + const imported = await importBridgeEvent({ + serviceToken: service.token, + sessionId: payload.sid, + }); + const sessionToken = createSession(row.id); + res.writeHead(302, { + Location: `/?bridge=${encodeURIComponent(imported.eventId)}`, + 'Set-Cookie': sessionCookie(req, sessionToken, 30 * 24 * 3600), + 'Cache-Control': 'no-store', + }); + res.end(); + } catch (err) { + return error( + res, + 502, + err instanceof Error ? err.message : 'Could not open the advanced editor', + ); + } +}); + +route('GET', '/api/sync', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + json(res, 200, { + user, + events: listEvents(), + photos: listPhotos(), + presets: kv.get('presets') ?? [], + }); +}); + +route('PUT', '/api/events/:id', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + const body = await readJson(req, 256 * 1024); + const record = { ...body, id: params.id }; + saveEvent(record, typeof body.order === 'number' ? body.order : Number(body.createdAt ?? Date.now())); + json(res, 200, { event: record }); +}); + +route('DELETE', '/api/events/:id', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + removeEvent(params.id); + json(res, 200, { ok: true }); +}); + +route('PUT', '/api/presets', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + const body = await readJson(req, 512 * 1024); + kv.set('presets', Array.isArray(body.presets) ? body.presets : []); + json(res, 200, { ok: true }); +}); + +/** + * Store the original file. Raw files are demosaiced here so every browser can + * edit them; ordinary images are kept byte-for-byte and previewed client-side. + */ +route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + const url = new URL(req.url ?? '/', 'http://localhost'); + const name = url.searchParams.get('name') || 'upload'; + const mime = url.searchParams.get('mime') || 'application/octet-stream'; + const drop = url.searchParams.get('drop') === '1'; + const data = await readBody(req); + if (!data.length) return error(res, 400, 'Empty upload'); + + const ext = (name.split('.').pop() || 'bin').toLowerCase(); + await writeOriginal(params.id, ext, data); + + if (isRawName(name) || drop) { + try { + const decoded = await decodeRaw(data); + await writePreview(params.id, decoded.jpeg, decoded.ext); + const info = await jpegInfo(decoded.jpeg); + return json(res, 201, { + raw: true, + engine: decoded.engine, + width: info?.width || decoded.width, + height: info?.height || decoded.height, + mime: 'image/jpeg', + previewUrl: `/api/photos/${params.id}/preview`, + thumbUrl: `/api/photos/${params.id}/thumb`, + note: decoded.note ?? null, + maxEdge: RAW_PREVIEW_EDGE, + }); + } catch (err) { + return error(res, 422, err instanceof Error ? err.message : 'Could not decode this raw file'); + } + } + + return json(res, 201, { raw: false, mime, size: data.length }); +}); + +route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => { + const thumb = findThumb(params.id); + if (thumb) return sendFile(req, res, thumb, 'image/jpeg'); + + const linked = bridgeLinkForPhoto(params.id); + if (!linked) return error(res, 404, 'Not found'); + const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'thumb'); + if (!upstream.ok) return error(res, 404, 'Thumbnail unavailable'); + const data = Buffer.from(await upstream.arrayBuffer()); + await writeThumb(params.id, data); + return sendBuffer(res, data, 'image/jpeg'); +}); + +route('GET', '/api/photos/:id/preview', async ({ req, res, params }) => { + const preview = findPreview(params.id); + if (preview) return sendFile(req, res, preview, preview.endsWith('.png') ? 'image/png' : 'image/jpeg'); + + const linked = bridgeLinkForPhoto(params.id); + if (linked) { + const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'proxy'); + if (!upstream.ok) return error(res, 404, 'Preview unavailable'); + const data = Buffer.from(await upstream.arrayBuffer()); + await writePreview(params.id, data); + const info = await jpegInfo(data); + if (info?.width && info?.height) { + savePhoto({ ...linked.photo, width: info.width, height: info.height, mime: 'image/jpeg', size: data.length }); + } + return sendBuffer(res, data, 'image/jpeg'); + } + + return sendFile(req, res, findOriginal(params.id), 'application/octet-stream'); +}); + +route('GET', '/api/photos/:id/original', async ({ req, res, params }) => { + const original = findOriginal(params.id); + if (original) return sendFile(req, res, original, 'application/octet-stream', 'private, max-age=3600'); + + const linked = bridgeLinkForPhoto(params.id); + if (!linked) return error(res, 404, 'Not found'); + const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'original'); + if (!upstream.ok) return error(res, 404, 'Original unavailable'); + const data = Buffer.from(await upstream.arrayBuffer()); + return sendBuffer(res, data, linked.photo.mime || 'application/octet-stream'); +}); + +route('POST', '/api/bridge/export', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + + const body = await readJson(req, 64 * 1024 * 1024); + if (typeof body.photoId !== 'string' || typeof body.jpeg !== 'string') { + return error(res, 400, 'A photo id and a rendered JPEG are required'); + } + + const linked = bridgeLinkForPhoto(body.photoId); + if (!linked) return error(res, 404, 'This photo is not part of an advanced edit'); + + const result = await forwardBridgeRender(linked.bridge, linked.sourceId, { + jpeg: body.jpeg, + edits: body.edits ?? {}, + }); + if (result.status >= 400) { + return error(res, result.status, result.body?.error || 'The edit could not be saved to the event'); + } + return json(res, 200, result.body ?? { ok: true }); +}); + +route('PUT', '/api/photos/:id', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + const body = await readJson(req); + if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL'); + const record = { ...body, id: params.id }; + + const thumb = decodeDataUrl(record.thumb); + if (thumb) { + await writeThumb(params.id, thumb.data); + delete record.thumb; + } + if (record.raw) { + record.previewUrl = `/api/photos/${params.id}/preview`; + const preview = findPreview(params.id); + if (!preview) { + const original = findOriginal(params.id); + if (original) { + const proxy = await toJpegProxy(await fsp.readFile(original)); + if (proxy) await writePreview(params.id, proxy.data, proxy.ext); + } + } + } + record.thumbUrl = `/api/photos/${params.id}/thumb`; + savePhoto(record); + json(res, 200, { photo: record }); +}); + +route('DELETE', '/api/photos/:id', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + removePhoto(params.id); + await removeAsset(params.id); + json(res, 200, { ok: true }); +}); + +/* ---------------------------------------------------------------- static ui */ + +const MIME = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.pdf': 'application/pdf', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.woff2': 'font/woff2', + '.map': 'application/json; charset=utf-8', +}; + +async function serveStatic(req, res, url) { + const pathname = decodeURIComponent(url.pathname); + const candidate = path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname); + if (candidate.startsWith(DIST_DIR)) { + try { + const stat = await fsp.stat(candidate); + if (stat.isFile()) { + const ext = path.extname(candidate).toLowerCase(); + const immutable = pathname.startsWith('/assets/'); + return sendFile( + req, + res, + candidate, + MIME[ext] ?? 'application/octet-stream', + immutable ? 'public, max-age=31536000, immutable' : 'no-cache', + ); + } + } catch { + /* fall through to the SPA entry */ + } + } + const index = path.join(DIST_DIR, 'index.html'); + if (!fs.existsSync(index)) { + return error( + res, + 503, + 'The web build is missing. Run "npm run build" (or use "npm run dev" with the Vite dev server).', + ); + } + return sendFile(req, res, index, MIME['.html'], 'no-cache'); +} + +/* ------------------------------------------------------------------ server */ + +const server = http.createServer(async (req, res) => { + const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`); + res.setHeader('X-Frame-Options', 'SAMEORIGIN'); + res.setHeader('Referrer-Policy', 'same-origin'); + try { + if (url.pathname.startsWith('/api/')) { + for (const r of routes) { + if (r.method !== req.method) continue; + const params = match(url.pathname, r.pattern); + if (!params) continue; + return await r.handler({ req, res, params, url }); + } + return error(res, 404, `No route for ${req.method} ${url.pathname}`); + } + return await serveStatic(req, res, url); + } catch (err) { + const message = err instanceof Error ? err.message : 'Unexpected error'; + console.error(`[lumenroom] ${req.method} ${url.pathname} → ${message}`); + if (!res.headersSent) return error(res, 500, message); + res.end(); + } +}); + +server.listen(PORT, HOST, async () => { + const raw = await rawSupport(); + console.log(`Lumenroom server listening on http://localhost:${PORT}`); + console.log(` data: ${DATA_DIR}`); + console.log( + ` raw: libraw ${raw.libraw ? `ready (${raw.workers} parallel worker${raw.workers === 1 ? '' : 's'})` : 'missing'} · jpeg ${raw.sharp ? 'sharp' : 'png fallback'}`, + ); + console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' — first signup becomes admin' : ''}`); + if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)'); +}); + +for (const signal of ['SIGINT', 'SIGTERM']) { + process.on(signal, () => { + server.close(() => process.exit(0)); + }); +} diff --git a/lumenroom/server/libraw-pool.mjs b/lumenroom/server/libraw-pool.mjs new file mode 100644 index 0000000..1938a2e --- /dev/null +++ b/lumenroom/server/libraw-pool.mjs @@ -0,0 +1,120 @@ +import { RAW_IDLE_MS, RAW_WORKERS } from './config.mjs'; +import { installLibrawRuntime } from './libraw-runtime.mjs'; + +let ctorPromise = null; + +/** Load the decoder class once; installs the Node worker shim on first use. */ +export function loadLibRaw() { + if (!ctorPromise) { + ctorPromise = (async () => { + await installLibrawRuntime(); + const mod = await import('libraw-wasm'); + const ctor = mod.default?.default ?? mod.default; + if (typeof ctor !== 'function') throw new Error('libraw-wasm did not export a constructor'); + return ctor; + })(); + } + return ctorPromise; +} + +/** + * Bounded pool of decoder instances. Each instance owns one worker thread, so + * this caps how much demosaicing runs at the same time; extra jobs queue. + * Idle instances are disposed after RAW_IDLE_MS to give the memory back. + */ +class LibRawPool { + constructor(size = RAW_WORKERS) { + this.size = Math.max(1, Math.floor(size)); + this.free = []; + this.total = 0; + this.waiters = []; + this.closed = false; + } + + async acquire() { + const entry = this.free.pop(); + if (entry) { + if (entry.timer) clearTimeout(entry.timer); + return entry.lib; + } + if (this.total < this.size) { + this.total++; + try { + const Ctor = await loadLibRaw(); + return new Ctor(); + } catch (err) { + this.total--; + throw err; + } + } + return new Promise((resolve, reject) => this.waiters.push({ resolve, reject })); + } + + release(lib, healthy = true) { + if (this.closed || !healthy) { + this.discard(lib); + return; + } + const waiter = this.waiters.shift(); + if (waiter) { + waiter.resolve(lib); + return; + } + const entry = { lib, timer: null }; + entry.timer = setTimeout(() => { + const idx = this.free.indexOf(entry); + if (idx >= 0) { + this.free.splice(idx, 1); + this.discard(lib); + } + }, RAW_IDLE_MS); + entry.timer.unref?.(); + this.free.push(entry); + } + + discard(lib) { + try { + lib.dispose(); + } catch { + /* worker already gone */ + } + this.total = Math.max(0, this.total - 1); + const waiter = this.waiters.shift(); + if (waiter) { + this.total++; + loadLibRaw() + .then((Ctor) => new Ctor()) + .then(waiter.resolve, waiter.reject); + } + } + + /** Run `fn` with a decoder instance; the instance returns to the pool after. */ + async use(fn) { + const lib = await this.acquire(); + let healthy = true; + try { + return await fn(lib); + } catch (err) { + // A dead worker keeps failing, so recycle it instead of handing it back. + if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false; + throw err; + } finally { + this.release(lib, healthy); + } + } + + get stats() { + return { + size: this.size, + busy: this.total - this.free.length, + idle: this.free.length, + queued: this.waiters.length, + }; + } +} + +export const rawPool = new LibRawPool(); + +export function poolSupport() { + return { size: rawPool.size, workers: RAW_WORKERS }; +} diff --git a/lumenroom/server/libraw-runtime.mjs b/lumenroom/server/libraw-runtime.mjs new file mode 100644 index 0000000..6b6e90f --- /dev/null +++ b/lumenroom/server/libraw-runtime.mjs @@ -0,0 +1,34 @@ +/** + * libraw-wasm is browser-first: the wrapper spawns a Web Worker and the + * Emscripten build loads libraw.wasm with fetch(). Node has neither a global + * Worker nor file:// support in fetch, so the decoder runs in a worker_thread + * with a tiny browser-globals shim (see libraw-worker.mjs). + * + * This is a no-op in the browser, where the real Worker already exists. + */ +let installed = false; + +export async function installLibrawRuntime() { + if (installed) return; + installed = true; + if (typeof globalThis.Worker === 'function') return; + + const { Worker: NodeWorker } = await import('node:worker_threads'); + const entry = new URL('./libraw-worker.mjs', import.meta.url); + + class BrowserWorker { + constructor() { + this._worker = new NodeWorker(entry); + this._worker.on('message', (data) => this.onmessage?.({ data })); + this._worker.on('error', (err) => this.onerror?.(err)); + } + postMessage(message, transfer) { + this._worker.postMessage(message, transfer); + } + terminate() { + return this._worker.terminate(); + } + } + + globalThis.Worker = BrowserWorker; +} diff --git a/lumenroom/server/libraw-worker.mjs b/lumenroom/server/libraw-worker.mjs new file mode 100644 index 0000000..8b4d338 --- /dev/null +++ b/lumenroom/server/libraw-worker.mjs @@ -0,0 +1,31 @@ +import { parentPort } from 'node:worker_threads'; +import fs from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +// libraw-wasm targets browsers: emulate the worker globals its build expects. +globalThis.self = globalThis; +globalThis.WorkerGlobalScope = globalThis; +globalThis.postMessage = (msg, transfer) => parentPort.postMessage(msg, transfer); +globalThis.addEventListener = () => {}; + +// Emscripten loads libraw.wasm through fetch(); Node's fetch rejects file:// URLs. +const realFetch = globalThis.fetch; +globalThis.fetch = async (url, init) => { + const href = typeof url === 'string' ? url : url instanceof URL ? url.href : String(url); + if (href.startsWith('file:')) { + const buf = await fs.readFile(fileURLToPath(href)); + return new Response(buf, { status: 200, headers: { 'content-type': 'application/wasm' } }); + } + return realFetch(url, init); +}; + +// Buffer anything that arrives before the module registers `onmessage`. +const queue = []; +parentPort.on('message', (data) => { + if (typeof globalThis.onmessage === 'function') globalThis.onmessage({ data }); + else queue.push(data); +}); + +await import('libraw-wasm/dist/worker.js'); + +for (const data of queue.splice(0)) globalThis.onmessage({ data }); diff --git a/lumenroom/server/raw.mjs b/lumenroom/server/raw.mjs new file mode 100644 index 0000000..8d05427 --- /dev/null +++ b/lumenroom/server/raw.mjs @@ -0,0 +1,214 @@ +import { RAW_PREVIEW_EDGE } from './config.mjs'; +import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs'; +import { loadLibRaw, rawPool } from './libraw-pool.mjs'; + +/** Every raw container the pipeline will attempt, grouped by vendor family. */ +export const RAW_EXTENSIONS = new Set([ + // Canon + 'cr2', 'cr3', 'crw', + // Nikon + 'nef', 'nrw', + // Sony + 'arw', 'srf', 'sr2', + // Olympus / OM System + 'orf', + // Panasonic / Leica + 'rw2', 'raw', 'rwl', + // Fujifilm + 'raf', + // Pentax / Ricoh + 'pef', 'dng', + // Samsung, Hasselblad, Leaf, Phase One, Sigma, Epson, Kodak, Minolta + 'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', 'sraw', +]); + +export function isRawName(name = '') { + const ext = name.split('.').pop()?.toLowerCase() ?? ''; + return RAW_EXTENSIONS.has(ext); +} + +/** True when the buffer starts with a container signature LibRaw can open. */ +export function looksLikeRaw(buffer) { + if (!buffer || buffer.length < 64) return false; + const hex4 = buffer.subarray(0, 4).toString('hex'); + const ascii = buffer.subarray(0, 16).toString('latin1'); + if (hex4 === '49492a00' || hex4 === '4d4d002a') return true; // TIFF family + if (hex4 === '4949524f' || hex4 === '4d4d4f52') return true; // ORF + if (hex4 === '49495500') return true; // RW2 + if (hex4 === '49494949') return true; // Phase One IIQ + if (ascii.startsWith('FUJIFILMCCD-RAW')) return true; // RAF + if (ascii.startsWith('FOVb')) return true; // X3F + if (buffer.subarray(4, 8).toString('latin1') === 'ftyp') return true; // CR3 + return false; +} + +let engineState = 'unloaded'; + +export async function rawEngine() { + if (engineState === 'unloaded') { + try { + await loadLibRaw(); + engineState = 'ready'; + } catch { + engineState = 'missing'; + } + } + return engineState; +} + +const DECODE_SETTINGS = { + outputBps: 8, + useCameraWb: true, + outputColor: 1, // sRGB + userQual: 3, + highlight: 0, + noAutoBright: false, + // Use the orientation stored in the raw container: phone and DSLR files often + // record the shot rotated (EXIF 6/8), and demosaicing without it produces a + // sideways proxy that no later step can fix without losing the original axes. + userFlip: -1, + useFujiRotate: -1, +}; + +/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */ +function toRgb(img) { + if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels'); + const width = Number(img.width); + const height = Number(img.height); + const colors = Number(img.colors ?? 3); + const bits = Number(img.bits ?? 8); + const src = img.data; + const pixelCount = width * height; + const needed = pixelCount * colors * (bits > 8 ? 2 : 1); + if (src.length < needed) { + throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`); + } + + const rgb = Buffer.alloc(pixelCount * 3); + if (bits > 8) { + const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2)); + for (let i = 0; i < pixelCount; i++) { + const s = i * colors; + rgb[i * 3] = view[s] >> 8; + rgb[i * 3 + 1] = view[s + 1] >> 8; + rgb[i * 3 + 2] = view[s + 2] >> 8; + } + } else { + for (let i = 0; i < pixelCount; i++) { + const s = i * colors; + rgb[i * 3] = src[s]; + rgb[i * 3 + 1] = src[s + 1]; + rgb[i * 3 + 2] = src[s + 2]; + } + } + return { rgb, width, height }; +} + +/** + * Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file; + * the pixels come from `imageData()`, which rejects when the camera is unsupported. + */ +async function demosaic(buffer) { + if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed'); + return rawPool.use(async (lib) => { + // LibRaw transfers the buffer to its worker, which detaches it here. Hand it + // a copy so the caller's bytes survive for the embedded-preview fallback. + await lib.open(Buffer.from(buffer), DECODE_SETTINGS); + return toRgb(await lib.imageData()); + }); +} + +const SOI = Buffer.from([0xff, 0xd8, 0xff]); +const EOI = Buffer.from([0xff, 0xd9]); + +/** Pull the largest embedded JPEG straight out of a raw container. */ +export function extractEmbeddedJpeg(buffer) { + let best = null; + let from = 0; + while (from < buffer.length - 3) { + const start = buffer.indexOf(SOI, from); + if (start < 0) break; + const end = buffer.indexOf(EOI, start + 3); + if (end < 0) break; + const length = end + 2 - start; + if (length > 4096 && (!best || length > best.length)) best = buffer.subarray(start, end + 2); + from = end + 2; + } + return best; +} + +/** Camera preview, preferably the one LibRaw knows the offset and length of. */ +async function embeddedPreview(buffer) { + if ((await rawEngine()) === 'ready') { + try { + const thumb = await rawPool.use(async (lib) => { + await lib.open(Buffer.from(buffer), { useCameraWb: true }); + return lib.thumbnailData(); + }); + if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) { + return Buffer.from(thumb.data); + } + } catch { + /* fall through to the byte scan */ + } + } + return extractEmbeddedJpeg(buffer); +} + +/** + * Convert a raw file into an editable JPEG. LibRaw demosaics where possible and + * falls back to the camera's own embedded preview when it cannot. + */ +export async function decodeRaw(buffer) { + let librawError = null; + if (looksLikeRaw(buffer)) { + try { + const { rgb, width, height } = await demosaic(buffer); + const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE); + return { + jpeg: encoded.data, + width: encoded.width, + height: encoded.height, + engine: 'libraw', + ext: encoded.ext, + }; + } catch (err) { + librawError = err instanceof Error ? err.message : String(err); + } + } else { + librawError = 'not a recognised raw container'; + } + + const embedded = await embeddedPreview(buffer); + if (embedded) { + const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE); + if (proxy) { + const size = await jpegInfo(proxy.data); + return { + jpeg: proxy.data, + width: size?.width || proxy.width, + height: size?.height || proxy.height, + engine: 'embedded', + ext: proxy.ext, + note: `LibRaw could not decode this file (${librawError}); using the camera preview.`, + }; + } + return { jpeg: embedded, width: 0, height: 0, engine: 'embedded', ext: 'jpg', note: librawError ?? undefined }; + } + + throw new Error( + `Could not decode this raw file. ${librawError ? `LibRaw said: ${librawError}.` : 'LibRaw is not installed.'}`, + ); +} + +export async function rawSupport() { + const engine = await rawEngine(); + const sharp = await loadSharp(); + return { + libraw: engine === 'ready', + sharp: Boolean(sharp), + workers: rawPool.size, + busy: rawPool.stats.busy, + formats: [...RAW_EXTENSIONS].sort(), + }; +} diff --git a/lumenroom/server/storage.mjs b/lumenroom/server/storage.mjs new file mode 100644 index 0000000..5a106bb --- /dev/null +++ b/lumenroom/server/storage.mjs @@ -0,0 +1,90 @@ +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import { ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR } from './config.mjs'; + +for (const dir of [ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR]) fs.mkdirSync(dir, { recursive: true }); + +const SAFE = /^[A-Za-z0-9_-]{1,80}$/; + +function safeId(id) { + if (!SAFE.test(id)) throw new Error('Invalid asset id'); + return id; +} + +/** Original files keep their real extension so a raw can be recovered later. */ +function originalPath(id, ext = 'bin') { + return path.join(ORIGINAL_DIR, `${safeId(id)}.${ext.replace(/[^a-z0-9]/gi, '') || 'bin'}`); +} + +export async function writeOriginal(id, ext, data) { + const target = originalPath(id, ext); + await fsp.writeFile(target, data); + return target; +} + +/** + * Reads are lookups: a malformed id simply has no file, so it must not throw a + * 500 out of the request handler. Writers keep the strict check. + */ +function lookupId(id) { + return typeof id === 'string' && SAFE.test(id) ? id : null; +} + +export function findOriginal(id) { + const safe = lookupId(id); + if (!safe) return null; + const prefix = `${safe}.`; + for (const name of fs.readdirSync(ORIGINAL_DIR)) { + if (name.startsWith(prefix)) return path.join(ORIGINAL_DIR, name); + } + return null; +} + +export async function writePreview(id, data, ext = 'jpg') { + const target = path.join(PREVIEW_DIR, `${safeId(id)}.${ext}`); + await fsp.writeFile(target, data); + return target; +} + +export function findPreview(id) { + const safe = lookupId(id); + if (!safe) return null; + for (const ext of ['jpg', 'png']) { + const p = path.join(PREVIEW_DIR, `${safe}.${ext}`); + if (fs.existsSync(p)) return p; + } + return null; +} + +export async function writeThumb(id, data) { + const target = path.join(THUMB_DIR, `${safeId(id)}.jpg`); + await fsp.writeFile(target, data); + return target; +} + +export function findThumb(id) { + const safe = lookupId(id); + if (!safe) return null; + const p = path.join(THUMB_DIR, `${safe}.jpg`); + return fs.existsSync(p) ? p : null; +} + +export async function removeAsset(id) { + const files = [findOriginal(id), findPreview(id), findThumb(id)]; + await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve()))); +} + +export function storageBytes() { + let total = 0; + for (const dir of [ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR]) { + for (const name of fs.readdirSync(dir)) { + try { + total += fs.statSync(path.join(dir, name)).size; + } catch { + /* file vanished mid-scan */ + } + } + } + return total; +} diff --git a/lumenroom/src/App.tsx b/lumenroom/src/App.tsx new file mode 100644 index 0000000..61825b1 --- /dev/null +++ b/lumenroom/src/App.tsx @@ -0,0 +1,1202 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import CloudPanel from './components/CloudPanel'; +import ContextMenu, { type MenuEntry } from './components/ContextMenu'; +import Develop from './components/Develop'; +import EventSidebar from './components/EventSidebar'; +import ExportModal from './components/ExportModal'; +import FilterBar from './components/FilterBar'; +import ImportModal from './components/ImportModal'; +import LibraryGrid from './components/LibraryGrid'; +import Shortcuts from './components/Shortcuts'; +import Stars, { ColorSwatches, FlagButtons } from './components/Stars'; +import TopBar from './components/TopBar'; +import { + currentUser, + deleteEventRemote, + deletePhotoRemote, + getHealth, + login as apiLogin, + logout as apiLogout, + pullAll, + pushEvent, + pushPhoto, + register as apiRegister, + uploadOriginal, +} from './lib/api'; +import type { Health, SessionUser } from './lib/api'; +import { + deleteEventRecord, + deletePhotoRecord, + getAllEvents, + getAllPhotos, + getAsset, + getKV, + putEvent, + putPhoto, + setKV, +} from './lib/db'; +import type { ExportOptions } from './lib/export'; +import { DEFAULT_EXPORT, renderPhotoBlob } from './lib/export'; +import { COLOR_LABELS, defaultEdits, isEdited, normalizePhoto } from './lib/edits'; +import { evictBitmap } from './lib/images'; +import { uid } from './lib/import'; +import { PRESETS } from './lib/presets'; +import type { Edits, EventRecord, Filters, PhotoRecord, Preset, SortKey, ViewMode } from './types'; + +const EMPTY_FILTERS: Filters = { + minRating: 0, + flag: 'any', + colors: [], + text: '', + editedOnly: false, + unrated: false, +}; + +async function blobToBase64(blob: Blob): Promise { + const bytes = new Uint8Array(await blob.arrayBuffer()); + let binary = ''; + const chunk = 0x8000; + for (let i = 0; i < bytes.length; i += chunk) { + binary += String.fromCharCode(...bytes.subarray(i, i + chunk)); + } + return btoa(binary); +} + +const byOrder = (a: EventRecord, b: EventRecord) => + (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || a.createdAt - b.createdAt; + +export default function App() { + const [events, setEvents] = useState([]); + const [photos, setPhotos] = useState([]); + const [loaded, setLoaded] = useState(false); + const [loadError, setLoadError] = useState(null); + const [eventId, setEventId] = useState('all'); + const [view, setView] = useState('grid'); + const [activeId, setActiveId] = useState(null); + const [selected, setSelected] = useState([]); + const [anchorId, setAnchorId] = useState(null); + const [filters, setFilters] = useState(EMPTY_FILTERS); + const [sort, setSort] = useState('taken'); + const [asc, setAsc] = useState(false); + const [importOpen, setImportOpen] = useState(false); + const [pendingFiles, setPendingFiles] = useState([]); + const [clipboard, setClipboard] = useState(null); + const [customPresets, setCustomPresets] = useState([]); + const [toast, setToast] = useState(null); + const [menu, setMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null); + const [helpOpen, setHelpOpen] = useState(false); + const [dropActive, setDropActive] = useState(false); + const [bridgeBusy, setBridgeBusy] = useState(false); + + const [cloudHealth, setCloudHealth] = useState(null); + const [cloudUser, setCloudUser] = useState(null); + const [cloudOpen, setCloudOpen] = useState(false); + const [cloudBusy, setCloudBusy] = useState(false); + const [cloudError, setCloudError] = useState(null); + const [cloudNote, setCloudNote] = useState(null); + + const [exportOpen, setExportOpen] = useState(false); + const [exportOptions, setExportOptions] = useState(DEFAULT_EXPORT); + + const saveTimers = useRef(new Map>()); + const photosRef = useRef([]); + const eventsRef = useRef([]); + const userRef = useRef(null); + photosRef.current = photos; + eventsRef.current = events; + userRef.current = cloudUser; + + useEffect(() => { + let alive = true; + (async () => { + try { + const [loadedEvents, loadedPhotos, presets] = await Promise.all([ + getAllEvents(), + getAllPhotos(), + getKV('customPresets'), + ]); + if (!alive) return; + setEvents([...loadedEvents].sort(byOrder)); + setPhotos(loadedPhotos.map((p) => normalizePhoto(p))); + if (Array.isArray(presets)) setCustomPresets(presets); + } catch (err) { + setLoadError(err instanceof Error ? err.message : 'Could not read local storage'); + } finally { + if (alive) setLoaded(true); + } + })(); + return () => { + alive = false; + }; + }, []); + + // Detect the team server; a missing one simply means a browser-only library. + useEffect(() => { + let alive = true; + (async () => { + const health = await getHealth(); + if (!alive) return; + setCloudHealth(health); + if (health) { + const user = await currentUser(); + if (alive) setCloudUser(user); + } + })(); + return () => { + alive = false; + }; + }, []); + + useEffect(() => { + if (!toast) return; + const t = setTimeout(() => setToast(null), 2800); + return () => clearTimeout(t); + }, [toast]); + + const queueSave = useCallback((photo: PhotoRecord) => { + const existing = saveTimers.current.get(photo.id); + if (existing) clearTimeout(existing); + saveTimers.current.set( + photo.id, + setTimeout(() => { + saveTimers.current.delete(photo.id); + putPhoto(photo).catch((err) => console.error('Failed to save photo', err)); + + if (!userRef.current) return; + const payload: PhotoRecord = photo.thumbUrl ? { ...photo, thumb: '' } : photo; + pushPhoto(payload) + .then((saved) => { + setPhotos((prev) => + prev.map((p) => + p.id === saved.id && (p.thumbUrl !== saved.thumbUrl || p.previewUrl !== saved.previewUrl) + ? { ...p, thumbUrl: saved.thumbUrl, previewUrl: saved.previewUrl ?? p.previewUrl } + : p, + ), + ); + }) + .catch((err) => console.warn('Could not sync photo', photo.name, err)); + }, 320), + ); + }, []); + + const updatePhoto = useCallback( + ( + id: string, + patch: Partial | ((p: PhotoRecord) => Partial), + historyLabel?: string, + ) => { + setPhotos((prev) => + prev.map((p) => { + if (p.id !== id) return p; + const partial = typeof patch === 'function' ? patch(p) : patch; + let next: PhotoRecord = { ...p, ...partial }; + if (partial.edits && historyLabel) { + const now = Date.now(); + const hist = next.history ?? []; + const last = hist[hist.length - 1]; + const entry = { label: historyLabel, ts: now, edits: next.edits }; + next = { + ...next, + history: + last && last.label === historyLabel && now - last.ts < 1400 + ? [...hist.slice(0, -1), entry] + : [...hist, entry].slice(-90), + }; + } + queueSave(next); + return next; + }), + ); + }, + [queueSave], + ); + + const bulkUpdate = useCallback( + (ids: string[], patch: Partial) => { + if (!ids.length) return; + setPhotos((prev) => + prev.map((p) => { + if (!ids.includes(p.id)) return p; + const next = { ...p, ...patch }; + queueSave(next); + return next; + }), + ); + }, + [queueSave], + ); + + const removePhotos = useCallback( + async (ids: string[]) => { + if (!ids.length) return; + const label = ids.length === 1 ? 'this photo' : `${ids.length} photos`; + if (!window.confirm(`Delete ${label} permanently? This cannot be undone.`)) return; + for (const id of ids) { + try { + await deletePhotoRecord(id); + evictBitmap(id); + if (userRef.current) await deletePhotoRemote(id).catch(() => undefined); + } catch (err) { + console.error('Delete failed', err); + } + } + setPhotos((prev) => prev.filter((p) => !ids.includes(p.id))); + setSelected((prev) => prev.filter((id) => !ids.includes(id))); + if (activeId && ids.includes(activeId)) { + setActiveId(null); + setView('grid'); + } + setToast(`Deleted ${label}`); + }, + [activeId], + ); + + const createEvent = useCallback(async (name: string) => { + const event: EventRecord = { + id: uid(), + name: name.trim() || `Event ${new Date().toLocaleDateString()}`, + createdAt: Date.now(), + date: Date.now(), + order: eventsRef.current.length, + }; + await putEvent(event); + if (userRef.current) pushEvent(event).catch(() => undefined); + setEvents((prev) => [...prev, event].sort(byOrder)); + return event; + }, []); + + const renameEvent = useCallback(async (id: string, name: string) => { + const trimmed = name.trim(); + if (!trimmed) return; + setEvents((prev) => { + const next = prev.map((e) => (e.id === id ? { ...e, name: trimmed } : e)); + const target = next.find((e) => e.id === id); + if (target) { + putEvent(target).catch((err) => console.error(err)); + if (userRef.current) pushEvent(target).catch(() => undefined); + } + return next; + }); + }, []); + + const removeEvent = useCallback( + async (id: string) => { + const event = events.find((e) => e.id === id); + if (!event) return; + if (!window.confirm(`Remove the event "${event.name}"? Its photos stay in All Photos.`)) return; + await deleteEventRecord(id); + if (userRef.current) await deleteEventRemote(id).catch(() => undefined); + setEvents((prev) => prev.filter((e) => e.id !== id)); + setPhotos((prev) => { + const next = prev.map((p) => (p.eventId === id ? { ...p, eventId: '' } : p)); + for (const p of next) if (p.eventId === '') queueSave(p); + return next; + }); + if (eventId === id) setEventId('all'); + }, + [events, eventId, queueSave], + ); + + const sorted = useMemo(() => { + const text = filters.text.trim().toLowerCase(); + const eventNames = new Map(events.map((e) => [e.id, e.name.toLowerCase()])); + const list = photos.filter((p) => { + if (eventId === 'unsorted' && p.eventId) return false; + if (eventId !== 'all' && eventId !== 'unsorted' && p.eventId !== eventId) return false; + if (filters.minRating > 0 && p.rating < filters.minRating) return false; + if (filters.unrated && p.rating !== 0) return false; + if (filters.flag !== 'any' && p.flag !== filters.flag) return false; + if (filters.colors.length && !filters.colors.includes(p.color)) return false; + if (filters.editedOnly && !isEdited(p.edits)) return false; + if (text) { + const hay = [ + p.name, + p.meta.camera ?? '', + p.meta.lens ?? '', + p.eventId ? eventNames.get(p.eventId) ?? '' : '', + ...p.keywords, + ] + .join(' ') + .toLowerCase(); + if (!hay.includes(text)) return false; + } + return true; + }); + + if (sort === 'custom') { + return [...list].sort( + (a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || a.addedAt - b.addedAt, + ); + } + + const dir = asc ? 1 : -1; + const keyOf = (p: PhotoRecord): number | string => { + if (sort === 'taken') return p.takenAt ?? p.addedAt; + if (sort === 'added') return p.addedAt; + if (sort === 'rating') return p.rating; + return p.name.toLowerCase(); + }; + return [...list].sort((a, b) => { + const ka = keyOf(a); + const kb = keyOf(b); + if (typeof ka === 'string' && typeof kb === 'string') return ka.localeCompare(kb) * dir; + return ((ka as number) - (kb as number)) * dir; + }); + }, [photos, events, eventId, filters, sort, asc]); + + const activePhoto = useMemo(() => photos.find((p) => p.id === activeId) ?? null, [photos, activeId]); + + /** The dashboard event id this tab was opened for, when bridged. */ + const bridgeParam = useMemo( + () => new URLSearchParams(window.location.search).get('bridge'), + [], + ); + const bridgeEvent = useMemo( + () => + events.find((event) => event.bridge && (event.id === bridgeParam || event.id === eventId)) ?? + null, + [events, bridgeParam, eventId], + ); + const bridgeSynced = useRef(false); + + const selectPhoto = useCallback( + (id: string, e: React.MouseEvent) => { + if (e.shiftKey && anchorId) { + const a = sorted.findIndex((p) => p.id === anchorId); + const b = sorted.findIndex((p) => p.id === id); + if (a >= 0 && b >= 0) { + const [lo, hi] = a < b ? [a, b] : [b, a]; + setSelected(sorted.slice(lo, hi + 1).map((p) => p.id)); + return; + } + } + if (e.metaKey || e.ctrlKey) { + setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id])); + setAnchorId(id); + return; + } + setSelected([id]); + setAnchorId(id); + }, + [anchorId, sorted], + ); + + const openPhoto = useCallback((id: string) => { + setActiveId(id); + setSelected([id]); + setView('develop'); + }, []); + + const navigate = useCallback( + (dir: -1 | 1) => { + if (!activePhoto) return; + const idx = sorted.findIndex((p) => p.id === activePhoto.id); + const nextIdx = idx < 0 ? 0 : Math.min(sorted.length - 1, Math.max(0, idx + dir)); + const next = sorted[nextIdx]; + if (next && next.id !== activePhoto.id) { + setActiveId(next.id); + setSelected([next.id]); + } + }, + [activePhoto, sorted], + ); + + const copySettings = useCallback(() => { + if (!activePhoto) return; + setClipboard(activePhoto.edits); + setToast('Develop settings copied'); + }, [activePhoto]); + + const pasteSettings = useCallback( + (ids: string[]) => { + if (!clipboard || !ids.length) return; + setPhotos((prev) => + prev.map((p) => { + if (!ids.includes(p.id)) return p; + const edits: Edits = { ...clipboard, crop: p.edits.crop }; + const next: PhotoRecord = { + ...p, + edits, + history: [...p.history, { label: 'Paste settings', ts: Date.now(), edits }].slice(-90), + }; + queueSave(next); + return next; + }), + ); + setToast(`Settings pasted to ${ids.length} photo${ids.length === 1 ? '' : 's'}`); + }, + [clipboard, queueSave], + ); + + /* ------------------------------------------------------- context actions */ + + const openPhotoMenu = useCallback( + (e: React.MouseEvent, id: string) => { + e.preventDefault(); + e.stopPropagation(); + const ids = selected.includes(id) ? selected : [id]; + if (!selected.includes(id)) { + setSelected([id]); + setAnchorId(id); + } + setMenu({ x: e.clientX, y: e.clientY, ids }); + }, + [selected], + ); + + const copySettingsOf = useCallback((id: string) => { + const source = photosRef.current.find((p) => p.id === id); + if (!source) return; + setClipboard(source.edits); + setToast(`Develop settings copied from ${source.name}`); + }, []); + + const resetEdits = useCallback( + (ids: string[]) => { + if (!ids.length) return; + setPhotos((prev) => + prev.map((p) => { + if (!ids.includes(p.id)) return p; + const edits: Edits = { ...defaultEdits(), crop: p.edits.crop }; + const next: PhotoRecord = { + ...p, + edits, + history: [...p.history, { label: 'Reset', ts: Date.now(), edits }].slice(-90), + }; + queueSave(next); + return next; + }), + ); + setToast(`Reset adjustments on ${ids.length} photo${ids.length === 1 ? '' : 's'}`); + }, + [queueSave], + ); + + const savePreset = useCallback( + (name: string, edits: Edits) => { + const { crop: _crop, ...withoutCrop } = edits; + const preset: Preset = { + id: uid(), + name, + group: 'User presets', + custom: true, + edits: withoutCrop, + }; + const next = [...customPresets, preset]; + setCustomPresets(next); + setKV('customPresets', next).catch((err) => console.error(err)); + if (userRef.current) { + import('./lib/api').then(({ pushPresets }) => pushPresets(next).catch(() => undefined)); + } + setToast(`Preset "${name}" saved`); + }, + [customPresets], + ); + + /* ------------------------------------------------------------- reordering */ + + const reorderPhotos = useCallback( + (ids: string[], targetId: string | null) => { + if (!ids.length) return; + const visible = sorted.map((p) => p.id); + const moving = ids.filter((id) => visible.includes(id)); + if (!moving.length) return; + const rest = visible.filter((id) => !ids.includes(id)); + const at = targetId ? Math.max(0, rest.indexOf(targetId)) : rest.length; + rest.splice(at < 0 ? rest.length : at, 0, ...moving); + const positions = new Map(rest.map((id, i) => [id, i])); + + setPhotos((prev) => + prev.map((p) => { + const order = positions.get(p.id); + if (order === undefined || p.order === order) return p; + const next = { ...p, order }; + queueSave(next); + return next; + }), + ); + setSort('custom'); + setToast(`Moved ${moving.length} photo${moving.length === 1 ? '' : 's'}`); + }, + [sorted, queueSave], + ); + + const movePhotosToEvent = useCallback( + (ids: string[], targetEventId: string) => { + if (!ids.length) return; + const inTarget = photos.filter((p) => p.eventId === targetEventId).length; + setPhotos((prev) => + prev.map((p, i) => { + if (!ids.includes(p.id)) return p; + const next = { ...p, eventId: targetEventId, order: inTarget + i }; + queueSave(next); + return next; + }), + ); + const name = targetEventId ? events.find((e) => e.id === targetEventId)?.name ?? 'event' : 'Unsorted'; + setToast(`Moved ${ids.length} photo${ids.length === 1 ? '' : 's'} to ${name}`); + }, + [events, photos, queueSave], + ); + + const reorderEvents = useCallback((dragId: string, targetId: string) => { + setEvents((prev) => { + const list = [...prev]; + const from = list.findIndex((e) => e.id === dragId); + const to = list.findIndex((e) => e.id === targetId); + if (from < 0 || to < 0 || from === to) return prev; + const [moved] = list.splice(from, 1); + list.splice(to, 0, moved); + const next = list.map((e, i) => (e.order === i ? e : { ...e, order: i })); + for (const e of next) { + putEvent(e).catch(() => undefined); + if (userRef.current) pushEvent(e).catch(() => undefined); + } + return next; + }); + }, []); + + /* ------------------------------------------------------------------ cloud */ + + const applyRemote = useCallback( + (remote: { events: EventRecord[]; photos: PhotoRecord[]; presets: Preset[] }, local: PhotoRecord[]) => { + const localById = new Map(local.map((p) => [p.id, p])); + const merged = remote.photos.map((r) => { + const l = localById.get(r.id); + return normalizePhoto({ ...r, thumb: l?.thumb || r.thumb || '' }); + }); + const seen = new Set(merged.map((p) => p.id)); + for (const l of local) if (!seen.has(l.id)) merged.push(l); + setPhotos(merged); + for (const p of merged) putPhoto(p).catch(() => undefined); + if (remote.events.length) setEvents([...remote.events].sort(byOrder)); + if (remote.presets.length) setCustomPresets(remote.presets); + }, + [], + ); + + const syncLibrary = useCallback(async () => { + const user = userRef.current ?? (await currentUser()); + if (!user) throw new Error('Sign in to the team server first'); + const localPhotos = photosRef.current; + const localEvents = eventsRef.current; + + for (const event of localEvents) { + try { + await pushEvent(event); + } catch (err) { + console.warn('Could not sync event', event.name, err); + } + } + + for (const photo of localPhotos) { + try { + if (!photo.raw && !photo.thumbUrl) { + const blob = await getAsset(photo.id); + if (blob) await uploadOriginal(photo.id, blob, photo.name).catch(() => undefined); + } + const payload: PhotoRecord = photo.thumbUrl ? { ...photo, thumb: '' } : photo; + const saved = await pushPhoto(payload); + if (saved.thumbUrl || saved.previewUrl) { + setPhotos((prev) => + prev.map((p) => + p.id === saved.id ? { ...p, thumbUrl: saved.thumbUrl ?? p.thumbUrl, previewUrl: saved.previewUrl ?? p.previewUrl } : p, + ), + ); + } + } catch (err) { + console.warn('Could not sync photo', photo.name, err); + } + } + + const remote = await pullAll(); + applyRemote(remote, localPhotos); + return remote.photos.length; + }, [applyRemote]); + + // Arriving from the dashboard: the bridge login already created a session and + // imported the event, so pull it once and open that event. + useEffect(() => { + if (!loaded || !bridgeParam || !cloudUser || bridgeSynced.current) return; + bridgeSynced.current = true; + syncLibrary() + .then(() => { + setEventId(bridgeParam); + setView('grid'); + }) + .catch((err) => + setLoadError( + err instanceof Error ? err.message : 'Could not load the advanced edit', + ), + ); + }, [loaded, bridgeParam, cloudUser, syncLibrary]); + + /** Render the open photo at full size and store it on the event. */ + const saveActiveToEvent = useCallback(async () => { + if (!activePhoto || !bridgeEvent) return; + setBridgeBusy(true); + try { + const blob = await renderPhotoBlob(activePhoto, { + ...DEFAULT_EXPORT, + format: 'jpeg', + quality: 92, + resize: 'none', + }); + const res = await fetch('/api/bridge/export', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + photoId: activePhoto.id, + jpeg: await blobToBase64(blob), + edits: activePhoto.edits, + width: activePhoto.width, + height: activePhoto.height, + }), + }); + const data = (await res.json().catch(() => ({}))) as { error?: string }; + if (!res.ok) throw new Error(data.error || 'The photo could not be saved'); + 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]); + + const handleCloudLogin = useCallback( + async (email: string, password: string) => { + setCloudBusy(true); + setCloudError(null); + try { + const user = await apiLogin(email, password); + userRef.current = user; + setCloudUser(user); + const count = await syncLibrary(); + setCloudHealth(await getHealth()); + setCloudNote(`Signed in · ${count} photo${count === 1 ? '' : 's'} on the server`); + setToast('Connected to the team server'); + } catch (err) { + setCloudError(err instanceof Error ? err.message : 'Could not sign in'); + } finally { + setCloudBusy(false); + } + }, + [syncLibrary], + ); + + const handleCloudRegister = useCallback( + async (input: { email: string; password: string; name: string; invite: string }) => { + setCloudBusy(true); + setCloudError(null); + try { + const user = await apiRegister(input); + userRef.current = user; + setCloudUser(user); + const count = await syncLibrary(); + setCloudHealth(await getHealth()); + setCloudNote(`Account created · ${count} photo${count === 1 ? '' : 's'} on the server`); + setToast('Team account created'); + } catch (err) { + setCloudError(err instanceof Error ? err.message : 'Could not create the account'); + } finally { + setCloudBusy(false); + } + }, + [syncLibrary], + ); + + const handleCloudLogout = useCallback(async () => { + setCloudBusy(true); + try { + await apiLogout(); + } catch { + /* signing out locally is enough */ + } + setCloudUser(null); + setCloudNote(null); + setCloudError(null); + setCloudBusy(false); + setToast('Signed out — the library stays on this device'); + }, []); + + const handleSync = useCallback(async () => { + setCloudBusy(true); + setCloudError(null); + try { + const count = await syncLibrary(); + setCloudHealth(await getHealth()); + setCloudNote(`Synced · ${count} photo${count === 1 ? '' : 's'} on the server`); + setToast('Library synced'); + } catch (err) { + setCloudError(err instanceof Error ? err.message : 'Sync failed'); + } finally { + setCloudBusy(false); + } + }, [syncLibrary]); + + /* ----------------------------------------------------------------- export */ + + const exportTargets = useMemo(() => { + if (view === 'develop' && activePhoto) return [activePhoto]; + return photos.filter((p) => selected.includes(p.id)); + }, [view, activePhoto, photos, selected]); + + const openExport = useCallback(() => { + if (!exportTargets.length) { + setToast('Select photos to export'); + return; + } + setExportOpen(true); + }, [exportTargets]); + + const closeExport = useCallback((message: string) => { + setToast(message); + }, []); + + // Keyboard selection walks the grid the way it is laid out: the column count + // comes from the rendered rows, so up/down move by whole rows at any width. + const moveSelection = useCallback( + (dx: number, dy: number, extend: boolean) => { + if (!sorted.length) return; + const currentId = selected[0] ?? anchorId; + const index = Math.max(0, sorted.findIndex((p) => p.id === currentId)); + let columns = 1; + const grid = document.querySelector('.grid'); + if (grid) { + const card = grid.querySelector('.card'); + if (card) { + const firstTop = Math.round(card.getBoundingClientRect().top); + const perRow = new Map(); + for (const el of grid.querySelectorAll('.card')) { + const top = Math.round(el.getBoundingClientRect().top); + perRow.set(top, (perRow.get(top) ?? 0) + 1); + } + columns = perRow.get(firstTop) ?? 1; + } + } + const nextIndex = Math.min(sorted.length - 1, Math.max(0, index + dy * columns + dx)); + const target = sorted[nextIndex]; + if (!target) return; + if (extend && anchorId) { + const a = sorted.findIndex((p) => p.id === anchorId); + const [lo, hi] = a < nextIndex ? [a, nextIndex] : [nextIndex, a]; + setSelected(sorted.slice(lo, hi + 1).map((p) => p.id)); + } else { + setSelected([target.id]); + setAnchorId(target.id); + } + }, + [anchorId, selected, sorted], + ); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + const target = e.target as HTMLElement | null; + if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return; + const mod = e.metaKey || e.ctrlKey; + const k = e.key.toLowerCase(); + + if (e.key === '?') { + e.preventDefault(); + setHelpOpen((v) => !v); + return; + } + if (helpOpen || importOpen || exportOpen || cloudOpen) return; + + if (mod && k === 'i') { + e.preventDefault(); + setPendingFiles([]); + setImportOpen(true); + return; + } + if (mod && k === 'e') { + e.preventDefault(); + openExport(); + return; + } + if (mod && k === 'a' && view === 'grid') { + e.preventDefault(); + setSelected(sorted.map((p) => p.id)); + setAnchorId(sorted[0]?.id ?? null); + return; + } + if ((e.key === 'Delete' || e.key === 'Backspace') && selected.length) { + e.preventDefault(); + void removePhotos(selected); + return; + } + if (view === 'grid') { + if (e.key.startsWith('Arrow')) { + e.preventDefault(); + const dx = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0; + const dy = e.key === 'ArrowDown' ? 1 : e.key === 'ArrowUp' ? -1 : 0; + moveSelection(dx, dy, e.shiftKey); + return; + } + if (e.key === 'Home' || e.key === 'End') { + e.preventDefault(); + const target = e.key === 'Home' ? sorted[0] : sorted[sorted.length - 1]; + if (target) { + setSelected([target.id]); + setAnchorId(target.id); + } + return; + } + if (k === 'escape') { + setSelected([]); + return; + } + } + + if (!selected.length) { + if (k === 'g') setView('grid'); + return; + } + if (/^[0-5]$/.test(e.key)) { + bulkUpdate(selected, { rating: Number(e.key) }); + e.preventDefault(); + return; + } + if (/^[6-9]$/.test(e.key)) { + const label = COLOR_LABELS[Number(e.key) - 6]; + if (label) { + bulkUpdate(selected, { color: label.value }); + e.preventDefault(); + } + return; + } + if (k === 'p') bulkUpdate(selected, { flag: 'pick' }); + else if (k === 'x') bulkUpdate(selected, { flag: 'reject' }); + else if (k === 'u') bulkUpdate(selected, { flag: 'none' }); + else if (k === 'g') setView('grid'); + else if (k === 'e' && selected[0]) openPhoto(selected[0]); + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [ + selected, + sorted, + anchorId, + view, + bulkUpdate, + openPhoto, + moveSelection, + removePhotos, + openExport, + helpOpen, + importOpen, + exportOpen, + cloudOpen, + ]); + + // Dropping files anywhere in the window imports them, like any desktop editor. + useEffect(() => { + const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files'); + let depth = 0; + const onEnter = (e: DragEvent) => { + if (!hasFiles(e)) return; + depth += 1; + setDropActive(true); + }; + const onOver = (e: DragEvent) => { + if (!hasFiles(e)) return; + e.preventDefault(); + if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'; + }; + const onLeave = (e: DragEvent) => { + if (!hasFiles(e)) return; + depth = Math.max(0, depth - 1); + if (!depth) setDropActive(false); + }; + const onDrop = (e: DragEvent) => { + if (!hasFiles(e)) return; + e.preventDefault(); + depth = 0; + setDropActive(false); + const files = Array.from(e.dataTransfer?.files ?? []); + if (!files.length) return; + setPendingFiles(files); + setImportOpen(true); + }; + window.addEventListener('dragenter', onEnter); + window.addEventListener('dragover', onOver); + window.addEventListener('dragleave', onLeave); + window.addEventListener('drop', onDrop); + return () => { + window.removeEventListener('dragenter', onEnter); + window.removeEventListener('dragover', onOver); + window.removeEventListener('dragleave', onLeave); + window.removeEventListener('drop', onDrop); + }; + }, []); + + const eventName = + eventId === 'all' + ? 'All photos' + : eventId === 'unsorted' + ? 'Unsorted' + : events.find((e) => e.id === eventId)?.name ?? 'All photos'; + + if (!loaded) { + return ( +
+
Lumenroom
+

Opening your library…

+
+ ); + } + + return ( +
+ { + if (v === 'develop' && !activePhoto) { + if (sorted[0]) openPhoto(sorted[0].id); + return; + } + setView(v); + }} + onImport={() => { + setPendingFiles([]); + setImportOpen(true); + }} + onExport={openExport} + onCloud={() => { + setCloudError(null); + setCloudOpen(true); + }} + onHelp={() => setHelpOpen(true)} + /> + + {loadError &&
Storage unavailable: {loadError}
} + + {bridgeEvent?.bridge && ( +
+ + Advanced edit of “{bridgeEvent.name}” — a temporary copy. Use “Save to + event” on a photo when its look is ready. + + + + + Back to dashboard + + +
+ )} + +
+ {view === 'grid' && ( + { + await createEvent(name); + }} + onRename={renameEvent} + onDelete={removeEvent} + onReorderEvents={reorderEvents} + onDropPhotos={movePhotosToEvent} + storageNote={ + cloudUser + ? `Synced as ${cloudUser.name || cloudUser.email}. Originals live on the team server.` + : cloudHealth + ? 'Server found — sign in to share this library with the team.' + : 'Stored in this browser. Run "npm run server" to share with the team.' + } + /> + )} + +
+ {view === 'grid' ? ( + <> + + updatePhoto(id, { rating })} + onBulkRate={(rating) => bulkUpdate(selected, { rating })} + onBulkFlag={(flag) => bulkUpdate(selected, { flag })} + onBulkColor={(color) => bulkUpdate(selected, { color })} + onDelete={() => removePhotos(selected)} + onExport={openExport} + onImport={() => { + setPendingFiles([]); + setImportOpen(true); + }} + onDropFiles={(files) => { + setPendingFiles(files); + setImportOpen(true); + }} + onClearSelection={() => setSelected([])} + onReorder={reorderPhotos} + onMarqueeSelect={(ids) => { + setSelected(ids); + setAnchorId(ids[0] ?? null); + }} + /> + + ) : activePhoto ? ( + setView('grid')} + onUpdate={updatePhoto} + onNavigate={navigate} + clipboard={clipboard} + onCopy={copySettings} + onPaste={() => pasteSettings([activePhoto.id])} + onExport={openExport} + presets={[...PRESETS, ...customPresets]} + onSavePreset={savePreset} + onDelete={() => removePhotos([activePhoto.id])} + /> + ) : ( +
+

No photo selected

+ +
+ )} +
+
+ + {importOpen && ( + { + setImportOpen(false); + setCloudError(null); + setCloudOpen(true); + }} + onClose={() => { + setImportOpen(false); + setPendingFiles([]); + }} + onImported={(imported, targetEventId) => { + setPhotos((prev) => [...imported, ...prev]); + setEventId(targetEventId); + setSelected(imported.map((p) => p.id)); + setToast(`Imported ${imported.length} photo${imported.length === 1 ? '' : 's'}`); + }} + onCreateEvent={createEvent} + /> + )} + + {exportOpen && ( + setExportOpen(false)} + onDone={(message, options) => { + setExportOptions(options); + closeExport(message); + }} + /> + )} + + {helpOpen && setHelpOpen(false)} />} + + {dropActive && ( +
+
+ Drop to import + JPEG, PNG, TIFF or camera raw — released anywhere in the window +
+
+ )} + + {cloudOpen && ( + void handleCloudLogin(email, password)} + onRegister={(input) => void handleCloudRegister(input)} + onLogout={() => void handleCloudLogout()} + onSync={() => void handleSync()} + onClose={() => setCloudOpen(false)} + /> + )} + + {menu && + (() => { + const targets = photos.filter((p) => menu.ids.includes(p.id)); + const lead = targets[0]; + if (!lead) return null; + const sharedRating = targets.every((p) => p.rating === lead.rating) ? lead.rating : 0; + const sharedFlag = targets.every((p) => p.flag === lead.flag) ? lead.flag : 'none'; + const sharedColor = targets.every((p) => p.color === lead.color) ? lead.color : ''; + const anyEdited = targets.some((p) => isEdited(p.edits)); + const entries: MenuEntry[] = [ + { label: 'Open in Develop', shortcut: 'E', onSelect: () => openPhoto(lead.id) }, + 'separator', + { label: 'Copy settings', shortcut: '⌘C', onSelect: () => copySettingsOf(lead.id) }, + { + label: 'Paste settings', + shortcut: '⌘V', + disabled: !clipboard, + onSelect: () => pasteSettings(menu.ids), + }, + 'separator', + { label: 'Reset adjustments', disabled: !anyEdited, onSelect: () => resetEdits(menu.ids) }, + 'separator', + { label: 'Export…', onSelect: openExport }, + { label: 'Delete…', danger: true, onSelect: () => void removePhotos(menu.ids) }, + ]; + return ( + setMenu(null)} + header={ +
+ bulkUpdate(menu.ids, { rating: n })} size="md" /> + bulkUpdate(menu.ids, { flag: f })} /> + bulkUpdate(menu.ids, { color: c })} /> +
+ } + entries={entries} + /> + ); + })()} + + {toast &&
{toast}
} +
+ ); +} diff --git a/lumenroom/src/components/CloudPanel.tsx b/lumenroom/src/components/CloudPanel.tsx new file mode 100644 index 0000000..c2afa16 --- /dev/null +++ b/lumenroom/src/components/CloudPanel.tsx @@ -0,0 +1,196 @@ +import { useEffect, useState } from 'react'; +import type { Health, SessionUser } from '../lib/api'; + +interface Props { + health: Health | null; + user: SessionUser | null; + busy: boolean; + note: string | null; + error: string | null; + onLogin: (email: string, password: string) => void; + onRegister: (input: { email: string; password: string; name: string; invite: string }) => void; + onLogout: () => void; + onSync: () => void; + onClose: () => void; +} + +function fmtBytes(bytes: number) { + if (bytes > 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`; + if (bytes > 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)} MB`; + return `${Math.round(bytes / 1024)} KB`; +} + +export default function CloudPanel({ + health, + user, + busy, + note, + error, + onLogin, + onRegister, + onLogout, + onSync, + onClose, +}: Props) { + const [mode, setMode] = useState<'signin' | 'signup'>('signin'); + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [name, setName] = useState(''); + const [invite, setInvite] = useState(''); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key !== 'Escape') return; + e.preventDefault(); + e.stopImmediatePropagation(); + if (!busy) onClose(); + }; + window.addEventListener('keydown', onKey, true); + return () => window.removeEventListener('keydown', onKey, true); + }, [busy, onClose]); + + const submit = () => { + if (busy) return; + if (mode === 'signin') onLogin(email.trim(), password); + else onRegister({ email: email.trim(), password, name: name.trim(), invite: invite.trim() }); + }; + + return ( +
e.target === e.currentTarget && onClose()}> +
+
+

Team server

+ +
+ +
+ {!health ? ( +
+ No server detected +

+ The library is running fully in this browser. To share photos with the team, start the + server and reload: +

+
npm run server
+

+ Originals, edits and ratings are then stored on disk under server/data. +

+
+ ) : user ? ( +
+
+
{(user.name || user.email).slice(0, 1).toUpperCase()}
+
+ {user.name || user.email} +
+ {user.email} · {user.role} +
+
+
+
+
+
Photos on server
+
{health.photos}
+
+
+
Storage used
+
{fmtBytes(health.bytes)}
+
+
+
Raw engine
+
{health.raw.libraw ? 'LibRaw demosaic' : 'Embedded previews'}
+
+
+
Server version
+
{health.version}
+
+
+
+ + +
+ {note &&
{note}
} +
+ ) : ( + <> +
+ + +
+ + + + {mode === 'signup' && ( + + )} + + + + {mode === 'signup' && !health.needsSetup && ( + + )} + + {mode === 'signup' && health.needsSetup && ( +

+ The first account becomes the team admin. Share the invite code you set in{' '} + LUMENROOM_INVITE with everyone else. +

+ )} + + + + )} + + {error &&
{error}
} + + {health && ( +

+ Server sharing the folder server/data · raw formats:{' '} + {health.raw.formats.length} · {health.raw.sharp ? 'JPEG encoder ready' : 'PNG fallback'} +

+ )} +
+
+
+ ); +} diff --git a/lumenroom/src/components/ContextMenu.tsx b/lumenroom/src/components/ContextMenu.tsx new file mode 100644 index 0000000..9447dff --- /dev/null +++ b/lumenroom/src/components/ContextMenu.tsx @@ -0,0 +1,99 @@ +import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; +import { createPortal } from 'react-dom'; + +export interface MenuAction { + label: string; + shortcut?: string; + onSelect: () => void; + disabled?: boolean; + danger?: boolean; +} + +export type MenuEntry = MenuAction | 'separator'; + +interface Props { + x: number; + y: number; + entries: MenuEntry[]; + header?: ReactNode; + onClose: () => void; +} + +/** + * Right-click menu anchored to the pointer. Rendered in a portal so the app's + * scroll containers and panel overflow cannot clip it, and nudged inside the + * window when the cursor is close to an edge. + */ +export default function ContextMenu({ x, y, entries, header, onClose }: Props) { + const ref = useRef(null); + const [pos, setPos] = useState<{ left: number; top: number } | null>(null); + + useLayoutEffect(() => { + const el = ref.current; + if (!el) return; + const rect = el.getBoundingClientRect(); + const margin = 8; + setPos({ + left: Math.max(margin, Math.min(x, window.innerWidth - rect.width - margin)), + top: Math.max(margin, Math.min(y, window.innerHeight - rect.height - margin)), + }); + }, [x, y]); + + useEffect(() => { + const onPointerDown = (e: PointerEvent) => { + if (ref.current && e.target instanceof Node && ref.current.contains(e.target)) return; + onClose(); + }; + const onKeyDown = (e: KeyboardEvent) => { + if (e.key !== 'Escape') return; + e.preventDefault(); + e.stopPropagation(); + onClose(); + }; + window.addEventListener('pointerdown', onPointerDown, true); + window.addEventListener('keydown', onKeyDown, true); + window.addEventListener('resize', onClose); + window.addEventListener('blur', onClose); + window.addEventListener('wheel', onClose, { passive: true }); + return () => { + window.removeEventListener('pointerdown', onPointerDown, true); + window.removeEventListener('keydown', onKeyDown, true); + window.removeEventListener('resize', onClose); + window.removeEventListener('blur', onClose); + window.removeEventListener('wheel', onClose); + }; + }, [onClose]); + + return createPortal( +
e.preventDefault()} + > + {header &&
{header}
} + {entries.map((entry, i) => + entry === 'separator' ? ( +
+ ) : ( + + ), + )} +
, + document.body, + ); +} diff --git a/lumenroom/src/components/CropOverlay.tsx b/lumenroom/src/components/CropOverlay.tsx new file mode 100644 index 0000000..3ca1b6f --- /dev/null +++ b/lumenroom/src/components/CropOverlay.tsx @@ -0,0 +1,268 @@ +import { useEffect, useRef, useState, type PointerEvent } from 'react'; +import { clamp } from '../lib/curves'; +import { grainSampleWindow, Renderer } from '../gl/renderer'; +import type { CropState, Edits } from '../types'; + +type Mode = 'move' | 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'; + +/** + * Point (frame uv) the loupe sits on when dragged to `u`,`v` inside the crop + * rectangle, kept a half-box away from its edges so the patch stays inside. + */ +export function clampLoupe( + crop: { x: number; y: number; w: number; h: number }, + u: number, + v: number, + halfU: number, + halfV: number, +) { + const cx = Math.min(1 - halfU, Math.max(halfU, Math.min(1, Math.max(0, u)))); + const cy = Math.min(1 - halfV, Math.max(halfV, Math.min(1, Math.max(0, v)))); + return { x: crop.x + cx * crop.w, y: crop.y + cy * crop.h }; +} + +interface Props { + crop: CropState; + frame: { w: number; h: number }; + ratio: number | null; + bitmap: ImageBitmap | null; + edits: Edits; + onChange: (rect: Partial) => void; + /** lets the preview hold the grain still while a handle is moving */ + onDragChange?: (busy: boolean) => void; +} + +const MIN = 0.04; + +function clampRect(r: CropState): CropState { + let w = clamp(r.w, MIN, 1); + let h = clamp(r.h, MIN, 1); + const x = clamp(r.x, 0, 1 - w); + const y = clamp(r.y, 0, 1 - h); + return { ...r, x, y, w, h }; +} + +function applyDrag( + start: CropState, + mode: Mode, + dx: number, + dy: number, + ratio: number | null, + frame: { w: number; h: number }, +): Partial { + let { x, y, w, h } = start; + + if (mode === 'move') { + x = clamp(x + dx, 0, 1 - w); + y = clamp(y + dy, 0, 1 - h); + return { x, y }; + } + + if (mode.includes('e')) w = clamp(w + dx, MIN, 1 - x); + if (mode.includes('s')) h = clamp(h + dy, MIN, 1 - y); + if (mode.includes('w')) { + const nx = clamp(x + dx, 0, x + w - MIN); + w += x - nx; + x = nx; + } + if (mode.includes('n')) { + const ny = clamp(y + dy, 0, y + h - MIN); + h += y - ny; + y = ny; + } + + if (ratio) { + const frameRatio = frame.w / frame.h; + const dragsWidth = mode.includes('e') || mode.includes('w'); + if (dragsWidth) { + const targetH = (w * frameRatio) / ratio; + if (mode.includes('n')) y = y + h - targetH; + h = targetH; + } else if (mode.includes('n') || mode.includes('s')) { + const targetW = (h * ratio) / frameRatio; + x += (w - targetW) / 2; + w = targetW; + } + if (w > 1) { + const k = 1 / w; + w *= k; + h *= k; + } + if (h > 1) { + const k = 1 / h; + w *= k; + h *= k; + } + if (mode.includes('w')) x = start.x + start.w - w; + if (mode.includes('n')) y = start.y + start.h - h; + x = clamp(x, 0, 1 - w); + y = clamp(y, 0, 1 - h); + } + + return clampRect({ ...start, x, y, w, h }); +} + +export default function CropOverlay({ crop, frame, ratio, bitmap, edits, onChange, onDragChange }: Props) { + const ref = useRef(null); + const start = useRef<{ mode: Mode; x: number; y: number; rect: CropState } | null>(null); + const [dragging, setDragging] = useState(false); + const loupe = useRef(null); + const loupeRenderer = useRef(null); + /** where the patch is sampling, in frame uv; null = centre of the rectangle */ + const [loupePoint, setLoupePoint] = useState<{ x: number; y: number } | null>(null); + /** pointer offset from the patch centre while it is being dragged */ + const grab = useRef<{ x: number; y: number } | null>(null); + + useEffect( + () => () => { + loupeRenderer.current?.dispose(); + loupeRenderer.current = null; + }, + [], + ); + + // A live 1:1 grain patch inside the crop rectangle: it samples whatever area the + // rectangle frames, so the rectangle can be judged as it is dragged. + useEffect(() => { + const canvas = loupe.current; + if (!canvas || !bitmap) return; + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const cssW = 120; + const cropPxW = Math.max(1, frame.w * crop.w); + const cropPxH = Math.max(1, frame.h * crop.h); + const cssH = Math.round(Math.min(96, Math.max(48, cssW * (cropPxH / cropPxW)))); + const W = Math.max(1, Math.round(cssW * dpr)); + const H = Math.max(1, Math.round(cssH * dpr)); + canvas.style.width = `${cssW}px`; + canvas.style.height = `${cssH}px`; + if (canvas.width !== W) canvas.width = W; + if (canvas.height !== H) canvas.height = H; + try { + if (!loupeRenderer.current) loupeRenderer.current = new Renderer(canvas); + const r = loupeRenderer.current; + r.setImage(bitmap); + const view = grainSampleWindow(frame, crop, W, H, loupePoint); + r.render({ ...edits, crop }, { width: W, height: H, view }); + } catch { + // The overlay still works if the engine cannot start a second context. + } + }, [bitmap, crop, edits, frame, loupePoint]); + + const dpr = Math.min(typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1, 2); + const loupeCssW = 120; + const cropPxW = Math.max(1, frame.w * crop.w); + const cropPxH = Math.max(1, frame.h * crop.h); + const loupeCssH = Math.round(Math.min(96, Math.max(48, loupeCssW * (cropPxH / cropPxW)))); + const loupeW = Math.max(1, Math.round(loupeCssW * dpr)); + const loupeH = Math.max(1, Math.round(loupeCssH * dpr)); + const view = grainSampleWindow(frame, crop, loupeW, loupeH, loupePoint); + const fits = crop.w > 0.16 && crop.h > 0.16; + const loupeAt = { + left: `${((view.x + view.w / 2 - crop.x) / crop.w) * 100}%`, + top: `${((view.y + view.h / 2 - crop.y) / crop.h) * 100}%`, + width: `${loupeCssW}px`, + height: `${loupeCssH}px`, + transform: 'translate(-50%, -50%)', + display: fits && bitmap ? 'block' : 'none', + }; + + const startLoupe = (e: PointerEvent) => { + e.preventDefault(); + e.stopPropagation(); + e.currentTarget.setPointerCapture(e.pointerId); + const box = e.currentTarget.parentElement?.getBoundingClientRect(); + if (!box || !box.width || !box.height) return; + const cx = box.left + ((view.x + view.w / 2 - crop.x) / crop.w) * box.width; + const cy = box.top + ((view.y + view.h / 2 - crop.y) / crop.h) * box.height; + grab.current = { x: e.clientX - cx, y: e.clientY - cy }; + }; + + const moveLoupe = (e: PointerEvent) => { + const g = grab.current; + if (!g) return; + const box = e.currentTarget.parentElement?.getBoundingClientRect(); + if (!box || !box.width || !box.height) return; + const halfU = Math.min(0.5, loupeCssW / 2 / box.width); + const halfV = Math.min(0.5, loupeCssH / 2 / box.height); + setLoupePoint( + clampLoupe( + crop, + (e.clientX - g.x - box.left) / box.width, + (e.clientY - g.y - box.top) / box.height, + halfU, + halfV, + ), + ); + }; + + const endLoupe = () => { + grab.current = null; + }; + + const onPointerDown = (e: React.PointerEvent) => { + const el = e.target as HTMLElement; + const mode = (el.dataset.mode ?? 'move') as Mode; + e.preventDefault(); + e.stopPropagation(); + ref.current?.setPointerCapture(e.pointerId); + start.current = { mode, x: e.clientX, y: e.clientY, rect: { ...crop } }; + setDragging(true); + onDragChange?.(true); + }; + + const onPointerMove = (e: React.PointerEvent) => { + const s = start.current; + const el = ref.current; + if (!s || !el) return; + const rect = el.getBoundingClientRect(); + if (!rect.width || !rect.height) return; + const dx = (e.clientX - s.x) / rect.width; + const dy = (e.clientY - s.y) / rect.height; + onChange(applyDrag(s.rect, s.mode, dx, dy, ratio, frame)); + }; + + const end = (e: React.PointerEvent) => { + if (ref.current?.hasPointerCapture(e.pointerId)) ref.current.releasePointerCapture(e.pointerId); + start.current = null; + setDragging(false); + onDragChange?.(false); + }; + + const style = { + left: `${crop.x * 100}%`, + top: `${crop.y * 100}%`, + width: `${crop.w * 100}%`, + height: `${crop.h * 100}%`, + }; + + return ( +
+
+
+ {(['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as Mode[]).map((m) => ( + + ))} + + + {Math.round(crop.w * 100)}% × {Math.round(crop.h * 100)}% + +
+
+ ); +} diff --git a/lumenroom/src/components/CurveEditor.tsx b/lumenroom/src/components/CurveEditor.tsx new file mode 100644 index 0000000..2db1ad2 --- /dev/null +++ b/lumenroom/src/components/CurveEditor.tsx @@ -0,0 +1,122 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { buildSampler, clamp01 } from '../lib/curves'; +import type { CurvePoint } from '../types'; + +interface Props { + points: CurvePoint[]; + onChange: (points: CurvePoint[]) => void; + color: string; +} + +export default function CurveEditor({ points, onChange, color }: Props) { + const svgRef = useRef(null); + const pointsRef = useRef(points); + const [drag, setDrag] = useState(null); + const [hover, setHover] = useState(null); + + useEffect(() => { + pointsRef.current = points; + }, [points]); + + const sampler = useMemo(() => buildSampler(points), [points]); + + const path = useMemo(() => { + const segs: string[] = []; + for (let i = 0; i <= 80; i++) { + const x = i / 80; + const y = sampler(x); + segs.push(`${i === 0 ? 'M' : 'L'}${(x * 100).toFixed(2)},${((1 - y) * 100).toFixed(2)}`); + } + return segs.join(' '); + }, [sampler]); + + const toNorm = useCallback((clientX: number, clientY: number) => { + const svg = svgRef.current; + if (!svg) return { x: 0, y: 0 }; + const rect = svg.getBoundingClientRect(); + return { + x: clamp01((clientX - rect.left) / rect.width), + y: clamp01(1 - (clientY - rect.top) / rect.height), + }; + }, []); + + const handleDown = (e: React.PointerEvent) => { + e.preventDefault(); + const idxAttr = (e.target as Element).getAttribute('data-idx'); + let idx: number; + if (idxAttr !== null) { + idx = Number(idxAttr); + } else { + const p = toNorm(e.clientX, e.clientY); + const next = [...points, { x: p.x, y: p.y }].sort((a, b) => a.x - b.x); + idx = next.findIndex((pt) => pt.x === p.x && pt.y === p.y); + onChange(next); + } + setDrag(idx); + e.currentTarget.setPointerCapture(e.pointerId); + }; + + const handleMove = (e: React.PointerEvent) => { + if (drag === null) return; + const pts = pointsRef.current; + const idx = drag; + if (!pts[idx]) return; + const p = toNorm(e.clientX, e.clientY); + const lo = idx > 0 ? pts[idx - 1].x + 0.01 : 0; + const hi = idx < pts.length - 1 ? pts[idx + 1].x - 0.01 : 1; + const next = pts.map((pt, i) => (i === idx ? { x: Math.min(hi, Math.max(lo, p.x)), y: p.y } : pt)); + onChange(next); + }; + + const handleUp = () => setDrag(null); + + const removePoint = (idx: number) => { + const pts = pointsRef.current; + if (pts.length <= 2) return; + onChange(pts.filter((_, i) => i !== idx)); + setDrag(null); + }; + + return ( +
+ { + const idxAttr = (e.target as Element).getAttribute('data-idx'); + if (idxAttr !== null) removePoint(Number(idxAttr)); + }} + > + + {[25, 50, 75].map((v) => ( + + + + + ))} + + + {points.map((p, i) => ( + setHover(i)} + onPointerLeave={() => setHover((h) => (h === i ? null : h))} + /> + ))} + +
Click to add a point · drag to shape · double-click a point to remove
+
+ ); +} diff --git a/lumenroom/src/components/Develop.tsx b/lumenroom/src/components/Develop.tsx new file mode 100644 index 0000000..9b7f3fd --- /dev/null +++ b/lumenroom/src/components/Develop.tsx @@ -0,0 +1,736 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits'; +import { getBitmap } from '../lib/images'; +import { rotatedBounds, Renderer } from '../gl/renderer'; +import type { Edits, EventRecord, PhotoRecord, Preset } from '../types'; +import ContextMenu, { type MenuEntry } from './ContextMenu'; +import CropOverlay from './CropOverlay'; +import Histogram from './Histogram'; +import { + BasicPanel, + ColorGradingPanel, + CropPanel, + CurvePanel, + DetailPanel, + EffectsPanel, + HistoryPanel, + HslPanel, + MetadataPanel, + NavigatorPanel, + PresetsPanel, +} from './Panels'; +import Stars, { ColorSwatches, FlagButtons } from './Stars'; + +/** Zoom is expressed as a percentage of actual pixels, like Lightroom's readout. */ +const MAX_ZOOM = 400; +const clampNum = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); + +interface Rect { + x: number; + y: number; + w: number; + h: number; +} + +interface Geometry { + fitScale: number; + fitPct: number; + frameW: number; + frameH: number; + zoomFactor: number; + availW: number; + availH: number; + content: Rect; + view: Rect; +} + +const EMPTY_GEO: Geometry = { + fitScale: 0, + fitPct: 100, + frameW: 1, + frameH: 1, + zoomFactor: 1, + availW: 0, + availH: 0, + content: { x: 0, y: 0, w: 1, h: 1 }, + view: { x: 0, y: 0, w: 1, h: 1 }, +}; + +interface Props { + photo: PhotoRecord; + photos: PhotoRecord[]; + events: EventRecord[]; + onSelect: (id: string) => void; + onExit: () => void; + onUpdate: (id: string, patch: Partial, historyLabel?: string) => void; + onNavigate: (dir: -1 | 1) => void; + clipboard: Edits | null; + onCopy: () => void; + onPaste: () => void; + onExport: () => void; + presets: Preset[]; + onSavePreset: (name: string, edits: Edits) => void; + onDelete: () => void; +} + +export default function Develop({ + photo, + photos, + events, + onSelect, + onExit, + onUpdate, + onNavigate, + clipboard, + onCopy, + onPaste, + onExport, + presets, + onSavePreset, + onDelete, +}: Props) { + const canvasRef = useRef(null); + const stageRef = useRef(null); + const stripRef = useRef(null); + const rendererRef = useRef(null); + const histRef = useRef(null); + const geoRef = useRef(EMPTY_GEO); + const panRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null); + + const [bitmap, setBitmap] = useState(null); + const [stage, setStage] = useState({ w: 0, h: 0 }); + const [cropMode, setCropMode] = useState(false); + const [cropDrag, setCropDrag] = useState(false); + const [showOriginal, setShowOriginal] = useState(false); + const [histVersion, setHistVersion] = useState(0); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); + const [zoom, setZoom] = useState<{ pct: number | 'fit'; cx: number; cy: number }>({ + pct: 'fit', + cx: 0.5, + cy: 0.5, + }); + const [panning, setPanning] = useState(false); + const [readout, setReadout] = useState({ shown: 100, fit: 100 }); + const [menu, setMenu] = useState<{ x: number; y: number; kind: 'canvas' | 'film' } | null>(null); + + const edits = photo.edits; + const zoomed = zoom.pct !== 'fit'; + + const setEdits = useCallback( + (patch: Partial, label: string) => { + onUpdate(photo.id, { edits: { ...photo.edits, ...patch } }, label); + }, + [onUpdate, photo.id, photo.edits], + ); + + useEffect(() => { + const canvas = canvasRef.current; + if (!canvas) return; + try { + rendererRef.current = new Renderer(canvas); + } catch (err) { + setError(err instanceof Error ? err.message : 'The image engine could not start'); + } + return () => { + rendererRef.current?.dispose(); + rendererRef.current = null; + }; + }, []); + + useEffect(() => { + const el = stageRef.current; + if (!el) return; + setStage({ w: el.clientWidth, h: el.clientHeight }); + const ro = new ResizeObserver((entries) => { + const rect = entries[0].contentRect; + setStage({ w: Math.round(rect.width), h: Math.round(rect.height) }); + }); + ro.observe(el); + return () => ro.disconnect(); + }, [cropMode]); + + useEffect(() => { + let alive = true; + setLoading(true); + getBitmap(photo) + .then((bmp) => { + if (!alive) return; + setBitmap(bmp); + setLoading(false); + }) + .catch((err) => { + if (!alive) return; + setError(err instanceof Error ? err.message : 'Could not load the original image'); + setLoading(false); + }); + return () => { + alive = false; + }; + }, [photo.id, photo.raw, photo.previewUrl]); + + // A new photo, a crop change or entering crop mode all invalidate the current view. + useEffect(() => { + setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 }); + }, [photo.id, cropMode, edits.crop]); + + // Leaving crop mode mid-drag must not leave the grain frozen. + useEffect(() => { + if (!cropMode) setCropDrag(false); + }, [cropMode]); + + const drawPreview = useCallback(() => { + const renderer = rendererRef.current; + const canvas = canvasRef.current; + if (!renderer || !canvas || !bitmap) return; + if (stage.w < 40 || stage.h < 40) return; + + const activeEdits = showOriginal ? { ...defaultEdits(), crop: edits.crop } : edits; + const frame = rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter); + const content: Rect = cropMode + ? { x: 0, y: 0, w: 1, h: 1 } + : { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h }; + const contentW = Math.max(1, frame.w * content.w); + const contentH = Math.max(1, frame.h * content.h); + + const availW = Math.max(60, stage.w - 48); + const availH = Math.max(60, stage.h - 48); + const fitScale = Math.min(availW / contentW, availH / contentH); + const fitPct = Math.min(100, fitScale * 100); + const zoomFactor = zoom.pct === 'fit' ? 1 : Math.max(1, zoom.pct / 100 / fitScale); + + let view: Rect = content; + let cssW = Math.max(40, Math.round(contentW * fitScale)); + let cssH = Math.max(40, Math.round(contentH * fitScale)); + + if (zoomFactor > 1.0001) { + // The visible window keeps the stage's aspect, so the canvas is stage sized + // and the shader maps it onto a sub-rect of the frame. Cost stays constant + // no matter how far you zoom, and detail comes from the source bitmap. + const vw = Math.min(1, availW / (fitScale * zoomFactor) / frame.w); + const vh = Math.min(1, availH / (fitScale * zoomFactor) / frame.h); + const cx = + vw >= content.w + ? content.x + content.w / 2 + : clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2); + const cy = + vh >= content.h + ? content.y + content.h / 2 + : clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2); + view = { x: cx - vw / 2, y: cy - vh / 2, w: vw, h: vh }; + cssW = Math.round(availW); + cssH = Math.round(availH); + } + + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const cap = Math.min(1, 3200 / Math.max(1, Math.max(cssW * dpr, cssH * dpr))); + const pxW = Math.max(1, Math.round(cssW * dpr * cap)); + const pxH = Math.max(1, Math.round(cssH * dpr * cap)); + + canvas.style.width = `${cssW}px`; + canvas.style.height = `${cssH}px`; + + geoRef.current = { + fitScale, + fitPct, + frameW: frame.w, + frameH: frame.h, + zoomFactor, + availW, + availH, + content, + view, + }; + const shown = Math.round(fitScale * zoomFactor * 100); + const fit = Math.round(fitPct); + setReadout((prev) => (prev.shown === shown && prev.fit === fit ? prev : { shown, fit })); + + try { + renderer.setImage(bitmap); + renderer.render(activeEdits, { + width: pxW, + height: pxH, + cropPreview: cropMode, + // The histogram describes the whole photo, so it is only refreshed at fit. + histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001, + view: zoomFactor <= 1.0001 ? undefined : view, + // Holding the grain still keeps the noise from crawling while a crop + // handle moves; the new crop-relative scale applies on release. + freezeGrain: cropDrag, + // One source pixel per device pixel is the crossover: below it mipmaps + // resample cleanly, above it bicubic keeps magnified detail from squaring off. + upscale: dpr * cap * fitScale * zoomFactor > 1.1, + }); + histRef.current = renderer.histogram; + setHistVersion((v) => v + 1); + } catch (err) { + setError(err instanceof Error ? err.message : 'Rendering failed'); + } + }, [bitmap, edits, cropMode, showOriginal, stage, zoom, cropDrag]); + + useEffect(() => { + if (!bitmap) return; + const raf = requestAnimationFrame(drawPreview); + return () => cancelAnimationFrame(raf); + }, [bitmap, drawPreview]); + + /* ------------------------------------------------------------ zoom & pan */ + + const applyZoom = useCallback((rawPct: number | 'fit', point?: { x: number; y: number }) => { + const geo = geoRef.current; + if (!geo.fitScale) return; + const fitPct = geo.fitPct; + if (rawPct === 'fit' || rawPct <= fitPct * 1.015 || fitPct >= 99.5) { + setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 }); + return; + } + const next = clampNum(rawPct, fitPct * 1.02, MAX_ZOOM); + const zNow = Math.max(1, geo.zoomFactor); + const zNext = Math.max(1, next / fitPct); + const centerX = geo.view.x + geo.view.w / 2; + const centerY = geo.view.y + geo.view.h / 2; + let cx = centerX; + let cy = centerY; + + if (point) { + // Keep the frame point under the cursor fixed while the scale changes. + const rect = canvasRef.current?.getBoundingClientRect(); + if (rect) { + const dx = point.x - (rect.left + rect.width / 2); + const dy = point.y - (rect.top + rect.height / 2); + const pointX = centerX + dx / (geo.fitScale * zNow) / geo.frameW; + const pointY = centerY + dy / (geo.fitScale * zNow) / geo.frameH; + cx = pointX - dx / (geo.fitScale * zNext) / geo.frameW; + cy = pointY - dy / (geo.fitScale * zNext) / geo.frameH; + } + } + + const vw = geo.availW / (geo.fitScale * zNext) / geo.frameW; + const vh = geo.availH / (geo.fitScale * zNext) / geo.frameH; + const c = geo.content; + cx = vw >= c.w ? c.x + c.w / 2 : clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2); + cy = vh >= c.h ? c.y + c.h / 2 : clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2); + setZoom({ pct: next, cx, cy }); + }, []); + + // Filmstrip: the wheel browses photos sideways, and the current one is kept + // in view as you move through the shoot. + useEffect(() => { + const el = stripRef.current; + if (!el) return; + const onWheel = (e: WheelEvent) => { + if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return; + e.preventDefault(); + el.scrollLeft += e.deltaY; + }; + el.addEventListener('wheel', onWheel, { passive: false }); + return () => el.removeEventListener('wheel', onWheel); + }, []); + + useEffect(() => { + stripRef.current?.querySelector('.film.active')?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + }, [photo.id]); + + useEffect(() => { + const el = stageRef.current; + if (!el) return; + const onWheel = (e: WheelEvent) => { + if (cropMode) return; + const geo = geoRef.current; + if (!geo.fitScale) return; + if (!e.ctrlKey && Math.abs(e.deltaX) > Math.abs(e.deltaY)) return; + e.preventDefault(); + const base = geo.fitPct * Math.max(1, geo.zoomFactor); + applyZoom(base * Math.exp(-e.deltaY * 0.0022), { x: e.clientX, y: e.clientY }); + }; + el.addEventListener('wheel', onWheel, { passive: false }); + return () => el.removeEventListener('wheel', onWheel); + }, [cropMode, applyZoom]); + + const beginPan = (e: React.PointerEvent) => { + if (cropMode || !zoomed || e.button !== 0) return; + const geo = geoRef.current; + panRef.current = { + x: e.clientX, + y: e.clientY, + cx: geo.view.x + geo.view.w / 2, + cy: geo.view.y + geo.view.h / 2, + }; + e.currentTarget.setPointerCapture(e.pointerId); + setPanning(true); + }; + + const movePan = (e: React.PointerEvent) => { + const start = panRef.current; + if (!start) return; + const geo = geoRef.current; + const z = Math.max(1, geo.zoomFactor); + const dx = (e.clientX - start.x) / (geo.fitScale * z * geo.frameW); + const dy = (e.clientY - start.y) / (geo.fitScale * z * geo.frameH); + const c = geo.content; + const cx = + geo.view.w >= c.w + ? c.x + c.w / 2 + : clampNum(start.cx - dx, c.x + geo.view.w / 2, c.x + c.w - geo.view.w / 2); + const cy = + geo.view.h >= c.h + ? c.y + c.h / 2 + : clampNum(start.cy - dy, c.y + geo.view.h / 2, c.y + c.h - geo.view.h / 2); + setZoom((prev) => ({ pct: prev.pct, cx, cy })); + }; + + const endPan = (e: React.PointerEvent) => { + if (!panRef.current) return; + panRef.current = null; + setPanning(false); + if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId); + }; + + const toggleZoom = (x?: number, y?: number) => { + if (cropMode) return; + if (zoomed) applyZoom('fit'); + else applyZoom(100, x !== undefined && y !== undefined ? { x, y } : undefined); + }; + + const undo = useCallback(() => { + const hist = photo.history; + if (hist.length < 2) return; + const idx = hist.findIndex((h) => h.edits === photo.edits); + const target = idx > 0 ? hist[idx - 1] : hist[hist.length - 2]; + if (target) onUpdate(photo.id, { edits: target.edits }); + }, [photo.history, photo.edits, photo.id, onUpdate]); + + useEffect(() => { + const down = (e: KeyboardEvent) => { + const target = e.target as HTMLElement | null; + if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return; + if (e.key === '\\') { + setShowOriginal(true); + return; + } + if (e.key === 'ArrowRight') { + onNavigate(1); + e.preventDefault(); + } else if (e.key === 'ArrowLeft') { + onNavigate(-1); + e.preventDefault(); + } else if (e.key.toLowerCase() === 'c' && !e.metaKey && !e.ctrlKey) { + setCropMode((v) => !v); + } else if (e.key.toLowerCase() === 'z' && !e.metaKey && !e.ctrlKey) { + toggleZoom(); + e.preventDefault(); + } else if (e.key === 'Enter' && cropMode) { + setCropMode(false); + } else if (e.key === 'Escape') { + if (cropMode) setCropMode(false); + else onExit(); + } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') { + undo(); + e.preventDefault(); + } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c') { + onCopy(); + } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'v') { + onPaste(); + } + }; + const up = (e: KeyboardEvent) => { + if (e.key === '\\') setShowOriginal(false); + }; + window.addEventListener('keydown', down); + window.addEventListener('keyup', up); + return () => { + window.removeEventListener('keydown', down); + window.removeEventListener('keyup', up); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [cropMode, onExit, onNavigate, onCopy, onPaste, undo, applyZoom, zoomed]); + + const applyPreset = useCallback( + (preset: Preset) => { + const next: Edits = + preset.id === 'original' + ? { ...defaultEdits(), crop: photo.edits.crop } + : { ...photo.edits, ...preset.edits, crop: photo.edits.crop }; + onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`); + }, + [onUpdate, photo.id, photo.edits], + ); + + const frame = bitmap + ? rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter) + : { w: 1, h: 1 }; + const lockedRatio = useMemo(() => { + const def = ASPECTS.find((a) => a.id === edits.crop.aspect); + return def?.ratio ?? null; + }, [edits.crop.aspect]); + + const applyAspect = useCallback( + (id: string) => { + const def = ASPECTS.find((a) => a.id === id); + if (!def) return; + const f = bitmap + ? rotatedBounds(bitmap.width, bitmap.height, photo.edits.crop.angle, photo.edits.crop.quarter) + : { w: 1, h: 1 }; + let w = 1; + let h = 1; + if (def.ratio) { + const frameRatio = f.w / f.h; + if (def.ratio > frameRatio) { + w = 1; + h = frameRatio / def.ratio; + } else { + h = 1; + w = def.ratio / frameRatio; + } + } + setEdits( + { crop: { ...photo.edits.crop, x: (1 - w) / 2, y: (1 - h) / 2, w, h, aspect: id } }, + def.ratio ? `Crop ${def.label}` : 'Crop', + ); + }, + [bitmap, photo.edits.crop, setEdits], + ); + + const rotate = useCallback( + (dir: -1 | 1) => { + const c = photo.edits.crop; + const quarter = ((c.quarter + dir) % 4 + 4) % 4; + const rect = + dir === 1 + ? { x: 1 - (c.y + c.h), y: c.x, w: c.h, h: c.w } + : { x: c.y, y: 1 - (c.x + c.w), w: c.h, h: c.w }; + setEdits( + { crop: { ...c, quarter, ...rect } }, + dir === 1 ? 'Rotate 90° right' : 'Rotate 90° left', + ); + }, + [photo.edits.crop, setEdits], + ); + + const resetAll = () => { + if (!window.confirm('Reset all develop settings for this photo?')) return; + onUpdate(photo.id, { edits: { ...defaultEdits(), crop: photo.edits.crop } }, 'Reset'); + }; + + const canvasMenu: MenuEntry[] = [ + { label: 'Zoom to Fit', shortcut: 'Z', onSelect: () => applyZoom('fit') }, + { label: 'Zoom to 100%', onSelect: () => applyZoom(100) }, + 'separator', + { label: 'Crop & Straighten', shortcut: 'C', onSelect: () => setCropMode((v) => !v) }, + { label: 'Before / After', shortcut: '\\', onSelect: () => setShowOriginal((v) => !v) }, + 'separator', + { label: 'Copy settings', shortcut: '⌘C', onSelect: onCopy }, + { label: 'Paste settings', shortcut: '⌘V', onSelect: onPaste, disabled: !clipboard }, + { label: 'Reset settings', onSelect: resetAll }, + 'separator', + { label: 'Export…', onSelect: onExport }, + { label: 'Delete photo…', danger: true, onSelect: onDelete }, + ]; + + const filmMenu: MenuEntry[] = [ + { label: 'Copy settings', onSelect: onCopy }, + { label: 'Paste settings', onSelect: onPaste, disabled: !clipboard }, + { label: 'Reset settings', onSelect: resetAll }, + 'separator', + { label: 'Export…', onSelect: onExport }, + { label: 'Delete photo…', danger: true, onSelect: onDelete }, + ]; + + const index = photos.findIndex((p) => p.id === photo.id); + + return ( +
+
+ +
+ {photo.name} + + {index >= 0 ? `${index + 1} / ${photos.length}` : ''} · {photo.width}×{photo.height} + +
+ onUpdate(photo.id, { rating: r })} size="md" /> + onUpdate(photo.id, { flag: f })} /> + onUpdate(photo.id, { color: c })} /> +
+ + + + + + + +
+ +
+ + +
{ + e.preventDefault(); + setMenu({ x: e.clientX, y: e.clientY, kind: 'canvas' }); + }} + > + {error ? ( +
{error}
+ ) : ( +
+ toggleZoom(e.clientX, e.clientY)} + /> + {cropMode && bitmap && ( + setEdits({ crop: { ...photo.edits.crop, ...rect } }, 'Crop')} + onDragChange={setCropDrag} + /> + )} +
+ )} + {loading &&
Loading original…
} + {cropMode &&
Drag the edges to crop · Enter to apply · Esc to cancel
} + {!cropMode && !error && ( +
+ + + {readout.shown}% +
+ )} + {zoomed && !cropMode &&
Drag to pan · scroll to zoom · double-click to fit
} + {showOriginal &&
Before
} +
+ + +
+ +
+ {photos.map((p) => ( + + ))} +
+ + {menu && ( + setMenu(null)} + header={ + menu.kind === 'film' ? ( +
+ onUpdate(photo.id, { rating: r })} size="md" /> + onUpdate(photo.id, { flag: f })} /> + onUpdate(photo.id, { color: c })} /> +
+ ) : undefined + } + entries={menu.kind === 'canvas' ? canvasMenu : filmMenu} + /> + )} +
+ ); +} diff --git a/lumenroom/src/components/EventSidebar.tsx b/lumenroom/src/components/EventSidebar.tsx new file mode 100644 index 0000000..d75beac --- /dev/null +++ b/lumenroom/src/components/EventSidebar.tsx @@ -0,0 +1,202 @@ +import { useState } from 'react'; +import { + draggedEventId, + draggedPhotoIds, + endDrag, + EVENT_DRAG, + PHOTO_DRAG, + startEventDrag, + startPhotoDrag, +} from '../lib/drag'; +import type { EventRecord, PhotoRecord } from '../types'; + +interface Props { + events: EventRecord[]; + photos: PhotoRecord[]; + eventId: string; + onSelectEvent: (id: string) => void; + onCreate: (name: string) => Promise | void; + onRename: (id: string, name: string) => void; + onDelete: (id: string) => void; + onReorderEvents: (dragId: string, targetId: string) => void; + onDropPhotos: (ids: string[], eventId: string) => void; + storageNote: string; +} + +export default function EventSidebar({ + events, + photos, + eventId, + onSelectEvent, + onCreate, + onRename, + onDelete, + onReorderEvents, + onDropPhotos, + storageNote, +}: Props) { + const [adding, setAdding] = useState(false); + const [name, setName] = useState(''); + const [dropTarget, setDropTarget] = useState(null); + + const counts = new Map(); + let unsorted = 0; + for (const p of photos) { + if (!p.eventId) { + unsorted++; + continue; + } + counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1); + } + + const submit = async () => { + if (!name.trim()) { + setAdding(false); + return; + } + await onCreate(name); + setName(''); + setAdding(false); + }; + + const dropProps = (targetId: string) => ({ + onDragOver: (e: React.DragEvent) => { + if (draggedPhotoIds().length) { + e.preventDefault(); + e.stopPropagation(); + e.dataTransfer.dropEffect = 'move'; + setDropTarget(targetId); + } + }, + onDragLeave: () => setDropTarget((cur) => (cur === targetId ? null : cur)), + onDrop: (e: React.DragEvent) => { + const ids = draggedPhotoIds(); + setDropTarget(null); + if (!ids.length) return; + e.preventDefault(); + e.stopPropagation(); + onDropPhotos(ids, targetId); + endDrag(); + }, + }); + + return ( + + ); +} diff --git a/lumenroom/src/components/ExportModal.tsx b/lumenroom/src/components/ExportModal.tsx new file mode 100644 index 0000000..9c9dfa9 --- /dev/null +++ b/lumenroom/src/components/ExportModal.tsx @@ -0,0 +1,385 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import type { ExportOptions, ExportFormat, ResizeMode } from '../lib/export'; +import { buildFileName, DEFAULT_EXPORT, exportPhotos } from '../lib/export'; +import { getBitmap } from '../lib/images'; +import { frameToSource, grainCellPx, grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer'; +import type { PhotoRecord } from '../types'; + +interface Props { + photos: PhotoRecord[]; + initial: ExportOptions; + onClose: () => void; + onDone: (message: string, options: ExportOptions) => void; +} + +const FORMATS: { value: ExportFormat; label: string }[] = [ + { value: 'jpeg', label: 'JPEG' }, + { value: 'png', label: 'PNG' }, + { value: 'webp', label: 'WebP' }, +]; + +/** + * Three 1:1 patches of the export at half, current and double the chosen size. + * Each patch is rendered on the export's own pixel grid, so it shows exactly the + * grain and detail that file will carry at 100%. + */ +function ExportDetailStrip({ photo, size }: { photo: PhotoRecord; size: { w: number; h: number } | null }) { + const tiles = useRef<(HTMLCanvasElement | null)[]>([]); + const pick = useRef(null); + const work = useRef(null); + const renderer = useRef(null); + const bitmap = useRef(null); + const [ready, setReady] = useState(false); + const [point, setPoint] = useState<{ x: number; y: number } | null>(null); + const { crop } = photo.edits; + const srcW = Math.max(1, photo.width); + const srcH = Math.max(1, photo.height); + + useEffect(() => { + let alive = true; + getBitmap(photo) + .then((bmp) => { + if (!alive) return; + bitmap.current = bmp; + setReady(true); + }) + .catch(() => undefined); + return () => { + alive = false; + }; + }, [photo.id]); + + useEffect( + () => () => { + renderer.current?.dispose(); + renderer.current = null; + }, + [], + ); + + const steps = useMemo(() => { + if (!size) return []; + const long = Math.max(size.w, size.h); + return [Math.max(200, Math.round(long / 2)), long, Math.min(20000, long * 2)]; + }, [size]); + + useEffect(() => { + const bmp = bitmap.current; + if (!ready || !bmp || !size || !steps.length) return; + if (!work.current) work.current = document.createElement('canvas'); + const workCanvas = work.current; + try { + if (!renderer.current) renderer.current = new Renderer(workCanvas); + const r = renderer.current; + r.setImage(bmp); + const frame = rotatedBounds(bmp.width, bmp.height, crop.angle, crop.quarter); + const cropPxW = Math.max(1, frame.w * crop.w); + const cropPxH = Math.max(1, frame.h * crop.h); + const PW = 132; + const PH = Math.round(Math.min(92, Math.max(56, PW * (cropPxH / cropPxW)))); + const outLong = Math.max(1, Math.max(size.w, size.h)); + steps.forEach((longEdge, i) => { + const tile = tiles.current[i]; + if (!tile) return; + if (tile.width !== PW) tile.width = PW; + if (tile.height !== PH) tile.height = PH; + const scale = longEdge / outLong; + const pxPerSource = (size.w * scale) / cropPxW; + const view = grainSampleWindow( + frame, + crop, + Math.max(1, Math.round(PW / pxPerSource)), + Math.max(1, Math.round(PH / pxPerSource)), + point, + ); + r.render(photo.edits, { width: PW, height: PH, view, upscale: pxPerSource > 1.05 }); + const ctx = tile.getContext('2d'); + if (ctx) ctx.drawImage(workCanvas, 0, 0); + }); + + // The picker shows the whole exported crop, oriented like the main view. + const pickCanvas = pick.current; + if (pickCanvas) { + const pickW = 132; + const pickH = Math.round(Math.min(112, Math.max(56, pickW * (cropPxH / cropPxW)))); + r.render(photo.edits, { width: pickW, height: pickH, upscale: pickW / cropPxW > 1.05 }); + const ctx = pickCanvas.getContext('2d'); + if (ctx) { + if (pickCanvas.width !== pickW) pickCanvas.width = pickW; + if (pickCanvas.height !== pickH) pickCanvas.height = pickH; + ctx.imageSmoothingQuality = 'high'; + ctx.clearRect(0, 0, pickW, pickH); + ctx.drawImage(workCanvas, 0, 0, pickW, pickH); + } + } + } catch { + // Keep the previous patches if the engine is unavailable. + } + }, [ready, photo, crop, size, steps, point]); + + // Where the patch is, in photo terms, and how big a grain cell is in the file. + const info = useMemo(() => { + // The point lives in frame coordinates; the picker shows only the crop. + const p = point ?? { x: crop.x + crop.w / 2, y: crop.y + crop.h / 2 }; + const at = frameToSource(p, srcW, srcH, crop.angle, crop.quarter, crop.flipH, crop.flipV); + return { + sx: at.x, + sy: at.y, + px: Math.round(at.x * 100), + py: Math.round(at.y * 100), + ux: (p.x - crop.x) / crop.w, + uy: (p.y - crop.y) / crop.h, + cell: size ? grainCellPx(photo.edits, srcW, srcH, size.w) : 0, + }; + }, [point, crop, srcW, srcH, size, photo.edits]); + + if (!size || !steps.length) return null; + return ( + <> +
+
{ + const r = pick.current?.getBoundingClientRect(); + if (!r || !r.width || !r.height) return; + const u = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)); + const v = Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)); + setPoint({ x: crop.x + u * crop.w, y: crop.y + v * crop.h }); + }} + > + + +
+ Click the photo to move the 100% patches +
+
+ {steps.map((longEdge, i) => ( +
+ { tiles.current[i] = el; }} /> +
+ {longEdge === steps[1] ? 'This export' : longEdge < steps[1] ? 'Half size' : 'Double size'} · {longEdge} px · 100% +
+
+ ))} +
+

+ Sample {info.px}% × {info.py}% of the photo ·{' '} + {photo.edits.grain.amount > 1 + ? `grain ${info.cell < 1 ? info.cell.toFixed(2) : info.cell.toFixed(1)} px cells${ + info.cell < 0.9 ? ' (fades: finer than a pixel)' : '' + } at this size` + : 'grain off'} +

+ + ); +} + +export default function ExportModal({ photos, initial, onClose, onDone }: Props) { + const [opts, setOpts] = useState({ ...DEFAULT_EXPORT, ...initial }); + const [busy, setBusy] = useState(false); + const [progress, setProgress] = useState({ done: 0, total: 0 }); + const [error, setError] = useState(null); + + useEffect(() => { + // Capture phase so Escape closes the dialog even with the photo open behind it. + const onKey = (e: KeyboardEvent) => { + if (e.key !== 'Escape') return; + e.preventDefault(); + e.stopImmediatePropagation(); + if (!busy) onClose(); + }; + window.addEventListener('keydown', onKey, true); + return () => window.removeEventListener('keydown', onKey, true); + }, [busy, onClose]); + + const patch = (p: Partial) => setOpts((prev) => ({ ...prev, ...p })); + + const sample = photos[0]; + const previewSize = useMemo(() => { + if (!sample) return null; + const w = sample.width || 1; + const h = sample.height || 1; + const crop = sample.edits.crop; + const swapped = Math.round(crop.quarter) % 2 === 1; + const frameW = swapped ? h : w; + const frameH = swapped ? w : h; + const baseW = Math.max(1, Math.round(frameW * crop.w)); + const baseH = Math.max(1, Math.round(frameH * crop.h)); + let k = 1; + if (opts.resize === 'longEdge' && opts.longEdge > 0 && Math.max(baseW, baseH) > opts.longEdge) { + k = opts.longEdge / Math.max(baseW, baseH); + } else if (opts.resize === 'percent') { + k = Math.min(2, Math.max(0.05, opts.percent / 100)); + } + return { w: Math.round(baseW * k), h: Math.round(baseH * k) }; + }, [sample, opts.resize, opts.longEdge, opts.percent]); + + const sampleName = sample + ? buildFileName(opts.nameTemplate, sample, 0, opts) + : `export.${opts.format === 'jpeg' ? 'jpg' : opts.format}`; + + const run = async () => { + if (!photos.length || busy) return; + setBusy(true); + setError(null); + try { + const { count, failed } = await exportPhotos(photos, opts, (done, total) => + setProgress({ done, total }), + ); + if (!count) { + setError(failed.length ? 'Nothing could be exported. Check the browser console.' : 'Nothing to export'); + setBusy(false); + return; + } + onDone(`Exported ${count} photo${count === 1 ? '' : 's'}`, opts); + onClose(); + } catch (err) { + setError(err instanceof Error ? err.message : 'Export failed'); + setBusy(false); + } + }; + + return ( +
e.target === e.currentTarget && !busy && onClose()}> +
+
+

Export

+ +
+ +
+
+ + {photos.length} photo{photos.length === 1 ? '' : 's'} + + {previewSize && ( + + {previewSize.w} × {previewSize.h} px + + )} +
+ +
+ + + + + {opts.resize === 'longEdge' && ( + + )} + + {opts.resize === 'percent' && ( + + )} +
+ + {opts.format !== 'png' && ( + + )} + + {sample && } + + +

+ Tokens: {'{name}'} {'{date}'} {'{time}'}{' '} + {'{index}'} · first file: {sampleName} +

+ + {busy && progress.total > 0 && ( +
+
+
+
+
+ {progress.done} / {progress.total} +
+
+ )} + + {error &&
{error}
} +
+ +
+ + +
+
+
+ ); +} diff --git a/lumenroom/src/components/FilterBar.tsx b/lumenroom/src/components/FilterBar.tsx new file mode 100644 index 0000000..a8cef33 --- /dev/null +++ b/lumenroom/src/components/FilterBar.tsx @@ -0,0 +1,140 @@ +import { COLOR_LABELS } from '../lib/edits'; +import type { ColorLabel, Filters, Flag, SortKey } from '../types'; + +interface Props { + filters: Filters; + setFilters: (next: Filters) => void; + count: number; + total: number; + sort: SortKey; + setSort: (s: SortKey) => void; + asc: boolean; + setAsc: (v: boolean) => void; +} + +const FLAGS: { value: Flag | 'any'; label: string }[] = [ + { value: 'any', label: 'Any' }, + { value: 'pick', label: 'Picked' }, + { value: 'none', label: 'Unflagged' }, + { value: 'reject', label: 'Rejected' }, +]; + +export default function FilterBar({ filters, setFilters, count, total, sort, setSort, asc, setAsc }: Props) { + const patch = (p: Partial) => setFilters({ ...filters, ...p }); + const active = filters.minRating > 0 || filters.flag !== 'any' || filters.colors.length > 0 || !!filters.text || filters.editedOnly || filters.unrated; + + const toggleColor = (color: ColorLabel) => { + const exists = filters.colors.includes(color); + patch({ colors: exists ? filters.colors.filter((c) => c !== color) : [...filters.colors, color] }); + }; + + return ( +
+
+ Rating +
+ {[0, 1, 2, 3, 4, 5].map((n) => ( + + ))} + +
+
+ +
+ Flag +
+ {FLAGS.map((f) => ( + + ))} +
+
+ +
+ Label +
+ {COLOR_LABELS.map((c) => ( +
+
+ +
+ patch({ text: e.target.value })} + /> +
+ + + +
+ Sort + + +
+ + {active && ( + + )} + +
+ {count} + {count !== total ? ` / ${total}` : ''} shown +
+
+ ); +} diff --git a/lumenroom/src/components/Histogram.tsx b/lumenroom/src/components/Histogram.tsx new file mode 100644 index 0000000..3ced03b --- /dev/null +++ b/lumenroom/src/components/Histogram.tsx @@ -0,0 +1,63 @@ +import { useEffect, useRef } from 'react'; +import type { Histogram as HistogramData } from '../gl/renderer'; + +export default function Histogram({ data, version }: { data: HistogramData | null; version: number }) { + const ref = useRef(null); + + useEffect(() => { + const canvas = ref.current; + if (!canvas) return; + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const rect = canvas.getBoundingClientRect(); + const w = Math.max(1, Math.round(rect.width * dpr)); + const h = Math.max(1, Math.round(rect.height * dpr)); + if (canvas.width !== w) canvas.width = w; + if (canvas.height !== h) canvas.height = h; + const ctx = canvas.getContext('2d'); + if (!ctx) return; + ctx.clearRect(0, 0, w, h); + ctx.fillStyle = '#121214'; + ctx.fillRect(0, 0, w, h); + + // grid + ctx.strokeStyle = 'rgba(255,255,255,0.06)'; + ctx.lineWidth = 1; + for (let i = 1; i < 4; i++) { + const x = (i / 4) * w; + ctx.beginPath(); + ctx.moveTo(x, 0); + ctx.lineTo(x, h); + ctx.stroke(); + } + if (!data) return; + + let peak = 0; + for (let i = 1; i < 255; i++) { + peak = Math.max(peak, data.r[i], data.g[i], data.b[i]); + } + if (peak <= 0) return; + + const scale = (v: number) => Math.pow(v / peak, 0.42); + const drawChannel = (bins: Uint32Array, color: string) => { + ctx.beginPath(); + ctx.moveTo(0, h); + for (let i = 0; i < 256; i++) { + const x = (i / 255) * w; + const y = h - scale(bins[i]) * (h - 2); + ctx.lineTo(x, y); + } + ctx.lineTo(w, h); + ctx.closePath(); + ctx.fillStyle = color; + ctx.fill(); + }; + + ctx.globalCompositeOperation = 'lighter'; + drawChannel(data.r, 'rgba(220,64,64,0.55)'); + drawChannel(data.g, 'rgba(64,200,96,0.55)'); + drawChannel(data.b, 'rgba(72,120,240,0.55)'); + ctx.globalCompositeOperation = 'source-over'; + }, [data, version]); + + return ; +} diff --git a/lumenroom/src/components/ImportModal.tsx b/lumenroom/src/components/ImportModal.tsx new file mode 100644 index 0000000..b0b9ecf --- /dev/null +++ b/lumenroom/src/components/ImportModal.tsx @@ -0,0 +1,224 @@ +import { useEffect, useRef, useState } from 'react'; +import type { CloudImport, ImportProgress } from '../lib/import'; +import { importFiles, isSupportedFile } from '../lib/import'; +import { isRawFile, RAW_ACCEPT } from '../lib/raw'; +import type { EventRecord, PhotoRecord } from '../types'; + +interface Props { + events: EventRecord[]; + initialEventId: string; + initialFiles: File[]; + onClose: () => void; + onImported: (photos: PhotoRecord[], eventId: string) => void; + onCreateEvent: (name: string) => Promise; + cloud?: CloudImport | null; + onNeedServer: () => void; +} + +export default function ImportModal({ + events, + initialEventId, + initialFiles, + onClose, + onImported, + onCreateEvent, + cloud, + onNeedServer, +}: Props) { + const startId = initialEventId !== 'all' && initialEventId !== 'unsorted' ? initialEventId : events[0]?.id ?? '__new'; + const [eventId, setEventId] = useState(startId); + const [newName, setNewName] = useState(''); + const [files, setFiles] = useState(initialFiles); + const [dragOver, setDragOver] = useState(false); + const [busy, setBusy] = useState(false); + const [progress, setProgress] = useState(null); + const [failures, setFailures] = useState([]); + const inputRef = useRef(null); + const rawCount = files.filter(isRawFile).length; + + useEffect(() => { + // Capture phase: Escape closes this dialog even while a photo is open behind it. + const onKey = (e: KeyboardEvent) => { + if (e.key !== 'Escape') return; + e.preventDefault(); + e.stopImmediatePropagation(); + if (!busy) onClose(); + }; + window.addEventListener('keydown', onKey, true); + return () => window.removeEventListener('keydown', onKey, true); + }, [busy, onClose]); + + const addFiles = (list: FileList | null) => { + if (!list) return; + const incoming = Array.from(list).filter(isSupportedFile); + setFiles((prev) => { + const seen = new Set(prev.map((f) => `${f.name}:${f.size}`)); + return [...prev, ...incoming.filter((f) => !seen.has(`${f.name}:${f.size}`))]; + }); + }; + + const run = async () => { + if (!files.length || busy) return; + setBusy(true); + setFailures([]); + try { + let targetId = eventId; + if (targetId === '__new') { + const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`); + targetId = created.id; + } + const result = await importFiles(files, targetId, [], setProgress, cloud ?? null); + if (result.photos.length) onImported(result.photos, targetId); + if (result.failed.length) { + setFailures(result.failed.map((f) => `${f.name} — ${f.reason}`)); + setBusy(false); + setFiles([]); + setProgress(null); + if (result.photos.length) setTimeout(onClose, 1200); + } else { + onClose(); + } + } catch (err) { + setFailures([err instanceof Error ? err.message : 'Import failed']); + setBusy(false); + } + }; + + return ( +
e.target === e.currentTarget && !busy && onClose()}> +
+
+

Import photos

+ +
+ +
+ + + {eventId === '__new' && ( + + )} + +
{ + e.preventDefault(); + setDragOver(true); + }} + onDragLeave={() => setDragOver(false)} + onDrop={(e) => { + e.preventDefault(); + setDragOver(false); + addFiles(e.dataTransfer.files); + }} + onClick={() => inputRef.current?.click()} + > +
⤒
+
+ Drop photos here +

+ or click to choose files. JPEG, PNG, WebP, AVIF, TIFF and camera raw (CR2, CR3, NEF, + ARW, ORF, RW2, RAF, DNG, PEF…) — raw needs the team server. +

+
+ addFiles(e.target.files)} + /> +
+ + {files.length > 0 && ( +
+ + {files.length} file{files.length === 1 ? '' : 's'} ready ·{' '} + {(files.reduce((sum, f) => sum + f.size, 0) / (1024 * 1024)).toFixed(1)} MB + {rawCount > 0 ? ` · ${rawCount} raw` : ''} + + +
+ )} + + {rawCount > 0 && !cloud && ( +
+ + {rawCount} raw file{rawCount === 1 ? '' : 's'} cannot be read by the browser. + {' '} + They are decoded by the team server, so sign in before importing — or import them later + from the library. + +
+ )} + + {rawCount > 0 && cloud && ( +
+ Raw files are demosaiced by the server (LibRaw), a few at a time in parallel. Each file + usually takes 2–4 seconds. +
+ )} + + {progress && ( +
+
+
+
+
+ {progress.done} / {progress.total} {progress.current ? `· ${progress.current}` : ''} +
+
+ )} + + {failures.length > 0 && ( +
+ Some files could not be imported +
    + {failures.map((f) => ( +
  • {f}
  • + ))} +
+
+ )} +
+ +
+ + +
+
+
+ ); +} diff --git a/lumenroom/src/components/LibraryGrid.tsx b/lumenroom/src/components/LibraryGrid.tsx new file mode 100644 index 0000000..5bcb6ab --- /dev/null +++ b/lumenroom/src/components/LibraryGrid.tsx @@ -0,0 +1,358 @@ +import { useRef, useState } from 'react'; +import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits'; +import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag'; +import type { ColorLabel, Flag, PhotoRecord } from '../types'; +import Stars, { ColorSwatches, FlagButtons } from './Stars'; + +interface Props { + photos: PhotoRecord[]; + totalCount: number; + selected: string[]; + onSelect: (id: string, e: React.MouseEvent) => void; + onContextMenu: (e: React.MouseEvent, id: string) => void; + onOpen: (id: string) => void; + onRate: (id: string, rating: number) => void; + onBulkRate: (rating: number) => void; + onBulkFlag: (flag: Flag) => void; + onBulkColor: (color: ColorLabel) => void; + onDelete: () => void; + onExport: () => void; + onImport: () => void; + onDropFiles: (files: File[]) => void; + onClearSelection: () => void; + onReorder: (ids: string[], targetId: string | null) => void; + /** rubber-band selection: the complete new selection */ + onMarqueeSelect: (ids: string[]) => void; +} + +function fmtSize(bytes: number) { + if (bytes > 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + return `${Math.max(1, Math.round(bytes / 1024))} KB`; +} + +export default function LibraryGrid({ + photos, + totalCount, + selected, + onSelect, + onContextMenu, + onOpen, + onRate, + onBulkRate, + onBulkFlag, + onBulkColor, + onDelete, + onExport, + onImport, + onDropFiles, + onClearSelection, + onReorder, + onMarqueeSelect, +}: Props) { + const gridRef = useRef(null); + const band = useRef<{ sx: number; sy: number; base: string[]; moved: boolean; box: DOMRect } | null>(null); + const [bandRect, setBandRect] = useState<{ x: number; y: number; w: number; h: number } | null>(null); + const selectedSet = new Set(selected); + const someSelected = selected.length > 0; + const sharedRating = (() => { + if (!someSelected) return 0; + const rated = photos.filter((p) => selectedSet.has(p.id)); + if (!rated.length) return 0; + const first = rated[0].rating; + return rated.every((p) => p.rating === first) ? first : 0; + })(); + + if (!photos.length) { + return ( +
e.preventDefault()} + onDrop={(e) => { + e.preventDefault(); + const ids = draggedPhotoIds(); + if (ids.length) { onReorder(ids, null); + endDrag(); + return; + } + onDropFiles(Array.from(e.dataTransfer.files)); + }} + ref={gridRef} + onPointerDown={(e) => { + const grid = gridRef.current; + // A band starts on empty grid space; cards keep their own click/drag. + if (!grid || e.button !== 0 || e.target !== grid) return; + e.preventDefault(); + const box = grid.getBoundingClientRect(); + band.current = { + sx: e.clientX, + sy: e.clientY, + base: e.shiftKey || e.metaKey || e.ctrlKey ? [...selected] : [], + moved: false, + box, + }; + setBandRect({ x: e.clientX - box.left + grid.scrollLeft, y: e.clientY - box.top + grid.scrollTop, w: 0, h: 0 }); + grid.setPointerCapture(e.pointerId); + }} + onPointerMove={(e) => { + const grid = gridRef.current; + const start = band.current; + if (!grid || !start) return; + const left = Math.min(start.sx, e.clientX); + const top = Math.min(start.sy, e.clientY); + const right = Math.max(start.sx, e.clientX); + const bottom = Math.max(start.sy, e.clientY); + if (Math.abs(e.clientX - start.sx) > 3 || Math.abs(e.clientY - start.sy) > 3) start.moved = true; + setBandRect({ + x: left - start.box.left + grid.scrollLeft, + y: top - start.box.top + grid.scrollTop, + w: right - left, + h: bottom - top, + }); + if (!start.moved) return; + const hits: string[] = []; + for (const el of grid.querySelectorAll('.card')) { + const r = el.getBoundingClientRect(); + if (r.right > left && r.left < right && r.bottom > top && r.top < bottom) { + const id = el.dataset.id; + if (id) hits.push(id); + } + } + onMarqueeSelect([...start.base, ...hits.filter((id) => !start.base.includes(id))]); + }} + onPointerUp={(e) => { + const grid = gridRef.current; + const start = band.current; + band.current = null; + setBandRect(null); + if (!grid || !start) return; + if (grid.hasPointerCapture(e.pointerId)) grid.releasePointerCapture(e.pointerId); + if (!start.moved && !start.base.length) onClearSelection(); + }} + onPointerCancel={() => { + band.current = null; + setBandRect(null); + }} + > +
+ {totalCount > 0 ? ( + <> +

No photos match these filters

+

Loosen the rating, flag or label filters to see more of this event.

+ + ) : ( + <> +

Your library is empty

+

+ Create an event and import a shoot. Photos are stored locally, or on your team server + when one is connected. +

+ +

+ Drop JPEG, PNG, TIFF or camera raw files anywhere in this area. +

+ + )} +
+
+ ); + } + + return ( +
+
+ {someSelected ? ( + <> + {selected.length} selected + + + +
+ + + + + ) : ( + <> + + Click to select · drag on empty space to marquee · double-click to edit · 1–5 to rate ·{' '} + ? for shortcuts + +
+ {photos.length} photos + + )}
+ +
{ + if (draggedPhotoIds().length) { + e.preventDefault(); + e.dataTransfer.dropEffect = 'move'; + } + }} + onDrop={(e) => { + e.preventDefault(); + const ids = draggedPhotoIds(); + if (ids.length) { onReorder(ids, null); + endDrag(); + return; + } + onDropFiles(Array.from(e.dataTransfer.files)); + }} + ref={gridRef} + onPointerDown={(e) => { + const grid = gridRef.current; + // A band starts on empty grid space; cards keep their own click/drag. + if (!grid || e.button !== 0 || e.target !== grid) return; + e.preventDefault(); + const box = grid.getBoundingClientRect(); + band.current = { + sx: e.clientX, + sy: e.clientY, + base: e.shiftKey || e.metaKey || e.ctrlKey ? [...selected] : [], + moved: false, + box, + }; + setBandRect({ x: e.clientX - box.left + grid.scrollLeft, y: e.clientY - box.top + grid.scrollTop, w: 0, h: 0 }); + grid.setPointerCapture(e.pointerId); + }} + onPointerMove={(e) => { + const grid = gridRef.current; + const start = band.current; + if (!grid || !start) return; + const left = Math.min(start.sx, e.clientX); + const top = Math.min(start.sy, e.clientY); + const right = Math.max(start.sx, e.clientX); + const bottom = Math.max(start.sy, e.clientY); + if (Math.abs(e.clientX - start.sx) > 3 || Math.abs(e.clientY - start.sy) > 3) start.moved = true; + setBandRect({ + x: left - start.box.left + grid.scrollLeft, + y: top - start.box.top + grid.scrollTop, + w: right - left, + h: bottom - top, + }); + if (!start.moved) return; + const hits: string[] = []; + for (const el of grid.querySelectorAll('.card')) { + const r = el.getBoundingClientRect(); + if (r.right > left && r.left < right && r.bottom > top && r.top < bottom) { + const id = el.dataset.id; + if (id) hits.push(id); + } + } + onMarqueeSelect([...start.base, ...hits.filter((id) => !start.base.includes(id))]); + }} + onPointerUp={(e) => { + const grid = gridRef.current; + const start = band.current; + band.current = null; + setBandRect(null); + if (!grid || !start) return; + if (grid.hasPointerCapture(e.pointerId)) grid.releasePointerCapture(e.pointerId); + if (!start.moved && !start.base.length) onClearSelection(); + }} + onPointerCancel={() => { + band.current = null; + setBandRect(null); + }} + > + {bandRect && ( +
+ )} + {photos.map((p) => { + const color = COLOR_LABELS.find((c) => c.value === p.color); + const isDragging = draggedPhotoIds().includes(p.id); + return (
onSelect(p.id, e)} + onContextMenu={(e) => onContextMenu(e, p.id)} + onDoubleClick={() => onOpen(p.id)} + draggable + onDragStart={(e) => { + const ids = selectedSet.has(p.id) && selected.length > 1 ? selected : [p.id]; + startPhotoDrag(ids); + e.dataTransfer.effectAllowed = 'move'; + e.dataTransfer.setData(PHOTO_DRAG, ids.join(',')); + e.dataTransfer.setData('text/plain', ids.join(',')); + e.currentTarget.classList.add('dragging'); + }} + onDragEnd={(e) => { + e.currentTarget.classList.remove('dragging'); + endDrag(); + }} + onDragOver={(e) => { + if (!draggedPhotoIds().length) return; + e.preventDefault(); + e.stopPropagation(); + e.dataTransfer.dropEffect = 'move'; + e.currentTarget.classList.add('drop-target'); + }} + onDragLeave={(e) => e.currentTarget.classList.remove('drop-target')} + onDrop={(e) => { + const ids = draggedPhotoIds(); + e.currentTarget.classList.remove('drop-target'); + if (!ids.length) return; + e.preventDefault(); + e.stopPropagation(); + onReorder(ids, p.id); + endDrag(); + }} + > +
+ {p.name} +
+ {p.flag === 'pick' && ✓} + {p.flag === 'reject' && ✕} + {p.raw && ( + + RAW + + )} + {isEdited(p.edits) && ( + + ✎ + + )} +
+ {color && } +
+ {fmtSize(p.size)} + + {p.width}×{p.height} + +
+
+
+
+ {p.name} +
+
+ onRate(p.id, n)} /> + {p.meta.camera && {p.meta.camera}} +
+
+
+ ); + })} +
+
+ ); +} diff --git a/lumenroom/src/components/Panels.tsx b/lumenroom/src/components/Panels.tsx new file mode 100644 index 0000000..0eb0c88 --- /dev/null +++ b/lumenroom/src/components/Panels.tsx @@ -0,0 +1,700 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, thumbTransform } from '../lib/edits'; +import { computeAutoEdits } from '../lib/auto'; +import { clamp } from '../lib/curves'; +import type { CurveChannel, Edits, EventRecord, HistoryEntry, PhotoRecord, Preset } from '../types'; +import CurveEditor from './CurveEditor'; +import { getBitmap } from '../lib/images'; +import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer'; +import { applyFilmVariant, FILM_VARIANTS, type FilmVariant } from '../lib/presets'; +import { usePresetThumbs } from './PresetThumbs'; +import Slider from './Slider'; + +export function Panel({ + title, + children, + defaultOpen = true, + right, +}: { + title: string; + children: React.ReactNode; + defaultOpen?: boolean; + right?: React.ReactNode; +}) { + const [open, setOpen] = useState(defaultOpen); + return ( +
+
+ + {right} +
+ {open &&
{children}
} +
+ ); +} + +export interface PanelSetProps { + edits: Edits; + photo: PhotoRecord; + set: (patch: Partial, label: string) => void; +} + +const HUE_TRACK = 'linear-gradient(90deg,#ff4d4d,#ffd24d,#6dff6d,#4dfff0,#4d8bff,#c44dff,#ff4dd2,#ff4d4d)'; + +export function BasicPanel({ edits, photo, set }: PanelSetProps) { + const [autoBusy, setAutoBusy] = useState(false); + + const auto = async () => { + setAutoBusy(true); + try { + const partial = await computeAutoEdits(photo.thumb); + set(partial, 'Auto tone'); + } finally { + setAutoBusy(false); + } + }; + + return ( + +
+ White balance + +
+ set({ temp: v }, 'Temperature')} + track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)" + /> + set({ tint: v }, 'Tint')} + track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)" + /> + +
+ Tone + +
+ set({ exposure: v }, 'Exposure')} + format={(v) => v.toFixed(2)} + /> + set({ contrast: v }, 'Contrast')} /> + set({ highlights: v }, 'Highlights')} /> + set({ shadows: v }, 'Shadows')} /> + set({ whites: v }, 'Whites')} /> + set({ blacks: v }, 'Blacks')} /> + +
+ Presence +
+ set({ texture: v }, 'Texture')} /> + set({ clarity: v }, 'Clarity')} /> + set({ dehaze: v }, 'Dehaze')} /> + set({ vibrance: v }, 'Vibrance')} /> + set({ saturation: v }, 'Saturation')} /> + + + {edits.bw && ( + <> +
+ B&W filter +
+
+ {BW_FILTERS.map((f) => ( + + ))} +
+ {edits.bwFilter !== 'none' && ( + set({ bwFilterAmount: v }, 'B&W filter strength')} + /> + )} +
+ A filter darkens the colors it absorbs: red drops blue skies, green lifts foliage. The color mixer + below tunes individual hues on top. +
+ + )} +
+ ); +} + +const CURVE_COLORS: Record = { + rgb: '#e9e9ec', + red: '#e06a6a', + green: '#6ecf7d', + blue: '#6f9de8', +}; + +export function CurvePanel({ edits, set }: PanelSetProps) { + const [channel, setChannel] = useState('rgb'); + const points = edits.curve[channel]; + const update = (next: typeof points) => set({ curve: { ...edits.curve, [channel]: next } }, `Curve ${channel.toUpperCase()}`); + + return ( + update(identityCurve())}> + Reset + + } + > +
+ {(['rgb', 'red', 'green', 'blue'] as CurveChannel[]).map((c) => ( + + ))} +
+ +
+ ); +} + +export function HslPanel({ edits, set }: PanelSetProps) { + const [band, setBand] = useState(0); + const active = HUE_BANDS[band]; + + const setBandValue = (kind: 'hue' | 'sat' | 'lum', value: number) => { + const arr = [...edits.hsl[kind]]; + arr[band] = value; + const label = kind === 'hue' ? 'Hue' : kind === 'sat' ? 'Saturation' : 'Luminance'; + set({ hsl: { ...edits.hsl, [kind]: arr } }, `${label} · ${active.name}`); + }; + + return ( + + set( + { hsl: { hue: HUE_BANDS.map(() => 0), sat: HUE_BANDS.map(() => 0), lum: HUE_BANDS.map(() => 0) } }, + 'Reset color mixer', + ) + } + > + Reset + + } + > +
+ {HUE_BANDS.map((b, i) => ( +
+
{active.name}
+ setBandValue('hue', v)} track={HUE_TRACK} /> + setBandValue('sat', v)} /> + setBandValue('lum', v)} /> +
Shift, saturate or brighten one color range without touching the rest.
+
+ ); +} + +export function ColorGradingPanel({ edits, set }: PanelSetProps) { + return ( + +
+ Shadows + +
+ set({ grading: { ...edits.grading, shadows: { ...edits.grading.shadows, h: v } } }, 'Grading shadows hue')} + track={HUE_TRACK} + /> + set({ grading: { ...edits.grading, shadows: { ...edits.grading.shadows, s: v } } }, 'Grading shadows')} + /> +
+ Highlights + +
+ + set({ grading: { ...edits.grading, highlights: { ...edits.grading.highlights, h: v } } }, 'Grading highlights hue') + } + track={HUE_TRACK} + /> + set({ grading: { ...edits.grading, highlights: { ...edits.grading.highlights, s: v } } }, 'Grading highlights')} + /> + set({ grading: { ...edits.grading, balance: v } }, 'Grading balance')} + /> +
+ ); +} + +/** + * 1:1 loupe of the grain. A small window of the real crop is rendered at actual + * pixels, which is the only way to judge a resolution independent grain size + * without exporting: this is what the file looks like at 100%. + */ +function GrainPatch({ + photo, + edits, + freezeGrain, +}: { + photo: PhotoRecord; + edits: Edits; + freezeGrain?: boolean; +}) { + const ref = useRef(null); + const renderer = useRef(null); + const bitmap = useRef(null); + const [ready, setReady] = useState(false); + + useEffect(() => { + let alive = true; + getBitmap(photo) + .then((bmp) => { + if (!alive) return; + bitmap.current = bmp; + setReady(true); + }) + .catch(() => undefined); + return () => { + alive = false; + }; + }, [photo.id]); + + useEffect( + () => () => { + renderer.current?.dispose(); + renderer.current = null; + }, + [], + ); + + useEffect(() => { + const canvas = ref.current; + const bmp = bitmap.current; + if (!canvas || !bmp) return; + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const frame = rotatedBounds(bmp.width, bmp.height, edits.crop.angle, edits.crop.quarter); + // The patch takes the shape of the framed area, so it reads as a window onto + // the crop rather than a generic swatch. + const cropPxW = Math.max(1, frame.w * edits.crop.w); + const cropPxH = Math.max(1, frame.h * edits.crop.h); + const cssW = 148; + const cssH = Math.round(Math.min(148, Math.max(64, cssW * (cropPxH / cropPxW)))); + const W = Math.max(1, Math.round(cssW * dpr)); + const H = Math.max(1, Math.round(cssH * dpr)); + canvas.style.width = `${cssW}px`; + canvas.style.height = `${cssH}px`; + if (canvas.width !== W) canvas.width = W; + if (canvas.height !== H) canvas.height = H; + try { + if (!renderer.current) renderer.current = new Renderer(canvas); + const r = renderer.current; + r.setImage(bmp); + // One source pixel per device pixel, centred on whatever the crop frames: + // drag the crop rectangle and the patch samples that part of the photo. + const view = grainSampleWindow(frame, edits.crop, W, H); + r.render(edits, { width: W, height: H, view, freezeGrain }); + } catch { + // Keep the last good frame rather than blanking the patch. + } + }, [photo.id, ready, edits, freezeGrain]); + + return ( +
+ + Grain at 100% · inside the crop +
+ ); +} + +export function EffectsPanel({ edits, photo, set, grainFreeze }: PanelSetProps & { grainFreeze?: boolean }) { + return ( + +
+ Vignette +
+ set({ vignette: { ...edits.vignette, amount: v } }, 'Vignette amount')} + /> + set({ vignette: { ...edits.vignette, midpoint: v } }, 'Vignette midpoint')} + /> + set({ vignette: { ...edits.vignette, feather: v } }, 'Vignette feather')} + /> +
+ Grain +
+ set({ grain: { ...edits.grain, amount: v } }, 'Grain amount')} + /> + set({ grain: { ...edits.grain, size: v } }, 'Grain size')} + /> + set({ grain: { ...edits.grain, roughness: v } }, 'Grain roughness')} + /> + +
+ ); +} + +export function DetailPanel({ edits, set }: PanelSetProps) { + return ( + +
+ Sharpening +
+ set({ sharpen: { ...edits.sharpen, amount: v } }, 'Sharpen amount')} + /> + set({ sharpen: { ...edits.sharpen, radius: v } }, 'Sharpen radius')} + format={(v) => v.toFixed(1)} + def={1} + /> + set({ sharpen: { ...edits.sharpen, detail: v } }, 'Sharpen detail')} + /> +
+ Noise reduction +
+ set({ noise: { ...edits.noise, luminance: v } }, 'Noise reduction')} + /> + set({ noise: { ...edits.noise, detail: v } }, 'Noise detail')} + /> +
+ ); +} + +const BRAND_PREFIX = /^(Kodak|Fujifilm|Ilford|Agfa|CineStill|Lomography) /; + +export function PresetsPanel({ + presets, + photo, + onApply, + onSave, +}: { + presets: Preset[]; + photo: PhotoRecord; + onApply: (preset: Preset) => void; + onSave: (name: string) => void; +}) { + const [variant, setVariant] = useState('base'); + // Variants are derived on the fly, so every stock gets push/pull and split + // grade versions without tripling the catalogue. + const shown = useMemo(() => presets.map((p) => applyFilmVariant(p, variant)), [presets, variant]); + + const groups = new Map(); + for (const preset of shown) { + const arr = groups.get(preset.group) ?? []; + arr.push(preset); + groups.set(preset.group, arr); + } + const thumbs = usePresetThumbs(photo, shown); + + return ( +
+
+ Presets + +
+
+ {FILM_VARIANTS.map((v) => ( + + ))} +
+ {[...groups.entries()].map(([group, items]) => ( +
+
{group}
+
+ {items.map((preset) => { + const src = thumbs[preset.id]; + return ( + + ); + })} +
+
+ ))} +
+ ); +} + +export function HistoryPanel({ history, onRestore }: { history: HistoryEntry[]; onRestore: (edits: Edits) => void }) { + return ( +
+
+ History + {history.length} +
+
+ {[...history].reverse().map((entry, i) => ( + + ))} +
+
+ ); +} + +export function CropPanel({ + edits, + set, + onAspect, + onRotate, + onFlipPreview, + mirrored, +}: { + edits: Edits; + set: PanelSetProps['set']; + frame: { w: number; h: number }; + onAspect: (id: string) => void; + onRotate: (dir: -1 | 1) => void; + onFlipPreview?: () => void; + mirrored?: boolean; +}) { + const crop = edits.crop; + return ( + +
+ + + {onFlipPreview && ( + + )} +
+
+ {ASPECTS.map((a) => ( + + ))} +
+ set({ crop: { ...crop, angle: v } }, 'Straighten')} + format={(v) => `${v.toFixed(1)}°`} + /> +
+ + + +
+
+ ); +} + +export function NavigatorPanel({ photo }: { photo: PhotoRecord }) { + return ( +
+
+ Navigator + Fit +
+
+ {photo.name} +
+
+ {photo.name} +
+
+ {photo.raw ? (photo.decode === 'embedded' ? 'Raw · camera preview' : 'Raw · demosaiced') : 'JPEG/PNG'}{' '} + · {photo.width}×{photo.height} +
+
+ ); +} + +export function MetadataPanel({ photo, events }: { photo: PhotoRecord; events: EventRecord[] }) { + const event = events.find((e) => e.id === photo.eventId); + const rows: [string, string][] = [ + ['File', photo.name], + ['Dimensions', `${photo.width} × ${photo.height}`], + ['Size', `${(photo.size / (1024 * 1024)).toFixed(2)} MB`], + ['Camera', photo.meta.camera ?? '—'], + ['Lens', photo.meta.lens ?? '—'], + ['ISO', photo.meta.iso ? String(photo.meta.iso) : '—'], + ['Aperture', photo.meta.aperture ? `f/${photo.meta.aperture}` : '—'], + ['Shutter', photo.meta.shutter ?? '—'], + ['Focal', photo.meta.focal ? `${photo.meta.focal} mm` : '—'], + ['Captured', photo.takenAt ? new Date(photo.takenAt).toLocaleString() : '—'], + ['Imported', new Date(photo.addedAt).toLocaleDateString()], + ['Event', event?.name ?? 'Unsorted'], + ]; + return ( + +
+ {rows.map(([key, value]) => ( +
+
{key}
+
{value}
+
+ ))} +
+
+ ); +} diff --git a/lumenroom/src/components/PresetThumbs.tsx b/lumenroom/src/components/PresetThumbs.tsx new file mode 100644 index 0000000..a0b19ce --- /dev/null +++ b/lumenroom/src/components/PresetThumbs.tsx @@ -0,0 +1,91 @@ +import { useEffect, useState } from 'react'; +import { normalizeEdits } from '../lib/edits'; +import { getBitmap } from '../lib/images'; +import { Renderer, rotatedBounds } from '../gl/renderer'; +import type { PhotoRecord, Preset } from '../types'; + +/** + * Preset thumbnails are rendered once per photo/preset pair and cached as small + * JPEG data URLs. One shared Renderer does all of them: a WebGL context per tile + * would exhaust the browser's context limit long before 70 presets. + */ +const cache = new Map(); +const CACHE_LIMIT = 900; +const THUMB_EDGE = 200; + +/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */ +const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`; + +export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record { + const [thumbs, setThumbs] = useState>({}); + // Preset edits never change after creation, so a stable id list is enough to + // avoid re-running for every parent render. + const presetKey = presets.map((p) => p.id).join('|'); + const crop = photo.edits.crop; + const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(','); + + useEffect(() => { + let alive = true; + let renderer: Renderer | null = null; + const canvas = document.createElement('canvas'); + + const known: Record = {}; + for (const preset of presets) { + const hit = cache.get(keyOf(photo.id, preset.id, cropKey)); + if (hit) known[preset.id] = hit; + } + setThumbs(known); + + const pending = presets.filter((p) => !known[p.id]); + if (!pending.length) return; + + (async () => { + try { + const bitmap = await getBitmap(photo); + if (!alive) return; + renderer = new Renderer(canvas); + // Every tile shows the photo as it is framed now, so a turned photo's + // presets are turned too. + const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter); + const cropW = Math.max(1, frame.w * crop.w); + const cropH = Math.max(1, frame.h * crop.h); + const scale = THUMB_EDGE / Math.max(cropW, cropH); + const width = Math.max(1, Math.round(cropW * scale)); + const height = Math.max(1, Math.round(cropH * scale)); + renderer.setImage(bitmap); + + for (const preset of pending) { + if (!alive) break; + try { + renderer.render({ ...normalizeEdits(preset.edits), crop }, { + width, + height, + upscale: Math.max(width / cropW, height / cropH) > 1.05, + }); + const url = canvas.toDataURL('image/jpeg', 0.72); + cache.set(keyOf(photo.id, preset.id, cropKey), url); + setThumbs((prev) => ({ ...prev, [preset.id]: url })); + } catch { + // One bad preset must not stop the rest of the grid. + } + // Yield between tiles so the panel fills in progressively. + await new Promise((resolve) => setTimeout(resolve, 0)); + } + + if (cache.size > CACHE_LIMIT) { + for (const key of [...cache.keys()].slice(0, cache.size - CACHE_LIMIT)) cache.delete(key); + } + } catch { + // No bitmap yet (raw not synced) or no WebGL: tiles keep their placeholders. + } + })(); + + return () => { + alive = false; + renderer?.dispose(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [photo.id, presetKey, cropKey]); + + return thumbs; +} diff --git a/lumenroom/src/components/Shortcuts.tsx b/lumenroom/src/components/Shortcuts.tsx new file mode 100644 index 0000000..1504ad3 --- /dev/null +++ b/lumenroom/src/components/Shortcuts.tsx @@ -0,0 +1,85 @@ +import { useEffect } from 'react'; + +const GROUPS: { title: string; rows: [string, string][] }[] = [ + { + title: 'Everywhere', + rows: [ + ['?', 'Show or hide this list'], + ['⌘ / Ctrl + I', 'Import photos'], + ['⌘ / Ctrl + E', 'Export'], + ['Esc', 'Close a dialog'], + ], + }, + { + title: 'Library', + rows: [ + ['G', 'Library grid'], + ['E', 'Open in Develop'], + ['← → ↑ ↓', 'Move the selection'], + ['Shift + arrows', 'Extend the selection'], + ['⌘ / Ctrl + A', 'Select all shown'], + ['1 – 5', 'Star rating'], + ['0', 'Clear rating'], + ['6 – 9', 'Red, yellow, green, blue label'], + ['P / X / U', 'Pick · reject · unflag'], + ['Delete', 'Remove selected photos'], + ['⌘ / Ctrl + C / V', 'Copy · paste develop settings'], + ['Drag on empty space', 'Rubber-band select'], + ], + }, + { + title: 'Develop', + rows: [ + ['Z', 'Fit · 100%'], + ['C', 'Crop & straighten'], + ['Enter', 'Apply the crop'], + ['\\ (hold)', 'Before / after'], + ['← →', 'Previous · next photo'], + ['Scroll · drag', 'Zoom · pan'], + ['⌘ / Ctrl + Z', 'Undo'], + ['⌘ / Ctrl + C / V', 'Copy · paste settings'], + ['Esc', 'Back to library'], + ], + }, +]; + +export default function Shortcuts({ onClose }: { onClose: () => void }) { + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') { + e.preventDefault(); + // Keep Escape from also closing the photo or crop behind the sheet. + e.stopImmediatePropagation(); + onClose(); + } + }; + window.addEventListener('keydown', onKey, true); + return () => window.removeEventListener('keydown', onKey, true); + }, [onClose]); + + return ( +
e.target === e.currentTarget && onClose()}> +
+
+

Keyboard shortcuts

+ +
+
+ {GROUPS.map((group) => ( +
+

{group.title}

+ {group.rows.map(([keys, what]) => ( +
+ {keys} + {what} +
+ ))} +
+ ))} +
+
+
+ ); +} diff --git a/lumenroom/src/components/Slider.tsx b/lumenroom/src/components/Slider.tsx new file mode 100644 index 0000000..3fe7afc --- /dev/null +++ b/lumenroom/src/components/Slider.tsx @@ -0,0 +1,84 @@ +import { useEffect, useState } from 'react'; + +export interface SliderProps { + label: string; + value: number; + min?: number; + max?: number; + step?: number; + def?: number; + onChange: (value: number) => void; + format?: (value: number) => string; + track?: string; + disabled?: boolean; +} + +function NumberField({ value, onChange, format }: { value: number; onChange: (v: number) => void; format?: (v: number) => string }) { + const [focused, setFocused] = useState(false); + const [text, setText] = useState(''); + const display = focused ? text : format ? format(value) : String(Math.round(value)); + + useEffect(() => { + if (!focused) setText(format ? format(value) : String(Math.round(value))); + }, [value, focused, format]); + + return ( + { + setText(String(Math.round(value * 100) / 100)); + setFocused(true); + }} + onBlur={() => setFocused(false)} + onChange={(e) => { + setText(e.target.value); + const v = parseFloat(e.target.value); + if (Number.isFinite(v)) onChange(v); + }} + onKeyDown={(e) => { + if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); + }} + /> + ); +} + +export default function Slider({ + label, + value, + min = -100, + max = 100, + step = 1, + def = 0, + onChange, + format, + track, + disabled, +}: SliderProps) { + const pct = max === min ? 0 : ((value - min) / (max - min)) * 100; + return ( +
+ !disabled && onChange(def)} + > + {label} + + onChange(parseFloat(e.target.value))} + onDoubleClick={() => onChange(def)} + /> + +
+ ); +} diff --git a/lumenroom/src/components/Stars.tsx b/lumenroom/src/components/Stars.tsx new file mode 100644 index 0000000..bbda1fc --- /dev/null +++ b/lumenroom/src/components/Stars.tsx @@ -0,0 +1,75 @@ +import type { ColorLabel, Flag } from '../types'; + +interface Props { + value: number; + onChange?: (rating: number) => void; + size?: 'sm' | 'md' | 'lg'; + title?: string; +} + +export default function Stars({ value, onChange, size = 'sm', title }: Props) { + return ( +
+ {[1, 2, 3, 4, 5].map((n) => ( + + ))} +
+ ); +} + +export function FlagButtons({ value, onChange }: { value: Flag; onChange: (flag: Flag) => void }) { + return ( +
+ + +
+ ); +} + +export function ColorSwatches({ value, onChange }: { value: ColorLabel; onChange: (color: ColorLabel) => void }) { + return ( +
+ {( + [ + { c: 'red' as ColorLabel, hex: '#e05252' }, + { c: 'yellow' as ColorLabel, hex: '#e0c04a' }, + { c: 'green' as ColorLabel, hex: '#56b268' }, + { c: 'blue' as ColorLabel, hex: '#4f86e0' }, + { c: 'purple' as ColorLabel, hex: '#9b6ede' }, + ] as const + ).map(({ c, hex }) => ( +
+ ); +} diff --git a/lumenroom/src/components/TopBar.tsx b/lumenroom/src/components/TopBar.tsx new file mode 100644 index 0000000..8ebdb4c --- /dev/null +++ b/lumenroom/src/components/TopBar.tsx @@ -0,0 +1,81 @@ +import type { ViewMode } from '../types'; + +interface Props { + view: ViewMode; + eventName: string; + photoCount: number; + selectedCount: number; + cloudLabel: string; + cloudOn: boolean; + onViewChange: (view: ViewMode) => void; + onImport: () => void; + onExport: () => void; + onCloud: () => void; + onHelp: () => void; +} + +export default function TopBar({ + view, + eventName, + photoCount, + selectedCount, + cloudLabel, + cloudOn, + onViewChange, + onImport, + onExport, + onCloud, + onHelp, +}: Props) { + return ( +
+
+ + Lumenroom +
+ +
+ {eventName} + + {' '} + · {photoCount} photo{photoCount === 1 ? '' : 's'} + {selectedCount > 1 ? ` · ${selectedCount} selected` : ''} + +
+ + + +
+ + + + + Guide + + +
+
+ ); +} diff --git a/lumenroom/src/gl/renderer.ts b/lumenroom/src/gl/renderer.ts new file mode 100644 index 0000000..c356da9 --- /dev/null +++ b/lumenroom/src/gl/renderer.ts @@ -0,0 +1,970 @@ +import type { Edits } from '../types'; +import { buildSampler, clamp01 } from '../lib/curves'; +import { bwFilterRgb } from '../lib/edits'; + +const VERT = `#version 300 es +layout(location = 0) in vec2 a_pos; +out vec2 v_uv; +void main(){ + v_uv = a_pos * 0.5 + 0.5; + gl_Position = vec4(a_pos, 0.0, 1.0); +}`; + +const GRADE_FRAG = `#version 300 es +precision highp float; +in vec2 v_uv; +out vec4 outColor; + +uniform sampler2D u_src; +uniform sampler2D u_curve; +uniform vec2 u_srcSize; +uniform vec2 u_frameSize; +uniform vec4 u_crop; +uniform vec4 u_valid; +uniform float u_angle; +uniform int u_quarter; +uniform vec2 u_flip; +uniform float u_upscale; + +uniform float u_temp; +uniform float u_tint; +uniform float u_exposure; +uniform float u_contrast; +uniform float u_highlights; +uniform float u_shadows; +uniform float u_whites; +uniform float u_blacks; +uniform float u_vibrance; +uniform float u_saturation; +uniform float u_bw; +uniform vec3 u_bwFilter; +uniform float u_bwFilterAmt; +uniform float u_hue[8]; +uniform float u_sat[8]; +uniform float u_lum[8]; +uniform float u_gSh; +uniform float u_gSs; +uniform float u_gHi; +uniform float u_gHs; +uniform float u_gBal; + +const float HUE_CENTERS[8] = float[8](0.0, 32.0, 62.0, 120.0, 180.0, 230.0, 280.0, 320.0); + +float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); } + +vec3 toLinear(vec3 c){ + c = max(c, vec3(0.0)); + return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c)); +} + +vec3 toSRGB(vec3 c){ + c = max(c, vec3(0.0)); + return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); +} + +vec3 rgb2hsv(vec3 c){ + vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +vec3 hsv2rgb(vec3 c){ + vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); +} + +// Catmull-Rom weights for one axis; t is the fraction inside a texel. +vec4 cubicWeights(float t){ + float t2 = t * t; + float t3 = t2 * t; + return vec4( + -0.5 * t3 + t2 - 0.5 * t, + 1.5 * t3 - 2.5 * t2 + 1.0, + -1.5 * t3 + 2.0 * t2 + 0.5 * t, + 0.5 * t3 - 0.5 * t2 + ); +} + +// Bicubic magnification. Bilinear leaves texel-sized squares with hard edges +// once a photo is zoomed past 1:1, which reads as blocky rather than soft. +vec3 sampleBicubic(sampler2D tex, vec2 uv, vec2 size){ + vec2 coord = uv * size - 0.5; + vec2 base = floor(coord); + vec2 f = coord - base; + vec4 wx = cubicWeights(f.x); + vec4 wy = cubicWeights(f.y); + float ax[4] = float[4](wx.x, wx.y, wx.z, wx.w); + float ay[4] = float[4](wy.x, wy.y, wy.z, wy.w); + vec3 sum = vec3(0.0); + for (int j = 0; j < 4; j++){ + for (int i = 0; i < 4; i++){ + vec2 p = (base + vec2(float(i) - 1.0, float(j) - 1.0) + 0.5) / size; + sum += texture(tex, clamp(p, vec2(0.0), vec2(1.0))).rgb * ax[i] * ay[j]; + } + } + return sum; +} + +void main(){ + vec2 frame = mix(u_crop.xy, u_crop.xy + u_crop.zw, vec2(v_uv.x, 1.0 - v_uv.y)); + + // Only the cropped area carries picture data; the rest is letterbox when the + // view is zoomed out or the window aspect differs from the photo. + if (frame.x < u_valid.x || frame.y < u_valid.y || + frame.x > u_valid.x + u_valid.z || frame.y > u_valid.y + u_valid.w) { + outColor = vec4(0.035, 0.035, 0.04, 1.0); + return; + } + + vec2 p = (frame - 0.5) * u_frameSize; + float a = -(u_angle + float(u_quarter) * 1.57079632679); + float ca = cos(a); + float sa = sin(a); + vec2 rp = vec2(p.x * ca - p.y * sa, p.x * sa + p.y * ca); + vec2 s = rp / u_srcSize + 0.5; + s = (s - 0.5) * u_flip + 0.5; + + if (s.x < 0.0 || s.x > 1.0 || s.y < 0.0 || s.y > 1.0) { + outColor = vec4(0.035, 0.035, 0.04, 1.0); + return; + } + + // s is already in the texture's own top-down row order, so it is sampled as + // it stands: negating y here would mirror the photo top to bottom. + vec2 uv = s; + vec3 src = u_upscale > 0.5 + ? sampleBicubic(u_src, uv, u_srcSize) + : texture(u_src, uv).rgb; + vec3 col = toLinear(clamp(src, 0.0, 1.0)); + + // White balance (relative to as-shot) + float t = u_temp / 100.0; + float ti = u_tint / 100.0; + vec3 wb = vec3(1.0 + 0.30 * t + 0.06 * ti, 1.0 - 0.16 * ti, 1.0 - 0.26 * t + 0.06 * ti); + col *= wb / max(0.05, luma(wb)); + + // Exposure + col *= exp2(u_exposure); + + // Tonal range + float lm = clamp(luma(col), 0.0, 1.0); + col += (u_shadows / 100.0) * 0.45 * pow(1.0 - lm, 3.0); + col += (u_highlights / 100.0) * 0.50 * pow(lm, 2.0); + col += (u_whites / 100.0) * 0.34 * smoothstep(0.55, 1.0, lm); + col += (u_blacks / 100.0) * 0.13 * smoothstep(0.30, 0.0, lm); + + vec3 srgb = clamp(toSRGB(col), 0.0, 1.0); + + // Contrast + srgb = clamp((srgb - 0.5) * (1.0 + (u_contrast / 100.0) * 1.1) + 0.5, 0.0, 1.0); + + // Tone curve (composite baked with per-channel curves) + srgb = vec3( + texture(u_curve, vec2(clamp(srgb.r, 0.0, 1.0), 0.5)).r, + texture(u_curve, vec2(clamp(srgb.g, 0.0, 1.0), 0.5)).g, + texture(u_curve, vec2(clamp(srgb.b, 0.0, 1.0), 0.5)).b + ); + + // HSL bands + vec3 hsv = rgb2hsv(srgb); + float hdeg = hsv.x * 360.0; + float hueWeight = smoothstep(0.02, 0.18, hsv.y); + float hShift = 0.0; + float sShift = 0.0; + float lShift = 0.0; + float wsum = 0.0; + for (int i = 0; i < 8; i++) { + float d = abs(hdeg - HUE_CENTERS[i]); + d = min(d, 360.0 - d); + float w = smoothstep(52.0, 0.0, d); + hShift += w * u_hue[i]; + sShift += w * u_sat[i]; + lShift += w * u_lum[i]; + wsum += w; + } + float norm = max(wsum, 0.0001); + hShift = (hShift / norm) * hueWeight; + sShift = sShift / norm; + lShift = lShift / norm; + + hsv.x = fract(hsv.x + (hShift / 100.0) * 0.08 + 1.0); + float satMul = sShift >= 0.0 ? 1.0 + (sShift / 100.0) * 0.8 : 1.0 + sShift / 100.0; + hsv.y = clamp(hsv.y * satMul, 0.0, 1.0); + hsv.z = clamp(hsv.z * (1.0 + (lShift / 100.0) * 0.5), 0.0, 1.0); + srgb = hsv2rgb(hsv); + + if (u_bw > 0.5) { + // A colored filter over the lens changes which hues turn dark in the print: + // red drops blue skies, green lifts foliage, blue opens up shadows. The + // strength blends the transmission back towards a neutral filter. + vec3 bwTint = mix(vec3(1.0), u_bwFilter, clamp(u_bwFilterAmt, 0.0, 1.0)); + float wl = max(0.05, luma(bwTint)); + srgb = vec3(luma(srgb * bwTint) / wl); + } + + // Vibrance and saturation + vec3 satRgb = clamp(srgb, 0.0, 1.0); + float mx = max(max(satRgb.r, satRgb.g), satRgb.b); + float mn = min(min(satRgb.r, satRgb.g), satRgb.b); + float curSat = mx - mn; + float gray = luma(satRgb); + srgb = mix(vec3(gray), satRgb, clamp(1.0 + (u_vibrance / 100.0) * (1.0 - curSat) * 0.9, 0.0, 3.0)); + srgb = mix(vec3(luma(srgb)), srgb, clamp(1.0 + u_saturation / 100.0, 0.0, 3.0)); + + // Color grading + float gl = clamp(luma(srgb), 0.0, 1.0); + float bal = u_gBal / 100.0; + float sMask = pow(1.0 - gl, 2.0 + bal); + float hMask = pow(gl, 2.0 - bal); + vec3 shCol = hsv2rgb(vec3(u_gSh, 1.0, 1.0)); + shCol -= vec3(luma(shCol)); + vec3 hiCol = hsv2rgb(vec3(u_gHi, 1.0, 1.0)); + hiCol -= vec3(luma(hiCol)); + srgb += shCol * (u_gSs / 100.0) * 0.45 * sMask; + srgb += hiCol * (u_gHs / 100.0) * 0.45 * hMask; + + outColor = vec4(clamp(srgb, 0.0, 1.0), 1.0); +}`; + +const BLUR_FRAG = `#version 300 es +precision highp float; +in vec2 v_uv; +out vec4 outColor; +uniform sampler2D u_tex; +uniform vec2 u_dir; +void main(){ + vec3 s = texture(u_tex, v_uv).rgb * 0.2270270270; + s += texture(u_tex, v_uv + u_dir * 1.3846153846).rgb * 0.3162162162; + s += texture(u_tex, v_uv - u_dir * 1.3846153846).rgb * 0.3162162162; + s += texture(u_tex, v_uv + u_dir * 3.2307692308).rgb * 0.0702702703; + s += texture(u_tex, v_uv - u_dir * 3.2307692308).rgb * 0.0702702703; + outColor = vec4(s, 1.0); +}`; + +const FINISH_FRAG = `#version 300 es +precision highp float; +in vec2 v_uv; +out vec4 outColor; +uniform sampler2D u_graded; +uniform sampler2D u_blurSmall; +uniform sampler2D u_blurBig; +uniform float u_texture; +uniform float u_clarity; +uniform float u_dehaze; +uniform float u_sharpen; +uniform float u_nr; +uniform float u_vigAmt; +uniform float u_vigMid; +uniform float u_vigFeather; +uniform float u_grainAmt; +uniform float u_grainSize; +uniform float u_grainRough; +uniform vec4 u_crop; +uniform vec4 u_grainFrame; +uniform vec2 u_grainSpace; +uniform vec2 u_outSize; +uniform vec2 u_frameSize; +uniform vec2 u_grainFlip; +uniform float u_grainRot; +uniform float u_grainUnits; +uniform float u_aspect; + +float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); } +// Integer hash (Dave Hoskins). A sin-based hash correlates at whole-pixel +// lattice points, which is exactly what drew diagonal streaks through grain. +float hash(vec2 p){ + vec3 p3 = fract(vec3(p.xyx) * 0.1031); + p3 += dot(p3, p3.yzx + 33.33); + return fract((p3.x + p3.y) * p3.z); +} + +// Smooth value noise: interpolates between lattice samples instead of hashing +// whole blocks, so neighbouring pixels never sit at identical values. +float valueNoise(vec2 p){ + vec2 i = floor(p); + vec2 f = fract(p); + vec2 u = f * f * (3.0 - 2.0 * f); + return mix( + mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x), + mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), + u.y + ); +} + +void main(){ + vec3 c = texture(u_graded, v_uv).rgb; + vec3 bs = texture(u_blurSmall, v_uv).rgb; + vec3 bb = texture(u_blurBig, v_uv).rgb; + + // Noise reduction blends towards a smoothed version first. + float nr = clamp(u_nr / 100.0, 0.0, 1.0); + vec3 base = mix(c, mix(bs, bb, 0.5), nr * 0.6); + + // Local contrast / detail work on gamma encoded values. + vec3 detailSmall = c - bs; + vec3 detailBig = base - bb; + vec3 col = base; + col += detailSmall * ((u_texture / 100.0) * 0.9 + (u_sharpen / 100.0) * 1.35); + col += detailBig * (u_clarity / 100.0) * 1.25; + + // Dehaze + float d = u_dehaze / 100.0; + if (d > 0.0) { + float veil = luma(bb); + col = (col - d * 0.32 * veil * vec3(0.95, 0.98, 1.02)) / max(0.05, 1.0 - d * 0.28); + } else if (d < 0.0) { + col = mix(col, bb * 0.85 + vec3(0.09), -d * 0.55); + } + + // Vignette + float amt = u_vigAmt / 100.0; + if (abs(amt) > 0.001) { + vec2 q = (v_uv - 0.5) * vec2(u_aspect, 1.0); + float r = length(q) / max(0.05, length(vec2(u_aspect, 1.0) * 0.5)); + float mid = mix(0.18, 1.05, u_vigMid / 100.0); + float feather = mix(0.05, 1.0, u_vigFeather / 100.0); + float v = smoothstep(mid, mid + feather * 0.6, r); + float strength = abs(amt) * v; + if (amt < 0.0) col *= 1.0 - strength * 0.92; + else col = mix(col, vec3(1.0), strength * 0.6); + } + + // Grain: film-like noise laid down in image space. Measured in output pixels + // a 6000 px export came out four times finer than the 1500 px preview, so the + // pattern is generated from the frame instead and every octave is band limited: + // nothing here depends on how many pixels the target happens to have. + float ga = u_grainAmt / 100.0; + if (ga > 0.001) { + float cell = mix(1.0, 3.0, clamp((u_grainSize - 10.0) / 90.0, 0.0, 1.0)); + vec2 frameUv = mix(u_crop.xy, u_crop.xy + u_crop.zw, vec2(v_uv.x, 1.0 - v_uv.y)); + // Grain lives on the photo, not on the output frame: the coordinates go + // through the same rotation/quarter/flip the frame uses, so straightening + // and rotating carry the texture along with the pixels instead of shifting + // it underneath them. + vec2 p = (frameUv - 0.5) * u_frameSize; + float ca = cos(u_grainRot); + float sa = sin(u_grainRot); + vec2 rp = vec2(p.x * ca - p.y * sa, p.x * sa + p.y * ca) * u_grainFlip; + vec2 px = rp * u_grainUnits; + float pxPerUnit = length(u_outSize) / max(1.0, length(u_grainSpace * (u_crop.zw / u_grainFrame.zw))); + // Grain below a pixel cannot be drawn: it would either moire or read as a + // different, coarser pattern, so fade it out instead of rescaling it. + float vis = smoothstep(0.45, 1.0, cell * max(pxPerUnit, 1e-4)); + // Roughness adds a finer octave on top of the clumps: cream at 0, bite at 100. + float w = clamp(u_grainRough / 100.0, 0.0, 1.0) * 0.85; + float fineCell = max(cell * 0.45, 1.25 / max(pxPerUnit, 1e-4)); + float n = (valueNoise(px / cell) - 0.5) + + (valueNoise(px / fineCell + 11.7) - 0.5) * w; + n *= vis * inversesqrt(1.0 + w * w); + float mask = 1.0 - abs(clamp(luma(col), 0.0, 1.0) * 2.0 - 1.0); + col += n * ga * 0.20 * (0.6 + mask * 0.4); + } + + outColor = vec4(clamp(col, 0.0, 1.0), 1.0); +}`; + +export interface Histogram { + r: Uint32Array; + g: Uint32Array; + b: Uint32Array; + l: Uint32Array; +} + +interface Target { + tex: WebGLTexture; + fbo: WebGLFramebuffer; + w: number; + h: number; +} + +function makeHistogram(): Histogram { + return { + r: new Uint32Array(256), + g: new Uint32Array(256), + b: new Uint32Array(256), + l: new Uint32Array(256), + }; +} + +export function rotatedBounds(imgW: number, imgH: number, angleDeg: number, quarter = 0) { + const swap = (((Math.round(quarter) % 4) + 4) % 4) % 2 === 1; + const w0 = swap ? imgH : imgW; + const h0 = swap ? imgW : imgH; + const a = (angleDeg * Math.PI) / 180; + const c = Math.abs(Math.cos(a)); + const s = Math.abs(Math.sin(a)); + return { + w: Math.max(1, w0 * c + h0 * s), + h: Math.max(1, w0 * s + h0 * c), + }; +} + +export function outputSize(edits: Edits, imgW: number, imgH: number) { + const frame = rotatedBounds(imgW, imgH, edits.crop.angle, edits.crop.quarter); + return { + w: Math.max(1, Math.round(frame.w * edits.crop.w)), + h: Math.max(1, Math.round(frame.h * edits.crop.h)), + }; +} + +/** + * Frame-uv window for a loupe that tracks the crop: a `pxW` x `pxH` source-pixel + * window (pass the export's span for output-size patches), centred on the crop or + * on an explicit point, and clamped so it never samples outside the crop. + */ +export function grainSampleWindow( + frame: { w: number; h: number }, + crop: { x: number; y: number; w: number; h: number }, + pxW: number, + pxH: number, + point?: { x: number; y: number } | null, +) { + const w = Math.min(crop.w, pxW / Math.max(1, frame.w)); + const h = Math.min(crop.h, pxH / Math.max(1, frame.h)); + const cx = point ? Math.min(Math.max(point.x, crop.x), crop.x + crop.w) : crop.x + crop.w / 2; + const cy = point ? Math.min(Math.max(point.y, crop.y), crop.y + crop.h) : crop.y + crop.h / 2; + return { + x: Math.min(Math.max(cx - w / 2, crop.x), crop.x + crop.w - w), + y: Math.min(Math.max(cy - h / 2, crop.y), crop.y + crop.h - h), + w, + h, + }; +} + +function frameAngle(angle: number, quarter: number) { + return -((angle * Math.PI) / 180 + (quarter * Math.PI) / 2); +} + +/** + * Photo coordinates (0-1 over the untouched file) to frame coordinates, through + * the same rotate / quarter turn / flip the renderer applies. Lets a click on an + * unrotated thumbnail pick the point that lands there in the straightened crop. + */ +export function sourceToFrame( + p: { x: number; y: number }, + srcW: number, + srcH: number, + angle: number, + quarter: number, + flipH = false, + flipV = false, +) { + const b = rotatedBounds(srcW, srcH, angle, quarter); + // Frame uv grows the same way as the photo's pixels (y down, as the canvas + // draws them), so only a flip mirror the offset. + const sx = (p.x - 0.5) * srcW * (flipH ? -1 : 1); + const sy = (p.y - 0.5) * srcH * (flipV ? -1 : 1); + const a = frameAngle(angle, quarter); + const ca = Math.cos(-a); + const sa = Math.sin(-a); + return { + x: (sx * ca - sy * sa) / b.w + 0.5, + y: (sx * sa + sy * ca) / b.h + 0.5, + }; +} + +/** The inverse of `sourceToFrame`, for drawing a marker back onto the thumbnail. */ +export function frameToSource( + p: { x: number; y: number }, + srcW: number, + srcH: number, + angle: number, + quarter: number, + flipH = false, + flipV = false, +) { + const b = rotatedBounds(srcW, srcH, angle, quarter); + const dx = (p.x - 0.5) * b.w; + const dy = (p.y - 0.5) * b.h; + const a = frameAngle(angle, quarter); + const ca = Math.cos(a); + const sa = Math.sin(a); + const sx = (dx * ca - dy * sa) * (flipH ? -1 : 1); + const sy = (dx * sa + dy * ca) * (flipV ? -1 : 1); + return { x: sx / srcW + 0.5, y: sy / srcH + 0.5 }; +} + +/** + * Size of one grain cell in exported pixels, using the renderer's own scale: + * 1200 cells across the crop's long edge, cell size 1-3 units from the slider. + */ +export function grainCellPx( + edits: { + crop: { x: number; y: number; w: number; h: number; angle: number; quarter: number }; + grain: { size: number }; + }, + srcW: number, + srcH: number, + outW: number, +) { + const { crop } = edits; + const base = rotatedBounds(srcW, srcH, 0, crop.quarter); + const unitsPerPx = 1200 / Math.max(1, base.w * crop.w, base.h * crop.h); + const frame = rotatedBounds(srcW, srcH, crop.angle, crop.quarter); + const pxPerSource = outW / Math.max(1, frame.w * crop.w); + const cell = 1 + 2 * Math.min(1, Math.max(0, (edits.grain.size - 10) / 90)); + return (cell / unitsPerPx) * pxPerSource; +} + +/** Builds a 256px LUT with the composite curve baked together with each channel curve. */ +export function buildCurveLUT(edits: Edits): Uint8Array { + const rgb = buildSampler(edits.curve.rgb); + const red = buildSampler(edits.curve.red); + const green = buildSampler(edits.curve.green); + const blue = buildSampler(edits.curve.blue); + const data = new Uint8Array(256 * 4); + for (let i = 0; i < 256; i++) { + const base = rgb(i / 255); + data[i * 4 + 0] = Math.round(clamp01(red(base)) * 255); + data[i * 4 + 1] = Math.round(clamp01(green(base)) * 255); + data[i * 4 + 2] = Math.round(clamp01(blue(base)) * 255); + data[i * 4 + 3] = 255; + } + return data; +} + +class Prog { + private cache = new Map(); + constructor(private gl: WebGL2RenderingContext, public program: WebGLProgram) {} + + loc(name: string): WebGLUniformLocation | null { + if (!this.cache.has(name)) this.cache.set(name, this.gl.getUniformLocation(this.program, name)); + return this.cache.get(name) ?? null; + } + f(name: string, v: number) { + const l = this.loc(name); + if (l) this.gl.uniform1f(l, v); + } + i(name: string, v: number) { + const l = this.loc(name); + if (l) this.gl.uniform1i(l, v); + } + v2(name: string, a: number, b: number) { + const l = this.loc(name); + if (l) this.gl.uniform2f(l, a, b); + } + v4(name: string, a: number, b: number, c: number, d: number) { + const l = this.loc(name); + if (l) this.gl.uniform4f(l, a, b, c, d); + } + v3(name: string, a: number, b: number, c: number) { + const l = this.loc(name); + if (l) this.gl.uniform3f(l, a, b, c); + } + fv(name: string, values: Float32Array) { + const l = this.loc(`${name}[0]`) ?? this.loc(name); + if (l) this.gl.uniform1fv(l, values); + } + tex(name: string, texture: WebGLTexture, unit: number) { + const l = this.loc(name); + if (!l) return; + this.gl.activeTexture(this.gl.TEXTURE0 + unit); + this.gl.bindTexture(this.gl.TEXTURE_2D, texture); + this.gl.uniform1i(l, unit); + } +} + +function compile(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader { + const shader = gl.createShader(type); + if (!shader) throw new Error('Unable to create shader'); + gl.shaderSource(shader, source); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + const log = gl.getShaderInfoLog(shader); + gl.deleteShader(shader); + throw new Error(`Shader compile error: ${log}`); + } + return shader; +} + +function link(gl: WebGL2RenderingContext, vsSource: string, fsSource: string): WebGLProgram { + const vs = compile(gl, gl.VERTEX_SHADER, vsSource); + const fs = compile(gl, gl.FRAGMENT_SHADER, fsSource); + const program = gl.createProgram(); + if (!program) throw new Error('Unable to create program'); + gl.attachShader(program, vs); + gl.attachShader(program, fs); + gl.linkProgram(program); + gl.deleteShader(vs); + gl.deleteShader(fs); + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + const log = gl.getProgramInfoLog(program); + gl.deleteProgram(program); + throw new Error(`Program link error: ${log}`); + } + return program; +} + +export class Renderer { + readonly canvas: HTMLCanvasElement; + private gl: WebGL2RenderingContext; + private grade: Prog; + private blur: Prog; + private finish: Prog; + private quad: WebGLBuffer; + private vao: WebGLVertexArrayObject; + private srcTex: WebGLTexture; + private srcBitmap: ImageBitmap | null = null; + private srcW = 1; + private srcH = 1; + private curveTex: WebGLTexture; + private targets: { graded?: Target; smallA?: Target; smallB?: Target; bigA?: Target; bigB?: Target } = {}; + private histTarget: Target | null = null; + private histW = 160; + private histH = 112; + private grainRef: { x: number; y: number; w: number; h: number; sx: number; sy: number; units: number } | null = null; + + histogram: Histogram = makeHistogram(); + + constructor(canvas: HTMLCanvasElement) { + this.canvas = canvas; + const gl = canvas.getContext('webgl2', { + alpha: false, + antialias: false, + depth: false, + stencil: false, + preserveDrawingBuffer: false, + powerPreference: 'high-performance', + }); + if (!gl) throw new Error('This browser does not support WebGL2, which the editor needs.'); + this.gl = gl; + + this.grade = new Prog(gl, link(gl, VERT, GRADE_FRAG)); + this.blur = new Prog(gl, link(gl, VERT, BLUR_FRAG)); + this.finish = new Prog(gl, link(gl, VERT, FINISH_FRAG)); + + const quad = gl.createBuffer(); + if (!quad) throw new Error('Unable to create buffer'); + this.quad = quad; + gl.bindBuffer(gl.ARRAY_BUFFER, quad); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW); + + const vao = gl.createVertexArray(); + if (!vao) throw new Error('Unable to create vertex array'); + this.vao = vao; + gl.bindVertexArray(vao); + gl.bindBuffer(gl.ARRAY_BUFFER, quad); + gl.enableVertexAttribArray(0); + gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); + gl.bindVertexArray(null); + + const srcTex = gl.createTexture(); + if (!srcTex) throw new Error('Unable to create texture'); + this.srcTex = srcTex; + gl.bindTexture(gl.TEXTURE_2D, srcTex); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + + const curveTex = gl.createTexture(); + if (!curveTex) throw new Error('Unable to create texture'); + this.curveTex = curveTex; + gl.bindTexture(gl.TEXTURE_2D, curveTex); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + + gl.disable(gl.BLEND); + gl.disable(gl.DEPTH_TEST); + } + + static isSupported(): boolean { + try { + const c = document.createElement('canvas'); + return !!c.getContext('webgl2'); + } catch { + return false; + } + } + + setImage(bitmap: ImageBitmap) { + if (this.srcBitmap === bitmap) return; + this.grainRef = null; + const gl = this.gl; + this.srcBitmap = bitmap; + this.srcW = bitmap.width; + this.srcH = bitmap.height; + gl.bindTexture(gl.TEXTURE_2D, this.srcTex); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); + // Mipmaps: a 6000 px proxy shown fitted is a 4-8x minification, which shimmers + // badly with plain bilinear sampling. + gl.generateMipmap(gl.TEXTURE_2D); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); + } + + private makeTarget(w: number, h: number): Target { + const gl = this.gl; + const tex = gl.createTexture(); + const fbo = gl.createFramebuffer(); + if (!tex || !fbo) throw new Error('Unable to allocate render target'); + gl.bindTexture(gl.TEXTURE_2D, tex); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + return { tex, fbo, w, h }; + } + + private freeTarget(target?: Target) { + if (!target) return; + this.gl.deleteTexture(target.tex); + this.gl.deleteFramebuffer(target.fbo); + } + + private ensureTargets(w: number, h: number) { + const t = this.targets; + if (!t.graded || t.graded.w !== w || t.graded.h !== h) { + this.freeTarget(t.graded); + this.freeTarget(t.smallA); + this.freeTarget(t.smallB); + this.freeTarget(t.bigA); + this.freeTarget(t.bigB); + const sw = Math.max(1, Math.ceil(w / 2)); + const sh = Math.max(1, Math.ceil(h / 2)); + const bw = Math.max(1, Math.ceil(w / 4)); + const bh = Math.max(1, Math.ceil(h / 4)); + this.targets = { + graded: this.makeTarget(w, h), + smallA: this.makeTarget(sw, sh), + smallB: this.makeTarget(sw, sh), + bigA: this.makeTarget(bw, bh), + bigB: this.makeTarget(bw, bh), + }; + } + } + + private drawQuad() { + const gl = this.gl; + gl.bindVertexArray(this.vao); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + gl.bindVertexArray(null); + } + + private uploadCurve(edits: Edits) { + const gl = this.gl; + const data = buildCurveLUT(edits); + gl.bindTexture(gl.TEXTURE_2D, this.curveTex); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); + } + + render( + edits: Edits, + opts: { + width: number; + height: number; + cropPreview?: boolean; + histogram?: boolean; + /** visible sub-rect of the frame, normalized; defaults to the whole crop */ + view?: { x: number; y: number; w: number; h: number }; + /** sample bicubically, for when the view magnifies the source beyond 1:1 */ + upscale?: boolean; + /** hold the grain pattern still, e.g. while a crop handle is being dragged */ + freezeGrain?: boolean; + }, + ) { + const gl = this.gl; + if (!this.srcBitmap) return; + const w = Math.max(1, Math.round(opts.width)); + const h = Math.max(1, Math.round(opts.height)); + if (this.canvas.width !== w) this.canvas.width = w; + if (this.canvas.height !== h) this.canvas.height = h; + + this.ensureTargets(w, h); + const t = this.targets; + if (!t.graded || !t.smallA || !t.smallB || !t.bigA || !t.bigB) return; + + this.uploadCurve(edits); + + const bounds = rotatedBounds(this.srcW, this.srcH, edits.crop.angle, edits.crop.quarter); + const valid = opts.cropPreview + ? { x: 0, y: 0, w: 1, h: 1 } + : { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h }; + const crop = opts.view ?? valid; + + // Pass 1: white balance, tone, curve, color + gl.bindFramebuffer(gl.FRAMEBUFFER, t.graded.fbo); + gl.viewport(0, 0, w, h); + const g = this.grade; + gl.useProgram(g.program); + g.tex('u_src', this.srcTex, 0); + g.tex('u_curve', this.curveTex, 1); + g.v2('u_srcSize', this.srcW, this.srcH); + g.v2('u_frameSize', bounds.w, bounds.h); + g.v4('u_crop', crop.x, crop.y, crop.w, crop.h); + g.v4('u_valid', valid.x, valid.y, valid.w, valid.h); + g.f('u_angle', (edits.crop.angle * Math.PI) / 180); + g.i('u_quarter', edits.crop.quarter); + g.v2('u_flip', edits.crop.flipH ? -1 : 1, edits.crop.flipV ? -1 : 1); + g.f('u_upscale', opts.upscale ? 1 : 0); + g.f('u_temp', edits.temp); + g.f('u_tint', edits.tint); + g.f('u_exposure', edits.exposure); + g.f('u_contrast', edits.contrast); + g.f('u_highlights', edits.highlights); + g.f('u_shadows', edits.shadows); + g.f('u_whites', edits.whites); + g.f('u_blacks', edits.blacks); + g.f('u_vibrance', edits.vibrance); + g.f('u_saturation', edits.saturation); + g.f('u_bw', edits.bw ? 1 : 0); + const bwFilter = bwFilterRgb(edits.bwFilter); + g.v3('u_bwFilter', bwFilter[0], bwFilter[1], bwFilter[2]); + g.f('u_bwFilterAmt', clamp01(edits.bwFilterAmount / 100)); + g.fv('u_hue', new Float32Array(edits.hsl.hue)); + g.fv('u_sat', new Float32Array(edits.hsl.sat)); + g.fv('u_lum', new Float32Array(edits.hsl.lum)); + g.f('u_gSh', edits.grading.shadows.h / 360); + g.f('u_gSs', edits.grading.shadows.s); + g.f('u_gHi', edits.grading.highlights.h / 360); + g.f('u_gHs', edits.grading.highlights.s); + g.f('u_gBal', edits.grading.balance); + this.drawQuad(); + + // Passes 2-3: small blur (detail) and large blur (clarity) from the graded image + const blurPass = (from: Target, to: Target, dx: number, dy: number, srcTex: WebGLTexture) => { + const gl2 = this.gl; + gl2.bindFramebuffer(gl2.FRAMEBUFFER, to.fbo); + gl2.viewport(0, 0, to.w, to.h); + gl2.useProgram(this.blur.program); + this.blur.tex('u_tex', srcTex, 0); + this.blur.v2('u_dir', dx, dy); + this.drawQuad(); + }; + + gl.bindFramebuffer(gl.FRAMEBUFFER, t.smallA.fbo); + gl.viewport(0, 0, t.smallA.w, t.smallA.h); + gl.useProgram(this.blur.program); + this.blur.tex('u_tex', t.graded.tex, 0); + this.blur.v2('u_dir', (edits.sharpen.radius / t.smallA.w) * 0.75, 0); + this.drawQuad(); + blurPass(t.smallA, t.smallB, 0, (edits.sharpen.radius / t.smallB.h) * 0.75, t.smallA.tex); + + gl.bindFramebuffer(gl.FRAMEBUFFER, t.bigA.fbo); + gl.viewport(0, 0, t.bigA.w, t.bigA.h); + gl.useProgram(this.blur.program); + this.blur.tex('u_tex', t.graded.tex, 0); + this.blur.v2('u_dir', 2.0 / t.bigA.w, 0); + this.drawQuad(); + blurPass(t.bigA, t.bigB, 0, 2.0 / t.bigB.h, t.bigA.tex); + + // Grain cells are counted across the crop's long edge: the same slider value + // covers the same share of the picture at every resolution and crop. While a + // handle is being dragged the reference is held, so the noise stands still. + const GRAIN_UNITS = 1200; + // Scaled from the un-straightened frame: straightening grows the rotating + // bounding box, which would otherwise resize the grain along with it. + const base = rotatedBounds(this.srcW, this.srcH, 0, edits.crop.quarter); + const cropW = Math.max(1, base.w * valid.w); + const cropH = Math.max(1, base.h * valid.h); + const grainUnits = GRAIN_UNITS / Math.max(cropW, cropH); + if (!opts.freezeGrain || !this.grainRef) { + this.grainRef = { + x: valid.x, + y: valid.y, + w: valid.w, + h: valid.h, + sx: cropW * grainUnits, + sy: cropH * grainUnits, + units: grainUnits, + }; + } + const grain = this.grainRef; + const grainRot = -((edits.crop.angle * Math.PI) / 180 + (edits.crop.quarter * Math.PI) / 2); + + // Pass 4: detail, effects, grain -> canvas + const finishDraw = (target: Target | null) => { + const gl2 = this.gl; + if (target) { + gl2.bindFramebuffer(gl2.FRAMEBUFFER, target.fbo); + gl2.viewport(0, 0, target.w, target.h); + } else { + gl2.bindFramebuffer(gl2.FRAMEBUFFER, null); + gl2.viewport(0, 0, w, h); + } + gl2.useProgram(this.finish.program); + this.finish.tex('u_graded', t.graded!.tex, 0); + this.finish.tex('u_blurSmall', t.smallB!.tex, 1); + this.finish.tex('u_blurBig', t.bigB!.tex, 2); + this.finish.f('u_texture', edits.texture); + this.finish.f('u_clarity', edits.clarity); + this.finish.f('u_dehaze', edits.dehaze); + this.finish.f('u_sharpen', edits.sharpen.amount); + this.finish.f('u_nr', edits.noise.luminance); + this.finish.f('u_vigAmt', edits.vignette.amount); + this.finish.f('u_vigMid', edits.vignette.midpoint); + this.finish.f('u_vigFeather', edits.vignette.feather); + this.finish.f('u_grainAmt', edits.grain.amount); + this.finish.f('u_grainSize', edits.grain.size); + this.finish.f('u_grainRough', edits.grain.roughness); + this.finish.v4('u_crop', crop.x, crop.y, crop.w, crop.h); + this.finish.v4('u_grainFrame', grain.x, grain.y, grain.w, grain.h); + this.finish.v2('u_grainSpace', grain.sx, grain.sy); + this.finish.f('u_grainUnits', grain.units); + this.finish.v2('u_frameSize', bounds.w, bounds.h); + this.finish.f('u_grainRot', grainRot); + this.finish.v2('u_grainFlip', edits.crop.flipH ? -1 : 1, edits.crop.flipV ? -1 : 1); + this.finish.v2('u_outSize', target ? target.w : w, target ? target.h : h); + this.finish.f('u_aspect', w / h); + this.drawQuad(); + }; + + finishDraw(null); + + if (opts.histogram) { + if (!this.histTarget) this.histTarget = this.makeTarget(this.histW, this.histH); + finishDraw(this.histTarget); + const pixels = new Uint8Array(this.histW * this.histH * 4); + gl.readPixels(0, 0, this.histW, this.histH, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + const hist = this.histogram; + hist.r.fill(0); + hist.g.fill(0); + hist.b.fill(0); + hist.l.fill(0); + for (let i = 0; i < pixels.length; i += 4) { + const r = pixels[i]; + const gg = pixels[i + 1]; + const b = pixels[i + 2]; + hist.r[r]++; + hist.g[gg]++; + hist.b[b]++; + hist.l[Math.round(0.2126 * r + 0.7152 * gg + 0.0722 * b)]++; + } + } + + } + + dispose() { + const gl = this.gl; + this.freeTarget(this.targets.graded); + this.freeTarget(this.targets.smallA); + this.freeTarget(this.targets.smallB); + this.freeTarget(this.targets.bigA); + this.freeTarget(this.targets.bigB); + this.freeTarget(this.histTarget ?? undefined); + gl.deleteTexture(this.srcTex); + gl.deleteTexture(this.curveTex); + gl.deleteBuffer(this.quad); + gl.deleteVertexArray(this.vao); + gl.deleteProgram(this.grade.program); + gl.deleteProgram(this.blur.program); + gl.deleteProgram(this.finish.program); + // Release the context slot so switching between library and develop does not + // exhaust the browser's WebGL context limit. + const ext = gl.getExtension('WEBGL_lose_context'); + ext?.loseContext(); + } +} + diff --git a/lumenroom/src/lib/api.ts b/lumenroom/src/lib/api.ts new file mode 100644 index 0000000..9b6d40b --- /dev/null +++ b/lumenroom/src/lib/api.ts @@ -0,0 +1,161 @@ +import type { EventRecord, PhotoRecord, Preset } from '../types'; + +export interface Health { + ok: boolean; + app: string; + version: string; + needsSetup: boolean; + registrationOpen: boolean; + photos: number; + bytes: number; + raw: { libraw: boolean; sharp: boolean; formats: string[] }; +} + +export interface SessionUser { + id: string; + email: string; + name: string; + role: string; +} + +export interface UploadResult { + raw: boolean; + engine?: 'libraw' | 'embedded'; + width?: number; + height?: number; + mime?: string; + size?: number; + previewUrl?: string; + thumbUrl?: string; + note?: string | null; +} + +export class ApiError extends Error { + status: number; + constructor(message: string, status: number) { + super(message); + this.status = status; + } +} + +async function request(path: string, init?: RequestInit): Promise { + let res: Response; + try { + res = await fetch(path, { credentials: 'same-origin', ...init }); + } catch { + throw new ApiError('Cannot reach the Lumenroom server', 0); + } + if (!res.ok) { + let message = `Request failed (${res.status})`; + try { + const body = (await res.json()) as { error?: string }; + if (body?.error) message = body.error; + } catch { + /* non-JSON error body */ + } + throw new ApiError(message, res.status); + } + if (res.status === 204) return undefined as T; + return (await res.json()) as T; +} + +function jsonBody(payload: unknown): RequestInit { + return { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }; +} + +/** Returns null when the app is running without a server (pure browser library). */ +export async function getHealth(): Promise { + try { + const res = await fetch('/api/health', { credentials: 'same-origin' }); + if (!res.ok) return null; + const body = (await res.json()) as Health; + return body?.ok ? body : null; + } catch { + return null; + } +} + +export async function register(input: { + email: string; + password: string; + name?: string; + invite?: string; +}): Promise { + const res = await request<{ user: SessionUser }>('/api/auth/register', jsonBody(input)); + return res.user; +} + +export async function login(email: string, password: string): Promise { + const res = await request<{ user: SessionUser }>('/api/auth/login', jsonBody({ email, password })); + return res.user; +} + +export async function logout(): Promise { + await request('/api/auth/logout', { method: 'POST' }); +} + +export async function currentUser(): Promise { + try { + const res = await request<{ user: SessionUser }>('/api/auth/me'); + return res.user; + } catch (err) { + if (err instanceof ApiError && err.status === 401) return null; + return null; + } +} + +export interface SyncPayload { + user: SessionUser; + events: EventRecord[]; + photos: PhotoRecord[]; + presets: Preset[]; +} + +export function pullAll(): Promise { + return request('/api/sync'); +} + +export function uploadOriginal(id: string, file: File | Blob, name: string): Promise { + const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' }); + return request(`/api/photos/${encodeURIComponent(id)}/original?${query}`, { + method: 'POST', + headers: { 'Content-Type': 'application/octet-stream' }, + body: file, + }); +} + +export function pushPhoto(photo: PhotoRecord): Promise { + return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(photo), + }).then((res) => res.photo); +} + +export function deletePhotoRemote(id: string): Promise { + return request(`/api/photos/${encodeURIComponent(id)}`, { method: 'DELETE' }); +} + +export function pushEvent(event: EventRecord): Promise { + return request<{ event: EventRecord }>(`/api/events/${encodeURIComponent(event.id)}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(event), + }).then((res) => res.event); +} + +export function deleteEventRemote(id: string): Promise { + return request(`/api/events/${encodeURIComponent(id)}`, { method: 'DELETE' }); +} + +export function pushPresets(presets: Preset[]): Promise { + return request('/api/presets', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ presets }), + }); +} diff --git a/lumenroom/src/lib/auto.ts b/lumenroom/src/lib/auto.ts new file mode 100644 index 0000000..85ba533 --- /dev/null +++ b/lumenroom/src/lib/auto.ts @@ -0,0 +1,73 @@ +import type { Edits } from '../types'; +import { clamp } from './curves'; + +interface Stats { + mean: number; + p05: number; + p95: number; + saturation: number; +} + +async function analyze(thumb: string): Promise { + const img = new Image(); + img.src = thumb; + await img.decode(); + const w = 96; + const h = Math.max(1, Math.round((img.height / img.width) * w)) || 96; + const canvas = document.createElement('canvas'); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext('2d'); + if (!ctx) throw new Error('Canvas unavailable'); + ctx.drawImage(img, 0, 0, w, h); + const { data } = ctx.getImageData(0, 0, w, h); + const hist = new Uint32Array(256); + let total = 0; + let lumaSum = 0; + let satSum = 0; + for (let i = 0; i < data.length; i += 4) { + const r = data[i] / 255; + const g = data[i + 1] / 255; + const b = data[i + 2] / 255; + const l = 0.2126 * r + 0.7152 * g + 0.0722 * b; + hist[Math.round(l * 255)]++; + lumaSum += l; + satSum += Math.max(r, g, b) - Math.min(r, g, b); + total++; + } + const percentile = (p: number) => { + const target = total * p; + let acc = 0; + for (let i = 0; i < 256; i++) { + acc += hist[i]; + if (acc >= target) return i / 255; + } + return 1; + }; + return { + mean: lumaSum / total, + p05: percentile(0.05), + p95: percentile(0.95), + saturation: satSum / total, + }; +} + +/** Simple histogram based auto tone, in the spirit of Lightroom's Auto button. */ +export async function computeAutoEdits(thumb: string): Promise> { + try { + const s = await analyze(thumb); + const mean = clamp(s.mean, 0.03, 0.97); + const exposure = clamp(Math.log2(0.46 / mean), -2, 2); + return { + exposure: Math.round(exposure * 100) / 100, + contrast: s.p95 - s.p05 < 0.55 ? 18 : 10, + highlights: s.p95 > 0.94 ? -32 : 4, + shadows: s.p05 < 0.055 ? 32 : 4, + whites: s.p95 > 0.96 ? -8 : 10, + blacks: s.p05 < 0.03 ? 6 : -6, + vibrance: s.saturation < 0.18 ? 18 : 8, + }; + } catch { + return { contrast: 12, shadows: 12, highlights: -12, vibrance: 8 }; + } +} diff --git a/lumenroom/src/lib/curves.ts b/lumenroom/src/lib/curves.ts new file mode 100644 index 0000000..12a1455 --- /dev/null +++ b/lumenroom/src/lib/curves.ts @@ -0,0 +1,71 @@ +import type { CurvePoint } from '../types'; + +export const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); +export const clamp01 = (v: number) => clamp(v, 0, 1); +export const round2 = (v: number) => Math.round(v * 100) / 100; + +export type CurveSampler = (x: number) => number; + +/** Monotone cubic (Fritsch-Carlson) interpolation through normalized curve points. */ +export function buildSampler(input: CurvePoint[]): CurveSampler { + const pts = [...input].sort((a, b) => a.x - b.x); + if (pts.length < 2) return (x: number) => clamp01(x); + const xs = pts.map((p) => clamp01(p.x)); + const ys = pts.map((p) => clamp01(p.y)); + const n = xs.length; + + const d: number[] = []; + for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / Math.max(1e-6, xs[i + 1] - xs[i])); + + const m: number[] = new Array(n); + m[0] = d[0]; + m[n - 1] = d[n - 2]; + for (let i = 1; i < n - 1; i++) { + if (d[i - 1] * d[i] <= 0) m[i] = 0; + else m[i] = (d[i - 1] + d[i]) / 2; + } + for (let i = 0; i < n - 1; i++) { + if (d[i] === 0) { + m[i] = 0; + m[i + 1] = 0; + continue; + } + const a = m[i] / d[i]; + const b = m[i + 1] / d[i]; + const s = a * a + b * b; + if (s > 9) { + const t = 3 / Math.sqrt(s); + m[i] = t * a * d[i]; + m[i + 1] = t * b * d[i]; + } + } + + return (x: number) => { + if (x <= xs[0]) return clamp01(ys[0] + (x - xs[0]) * m[0]); + if (x >= xs[n - 1]) return clamp01(ys[n - 1] + (x - xs[n - 1]) * m[n - 1]); + let i = 0; + while (i < n - 2 && x > xs[i + 1]) i++; + const h = xs[i + 1] - xs[i]; + const t = (x - xs[i]) / h; + const t2 = t * t; + const t3 = t2 * t; + const h00 = 2 * t3 - 3 * t2 + 1; + const h10 = t3 - 2 * t2 + t; + const h01 = -2 * t3 + 3 * t2; + const h11 = t3 - t2; + return clamp01(h00 * ys[i] + h10 * h * m[i] + h01 * ys[i + 1] + h11 * h * m[i + 1]); + }; +} + +export function sanitizeCurve(input: unknown): CurvePoint[] { + const fallback: CurvePoint[] = [ + { x: 0, y: 0 }, + { x: 1, y: 1 }, + ]; + if (!Array.isArray(input)) return fallback; + const pts = input + .filter((p): p is CurvePoint => !!p && typeof p.x === 'number' && typeof p.y === 'number') + .map((p) => ({ x: clamp01(p.x), y: clamp01(p.y) })) + .sort((a, b) => a.x - b.x); + return pts.length >= 2 ? pts : fallback; +} diff --git a/lumenroom/src/lib/db.ts b/lumenroom/src/lib/db.ts new file mode 100644 index 0000000..cf79023 --- /dev/null +++ b/lumenroom/src/lib/db.ts @@ -0,0 +1,91 @@ +import type { EventRecord, PhotoRecord } from '../types'; + +const DB_NAME = 'lumenroom'; +const DB_VERSION = 1; + +let dbPromise: Promise | null = null; + +export function openDB(): Promise { + if (dbPromise) return dbPromise; + dbPromise = new Promise((resolve, reject) => { + const req = indexedDB.open(DB_NAME, DB_VERSION); + req.onupgradeneeded = () => { + const db = req.result; + if (!db.objectStoreNames.contains('photos')) { + const store = db.createObjectStore('photos', { keyPath: 'id' }); + store.createIndex('eventId', 'eventId', { unique: false }); + } + if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets'); + if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' }); + if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv'); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error ?? new Error('Unable to open database')); + }); + return dbPromise; +} + +function wrap(request: IDBRequest): Promise { + return new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed')); + }); +} + +async function store(name: string, mode: IDBTransactionMode = 'readonly') { + const db = await openDB(); + return db.transaction(name, mode).objectStore(name); +} + +export async function getAllPhotos(): Promise { + return wrap((await store('photos')).getAll() as IDBRequest); +} + +export async function putPhoto(photo: PhotoRecord): Promise { + await wrap((await store('photos', 'readwrite')).put(photo)); +} + +export async function deletePhotoRecord(id: string): Promise { + const db = await openDB(); + const tx = db.transaction(['photos', 'assets'], 'readwrite'); + tx.objectStore('photos').delete(id); + tx.objectStore('assets').delete(id); + await new Promise((resolve, reject) => { + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error); + }); +} + +export async function putAsset(id: string, blob: Blob): Promise { + await wrap((await store('assets', 'readwrite')).put(blob, id)); +} + +export async function getAsset(id: string): Promise { + return wrap((await store('assets')).get(id) as IDBRequest); +} + +export async function getAllEvents(): Promise { + return wrap((await store('events')).getAll() as IDBRequest); +} + +export async function putEvent(event: EventRecord): Promise { + await wrap((await store('events', 'readwrite')).put(event)); +} + +export async function deleteEventRecord(id: string): Promise { + await wrap((await store('events', 'readwrite')).delete(id)); +} + +export async function getKV(key: string): Promise { + return wrap((await store('kv')).get(key) as IDBRequest); +} + +export async function setKV(key: string, value: unknown): Promise { + await wrap((await store('kv', 'readwrite')).put(value, key)); +} + +export async function estimateUsage(): Promise<{ usage: number; quota: number }> { + if (!navigator.storage?.estimate) return { usage: 0, quota: 0 }; + const est = await navigator.storage.estimate(); + return { usage: est.usage ?? 0, quota: est.quota ?? 0 }; +} diff --git a/lumenroom/src/lib/drag.ts b/lumenroom/src/lib/drag.ts new file mode 100644 index 0000000..7fdd8b2 --- /dev/null +++ b/lumenroom/src/lib/drag.ts @@ -0,0 +1,34 @@ +/** + * Drag payloads live in a module variable because browsers only expose + * `dataTransfer.getData` on drop, not during dragover — and we need to know + * whether a photo (rather than an OS file) is being dragged while hovering. + */ + +let photoIds: string[] = []; +let eventId: string | null = null; + +export const PHOTO_DRAG = 'application/x-lumen-photos'; +export const EVENT_DRAG = 'application/x-lumen-event'; + +export function startPhotoDrag(ids: string[]) { + photoIds = ids; + eventId = null; +} + +export function draggedPhotoIds(): string[] { + return photoIds; +} + +export function startEventDrag(id: string) { + eventId = id; + photoIds = []; +} + +export function draggedEventId(): string | null { + return eventId; +} + +export function endDrag() { + photoIds = []; + eventId = null; +} diff --git a/lumenroom/src/lib/edits.ts b/lumenroom/src/lib/edits.ts new file mode 100644 index 0000000..41444c8 --- /dev/null +++ b/lumenroom/src/lib/edits.ts @@ -0,0 +1,296 @@ +import type { BwFilter, ColorLabel, CropState, CurvePoint, Edits, Flag, PhotoRecord, PhotoMeta } from '../types'; +import { clamp, clamp01, sanitizeCurve } from './curves'; + +export interface HueBand { + key: string; + name: string; + center: number; + swatch: string; +} + +export const HUE_BANDS: HueBand[] = [ + { key: 'red', name: 'Red', center: 0, swatch: '#e2453c' }, + { key: 'orange', name: 'Orange', center: 32, swatch: '#e88b3a' }, + { key: 'yellow', name: 'Yellow', center: 62, swatch: '#e3cd48' }, + { key: 'green', name: 'Green', center: 120, swatch: '#57a95a' }, + { key: 'aqua', name: 'Aqua', center: 180, swatch: '#48b3b8' }, + { key: 'blue', name: 'Blue', center: 230, swatch: '#4a72c9' }, + { key: 'purple', name: 'Purple', center: 280, swatch: '#8a63c6' }, + { key: 'magenta', name: 'Magenta', center: 320, swatch: '#c455a0' }, +]; + +/** + * Photographic contrast filters for black & white: transmission per channel. + * A red filter passes red and blocks blue, so skies print almost black. + */ +export const BW_FILTERS: { id: BwFilter; label: string; rgb: [number, number, number] }[] = [ + { id: 'none', label: 'None', rgb: [1, 1, 1] }, + { id: 'yellow', label: 'Yellow', rgb: [1, 0.9, 0.28] }, + { id: 'orange', label: 'Orange', rgb: [1, 0.66, 0.13] }, + { id: 'red', label: 'Red', rgb: [1, 0.36, 0.05] }, + { id: 'green', label: 'Green', rgb: [0.42, 1, 0.45] }, + { id: 'blue', label: 'Blue', rgb: [0.35, 0.75, 1] }, +]; + +export function bwFilterRgb(id: BwFilter): [number, number, number] { + return BW_FILTERS.find((f) => f.id === id)?.rgb ?? [1, 1, 1]; +} + +/** + * CSS transform that shows a grid thumbnail in the photo's *current* orientation. + * Uses the same order as the renderer: flips act on the photo, then the quarter + * turns and straighten rotate it, and the result is scaled so the rotated image + * still fills the card (a 90 degree turn of a 4:3 photo would otherwise leave gaps). + */ +export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string { + const { quarter, angle, flipH, flipV } = photo.edits.crop; + const deg = quarter * 90 + angle; + if (Math.abs(deg) < 1e-6 && !flipH && !flipV) return 'none'; + + const w = Math.max(1, photo.width || 1); + const h = Math.max(1, photo.height || 1); + const boxH = 1 / boxAspect; + // object-fit: cover — the photo already fills the card before any transform. + const cover = Math.max(1 / w, boxH / h); + const dw = w * cover; + const dh = h * cover; + const rad = (Math.abs(deg) * Math.PI) / 180; + const c = Math.abs(Math.cos(rad)); + const s = Math.abs(Math.sin(rad)); + // A rotated photo has to contain all four corners of the card, not just its + // bounding box: after un-rotating a card corner by -deg it sits at + // ((c + boxH*s)/2, (s + boxH*c)/2), so the photo must be at least that wide + // and tall. Fitting the bounding box instead leaves gaps on angle-only turns. + const coverFit = Math.max((c + boxH * s) / dw, (s + boxH * c) / dh); + // A thumbnail's rounded pixel size can differ from the record's ratio by a + // fraction of a percent; a hair of slack keeps it from showing a sliver at + // the edge. It is invisible at any real card size. + const fit = Math.abs(deg) > 1e-6 ? coverFit * 1.005 : coverFit; + + const parts = [`rotate(${deg.toFixed(2)}deg)`]; + // Round up: rounding the scale down would leave a hairline gap at the edge. + const rounded = Math.ceil(fit * 1e4) / 1e4; + if (Math.abs(rounded - 1) > 1e-4) parts.push(`scale(${rounded.toFixed(4)})`); + if (flipH) parts.push('scaleX(-1)'); + if (flipV) parts.push('scaleY(-1)'); + return parts.join(' '); +} + +export const ASPECTS: { id: string; label: string; ratio: number | null }[] = [ + { id: 'original', label: 'Original', ratio: null }, + { id: 'free', label: 'Free', ratio: null }, + { id: '1:1', label: '1 × 1', ratio: 1 }, + { id: '4:5', label: '4 × 5', ratio: 4 / 5 }, + { id: '5:4', label: '5 × 4', ratio: 5 / 4 }, + { id: '4:3', label: '4 × 3', ratio: 4 / 3 }, + { id: '3:2', label: '3 × 2', ratio: 3 / 2 }, + { id: '16:9', label: '16 × 9', ratio: 16 / 9 }, + { id: '2:1', label: '2 × 1', ratio: 2 }, + { id: '9:16', label: '9 × 16', ratio: 9 / 16 }, +]; + +export function defaultCrop(): CropState { + return { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original', flipH: false, flipV: false }; +} + +export function identityCurve(): CurvePoint[] { + return [ + { x: 0, y: 0 }, + { x: 1, y: 1 }, + ]; +} + +export function defaultEdits(): Edits { + return { + temp: 0, + tint: 0, + exposure: 0, + contrast: 0, + highlights: 0, + shadows: 0, + whites: 0, + blacks: 0, + texture: 0, + clarity: 0, + dehaze: 0, + vibrance: 0, + saturation: 0, + bw: false, + bwFilter: 'none', + bwFilterAmount: 100, + curve: { + rgb: identityCurve(), + red: identityCurve(), + green: identityCurve(), + blue: identityCurve(), + }, + hsl: { + hue: HUE_BANDS.map(() => 0), + sat: HUE_BANDS.map(() => 0), + lum: HUE_BANDS.map(() => 0), + }, + grading: { + shadows: { h: 210, s: 0 }, + highlights: { h: 45, s: 0 }, + balance: 0, + }, + sharpen: { amount: 0, radius: 1, detail: 25 }, + noise: { luminance: 0, detail: 50 }, + vignette: { amount: 0, midpoint: 50, feather: 50 }, + grain: { amount: 0, size: 25, roughness: 50 }, + crop: defaultCrop(), + }; +} + +function bands(input: unknown): number[] { + const arr = Array.isArray(input) ? input : []; + return HUE_BANDS.map((_, i) => { + const v = arr[i]; + return typeof v === 'number' && Number.isFinite(v) ? clamp(v, -100, 100) : 0; + }); +} + +function num(value: unknown, fallback: number, lo: number, hi: number): number { + return typeof value === 'number' && Number.isFinite(value) ? clamp(value, lo, hi) : fallback; +} + +/** Deep-merge stored edits with the current defaults so older records keep working. */ +export function normalizeEdits(input: Partial | undefined | null): Edits { + const d = defaultEdits(); + if (!input) return d; + const curve = (input.curve ?? {}) as Partial; + const grading = (input.grading ?? {}) as Partial; + const sharpen = (input.sharpen ?? {}) as Partial; + const noise = (input.noise ?? {}) as Partial; + const vignette = (input.vignette ?? {}) as Partial; + const grain = (input.grain ?? {}) as Partial; + const crop = (input.crop ?? {}) as Partial; + + return { + ...d, + ...input, + temp: num(input.temp, 0, -100, 100), + tint: num(input.tint, 0, -100, 100), + exposure: num(input.exposure, 0, -5, 5), + contrast: num(input.contrast, 0, -100, 100), + highlights: num(input.highlights, 0, -100, 100), + shadows: num(input.shadows, 0, -100, 100), + whites: num(input.whites, 0, -100, 100), + blacks: num(input.blacks, 0, -100, 100), + texture: num(input.texture, 0, -100, 100), + clarity: num(input.clarity, 0, -100, 100), + dehaze: num(input.dehaze, 0, -100, 100), + vibrance: num(input.vibrance, 0, -100, 100), + saturation: num(input.saturation, 0, -100, 100), + bw: !!input.bw, + bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none', + bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100), + curve: { + rgb: sanitizeCurve(curve.rgb), + red: sanitizeCurve(curve.red), + green: sanitizeCurve(curve.green), + blue: sanitizeCurve(curve.blue), + }, + hsl: { + hue: bands(input.hsl?.hue), + sat: bands(input.hsl?.sat), + lum: bands(input.hsl?.lum), + }, + grading: { + shadows: { + h: num(grading.shadows?.h, d.grading.shadows.h, 0, 360), + s: num(grading.shadows?.s, 0, 0, 100), + }, + highlights: { + h: num(grading.highlights?.h, d.grading.highlights.h, 0, 360), + s: num(grading.highlights?.s, 0, 0, 100), + }, + balance: num(grading.balance, 0, -100, 100), + }, + sharpen: { + amount: num(sharpen.amount, 0, 0, 150), + radius: num(sharpen.radius, 1, 0.5, 3), + detail: num(sharpen.detail, 25, 0, 100), + }, + noise: { + luminance: num(noise.luminance, 0, 0, 100), + detail: num(noise.detail, 50, 0, 100), + }, + vignette: { + amount: num(vignette.amount, 0, -100, 100), + midpoint: num(vignette.midpoint, 50, 0, 100), + feather: num(vignette.feather, 50, 0, 100), + }, + grain: { + amount: num(grain.amount, 0, 0, 100), + size: num(grain.size, 25, 10, 100), + roughness: num(grain.roughness, 50, 0, 100), + }, + crop: { + x: clamp01(num(crop.x, 0, 0, 1)), + y: clamp01(num(crop.y, 0, 0, 1)), + w: clamp01(num(crop.w, 1, 0.02, 1)), + h: clamp01(num(crop.h, 1, 0.02, 1)), + angle: num(crop.angle, 0, -45, 45), + quarter: typeof crop.quarter === 'number' && Number.isFinite(crop.quarter) + ? ((Math.round(crop.quarter) % 4) + 4) % 4 + : 0, + aspect: typeof crop.aspect === 'string' ? crop.aspect : 'original', + flipH: !!crop.flipH, + flipV: !!crop.flipV, + }, + }; +} + +const editCache = new WeakMap(); + +export function isEdited(edits: Edits): boolean { + const cached = editCache.get(edits); + if (cached !== undefined) return cached; + const d = defaultEdits(); + const strip = (e: Edits) => JSON.stringify({ ...e, crop: { ...e.crop, aspect: undefined } }); + const result = strip(edits) !== strip(d); + editCache.set(edits, result); + return result; +} + +export function normalizePhoto(input: Partial & { id: string }): PhotoRecord { + const edits = normalizeEdits(input.edits); + const addedAt = input.addedAt ?? Date.now(); + const meta: PhotoMeta = input.meta ?? {}; + return { + id: input.id, + eventId: input.eventId ?? '', + order: typeof input.order === 'number' ? input.order : undefined, + raw: !!input.raw, + decode: input.decode, + previewUrl: input.previewUrl, + thumbUrl: input.thumbUrl, + name: input.name ?? 'Untitled', + width: input.width ?? 0, + height: input.height ?? 0, + size: input.size ?? 0, + mime: input.mime ?? 'image/jpeg', + addedAt, + takenAt: input.takenAt, + meta, + thumb: input.thumb ?? '', + rating: clamp(Math.round(input.rating ?? 0), 0, 5), + flag: (input.flag ?? 'none') as Flag, + color: (input.color ?? '') as ColorLabel, + keywords: Array.isArray(input.keywords) ? input.keywords : [], + edits, + history: + Array.isArray(input.history) && input.history.length + ? input.history + : [{ label: 'Import', ts: addedAt, edits }], + }; +} + +export const COLOR_LABELS: { value: ColorLabel; name: string; hex: string }[] = [ + { value: 'red', name: 'Red', hex: '#e05252' }, + { value: 'yellow', name: 'Yellow', hex: '#e0c04a' }, + { value: 'green', name: 'Green', hex: '#56b268' }, + { value: 'blue', name: 'Blue', hex: '#4f86e0' }, + { value: 'purple', name: 'Purple', hex: '#9b6ede' }, +]; diff --git a/lumenroom/src/lib/export.ts b/lumenroom/src/lib/export.ts new file mode 100644 index 0000000..9d1fa0e --- /dev/null +++ b/lumenroom/src/lib/export.ts @@ -0,0 +1,137 @@ +import type { Edits, PhotoRecord } from '../types'; +import { getBitmap } from './images'; +import { normalizeEdits } from './edits'; +import { outputSize, Renderer } from '../gl/renderer'; + +export type ExportFormat = 'jpeg' | 'png' | 'webp'; +export type ResizeMode = 'none' | 'longEdge' | 'percent'; + +export interface ExportOptions { + format: ExportFormat; + quality: number; + resize: ResizeMode; + longEdge: number; + percent: number; + nameTemplate: string; +} + +export const DEFAULT_EXPORT: ExportOptions = { + format: 'jpeg', + quality: 92, + resize: 'none', + longEdge: 3000, + percent: 100, + nameTemplate: '{name}', +}; + +const MIME: Record = { + jpeg: 'image/jpeg', + png: 'image/png', + webp: 'image/webp', +}; + +const EXT: Record = { + jpeg: 'jpg', + png: 'png', + webp: 'webp', +}; + +function download(blob: Blob, filename: string) { + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 4000); +} + +function pad(n: number) { + return String(n).padStart(2, '0'); +} + +export function buildFileName(template: string, photo: PhotoRecord, index: number, opts: ExportOptions) { + const stamp = new Date(photo.takenAt ?? photo.addedAt); + const base = photo.name.replace(/\.[^.]+$/, '') || 'export'; + const name = (template || '{name}') + .replace(/\{name\}/g, base) + .replace(/\{date\}/g, `${stamp.getFullYear()}${pad(stamp.getMonth() + 1)}${pad(stamp.getDate())}`) + .replace(/\{time\}/g, `${pad(stamp.getHours())}${pad(stamp.getMinutes())}`) + .replace(/\{index\}/g, String(index + 1).padStart(3, '0')) + .replace(/[\\/:*?"<>|]+/g, '-') + .trim(); + return `${name || 'export'}.${EXT[opts.format]}`; +} + +function targetSize(photo: PhotoRecord, edits: Edits, bitmap: ImageBitmap, opts: ExportOptions) { + const size = outputSize(edits, bitmap.width, bitmap.height); + const longEdge = Math.max(size.w, size.h); + let scale = 1; + if (opts.resize === 'longEdge' && opts.longEdge > 0 && longEdge > opts.longEdge) { + scale = opts.longEdge / longEdge; + } else if (opts.resize === 'percent') { + scale = Math.min(2, Math.max(0.05, opts.percent / 100)); + } + return { + w: Math.max(1, Math.round(size.w * scale)), + h: Math.max(1, Math.round(size.h * scale)), + }; +} + +export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions): Promise { + const bitmap = await getBitmap(photo); + const edits = normalizeEdits(photo.edits); + const { w, h } = targetSize(photo, edits, bitmap, opts); + const canvas = document.createElement('canvas'); + canvas.width = 1; + canvas.height = 1; + const renderer = new Renderer(canvas); + try { + renderer.setImage(bitmap); + renderer.render(edits, { width: w, height: h }); + const mime = MIME[opts.format]; + const blob = await new Promise((resolve) => + canvas.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))), + ); + if (!blob) throw new Error('Export failed while encoding the image'); + return blob; + } finally { + renderer.dispose(); + } +} + +export async function exportPhotos( + photos: PhotoRecord[], + opts: ExportOptions, + onProgress?: (done: number, total: number) => void, +): Promise<{ count: number; failed: string[] }> { + let count = 0; + const failed: string[] = []; + for (let i = 0; i < photos.length; i++) { + const photo = photos[i]; + try { + const blob = await renderPhotoBlob(photo, opts); + download(blob, buildFileName(opts.nameTemplate, photo, i, opts)); + count++; + } catch (err) { + console.error('Export failed for', photo.name, err); + failed.push(photo.name); + } + onProgress?.(i + 1, photos.length); + // Give the browser a beat so long batches keep the tab responsive. + await new Promise((r) => setTimeout(r, 0)); + } + return { count, failed }; +} + +/** Backwards compatible single-photo export. */ +export async function exportPhoto(photo: PhotoRecord, maxLongEdge = 0): Promise { + const opts: ExportOptions = { + ...DEFAULT_EXPORT, + resize: maxLongEdge > 0 ? 'longEdge' : 'none', + longEdge: maxLongEdge || DEFAULT_EXPORT.longEdge, + }; + const blob = await renderPhotoBlob(photo, opts); + download(blob, buildFileName(opts.nameTemplate, photo, 0, opts)); +} diff --git a/lumenroom/src/lib/images.ts b/lumenroom/src/lib/images.ts new file mode 100644 index 0000000..a064b7f --- /dev/null +++ b/lumenroom/src/lib/images.ts @@ -0,0 +1,67 @@ +import type { PhotoRecord } from '../types'; +import { getAsset, putAsset } from './db'; + +const CACHE_LIMIT = 6; +const cache = new Map(); + +/** Where to fetch the original (or raw proxy) when it is not cached on this device. */ +export function remoteAssetUrl(photo: PhotoRecord): string { + if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`; + return `/api/photos/${encodeURIComponent(photo.id)}/original`; +} + +async function fetchRemote(photo: PhotoRecord): Promise { + try { + const res = await fetch(remoteAssetUrl(photo), { credentials: 'same-origin' }); + if (!res.ok) return null; + const blob = await res.blob(); + // Cache it locally so the photo keeps working offline after the first look. + await putAsset(photo.id, blob).catch(() => undefined); + return blob; + } catch { + return null; + } +} + +export async function getBitmap(photo: PhotoRecord): Promise { + const hit = cache.get(photo.id); + if (hit) { + cache.delete(photo.id); + cache.set(photo.id, hit); + return hit; + } + + let blob = await getAsset(photo.id); + if (!blob) blob = (await fetchRemote(photo)) ?? undefined; + if (!blob) { + throw new Error( + photo.raw + ? 'This raw file has no editable proxy yet. Sign in to the server and sync to fetch it.' + : 'Original image data is missing from browser storage', + ); + } + + // Apply EXIF orientation so the pixels the editor works on are upright. + const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' }); + cache.set(photo.id, bitmap); + while (cache.size > CACHE_LIMIT) { + const first = cache.keys().next(); + if (first.done) break; + const old = cache.get(first.value); + cache.delete(first.value); + old?.close(); + } + return bitmap; +} + +export function evictBitmap(photoId: string) { + const bmp = cache.get(photoId); + if (!bmp) return; + cache.delete(photoId); + bmp.close(); +} + +export function clearBitmapCache() { + for (const bmp of cache.values()) bmp.close(); + cache.clear(); +} diff --git a/lumenroom/src/lib/import.ts b/lumenroom/src/lib/import.ts new file mode 100644 index 0000000..228ee42 --- /dev/null +++ b/lumenroom/src/lib/import.ts @@ -0,0 +1,240 @@ +import exifr from 'exifr'; +import type { UploadResult } from './api'; +import type { PhotoMeta, PhotoRecord } from '../types'; +import { putAsset, putPhoto } from './db'; +import { defaultEdits, normalizePhoto } from './edits'; +import { isRawFile, RAW_EXTENSIONS } from './raw'; + +export interface ImportProgress { + done: number; + total: number; + current: string; +} + +export interface ImportResult { + photos: PhotoRecord[]; + failed: { name: string; reason: string }[]; +} + +/** Provided by the app when a Lumenroom server is connected. */ +export interface CloudImport { + uploadOriginal: (id: string, file: File, name: string) => Promise; + push: (photo: PhotoRecord) => Promise; +} + +/** Files imported at once; the server bounds how many raws decode in parallel. */ +const IMPORT_CONCURRENCY = 4; + +export function uid(): string { + if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID(); + return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`; +} + +function mapLimit(items: T[], limit: number, fn: (item: T, index: number) => Promise): Promise { + let cursor = 0; + const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => { + for (;;) { + const index = cursor++; + if (index >= items.length) return; + await fn(items[index], index); + } + }); + return Promise.all(runners); +} + +function formatShutter(time: unknown): string | undefined { + if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined; + if (time >= 1) return `${Math.round(time * 10) / 10}s`; + return `1/${Math.round(1 / time)}s`; +} + +async function readMeta(file: File): Promise<{ meta: PhotoMeta; takenAt?: number }> { + try { + const data = (await exifr.parse(file, { + tiff: true, + exif: true, + gps: false, + interop: false, + translateValues: false, + reviveValues: true, + })) as Record | undefined; + if (!data) return { meta: {} }; + const make = typeof data.Make === 'string' ? data.Make.trim() : ''; + const model = typeof data.Model === 'string' ? data.Model.trim() : ''; + const meta: PhotoMeta = { + camera: [make, model].filter(Boolean).join(' ').replace(/\s+/g, ' ') || undefined, + lens: typeof data.LensModel === 'string' ? data.LensModel.trim() : undefined, + iso: typeof data.ISO === 'number' ? data.ISO : undefined, + aperture: typeof data.FNumber === 'number' ? data.FNumber : undefined, + shutter: formatShutter(data.ExposureTime), + focal: typeof data.FocalLength === 'number' ? Math.round(data.FocalLength) : undefined, + }; + const taken = data.DateTimeOriginal ?? data.CreateDate ?? data.ModifyDate; + const takenAt = taken instanceof Date && !Number.isNaN(taken.getTime()) ? taken.getTime() : undefined; + return { meta, takenAt }; + } catch { + return { meta: {} }; + } +} + +async function makeThumb(bitmap: ImageBitmap): Promise { + const max = 560; + const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height)); + const w = Math.max(1, Math.round(bitmap.width * scale)); + const h = Math.max(1, Math.round(bitmap.height * scale)); + const canvas = document.createElement('canvas'); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext('2d'); + if (!ctx) throw new Error('Canvas 2D is unavailable'); + ctx.imageSmoothingQuality = 'high'; + ctx.drawImage(bitmap, 0, 0, w, h); + return canvas.toDataURL('image/jpeg', 0.82); +} + +export function isSupportedFile(file: File): boolean { + if (file.type.startsWith('image/')) return true; + const ext = file.name.split('.').pop()?.toLowerCase() ?? ''; + return RAW_EXTENSIONS.has(ext) || /^(jpe?g|png|webp|avif|gif|bmp|tiff?)$/.test(ext); +} + +/** + * Raw files cannot be decoded by the browser, so they are sent to the server, + * demosaiced there, and represented locally by the returned editable proxy. + */ +async function importRaw(file: File, eventId: string, keywords: string[], cloud: CloudImport): Promise { + const id = uid(); + const upload = await cloud.uploadOriginal(id, file, file.name); + const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`; + const res = await fetch(previewUrl, { credentials: 'same-origin' }); + if (!res.ok) throw new Error('The server could not produce a preview for this raw file'); + const blob = await res.blob(); + const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' }); + const thumb = await makeThumb(bitmap); + const { meta, takenAt } = await readMeta(file); + const width = upload.width ?? bitmap.width; + const height = upload.height ?? bitmap.height; + bitmap.close(); + + const record = normalizePhoto({ + id, + eventId, + name: file.name, + width, + height, + size: file.size, + mime: 'image/jpeg', + addedAt: Date.now(), + takenAt: takenAt ?? file.lastModified, + meta, + thumb, + rating: 0, + flag: 'none', + color: '', + keywords, + edits: defaultEdits(), + history: [{ label: 'Import', ts: Date.now(), edits: defaultEdits() }], + raw: true, + decode: upload.engine, + previewUrl, + }); + + await putPhoto(record); + // No local blob: the multi-megabyte raw stays on the server. + const saved = await cloud.push(record); + const merged = normalizePhoto({ ...record, ...saved }); + await putPhoto(merged); + return merged; +} + +async function importStandard( + file: File, + eventId: string, + keywords: string[], + cloud?: CloudImport | null, +): Promise { + // Camera JPEGs carry their orientation in EXIF; ask for it to be applied so + // the thumbnail and the edited proxy agree with what the camera shot. + const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' }); + const thumb = await makeThumb(bitmap); + const { meta, takenAt } = await readMeta(file); + const id = uid(); + let record = normalizePhoto({ + id, + eventId, + name: file.name, + width: bitmap.width, + height: bitmap.height, + size: file.size, + mime: file.type || 'image/jpeg', + addedAt: Date.now(), + takenAt: takenAt ?? file.lastModified, + meta, + thumb, + rating: 0, + flag: 'none', + color: '', + keywords, + edits: defaultEdits(), + history: [{ label: 'Import', ts: Date.now(), edits: defaultEdits() }], + }); + await putAsset(id, file); + bitmap.close(); + + if (cloud) { + // Originals are mirrored to the server; failures fall back to a local-only import. + try { + await cloud.uploadOriginal(id, file, file.name); + const saved = await cloud.push(record); + record = normalizePhoto({ ...record, ...saved }); + } catch (err) { + console.warn('Could not copy the original to the server', file.name, err); + } + } + + await putPhoto(record); + return record; +} + +export async function importFiles( + files: File[], + eventId: string, + keywords: string[] = [], + onProgress?: (p: ImportProgress) => void, + cloud?: CloudImport | null, +): Promise { + const result: ImportResult = { photos: [], failed: [] }; + const images = files.filter(isSupportedFile); + const total = images.length; + if (!total) return result; + + const collected: { index: number; photo: PhotoRecord }[] = []; + let done = 0; + + await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => { + try { + const photo = isRawFile(file) + ? cloud + ? await importRaw(file, eventId, keywords, cloud) + : (() => { + throw new Error('Raw files need the Lumenroom server. Sign in, then import again.'); + })() + : await importStandard(file, eventId, keywords, cloud); + collected.push({ index, photo }); + } catch (err) { + result.failed.push({ + name: file.name, + reason: err instanceof Error ? err.message : 'Unsupported image format', + }); + } finally { + done += 1; + onProgress?.({ done, total, current: file.name }); + } + }); + + // Keep the shoot in capture/selection order regardless of which finished first. + collected.sort((a, b) => a.index - b.index); + result.photos = collected.map((c) => c.photo); + onProgress?.({ done: total, total, current: '' }); + return result; +} diff --git a/lumenroom/src/lib/presets.ts b/lumenroom/src/lib/presets.ts new file mode 100644 index 0000000..3c167a9 --- /dev/null +++ b/lumenroom/src/lib/presets.ts @@ -0,0 +1,1171 @@ +import type { BwFilter, Edits, Preset } from '../types'; + +const identity = () => [ + { x: 0, y: 0 }, + { x: 1, y: 1 }, +]; + +/* --------------------------------------------------------------- film pack */ + +type Band = 'red' | 'orange' | 'yellow' | 'green' | 'aqua' | 'blue' | 'purple' | 'magenta'; + +const BAND_ORDER: Band[] = ['red', 'orange', 'yellow', 'green', 'aqua', 'blue', 'purple', 'magenta']; + +interface BandShift { + hue?: number; + sat?: number; + lum?: number; +} + +function mix(shifts: Partial>): Edits['hsl'] { + return { + hue: BAND_ORDER.map((b) => shifts[b]?.hue ?? 0), + sat: BAND_ORDER.map((b) => shifts[b]?.sat ?? 0), + lum: BAND_ORDER.map((b) => shifts[b]?.lum ?? 0), + }; +} + +interface FilmSpec { + id: string; + name: string; + group: string; + /** black & white stock */ + bw?: boolean; + /** contrast filter used with the stock */ + filter?: BwFilter; + temp?: number; + tint?: number; + contrast?: number; + highlights?: number; + shadows?: number; + whites?: number; + blacks?: number; + texture?: number; + clarity?: number; + dehaze?: number; + vibrance?: number; + saturation?: number; + curve?: [number, number][]; + hsl?: Partial>; + grade?: { shadows?: [number, number]; highlights?: [number, number]; balance?: number }; + /** amount, size, and optionally roughness */ + grain?: [number, number, number?]; + vignette?: number; + vignetteMid?: number; +} + +/** A film look replaces the full colour/tone treatment (exposure stays yours). */ +function film(f: FilmSpec): Preset { + const curve = f.curve + ? { rgb: f.curve.map(([x, y]) => ({ x, y })), red: identity(), green: identity(), blue: identity() } + : { rgb: identity(), red: identity(), green: identity(), blue: identity() }; + + const edits: Preset['edits'] = { + temp: f.temp ?? 0, + tint: f.tint ?? 0, + contrast: f.contrast ?? 0, + highlights: f.highlights ?? 0, + shadows: f.shadows ?? 0, + whites: f.whites ?? 0, + blacks: f.blacks ?? 0, + texture: f.texture ?? 0, + clarity: f.clarity ?? 0, + dehaze: f.dehaze ?? 0, + vibrance: f.vibrance ?? 0, + saturation: f.saturation ?? 0, + bw: !!f.bw, + bwFilter: f.bw ? f.filter ?? 'none' : 'none', + bwFilterAmount: 100, + curve, + hsl: mix(f.hsl ?? {}), + grading: { + shadows: { h: f.grade?.shadows?.[0] ?? 210, s: f.grade?.shadows?.[1] ?? 0 }, + highlights: { h: f.grade?.highlights?.[0] ?? 45, s: f.grade?.highlights?.[1] ?? 0 }, + balance: f.grade?.balance ?? 0, + }, + grain: { amount: f.grain?.[0] ?? 0, size: f.grain?.[1] ?? 25, roughness: f.grain?.[2] ?? 55 }, + vignette: { amount: f.vignette ?? 0, midpoint: f.vignetteMid ?? 45, feather: 60 }, + }; + + return { id: f.id, name: f.name, group: f.group, edits }; +} + +/** S-curve used by most slide films: deep blacks, bright but clean highlights. */ +const SLIDE: [number, number][] = [ + [0, 0.02], + [0.25, 0.2], + [0.75, 0.82], + [1, 0.99], +]; + +/** Soft shoulder used by colour negative print films. */ +const PRINT: [number, number][] = [ + [0, 0.02], + [0.3, 0.29], + [0.75, 0.77], + [1, 0.98], +]; + +/** Lifted blacks of instant film. */ +const INSTANT: [number, number][] = [ + [0, 0.09], + [0.5, 0.52], + [1, 0.95], +]; + +const FILM_PACK: FilmSpec[] = [ + /* ----------------------------------------------------------------- Kodak */ + { + id: 'film-portra-160', + name: 'Kodak Portra 160', + group: 'Kodak', + temp: 4, + contrast: -6, + highlights: -8, + shadows: 10, + vibrance: 8, + saturation: -4, + curve: PRINT, + hsl: { orange: { sat: -4, lum: 5 }, green: { sat: -6 }, blue: { sat: -4 } }, + grade: { shadows: [212, 4], highlights: [40, 8] }, + grain: [10, 24], + }, + { + id: 'film-portra-400', + name: 'Kodak Portra 400', + group: 'Kodak', + temp: 6, + contrast: -2, + highlights: -10, + shadows: 8, + vibrance: 10, + saturation: -2, + curve: PRINT, + hsl: { orange: { sat: 5, lum: 6 }, green: { sat: -4 }, blue: { sat: -2 } }, + grade: { shadows: [215, 5], highlights: [42, 9] }, + grain: [16, 28], + }, + { + id: 'film-portra-800', + name: 'Kodak Portra 800', + group: 'Kodak', + temp: 8, + contrast: 2, + highlights: -8, + shadows: 10, + vibrance: 8, + saturation: -4, + curve: PRINT, + hsl: { orange: { sat: 6, lum: 8 }, green: { sat: -6 } }, + grade: { shadows: [216, 6], highlights: [44, 10] }, + grain: [26, 32], + }, + { + id: 'film-ektar-100', + name: 'Kodak Ektar 100', + group: 'Kodak', + contrast: 18, + blacks: -10, + vibrance: 26, + saturation: 8, + clarity: 6, + curve: SLIDE, + hsl: { red: { sat: 12 }, green: { sat: 6, hue: -4 }, blue: { sat: 14, lum: -4 }, aqua: { sat: 8 } }, + grade: { shadows: [214, 6], highlights: [45, 4] }, + grain: [6, 22], + }, + { + id: 'film-gold-200', + name: 'Kodak Gold 200', + group: 'Kodak', + temp: 14, + contrast: 6, + highlights: -10, + shadows: 6, + vibrance: 14, + saturation: 6, + curve: PRINT, + hsl: { orange: { sat: 10, lum: 6 }, yellow: { sat: 8 }, green: { sat: -6 } }, + grade: { shadows: [35, 6], highlights: [45, 12] }, + grain: [14, 28], + }, + { + id: 'film-colorplus-200', + name: 'Kodak ColorPlus 200', + group: 'Kodak', + temp: 18, + tint: 4, + contrast: 4, + highlights: -6, + shadows: 8, + saturation: 8, + vibrance: 10, + curve: PRINT, + hsl: { orange: { sat: 12, lum: 5 }, yellow: { sat: 10 }, aqua: { sat: -6 } }, + grade: { shadows: [38, 8], highlights: [46, 12] }, + grain: [18, 30], + }, + { + id: 'film-ultramax-400', + name: 'Kodak Ultramax 400', + group: 'Kodak', + temp: 12, + contrast: 8, + blacks: -6, + vibrance: 18, + saturation: 4, + curve: PRINT, + hsl: { orange: { sat: 8 }, yellow: { sat: 6 }, blue: { sat: 10 }, green: { sat: -4 } }, + grade: { shadows: [30, 6], highlights: [44, 10] }, + grain: [20, 30], + }, + { + id: 'film-pro-image-100', + name: 'Kodak Pro Image 100', + group: 'Kodak', + temp: 6, + contrast: 10, + shadows: 4, + vibrance: 12, + saturation: 2, + curve: PRINT, + hsl: { orange: { sat: 6, lum: 4 }, blue: { sat: 4 } }, + grade: { shadows: [205, 4], highlights: [42, 8] }, + grain: [8, 24], + }, + { + id: 'film-ektachrome-e100', + name: 'Kodak Ektachrome E100', + group: 'Kodak', + temp: -6, + contrast: 20, + highlights: -10, + blacks: -8, + saturation: 4, + vibrance: 16, + clarity: 4, + curve: SLIDE, + hsl: { blue: { sat: 12 }, green: { sat: 6 }, red: { sat: 6 } }, + grade: { shadows: [220, 8], highlights: [48, 4] }, + grain: [6, 22], + }, + { + id: 'film-kodachrome-25', + name: 'Kodak Kodachrome 25', + group: 'Kodak', + temp: 8, + contrast: 20, + blacks: -12, + vibrance: 6, + saturation: -4, + curve: SLIDE, + hsl: { red: { sat: 16, hue: -4 }, orange: { sat: 10, lum: 4 }, blue: { sat: -12, hue: 4 } }, + grade: { shadows: [210, 8], highlights: [44, 6] }, + grain: [5, 20], + }, + { + id: 'film-kodachrome-64', + name: 'Kodak Kodachrome 64', + group: 'Kodak', + temp: 8, + contrast: 16, + blacks: -10, + vibrance: 6, + saturation: -4, + curve: SLIDE, + hsl: { red: { sat: 16, hue: -4 }, orange: { sat: 10, lum: 4 }, blue: { sat: -12, hue: 4 } }, + grade: { shadows: [210, 7], highlights: [44, 6] }, + grain: [9, 24], + }, + { + id: 'film-kodachrome-200', + name: 'Kodak Kodachrome 200', + group: 'Kodak', + temp: 8, + contrast: 12, + blacks: -8, + vibrance: 4, + saturation: -6, + curve: PRINT, + hsl: { red: { sat: 14 }, orange: { sat: 8, lum: 5 }, blue: { sat: -10 } }, + grade: { shadows: [212, 8], highlights: [44, 6] }, + grain: [20, 30], + }, + { + id: 'film-tri-x-400', + name: 'Kodak Tri-X 400', + group: 'Kodak', + bw: true, + filter: 'yellow', + contrast: 22, + blacks: -12, + whites: 10, + clarity: 8, + curve: SLIDE, + grain: [26, 32], + }, + { + id: 'film-tri-x-320', + name: 'Kodak Tri-X 320', + group: 'Kodak', + bw: true, + filter: 'yellow', + contrast: 18, + blacks: -10, + whites: 8, + curve: PRINT, + grain: [22, 30], + }, + { + id: 'film-tmax-100', + name: 'Kodak T-Max 100', + group: 'Kodak', + bw: true, + filter: 'none', + contrast: 16, + blacks: -8, + clarity: 8, + curve: SLIDE, + grain: [6, 22], + }, + { + id: 'film-tmax-400', + name: 'Kodak T-Max 400', + group: 'Kodak', + bw: true, + filter: 'none', + contrast: 14, + blacks: -6, + clarity: 6, + curve: SLIDE, + grain: [14, 26], + }, + { + id: 'film-tmax-3200', + name: 'Kodak T-Max 3200', + group: 'Kodak', + bw: true, + filter: 'none', + contrast: 20, + shadows: 10, + blacks: -8, + curve: PRINT, + grain: [40, 38], + }, + { + id: 'film-plus-x-125', + name: 'Kodak Plus-X 125', + group: 'Kodak', + bw: true, + filter: 'yellow', + contrast: 12, + curve: PRINT, + grain: [8, 24], + }, + { + id: 'film-bw400cn', + name: 'Kodak BW400CN', + group: 'Kodak', + bw: true, + filter: 'none', + contrast: 6, + highlights: -8, + curve: PRINT, + grain: [10, 26], + }, + + /* -------------------------------------------------------------- Fujifilm */ + { + id: 'film-pro-400h', + name: 'Fujifilm Pro 400H', + group: 'Fujifilm', + temp: -6, + tint: 4, + contrast: -10, + highlights: -6, + shadows: 12, + vibrance: 6, + saturation: -10, + curve: PRINT, + hsl: { green: { hue: 6, sat: 8 }, aqua: { hue: 4, sat: 6 }, orange: { lum: 6, sat: -4 } }, + grade: { shadows: [190, 8], highlights: [50, 6] }, + grain: [12, 26], + }, + { + id: 'film-superia-400', + name: 'Fujifilm Superia 400', + group: 'Fujifilm', + temp: -4, + contrast: 10, + vibrance: 16, + saturation: 4, + curve: PRINT, + hsl: { green: { sat: 12, hue: -6 }, aqua: { sat: 8, hue: -4 }, red: { sat: 6 } }, + grade: { shadows: [195, 8], highlights: [48, 6] }, + grain: [20, 30], + }, + { + id: 'film-superia-200', + name: 'Fujifilm Superia 200', + group: 'Fujifilm', + temp: -2, + contrast: 8, + vibrance: 14, + saturation: 2, + curve: PRINT, + hsl: { green: { sat: 10, hue: -4 }, aqua: { sat: 6 } }, + grade: { shadows: [196, 7], highlights: [48, 6] }, + grain: [13, 26], + }, + { + id: 'film-c200', + name: 'Fujifilm C200', + group: 'Fujifilm', + tint: 2, + contrast: 6, + vibrance: 12, + saturation: 2, + curve: PRINT, + hsl: { green: { sat: 8, hue: 4 }, blue: { sat: 6 } }, + grade: { shadows: [200, 6], highlights: [50, 5] }, + grain: [14, 28], + }, + { + id: 'film-pro-neg-hi', + name: 'Fujifilm Pro Neg Hi', + group: 'Fujifilm', + temp: -2, + contrast: 14, + shadows: 8, + vibrance: 8, + saturation: -2, + curve: PRINT, + hsl: { green: { sat: 6 }, orange: { lum: 4 } }, + grade: { shadows: [198, 6], highlights: [46, 6] }, + grain: [8, 24], + }, + { + id: 'film-pro-neg-std', + name: 'Fujifilm Pro Neg Std', + group: 'Fujifilm', + contrast: 2, + highlights: -6, + shadows: 12, + saturation: -12, + vibrance: 4, + curve: PRINT, + hsl: { green: { sat: 4 }, orange: { lum: 6 } }, + grade: { shadows: [200, 6], highlights: [48, 4] }, + grain: [8, 24], + }, + { + id: 'film-velvia-50', + name: 'Fujifilm Velvia 50', + group: 'Fujifilm', + temp: -8, + contrast: 26, + blacks: -14, + clarity: 8, + vibrance: 34, + saturation: 18, + curve: SLIDE, + hsl: { + red: { sat: 18 }, + orange: { sat: 10 }, + yellow: { sat: 12 }, + green: { sat: 20, hue: -8 }, + aqua: { sat: 12 }, + blue: { sat: 14 }, + }, + grain: [5, 20], + }, + { + id: 'film-velvia-100', + name: 'Fujifilm Velvia 100', + group: 'Fujifilm', + temp: -7, + contrast: 24, + blacks: -12, + clarity: 6, + vibrance: 30, + saturation: 14, + curve: SLIDE, + hsl: { + red: { sat: 16 }, + yellow: { sat: 10 }, + green: { sat: 18, hue: -6 }, + aqua: { sat: 10 }, + blue: { sat: 12 }, + }, + grain: [8, 22], + }, + { + id: 'film-provia-100f', + name: 'Fujifilm Provia 100F', + group: 'Fujifilm', + temp: -2, + contrast: 16, + blacks: -8, + vibrance: 18, + saturation: 6, + curve: SLIDE, + hsl: { blue: { sat: 8 }, green: { sat: 6 }, red: { sat: 6 } }, + grain: [6, 22], + }, + { + id: 'film-astia-100f', + name: 'Fujifilm Astia 100F', + group: 'Fujifilm', + temp: 2, + contrast: 6, + highlights: -6, + shadows: 8, + vibrance: 10, + saturation: -6, + curve: PRINT, + hsl: { orange: { lum: 6, sat: 4 }, green: { sat: 4 }, blue: { sat: -4 } }, + grade: { shadows: [205, 4], highlights: [45, 5] }, + grain: [6, 22], + }, + { + id: 'film-fortia-sp', + name: 'Fujifilm Fortia SP', + group: 'Fujifilm', + temp: -4, + contrast: 20, + blacks: -10, + vibrance: 30, + saturation: 24, + curve: SLIDE, + hsl: { green: { sat: 18 }, red: { sat: 20 }, blue: { sat: 16 }, magenta: { sat: 12 } }, + grain: [6, 22], + }, + { + id: 'film-acros-100-ii', + name: 'Fujifilm Acros 100 II', + group: 'Fujifilm', + bw: true, + filter: 'none', + contrast: 14, + blacks: -10, + clarity: 6, + curve: SLIDE, + grain: [4, 20], + }, + { + id: 'film-neopan-400', + name: 'Fujifilm Neopan 400', + group: 'Fujifilm', + bw: true, + filter: 'yellow', + contrast: 12, + curve: PRINT, + grain: [18, 28], + }, + { + id: 'film-neopan-1600', + name: 'Fujifilm Neopan 1600', + group: 'Fujifilm', + bw: true, + filter: 'none', + contrast: 16, + shadows: 8, + curve: PRINT, + grain: [34, 34], + }, + + /* ---------------------------------------------------------------- Ilford */ + { + id: 'film-hp5-plus-400', + name: 'Ilford HP5 Plus 400', + group: 'Ilford', + bw: true, + filter: 'yellow', + contrast: 14, + blacks: -8, + clarity: 6, + curve: PRINT, + grain: [24, 32], + }, + { + id: 'film-fp4-plus-125', + name: 'Ilford FP4 Plus 125', + group: 'Ilford', + bw: true, + filter: 'yellow', + contrast: 12, + curve: PRINT, + grain: [10, 26], + }, + { + id: 'film-delta-100', + name: 'Ilford Delta 100', + group: 'Ilford', + bw: true, + filter: 'none', + contrast: 16, + blacks: -8, + clarity: 6, + curve: SLIDE, + grain: [6, 22], + }, + { + id: 'film-delta-400', + name: 'Ilford Delta 400', + group: 'Ilford', + bw: true, + filter: 'none', + contrast: 16, + blacks: -6, + curve: SLIDE, + grain: [14, 26], + }, + { + id: 'film-delta-3200', + name: 'Ilford Delta 3200', + group: 'Ilford', + bw: true, + filter: 'none', + contrast: 18, + shadows: 12, + blacks: -10, + curve: PRINT, + grain: [44, 38], + }, + { + id: 'film-pan-f-plus-50', + name: 'Ilford Pan F Plus 50', + group: 'Ilford', + bw: true, + filter: 'orange', + contrast: 18, + blacks: -10, + clarity: 10, + curve: SLIDE, + grain: [4, 20], + }, + { + id: 'film-xp2-super-400', + name: 'Ilford XP2 Super 400', + group: 'Ilford', + bw: true, + filter: 'yellow', + contrast: 8, + highlights: -8, + shadows: 6, + curve: PRINT, + grain: [10, 26], + }, + { + id: 'film-ortho-plus-80', + name: 'Ilford Ortho Plus 80', + group: 'Ilford', + bw: true, + filter: 'green', + contrast: 18, + clarity: 8, + curve: SLIDE, + grain: [5, 20], + }, + + /* ------------------------------------------------------------------ Agfa */ + { + id: 'film-vista-200', + name: 'Agfa Vista 200', + group: 'Agfa', + temp: 8, + contrast: 6, + vibrance: 12, + saturation: 4, + curve: PRINT, + hsl: { green: { sat: 10, hue: -6 }, red: { sat: 8 }, blue: { sat: 6 } }, + grade: { shadows: [30, 6], highlights: [45, 8] }, + grain: [18, 30], + }, + { + id: 'film-ultra-100', + name: 'Agfa Ultra 100', + group: 'Agfa', + temp: 4, + contrast: 14, + vibrance: 20, + saturation: 26, + curve: SLIDE, + hsl: { red: { sat: 18 }, blue: { sat: 12 }, green: { sat: 8 } }, + grain: [8, 24], + }, + { + id: 'film-apx-100', + name: 'Agfa APX 100', + group: 'Agfa', + bw: true, + filter: 'yellow', + contrast: 14, + blacks: -6, + curve: PRINT, + grain: [14, 26], + }, + { + id: 'film-apx-400', + name: 'Agfa APX 400', + group: 'Agfa', + bw: true, + filter: 'yellow', + contrast: 10, + curve: PRINT, + grain: [26, 32], + }, + { + id: 'film-scala-200x', + name: 'Agfa Scala 200X', + group: 'Agfa', + bw: true, + filter: 'none', + contrast: 20, + blacks: -12, + clarity: 8, + curve: SLIDE, + grain: [8, 22], + }, + + /* -------------------------------------------------------------- CineStill */ + { + id: 'film-cinestill-50d', + name: 'CineStill 50D', + group: 'CineStill', + temp: -4, + contrast: 12, + highlights: -8, + vibrance: 16, + saturation: 4, + curve: PRINT, + hsl: { green: { hue: 4, sat: 6 }, aqua: { sat: 6 }, blue: { sat: 6 } }, + grade: { shadows: [200, 6], highlights: [46, 6] }, + grain: [8, 24], + }, + { + id: 'film-cinestill-800t', + name: 'CineStill 800T', + group: 'CineStill', + temp: -26, + tint: -6, + contrast: 10, + shadows: 8, + vibrance: 12, + saturation: 2, + curve: PRINT, + hsl: { blue: { sat: 10, hue: 4 }, aqua: { sat: 12 }, red: { sat: 8 } }, + grade: { shadows: [200, 24], highlights: [40, 10] }, + grain: [22, 30], + }, + + /* ------------------------------------------------------------ Lomography */ + { + id: 'film-lomocolor-100', + name: 'Lomography Color Negative 100', + group: 'Lomography', + temp: 6, + contrast: 18, + vibrance: 20, + saturation: 14, + curve: SLIDE, + hsl: { green: { sat: 14 }, blue: { sat: 10 }, red: { sat: 8 } }, + grade: { shadows: [220, 10], highlights: [45, 6] }, + vignette: -24, + grain: [16, 28], + }, + { + id: 'film-lomocolor-400', + name: 'Lomography Color Negative 400', + group: 'Lomography', + temp: 4, + contrast: 14, + vibrance: 16, + saturation: 10, + curve: PRINT, + hsl: { green: { sat: 10 }, blue: { sat: 8 } }, + grade: { shadows: [225, 12], highlights: [45, 6] }, + vignette: -30, + grain: [26, 32], + }, + { + id: 'film-lomochrome-purple', + name: 'LomoChrome Purple', + group: 'Lomography', + contrast: 12, + vibrance: 14, + saturation: 6, + curve: PRINT, + hsl: { green: { hue: 60, sat: 20 }, yellow: { hue: 50 }, aqua: { hue: 40, sat: 16 }, red: { hue: -12 } }, + grade: { shadows: [285, 26], highlights: [320, 10] }, + grain: [16, 28], + }, + { + id: 'film-lomochrome-metropolis', + name: 'LomoChrome Metropolis', + group: 'Lomography', + contrast: 16, + highlights: -8, + vibrance: 2, + saturation: -38, + curve: PRINT, + hsl: { green: { sat: -20 }, blue: { sat: -12 }, orange: { sat: -8 } }, + grade: { shadows: [190, 14], highlights: [40, 6] }, + grain: [14, 26], + }, + + /* --------------------------------------------------------- Polaroid/instant */ + { + id: 'film-polaroid-600', + name: 'Polaroid 600', + group: 'Polaroid & Instant', + temp: 10, + contrast: -12, + highlights: -6, + shadows: 22, + blacks: 26, + saturation: -18, + vibrance: 4, + curve: INSTANT, + hsl: { orange: { lum: 6, sat: 6 }, blue: { sat: -10 }, green: { sat: -12 } }, + grade: { shadows: [200, 10], highlights: [45, 10] }, + vignette: -14, + grain: [20, 34], + }, + { + id: 'film-polaroid-sx70', + name: 'Polaroid SX-70', + group: 'Polaroid & Instant', + temp: 14, + contrast: -16, + highlights: -4, + shadows: 26, + blacks: 34, + saturation: -24, + curve: [[0, 0.12], [0.5, 0.55], [1, 0.94]], + hsl: { orange: { lum: 8, sat: 8 }, blue: { sat: -12, lum: 4 }, green: { sat: -14 } }, + grade: { shadows: [42, 12], highlights: [48, 12] }, + vignette: -16, + vignetteMid: 40, + grain: [24, 36], + }, + { + id: 'film-instax-mini', + name: 'Fujifilm Instax Mini', + group: 'Polaroid & Instant', + temp: 2, + contrast: -4, + highlights: -8, + shadows: 10, + vibrance: 12, + saturation: 6, + curve: PRINT, + hsl: { aqua: { sat: 8 }, green: { sat: 6 }, orange: { lum: 4 } }, + grade: { shadows: [195, 6], highlights: [50, 6] }, + grain: [8, 24], + }, + + /* -------------------------------------------------------- Rollei & Bergger */ + { + id: 'film-rollei-retro-80s', + name: 'Rollei Retro 80S', + group: 'Rollei & Bergger', + bw: true, + filter: 'orange', + contrast: 20, + blacks: -10, + clarity: 10, + curve: SLIDE, + grain: [8, 22], + }, + { + id: 'film-rollei-infrared-400', + name: 'Rollei Infrared 400', + group: 'Rollei & Bergger', + bw: true, + filter: 'red', + contrast: 24, + blacks: -12, + clarity: 8, + curve: SLIDE, + hsl: { green: { lum: 30 }, yellow: { lum: 18 }, blue: { lum: -14 } }, + grain: [18, 30], + }, + { + id: 'film-bergger-pancro-400', + name: 'Bergger Pancro 400', + group: 'Rollei & Bergger', + bw: true, + filter: 'yellow', + contrast: 12, + shadows: 6, + curve: PRINT, + grain: [22, 30], + }, +]; + +export const FILM_PRESETS: Preset[] = FILM_PACK.map(film); + +/* --------------------------------------------------------------- essentials */ + +export const PRESETS: Preset[] = [ + { + id: 'original', + name: 'Original', + group: 'Essentials', + edits: {}, + }, + { + id: 'punch', + name: 'Punch', + group: 'Essentials', + edits: { contrast: 26, clarity: 18, vibrance: 24, blacks: -12, highlights: -12, whites: 8 }, + }, + { + id: 'matte-fade', + name: 'Matte Fade', + group: 'Film', + edits: { + contrast: -8, + shadows: 26, + blacks: 30, + saturation: -14, + curve: { rgb: [{ x: 0, y: 0.075 }, { x: 0.55, y: 0.55 }, { x: 1, y: 0.975 }], red: identity(), green: identity(), blue: identity() }, + }, + }, + { + id: 'golden-hour', + name: 'Golden Hour', + group: 'Warm', + edits: { + temp: 26, + exposure: 0.12, + highlights: -16, + shadows: 12, + vibrance: 18, + grading: { shadows: { h: 32, s: 8 }, highlights: { h: 42, s: 24 }, balance: 0 }, + }, + }, + { + id: 'cool-cinema', + name: 'Cool Cinema', + group: 'Cinematic', + edits: { + temp: -18, + tint: 6, + contrast: 16, + shadows: 14, + saturation: -8, + blacks: -8, + grading: { shadows: { h: 214, s: 26 }, highlights: { h: 40, s: 16 }, balance: 10 }, + }, + }, + { + id: 'film-chrome', + name: 'Film Chrome', + group: 'Film', + edits: { + contrast: 10, + clarity: -6, + vibrance: 12, + grain: { amount: 24, size: 28, roughness: 55 }, + curve: { + rgb: [ + { x: 0, y: 0.03 }, + { x: 0.25, y: 0.2 }, + { x: 0.75, y: 0.8 }, + { x: 1, y: 0.98 }, + ], + red: identity(), + green: identity(), + blue: identity(), + }, + }, + }, + { + id: 'vivid-landscape', + name: 'Vivid Landscape', + group: 'Outdoor', + edits: { + texture: 12, + clarity: 20, + dehaze: 12, + vibrance: 28, + saturation: 6, + highlights: -22, + shadows: 18, + hsl: { + hue: [0, 0, 0, 4, 0, 0, 0, 0], + sat: [0, 0, 6, 12, 8, 14, 0, 0], + lum: [0, 0, 0, -4, 0, -6, 0, 0], + }, + }, + }, + { + id: 'portrait-warm', + name: 'Portrait Warm', + group: 'Portrait', + edits: { + temp: 12, + texture: -8, + clarity: -6, + shadows: 10, + vibrance: 10, + hsl: { + hue: [0, 2, 0, 0, 0, 0, 0, 0], + sat: [0, 8, 0, 0, 0, 0, 0, 0], + lum: [0, 6, 0, 0, 0, 0, 0, 0], + }, + grading: { shadows: { h: 210, s: 6 }, highlights: { h: 38, s: 12 }, balance: 0 }, + }, + }, + { + id: 'bw-contrast', + name: 'B&W Contrast', + group: 'Black & White', + edits: { + bw: true, + bwFilter: 'yellow', + bwFilterAmount: 100, + contrast: 26, + clarity: 16, + blacks: -14, + whites: 10, + grain: { amount: 12, size: 30, roughness: 40 }, + hsl: { hue: [0, 0, 0, 0, 0, 0, 0, 0], sat: [0, 0, 0, 0, 0, 0, 0, 0], lum: [10, 14, 8, -10, 0, -16, 0, 0] }, + }, + }, + { + id: 'bw-soft', + name: 'B&W Soft', + group: 'Black & White', + edits: { + bw: true, + bwFilter: 'none', + bwFilterAmount: 100, + contrast: -4, + shadows: 16, + clarity: -6, + grain: { amount: 18, size: 32, roughness: 30 }, + curve: { rgb: [{ x: 0, y: 0.05 }, { x: 0.5, y: 0.52 }, { x: 1, y: 0.96 }], red: identity(), green: identity(), blue: identity() }, + }, + }, + { + id: 'neon-night', + name: 'Neon Night', + group: 'Cinematic', + edits: { + temp: -14, + contrast: 20, + blacks: -22, + vibrance: 30, + clarity: 10, + grading: { shadows: { h: 262, s: 30 }, highlights: { h: 192, s: 22 }, balance: -6 }, + }, + }, + { + id: 'vintage-print', + name: 'Vintage Print', + group: 'Film', + edits: { + temp: 16, + contrast: -6, + saturation: -20, + grain: { amount: 28, size: 34, roughness: 45 }, + vignette: { amount: -30, midpoint: 45, feather: 60 }, + grading: { shadows: { h: 38, s: 18 }, highlights: { h: 46, s: 10 }, balance: 0 }, + }, + }, + { + id: 'clean-minimal', + name: 'Clean Minimal', + group: 'Essentials', + edits: { exposure: 0.08, contrast: 6, clarity: 4, vibrance: 8, highlights: -12, shadows: 6 }, + }, + ...FILM_PRESETS, +]; + +/* ------------------------------------------------------------- film variants */ + +export type FilmVariant = 'base' | 'push' | 'pull' | 'warm' | 'cool'; + +export const FILM_VARIANTS: { id: FilmVariant; label: string; hint: string }[] = [ + { id: 'base', label: 'Stock', hint: 'The film as normally exposed and developed' }, + { id: 'push', label: 'Push +1', hint: 'One stop over-developed: brighter, punchier, grainier' }, + { id: 'pull', label: 'Pull −1', hint: 'One stop under-developed: darker, flatter, finer grain' }, + { id: 'warm', label: 'Warm split', hint: 'Split grade with warm highlights and cool shadows' }, + { id: 'cool', label: 'Cool split', hint: 'Split grade with cool highlights and warm shadows' }, +]; + +const FILM_GROUPS = new Set([ + 'Kodak', + 'Fujifilm', + 'Ilford', + 'Agfa', + 'CineStill', + 'Lomography', + 'Polaroid & Instant', + 'Rollei & Bergger', +]); + +/** Derives a push/pull or split-grade version of a film stock preset. */ +export function applyFilmVariant(preset: Preset, variant: FilmVariant): Preset { + if (variant === 'base' || !FILM_GROUPS.has(preset.group)) return preset; + + const e = preset.edits; + const grading = e.grading ?? { shadows: { h: 210, s: 0 }, highlights: { h: 45, s: 0 }, balance: 0 }; + const grain = e.grain ?? { amount: 0, size: 25, roughness: 50 }; + const next: Preset['edits'] = { ...e }; + let label = ''; + + if (variant === 'push') { + label = 'Push +1'; + next.exposure = (e.exposure ?? 0) + 1; + next.contrast = (e.contrast ?? 0) + 8; + next.highlights = (e.highlights ?? 0) - 6; + next.blacks = (e.blacks ?? 0) - 6; + next.vibrance = (e.vibrance ?? 0) + 4; + next.grain = { ...grain, amount: Math.min(100, Math.round(grain.amount * 1.6 + 4)) }; + } else if (variant === 'pull') { + label = 'Pull −1'; + next.exposure = (e.exposure ?? 0) - 1; + next.contrast = (e.contrast ?? 0) - 10; + next.shadows = (e.shadows ?? 0) + 4; + next.blacks = (e.blacks ?? 0) + 2; + next.grain = { ...grain, amount: Math.round(grain.amount * 0.65) }; + } else if (variant === 'warm') { + label = 'Warm split'; + next.grading = { + highlights: { h: 42, s: Math.max(14, grading.highlights.s) }, + shadows: { h: 214, s: Math.max(10, grading.shadows.s) }, + balance: 12, + }; + } else { + label = 'Cool split'; + next.grading = { + highlights: { h: 196, s: Math.max(12, grading.highlights.s) }, + shadows: { h: 34, s: Math.max(8, grading.shadows.s) }, + balance: -10, + }; + } + + return { ...preset, id: `${preset.id}::${variant}`, name: `${preset.name} · ${label}`, edits: next }; +} + +export const PRESET_GROUPS = [ + 'Essentials', + 'Portrait', + 'Outdoor', + 'Warm', + 'Cinematic', + 'Film', + 'Black & White', + 'Kodak', + 'Fujifilm', + 'Ilford', + 'Agfa', + 'CineStill', + 'Lomography', + 'Polaroid & Instant', + 'Rollei & Bergger', +]; diff --git a/lumenroom/src/lib/raw.ts b/lumenroom/src/lib/raw.ts new file mode 100644 index 0000000..1722622 --- /dev/null +++ b/lumenroom/src/lib/raw.ts @@ -0,0 +1,18 @@ +/** Raw containers the server can demosaic (LibRaw) or fall back to previews for. */ +export const RAW_EXTENSIONS = new Set([ + 'cr2', 'cr3', 'crw', + 'nef', 'nrw', + 'arw', 'srf', 'sr2', + 'orf', + 'rw2', 'raw', 'rwl', + 'raf', + 'pef', 'dng', + 'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', +]); + +export function isRawFile(file: File): boolean { + const ext = file.name.split('.').pop()?.toLowerCase() ?? ''; + return RAW_EXTENSIONS.has(ext); +} + +export const RAW_ACCEPT = [...RAW_EXTENSIONS].map((e) => `.${e}`).join(','); diff --git a/lumenroom/src/main.tsx b/lumenroom/src/main.tsx new file mode 100644 index 0000000..452fa06 --- /dev/null +++ b/lumenroom/src/main.tsx @@ -0,0 +1,7 @@ +import { createRoot } from 'react-dom/client'; +import App from './App'; +import './styles.css'; + +const root = document.getElementById('root'); +if (!root) throw new Error('root element missing'); +createRoot(root).render(); diff --git a/lumenroom/src/styles.css b/lumenroom/src/styles.css new file mode 100644 index 0000000..17a5062 --- /dev/null +++ b/lumenroom/src/styles.css @@ -0,0 +1,2139 @@ +/* Lumenroom — web photo library & develop module */ + +:root { + --bg: #0c0c0e; + --panel: #15151a; + --panel-2: #1b1b21; + --panel-3: #23232a; + --line: #2a2a32; + --text: #e8e8ec; + --muted: #8b8b96; + --accent: #5b9dff; + --accent-dim: #2c5f9e; + --danger: #e05d5d; + --radius: 7px; + color-scheme: dark; +} + +* { + box-sizing: border-box; +} + +html, +body, +#root { + height: 100%; + margin: 0; +} + +body { + background: var(--bg); + color: var(--text); + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, Roboto, Helvetica, Arial, sans-serif; + font-size: 13px; + -webkit-font-smoothing: antialiased; + overflow: hidden; +} + +button, +input, +select { + font: inherit; + color: inherit; +} + +button { + cursor: pointer; + border: none; + background: none; +} + +button:disabled { + cursor: default; + opacity: 0.45; +} + +img { + display: block; +} + +.muted { + color: var(--muted); +} + +.small { + font-size: 11.5px; +} + +.spacer { + flex: 1; +} + +/* ---------- buttons ---------- */ + +.btn { + border-radius: 6px; + padding: 7px 14px; + font-size: 12.5px; + font-weight: 550; + border: 1px solid transparent; + transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease; + white-space: nowrap; +} + +.btn.primary { + background: var(--accent); + color: #06121f; +} + +.btn.primary:hover:not(:disabled) { + background: #7cb1ff; +} + +.btn.ghost { + background: var(--panel-3); + border-color: var(--line); + color: var(--text); +} + +.btn.ghost:hover:not(:disabled) { + background: #2c2c35; +} + +.btn.ghost.on { + border-color: var(--accent); + color: var(--accent); +} + +.btn.ghost.danger:hover:not(:disabled) { + color: var(--danger); + border-color: #5c2b2b; +} + +.btn.small { + padding: 4px 9px; + font-size: 11.5px; +} + +.icon-btn { + width: 24px; + height: 24px; + border-radius: 5px; + color: var(--muted); + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 13px; +} + +.icon-btn:hover { + background: var(--panel-3); + color: var(--text); +} + +.icon-btn.danger:hover { + color: var(--danger); +} + +.link-btn { + color: var(--accent); + font-size: 11.5px; + padding: 0 2px; +} + +.link-btn:hover:not(:disabled) { + text-decoration: underline; +} + +/* ---------- shell ---------- */ + +.app { + display: flex; + flex-direction: column; + height: 100vh; + overflow: hidden; +} + +.app-body { + flex: 1; + min-height: 0; + display: flex; +} + +.main { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + overflow: hidden; +} + +.splash { + height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 10px; + color: var(--muted); +} + +.logo.large { + font-size: 30px; + letter-spacing: 0.16em; + text-transform: uppercase; + color: var(--text); +} + +.banner { + padding: 8px 14px; + font-size: 12px; +} + +.banner.error { + background: #3a1d1d; + color: #ffb4b4; + border-bottom: 1px solid #582929; +} + +.bridge-banner { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + background: #1d2a3a; + color: #cfe2ff; + border-bottom: 1px solid #324a66; +} + +.bridge-banner .banner-actions { + display: flex; + gap: 8px; +} + +.toast { + position: fixed; + bottom: 22px; + left: 50%; + transform: translateX(-50%); + background: #24242c; + border: 1px solid var(--line); + padding: 9px 16px; + border-radius: 999px; + font-size: 12.5px; + box-shadow: 0 12px 30px rgba(0, 0, 0, 0.5); + z-index: 100; +} + +.empty { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 12px; + color: var(--muted); +} + +/* ---------- topbar ---------- */ + +.topbar { + height: 50px; + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 18px; + padding: 0 14px; + background: var(--panel); + border-bottom: 1px solid var(--line); +} + +.brand { + display: flex; + align-items: center; + gap: 8px; + font-weight: 650; + letter-spacing: 0.04em; +} + +.brand .dot { + width: 9px; + height: 9px; + border-radius: 50%; + background: var(--accent); + box-shadow: 0 0 12px rgba(91, 157, 255, 0.8); +} + +.view-tabs { + display: flex; + background: var(--panel-2); + border-radius: 7px; + padding: 2px; + border: 1px solid var(--line); +} + +.view-tabs button { + padding: 5px 14px; + border-radius: 5px; + color: var(--muted); + font-size: 12.5px; +} + +.view-tabs button.active { + background: var(--panel-3); + color: var(--text); +} + +.topbar-title { + font-size: 12.5px; + font-weight: 550; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.topbar-actions { + margin-left: auto; + display: flex; + gap: 8px; +} + +/* ---------- sidebar ---------- */ + +.sidebar { + width: 218px; + flex: 0 0 auto; + background: var(--panel); + border-right: 1px solid var(--line); + display: flex; + flex-direction: column; + min-height: 0; +} + +.sidebar-head, +.dev-panel-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: 11px 12px; + font-size: 10.5px; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--muted); +} + +.new-event { + display: flex; + gap: 6px; + padding: 0 10px 10px; +} + +.new-event input, +.search, +.select, +.field input, +.field select { + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 6px; + padding: 6px 9px; + font-size: 12px; + min-width: 0; + outline: none; +} + +.new-event input:focus, +.search:focus, +.field input:focus, +.field select:focus { + border-color: var(--accent-dim); +} + +.new-event input { + flex: 1; +} + +.event-list { + flex: 1; + overflow-y: auto; + padding: 0 8px 12px; +} + +.event-item { + display: flex; + align-items: center; + border-radius: 6px; + margin-bottom: 2px; + padding-right: 4px; +} + +.event-item:hover { + background: var(--panel-2); +} + +.event-item.active { + background: var(--panel-3); +} + +.event-item.all { + width: 100%; + justify-content: space-between; +} + +.event-main { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 7px 9px; + text-align: left; +} + +.event-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12.5px; +} + +.event-count { + font-size: 11px; + color: var(--muted); + font-variant-numeric: tabular-nums; +} + +.event-tools { + display: none; + gap: 2px; +} + +.event-item:hover .event-tools { + display: flex; +} + +.sidebar-foot { + padding: 10px 12px; + border-top: 1px solid var(--line); + font-size: 10.5px; + line-height: 1.5; + color: var(--muted); +} + +/* ---------- filters ---------- */ + +.filterbar { + flex: 0 0 auto; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 14px; + padding: 9px 14px; + background: var(--panel-2); + border-bottom: 1px solid var(--line); +} + +.filter-group { + display: flex; + align-items: center; + gap: 7px; +} + +.filter-group.grow { + flex: 1; + min-width: 160px; +} + +.filter-label { + font-size: 10px; + letter-spacing: 0.1em; + text-transform: uppercase; + color: var(--muted); +} + +.rating-filter { + display: flex; + gap: 3px; +} + +.chip { + padding: 3px 8px; + border-radius: 5px; + background: var(--panel-3); + border: 1px solid transparent; + color: var(--muted); + font-size: 11.5px; + white-space: nowrap; +} + +.chip:hover { + color: var(--text); +} + +.chip.on { + border-color: var(--accent); + color: var(--accent); + background: rgba(91, 157, 255, 0.1); +} + +.chip.ghost { + background: transparent; + border-color: var(--line); +} + +.chip.small { + padding: 2px 7px; + font-size: 11px; +} + +.color-filter { + display: flex; + gap: 5px; +} + +.swatch { + width: 15px; + height: 15px; + border-radius: 4px; + border: 1px solid rgba(255, 255, 255, 0.16); + opacity: 0.55; +} + +.swatch:hover { + opacity: 1; +} + +.swatch.on { + opacity: 1; + border-color: #fff; + box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.18); +} + +.swatch-mini { + width: 12px; + height: 12px; + border-radius: 3px; + display: inline-block; +} + +.search { + width: 100%; +} + +.select { + padding: 4px 6px; +} + +.filter-count { + font-size: 11.5px; + color: var(--muted); + font-variant-numeric: tabular-nums; + margin-left: auto; +} + +/* ---------- grid ---------- */ + +.grid-area { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; +} + +.grid-toolbar { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 14px; + border-bottom: 1px solid var(--line); + min-height: 42px; +} + +.selection-count { + font-size: 12px; + font-weight: 600; + color: var(--accent); +} + +.grid { + flex: 1; + overflow-y: auto; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 12px; + padding: 14px; + align-content: start; +} + +.card { + margin: 0; + background: var(--panel); + border: 1px solid #1f1f25; + border-radius: 6px; + overflow: hidden; + cursor: pointer; + transition: border-color 0.1s ease, transform 0.1s ease; +} + +.card:hover { + border-color: #3a3a45; +} + +.card.selected { + border-color: var(--accent); + box-shadow: 0 0 0 1px var(--accent); +} + +.card.rejected { + opacity: 0.55; +} + +.card-thumb { + position: relative; + aspect-ratio: 4 / 3; + background: #101014; + overflow: hidden; +} + +.card-thumb img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.card-badges { + position: absolute; + top: 6px; + left: 6px; + display: flex; + gap: 4px; +} + +.badge { + width: 18px; + height: 18px; + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + font-size: 10px; + background: rgba(10, 10, 12, 0.75); +} + +.badge.pick { + color: #7ce08a; +} + +.badge.reject { + color: #ff8a8a; +} + +.badge.edit { + color: var(--accent); + margin-left: auto; +} + +.color-strip { + position: absolute; + left: 0; + bottom: 0; + width: 100%; + height: 3px; +} + +.card-hover { + position: absolute; + right: 7px; + bottom: 6px; + display: flex; + gap: 8px; + opacity: 0; + transition: opacity 0.12s ease; + background: rgba(8, 8, 10, 0.68); + padding: 2px 6px; + border-radius: 4px; +} + +.card:hover .card-hover { + opacity: 1; +} + +figcaption { + padding: 7px 8px 8px; +} + +.card-name { + font-size: 11.5px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + margin-bottom: 3px; +} + +.card-bottom { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; +} + +.card-cam { + font-size: 10px; + color: var(--muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 55%; +} + +.grid-empty { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + padding: 30px; +} + +.empty-card { + max-width: 420px; + text-align: center; + background: var(--panel); + border: 1px dashed var(--line); + border-radius: 12px; + padding: 32px; +} + +.empty-card h2 { + margin: 0 0 8px; + font-size: 18px; +} + +.empty-card p { + margin: 10px 0; + line-height: 1.55; +} + +/* ---------- stars / flags ---------- */ + +.stars { + display: inline-flex; + gap: 1px; +} + +.star { + color: #3d3d47; + font-size: 13px; + line-height: 1; + padding: 0 0.5px; + transition: color 0.08s ease; +} + +.star.on { + color: #f2c14e; +} + +.stars.md .star { + font-size: 16px; +} + +.stars.lg .star { + font-size: 20px; +} + +.flag-buttons { + display: flex; + gap: 3px; +} + +.flag-btn { + width: 24px; + height: 22px; + border-radius: 5px; + background: var(--panel-3); + color: #55555f; + font-size: 12px; +} + +.flag-btn.on.pick { + background: rgba(86, 178, 104, 0.18); + color: #7ce08a; +} + +.flag-btn.on.reject { + background: rgba(224, 82, 82, 0.16); + color: #ff9090; +} + +/* ---------- develop ---------- */ + +.develop { + flex: 1; + display: flex; + flex-direction: column; + min-height: 0; +} + +.dev-toolbar { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 8px; + padding: 7px 12px; + background: var(--panel); + border-bottom: 1px solid var(--line); + overflow-x: auto; +} + +.dev-title { + display: flex; + flex-direction: column; + min-width: 0; + margin-right: 6px; +} + +.dev-title strong { + font-size: 12.5px; + font-weight: 600; + max-width: 220px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dev-body { + flex: 1; + min-height: 0; + display: flex; +} + +.dev-left { + width: 208px; + flex: 0 0 auto; + background: var(--panel); + border-right: 1px solid var(--line); + overflow-y: auto; + display: flex; + flex-direction: column; +} + +.dev-right { + width: 324px; + flex: 0 0 auto; + background: var(--panel); + border-left: 1px solid var(--line); + display: flex; + flex-direction: column; + min-height: 0; +} + +.histo-wrap { + padding: 10px 12px 8px; + border-bottom: 1px solid var(--line); +} + +.histogram { + width: 100%; + height: 96px; + border-radius: 5px; + display: block; + border: 1px solid var(--line); +} + +.histo-legend { + display: flex; + justify-content: space-between; + margin-top: 6px; + font-size: 10.5px; + color: var(--muted); + font-variant-numeric: tabular-nums; +} + +.panel-scroll { + flex: 1; + overflow-y: auto; + min-height: 0; +} + +.canvas-stage { + flex: 1; + min-width: 0; + position: relative; + display: flex; + align-items: center; + justify-content: center; + background: #08080a; + overflow: hidden; + padding: 24px; +} + +.canvas-wrap { + position: relative; + display: inline-block; + line-height: 0; + box-shadow: 0 18px 60px rgba(0, 0, 0, 0.65); + background: #101013; +} + +.preview { + display: block; + max-width: 100%; +} + +.canvas-loading { + position: absolute; + color: var(--muted); + font-size: 12px; +} + +.before-badge { + position: absolute; + top: 14px; + left: 16px; + background: rgba(91, 157, 255, 0.18); + border: 1px solid var(--accent-dim); + color: var(--accent); + font-size: 10.5px; + letter-spacing: 0.1em; + text-transform: uppercase; + padding: 3px 8px; + border-radius: 4px; +} + +.crop-hint { + position: absolute; + bottom: 14px; + left: 50%; + transform: translateX(-50%); + background: rgba(18, 18, 22, 0.9); + border: 1px solid var(--line); + border-radius: 999px; + padding: 5px 14px; + font-size: 11.5px; + color: var(--muted); + white-space: nowrap; +} + +/* filmstrip */ + +.filmstrip { + flex: 0 0 auto; + height: 92px; + display: flex; + gap: 6px; + align-items: center; + padding: 8px 10px; + background: var(--panel); + border-top: 1px solid var(--line); + overflow-x: auto; + overflow-y: hidden; +} + +.film { + position: relative; + width: 108px; + height: 72px; + flex: 0 0 auto; + border-radius: 4px; + overflow: hidden; + /* An inset ring rather than a border keeps the picture area exactly 3:2, + which the orientation transform relies on. */ + box-shadow: inset 0 0 0 1px transparent; + background: #101014; + padding: 0; +} + +.film img { + width: 100%; + height: 100%; + object-fit: cover; + transform-origin: 50% 50%; +} + +.film.active { + box-shadow: inset 0 0 0 1px var(--accent), 0 0 0 1px var(--accent); +} + +.film-rating { + position: absolute; + bottom: 2px; + left: 3px; + font-size: 9px; + color: #f2c14e; + text-shadow: 0 1px 3px #000; +} + +/* ---------- panels ---------- */ + +.panel { + border-bottom: 1px solid var(--line); +} + +.panel-head { + display: flex; + align-items: center; + justify-content: space-between; + padding-right: 10px; +} + +.panel-toggle { + flex: 1; + display: flex; + align-items: center; + gap: 6px; + padding: 10px 12px; + font-size: 10.5px; + letter-spacing: 0.1em; + text-transform: uppercase; + color: #b9b9c4; + text-align: left; +} + +.panel-toggle:hover { + color: var(--text); +} + +.chev { + color: var(--muted); + font-size: 9px; + width: 9px; +} + +.panel-body { + padding: 2px 12px 14px; +} + +.subhead { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin: 12px 0 6px; + font-size: 10.5px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); +} + +.subhead:first-child { + margin-top: 2px; +} + +.row { + display: grid; + grid-template-columns: 74px 1fr 44px; + align-items: center; + gap: 7px; + padding: 2.5px 0; +} + +.row.disabled { + opacity: 0.4; + pointer-events: none; +} + +.row-label { + font-size: 11.5px; + color: #b7b7c2; + user-select: none; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.row-num { + width: 44px; + background: var(--panel-2); + border: 1px solid transparent; + border-radius: 4px; + padding: 2px 4px; + font-size: 11px; + text-align: right; + font-variant-numeric: tabular-nums; + outline: none; +} + +.row-num:focus { + border-color: var(--accent-dim); + background: #10101499; +} + +.row-range { + -webkit-appearance: none; + appearance: none; + width: 100%; + height: 4px; + border-radius: 3px; + background: var(--track, linear-gradient(90deg, var(--accent) 0 var(--pct, 50%), #33333c var(--pct, 50%) 100%)); + outline: none; +} + +.row-range::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 11px; + height: 11px; + border-radius: 50%; + background: #eaeaee; + border: 1px solid #0a0a0c; + cursor: ew-resize; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); +} + +.row-range::-moz-range-thumb { + width: 11px; + height: 11px; + border-radius: 50%; + background: #eaeaee; + border: 1px solid #0a0a0c; + cursor: ew-resize; +} + +.toggle { + display: flex; + align-items: center; + gap: 8px; + margin-top: 10px; + font-size: 12px; + color: #c9c9d2; + cursor: pointer; +} + +.toggle input { + accent-color: var(--accent); +} + +.tabs { + display: flex; + gap: 4px; + margin-bottom: 8px; +} + +.tab { + flex: 1; + padding: 3px 0; + border-radius: 4px; + background: var(--panel-2); + color: var(--muted); + font-size: 11px; +} + +.tab.on { + background: var(--panel-3); + color: var(--text); + box-shadow: inset 0 0 0 1px var(--line); +} + +.band-row { + display: flex; + gap: 4px; + margin-bottom: 8px; +} + +.band-swatch { + flex: 1; + height: 18px; + border-radius: 4px; + opacity: 0.6; + border: 1px solid transparent; +} + +.band-swatch.on { + opacity: 1; + border-color: #fff; + box-shadow: 0 0 0 1.5px rgba(255, 255, 255, 0.25); +} + +.band-title { + font-size: 11.5px; + color: var(--text); + margin-bottom: 4px; +} + +.aspect-grid { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-bottom: 10px; +} + +.btn-row { + display: flex; + gap: 6px; + margin-top: 10px; + flex-wrap: wrap; +} + +.meta { + margin: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +.meta-row { + display: flex; + gap: 8px; + font-size: 11.5px; +} + +.meta-row dt { + width: 78px; + flex: 0 0 auto; + color: var(--muted); +} + +.meta-row dd { + margin: 0; + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* presets / history */ + +.panel-stack { + border-bottom: 1px solid var(--line); +} + +.preset-group { + padding: 0 10px 8px; +} + +.preset-group-name { + font-size: 10px; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--muted); + margin: 6px 2px 4px; +} + +.preset-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 5px; +} + +.preset-tile { + display: flex; + flex-direction: column; + gap: 2px; + padding: 0; + overflow: hidden; + border-radius: 5px; + background: var(--panel-2); + border: 1px solid transparent; +} + +.preset-tile:hover { + border-color: var(--accent-dim); +} + +.preset-tile img, +.preset-tile-blank { + display: block; + width: 100%; + height: 52px; + object-fit: cover; + background: var(--panel-3); +} + +.preset-tile-name { + padding: 1px 4px 4px; + overflow: hidden; + font-size: 9px; + line-height: 1.15; + color: var(--muted); + text-overflow: ellipsis; + white-space: nowrap; +} + +.preset-tile:hover .preset-tile-name { + color: var(--text); +} + +.variant-row { + display: flex; + flex-wrap: wrap; + gap: 3px; + padding: 0 10px 7px; +} + +.variant-btn { + padding: 3px 7px; + border-radius: 999px; + border: 1px solid var(--line); + background: var(--panel-2); + color: var(--muted); + font-size: 10px; +} + +.variant-btn:hover { + color: var(--text); +} + +.variant-btn.on { + color: var(--text); + border-color: var(--accent-dim); + background: var(--panel-3); +} + +.history { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + border-bottom: none; +} + +.history-list { + flex: 1; + overflow-y: auto; + padding: 0 8px 10px; + min-height: 120px; +} + +.history-item { + width: 100%; + display: flex; + justify-content: space-between; + gap: 8px; + padding: 4px 7px; + border-radius: 4px; + font-size: 11px; + color: #b9b9c4; + text-align: left; +} + +.history-item:hover { + background: var(--panel-2); + color: var(--text); +} + +.history-label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* curve editor */ + +.curve-wrap { + margin-top: 4px; +} + +.curve { + width: 100%; + aspect-ratio: 1; + display: block; + border-radius: 5px; + cursor: crosshair; + touch-action: none; + background: #101014; + border: 1px solid var(--line); +} + +.curve-bg { + fill: transparent; +} + +.curve-grid { + stroke: rgba(255, 255, 255, 0.07); + stroke-width: 0.5; + vector-effect: non-scaling-stroke; +} + +.curve-diag { + stroke: rgba(255, 255, 255, 0.1); + stroke-width: 1; + stroke-dasharray: 2 3; + vector-effect: non-scaling-stroke; +} + +.curve-point { + stroke: #101014; + stroke-width: 0.8; + cursor: grab; + vector-effect: non-scaling-stroke; +} + +.curve-hint { + font-size: 10px; + color: var(--muted); + margin-top: 5px; + line-height: 1.4; +} + +/* crop overlay */ + +.crop-overlay { + position: absolute; + inset: 0; + overflow: hidden; + touch-action: none; + cursor: default; +} + +.crop-rect { + position: absolute; + border: 1px solid rgba(255, 255, 255, 0.9); + box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.55); + cursor: move; +} + +.crop-grid { + position: absolute; + inset: 0; + background-image: linear-gradient(to right, transparent 33.2%, rgba(255, 255, 255, 0.28) 33.2%, rgba(255, 255, 255, 0.28) 33.4%, transparent 33.4%, transparent 66.4%, rgba(255, 255, 255, 0.28) 66.4%, rgba(255, 255, 255, 0.28) 66.6%, transparent 66.6%), + linear-gradient(to bottom, transparent 33.2%, rgba(255, 255, 255, 0.28) 33.2%, rgba(255, 255, 255, 0.28) 33.4%, transparent 33.4%, transparent 66.4%, rgba(255, 255, 255, 0.28) 66.4%, rgba(255, 255, 255, 0.28) 66.6%, transparent 66.6%); + pointer-events: none; +} + +.handle { + position: absolute; + width: 16px; + height: 16px; + background: transparent; +} + +.handle::after { + content: ''; + position: absolute; + background: #fff; + border-radius: 1px; +} + +.handle.nw { left: -8px; top: -8px; cursor: nwse-resize; } +.handle.ne { right: -8px; top: -8px; cursor: nesw-resize; } +.handle.sw { left: -8px; bottom: -8px; cursor: nesw-resize; } +.handle.se { right: -8px; bottom: -8px; cursor: nwse-resize; } +.handle.n { left: 8px; right: 8px; top: -8px; height: 16px; cursor: ns-resize; } +.handle.s { left: 8px; right: 8px; bottom: -8px; height: 16px; cursor: ns-resize; } +.handle.w { top: 8px; bottom: 8px; left: -8px; width: 16px; cursor: ew-resize; } +.handle.e { top: 8px; bottom: 8px; right: -8px; width: 16px; cursor: ew-resize; } + +.handle.nw::after, +.handle.ne::after, +.handle.sw::after, +.handle.se::after { + inset: 5px; +} + +.handle.n::after { left: 50%; top: 6px; width: 22px; height: 3px; margin-left: -11px; } +.handle.s::after { left: 50%; bottom: 6px; width: 22px; height: 3px; margin-left: -11px; } +.handle.w::after { top: 50%; left: 6px; height: 22px; width: 3px; margin-top: -11px; } +.handle.e::after { top: 50%; right: 6px; height: 22px; width: 3px; margin-top: -11px; } + +.crop-size { + position: absolute; + bottom: 6px; + left: 6px; + font-size: 10px; + background: rgba(0, 0, 0, 0.6); + padding: 1px 5px; + border-radius: 3px; + color: #ddd; + pointer-events: none; +} + +/* ---------- modal ---------- */ + +.modal-backdrop { + position: fixed; + inset: 0; + background: rgba(4, 4, 6, 0.72); + display: flex; + align-items: center; + justify-content: center; + z-index: 60; + padding: 24px; +} + +.modal { + width: min(560px, 100%); + max-height: 88vh; + display: flex; + flex-direction: column; + background: var(--panel); + border: 1px solid var(--line); + border-radius: 12px; + box-shadow: 0 30px 80px rgba(0, 0, 0, 0.6); + overflow: hidden; +} + +.modal-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: 14px 16px; + border-bottom: 1px solid var(--line); +} + +.modal-head h2 { + margin: 0; + font-size: 15px; + font-weight: 600; +} + +.modal-body { + padding: 16px; + display: flex; + flex-direction: column; + gap: 12px; + overflow-y: auto; +} + +.field { + display: flex; + flex-direction: column; + gap: 5px; +} + +.field > span { + font-size: 10.5px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); +} + +.dropzone { + border: 1px dashed #3b3b46; + border-radius: 10px; + padding: 22px; + display: flex; + align-items: center; + gap: 14px; + cursor: pointer; + background: var(--panel-2); + transition: border-color 0.12s ease, background 0.12s ease; +} + +.dropzone.over { + border-color: var(--accent); + background: rgba(91, 157, 255, 0.07); +} + +.dropzone-icon { + font-size: 22px; + color: var(--muted); +} + +.dropzone p { + margin: 3px 0 0; + font-size: 11.5px; +} + +.file-summary { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 11.5px; + color: var(--muted); +} + +.progress-bar { + height: 4px; + border-radius: 3px; + background: var(--panel-3); + overflow: hidden; +} + +.progress-fill { + height: 100%; + background: var(--accent); + transition: width 0.15s linear; +} + +.progress .muted { + margin-top: 5px; +} + +.failures { + background: #2c1b1b; + border: 1px solid #4a2626; + border-radius: 8px; + padding: 10px 12px; + font-size: 11.5px; +} + +.failures ul { + margin: 6px 0 0; + padding-left: 16px; + color: #e6b3b3; +} + +.modal-foot { + display: flex; + justify-content: flex-end; + gap: 8px; + padding: 12px 16px; + border-top: 1px solid var(--line); + background: var(--panel-2); +} + +/* ---------- responsive ---------- */ + +@media (max-width: 1180px) { + .dev-left { + width: 176px; + } + .dev-right { + width: 288px; + } + .topbar-title .muted { + display: none; + } +} + +@media (max-width: 900px) { + .sidebar { + width: 168px; + } + .dev-left { + display: none; + } + .filterbar { + gap: 10px; + } +} + +/* ---------------------------------------------------------------- additions */ + +.module-bar { + display: flex; + gap: 2px; + margin-left: auto; + background: rgba(0, 0, 0, 0.25); + border: 1px solid #34343a; + border-radius: 7px; + padding: 2px; +} +.module-bar button { + border: 0; + background: transparent; + color: #9a9aa4; + font-size: 11.5px; + letter-spacing: 0.06em; + text-transform: uppercase; + padding: 5px 12px; + border-radius: 5px; + cursor: pointer; +} +.module-bar button:hover { color: #d8d8de; } +.module-bar button.active { + background: #3a3a42; + color: #fff; +} + +.cloud-pill { + display: inline-flex; + align-items: center; + gap: 6px; + height: 26px; + padding: 0 10px; + border-radius: 13px; + border: 1px solid #3a3a42; + background: #232329; + color: #a8a8b2; + font-size: 11.5px; + cursor: pointer; + max-width: 190px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.cloud-pill:hover { border-color: #4a4a55; color: #e6e6ea; } +.cloud-pill.on { color: #b9e3c1; border-color: #33543b; background: #1d2a20; } +.cloud-dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: #6b6b74; + flex: none; +} +.cloud-pill.on .cloud-dot { background: #58c774; box-shadow: 0 0 6px #58c77499; } + +.badge.raw { + background: #2a2a31; + color: #e0b45a; + border: 1px solid #4a3f28; + font-size: 8.5px; + letter-spacing: 0.08em; + padding: 2px 4px; +} + +.card.dragging { opacity: 0.45; } +.card.drop-target { + outline: 2px solid #5b9dd9; + outline-offset: -2px; + border-radius: 8px; +} +.card.drop-target::after { + content: ''; + position: absolute; + left: -7px; + top: 0; + bottom: 0; + width: 3px; + background: #5b9dd9; + border-radius: 2px; +} +.card { position: relative; } + +.event-item.drop { + outline: 1.5px dashed #5b9dd9; + outline-offset: -2px; + background: #24303a; +} +.sidebar-head.sub { margin-top: 10px; } +.catalog-links { display: flex; flex-direction: column; gap: 1px; } +.sidebar-hint { padding: 8px 12px; } + +.navigator-thumb { + padding: 8px 10px; + background: #131316; + border-bottom: 1px solid #2b2b31; + overflow: hidden; +} +.navigator-thumb img { + width: 100%; + aspect-ratio: 4 / 3; + object-fit: cover; + transform-origin: 50% 50%; + display: block; + background: #0d0d10; +} +.navigator-name { + padding: 6px 10px 0; + font-size: 11px; + color: #cfcfd6; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.navigator-meta { padding: 2px 10px 8px; } + +.rotate-row { margin-bottom: 10px; } +.btn.on { background: #33506e; border-color: #4a76a0; color: #fff; } + +.export-modal { width: 560px; } +.export-summary { + display: flex; + align-items: baseline; + gap: 10px; + padding: 9px 11px; + background: #1c1c21; + border: 1px solid #303038; + border-radius: 7px; + margin-bottom: 14px; +} +.field-row { display: flex; gap: 10px; align-items: flex-end; } +.field-row .field { flex: 1; margin-bottom: 12px; } +.field-row .field.narrow { flex: 0 0 96px; } + +.cloud-modal { width: 520px; } +.cloud-offline strong { display: block; margin-bottom: 6px; } +.code-block { + background: #16161a; + border: 1px solid #303038; + border-radius: 6px; + padding: 10px 12px; + font-size: 12px; + color: #c9c9d2; + overflow-x: auto; +} +.cloud-hero { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; } +.cloud-avatar { + width: 38px; + height: 38px; + border-radius: 50%; + background: #2f4a63; + color: #cfe6ff; + display: flex; + align-items: center; + justify-content: center; + font-weight: 600; +} +.cloud-stats { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1px; + background: #2b2b31; + border: 1px solid #2b2b31; + border-radius: 7px; + overflow: hidden; + margin: 0 0 14px; +} +.cloud-stats > div { background: #1a1a1f; padding: 9px 11px; } +.cloud-stats dt { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.05em; color: #83838d; } +.cloud-stats dd { margin: 3px 0 0; font-size: 13px; color: #e4e4e9; } +.cloud-foot { margin: 12px 0 0; } +.banner.ok { + background: #1c2a20; + border: 1px solid #33543b; + color: #a9dcb5; + padding: 8px 10px; + border-radius: 6px; + font-size: 12px; + margin-top: 10px; +} + +/* black & white contrast filters */ + +.bw-filters { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-bottom: 8px; +} + +.bw-filter { + padding: 3px 9px; + border-radius: 999px; + border: 1px solid var(--line); + background: var(--panel-2); + color: var(--muted); + font-size: 11px; +} + +.bw-filter:hover { + color: var(--text); + border-color: var(--panel-3); +} + +.bw-filter.on { + color: var(--text); + border-color: var(--accent-dim); + background: var(--panel-3); +} + +/* right-click context menu */ + +.ctx-menu { + position: fixed; + z-index: 120; + min-width: 218px; + padding: 5px; + border-radius: 8px; + background: rgba(23, 23, 28, 0.98); + border: 1px solid var(--line); + box-shadow: 0 20px 48px rgba(0, 0, 0, 0.62); + backdrop-filter: blur(10px); +} + +.ctx-header { + padding: 4px 6px 7px; + margin-bottom: 4px; + border-bottom: 1px solid var(--line); +} + +.ctx-rows { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} + +.ctx-sep { + height: 1px; + margin: 4px; + background: var(--line); +} + +.ctx-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 22px; + width: 100%; + padding: 6px 8px; + border-radius: 5px; + font-size: 12.5px; + text-align: left; + color: var(--text); +} + +.ctx-item:hover:not(:disabled) { + background: var(--panel-3); +} + +.ctx-item.danger { + color: var(--danger); +} + +.ctx-key { + color: var(--muted); + font-size: 11px; +} + +/* zoom controls */ + +.zoom-bar { + position: absolute; + right: 16px; + bottom: 12px; + z-index: 2; + display: flex; + align-items: center; + gap: 2px; + padding: 3px 6px 3px 4px; + border-radius: 999px; + background: rgba(18, 18, 22, 0.86); + border: 1px solid var(--line); + backdrop-filter: blur(8px); + opacity: 0; + transition: opacity 0.15s ease; +} + +.canvas-stage:hover .zoom-bar, +.zoom-bar:focus-within { + opacity: 1; +} + +.zoom-btn { + padding: 3px 9px; + border-radius: 999px; + font-size: 11px; + color: var(--muted); +} + +.zoom-btn:hover:not(:disabled) { + color: var(--text); + background: var(--panel-3); +} + +.zoom-btn.on { + color: var(--text); + background: var(--panel-3); +} + +.zoom-pct { + min-width: 40px; + padding-right: 2px; + text-align: right; + font-size: 11px; + color: var(--muted); + font-variant-numeric: tabular-nums; +} + +.canvas-stage.zoomed { + cursor: grab; +} + +.canvas-stage.zoomed.panning { + cursor: grabbing; +} + +.preview.zoomed { + max-width: none; + touch-action: none; + user-select: none; +} + +/* Live 1:1 grain loupe in the Effects panel. */ +.grain-patch { + margin: 12px 2px 4px; + display: flex; + flex-direction: column; + gap: 6px; +} +.grain-patch canvas { + width: 148px; + height: 100px; + display: block; + border-radius: 4px; + border: 1px solid #2c2c33; + background: #17171b; +} +.grain-patch span { + font-size: 10px; + color: #8a8a93; + letter-spacing: 0.02em; +} + +/* 100% detail patches inside the export dialog. */ +.export-detail { + display: flex; + gap: 10px; + margin: 12px 0 4px; +} +.export-detail figure { + margin: 0; +} +.export-detail canvas { + width: 132px; + display: block; + border-radius: 4px; + border: 1px solid #2c2c33; + background: #17171b; +} +.export-detail figcaption { + margin-top: 4px; + font-size: 10px; + line-height: 1.3; + color: #8a8a93; +} + +/* 1:1 grain loupe pinned inside the crop rectangle while cropping. */ +.crop-loupe { + position: absolute; + display: block; + border-radius: 3px; + border: 1px solid rgba(255, 255, 255, 0.4); + box-shadow: 0 3px 12px rgba(0, 0, 0, 0.55); + background: #17171b; + cursor: grab; + touch-action: none; + user-select: none; + z-index: 4; +} +.crop-loupe:active { + cursor: grabbing; +} + +/* Sample-point picker for the export detail patches. */ +.export-detail-pick { + display: flex; + gap: 8px; + align-items: flex-start; + margin: 10px 0 2px; +} +.export-detail-pick .pick-frame { + position: relative; + width: 132px; + cursor: crosshair; +} +.export-detail-pick canvas { + width: 132px; + display: block; + border-radius: 4px; + border: 1px solid #2c2c33; + background: #101014; +} +.export-detail-pick .pick-dot { + position: absolute; + width: 9px; + height: 9px; + margin: -5px 0 0 -5px; + border-radius: 50%; + border: 1px solid #fff; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.65); + pointer-events: none; +} +.export-detail-pick .hint { + font-size: 10px; + line-height: 1.4; + color: #8a8a93; +} + +/* Coordinates and grain scale under the export detail patches. */ +.export-detail-info { + margin: 6px 0 2px; + font-variant-numeric: tabular-nums; +} + +/* Grid thumbnails are rotated inline to the photo's current orientation. */ +.card-thumb img { + transform-origin: 50% 50%; +} + +/* Rubber-band selection over empty grid space. */ +.grid { + position: relative; +} +.marquee { + position: absolute; + border: 1px solid var(--accent); + background: rgba(91, 157, 217, 0.14); + border-radius: 2px; + pointer-events: none; + z-index: 3; +} + +/* Full-window drop target while files are dragged in from the desktop. */ +.drop-overlay { + position: fixed; + inset: 0; + z-index: 95; + display: grid; + place-items: center; + pointer-events: none; + background: rgba(9, 9, 12, 0.78); + box-shadow: inset 0 0 0 2px var(--accent); +} +.drop-overlay-inner { + padding: 22px 30px; + border: 1.5px dashed var(--accent); + border-radius: 10px; + background: rgba(18, 18, 23, 0.9); + color: #dfe8f3; + font-size: 14px; + line-height: 1.5; + text-align: center; +} +.drop-overlay-inner strong { display: block; font-size: 16px; } + +/* Keyboard shortcut reference. */ +.shortcuts-modal { + width: min(880px, 94vw); +} +.shortcut-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); + gap: 20px 30px; +} +.shortcut-grid h3 { + margin: 0 0 6px; + font-size: 10.5px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: #8b93a3; +} +.shortcut-row { + display: flex; + gap: 12px; + align-items: baseline; + padding: 4px 0; + border-bottom: 1px solid #1d1d23; + font-size: 12px; +} +.shortcut-keys { + flex: 0 0 118px; + color: #e2e8f2; + font-weight: 600; + font-variant-numeric: tabular-nums; +} +.shortcut-what { color: #98a2b3; } +.help-btn { + width: 26px; + height: 26px; + border-radius: 50%; + border: 1px solid #33333c; + font-weight: 700; +} + +/* Sits beside the ? button: opens the printable guide in a new tab. */ +.guide-btn { + display: inline-flex; + align-items: center; + height: 26px; + padding: 0 10px; + border-radius: 13px; + border: 1px solid #33333c; + background: transparent; + color: #c3c9d4; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.02em; + text-decoration: none; + white-space: nowrap; + transition: color 120ms ease, border-color 120ms ease, background 120ms ease; +} + +.guide-btn:hover { + color: #fff; + border-color: #4c8dff; + background: rgba(76, 141, 255, 0.1); +} diff --git a/lumenroom/src/types.ts b/lumenroom/src/types.ts new file mode 100644 index 0000000..c0adc8c --- /dev/null +++ b/lumenroom/src/types.ts @@ -0,0 +1,145 @@ +export type ViewMode = 'grid' | 'develop'; +export type Flag = 'none' | 'pick' | 'reject'; +export type ColorLabel = '' | 'red' | 'yellow' | 'green' | 'blue' | 'purple'; +/** Contrast filter placed over the lens when shooting black & white film. */ +export type BwFilter = 'none' | 'yellow' | 'orange' | 'red' | 'green' | 'blue'; +export type CurveChannel = 'rgb' | 'red' | 'green' | 'blue'; + +export interface CurvePoint { + x: number; + y: number; +} + +export interface CropState { + /** normalized crop rect inside the straightened frame, origin top-left */ + x: number; + y: number; + w: number; + h: number; + /** straighten angle in degrees */ + angle: number; + /** extra 90° turns applied before the straighten angle, 0–3 */ + quarter: number; + /** locked aspect preset id, "free" or "original" */ + aspect: string; + flipH: boolean; + flipV: boolean; +} + +export interface Edits { + temp: number; + tint: number; + exposure: number; + contrast: number; + highlights: number; + shadows: number; + whites: number; + blacks: number; + texture: number; + clarity: number; + dehaze: number; + vibrance: number; + saturation: number; + bw: boolean; + /** colored filter simulated in black & white mode */ + bwFilter: BwFilter; + /** how strongly that filter acts, 0–100 */ + bwFilterAmount: number; + curve: Record; + hsl: { hue: number[]; sat: number[]; lum: number[] }; + grading: { + shadows: { h: number; s: number }; + highlights: { h: number; s: number }; + balance: number; + }; + sharpen: { amount: number; radius: number; detail: number }; + noise: { luminance: number; detail: number }; + vignette: { amount: number; midpoint: number; feather: number }; + /** roughness leans from creamy clumps (0) to crisp per-pixel bite (100) */ + grain: { amount: number; size: number; roughness: number }; + crop: CropState; +} + +export interface PhotoMeta { + camera?: string; + lens?: string; + iso?: number; + aperture?: number; + shutter?: string; + focal?: number; +} + +export interface HistoryEntry { + label: string; + ts: number; + edits: Edits; +} + +export interface PhotoRecord { + id: string; + eventId: string; + /** manual sort position inside the event */ + order?: number; + name: string; + width: number; + height: number; + size: number; + mime: string; + addedAt: number; + takenAt?: number; + meta: PhotoMeta; + thumb: string; + rating: number; + flag: Flag; + color: ColorLabel; + keywords: string[]; + edits: Edits; + history: HistoryEntry[]; + /** true when the original is a camera raw decoded by the server */ + raw?: boolean; + /** how the editable proxy was produced */ + decode?: 'libraw' | 'embedded'; + /** server URL for the editable proxy (raw only) */ + previewUrl?: string; + /** server URL for the grid thumbnail */ + thumbUrl?: string; + /** Set when the photo is proxied from a dashboard bridge session. */ + bridgeSource?: { sessionId: string; sourceId: string }; +} + +export interface EventRecord { + id: string; + name: string; + date?: number; + createdAt: number; + notes?: string; + /** sidebar position */ + order?: number; + /** Set when this event is a temporary import from the dashboard bridge. */ + bridge?: { + sessionId: string; + sourceEventId: string; + /** Where "Back to dashboard" goes. */ + dashboardUrl: string; + expiresAt: number; + }; +} + +export interface Filters { + minRating: number; + flag: Flag | 'any'; + colors: ColorLabel[]; + text: string; + editedOnly: boolean; + unrated: boolean; +} + +export type SortKey = 'taken' | 'added' | 'name' | 'rating' | 'custom'; + +export interface Preset { + id: string; + name: string; + group: string; + edits: Partial>; + custom?: boolean; +} diff --git a/lumenroom/tsconfig.json b/lumenroom/tsconfig.json new file mode 100644 index 0000000..0ce3d47 --- /dev/null +++ b/lumenroom/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true + }, + "include": ["src", "vite.config.ts"] +} diff --git a/lumenroom/vite.config.ts b/lumenroom/vite.config.ts new file mode 100644 index 0000000..3a748df --- /dev/null +++ b/lumenroom/vite.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; + +/** Dev server proxies /api to the Lumenroom server on its default port. */ +const API_TARGET = 'http://127.0.0.1:8787'; + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + proxy: { + '/api': { target: API_TARGET, changeOrigin: false }, + }, + }, +}); diff --git a/src/app/api/bridge/sessions/[sessionId]/exchange/route.ts b/src/app/api/bridge/sessions/[sessionId]/exchange/route.ts new file mode 100644 index 0000000..bebf1a5 --- /dev/null +++ b/src/app/api/bridge/sessions/[sessionId]/exchange/route.ts @@ -0,0 +1,40 @@ +import { NextRequest } from "next/server"; +import { authenticateBridge } from "@/db/bridge"; +import { + BRIDGE_SESSION_TTL_SECONDS, + signBridgeToken, +} from "@/lib/bridge"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +/** + * POST /api/bridge/sessions/:sessionId/exchange + * + * The login token is deliberately short-lived because it travels in a URL. + * The editor exchanges it once for a service token it keeps server-side; that + * token authorizes the photo proxy and the save-back calls. + */ +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ sessionId: string }> }, +) => { + const { sessionId } = await params; + const auth = await authenticateBridge(req, sessionId, "login"); + if (!auth) return errorResponse(401, "invalid or expired bridge token"); + + const token = signBridgeToken({ + sid: auth.session.id, + eid: auth.session.eventId, + uid: auth.user.id, + email: auth.user.email, + name: auth.user.name, + kind: "service", + exp: Math.floor(Date.now() / 1000) + BRIDGE_SESSION_TTL_SECONDS, + }); + + return jsonResponse({ + token, + sessionId: auth.session.id, + eventId: auth.session.eventId, + expiresAt: auth.session.expiresAt, + }); +}; diff --git a/src/app/api/bridge/sessions/[sessionId]/photos/[photoId]/render/route.ts b/src/app/api/bridge/sessions/[sessionId]/photos/[photoId]/render/route.ts new file mode 100644 index 0000000..7772d97 --- /dev/null +++ b/src/app/api/bridge/sessions/[sessionId]/photos/[photoId]/render/route.ts @@ -0,0 +1,105 @@ +import { NextRequest } from "next/server"; +import { randomUUID } from "node:crypto"; +import { mkdir, rename, unlink, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { authenticateBridge, getBridgePhoto, saveBridgeRender } from "@/db/bridge"; +import { + editedStoredNameForEventPhoto, + eventPhotoPath, +} from "@/lib/event-photos"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; + +const MAX_BODY_BYTES = 64 * 1024 * 1024; +const MAX_RECIPE_BYTES = 512 * 1024; +const MAX_JPEG_BYTES = 48 * 1024 * 1024; + +/** + * POST /api/bridge/sessions/:sessionId/photos/:photoId/render + * Body: { jpeg: , edits: , 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. + */ +export const POST = async ( + req: NextRequest, + { + params, + }: { + params: Promise<{ sessionId: string; photoId: string }>; + }, +) => { + const { sessionId, photoId } = await params; + const auth = await authenticateBridge(req, sessionId); + if (!auth) return errorResponse(401, "invalid or expired bridge session"); + + if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) { + return errorResponse(413, "the rendered image is too large"); + } + + const photo = await getBridgePhoto(auth.session.eventId, photoId); + if (!photo) return errorResponse(404, "unknown photo"); + + const body = (await req.json().catch(() => null)) as + | { jpeg?: unknown; edits?: unknown } + | null; + if (!body || typeof body.jpeg !== "string") { + return errorResponse(400, "a base64 JPEG is required"); + } + + let data: Buffer; + try { + data = Buffer.from(body.jpeg, "base64"); + } catch { + return errorResponse(400, "the image could not be decoded"); + } + if (data.byteLength < 4 || data[0] !== 0xff || data[1] !== 0xd8) { + return errorResponse(400, "the image is not a JPEG"); + } + if (data.byteLength > MAX_JPEG_BYTES) { + return errorResponse(413, "the rendered image is too large"); + } + + const recipe = JSON.stringify(body.edits ?? {}); + if (recipe.length > MAX_RECIPE_BYTES) { + return errorResponse(413, "the edit recipe is too large"); + } + + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + + const storedName = editedStoredNameForEventPhoto( + auth.session.eventId, + photo.id, + ); + const target = eventPhotoPath(storage.root, storedName); + const temporary = `${target}.${randomUUID()}.tmp`; + try { + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(temporary, data); + await rename(temporary, target); + } catch { + await unlink(temporary).catch(() => undefined); + return errorResponse(500, "the edited image could not be saved"); + } + + const editedAt = await saveBridgeRender({ + photoId: photo.id, + editedStoredName: storedName, + editedSizeBytes: data.byteLength, + advancedEditJson: recipe, + editedBy: auth.user.id, + }); + if (!editedAt) { + await unlink(target).catch(() => undefined); + return errorResponse(404, "unknown photo"); + } + + return jsonResponse({ + ok: true, + editedAt, + editedSizeBytes: data.byteLength, + }); +}; diff --git a/src/app/api/bridge/sessions/[sessionId]/photos/[photoId]/source/route.ts b/src/app/api/bridge/sessions/[sessionId]/photos/[photoId]/source/route.ts new file mode 100644 index 0000000..579902f --- /dev/null +++ b/src/app/api/bridge/sessions/[sessionId]/photos/[photoId]/source/route.ts @@ -0,0 +1,165 @@ +import { NextRequest } from "next/server"; +import { randomUUID } from "node:crypto"; +import { createReadStream } from "node:fs"; +import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { Readable } from "node:stream"; +import sharp from "sharp"; +import { authenticateBridge, getBridgePhoto } from "@/db/bridge"; +import { + bridgeProxyStoredNameForEventPhoto, + bridgeThumbStoredNameForEventPhoto, + eventPhotoPath, +} from "@/lib/event-photos"; +import { errorResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; +import { defaultPhotoAdjustments } from "@/lib/photo-adjustments"; +import { renderPhotoJpeg } from "@/lib/photo-render"; + +const PROXY_MAX_EDGE = 4000; +const THUMB_MAX_EDGE = 480; + +function imageResponse(data: Buffer, contentType = "image/jpeg"): Response { + return new Response(new Uint8Array(data), { + status: 200, + headers: { + "content-type": contentType, + "content-length": String(data.byteLength), + "cache-control": "private, max-age=3600", + "x-content-type-options": "nosniff", + }, + }); +} + +/** Reads a cached derivative or writes it atomically on first use. */ +async function cached( + filePath: string, + produce: () => Promise, +): Promise { + try { + const info = await stat(filePath); + if (info.isFile() && info.size > 0) return readFile(filePath); + } catch { + // Not generated yet. + } + const data = await produce(); + await mkdir(path.dirname(filePath), { recursive: true }); + const temporary = `${filePath}.${randomUUID()}.tmp`; + await writeFile(temporary, data); + await rename(temporary, filePath); + return data; +} + +async function thumbFor(filePath: string, kind: "raw" | "image") { + 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(); +} + +/** + * GET /api/bridge/sessions/:sessionId/photos/:photoId/source?variant=original|proxy|thumb + * + * `original` streams the untouched bytes (the editor decodes RAW itself); + * `proxy` is a 4000 px JPEG, used when the editor only needs a browser image; + * `thumb` is a small grid preview. Derivatives are cached beside the original + * so repeated opens are free. + */ +export const GET = async ( + req: NextRequest, + { + params, + }: { + params: Promise<{ sessionId: string; photoId: string }>; + }, +) => { + const { sessionId, photoId } = await params; + const auth = await authenticateBridge(req, sessionId); + if (!auth) return errorResponse(401, "invalid or expired bridge session"); + + const photo = await getBridgePhoto(auth.session.eventId, photoId); + if (!photo) return errorResponse(404, "unknown photo"); + + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + + const originalPath = eventPhotoPath(storage.root, photo.storedName); + const variant = req.nextUrl.searchParams.get("variant") ?? "original"; + + if (variant === "original") { + let size: number; + try { + const info = await stat(originalPath); + if (!info.isFile()) throw new Error("missing"); + size = info.size; + } catch { + return errorResponse(404, "the file is missing from storage"); + } + const stream = createReadStream(originalPath); + return new Response( + Readable.toWeb(stream) as unknown as ReadableStream, + { + status: 200, + headers: { + "content-type": photo.mimeType || "application/octet-stream", + "content-length": String(size), + "content-disposition": "inline", + "cache-control": "private, max-age=3600", + "x-content-type-options": "nosniff", + }, + }, + ); + } + + if (variant === "thumb") { + try { + const thumbPath = eventPhotoPath( + storage.root, + bridgeThumbStoredNameForEventPhoto(auth.session.eventId, photo.id), + ); + const data = await cached(thumbPath, () => + thumbFor(originalPath, photo.kind), + ); + return imageResponse(data); + } catch { + return errorResponse(422, "the thumbnail could not be generated"); + } + } + + if (variant === "proxy") { + try { + const proxyPath = eventPhotoPath( + storage.root, + bridgeProxyStoredNameForEventPhoto(auth.session.eventId, photo.id), + ); + const data = await cached(proxyPath, async () => { + const rendered = await renderPhotoJpeg({ + filePath: originalPath, + kind: photo.kind, + adjustments: defaultPhotoAdjustments(), + maxDimension: PROXY_MAX_EDGE, + }); + return rendered.data; + }); + return imageResponse(data); + } catch { + return errorResponse(422, "the editable preview could not be generated"); + } + } + + return errorResponse(400, "unknown source variant"); +}; diff --git a/src/app/api/bridge/sessions/[sessionId]/route.ts b/src/app/api/bridge/sessions/[sessionId]/route.ts new file mode 100644 index 0000000..5328cb9 --- /dev/null +++ b/src/app/api/bridge/sessions/[sessionId]/route.ts @@ -0,0 +1,83 @@ +import { NextRequest } from "next/server"; +import { + authenticateBridge, + getBridgeEventSummary, + listBridgePhotos, +} from "@/db/bridge"; +import { bridgeReturnUrl } from "@/lib/bridge"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; +import { eventPhotoPath } from "@/lib/event-photos"; +import sharp from "sharp"; + +/** Reads the header dimensions without decoding the whole file. */ +async function imageSize( + path: string, +): Promise<{ width: number; height: number } | null> { + try { + const meta = await sharp(path).metadata(); + if (!meta.width || !meta.height) return null; + return { width: meta.width, height: meta.height }; + } catch { + return null; + } +} + +/** + * GET /api/bridge/sessions/:sessionId + * + * Everything the advanced editor needs to mirror one event: its title, dates + * and photo list. Photo bytes are fetched separately, one at a time, so opening + * a large event does not transfer gigabytes up front. + */ +export const GET = async ( + req: NextRequest, + { params }: { params: Promise<{ sessionId: string }> }, +) => { + const { sessionId } = await params; + const auth = await authenticateBridge(req, sessionId); + if (!auth) return errorResponse(401, "invalid or expired bridge session"); + + const event = await getBridgeEventSummary(auth.session.eventId); + if (!event) return errorResponse(404, "unknown event"); + + const rows = await listBridgePhotos(auth.session.eventId); + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + + // Dimensions are only known for browser images; RAW dimensions arrive with + // the proxy the editor builds from the original. + const sizes = new Map(); + for (const row of rows) { + if (row.kind !== "image") continue; + const size = await imageSize( + eventPhotoPath(storage.root, row.storedName), + ).catch(() => null); + if (size) sizes.set(row.id, size); + } + + return jsonResponse({ + session: { id: auth.session.id, expiresAt: auth.session.expiresAt }, + event: { + id: event.id, + title: event.title, + eventType: event.eventType, + startsAt: event.startsAt, + endsAt: event.endsAt, + location: event.location, + description: event.description, + }, + photos: rows.map((row) => ({ + id: row.id, + filename: row.filename, + mimeType: row.mimeType, + kind: row.kind, + sizeBytes: row.sizeBytes, + folderName: row.folderName, + width: sizes.get(row.id)?.width ?? 0, + height: sizes.get(row.id)?.height ?? 0, + takenAt: row.createdAt, + })), + editor: { returnUrl: bridgeReturnUrl(auth.session.eventId) }, + }); +}; diff --git a/src/app/api/events/[id]/advanced/route.ts b/src/app/api/events/[id]/advanced/route.ts new file mode 100644 index 0000000..b84a9b5 --- /dev/null +++ b/src/app/api/events/[id]/advanced/route.ts @@ -0,0 +1,63 @@ +import { NextRequest } from "next/server"; +import { gateSession } from "@/auth/api"; +import { bridgeUser, createBridgeSession } from "@/db/bridge"; +import { getEventAccess } from "@/db/events"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { + BRIDGE_LOGIN_TTL_SECONDS, + advancedEditorUrl, + bridgeConfigured, + bridgeReturnUrl, + signBridgeToken, +} from "@/lib/bridge"; + +/** + * POST /api/events/:id/advanced + * + * Opens a bridge session for the advanced editor and returns the one-time URL + * the browser should follow. Authorization happens here, once, with the normal + * dashboard session; the editor only ever sees the scoped token. + */ +export const POST = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + + if (!bridgeConfigured()) { + return errorResponse( + 503, + "the advanced editor is not configured; set BRIDGE_SECRET and LUMENROOM_URL", + ); + } + + const editor = advancedEditorUrl()!; + const user = await bridgeUser(gate.id); + if (!user) return errorResponse(401, "Authentication required"); + + const session = await createBridgeSession({ + userId: gate.id, + eventId: id, + }); + + const token = signBridgeToken({ + sid: session.id, + eid: id, + uid: gate.id, + email: user.email, + name: user.name, + kind: "login", + exp: Math.floor(Date.now() / 1000) + BRIDGE_LOGIN_TTL_SECONDS, + }); + + return jsonResponse({ + url: `${editor}/api/bridge/login?token=${encodeURIComponent(token)}`, + expiresAt: session.expiresAt, + returnUrl: bridgeReturnUrl(id), + }); +}; diff --git a/src/components/app/events/photo-viewer.tsx b/src/components/app/events/photo-viewer.tsx index 2431718..fc90531 100644 --- a/src/components/app/events/photo-viewer.tsx +++ b/src/components/app/events/photo-viewer.tsx @@ -14,6 +14,7 @@ import { Download, Loader2, RotateCcw, + Wand2, X, } from "lucide-react"; import { Button } from "@/components/ui/button"; @@ -407,6 +408,8 @@ export function PhotoViewer({ blue: number[]; } | null>(null); const [saving, setSaving] = useState(false); + const [advancedBusy, setAdvancedBusy] = useState(false); + const [advancedError, setAdvancedError] = useState(null); const [saveError, setSaveError] = useState(null); const [saveResult, setSaveResult] = useState<{ editedAt: string; @@ -605,6 +608,33 @@ export function PhotoViewer({ } } + async function openAdvanced() { + setAdvancedBusy(true); + setAdvancedError(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 (error) { + setAdvancedError( + error instanceof Error + ? error.message + : "The advanced editor could not be opened.", + ); + setAdvancedBusy(false); + } + } + async function save() { setSaving(true); setSaveError(null); @@ -696,6 +726,22 @@ export function PhotoViewer({ )}
+