From 07be48d77067a3e4fd4eddcd0abe9bb3901f97e7 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 6 Oct 2026 16:21:26 -0500 Subject: [PATCH] Uploads: frame a photo before it goes (crop, zoom, position) A photo field with a shape (crop: square for people, 16:9 for event photos, covers and hero photos, the photo's own for block images and schedule graphics) opens Frame the photo when a JPEG, PNG or WebP is uploaded: drag or arrow keys to place it, a zoom slider, and a shape menu. The framed part is drawn on a canvas and uploaded in place of the original; Upload as is skips it. Logos, SVGs and GIFs go as they are. No new dependency and nothing stored beside the picture. Co-Authored-By: Claude Opus 5.5 --- docs/media-uploads.md | 8 + src/components/admin/CropDialog.tsx | 243 ++++++++++++++++++++++++++ src/components/admin/MediaLibrary.tsx | 37 +++- src/components/admin/fields.tsx | 5 +- src/lib/adminSchema/blog.ts | 4 +- src/lib/adminSchema/events.ts | 2 + src/lib/adminSchema/frontPage.ts | 2 +- src/lib/adminSchema/people.ts | 2 +- src/lib/adminSchema/shared.ts | 5 + 9 files changed, 298 insertions(+), 10 deletions(-) create mode 100644 src/components/admin/CropDialog.tsx diff --git a/docs/media-uploads.md b/docs/media-uploads.md index 6e3bfdb..99ad77c 100644 --- a/docs/media-uploads.md +++ b/docs/media-uploads.md @@ -15,6 +15,14 @@ in the `media` table (`server/src/migrations/028_media.sql`). - **Keep original** stores the file exactly as uploaded (up to 10 MB), metadata and all. - SVGs are always kept as they are. +- A photo field with a shape (people, event photos and card + backgrounds, blog covers, hero photos, link card pictures, block + images and schedule graphics; not logos) opens **Frame the photo** + before uploading a JPEG, PNG or WebP: drag and zoom it inside the + field's shape, or pick another (As uploaded keeps the photo's own). + The framed part is what's uploaded; nothing about the framing is + saved, so framing again means uploading again. Upload as is skips + it. A field's shape is its `crop` option (`src/components/admin/fields.tsx`). - Accepted types: JPEG, PNG, GIF, WebP, SVG, and WebVTT captions (`.vtt`, kept as they are, always in `captions/`). The type is read from the file's contents, not its name: a captions file has to start diff --git a/src/components/admin/CropDialog.tsx b/src/components/admin/CropDialog.tsx new file mode 100644 index 0000000..de550a2 --- /dev/null +++ b/src/components/admin/CropDialog.tsx @@ -0,0 +1,243 @@ +/* ═══════════════════════════════════════════════════════════════ + CROP DIALOG + + The framing step between choosing a photo and uploading it, for an + image field with `crop` (fields.tsx). The photo sits behind a frame + in the field's shape: drag it (or use the arrow keys) to place it, + zoom with the slider, or pick another shape, "As uploaded" keeping + the photo's own. "Use this framing" draws the framed part onto a + canvas and hands that file on to be uploaded; "Upload as is" hands + on the original; Cancel uploads nothing. + + The crop is the file: nothing about it is saved beside the + picture, so framing again means uploading again. + ═══════════════════════════════════════════════════════════════ */ + +import { X } from "@phosphor-icons/react"; +import { useEffect, useRef, useState, type PointerEvent } from "react"; + +/* An image field's `crop`: width over height, or "free" for the + photo's own shape. */ +export type Crop = number | "free"; + +const SHAPES: [string, Crop][] = [ + ["Square", 1], + ["Portrait 4:5", 4 / 5], + ["Landscape 3:2", 3 / 2], + ["Wide 16:9", 16 / 9], + ["As uploaded", "free"], +]; + +/* The frame's largest box on screen, and the zoom slider's top. */ +const STAGE_W = 560; +const STAGE_H = 380; +const MAX_ZOOM = 4; +/* The longest side saved; the server shrinks to this anyway. */ +const MAX_SIDE = 2400; +/* How far an arrow key moves the photo, in screen pixels. */ +const KEY_STEP = 10; + +type Box = { x: number; y: number }; + +export default function CropDialog({ + file, + crop, + onDone, +}: { + file: File; + crop: Crop; + /** The file to upload (cropped or as is), or null for Cancel. */ + onDone: (file: File | null) => void; +}) { + const dialogRef = useRef(null); + const [img, setImg] = useState(null); + const [shape, setShape] = useState(crop); + const [zoom, setZoom] = useState(1); + const [at, setAt] = useState({ x: 0, y: 0 }); + const [saving, setSaving] = useState(false); + const drag = useRef<{ x: number; y: number; from: Box } | null>(null); + // Set when a button already answered, so closing doesn't cancel. + const answered = useRef(false); + + useEffect(() => { + dialogRef.current?.showModal(); + const url = URL.createObjectURL(file); + const image = new Image(); + image.onload = () => setImg(image); + image.src = url; + return () => URL.revokeObjectURL(url); + }, [file]); + + // The frame on screen, the photo's scale in it, and where the photo + // may sit so it always covers the frame. + const aspect = shape === "free" ? (img ? img.naturalWidth / img.naturalHeight : 1) : shape; + const stageW = Math.min(STAGE_W, window.innerWidth - 64); + const frameW = Math.min(stageW, STAGE_H * aspect); + const frameH = frameW / aspect; + const cover = img ? Math.max(frameW / img.naturalWidth, frameH / img.naturalHeight) : 1; + const scale = cover * zoom; + const imgW = img ? img.naturalWidth * scale : 0; + const imgH = img ? img.naturalHeight * scale : 0; + const clamp = (box: Box): Box => ({ + x: Math.min(0, Math.max(frameW - imgW, box.x)), + y: Math.min(0, Math.max(frameH - imgH, box.y)), + }); + const pos = clamp(at); + + // A new shape or a loaded photo starts centered, unzoomed. + useEffect(() => { + if (!img) return; + setZoom(1); + const s = Math.max(frameW / img.naturalWidth, frameH / img.naturalHeight); + setAt({ x: (frameW - img.naturalWidth * s) / 2, y: (frameH - img.naturalHeight * s) / 2 }); + }, [img, shape]); + + // Zooming keeps the frame's center on the same spot of the photo. + const zoomTo = (next: number) => { + const ratio = next / zoom; + setAt({ + x: frameW / 2 - (frameW / 2 - pos.x) * ratio, + y: frameH / 2 - (frameH / 2 - pos.y) * ratio, + }); + setZoom(next); + }; + + const onPointerDown = (e: PointerEvent) => { + e.currentTarget.setPointerCapture(e.pointerId); + drag.current = { x: e.clientX, y: e.clientY, from: pos }; + }; + const onPointerMove = (e: PointerEvent) => { + const d = drag.current; + if (d) setAt(clamp({ x: d.from.x + e.clientX - d.x, y: d.from.y + e.clientY - d.y })); + }; + + const finish = (result: File | null) => { + answered.current = true; + onDone(result); + dialogRef.current?.close(); + }; + + // The framed part, at the photo's own resolution (up to MAX_SIDE). + const save = () => { + if (!img) return; + setSaving(true); + const sw = frameW / scale; + const sh = frameH / scale; + const k = Math.min(1, MAX_SIDE / Math.max(sw, sh)); + const canvas = document.createElement("canvas"); + canvas.width = Math.round(sw * k); + canvas.height = Math.round(sh * k); + canvas.getContext("2d")!.drawImage(img, -pos.x / scale, -pos.y / scale, sw, sh, 0, 0, canvas.width, canvas.height); + // PNG and WebP keep their transparency; anything else goes as JPEG. + const type = file.type === "image/png" || file.type === "image/webp" ? file.type : "image/jpeg"; + const name = file.name.replace(/\.[^.]+$/, "") + (type === "image/jpeg" ? ".jpg" : type === "image/png" ? ".png" : ".webp"); + canvas.toBlob( + (blob) => { + setSaving(false); + if (blob) finish(new File([blob], name, { type })); + }, + type, + 0.92, + ); + }; + + const button = "btn border border-brand px-4 py-1.5 text-sm text-link transition-colors hover:bg-tint"; + + return ( + !answered.current && onDone(null)} + className="m-auto w-[min(40rem,calc(100vw-2rem))] p-0 backdrop:bg-[#001011]/40" + > +
+

Frame the photo

+ +
+ +
+
+ {/* The frame: the photo moves behind it. */} +
(drag.current = null)} + onKeyDown={(e) => { + const move = { ArrowLeft: [KEY_STEP, 0], ArrowRight: [-KEY_STEP, 0], ArrowUp: [0, KEY_STEP], ArrowDown: [0, -KEY_STEP] }[e.key]; + if (!move) return; + e.preventDefault(); + setAt(clamp({ x: pos.x + move[0], y: pos.y + move[1] })); + }} + className="relative cursor-move touch-none overflow-hidden outline-offset-2" + style={{ width: frameW, height: frameH }} + > + {img ? ( + + ) : ( +
+ )} +
+
+ +
+ + +
+
+ +
+ + +
+
+ ); +} diff --git a/src/components/admin/MediaLibrary.tsx b/src/components/admin/MediaLibrary.tsx index ff85451..4cac05d 100644 --- a/src/components/admin/MediaLibrary.tsx +++ b/src/components/admin/MediaLibrary.tsx @@ -47,6 +47,7 @@ import { useAuth } from "../../lib/auth.tsx"; import { clock, parseClock } from "../../lib/clock.ts"; import { canWrite as roleCanWrite } from "../../lib/roles.ts"; import { useSmallImage } from "../../lib/useSmallImage.ts"; +import CropDialog, { type Crop } from "./CropDialog.tsx"; export type MediaItem = { id: number; @@ -187,29 +188,41 @@ export function UploadButton({ multiple = false, label = "Upload", folder, + crop, }: { onUploaded: (item: MediaItem) => void; multiple?: boolean; label?: string; /** Where it goes; blank: the server's default, images. */ folder?: string; + /** The field's shape: a photo is framed (CropDialog) before it goes. */ + crop?: Crop; }) { const inputRef = useRef(null); const keepId = useId(); const [keepOriginal, setKeepOriginal] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); + const [framing, setFraming] = useState(null); // Captions are kept as they are, so there's no original to keep. const captions = folder === "captions"; - async function send(files: FileList | null) { - if (!files || files.length === 0) return; + // A single photo for a field with a shape is framed first; SVGs and + // GIFs (which would lose their animation) go as they are. + function choose(files: FileList | null) { + const one = files?.length === 1 ? files[0] : null; + if (crop && one && /^image\/(jpeg|png|webp)$/.test(one.type)) setFraming(one); + else send(files ? Array.from(files) : []); + } + + async function send(files: File[]) { + if (files.length === 0) return; setBusy(true); setError(null); try { // One at a time: each is up to 25 MB, and a failure should // name the file it happened to. - for (const file of Array.from(files)) { + for (const file of files) { try { onUploaded(await uploadImage(file, keepOriginal, folder)); } catch (err) { @@ -241,7 +254,7 @@ export function UploadButton({ accept={captions ? ".vtt,text/vtt" : "image/jpeg,image/png,image/gif,image/webp,image/svg+xml"} multiple={multiple} className="hidden" - onChange={(e) => send(e.target.files)} + onChange={(e) => choose(e.target.files)} /> {!captions && (