Website 1.7.0: move and zoom photos in their frame; delete unused photos

- A section's photo (hero, welcome, invitation, image-text) shows in the
  shape of its frame for the current template and layout, with a Move and
  zoom dialog: drag or arrow keys to choose what stays in view, zoom to
  300%. Saved with the section as data.framing ({ x, y, zoom } by media
  id), a draft until published. The site draws it with object-position
  and scale() around that point; Bold split/collage frames now clip, and
  a zoomed photo stays inside Heritage's mat. Framing for photos a section
  no longer shows is dropped on save.
- Media library: each photo says where it's used; one used nowhere can be
  deleted with its files (DELETE /admin/media/:id, 409 IN_USE otherwise,
  audited as media_deleted).

Checked: Website backend tests (135) and typecheck, frontend typecheck,
lint and production build, and an e2e test of both flows in Chromium.
Lighthouse not run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 23:34:10 +02:00
co-authored by Claude Opus 5.5
parent 25100bd749
commit a9215ac4e4
22 changed files with 494 additions and 50 deletions
+57
View File
@@ -147,6 +147,63 @@ export async function processImage(body: Buffer, kind: Kind, basePath: string) {
return { main, width, height, sizes, files };
}
/**
* Where each photo is used, so one in use is never deleted (it would leave a hole on the site):
* the draft pages and their sections, ministries, leaders, series, events, the site icon, the
* live site (the latest published version) and the church's logo. Returns a lookup by media id.
*/
export async function mediaUsage(ctx: Ctx): Promise<(m: { id: string; filename: string }) => string[]> {
const [pages, sections, ministries, leaders, series, events, settings, latest, church] = await Promise.all([
ctx.db.page.findMany({ where: { archivedAt: null } }),
ctx.db.section.findMany(),
ctx.db.ministry.findMany({ where: { archivedAt: null } }),
ctx.db.leader.findMany({ where: { archivedAt: null } }),
ctx.db.messageSeries.findMany(),
ctx.db.simpleEvent.findMany(),
ctx.db.appSetting.findMany(),
ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { snapshot: true } }),
import('../church/profile.js').then((p) => p.churchProfile(ctx)).catch(() => null),
]);
const titles = new Map(pages.map((p) => [p.id, p.title]));
const places: { label: string; text: string }[] = [
...pages.map((p) => ({ label: `${p.title} page`, text: String(p.imageId ?? '') })),
...sections.filter((s) => titles.has(s.pageId)).map((s) => ({ label: `${titles.get(s.pageId)} page`, text: JSON.stringify(s.data ?? null) })),
...ministries.map((m) => ({ label: `Ministry: ${m.name}`, text: String(m.imageId ?? '') })),
...leaders.map((l) => ({ label: `Leader: ${l.name}`, text: String(l.photoId ?? '') })),
...series.map((s) => ({ label: `Series: ${s.title}`, text: String(s.imageId ?? '') })),
...events.map((e) => ({ label: `Event: ${e.title}`, text: String(e.imageId ?? '') })),
...settings.filter((s) => !s.key.startsWith('hub_')).map((s) => ({ label: 'Site settings', text: s.value })),
{ label: 'The live site', text: JSON.stringify(latest?.snapshot ?? null) },
{ label: 'Church logo', text: JSON.stringify(church?.branding ?? null) },
];
return (m) => {
const url = mediaUrl(m.filename);
// A page's sections each name it: list each place once.
return [...new Set(places.filter((p) => p.text.includes(m.id) || p.text.includes(url)).map((p) => p.label))];
};
}
/** Deletes a photo and its files, unless it's used somewhere (then says where). */
export async function deleteMedia(ctx: Ctx, id: string, by: { id: string; role: string }) {
const row = await ctx.db.mediaAsset.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That image doesn\'t exist.');
const usedIn = (await mediaUsage(ctx))(row);
if (usedIn.length) {
throw new ApiError(409, 'IN_USE', `That photo is still used (${usedIn.join(', ')}). Take it out there first; if it's on the live site, publish after.`);
}
await ctx.db.mediaAsset.delete({ where: { id } });
const dir = uploadDir(ctx);
const sub = path.dirname(row.filename);
const sizes = Array.isArray(row.sizes) ? (row.sizes as Sizes) : [];
const files = [row.filename, ...sizes.flatMap((s) => [path.join(sub, s.webp), path.join(sub, s.jpg)])];
await Promise.all(files.map((f) => {
const full = path.resolve(dir, f);
// Never outside the uploads folder, whatever the row says.
return full.startsWith(dir + path.sep) ? fs.rm(full, { force: true }).catch(() => undefined) : undefined;
}));
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'media_deleted', targetType: 'media', targetId: id, metadata: { alt: row.alt, bytes: row.bytes } });
}
type StorageAsk = { at: string; steps: number; limitAtRequest: number };
/** The open "Get more storage" request, if any: open until the limit goes up. */
+4 -4
View File
@@ -22,7 +22,7 @@ import { syncYoutube } from '../site/youtube.js';
import { publishOn, syncLink } from '../feed/feed.js';
import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js';
import { MAX_UPLOAD_BYTES, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { deleteMedia, MAX_UPLOAD_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
import { maintenanceRouter } from './maintenance.js';
@@ -96,10 +96,10 @@ export function adminRouter(ctx: Ctx) {
// ─── Media library and storage ───
r.get('/media', handle(async () => {
const rows = await ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } });
const s = await storage(ctx);
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes })) };
const [rows, s, usedIn] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } }), storage(ctx), mediaUsage(ctx)]);
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) };
}));
r.delete('/media/:id', editor, handle(async (req) => { await deleteMedia(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) =>
upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id)));
// Get more storage: it costs the church, so an Owner or Admin asks (decision 12).
+23 -4
View File
@@ -12,6 +12,23 @@ import type { SectionType } from './variants.js';
const text = (max: number) => z.string().trim().max(max);
const optional = (max: number) => text(max).nullable().default(null);
const mediaId = z.string().uuid();
/**
* How each photo sits in its frame, by media id: the point kept in view (`x`, `y`, 0 to 100 from
* the left and top, as CSS `object-position`) and how far it's zoomed in (1 fills the frame).
*/
const framing = z.record(z.string().uuid(), z.object({ x: z.number().min(0).max(100), y: z.number().min(0).max(100), zoom: z.number().min(1).max(4) })).optional();
/** Keeps framing only for the photos the section still shows (a removed photo's would hold it "in use"). */
function pruneFraming<T extends { framing?: Record<string, unknown> }>(d: T): T {
if (!d.framing) return d;
const ids = new Set<string>();
const walk = (x: unknown): void => {
if (typeof x === 'string') ids.add(x);
else if (Array.isArray(x)) x.forEach(walk);
else if (x && typeof x === 'object') Object.values(x).forEach(walk);
};
walk({ ...d, framing: undefined });
return { ...d, framing: Object.fromEntries(Object.entries(d.framing).filter(([id]) => ids.has(id))) };
}
/** A link on the site (`/visit`) or elsewhere (https only). */
const href = z.string().trim().max(500).refine((v) => /^\/(?!\/)/.test(v) || /^https:\/\//.test(v), 'A page of this site (/visit) or an https:// address');
const button = z.object({ label: text(60).min(1), href }).nullable().default(null);
@@ -25,7 +42,8 @@ export const SECTION_SCHEMAS = {
/** `video`: a short muted loop (an uploaded .mp4) shown over its still (the first image). */
videoId: mediaId.nullable().default(null),
button,
}),
framing,
}).transform(pruneFraming),
serviceTimes: z.object({
heading: optional(80),
/** E.g. "Kids church during the morning service". Times and address come from the church profile. */
@@ -38,12 +56,13 @@ export const SECTION_SCHEMAS = {
body: text(4000).default(''),
imageId: mediaId.nullable().default(null),
pastor: z.object({ name: text(120).min(1), role: optional(80), quote: optional(400), photoId: mediaId.nullable().default(null) }).nullable().default(null),
}),
framing,
}).transform(pruneFraming),
ministries: z.object({ heading: optional(80), intro: optional(400) }),
team: z.object({ heading: optional(80), intro: optional(400) }),
events: z.object({ heading: optional(80), count: z.int().min(2).max(12).default(3) }),
latestMessage: z.object({ heading: optional(80) }),
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null) }),
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null), framing }).transform(pruneFraming),
} as const satisfies Record<SectionType, z.ZodType>;
export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)[S]> };
@@ -51,7 +70,7 @@ export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)
/** Blocks for the other pages and custom pages (§3, "Pages from blocks"); more come with the admin. */
export const BLOCK_SCHEMAS = {
text: z.object({ heading: optional(120), body: text(20000) }),
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button }),
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button, framing }).transform(pruneFraming),
quote: z.object({ quote: text(600).min(1), by: optional(120) }),
cta: z.object({ heading: text(120).min(1), text: optional(400), button }),
} as const;