From a9215ac4e463041ffe1fbcb4116b0d3d01d3e65a Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Fri, 27 Nov 2026 23:34:10 +0200 Subject: [PATCH] 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 --- CHANGELOG.md | 11 ++ apps/website/CHANGELOG.md | 23 +++ apps/website/WHATS-NEW.md | 9 ++ apps/website/backend/package.json | 2 +- apps/website/backend/src/admin/media.ts | 57 +++++++ apps/website/backend/src/admin/routes.ts | 8 +- apps/website/backend/src/site/sections.ts | 27 +++- apps/website/backend/tests/media.test.ts | 58 +++++++ apps/website/e2e/admin.spec.ts | 39 +++++ apps/website/frontend/package.json | 2 +- apps/website/frontend/src/admin/fields.tsx | 28 +++- apps/website/frontend/src/admin/framing.tsx | 152 ++++++++++++++++++ apps/website/frontend/src/admin/media.tsx | 36 ++++- .../frontend/src/app/admin/media/page.tsx | 14 +- .../src/app/admin/pages/[id]/page.tsx | 15 +- apps/website/frontend/src/site/load.ts | 10 +- apps/website/frontend/src/site/parts.tsx | 21 ++- .../frontend/src/site/sections/Hero.tsx | 8 +- .../frontend/src/site/sections/index.tsx | 8 +- apps/website/frontend/src/site/types.ts | 5 +- docs/VERSIONS.md | 7 +- package-lock.json | 4 +- 22 files changed, 494 insertions(+), 50 deletions(-) create mode 100644 apps/website/backend/tests/media.test.ts create mode 100644 apps/website/frontend/src/admin/framing.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index d29b8c0..6274bc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## website@1.7.0 - 2026-11-27 + +Photos can be moved and zoomed in their frame, and unused photos deleted. Details in +`apps/website/CHANGELOG.md`. No migration. + +- **Move and zoom:** a section's photo shows in its frame's shape for the template and layout, + with a dialog to drag and zoom it; saved with the section (`data.framing`), a draft until + published. +- **Delete photos:** the media library says where each photo is used, and deletes one used nowhere + (its files too); `DELETE /api/v1/admin/media/:id` refuses one in use. + ## events@3.7.2 + website@1.6.1 - 2026-11-27 Events shown on the other product's site no longer show twice after a reseed, and the Website's diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index 07bbb7a..37aae74 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog — Church Website +## [1.7.0] — 2026-11-27 + +No migration, no new environment settings. + +### Added + +- **Move and zoom a photo in its frame.** In a section's form (the top of the page, Welcome, + Invitation, Image and text), a chosen photo shows in the shape of the frame the site puts it in + for the current template and layout (`admin/framing.tsx`, `frameFor`), with **Move and zoom**: + drag (or arrow keys) to choose what stays in view, zoom up to 300% to crop closer, Reset. It's + saved with the section as `data.framing` (by media id: `{ x, y, zoom }`), so it's a draft + like any other edit: the live preview shows it on Save, visitors after Publish. The site draws it + with `object-position` and `scale()` around the same point (`focusStyle` in `site/parts.tsx`); + the Bold split and collage frames now clip (`overflow-hidden`), and a zoomed photo in a + Heritage frame stays inside its mat. Framing for a photo the section no longer shows is dropped + when it's saved. +- **Delete photos from the media library.** Each photo says where it's used (draft pages and + their sections, ministries, leaders, series, events, the site icon, the live site, the church's + logo); one used nowhere has **Delete** (Editors and up), which removes the row and its files + (the photo and its responsive sizes, never outside the uploads folder) and frees the storage. + `DELETE /api/v1/admin/media/:id` refuses one in use (409 `IN_USE`, saying where); audited as + `media_deleted`. + ## [1.6.1] — 2026-11-27 No migration, no new environment settings. diff --git a/apps/website/WHATS-NEW.md b/apps/website/WHATS-NEW.md index ad5a3f3..6bedf9f 100644 --- a/apps/website/WHATS-NEW.md +++ b/apps/website/WHATS-NEW.md @@ -3,6 +3,15 @@ What each version changes for the church, in plain language (read by the Hub like Cross Events' WHATS-NEW.md; a section shows once its version is tagged). +## 1.7.0 + +- **Move and zoom your photos.** When you choose a photo for a section, you now see it in the + shape it has on your site. Press **Move and zoom** to drag it so the right part shows (faces, + not the ceiling) and zoom in to crop closer. Save, and the preview shows it; publish, and + visitors see it. +- **Delete photos you don't need.** In the **Media library**, each photo says where it's used. + Photos that aren't used anywhere have a **Delete** button, which frees up their storage. + ## 1.6.1 - **The link to your Cross Events site is easier to tell apart** in your website's menu: it now diff --git a/apps/website/backend/package.json b/apps/website/backend/package.json index a0c4d9f..3ee9271 100644 --- a/apps/website/backend/package.json +++ b/apps/website/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-backend", - "version": "1.6.1", + "version": "1.7.0", "description": "Church Website: the public site's content API, the admin API, publishing and uploads", "private": true, "type": "module", diff --git a/apps/website/backend/src/admin/media.ts b/apps/website/backend/src/admin/media.ts index 9fe827b..8210f00 100644 --- a/apps/website/backend/src/admin/media.ts +++ b/apps/website/backend/src/admin/media.ts @@ -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. */ diff --git a/apps/website/backend/src/admin/routes.ts b/apps/website/backend/src/admin/routes.ts index e626800..0fd5a65 100644 --- a/apps/website/backend/src/admin/routes.ts +++ b/apps/website/backend/src/admin/routes.ts @@ -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). diff --git a/apps/website/backend/src/site/sections.ts b/apps/website/backend/src/site/sections.ts index ad211be..c2bf825 100644 --- a/apps/website/backend/src/site/sections.ts +++ b/apps/website/backend/src/site/sections.ts @@ -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 }>(d: T): T { + if (!d.framing) return d; + const ids = new Set(); + 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; 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; diff --git a/apps/website/backend/tests/media.test.ts b/apps/website/backend/tests/media.test.ts new file mode 100644 index 0000000..b8538b6 --- /dev/null +++ b/apps/website/backend/tests/media.test.ts @@ -0,0 +1,58 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import request from 'supertest'; +import { hashToken } from '../src/lib/crypto.js'; +import { parseSectionData } from '../src/site/sections.js'; +import { harness, SITE } from './support/harness.js'; + +async function site() { + const uploads = await fs.mkdtemp(path.join(os.tmpdir(), 'ccw-media-')); + const h = await harness({ linked: false, env: { UPLOAD_DIR: uploads } }); + const id = '00000000-0000-4000-8000-00000000000a'; + await h.db.websiteUser.create({ data: { id, name: 'Ann', email: 'ann@hope.test', role: 'editor' } }); + await h.db.session.create({ data: { tokenHash: hashToken('ann'), userId: id, expiresAt: new Date(Date.now() + 864e5) } }); + const go = (m: 'get' | 'delete', p: string) => request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=ann').set('Origin', SITE); + return { ...h, go, uploads }; +} + +describe('deleting photos', () => { + it('deletes one that is not used, with its files, and refuses one that is, saying where', async () => { + const { go, db, uploads, ctx } = await site(); + const dir = path.resolve(ctx.config.uploadDir ?? uploads); + await fs.mkdir(path.join(dir, '2026/11'), { recursive: true }); + for (const f of ['old.jpg', 'old-480.webp', 'old-480.jpg']) await fs.writeFile(path.join(dir, '2026/11', f), 'x'); + const old = await db.mediaAsset.create({ data: { filename: '2026/11/old.jpg', mime: 'image/jpeg', bytes: 3, width: 960, sizes: [{ w: 480, webp: 'old-480.webp', jpg: 'old-480.jpg' }] } }); + const used = await db.mediaAsset.create({ data: { filename: '2026/11/used.jpg', mime: 'image/jpeg', bytes: 3 } }); + const page = await db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } }); + await db.section.create({ data: { pageId: page.id, type: 'hero', data: { headline: 'Hi', images: [used.id] } } }); + + const list = (await go('get', '/media')).body.items as { id: string; usedIn: string[] }[]; + assert.deepEqual(list.find((m) => m.id === used.id)!.usedIn, ['Home page']); + assert.deepEqual(list.find((m) => m.id === old.id)!.usedIn, []); + + const refused = await go('delete', `/media/${used.id}`); + assert.equal(refused.status, 409); + assert.match(refused.body.error.message, /Home page/); + assert.ok(await db.mediaAsset.findUnique({ where: { id: used.id } })); + + assert.equal((await go('delete', `/media/${old.id}`)).status, 200); + assert.equal(await db.mediaAsset.findUnique({ where: { id: old.id } }), null); + assert.deepEqual(await fs.readdir(path.join(dir, '2026/11')), []); + assert.equal((await go('delete', `/media/${old.id}`)).status, 404); + }); +}); + +describe('framing a photo in its frame', () => { + it('keeps where each photo sits and how far it is zoomed, and refuses nonsense', () => { + const id = '11111111-1111-4111-8111-111111111111'; + const ok = parseSectionData('hero', { headline: 'Hi', images: [id], framing: { [id]: { x: 30, y: 60, zoom: 1.5 } } }); + assert.deepEqual(ok?.framing, { [id]: { x: 30, y: 60, zoom: 1.5 } }); + assert.equal(parseSectionData('image-text', {})?.framing, undefined); + // A photo taken out of the section takes its framing with it (or it would count as "in use"). + assert.deepEqual(parseSectionData('hero', { headline: 'Hi', images: [], framing: { [id]: { x: 30, y: 60, zoom: 1 } } })?.framing, {}); + assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null); + }); +}); diff --git a/apps/website/e2e/admin.spec.ts b/apps/website/e2e/admin.spec.ts index 5d8f8d3..078d6b5 100644 --- a/apps/website/e2e/admin.spec.ts +++ b/apps/website/e2e/admin.spec.ts @@ -185,3 +185,42 @@ test("the admin's screens are accessible", async ({ page, context }) => { const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze(); expect(axe.violations.map((v) => `editor: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]); }); + +test("move and zoom a photo in its frame, then delete a photo nothing uses", async ({ page, context }) => { + await signIn(context); + await page.goto("/admin/pages"); + await page.getByRole("link", { name: /^Home\b/ }).first().click(); + await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/); + await page.getByRole("button", { name: /Top of the page/ }).click(); + await page.getByRole("button", { name: "Move and zoom" }).first().click(); + const dialog = page.getByRole("dialog", { name: "Move and zoom the photo" }); + await expect(dialog).toBeVisible(); + await dialog.getByRole("slider").fill("2"); + const box = (await dialog.getByLabel(/in its frame/).boundingBox())!; + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(box.x + box.width / 2 + 80, box.y + box.height / 2 + 30, { steps: 5 }); + await page.mouse.up(); + await dialog.getByRole("button", { name: "Done" }).click(); + await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible(); + await page.getByRole("button", { name: "Save", exact: true }).click(); + await expect(page.getByText("Saved as a draft.")).toBeVisible(); + // The live preview draws it the same way. + const frame = page.frameLocator('iframe[title="Live preview of this page"]'); + await expect(frame.locator(".cc-section-hero img").first()).toHaveAttribute("style", /scale\(2\)/); + await page.screenshot({ path: "e2e/test-results/framing.png" }); + + // Upload one nothing uses, then delete it; one in use says where instead. + await page.goto("/admin/media"); + const before = await page.locator("main li").count(); + const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64"); + await page.locator('input[type="file"]').setInputFiles({ name: "dot.png", mimeType: "image/png", buffer: png }); + await page.getByLabel("What the photo shows").fill("A dot to delete"); + await page.getByRole("button", { name: "Upload" }).click(); + await expect(page.locator("main li")).toHaveCount(before + 1); + await expect(page.getByText("Used on:").first()).toBeVisible(); + page.once("dialog", (d) => d.accept()); + await page.locator("main li").filter({ has: page.locator('input[value="A dot to delete"]') }).getByRole("button", { name: "Delete" }).click(); + await expect(page.getByText("Deleted.")).toBeVisible(); + await expect(page.locator("main li")).toHaveCount(before); +}); diff --git a/apps/website/frontend/package.json b/apps/website/frontend/package.json index 1c2a705..6261069 100644 --- a/apps/website/frontend/package.json +++ b/apps/website/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-frontend", - "version": "1.6.1", + "version": "1.7.0", "private": true, "description": "Church Website: the church's public site in its template, and the admin", "scripts": { diff --git a/apps/website/frontend/src/admin/fields.tsx b/apps/website/frontend/src/admin/fields.tsx index 53488d0..582d60c 100644 --- a/apps/website/frontend/src/admin/fields.tsx +++ b/apps/website/frontend/src/admin/fields.tsx @@ -4,6 +4,8 @@ * The forms for each homepage section and block, from one description per type (the backend's * zod schemas in src/site/sections.ts check what's saved; field errors come back by path). */ +import type { Focus } from "@/site/types"; +import { FramingContext, type Framing } from "./framing"; import { ImagePicker } from "./media"; import { Btn, Field, inputClass } from "./ui"; @@ -52,9 +54,13 @@ export const BLOCK_FIELDS: Record = { type Data = Record; -export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record; prefix?: string }) { +/** + * A section's or block's fields. With `frame` (the top-level form of a section), its photos show in + * the shape of their frame on the site and can be moved and zoomed (saved in `data.framing`). + */ +export function DataForm({ fields, value, onChange, errors, prefix = "", frame }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record; prefix?: string; frame?: Framing["frame"] }) { const set = (k: string, v: unknown) => onChange({ ...value, [k]: v }); - return ( + const form = (
{fields.map((f) => { const err = errors[`${prefix}${f.key}`]; @@ -67,14 +73,14 @@ export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fie case "number": return set(f.key, Number(e.target.value))} />; case "image": - return
set(f.key, id)} />{err &&

{err}

}
; + return
set(f.key, id)} />{err &&

{err}

}
; case "images": { const list = Array.isArray(v) ? (v as string[]) : []; return (

{f.label}

- {list.map((id, i) => set(f.key, n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i))} />)} - {list.length < f.max && n && set(f.key, [...list, n])} />} + {list.map((id, i) => set(f.key, n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i))} />)} + {list.length < f.max && n && set(f.key, [...list, n])} />}
); } @@ -111,4 +117,16 @@ export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fie })}
); + if (!frame) return form; + const framing = (value.framing ?? {}) as Record; + const ctx: Framing = { + get: (id) => framing[id], + set: (id, f) => { + const next = { ...framing }; + if (f) next[id] = f; else delete next[id]; + onChange({ ...value, framing: next }); + }, + frame, + }; + return {form}; } diff --git a/apps/website/frontend/src/admin/framing.tsx b/apps/website/frontend/src/admin/framing.tsx new file mode 100644 index 0000000..61297ed --- /dev/null +++ b/apps/website/frontend/src/admin/framing.tsx @@ -0,0 +1,152 @@ +"use client"; + +/** + * Framing a photo: see it in the shape of the frame the site puts it in (the template and layout + * chosen), drag it to move it and zoom in to crop. Saved with the section (`data.framing`, by media + * id), so it's a draft like any other change: previewed, then published. + */ +import { createContext, useContext, useEffect, useRef, useState } from "react"; +import { focusStyle } from "@/site/parts"; +import type { Focus } from "@/site/types"; +import { Btn, cx } from "./ui"; + +export type Frame = { ratio: number; round?: boolean; label: string }; + +export const CENTRE: Focus = { x: 50, y: 50, zoom: 1 }; + +type Design = { template?: string; variants?: Record } | null | undefined; + +/** + * The frame a section's photo is shown in, as wide as the site's desktop layout draws it + * (site/sections). `key` is the field (images, imageId, photoId); `index` the photo in a list. + */ +export function frameFor(design: Design, type: string, key: string, index = 0): Frame { + const t = design?.template ?? "heritage"; + const v = design?.variants?.[type]; + if (type === "hero") { + if (v === "text") return { ratio: 16 / 9, label: "Not shown: the top of the page is set to Text only" }; + if (v === "split") return t === "bold" ? { ratio: 4 / 5, label: "Half the screen, beside the headline" } : { ratio: 4 / 3, label: "Beside the headline" }; + if (v === "collage") { + if (t === "bold") return { ratio: 3 / 5, label: `Column ${index + 1} of 3, behind the headline` }; + if (t === "community") return { ratio: 1, round: index === 2, label: `Photo ${index + 1} of the overlapping three` }; + return { ratio: t === "heritage" ? 3 / 4 : 1, label: `Photo ${index + 1} of 3` }; + } + if (t === "bold") return { ratio: 16 / 9, label: "The whole screen, behind the headline (taller on phones)" }; + if (t === "heritage") return { ratio: 16 / 7, label: "Wide, above the headline" }; + if (t === "community") return { ratio: 21 / 9, label: "Wide, behind the headline card (16:9 on phones)" }; + return { ratio: 16 / 9, label: "Below the headline" }; + } + if (type === "welcome") { + if (key === "photoId") return { ratio: 4 / 5, label: "The pastor's photo" }; + return t === "bold" ? { ratio: 1, label: "Beside the welcome" } : { ratio: 4 / 3, label: "Beside the welcome" }; + } + if (type === "invitation") return { ratio: 3, label: "Behind the invitation, darkened (the Image background layout)" }; + return { ratio: 4 / 3, label: "Beside the text" }; +} + +/** What DataForm shares with each ImagePicker in a section: its framing, and the frame per field. */ +export type Framing = { + get: (id: string) => Focus | undefined; + set: (id: string, f: Focus | null) => void; + frame: (key: string, index?: number) => Frame; +}; + +export const FramingContext = createContext(null); +export const useFraming = () => useContext(FramingContext); + +/** The photo drawn in its frame, as the site draws it (object-cover, point kept in view, zoom). */ +export function Framed({ url, frame, focus, className, imgRef }: { url: string; frame: Frame; focus: Focus | undefined; className?: string; imgRef?: React.Ref }) { + return ( +
+ +
+ ); +} + +const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n)); + +/** Drag to move, slider (or wheel) to zoom; Done keeps it, Cancel leaves it as it was. */ +export function FramingDialog({ url, alt, frame, initial, onDone, onClose }: { + url: string; alt: string; frame: Frame; initial: Focus | undefined; onDone: (f: Focus | null) => void; onClose: () => void; +}) { + const [f, setF] = useState(initial ?? CENTRE); + const box = useRef(null); + const img = useRef(null); + const drag = useRef<{ x: number; y: number; start: Focus } | null>(null); + + useEffect(() => { + const esc = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); }; + window.addEventListener("keydown", esc); + return () => window.removeEventListener("keydown", esc); + }, [onClose]); + + /** How far the photo can move (px) across 0–100%: its drawn size, zoomed, less the frame's. */ + const room = () => { + const b = box.current?.getBoundingClientRect(); + const i = img.current; + if (!b || !i?.naturalWidth) return { x: 0, y: 0 }; + const cover = Math.max(b.width / i.naturalWidth, b.height / i.naturalHeight); + return { x: i.naturalWidth * cover * f.zoom - b.width, y: i.naturalHeight * cover * f.zoom - b.height }; + }; + + const down = (e: React.PointerEvent) => { + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + drag.current = { x: e.clientX, y: e.clientY, start: f }; + }; + const move = (e: React.PointerEvent) => { + const d = drag.current; + if (!d) return; + const r = room(); + // Dragging the photo right shows more of its left: the point in view moves left. + setF({ + ...d.start, + x: r.x > 1 ? clamp(d.start.x - ((e.clientX - d.x) / r.x) * 100, 0, 100) : d.start.x, + y: r.y > 1 ? clamp(d.start.y - ((e.clientY - d.y) / r.y) * 100, 0, 100) : d.start.y, + }); + }; + const key = (e: React.KeyboardEvent) => { + const step = e.shiftKey ? 10 : 2; + const by: Record = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] }; + const m = by[e.key]; + if (!m) return; + e.preventDefault(); + setF({ ...f, x: clamp(f.x + m[0], 0, 100), y: clamp(f.y + m[1], 0, 100) }); + }; + const round = (x: Focus): Focus => ({ x: Math.round(x.x * 10) / 10, y: Math.round(x.y * 10) / 10, zoom: Math.round(x.zoom * 100) / 100 }); + const centred = f.x === 50 && f.y === 50 && f.zoom === 1; + + return ( +
+
+

Move and zoom

+

{frame.label}. Drag the photo to choose what shows; zoom in to crop closer.

+
{ drag.current = null; }} + onPointerCancel={() => { drag.current = null; }} + onKeyDown={key} + onWheel={(e) => setF((x) => ({ ...x, zoom: clamp(x.zoom - e.deltaY * 0.002, 1, 3) }))} + className="mx-auto mt-4 cursor-grab touch-none outline-none ring-brand focus-visible:ring-2 active:cursor-grabbing" + style={{ maxWidth: frame.ratio < 1 ? `${Math.round(360 * frame.ratio)}px` : undefined }} + > + +
+ +

On phones the frame can be a different shape; the part you chose stays in view.

+
+ onDone(centred ? null : round(f))}>Done + Cancel + setF(CENTRE)} disabled={centred}>Reset +
+
+
+ ); +} diff --git a/apps/website/frontend/src/admin/media.tsx b/apps/website/frontend/src/admin/media.tsx index ab397e7..61fff98 100644 --- a/apps/website/frontend/src/admin/media.tsx +++ b/apps/website/frontend/src/admin/media.tsx @@ -2,10 +2,12 @@ /** The media library: pick an image, or upload one (with its alt text) and pick it. */ import { useRef, useState } from "react"; +import { Move } from "lucide-react"; import { api } from "./api"; +import { Framed, FramingDialog, useFraming } from "./framing"; import { Btn, cx, Field, inputClass, Notice, useAction, useAdmin } from "./ui"; -export type MediaItem = { id: string; url: string; alt: string; width: number | null; height: number | null; bytes: number }; +export type MediaItem = { id: string; url: string; alt: string; width: number | null; height: number | null; bytes: number; usedIn?: string[] }; export type Storage = { usedBytes: number; limitBytes: number; full: boolean; percent: number }; export const gb = (n: number) => `${(n / 1024 ** 3).toFixed(n < 1024 ** 3 ? 2 : 1)} GB`; @@ -49,21 +51,41 @@ export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem) ); } -/** One image field: shows the chosen image, with Choose and Remove. */ -export function ImagePicker({ value, onChange, label }: { value: string | null; onChange: (id: string | null) => void; label: string }) { +/** + * One image field: shows the chosen image, with Choose and Remove. In a section (`slot` and a + * FramingContext), it's shown in the shape of its frame on the site, with Move and zoom. + */ +export function ImagePicker({ value, onChange, label, slot }: { value: string | null; onChange: (id: string | null) => void; label: string; slot?: { key: string; index?: number } }) { const [open, setOpen] = useState(false); + const [framingOpen, setFramingOpen] = useState(false); const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null); const chosen = data?.items.find((m) => m.id === value); + const framing = useFraming(); + const frame = framing && slot ? framing.frame(slot.key, slot.index) : null; + const focus = value ? framing?.get(value) : undefined; return (
{label} -
-
- {chosen ? {chosen.alt} : No image} -
+
+ {chosen && frame ? ( + + ) : ( +
+ {chosen ? {chosen.alt} : No image} +
+ )} setOpen(true)}>{value ? "Change" : "Choose"} + {chosen && frame && setFramingOpen(true)}>Move and zoom} {value && onChange(null)}>Remove}
+ {chosen && frame && focus &&

Moved{focus.zoom > 1 ? ` and zoomed to ${Math.round(focus.zoom * 100)}%` : ""}. Save to see it in the preview.

} + {framingOpen && chosen && frame && framing && ( + { framing.set(chosen.id, f); setFramingOpen(false); }} onClose={() => setFramingOpen(false)} /> + )} {open && (
diff --git a/apps/website/frontend/src/app/admin/media/page.tsx b/apps/website/frontend/src/app/admin/media/page.tsx index 633305f..a5e5dd9 100644 --- a/apps/website/frontend/src/app/admin/media/page.tsx +++ b/apps/website/frontend/src/app/admin/media/page.tsx @@ -1,10 +1,10 @@ "use client"; import { useState } from "react"; -import { api } from "@/admin/api"; +import { api, canEdit } from "@/admin/api"; import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media"; import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui"; -import { Image as ImageIcon } from "lucide-react"; +import { Image as ImageIcon, Trash2 } from "lucide-react"; /** The media library (§10): uploads, what each photo shows (alt text), and storage used. */ export default function Media() { @@ -15,6 +15,7 @@ export default function Media() { const { busy, message, run } = useAction(); if (!data) return ; const manager = ["owner", "admin"].includes(me.data?.user.role ?? ""); + const editor = canEdit(me.data?.user.role ?? ""); const s = data.storage; return ( <> @@ -35,6 +36,15 @@ export default function Media() { )} {!m.alt &&

Add what it shows, for people who can't see it.

}

{m.width && m.height ? `${m.width} × ${m.height}` : ""} · {gb(m.bytes)}

+ {m.usedIn?.length ? ( +

Used on: {m.usedIn.join(", ")}

+ ) : editor && ( + { + if (window.confirm(`Delete this photo${m.alt ? ` (“${m.alt}”)` : ""}? It isn't used anywhere. This can't be undone.`)) { + void run(async () => { await api(`/media/${m.id}`, { method: "DELETE" }); await reload(); }, "Deleted."); + } + }}>Delete + )} ))} diff --git a/apps/website/frontend/src/app/admin/pages/[id]/page.tsx b/apps/website/frontend/src/app/admin/pages/[id]/page.tsx index 603098c..c1cbdb9 100644 --- a/apps/website/frontend/src/app/admin/pages/[id]/page.tsx +++ b/apps/website/frontend/src/app/admin/pages/[id]/page.tsx @@ -15,13 +15,14 @@ import { } from "lucide-react"; import { api } from "@/admin/api"; import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields"; +import { frameFor, type Framing } from "@/admin/framing"; import { WithPreview } from "@/admin/LivePreview"; import { ImagePicker } from "@/admin/media"; import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui"; type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record; updatedAt: string }; type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] }; -type Design = { home: { section: string; hidden: boolean }[] }; +type Design = { template: string; variants: Record; home: { section: string; hidden: boolean }[] }; const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"]; const LISTS: Record = { @@ -48,8 +49,8 @@ const summary = (data: Record) => { return null; }; -function SectionEditor({ type, title, fields, initial, onSave, hidden, extra }: { - type: string; title: string; fields: Parameters[0]["fields"]; initial: Record; +function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, frame }: { + type: string; title: string; fields: Parameters[0]["fields"]; initial: Record; frame?: Framing["frame"]; onSave: (data: Record) => Promise; hidden?: React.ReactNode; extra?: React.ReactNode; }) { const [value, setValue] = useState(initial); @@ -73,7 +74,7 @@ function SectionEditor({ type, title, fields, initial, onSave, hidden, extra }:
{open && (
- +
run(() => onSave(value), "Saved as a draft.")}>Save setOpen(false)}>Close @@ -134,7 +135,7 @@ export default function EditPage() { const router = useRouter(); const { data: page, error, setData } = useAdmin(`/pages/${id}`); const isHome = page?.kind === "home"; - const design = useAdmin<{ design: Design }>(isHome ? "/design" : null); + const design = useAdmin<{ design: Design }>("/design"); const blocks = useAction(); const remove = useAction(); const [tab, setTab] = useState<"content" | "details">("content"); @@ -171,7 +172,7 @@ export default function EditPage() { const s = page.sections.find((x) => x.type === type); const spec = SECTION_FIELDS[type]; if (!spec) return null; - return frameFor(design.data?.design, type, key, i)} hidden={hidden && Not shown} onSave={async (data) => setData(await api(`/pages/${id}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />; })} @@ -184,7 +185,7 @@ export default function EditPage() { const spec = BLOCK_FIELDS[s.type]; if (!spec) return null; return ( - frameFor(design.data?.design, s.type, key, i)} hidden={s.hidden && Hidden} onSave={async (data) => setData(await api(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))} extra={<> diff --git a/apps/website/frontend/src/site/load.ts b/apps/website/frontend/src/site/load.ts index 2e3f750..74a7797 100644 --- a/apps/website/frontend/src/site/load.ts +++ b/apps/website/frontend/src/site/load.ts @@ -1,6 +1,6 @@ import { cookies, headers } from "next/headers"; import { cache } from "react"; -import type { Image, Published, SiteContent, Template } from "./types"; +import type { Focus, Image, Published, SiteContent, Template } from "./types"; const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, ""); @@ -57,8 +57,12 @@ export async function loadPublished(): Promise { return c.mode === "published" ? c : null; } -/** An image from a section's data (a media id), or null. */ -export const media = (site: Published, id: unknown): Image | null => (typeof id === "string" ? site.snapshot.media[id] ?? null : null); +/** An image from a section's data (a media id), or null; placed as the section frames it (`data.framing`). */ +export const media = (site: Published, id: unknown, data?: Record): Image | null => { + const img = typeof id === "string" ? site.snapshot.media[id] ?? null : null; + const focus = img && (data?.framing as Record | undefined)?.[id as string]; + return img && focus ? { ...img, focus } : img; +}; /** Per-template class names: `t(template, { heritage: "…", bold: "…" }, "fallback")`. */ export const t = (template: Template, by: Partial>, otherwise = "") => by[template] ?? otherwise; diff --git a/apps/website/frontend/src/site/parts.tsx b/apps/website/frontend/src/site/parts.tsx index 8dd4b94..dbf53c4 100644 --- a/apps/website/frontend/src/site/parts.tsx +++ b/apps/website/frontend/src/site/parts.tsx @@ -1,8 +1,18 @@ /** Small building blocks every template uses. */ -import type { Image } from "./types"; +import type { Focus, Image } from "./types"; export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); +/** + * How a photo sits in its frame (object-cover): the chosen point kept in view, zoomed around that + * point. The frame clips it (overflow hidden). The admin's framing dialog draws it the same way. + */ +export function focusStyle(f: Focus | undefined): React.CSSProperties | undefined { + if (!f) return undefined; + const at = `${f.x}% ${f.y}%`; + return f.zoom > 1 ? { objectPosition: at, transform: `scale(${f.zoom})`, transformOrigin: at } : { objectPosition: at }; +} + /** * An uploaded image at the size the screen needs (§3: responsive sizes in WebP and JPEG): the * browser picks from the `srcset`s by `sizes`. `alt` overrides the image's own (e.g. "" when it's @@ -12,7 +22,7 @@ export function Picture({ image, className, sizes = "100vw", priority = false, a const img = ( {alt + loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className={className} style={focusStyle(image.focus)} /> ); return image.srcset ? {img} : img; } @@ -21,7 +31,12 @@ export function Picture({ image, className, sizes = "100vw", priority = false, a export function Img({ image, className, sizes = "(min-width: 768px) 50vw, 100vw", priority = false, ratio = "aspect-[4/3]" }: { image: Image | null; className?: string; sizes?: string; priority?: boolean; ratio?: string }) { return (
- {image ? ( + {image && (image.focus?.zoom ?? 1) > 1 ? ( + // Zoomed: clipped inside the frame's mat (Heritage pads its frames), not over it. +
+ +
+ ) : image ? ( ) : (