Feature updates: photo framing, group pages, schedule images, content block placement #29

Merged
ngu-git-admin merged 8 commits from feature-updates into main 2026-10-07 22:52:59 +01:00
9 changed files with 298 additions and 10 deletions
Showing only changes of commit 07be48d770 - Show all commits

View file

@ -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

View file

@ -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<HTMLDialogElement>(null);
const [img, setImg] = useState<HTMLImageElement | null>(null);
const [shape, setShape] = useState<Crop>(crop);
const [zoom, setZoom] = useState(1);
const [at, setAt] = useState<Box>({ 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<HTMLDivElement>) => {
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { x: e.clientX, y: e.clientY, from: pos };
};
const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {
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 (
<dialog
ref={dialogRef}
aria-label="Frame the photo"
onClose={() => !answered.current && onDone(null)}
className="m-auto w-[min(40rem,calc(100vw-2rem))] p-0 backdrop:bg-[#001011]/40"
>
<div className="flex items-center gap-3 border-b border-brand/15 px-5 py-4">
<h2 className="text-lg font-bold text-link">Frame the photo</h2>
<button
type="button"
onClick={() => finish(null)}
aria-label="Cancel"
className="ml-auto flex h-8 w-8 items-center justify-center btn text-muted hover:bg-tint"
>
<X aria-hidden="true" weight="bold" className="h-4 w-4" />
</button>
</div>
<div className="space-y-4 px-5 py-4">
<div className="flex justify-center bg-tint-soft py-3">
{/* The frame: the photo moves behind it. */}
<div
tabIndex={0}
role="img"
aria-label="The framed photo. Drag it, or use the arrow keys, to place it."
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={() => (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 ? (
<img
src={img.src}
alt=""
draggable={false}
className="absolute max-w-none select-none"
style={{ left: pos.x, top: pos.y, width: imgW, height: imgH }}
/>
) : (
<div className="skeleton h-full w-full" role="status" aria-label="Loading the photo" />
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-x-6 gap-y-3">
<label className="flex items-center gap-2 text-sm text-muted">
Zoom
<input
type="range"
min={1}
max={MAX_ZOOM}
step={0.01}
value={zoom}
onChange={(e) => zoomTo(Number(e.target.value))}
className="w-40"
/>
</label>
<label className="flex items-center gap-2 text-sm text-muted">
Shape
<select
value={String(shape)}
onChange={(e) => setShape(e.target.value === "free" ? "free" : Number(e.target.value))}
className="border border-muted/25 bg-surface px-2 py-1 text-body"
>
{SHAPES.map(([label, value]) => (
<option key={label} value={String(value)}>
{value === crop ? `${label} (this field's)` : label}
</option>
))}
</select>
</label>
</div>
</div>
<div className="flex flex-wrap justify-end gap-2 border-t border-brand/15 px-5 py-4">
<button type="button" onClick={() => finish(file)} className={button}>
Upload as is
</button>
<button
type="button"
onClick={save}
disabled={!img || saving}
className="btn bg-action px-4 py-1.5 text-sm text-white transition-colors hover:bg-action-hover disabled:bg-muted/25"
>
{saving ? "Framing…" : "Use this framing"}
</button>
</div>
</dialog>
);
}

View file

@ -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<HTMLInputElement>(null);
const keepId = useId();
const [keepOriginal, setKeepOriginal] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [framing, setFraming] = useState<File | null>(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 && (
<label htmlFor={keepId} className="flex items-center gap-1.5 text-xs text-muted">
@ -257,6 +270,17 @@ export function UploadButton({
)}
</div>
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
{framing && crop && (
<CropDialog
file={framing}
crop={crop}
onDone={(file) => {
setFraming(null);
if (file) send([file]);
else if (inputRef.current) inputRef.current.value = "";
}}
/>
)}
</div>
);
}
@ -535,6 +559,7 @@ export function ImageInput({
resolve,
folder,
videoUrl,
crop,
locked,
className,
onChange,
@ -546,6 +571,8 @@ export function ImageInput({
folder?: string;
/** A video link to take a frame from (the field's `frameFrom`). */
videoUrl?: string | null;
/** The field's `crop`: uploads are framed to it first. */
crop?: Crop;
locked: boolean;
className: string;
onChange: (value: string) => void;
@ -587,7 +614,7 @@ export function ImageInput({
/>
{editable && (
<div className="flex flex-wrap items-start gap-2">
<UploadButton folder={folder} onUploaded={(item) => onChange(item.url)} />
<UploadButton folder={folder} crop={crop} onUploaded={(item) => onChange(item.url)} />
<button type="button" className={button} onClick={() => setPicking(true)}>
Choose from library
</button>

View file

@ -77,7 +77,9 @@
`folder` ("logos" for logo and icon fields) is where uploads go and
the tab the library opens on. `frameFrom` names the row's video
link field and adds "Frame at" (a still at a typed time, saved to
thumbnails/); `frameWhen` limits it to rows that match.
thumbnails/); `frameWhen` limits it to rows that match. `crop` (a
width-over-height shape, or "free") frames an uploaded photo before
it goes (CropDialog.tsx); logo fields leave it off.
Two options change the box itself rather than what goes in it:
@ -390,6 +392,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
value={value}
resolve={field.resolve}
folder={field.folder}
crop={field.crop}
videoUrl={field.frameFrom && fieldShown({ when: field.frameWhen }, row) ? getPath(row, field.frameFrom) : null}
locked={locked}
className={locked ? inputLocked : common.className}

View file

@ -51,7 +51,7 @@ export const blogPosts = {
full: true,
help: "A sentence or two for the card. Default: the body's first paragraph.",
},
{ path: "cover_image", label: "Cover image", widget: "image", resolve: mediaUrl, full: true },
{ path: "cover_image", label: "Cover image", widget: "image", crop: 16 / 9, resolve: mediaUrl, full: true },
{
path: "show_contents",
label: "Show contents",
@ -71,7 +71,7 @@ export const blogPosts = {
note: "For a writer with no People record. People who wrote it go under Authors below; both can be set.",
fields: [
{ path: "guest_author", label: "Name" },
{ path: "guest_photo", label: "Photo", widget: "image", resolve: mediaUrl, full: true },
{ path: "guest_photo", label: "Photo", widget: "image", crop: 1, resolve: mediaUrl, full: true },
],
},
{

View file

@ -151,6 +151,7 @@ export const events = {
path: "photo",
label: "Event photo",
widget: "image",
crop: 16 / 9,
resolve: mediaUrl,
full: true,
help: "16:9, eg. 1920 x 1080, shown whole: at the top of the event's page, as the front page's featured event, on featured cards, in the newsletter and when the page is shared.",
@ -165,6 +166,7 @@ export const events = {
path: "card_image",
label: "Card background",
widget: "image",
crop: 1,
resolve: mediaUrl,
full: true,
help: "Only behind the event's card, faded so the text stays readable and cropped to the card's shape (about square). Keep the subject centered and leave words out.",

View file

@ -195,7 +195,7 @@ export const frontPage = {
title: (row) => row.caption || row.media || "New photo",
blank: { media: "", alt: "", caption: "" },
fields: [
{ path: "media", label: "Photo", required: true, widget: "image", resolve: mediaUrl, full: true },
{ path: "media", label: "Photo", required: true, widget: "image", crop: 16 / 9, resolve: mediaUrl, full: true },
{ path: "alt", label: "Description", help: "For screen readers" },
{ path: "caption", label: "Caption", full: true },
{ path: "link_url", label: "Link", help: "Optional; makes the caption a link" },

View file

@ -38,7 +38,7 @@ export const people = {
full: true,
help: "One line shown in directories, eg. Vocals, piano · Gospel, folk",
},
{ path: "photo", label: "Photo", widget: "image", resolve: mediaUrl, full: true },
{ path: "photo", label: "Photo", widget: "image", crop: 1, resolve: mediaUrl, full: true },
{
path: "primary_org_id",
label: "Home organization",

View file

@ -188,6 +188,7 @@ export const featuredCardsChild = {
path: "image",
label: "Image",
widget: "image",
crop: "free",
resolve: mediaUrl,
full: true,
frameFrom: "url",
@ -403,6 +404,7 @@ export const blocksChild = {
path: "media",
label: "Image",
widget: "image",
crop: "free",
resolve: mediaUrl,
full: true,
when: { path: "type", value: ["image", "video"] },
@ -495,6 +497,7 @@ export const blocksChild = {
path: "media",
label: "Picture",
widget: "image",
crop: 16 / 9,
resolve: mediaUrl,
full: true,
help: "Optional. Default: none, the card is text only.",
@ -512,6 +515,7 @@ export const blocksChild = {
path: "media",
label: "Graphic",
widget: "image",
crop: "free",
resolve: mediaUrl,
full: true,
help: "Optional, in the fold-out: a map of the site, a slide, a poster",
@ -535,6 +539,7 @@ export const blocksChild = {
path: "map_image",
label: "Map image",
widget: "image",
crop: "free",
resolve: mediaUrl,
full: true,
help: "Optional: your own map, eg. the camp with the room marked. Shown in the fold-out in place of the Google map (which stays a link), and as a slide when the schedule is presented.",