This commit is contained in:
1 parent
ac219a8439
commit
8b01ae8b64
10 files changed
+413
-32
No files matched your search
+147
-13
@@ -17,7 +17,7 @@ let autoIds = 0;
|
||||
* Asks the render worker for automatic values computed from the open photo (tone, white balance, or the
|
||||
* eyedropper at a point of the uncropped frame). Resolves with control id -> value, ready for `develop.set`.
|
||||
*/
|
||||
export function engineAuto(key: string, kind: "tone" | "wb" | "pick", opts: { settings?: string; x?: number; y?: number } = {}): Promise<Record<string, number>> {
|
||||
export function engineAuto(key: string, kind: "tone" | "wb" | "pick" | "level", opts: { settings?: string; x?: number; y?: number } = {}): Promise<Record<string, number>> {
|
||||
const w = renderWorker();
|
||||
if (!w) return Promise.reject(new Error("no worker"));
|
||||
const id = ++autoIds;
|
||||
@@ -166,8 +166,40 @@ export function Viewer(props: ViewerProps) {
|
||||
return () => clearTimeout(settle.current);
|
||||
}, [opened, photoKey, settings, size.w, size.h, dragging, cropping, send, props.actualPixels]);
|
||||
|
||||
// 1:1: click and drag moves the photo (the hand tool), like Lightroom.
|
||||
const pan = useRef<{ x: number; y: number; left: number; top: number; id: number } | null>(null);
|
||||
const panning = !!props.actualPixels && !props.picking && !cropping;
|
||||
const panHandlers = panning
|
||||
? {
|
||||
onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (e.button !== 0 || !box.current) return;
|
||||
e.preventDefault();
|
||||
box.current.setPointerCapture(e.pointerId);
|
||||
pan.current = { x: e.clientX, y: e.clientY, left: box.current.scrollLeft, top: box.current.scrollTop, id: e.pointerId };
|
||||
box.current.style.cursor = "grabbing";
|
||||
},
|
||||
onPointerMove: (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
const p = pan.current;
|
||||
if (!p || !box.current) return;
|
||||
box.current.scrollLeft = p.left - (e.clientX - p.x);
|
||||
box.current.scrollTop = p.top - (e.clientY - p.y);
|
||||
},
|
||||
onPointerUp: (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!pan.current || !box.current) return;
|
||||
box.current.releasePointerCapture?.(e.pointerId);
|
||||
pan.current = null;
|
||||
box.current.style.cursor = "";
|
||||
},
|
||||
}
|
||||
: {};
|
||||
|
||||
return (
|
||||
<div ref={box} className={`relative flex h-full w-full ${props.actualPixels ? "overflow-auto" : "items-center justify-center overflow-hidden"}`}>
|
||||
<div
|
||||
ref={box}
|
||||
className={`relative flex h-full w-full ${props.actualPixels ? `overflow-auto select-none ${panning ? "cursor-grab" : ""}` : "items-center justify-center overflow-hidden"}`}
|
||||
{...panHandlers}
|
||||
onPointerCancel={panHandlers.onPointerUp}
|
||||
>
|
||||
<div className={`relative ${props.actualPixels ? "m-auto shrink-0" : ""}`} style={frame ? (props.actualPixels ? actualStyle(frame) : fitStyle(frame, size)) : { display: "none" }}>
|
||||
<canvas
|
||||
ref={canvas}
|
||||
@@ -202,35 +234,58 @@ function fitStyle(frame: { w: number; h: number }, box: { w: number; h: number }
|
||||
|
||||
type Handle = "move" | "nw" | "ne" | "sw" | "se" | "n" | "s" | "e" | "w";
|
||||
|
||||
/** Crop rectangle over the whole (uncropped) frame: drag inside to move, corners and edges to resize. */
|
||||
/**
|
||||
* Crop rectangle over the whole (uncropped) frame: drag on the photo to draw a new crop (in the chosen aspect),
|
||||
* drag inside the crop to move it, corners and edges to resize.
|
||||
*/
|
||||
function CropFrame({ crop, onCrop }: { crop: Crop; onCrop: (rect: Rect, final: boolean) => void }) {
|
||||
const el = useRef<HTMLDivElement>(null);
|
||||
const drag = useRef<{ handle: Handle; x: number; y: number; start: Rect } | null>(null);
|
||||
const drag = useRef<{ handle: Handle | "draw" | "pan"; x: number; y: number; start: Rect; drew: boolean } | null>(null);
|
||||
const r = crop.rect;
|
||||
const full = r.x0 <= 0 && r.y0 <= 0 && r.x1 >= 1 && r.y1 >= 1;
|
||||
|
||||
const onDown = (handle: Handle) => (e: React.PointerEvent) => {
|
||||
const ratioIn = (box: DOMRect) => (crop.aspect ? (crop.aspect[0] / crop.aspect[1]) * (box.height / box.width) : null);
|
||||
const onDown = (handle: Handle | "draw") => (e: React.PointerEvent) => {
|
||||
if (e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
(e.target as Element).setPointerCapture(e.pointerId);
|
||||
drag.current = { handle, x: e.clientX, y: e.clientY, start: { ...r } };
|
||||
el.current?.setPointerCapture(e.pointerId);
|
||||
// Ctrl/Cmd + drag: the photo moves under the crop. Nothing cropped yet: dragging anywhere draws the crop.
|
||||
const h = e.ctrlKey || e.metaKey ? "pan" : handle === "move" && full ? "draw" : handle;
|
||||
drag.current = { handle: h, x: e.clientX, y: e.clientY, start: { ...r }, drew: false };
|
||||
};
|
||||
const onMove = (e: React.PointerEvent) => {
|
||||
const d = drag.current;
|
||||
const box = el.current?.getBoundingClientRect();
|
||||
if (!d || !box) return;
|
||||
onCrop(moveRect(d.start, d.handle, (e.clientX - d.x) / box.width, (e.clientY - d.y) / box.height, crop.aspect ? (crop.aspect[0] / crop.aspect[1]) * (box.height / box.width) : null), false);
|
||||
if (d.handle === "draw") {
|
||||
const a = { x: (d.x - box.left) / box.width, y: (d.y - box.top) / box.height };
|
||||
const p = { x: (e.clientX - box.left) / box.width, y: (e.clientY - box.top) / box.height };
|
||||
const drawn = drawRect(a, p, ratioIn(box));
|
||||
if (!drawn) return;
|
||||
d.drew = true;
|
||||
onCrop(drawn, false);
|
||||
return;
|
||||
}
|
||||
const dx = (e.clientX - d.x) / box.width;
|
||||
const dy = (e.clientY - d.y) / box.height;
|
||||
// Panning drags the photo, so the crop goes the other way.
|
||||
if (d.handle === "pan") onCrop(moveRect(d.start, "move", -dx, -dy, null), false);
|
||||
else onCrop(moveRect(d.start, d.handle, dx, dy, ratioIn(box)), false);
|
||||
};
|
||||
const onUp = (e: React.PointerEvent) => {
|
||||
if (!drag.current) return;
|
||||
const d = drag.current;
|
||||
if (!d) return;
|
||||
drag.current = null;
|
||||
(e.target as Element).releasePointerCapture?.(e.pointerId);
|
||||
onCrop(r, true);
|
||||
el.current?.releasePointerCapture?.(e.pointerId);
|
||||
// A click without a drag leaves the crop as it was.
|
||||
onCrop(d.handle === "draw" && !d.drew ? d.start : r, true);
|
||||
};
|
||||
|
||||
const pct = (v: number) => `${v * 100}%`;
|
||||
const corner = "absolute h-3 w-3 border-2 border-white bg-black/40";
|
||||
return (
|
||||
<div ref={el} className="absolute inset-0 touch-none select-none" onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}>
|
||||
<div ref={el} className="absolute inset-0 cursor-crosshair touch-none select-none" onPointerDown={onDown("draw")} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}>
|
||||
{/* Shade outside the crop. */}
|
||||
<div className="pointer-events-none absolute bg-black/55" style={{ left: 0, top: 0, right: 0, height: pct(r.y0) }} />
|
||||
<div className="pointer-events-none absolute bg-black/55" style={{ left: 0, bottom: 0, right: 0, height: pct(1 - r.y1) }} />
|
||||
@@ -239,7 +294,7 @@ function CropFrame({ crop, onCrop }: { crop: Crop; onCrop: (rect: Rect, final: b
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Área de recorte"
|
||||
className="absolute cursor-move border border-white/90"
|
||||
className={`absolute border border-white/90 ${full ? "cursor-crosshair" : "cursor-move"}`}
|
||||
style={{ left: pct(r.x0), top: pct(r.y0), width: pct(r.x1 - r.x0), height: pct(r.y1 - r.y0) }}
|
||||
onPointerDown={onDown("move")}
|
||||
>
|
||||
@@ -303,6 +358,85 @@ export function moveRect(start: Rect, handle: Handle, dx: number, dy: number, ra
|
||||
return { x0, y0, x1, y1 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The crop drawn by dragging from `a` to `p` (fractions of the frame), kept inside the frame. `ratio` is the
|
||||
* locked width/height in frame fractions (null: free). Null while the drag is still too small to be a crop.
|
||||
* Exported for tests.
|
||||
*/
|
||||
export function drawRect(a: { x: number; y: number }, p: { x: number; y: number }, ratio: number | null): Rect | null {
|
||||
const ax = clamp01(a.x);
|
||||
const ay = clamp01(a.y);
|
||||
const sx = p.x >= ax ? 1 : -1;
|
||||
const sy = p.y >= ay ? 1 : -1;
|
||||
// Room from the anchor to the frame edge in the drag direction.
|
||||
const roomX = sx > 0 ? 1 - ax : ax;
|
||||
const roomY = sy > 0 ? 1 - ay : ay;
|
||||
let w = Math.min(Math.abs(p.x - ax), roomX);
|
||||
let h = Math.min(Math.abs(p.y - ay), roomY);
|
||||
if (ratio) {
|
||||
// The larger side of the drag decides the size; then shrink to fit the frame.
|
||||
if (w / ratio >= h) h = w / ratio;
|
||||
else w = h * ratio;
|
||||
if (w > roomX) {
|
||||
w = roomX;
|
||||
h = w / ratio;
|
||||
}
|
||||
if (h > roomY) {
|
||||
h = roomY;
|
||||
w = h * ratio;
|
||||
}
|
||||
}
|
||||
if (w < MIN || h < MIN) return null;
|
||||
const x0 = sx > 0 ? ax : ax - w;
|
||||
const y0 = sy > 0 ? ay : ay - h;
|
||||
return { x0, y0, x1: x0 + w, y1: y0 + h };
|
||||
}
|
||||
|
||||
/** Whether every corner of `r` (normalized, in the frame rotated by `angle` degrees) lies on a `w`×`h` photo. */
|
||||
export function insideRotated(r: Rect, angle: number, w: number, h: number): boolean {
|
||||
const a = (-angle * Math.PI) / 180;
|
||||
const [c, s] = [Math.cos(a), Math.sin(a)];
|
||||
const eps = 1e-6;
|
||||
return [
|
||||
[r.x0, r.y0],
|
||||
[r.x1, r.y0],
|
||||
[r.x0, r.y1],
|
||||
[r.x1, r.y1],
|
||||
].every(([nx, ny]) => {
|
||||
const px = nx! * w - w / 2;
|
||||
const py = ny! * h - h / 2;
|
||||
const qx = px * c - py * s + w / 2;
|
||||
const qy = px * s + py * c + h / 2;
|
||||
return qx >= -eps * w && qy >= -eps * h && qx <= w * (1 + eps) && qy <= h * (1 + eps);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The crop kept on the photo when it is straightened by `angle` (Lightroom's "constrain to image"): moved
|
||||
* towards the centre first, then shrunk about the centre keeping its shape. `w`×`h` is the photo's size.
|
||||
*/
|
||||
export function constrainRotated(r: Rect, angle: number, w: number, h: number): Rect {
|
||||
if (insideRotated(r, angle, w, h)) return r;
|
||||
const cx = (r.x0 + r.x1) / 2;
|
||||
const cy = (r.y0 + r.y1) / 2;
|
||||
const rw = r.x1 - r.x0;
|
||||
const rh = r.y1 - r.y0;
|
||||
for (let i = 1; i <= 32; i++) {
|
||||
const t = i / 32;
|
||||
const nx = cx + (0.5 - cx) * t;
|
||||
const ny = cy + (0.5 - cy) * t;
|
||||
const cand = { x0: nx - rw / 2, y0: ny - rh / 2, x1: nx + rw / 2, y1: ny + rh / 2 };
|
||||
if (insideRotated(cand, angle, w, h)) return cand;
|
||||
}
|
||||
// Largest scale that fits, centred (half extents in pixels against the rotated photo).
|
||||
const a = Math.abs((angle * Math.PI) / 180);
|
||||
const [sn, cs] = [Math.sin(a), Math.cos(a)];
|
||||
const hx = (rw * w) / 2;
|
||||
const hy = (rh * h) / 2;
|
||||
const k = Math.min(1, w / 2 / (hx * cs + hy * sn), h / 2 / (hx * sn + hy * cs));
|
||||
return { x0: 0.5 - (rw * k) / 2, y0: 0.5 - (rh * k) / 2, x1: 0.5 + (rw * k) / 2, y1: 0.5 + (rh * k) / 2 };
|
||||
}
|
||||
|
||||
/** The largest rect of `ratio` (width/height in frame fractions) centred on `r`, inside the frame. */
|
||||
export function fitAspect(r: Rect, ratio: number): Rect {
|
||||
const cx = (r.x0 + r.x1) / 2;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { constrainRotated, drawRect, insideRotated, moveRect } from "./Viewer.js";
|
||||
|
||||
const close = (a: number, b: number) => expect(Math.abs(a - b)).toBeLessThan(1e-6);
|
||||
|
||||
describe("drawing a crop by dragging", () => {
|
||||
it("free: the rectangle between the two points, whichever way the drag goes", () => {
|
||||
expect(drawRect({ x: 0.2, y: 0.3 }, { x: 0.6, y: 0.8 }, null)).toEqual({ x0: 0.2, y0: 0.3, x1: 0.6, y1: 0.8 });
|
||||
const up = drawRect({ x: 0.6, y: 0.8 }, { x: 0.2, y: 0.3 }, null)!;
|
||||
close(up.x0, 0.2);
|
||||
close(up.y0, 0.3);
|
||||
close(up.x1, 0.6);
|
||||
close(up.y1, 0.8);
|
||||
});
|
||||
|
||||
it("locked aspect: the longer side of the drag sets the size, kept inside the frame", () => {
|
||||
const r = drawRect({ x: 0.1, y: 0.1 }, { x: 0.5, y: 0.2 }, 2)!;
|
||||
close(r.x1 - r.x0, 0.4);
|
||||
close(r.y1 - r.y0, 0.2);
|
||||
// Dragging past the bottom edge: it shrinks to fit, still at the ratio.
|
||||
const edge = drawRect({ x: 0.1, y: 0.8 }, { x: 0.9, y: 0.95 }, 2)!;
|
||||
close(edge.y1, 1);
|
||||
close((edge.x1 - edge.x0) / (edge.y1 - edge.y0), 2);
|
||||
});
|
||||
|
||||
it("a click (no real drag) draws nothing", () => {
|
||||
expect(drawRect({ x: 0.5, y: 0.5 }, { x: 0.51, y: 0.5 }, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("panning the photo under the crop", () => {
|
||||
it("moves the crop the other way, without leaving the frame", () => {
|
||||
const start = { x0: 0.2, y0: 0.2, x1: 0.6, y1: 0.6 };
|
||||
// The pan handler passes the negated drag to the "move" handle.
|
||||
const r = moveRect(start, "move", -0.1, -0.05, null);
|
||||
close(r.x0, 0.1);
|
||||
close(r.y0, 0.15);
|
||||
expect(moveRect(start, "move", -0.5, 0, null).x0).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("straightening keeps the crop on the photo", () => {
|
||||
it("leaves a crop that already fits alone", () => {
|
||||
const r = { x0: 0.3, y0: 0.3, x1: 0.7, y1: 0.7 };
|
||||
expect(constrainRotated(r, 5, 6000, 4000)).toBe(r);
|
||||
});
|
||||
|
||||
it("shrinks the full frame when the photo is rotated, keeping its shape", () => {
|
||||
const full = { x0: 0, y0: 0, x1: 1, y1: 1 };
|
||||
expect(insideRotated(full, 4, 6000, 4000)).toBe(false);
|
||||
const r = constrainRotated(full, 4, 6000, 4000);
|
||||
expect(insideRotated(r, 4, 6000, 4000)).toBe(true);
|
||||
close((r.x1 - r.x0) / (r.y1 - r.y0), 1);
|
||||
close((r.x0 + r.x1) / 2, 0.5);
|
||||
expect(r.x1 - r.x0).toBeGreaterThan(0.8);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ export interface WasmPhoto {
|
||||
/** JSON object of control id -> value. */
|
||||
autoTone(settings: string): string;
|
||||
autoWb(): string;
|
||||
autoLevel(settings: string): string;
|
||||
wbAt(x: number, y: number): string;
|
||||
pixels(): Uint8Array;
|
||||
free(): void;
|
||||
@@ -68,7 +69,7 @@ export type WorkerRequest =
|
||||
| { type: "open"; key: string; url: string; bytes?: ArrayBuffer; maxEdge?: number }
|
||||
| { type: "render"; ticket: number; key: string; settings: string; maxW: number; maxH: number; draft: boolean; applyCrop: boolean }
|
||||
/** Auto values from the photo itself: tone (under `settings`), white balance, or the eyedropper at x, y. */
|
||||
| { type: "auto"; id: number; key: string; kind: "tone" | "wb" | "pick"; settings?: string; x?: number; y?: number };
|
||||
| { type: "auto"; id: number; key: string; kind: "tone" | "wb" | "pick" | "level"; settings?: string; x?: number; y?: number };
|
||||
|
||||
export type WorkerReply =
|
||||
| { type: "opened"; key: string; sourceWidth: number; sourceHeight: number }
|
||||
|
||||
@@ -46,7 +46,14 @@ self.onmessage = async (e: MessageEvent<WorkerRequest>) => {
|
||||
if (msg.type === "auto") {
|
||||
try {
|
||||
if (!photo) throw new Error("photo not open");
|
||||
const json = msg.kind === "tone" ? photo.autoTone(msg.settings ?? "{}") : msg.kind === "wb" ? photo.autoWb() : photo.wbAt(msg.x ?? 0.5, msg.y ?? 0.5);
|
||||
const json =
|
||||
msg.kind === "tone"
|
||||
? photo.autoTone(msg.settings ?? "{}")
|
||||
: msg.kind === "wb"
|
||||
? photo.autoWb()
|
||||
: msg.kind === "level"
|
||||
? photo.autoLevel(msg.settings ?? "{}")
|
||||
: photo.wbAt(msg.x ?? 0.5, msg.y ?? 0.5);
|
||||
post({ type: "auto", id: msg.id, values: JSON.parse(json) as Record<string, number> });
|
||||
} catch (err) {
|
||||
post({ type: "auto", id: msg.id, message: err instanceof Error ? err.message : String(err) });
|
||||
|
||||
@@ -40,7 +40,7 @@ export const t = {
|
||||
noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.",
|
||||
filter: "Filtro",
|
||||
filters: { all: "Todas", PICK: "Escolhidas", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas", stars: "★ 3+", noPlayers: "Sem jogador" },
|
||||
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · Enter lupa · Esc grelha · D revelar",
|
||||
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · E/Enter lupa · G/Esc grelha · D revelar",
|
||||
selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`),
|
||||
ofTotal: (n: number, total: number) => `${n} de ${total}`,
|
||||
players: "Jogadores",
|
||||
@@ -356,12 +356,17 @@ export const t = {
|
||||
aspect: "Proporção",
|
||||
aspectFree: "Livre",
|
||||
aspectOriginal: "Original",
|
||||
cropHelp: "A proporção escolhida fica por defeito nas fotos seguintes. Arrasta sobre a foto para desenhar o recorte; Ctrl/Cmd + arrastar move a foto dentro dele.",
|
||||
level: "Nivelar",
|
||||
levelHelp: "Endireita a foto pelo horizonte ou pelas linhas verticais (como o Auto do Lightroom).",
|
||||
levelNone: "Não encontrei horizonte nem linhas verticais claras nesta foto: endireita com o ângulo.",
|
||||
flagState: "Marcação",
|
||||
straighten: "Endireitar",
|
||||
copy: "Copiar ajustes",
|
||||
paste: "Colar ajustes",
|
||||
pasted: (n: number) => `Ajustes colados em ${n} ${n === 1 ? "foto" : "fotos"}`,
|
||||
noAccess: "Só podes revelar fotos que enviaste.",
|
||||
shortcuts: "← → foto · \\ antes/depois · R recortar · W conta-gotas · Z 1:1 · Ctrl+Z anular · Ctrl+Shift+Z refazer · duplo clique num cursor repõe",
|
||||
shortcuts: "← → foto · P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · G grelha · \\ antes/depois · R recortar · W conta-gotas · Z 1:1 (arrastar move) · Ctrl+Z anular",
|
||||
groups: { wb: "Equilíbrio de brancos", tone: "Tom", presence: "Presença", profile: "Perfil" },
|
||||
labels: {
|
||||
"profile.amount": "Intensidade",
|
||||
|
||||
@@ -30,6 +30,7 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
|
||||
<button
|
||||
ref={ref}
|
||||
type="button"
|
||||
data-photo-id={photo.id}
|
||||
onClick={(e) => onPick(photo.id, e)}
|
||||
onDoubleClick={() => onOpen(photo.id)}
|
||||
aria-pressed={selected}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { CONTROLS, DEFAULT_MODULES, type EditCommand, type LibraryMessage, type PhotoSummary } from "@photoreport/contracts";
|
||||
import { CONTROLS, DEFAULT_MODULES, type EditCommand, type LibraryMessage, type PhotoPatch, type PhotoSummary } from "@photoreport/contracts";
|
||||
import { hasRole } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { type EngineModule, loadEngine } from "../develop/engine.js";
|
||||
import { DevelopPanels, Section, Slider } from "../develop/Panels.js";
|
||||
import { cropOf, DevelopSession, localOutbox } from "../develop/session.js";
|
||||
import { engineAuto, fitAspect, Viewer } from "../develop/Viewer.js";
|
||||
import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/session.js";
|
||||
import { constrainRotated, engineAuto, fitAspect, Viewer } from "../develop/Viewer.js";
|
||||
import { applyPatch, patchForKey } from "../library/store.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { isDesktop, localOriginal, prefs } from "../platform.js";
|
||||
@@ -26,6 +27,19 @@ const ASPECTS: { label: string; value: [number, number] | "original" | null }[]
|
||||
];
|
||||
|
||||
const CLIPBOARD = "develop.clipboard";
|
||||
/** The aspect a new crop starts with (the last one chosen): "free", "original" or "W:H". Lightroom's default is the original. */
|
||||
const CROP_ASPECT = "develop.cropAspect";
|
||||
type AspectChoice = (typeof ASPECTS)[number]["value"];
|
||||
function defaultAspect(): AspectChoice {
|
||||
const v = prefs.get(CROP_ASPECT) ?? "original";
|
||||
if (v === "free") return null;
|
||||
if (v === "original") return "original";
|
||||
const [w, h] = v.split(":").map(Number);
|
||||
return w && h ? [w, h] : "original";
|
||||
}
|
||||
function saveDefaultAspect(choice: AspectChoice) {
|
||||
prefs.set(CROP_ASPECT, choice === null ? "free" : choice === "original" ? "original" : `${choice[0]}:${choice[1]}`);
|
||||
}
|
||||
|
||||
/** Controls a "copy settings" carries: everything numeric except the crop, which belongs to each photo. */
|
||||
export function copyableValues(value: (id: string) => number): Record<string, number> {
|
||||
@@ -109,6 +123,9 @@ export function DevelopPage() {
|
||||
if (m.type === "photo.edited") {
|
||||
if (session && m.photoId === session.photoId) void session.remote(m);
|
||||
setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p)));
|
||||
} else if (m.type === "photo.updated") {
|
||||
const ids = new Set(m.ids);
|
||||
setPhotos((list) => list.map((p) => (ids.has(p.id) ? applyPatch(p, m.patch) : p)));
|
||||
} else if (m.type === "photo.rendered") {
|
||||
setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)));
|
||||
}
|
||||
@@ -121,6 +138,22 @@ export function DevelopPage() {
|
||||
if (live === "live" && session?.loaded) void session.catchUp();
|
||||
}, [live, session]);
|
||||
|
||||
// Lightroom's culling keys work here too: P pick, X reject, U unflag, 0–5 stars, 6–9 colour.
|
||||
const canCull = !!role && hasRole(role, "INGESTER");
|
||||
const flagCurrent = useCallback(
|
||||
(change: PhotoPatch) => {
|
||||
if (!current || !canCull) return;
|
||||
const patch = { ...change };
|
||||
if (patch.colorLabel && current.colorLabel === patch.colorLabel) patch.colorLabel = "NONE";
|
||||
setPhotos((list) => list.map((p) => (p.id === current.id ? applyPatch(p, patch) : p)));
|
||||
api.updatePhotos(orgId, [current.id], patch).catch(() => {
|
||||
setNote(t.unexpectedError);
|
||||
setPhotos((list) => list.map((p) => (p.id === current.id ? current : p)));
|
||||
});
|
||||
},
|
||||
[api, orgId, current, canCull],
|
||||
);
|
||||
|
||||
const index = current ? photos.findIndex((p) => p.id === current.id) : -1;
|
||||
const go = useCallback(
|
||||
(delta: number) => {
|
||||
@@ -150,6 +183,11 @@ export function DevelopPage() {
|
||||
} else if (e.key === "ArrowRight") go(1);
|
||||
else if (e.key === "ArrowLeft") go(-1);
|
||||
else if (e.key === "\\") setBefore((b) => !b);
|
||||
else if (!mod && !e.altKey && e.key.toLowerCase() === "g") navigate("/", { state: { focus: current?.id } });
|
||||
else if (!mod && !e.altKey && patchForKey(e.key)) {
|
||||
e.preventDefault();
|
||||
flagCurrent(patchForKey(e.key)!);
|
||||
}
|
||||
else if (e.key.toLowerCase() === "r" && canEdit) setCropping((c) => !c);
|
||||
else if (e.key.toLowerCase() === "w" && canEdit) setPicking((p) => !p);
|
||||
else if (e.key.toLowerCase() === "z") setOneToOne((z) => !z);
|
||||
@@ -160,7 +198,7 @@ export function DevelopPage() {
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [session, go, canEdit]);
|
||||
}, [session, go, canEdit, navigate, current?.id, flagCurrent]);
|
||||
|
||||
const settings = session?.loaded ? session.settings : null;
|
||||
const crop = useMemo(() => (settings ? cropOf(settings) : { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null }), [settings]);
|
||||
@@ -207,6 +245,35 @@ export function DevelopPage() {
|
||||
return null;
|
||||
}
|
||||
}, [api, current]);
|
||||
// Straightening keeps the crop on the photo (shrinks it if needed), from where it was when the gesture began.
|
||||
const angleStart = useRef<Crop["rect"] | null>(null);
|
||||
const setAngle = useCallback(
|
||||
(angle: number, final: boolean) => {
|
||||
if (!session?.loaded || !sourceSize) return;
|
||||
const c = cropOf(session.settings);
|
||||
angleStart.current ??= c.rect;
|
||||
const rect = constrainRotated(angleStart.current, angle, sourceSize.w, sourceSize.h);
|
||||
setDragging(!final);
|
||||
session.edit({ command: "crop.set", params: { rect, angle, aspect: c.aspect } }, "crop.angle");
|
||||
if (final) {
|
||||
angleStart.current = null;
|
||||
session.endGesture();
|
||||
}
|
||||
},
|
||||
[session, sourceSize],
|
||||
);
|
||||
const autoLevel = useCallback(async () => {
|
||||
if (!session?.loaded || !current) return;
|
||||
try {
|
||||
const values = await engineAuto(current.id, "level", { settings: session.settings });
|
||||
if (values["crop.angle"] === undefined) return setNote(t.dev.levelNone);
|
||||
setNote(null);
|
||||
setAngle(values["crop.angle"], true);
|
||||
} catch (err) {
|
||||
setNote((err as Error).message);
|
||||
}
|
||||
}, [session, current, setAngle]);
|
||||
|
||||
const autoValues = useCallback(
|
||||
async (kind: "tone" | "wb" | "pick", at?: { x: number; y: number }) => {
|
||||
if (!session?.loaded || !current) return;
|
||||
@@ -231,15 +298,27 @@ export function DevelopPage() {
|
||||
const src = sourceSize ? sourceSize.w / sourceSize.h : 1.5;
|
||||
return aspect[0] / aspect[1] / src;
|
||||
};
|
||||
const setAspect = (choice: (typeof ASPECTS)[number]["value"]) => {
|
||||
const setAspect = (choice: AspectChoice, remember = true) => {
|
||||
if (!session || !sourceSize) return;
|
||||
const aspect: [number, number] | null = choice === "original" ? [sourceSize.w, sourceSize.h] : choice;
|
||||
const ratio = frameRatio(aspect);
|
||||
const rect = ratio ? fitAspect(crop.rect, ratio) : crop.rect;
|
||||
session.edit({ command: "crop.set", params: { rect, angle: crop.angle, aspect } });
|
||||
session.endGesture();
|
||||
if (remember) saveDefaultAspect(choice);
|
||||
};
|
||||
|
||||
// Entering crop on a photo that was never cropped: it starts with the default aspect (the last one chosen).
|
||||
const defaulted = useRef(new Set<string>());
|
||||
useEffect(() => {
|
||||
if (!cropping || !current || !session?.loaded || !sourceSize || defaulted.current.has(current.id)) return;
|
||||
defaulted.current.add(current.id);
|
||||
const r = crop.rect;
|
||||
const untouched = !crop.aspect && r.x0 <= 0 && r.y0 <= 0 && r.x1 >= 1 && r.y1 >= 1;
|
||||
const choice = defaultAspect();
|
||||
if (untouched && choice !== null) setAspect(choice, false);
|
||||
}); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
if (!organization) return <p className="p-6 text-sm text-muted">{t.noAccess}</p>;
|
||||
|
||||
const status = !session?.loaded ? "" : session.offline ? t.dev.offline : session.hasPending ? t.dev.saving : t.dev.saved;
|
||||
@@ -252,6 +331,12 @@ export function DevelopPage() {
|
||||
<div className="flex min-h-[60vh] min-w-0 flex-1 flex-col bg-[#121213] lg:min-h-0">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
|
||||
<span className="truncate font-mono text-[11px] text-faint">{current ? `${current.originalName} · ${index + 1}/${photos.length}` : ""}</span>
|
||||
{current && (
|
||||
<span className="text-[12px] text-ink" aria-label={t.dev.flagState}>
|
||||
{current.flag === "PICK" ? "⚑ " : current.flag === "REJECT" ? "✕ " : ""}
|
||||
{current.rating > 0 ? "★".repeat(current.rating) : ""}
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto flex items-center gap-2">
|
||||
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}>
|
||||
{t.dev.undo}
|
||||
@@ -341,14 +426,27 @@ export function DevelopPage() {
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="mb-2 text-[11px] text-faint">{t.dev.cropHelp}</p>
|
||||
{angle && (
|
||||
<Slider
|
||||
control={{ ...angle, min: -45, max: 45 }}
|
||||
value={session?.loaded ? session.value("crop.angle") : 0}
|
||||
disabled={!canEdit}
|
||||
onChange={setValue}
|
||||
onEnd={endGesture}
|
||||
/>
|
||||
<div className="flex items-end gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<Slider
|
||||
control={{ ...angle, min: -45, max: 45 }}
|
||||
value={session?.loaded ? session.value("crop.angle") : 0}
|
||||
disabled={!canEdit || !sourceSize}
|
||||
onChange={(_, v) => setAngle(v, false)}
|
||||
onEnd={() => setAngle(session?.loaded ? session.value("crop.angle") : 0, true)}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
disabled={!canEdit || !session?.loaded}
|
||||
onClick={() => void autoLevel()}
|
||||
title={t.dev.levelHelp}
|
||||
className="mb-1 h-6 shrink-0 border border-black bg-cell px-2 text-[11px] disabled:opacity-40"
|
||||
>
|
||||
{t.dev.level}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
@@ -408,11 +506,15 @@ export function DevelopPage() {
|
||||
key={p.id}
|
||||
aria-current={p.id === current?.id}
|
||||
onClick={() => navigate(`/develop/${p.id}`)}
|
||||
className={`relative h-full shrink-0 border ${p.id === current?.id ? "border-[#cfcfcf]" : "border-transparent opacity-70 hover:opacity-100"}`}
|
||||
className={`relative h-full shrink-0 border ${p.id === current?.id ? "border-[#cfcfcf]" : "border-transparent opacity-70 hover:opacity-100"} ${p.flag === "REJECT" ? "grayscale" : ""}`}
|
||||
title={p.originalName}
|
||||
>
|
||||
<img src={api.absolute(p.urls.thumb)} alt="" loading="lazy" className="h-full w-auto" draggable={false} />
|
||||
{p.developSeq > 0 && <span className="absolute bottom-0.5 right-0.5 bg-black/70 px-1 font-mono text-[9px] text-white">±</span>}
|
||||
{p.flag !== "NONE" && (
|
||||
<span className={`absolute left-0.5 top-0.5 px-1 text-[10px] ${p.flag === "PICK" ? "bg-white text-black" : "bg-black/80 text-white"}`}>{p.flag === "PICK" ? "⚑" : "✕"}</span>
|
||||
)}
|
||||
{p.rating > 0 && <span className="absolute bottom-0.5 left-0.5 bg-black/70 px-1 text-[9px] text-white">{"★".repeat(p.rating)}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { GallerySummary, LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
|
||||
import { hasRole, type DeliveryTarget, type EventSummary } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { pasteCommand } from "./DevelopPage.js";
|
||||
import { t } from "../i18n.js";
|
||||
@@ -148,7 +148,8 @@ export function LibraryPage() {
|
||||
dispatch({ type: "move", delta: moves[e.key]!, visible: visibleIds, extend: e.shiftKey });
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter" && focus) return setLoupe(true);
|
||||
if ((e.key === "Enter" || e.key.toLowerCase() === "e") && focus) return setLoupe(true);
|
||||
if (e.key.toLowerCase() === "g") return setLoupe(false);
|
||||
if (e.key.toLowerCase() === "d" && focus) return navigate(`/develop/${focus.id}`);
|
||||
if (e.key === "Escape") return setLoupe(false);
|
||||
const change = patchForKey(e.key);
|
||||
@@ -165,6 +166,16 @@ export function LibraryPage() {
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [visibleIds, selection, focus, loupe, patch, navigate]);
|
||||
|
||||
// Back from Develop (G): the photo that was open there is the one selected here.
|
||||
const location = useLocation();
|
||||
const backFocus = (location.state as { focus?: string } | null)?.focus;
|
||||
useEffect(() => {
|
||||
if (!backFocus || !state.photos.some((p) => p.id === backFocus)) return;
|
||||
dispatch({ type: "select", id: backFocus, mode: "single", visible: [] });
|
||||
requestAnimationFrame(() => document.querySelector(`[data-photo-id="${backFocus}"]`)?.scrollIntoView({ block: "nearest" }));
|
||||
navigate(".", { replace: true, state: null });
|
||||
}, [backFocus, state.photos, navigate]);
|
||||
|
||||
const onPick = useCallback(
|
||||
(id: string, e: React.MouseEvent) => dispatch({ type: "select", id, mode: e.shiftKey ? "range" : e.metaKey || e.ctrlKey ? "toggle" : "single", visible: visibleIds }),
|
||||
[visibleIds],
|
||||
|
||||
@@ -74,6 +74,14 @@ impl Source {
|
||||
]
|
||||
}
|
||||
|
||||
/// Auto straighten (Lightroom's Level): the crop angle that levels the photo's horizon or plumb lines, when
|
||||
/// they agree. `None` when there are no clear lines (crowds, close-ups): the angle is then left alone.
|
||||
pub fn auto_level(&self, settings: &DevelopSettings) -> Option<f64> {
|
||||
lightcraft_pipeline::upright::level_degrees(&self.image, &self.info, settings)
|
||||
.filter(|d| d.is_finite())
|
||||
.map(|d| (d.clamp(-45.0, 45.0) * 100.0).round() / 100.0)
|
||||
}
|
||||
|
||||
/// Automatic white balance (grey world on mid-tone, low-chroma pixels): `wb.temp` and `wb.tint`.
|
||||
pub fn auto_wb(&self) -> Vec<(&'static str, f64)> {
|
||||
let (temp, tint) = lightcraft_pipeline::auto::auto_wb(&self.image, &self.info);
|
||||
@@ -179,6 +187,48 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_level_finds_a_tilted_horizon() {
|
||||
// Sky over striped ground, the horizon falling 5 degrees to the right: the crop needs about -5.
|
||||
let (w, h) = (900u32, 600u32);
|
||||
let t = 5f64.to_radians().tan();
|
||||
let rgba = (0..h)
|
||||
.flat_map(|y| (0..w).map(move |x| (x, y)))
|
||||
.flat_map(|(x, y)| {
|
||||
let yh = h as f64 / 2.0 + (x as f64 - w as f64 / 2.0) * t;
|
||||
let c = if (y as f64) < yh {
|
||||
[150, 180, 230]
|
||||
} else if (((y as f64 - yh) / 30.0) as i32) % 2 == 0 {
|
||||
[20, 40, 60]
|
||||
} else {
|
||||
[50, 80, 100]
|
||||
};
|
||||
[c[0], c[1], c[2], 255]
|
||||
})
|
||||
.collect();
|
||||
let jpg = encode_jpeg(
|
||||
&Pixels {
|
||||
width: w,
|
||||
height: h,
|
||||
rgba,
|
||||
},
|
||||
95,
|
||||
)
|
||||
.unwrap();
|
||||
let src = Source::decode(&jpg, 0).unwrap();
|
||||
let deg = src
|
||||
.auto_level(&DevelopSettings::default())
|
||||
.expect("horizon found");
|
||||
assert!((deg + 5.0).abs() < 0.7, "{deg}");
|
||||
// A flat photo has no lines: the angle is left alone.
|
||||
assert_eq!(
|
||||
Source::decode(&jpeg(300, 200, [90, 90, 90]), 0)
|
||||
.unwrap()
|
||||
.auto_level(&DevelopSettings::default()),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_brightens_a_dark_photo_and_darkens_a_bright_one() {
|
||||
let get = |v: &[(&str, f64)], id: &str| v.iter().find(|(k, _)| *k == id).unwrap().1;
|
||||
|
||||
@@ -120,6 +120,19 @@ impl Photo {
|
||||
values_json(self.source.auto_tone(&s))
|
||||
}
|
||||
|
||||
/// Auto straighten: `{"crop.angle": ..}`, or `{}` when the photo has no clear horizon or verticals.
|
||||
#[wasm_bindgen(js_name = autoLevel)]
|
||||
pub fn auto_level(&self, settings: &str) -> Result<String, JsError> {
|
||||
let s = settings_from(settings)?;
|
||||
values_json(
|
||||
self.source
|
||||
.auto_level(&s)
|
||||
.map(|d| ("crop.angle", d))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Automatic white balance: `{"wb.temp": .., "wb.tint": ..}`.
|
||||
#[wasm_bindgen(js_name = autoWb)]
|
||||
pub fn auto_wb(&self) -> Result<String, JsError> {
|
||||
|
||||
Reference in new issue
Block a user