Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84c5b0c08e | ||
|
|
3caa1d1e1a |
@@ -34,8 +34,27 @@
|
||||
`/api/uploads/` (SVGs sandboxed).
|
||||
- **The demo church** (`npm run demo -- --template <id>`): Acacia Hill Church, fictional, with
|
||||
illustrated images; refuses to replace a site its admins published unless `--force`.
|
||||
- **End to end** (`npx playwright test` in apps/website, no database): every template's pages pass
|
||||
axe (WCAG 2.2 AA) and the SEO basics; screenshots at phone and desktop in `e2e/screens/`.
|
||||
- **End to end** (`npx playwright test` in apps/website, no database, a production build): every
|
||||
template's pages pass axe (WCAG 2.2 AA) and the SEO basics, with screenshots at phone and desktop in
|
||||
`e2e/screens/`; the admin's flows (edit, preview, publish; discard; a shared link, revoked;
|
||||
restore; a template switch; a Viewer; signing in from a deep admin page) and axe on every admin
|
||||
screen.
|
||||
- **The admin** (§4, §10): a dashboard with the setup checklist, pending changes, storage and notes
|
||||
about the church's colours; Template and style (the template, each homepage section's layout with
|
||||
the recommended ones first, the homepage order, the style settings); Pages (details, search
|
||||
engine title and description with a search result preview, the home page's sections, other pages'
|
||||
blocks: add, move, hide, remove; custom pages); Ministries and Leadership; the media library
|
||||
(uploads checked by their bytes, alt text, storage; **uploads stop when storage is full**); and
|
||||
Publish and history. Roles: a Viewer reads, an Editor and above changes and publishes, a Ministry
|
||||
leader edits only their own ministry. Every change comes from the site itself (same origin).
|
||||
- **Drafts, preview and publish** (§4): every change is a draft; the pending list says what changed,
|
||||
who and when, and any one can be **discarded**; one **Publish** for the whole site, with a note;
|
||||
every version is kept and any can be **restored** into the working copy (each version keeps the
|
||||
working copy's rows, never sent to visitors). The **preview** shows the working copy on the site's
|
||||
own addresses, fully clickable, with a bar above the page (phone / tablet / desktop width, Back to
|
||||
editing, Publish); a **shared preview link** works signed out for 7 days or until revoked, and
|
||||
can't change anything. Publish refreshes the public pages at once (`WEBSITE_CONTENT_CACHE_SECONDS`,
|
||||
30 by default, is how long they're kept otherwise).
|
||||
- The admin page signs people in and out; `/auth/problem` explains a refused sign-in.
|
||||
- **The church's export** (`scripts/export-church.ts`): `export.json` in
|
||||
`crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall.
|
||||
|
||||
@@ -8,7 +8,9 @@ section variants and style settings. Changes are drafts until an editor previews
|
||||
presses Publish; until the first publish visitors see Coming soon.
|
||||
|
||||
**State:** being built (2026-11-25): signing in through Accounts, the four templates and the public
|
||||
site, publishing, and the demo church. The admin's editing screens are next. Not released;
|
||||
site, the admin (editing, preview, publish, discard, restore, shared previews, media), and the demo
|
||||
church. Still to come: managing who has which role, messages and events in the admin (YouTube feed),
|
||||
responsive image sizes, the event feed, the Hub's "Get more storage", Lighthouse and the VM test. Not released;
|
||||
`website@1.0.0` is tagged when the plan is built.
|
||||
|
||||
**Signing in** (`backend/src/auth/`): the Website registers with the Hub (its install id is its
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Editing the working copy (WEBSITE-1.0-PLAN §4, §10): the site's design (template, section
|
||||
* variants, homepage order, style), pages and their sections or blocks, ministries and leaders.
|
||||
* Every change is a draft until Publish; each row records who changed it last (`updatedBy`).
|
||||
*
|
||||
* Shared facts (name, logo, colours, service times, contact) aren't here: they're the church
|
||||
* profile's, saved through Accounts (§2), and go live at once.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import { websiteTemplateSchema } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { BLOCK_SCHEMAS, isBlockType, SECTION_SCHEMAS } from '../site/sections.js';
|
||||
import { cleanDesign } from '../site/snapshot.js';
|
||||
import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
/** zod issues as `{ field: message }`, for the form. */
|
||||
function fieldsOf(e: z.ZodError): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const i of e.issues) out[i.path.join('.') || '_'] ??= i.message;
|
||||
return out;
|
||||
}
|
||||
|
||||
function check<T>(schema: z.ZodType<T>, body: unknown): T {
|
||||
const r = schema.safeParse(body);
|
||||
if (!r.success) throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fieldsOf(r.error));
|
||||
return r.data;
|
||||
}
|
||||
|
||||
// ─── Design ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getDesign(ctx: Ctx) {
|
||||
return cleanDesign(await ctx.db.siteDesign.findUnique({ where: { id: 1 } }));
|
||||
}
|
||||
|
||||
const designPatch = z.object({
|
||||
template: websiteTemplateSchema.optional(),
|
||||
variants: z.record(z.string(), z.string()).optional(),
|
||||
home: z.array(z.object({ section: sectionTypeSchema, hidden: z.boolean() })).max(SECTION_TYPES.length).optional(),
|
||||
style: z.object({
|
||||
sectionColour: z.enum(SECTION_COLOURS).optional(),
|
||||
spacing: z.enum(SPACINGS).optional(),
|
||||
buttons: z.enum(BUTTONS).optional(),
|
||||
images: z.enum(IMAGE_TREATMENTS).optional(),
|
||||
header: z.string().max(40).optional(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Changes the design. A template switch first moves everything still on the old template's
|
||||
* defaults to the new one's and keeps the church's own choices (§3); the rest of the patch then
|
||||
* applies. Returns what the switch moved, for the screen.
|
||||
*/
|
||||
export async function saveDesign(ctx: Ctx, body: unknown, by: Who) {
|
||||
const patch = check(designPatch, body);
|
||||
let design = await getDesign(ctx);
|
||||
let moved: { what: string; from: string; to: string }[] = [];
|
||||
if (patch.template && patch.template !== design.template) ({ design, changes: moved } = switchTemplate(design, patch.template));
|
||||
for (const [section, variant] of Object.entries(patch.variants ?? {})) {
|
||||
if (!SECTION_TYPES.includes(section as SectionType) || !isVariant(section as SectionType, variant)) throw new ApiError(400, 'VALIDATION', `"${variant}" isn't a layout for ${section}.`);
|
||||
(design.variants as Record<string, string>)[section] = variant;
|
||||
}
|
||||
if (patch.home) {
|
||||
if (new Set(patch.home.map((e) => e.section)).size !== patch.home.length) throw new ApiError(400, 'VALIDATION', 'Each homepage section can be listed once.');
|
||||
design.home = [...patch.home, ...design.home.filter((e) => !patch.home!.some((p) => p.section === e.section)).map((e) => ({ ...e, hidden: true }))];
|
||||
}
|
||||
if (patch.style) {
|
||||
const { header, ...rest } = patch.style;
|
||||
if (header && !(TEMPLATE_HEADERS[design.template] as readonly string[]).includes(header)) throw new ApiError(400, 'VALIDATION', `"${header}" isn't a header for ${design.template}.`);
|
||||
design.style = { ...design.style, ...rest, ...(header ? { header } : {}) };
|
||||
}
|
||||
const data = { template: design.template, variants: design.variants as never, home: design.home as never, style: design.style as never, updatedBy: by.id };
|
||||
await ctx.db.siteDesign.upsert({ where: { id: 1 }, create: { id: 1, ...data }, update: data });
|
||||
return { design, moved };
|
||||
}
|
||||
|
||||
// ─── Pages and sections ─────────────────────────────────────────────────────────
|
||||
|
||||
const slugSchema = z.string().trim().toLowerCase().regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Lower-case letters, numbers and dashes').max(80);
|
||||
const RESERVED = new Set(['admin', 'api', 'auth', 'preview', 'events', 'home', 'sitemap.xml', 'robots.txt', 'uploads']);
|
||||
|
||||
const pagePatch = z.object({
|
||||
title: z.string().trim().min(1).max(120).optional(),
|
||||
slug: slugSchema.optional(),
|
||||
seoTitle: z.string().trim().max(70).nullable().optional(),
|
||||
description: z.string().trim().max(300).nullable().optional(),
|
||||
navLabel: z.string().trim().max(40).nullable().optional(),
|
||||
inNav: z.boolean().optional(),
|
||||
position: z.int().min(0).max(1000).optional(),
|
||||
imageId: z.string().uuid().nullable().optional(),
|
||||
});
|
||||
|
||||
export async function listPages(ctx: Ctx) {
|
||||
const pages = await ctx.db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }] });
|
||||
return pages.map((p) => ({ id: p.id, kind: p.kind, slug: p.slug, title: p.title, inNav: p.inNav, position: p.position, path: p.kind === 'home' ? '/' : `/${p.slug}` }));
|
||||
}
|
||||
|
||||
export async function getPage(ctx: Ctx, id: string) {
|
||||
const page = await ctx.db.page.findUnique({ where: { id } });
|
||||
if (!page || page.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That page doesn\'t exist.');
|
||||
const sections = await ctx.db.section.findMany({ where: { pageId: id }, orderBy: { position: 'asc' } });
|
||||
return { ...page, sections };
|
||||
}
|
||||
|
||||
async function slugFree(ctx: Ctx, slug: string, except?: string) {
|
||||
if (RESERVED.has(slug)) throw new ApiError(400, 'VALIDATION', `"${slug}" is used by the site itself. Choose another address.`, { slug: 'Used by the site itself' });
|
||||
const other = await ctx.db.page.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } });
|
||||
if (other && !other.archivedAt) throw new ApiError(409, 'SLUG_TAKEN', 'Another page already has that address.', { slug: 'Another page has it' });
|
||||
if (other) await ctx.db.page.update({ where: { id: other.id }, data: { slug: `${other.slug}-${other.id.slice(0, 6)}` } });
|
||||
}
|
||||
|
||||
export async function savePage(ctx: Ctx, id: string, body: unknown, by: Who) {
|
||||
const page = await getPage(ctx, id);
|
||||
const patch = check(pagePatch, body);
|
||||
if (page.kind === 'home') delete patch.slug;
|
||||
if (patch.slug && patch.slug !== page.slug) await slugFree(ctx, patch.slug, id);
|
||||
await ctx.db.page.update({ where: { id }, data: { ...patch, updatedBy: by.id } });
|
||||
return getPage(ctx, id);
|
||||
}
|
||||
|
||||
/** A custom page (§3, "Pages from blocks"), starting with one text block. */
|
||||
export async function createPage(ctx: Ctx, body: unknown, by: Who) {
|
||||
const p = check(z.object({ title: z.string().trim().min(1).max(120), slug: slugSchema }), body);
|
||||
await slugFree(ctx, p.slug);
|
||||
const last = await ctx.db.page.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
|
||||
const page = await ctx.db.page.create({ data: { kind: 'custom', slug: p.slug, title: p.title, position: (last?.position ?? 0) + 1, updatedBy: by.id } });
|
||||
await ctx.db.section.create({ data: { pageId: page.id, type: 'text', position: 0, data: { heading: null, body: '' }, updatedBy: by.id } });
|
||||
return getPage(ctx, page.id);
|
||||
}
|
||||
|
||||
/** Archive, never delete (§4): restored by Discard or by restoring a version. The home page stays. */
|
||||
export async function archivePage(ctx: Ctx, id: string, by: Who) {
|
||||
const page = await getPage(ctx, id);
|
||||
if (page.kind === 'home') throw new ApiError(400, 'HOME', 'The home page can\'t be removed.');
|
||||
await ctx.db.page.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
|
||||
}
|
||||
|
||||
function schemaFor(type: string): z.ZodType {
|
||||
const s = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
|
||||
if (!s) throw new ApiError(400, 'VALIDATION', `"${type}" isn't a section or block.`);
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* The home page's section of `type` (one each; its layout is the design's, §3), created the first
|
||||
* time it's saved.
|
||||
*/
|
||||
export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, body: unknown, by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
if (page.kind !== 'home' || !SECTION_TYPES.includes(type as SectionType)) throw new ApiError(400, 'VALIDATION', 'That isn\'t a homepage section.');
|
||||
const data = check(schemaFor(type), (body as { data?: unknown })?.data);
|
||||
const existing = page.sections.find((s) => s.type === type);
|
||||
if (existing) await ctx.db.section.update({ where: { id: existing.id }, data: { data: data as never, updatedBy: by.id } });
|
||||
else await ctx.db.section.create({ data: { pageId, type, position: SECTION_TYPES.indexOf(type as SectionType), data: data as never, updatedBy: by.id } });
|
||||
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() });
|
||||
|
||||
/** The blocks of any other page: add, change, move, remove. */
|
||||
export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
if (page.kind === 'home') throw new ApiError(400, 'VALIDATION', 'The home page has its sections; blocks are for the other pages.');
|
||||
const { type } = check(z.object({ type: z.string() }), body);
|
||||
if (!isBlockType(type)) throw new ApiError(400, 'VALIDATION', `"${type}" isn't a block.`);
|
||||
const data = check(schemaFor(type), type === 'quote' ? { quote: 'Your quote here' } : type === 'cta' ? { heading: 'Your heading here' } : {});
|
||||
await ctx.db.section.create({ data: { pageId, type, position: page.sections.length, data: data as never, updatedBy: by.id } });
|
||||
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, body: unknown, by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
const s = page.sections.find((x) => x.id === sectionId);
|
||||
if (!s) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
|
||||
const patch = check(blockPatch, body);
|
||||
const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data);
|
||||
await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } });
|
||||
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
export async function moveBlock(ctx: Ctx, pageId: string, sectionId: string, direction: 'up' | 'down', by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
const list = [...page.sections];
|
||||
const i = list.findIndex((x) => x.id === sectionId);
|
||||
const j = direction === 'up' ? i - 1 : i + 1;
|
||||
if (i < 0 || j < 0 || j >= list.length) return page;
|
||||
[list[i], list[j]] = [list[j]!, list[i]!];
|
||||
for (const [n, s] of list.entries()) await ctx.db.section.update({ where: { id: s.id }, data: { position: n, updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
export async function removeBlock(ctx: Ctx, pageId: string, sectionId: string, by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
if (!page.sections.some((x) => x.id === sectionId)) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
|
||||
await ctx.db.section.delete({ where: { id: sectionId } });
|
||||
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
// ─── Ministries and leaders ─────────────────────────────────────────────────────
|
||||
|
||||
const ministrySchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
slug: slugSchema.optional(),
|
||||
summary: z.string().trim().max(300).nullable().default(null),
|
||||
body: z.string().trim().max(8000).nullable().default(null),
|
||||
imageId: z.string().uuid().nullable().default(null),
|
||||
position: z.int().min(0).max(1000).optional(),
|
||||
});
|
||||
|
||||
const leaderSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
role: z.string().trim().max(120).nullable().default(null),
|
||||
bio: z.string().trim().max(4000).nullable().default(null),
|
||||
photoId: z.string().uuid().nullable().default(null),
|
||||
position: z.int().min(0).max(1000).optional(),
|
||||
});
|
||||
|
||||
const slugify = (s: string) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'ministry';
|
||||
|
||||
export async function listMinistries(ctx: Ctx) {
|
||||
return ctx.db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] });
|
||||
}
|
||||
|
||||
export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, by: Who) {
|
||||
const m = check(ministrySchema, body);
|
||||
const slug = m.slug ?? slugify(m.name);
|
||||
const clash = await ctx.db.ministry.findFirst({ where: { slug, ...(id ? { NOT: { id } } : {}) } });
|
||||
if (clash) throw new ApiError(409, 'SLUG_TAKEN', 'Another ministry already has that name.', { name: 'Another ministry has it' });
|
||||
const data = { name: m.name, slug, summary: m.summary, body: m.body, imageId: m.imageId, ...(m.position !== undefined ? { position: m.position } : {}), updatedBy: by.id };
|
||||
if (id) {
|
||||
const row = await ctx.db.ministry.findUnique({ where: { id } });
|
||||
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That ministry doesn\'t exist.');
|
||||
return ctx.db.ministry.update({ where: { id }, data });
|
||||
}
|
||||
const last = await ctx.db.ministry.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
|
||||
return ctx.db.ministry.create({ data: { ...data, position: m.position ?? (last?.position ?? -1) + 1 } });
|
||||
}
|
||||
|
||||
export async function archiveMinistry(ctx: Ctx, id: string, by: Who) {
|
||||
await ctx.db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
|
||||
}
|
||||
|
||||
export async function listLeaders(ctx: Ctx) {
|
||||
return ctx.db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] });
|
||||
}
|
||||
|
||||
export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by: Who) {
|
||||
const l = check(leaderSchema, body);
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...(l.position !== undefined ? { position: l.position } : {}), updatedBy: by.id };
|
||||
if (id) {
|
||||
const row = await ctx.db.leader.findUnique({ where: { id } });
|
||||
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That person isn\'t on the team.');
|
||||
return ctx.db.leader.update({ where: { id }, data });
|
||||
}
|
||||
const last = await ctx.db.leader.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
|
||||
return ctx.db.leader.create({ data: { ...data, position: l.position ?? (last?.position ?? -1) + 1 } });
|
||||
}
|
||||
|
||||
export async function archiveLeader(ctx: Ctx, id: string, by: Who) {
|
||||
await ctx.db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* The media library and storage (WEBSITE-1.0-PLAN §10, ROADMAP-v3 §10): uploads of photos (JPEG,
|
||||
* PNG, WebP), checked by their bytes, not their name. 5 GB included; the licence's
|
||||
* `limits.storageBytes` says more once extra storage is bought. **When it's full, uploads stop**
|
||||
* (decision 12) until more is bought; what's already uploaded keeps showing.
|
||||
*
|
||||
* Responsive sizes (WebP and JPEG per width) come next; for now the file is served as uploaded.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { defaultUploadDir } from '../demo/demoChurch.js';
|
||||
import { INCLUDED_STORAGE_BYTES } from '../hub/client.js';
|
||||
import { hubPublicKey, verifyToken } from '../hub/licence.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { mediaUrl } from '../site/snapshot.js';
|
||||
|
||||
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
type Kind = { ext: string; mime: string };
|
||||
|
||||
/** What the bytes are, whatever the name says. */
|
||||
export function sniff(b: Buffer): Kind | null {
|
||||
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
|
||||
if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
|
||||
if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Width and height from the file's header (PNG, JPEG, WebP), or nulls. */
|
||||
export function dimensions(b: Buffer, kind: Kind): { width: number | null; height: number | null } {
|
||||
try {
|
||||
if (kind.ext === 'png') return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
|
||||
if (kind.ext === 'webp') {
|
||||
const chunk = b.toString('ascii', 12, 16);
|
||||
if (chunk === 'VP8X') return { width: 1 + b.readUIntLE(24, 3), height: 1 + b.readUIntLE(27, 3) };
|
||||
if (chunk === 'VP8 ') return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
|
||||
if (chunk === 'VP8L') {
|
||||
const bits = b.readUInt32LE(21);
|
||||
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
|
||||
}
|
||||
}
|
||||
if (kind.ext === 'jpg') {
|
||||
let i = 2;
|
||||
while (i < b.length) {
|
||||
if (b[i] !== 0xff) break;
|
||||
const marker = b[i + 1]!;
|
||||
const len = b.readUInt16BE(i + 2);
|
||||
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { height: b.readUInt16BE(i + 5), width: b.readUInt16BE(i + 7) };
|
||||
i += 2 + len;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A header we can't read: no dimensions, the image still shows.
|
||||
}
|
||||
return { width: null, height: null };
|
||||
}
|
||||
|
||||
export async function storage(ctx: Ctx): Promise<{ usedBytes: number; limitBytes: number; full: boolean; percent: number }> {
|
||||
const [sum, token, installId] = await Promise.all([
|
||||
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
|
||||
ctx.settings.get('hub_licence'),
|
||||
ctx.settings.get('hub_install_id'),
|
||||
]);
|
||||
const claims = verifyToken(token, hubPublicKey(ctx)) as { installId?: string; limits?: { storageBytes?: number } } | null;
|
||||
const fromLicence = claims && claims.installId === installId ? claims.limits?.storageBytes : undefined;
|
||||
const limitBytes = typeof fromLicence === 'number' ? fromLicence : INCLUDED_STORAGE_BYTES;
|
||||
const usedBytes = sum._sum.bytes ?? 0;
|
||||
return { usedBytes, limitBytes, full: usedBytes >= limitBytes, percent: limitBytes ? Math.min(100, Math.round((usedBytes / limitBytes) * 100)) : 100 };
|
||||
}
|
||||
|
||||
export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defaultUploadDir());
|
||||
|
||||
export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
|
||||
if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.');
|
||||
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
|
||||
const kind = sniff(body);
|
||||
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.');
|
||||
const s = await storage(ctx);
|
||||
if (s.usedBytes + body.length > s.limitBytes) {
|
||||
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. To get more (5 GB at a time), contact Cross Code; everything already uploaded keeps showing.');
|
||||
}
|
||||
const now = ctx.now();
|
||||
const rel = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.${kind.ext}`;
|
||||
const file = path.join(uploadDir(ctx), rel);
|
||||
await fs.mkdir(path.dirname(file), { recursive: true });
|
||||
await fs.writeFile(file, body, { mode: 0o644 });
|
||||
const { width, height } = dimensions(body, kind);
|
||||
const row = await ctx.db.mediaAsset.create({ data: { filename: rel, mime: kind.mime, bytes: body.length, width, height, alt: alt.trim().slice(0, 500), uploadedBy: by } });
|
||||
return { ...row, url: mediaUrl(row.filename) };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Shared previews (WEBSITE-1.0-PLAN §4): a link for someone without an account (the pastor), that
|
||||
* shows the working copy as it is when opened, for 7 days or until revoked. It can't edit or
|
||||
* publish, and its pages are `noindex`. Only the token's hash is stored; the link is shown once.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
|
||||
export const PREVIEW_DAYS = 7;
|
||||
|
||||
export async function createPreviewLink(ctx: Ctx, by: { id: string; role: string }) {
|
||||
const token = randomToken();
|
||||
const now = ctx.now();
|
||||
const row = await ctx.db.previewLink.create({ data: { tokenHash: hashToken(token), createdBy: by.id, createdAt: now, expiresAt: new Date(now.getTime() + PREVIEW_DAYS * 864e5) } });
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_created', targetType: 'preview_link', targetId: row.id });
|
||||
return { id: row.id, url: `${ctx.config.publicUrl}/preview/${token}`, expiresAt: row.expiresAt.toISOString() };
|
||||
}
|
||||
|
||||
export async function listPreviewLinks(ctx: Ctx) {
|
||||
const now = ctx.now();
|
||||
const rows = await ctx.db.previewLink.findMany({ orderBy: { createdAt: 'desc' } });
|
||||
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
|
||||
return rows.map((r) => ({
|
||||
id: r.id, createdAt: r.createdAt.toISOString(), expiresAt: r.expiresAt.toISOString(), by: names.get(r.createdBy) ?? null,
|
||||
active: !r.revokedAt && r.expiresAt > now, revokedAt: r.revokedAt?.toISOString() ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function revokePreviewLink(ctx: Ctx, id: string, by: { id: string; role: string }) {
|
||||
const row = await ctx.db.previewLink.findUnique({ where: { id } });
|
||||
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That preview link doesn\'t exist.');
|
||||
await ctx.db.previewLink.update({ where: { id }, data: { revokedAt: ctx.now() } });
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_revoked', targetType: 'preview_link', targetId: id });
|
||||
}
|
||||
|
||||
export async function previewTokenValid(ctx: Ctx, token: string | undefined): Promise<boolean> {
|
||||
if (!token || token.length > 200) return false;
|
||||
const row = await ctx.db.previewLink.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||
return !!row && !row.revokedAt && row.expiresAt > ctx.now();
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* The admin API (WEBSITE-1.0-PLAN §4, §10), under /api/v1/admin, signed in through Accounts.
|
||||
* Roles: a Viewer reads; an Editor (and Admin, Owner) changes anything, publishes and shares
|
||||
* previews; a Ministry leader changes only their own ministry, and their changes wait for an
|
||||
* Editor or above to publish (decision 11). Every change comes from the site itself (sameOrigin).
|
||||
*/
|
||||
import express, { type Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { atLeast, requireRole } from '../auth/sessions.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { ApiError, handle, sameOrigin } from '../http.js';
|
||||
import { buildPalette } from '../site/palette.js';
|
||||
import { mediaUrl, publish } from '../site/snapshot.js';
|
||||
import { TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_VARIANTS } from '../site/variants.js';
|
||||
import { changes, discard, restore } from '../site/workingCopy.js';
|
||||
import * as content from './content.js';
|
||||
import { MAX_UPLOAD_BYTES, storage, upload } from './media.js';
|
||||
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
|
||||
|
||||
const who = (req: Request) => ({ id: req.signed!.user.id, role: req.signed!.user.role });
|
||||
const param = (req: Request, name: string) => String(req.params[name] ?? '');
|
||||
|
||||
export function adminRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production));
|
||||
r.use(requireRole(ctx, 'viewer'));
|
||||
const json = express.json({ limit: '256kb' });
|
||||
const editor = requireRole(ctx, 'editor');
|
||||
|
||||
r.get('/me', handle((req) => ({ user: req.signed!.user, mfa: req.signed!.mfa })));
|
||||
|
||||
/** The dashboard: pending changes, the last publish, storage, and the setup checklist (§10). */
|
||||
r.get('/overview', handle(async () => {
|
||||
const [pending, last, s, church, design, pages, ministries] = await Promise.all([
|
||||
changes(ctx), ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } }), storage(ctx), churchProfile(ctx),
|
||||
ctx.db.siteDesign.findUnique({ where: { id: 1 } }), content.listPages(ctx), content.listMinistries(ctx),
|
||||
]);
|
||||
const palette = church ? buildPalette(church.branding.colours.primary, church.branding.colours.accent) : null;
|
||||
return {
|
||||
pending: pending.length,
|
||||
lastPublished: last ? { number: last.number, at: last.publishedAt.toISOString() } : null,
|
||||
storage: s,
|
||||
colourNotes: palette?.notes ?? [],
|
||||
checklist: [
|
||||
{ key: 'template', label: 'Choose your template', done: !!design, href: '/admin/template' },
|
||||
{ key: 'profile', label: 'Add your service times and address (your church profile in Accounts)', done: !!church && church.serviceTimes.length > 0 && !!church.contact.address, href: null },
|
||||
{ key: 'pages', label: 'Write your home page and Plan your visit', done: pages.some((p) => p.kind === 'visit'), href: '/admin/pages' },
|
||||
{ key: 'ministries', label: 'Add your ministries', done: ministries.length > 0, href: '/admin/ministries' },
|
||||
{ key: 'publish', label: 'Preview and publish', done: !!last, href: '/admin/publish' },
|
||||
],
|
||||
};
|
||||
}));
|
||||
|
||||
// ─── Design ───
|
||||
r.get('/design', handle(async () => ({ design: await content.getDesign(ctx), options: { variants: TEMPLATE_VARIANTS, headers: TEMPLATE_HEADERS, home: TEMPLATE_HOME_ORDER } })));
|
||||
r.put('/design', editor, json, handle((req) => content.saveDesign(ctx, req.body, who(req))));
|
||||
|
||||
// ─── Pages ───
|
||||
r.get('/pages', handle(() => content.listPages(ctx)));
|
||||
r.post('/pages', editor, json, handle((req) => content.createPage(ctx, req.body, who(req))));
|
||||
r.get('/pages/:id', handle((req) => content.getPage(ctx, param(req, 'id'))));
|
||||
r.put('/pages/:id', editor, json, handle((req) => content.savePage(ctx, param(req, 'id'), req.body, who(req))));
|
||||
r.delete('/pages/:id', editor, handle(async (req) => { await content.archivePage(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
r.put('/pages/:id/home/:type', editor, json, handle((req) => content.saveHomeSection(ctx, param(req, 'id'), param(req, 'type'), req.body, who(req))));
|
||||
r.post('/pages/:id/blocks', editor, json, handle((req) => content.addBlock(ctx, param(req, 'id'), req.body, who(req))));
|
||||
r.put('/pages/:id/blocks/:sid', editor, json, handle((req) => content.saveBlock(ctx, param(req, 'id'), param(req, 'sid'), req.body, who(req))));
|
||||
r.post('/pages/:id/blocks/:sid/move', editor, json, handle((req) => content.moveBlock(ctx, param(req, 'id'), param(req, 'sid'), req.body?.direction === 'up' ? 'up' : 'down', who(req))));
|
||||
r.delete('/pages/:id/blocks/:sid', editor, handle((req) => content.removeBlock(ctx, param(req, 'id'), param(req, 'sid'), who(req))));
|
||||
|
||||
// ─── Ministries (a Ministry leader: their own only) and leaders ───
|
||||
r.get('/ministries', handle(() => content.listMinistries(ctx)));
|
||||
r.post('/ministries', editor, json, handle((req) => content.saveMinistry(ctx, null, req.body, who(req))));
|
||||
r.put('/ministries/:id', json, handle((req) => {
|
||||
const s = req.signed!;
|
||||
if (!atLeast(s.user.role, 'editor') && !(s.user.role === 'ministry_leader' && s.user.ministryId === param(req, 'id'))) {
|
||||
throw new ApiError(403, 'FORBIDDEN', 'You can change your own ministry only.');
|
||||
}
|
||||
return content.saveMinistry(ctx, param(req, 'id'), req.body, who(req));
|
||||
}));
|
||||
r.delete('/ministries/:id', editor, handle(async (req) => { await content.archiveMinistry(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
r.get('/leaders', handle(() => content.listLeaders(ctx)));
|
||||
r.post('/leaders', editor, json, handle((req) => content.saveLeader(ctx, null, req.body, who(req))));
|
||||
r.put('/leaders/:id', editor, json, handle((req) => content.saveLeader(ctx, param(req, 'id'), req.body, who(req))));
|
||||
r.delete('/leaders/:id', editor, handle(async (req) => { await content.archiveLeader(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
|
||||
// ─── Media library and storage ───
|
||||
r.get('/media', handle(async () => {
|
||||
const rows = await ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } });
|
||||
return { storage: await storage(ctx), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes })) };
|
||||
}));
|
||||
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)));
|
||||
r.put('/media/:id', editor, json, handle(async (req) => {
|
||||
const alt = String(req.body?.alt ?? '').trim().slice(0, 500);
|
||||
const m = await ctx.db.mediaAsset.update({ where: { id: param(req, 'id') }, data: { alt } }).catch(() => null);
|
||||
if (!m) throw new ApiError(404, 'NOT_FOUND', 'That image doesn\'t exist.');
|
||||
return { id: m.id, alt: m.alt };
|
||||
}));
|
||||
|
||||
// ─── Publish, discard, restore, versions, shared previews (§4) ───
|
||||
r.get('/changes', handle(() => changes(ctx)));
|
||||
r.post('/publish', editor, json, handle(async (req) => {
|
||||
const pending = await changes(ctx);
|
||||
const first = !(await ctx.db.siteVersion.findFirst());
|
||||
if (!pending.length && !first) throw new ApiError(409, 'NOTHING_TO_PUBLISH', 'There are no changes to publish.');
|
||||
const note = typeof req.body?.note === 'string' && req.body.note.trim() ? req.body.note.trim().slice(0, 500) : null;
|
||||
const v = await publish(ctx, who(req), note);
|
||||
return { number: v.number, publishedAt: v.publishedAt.toISOString(), changes: pending.length };
|
||||
}));
|
||||
r.post('/discard', editor, json, handle((req) => discard(ctx, String(req.body?.key ?? ''), who(req))));
|
||||
r.get('/versions', handle(async () => {
|
||||
const rows = await ctx.db.siteVersion.findMany({ orderBy: { number: 'desc' }, take: 100, select: { number: true, publishedAt: true, publishedBy: true, note: true } });
|
||||
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
|
||||
return rows.map((v) => ({ number: v.number, publishedAt: v.publishedAt.toISOString(), by: names.get(v.publishedBy) ?? null, note: v.note }));
|
||||
}));
|
||||
r.post('/versions/:n/restore', editor, handle((req) => restore(ctx, Number(param(req, 'n')), who(req))));
|
||||
r.get('/preview-links', editor, handle(() => listPreviewLinks(ctx)));
|
||||
r.post('/preview-links', editor, handle((req) => createPreviewLink(ctx, who(req))));
|
||||
r.delete('/preview-links/:id', editor, handle(async (req) => { await revokePreviewLink(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
|
||||
return r;
|
||||
}
|
||||
@@ -16,13 +16,15 @@ import path from 'node:path';
|
||||
import express from 'express';
|
||||
import type { Ctx } from './context.js';
|
||||
import { authRouter } from './auth/routes.js';
|
||||
import { requireRole } from './auth/sessions.js';
|
||||
import { adminRouter } from './admin/routes.js';
|
||||
import { previewTokenValid } from './admin/previewLinks.js';
|
||||
import { atLeast, currentSession } from './auth/sessions.js';
|
||||
import { dbUp } from './hub/client.js';
|
||||
import { ApiError, handle, sendError } from './http.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
import { linksRouter } from './links/routes.js';
|
||||
import { defaultUploadDir } from './demo/demoChurch.js';
|
||||
import { siteContent } from './site/content.js';
|
||||
import { previewContent, siteContent } from './site/content.js';
|
||||
import { siteStatus } from './site/status.js';
|
||||
|
||||
export function createApp(ctx: Ctx) {
|
||||
@@ -45,6 +47,14 @@ export function createApp(ctx: Ctx) {
|
||||
|
||||
const site = express.Router();
|
||||
site.get('/status', handle(() => siteStatus(ctx)));
|
||||
// The preview (§4): the working copy, for a signed-in admin or a shared preview link. Never cached.
|
||||
site.get('/preview', handle(async (req, res) => {
|
||||
const signed = await currentSession(ctx, req);
|
||||
if (!signed && !(await previewTokenValid(ctx, req.get('x-preview-token')))) throw new ApiError(401, 'NO_PREVIEW', 'This preview has ended, or you need to sign in.');
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.set('X-Robots-Tag', 'noindex, nofollow');
|
||||
return { ...(await previewContent(ctx)), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') } };
|
||||
}));
|
||||
site.get('/content', handle(async (_req, res) => {
|
||||
// Short: Publish shows within a minute even where a proxy caches.
|
||||
res.set('Cache-Control', 'public, max-age=30');
|
||||
@@ -64,11 +74,7 @@ export function createApp(ctx: Ctx) {
|
||||
app.use('/api', authRouter(ctx));
|
||||
app.use('/api', linksRouter(ctx));
|
||||
|
||||
const admin = express.Router();
|
||||
admin.use(express.json({ limit: '256kb' }));
|
||||
admin.use(requireRole(ctx, 'viewer'));
|
||||
admin.get('/me', handle(async (req) => ({ user: req.signed!.user, mfa: req.signed!.mfa })));
|
||||
app.use('/api/v1/admin', admin);
|
||||
app.use('/api/v1/admin', adminRouter(ctx));
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and
|
||||
* Events' /api/v2) and async handlers.
|
||||
* Events' /api/v2), async handlers, and a same-origin check on everything that changes something.
|
||||
*/
|
||||
import type { Request, RequestHandler, Response } from 'express';
|
||||
|
||||
@@ -19,8 +19,30 @@ export function sendError(res: Response, e: unknown) {
|
||||
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
|
||||
}
|
||||
|
||||
export const handle = (fn: (req: Request, res: Response) => Promise<unknown>): RequestHandler => (req, res) => {
|
||||
fn(req, res).then((out) => {
|
||||
/** A handler whose result is sent as JSON; an error (thrown or rejected) as `{ error }`. */
|
||||
export const handle = (fn: (req: Request, res: Response) => unknown): RequestHandler => (req, res) => {
|
||||
Promise.resolve().then(() => fn(req, res)).then((out) => {
|
||||
if (out !== undefined && !res.headersSent) res.json(out);
|
||||
}).catch((e) => sendError(res, e));
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes only from the site itself: an `Origin` (or `Referer`) on the site's own address, as
|
||||
* Accounts' http.ts. With SameSite=Lax cookies this stops another site posting on someone's behalf.
|
||||
*/
|
||||
export function sameOrigin(publicUrl: string, production: boolean): RequestHandler {
|
||||
const own = new URL(publicUrl).origin;
|
||||
return (req, res, next) => {
|
||||
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
|
||||
let origin = req.get('origin') ?? null;
|
||||
if (!origin && req.get('referer')) {
|
||||
try {
|
||||
origin = new URL(req.get('referer')!).origin;
|
||||
} catch {
|
||||
origin = null;
|
||||
}
|
||||
}
|
||||
if (origin === own || (!production && origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin))) return next();
|
||||
return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'That request didn\'t come from this site.' } });
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { buildPalette, type Palette } from './palette.js';
|
||||
import { mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { buildSnapshot, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
|
||||
|
||||
export type SiteEvent = {
|
||||
@@ -51,7 +51,8 @@ export type SiteContent =
|
||||
| (Common & {
|
||||
mode: 'published';
|
||||
version: number;
|
||||
snapshot: Snapshot;
|
||||
/** Without its `source` (the working copy's rows): visitors never get internal ids or hidden sections. */
|
||||
snapshot: Omit<Snapshot, 'source'>;
|
||||
/** Per page path: whether the header sits over the hero (Bold's transparent header, §3). */
|
||||
transparentHeader: Record<string, boolean>;
|
||||
messages: SiteMessage[];
|
||||
@@ -129,8 +130,19 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
|
||||
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
|
||||
}
|
||||
|
||||
/** What visitors see: the latest published version, else Coming soon. */
|
||||
export async function siteContent(ctx: Ctx): Promise<SiteContent> {
|
||||
const [church, published] = await Promise.all([churchProfile(ctx), publishedSnapshot(ctx)]);
|
||||
return contentFrom(ctx, church, published);
|
||||
}
|
||||
|
||||
/** The preview (§4): the working copy as it would look published, whatever was published before. */
|
||||
export async function previewContent(ctx: Ctx): Promise<SiteContent> {
|
||||
const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx)]);
|
||||
return contentFrom(ctx, church, { number: 0, publishedAt: ctx.now(), snapshot });
|
||||
}
|
||||
|
||||
async function contentFrom(ctx: Ctx, church: Church | null, published: { number: number; publishedAt: Date; snapshot: Snapshot } | null): Promise<SiteContent> {
|
||||
if (!published) {
|
||||
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
|
||||
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
|
||||
@@ -139,7 +151,7 @@ export async function siteContent(ctx: Ctx): Promise<SiteContent> {
|
||||
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
|
||||
};
|
||||
}
|
||||
const { snapshot } = published;
|
||||
const { source: _source, ...snapshot } = published.snapshot;
|
||||
const template = snapshot.design.template;
|
||||
const transparentHeader = Object.fromEntries(snapshot.pages.map((p) => {
|
||||
const hero = p.sections[0]?.type === 'hero' ? (p.sections[0].variant as Variant<'hero'>) : null;
|
||||
|
||||
@@ -41,6 +41,8 @@ export type Snapshot = {
|
||||
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
|
||||
/** Every image the sections refer to, by media id. */
|
||||
media: Record<string, Image>;
|
||||
/** The working copy's rows at publish time: Restore and Discard copy from here (§4). */
|
||||
source: Source;
|
||||
};
|
||||
|
||||
export const mediaUrl = (filename: string) => `/api/uploads/${filename.split('/').map(encodeURIComponent).join('/')}`;
|
||||
@@ -62,16 +64,50 @@ export function cleanDesign(saved: { template: string; variants: unknown; home:
|
||||
return { template, variants: variants as SiteDesign['variants'], home: home.filter((e, i) => home.findIndex((x) => x.section === e.section) === i), style };
|
||||
}
|
||||
|
||||
/** The working copy as a snapshot. */
|
||||
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
/** The working copy's rows, as saved (the source of a snapshot, so a version can be restored, §4). */
|
||||
export type Source = {
|
||||
design: { template: string; variants: unknown; home: unknown; style: unknown } | null;
|
||||
pages: {
|
||||
id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null;
|
||||
inNav: boolean; position: number; imageId: string | null;
|
||||
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[];
|
||||
}[];
|
||||
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; position: number }[];
|
||||
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; position: number }[];
|
||||
};
|
||||
|
||||
/** Every page, section, ministry and leader that isn't archived, with who last changed it. */
|
||||
export async function readWorkingCopy(ctx: Ctx) {
|
||||
const db = ctx.db;
|
||||
const [design, pages, ministries, leaders, media] = await Promise.all([
|
||||
const [design, pages, ministries, leaders] = await Promise.all([
|
||||
db.siteDesign.findUnique({ where: { id: 1 } }),
|
||||
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
|
||||
db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.mediaAsset.findMany(),
|
||||
]);
|
||||
return { design, pages, ministries, leaders };
|
||||
}
|
||||
|
||||
export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source {
|
||||
return {
|
||||
design: w.design ? { template: w.design.template, variants: w.design.variants, home: w.design.home, style: w.design.style } : null,
|
||||
pages: w.pages.map((p) => ({
|
||||
id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav,
|
||||
position: p.position, imageId: p.imageId,
|
||||
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })),
|
||||
})),
|
||||
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position })),
|
||||
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position })),
|
||||
};
|
||||
}
|
||||
|
||||
/** The working copy as a snapshot (what Publish saves, and what the preview shows). */
|
||||
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
const [w, media] = await Promise.all([readWorkingCopy(ctx), ctx.db.mediaAsset.findMany()]);
|
||||
return snapshotFrom(toSource(w), media);
|
||||
}
|
||||
|
||||
export function snapshotFrom(source: Source, media: { id: string; filename: string; alt: string; width: number | null; height: number | null }[]): Snapshot {
|
||||
const images = new Map(media.map((m) => [m.id, { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } satisfies Image]));
|
||||
const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null);
|
||||
const used: Record<string, Image> = {};
|
||||
@@ -84,12 +120,12 @@ export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
};
|
||||
walk(data);
|
||||
};
|
||||
const d = cleanDesign(design);
|
||||
const snapshotPages: SnapshotPage[] = pages.map((p) => {
|
||||
const d = cleanDesign(source.design);
|
||||
const snapshotPages: SnapshotPage[] = source.pages.map((p) => {
|
||||
const sections: SnapshotSection[] = [];
|
||||
if (p.kind === 'home') {
|
||||
// The homepage: the design's order and variants, each section's data from the page.
|
||||
const byType = new Map(p.sections.map((s) => [s.type, s]));
|
||||
const byType = new Map(p.sections.map((x) => [x.type, x]));
|
||||
for (const entry of d.home) {
|
||||
if (entry.hidden) continue;
|
||||
const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
|
||||
@@ -98,12 +134,12 @@ export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
sections.push({ type: entry.section, variant: d.variants[entry.section], data });
|
||||
}
|
||||
} else {
|
||||
for (const s of p.sections) {
|
||||
if (s.hidden) continue;
|
||||
const data = parseSectionData(s.type, s.data);
|
||||
for (const x of p.sections) {
|
||||
if (x.hidden) continue;
|
||||
const data = parseSectionData(x.type, x.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: s.type, variant: s.variant, data });
|
||||
sections.push({ type: x.type, variant: x.variant, data });
|
||||
}
|
||||
}
|
||||
return {
|
||||
@@ -115,9 +151,10 @@ export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
v: SNAPSHOT_VERSION,
|
||||
design: d,
|
||||
pages: snapshotPages,
|
||||
ministries: ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
|
||||
leaders: leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
|
||||
ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
|
||||
leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
|
||||
media: used,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Pending changes, Discard and Restore (WEBSITE-1.0-PLAN §4). The working copy is compared with
|
||||
* the latest published version's `source`, item by item: the site's design, each page (with its
|
||||
* sections), each ministry and each leader.
|
||||
*
|
||||
* changes(ctx) what Publish would put live: added, changed or removed, who and when
|
||||
* discard(ctx, key) one item back to its published state (an added one is archived)
|
||||
* restore(ctx, n) a whole version back into the working copy (then previewed and published
|
||||
* like any other change; nothing is lost)
|
||||
*
|
||||
* Archive instead of delete: a removed page, ministry or leader keeps its row (`archivedAt`).
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { publishedSnapshot, readWorkingCopy, toSource, type Source } from './snapshot.js';
|
||||
|
||||
export type ChangeKind = 'added' | 'changed' | 'removed';
|
||||
export type Change = { key: string; kind: ChangeKind; what: 'design' | 'page' | 'ministry' | 'leader'; label: string; by: string | null; at: string | null };
|
||||
|
||||
type Item = { key: string; what: Change['what']; label: string; value: unknown };
|
||||
|
||||
function items(s: Source | null): Map<string, Item> {
|
||||
const m = new Map<string, Item>();
|
||||
if (!s) return m;
|
||||
if (s.design) m.set('design', { key: 'design', what: 'design', label: 'Template and style', value: s.design });
|
||||
for (const p of s.pages) m.set(`page:${p.id}`, { key: `page:${p.id}`, what: 'page', label: p.title, value: p });
|
||||
for (const x of s.ministries) m.set(`ministry:${x.id}`, { key: `ministry:${x.id}`, what: 'ministry', label: x.name, value: x });
|
||||
for (const x of s.leaders) m.set(`leader:${x.id}`, { key: `leader:${x.id}`, what: 'leader', label: x.name, value: x });
|
||||
return m;
|
||||
}
|
||||
|
||||
/** JSON with sorted keys, so two copies of the same thing compare equal. */
|
||||
function stable(v: unknown): string {
|
||||
if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`;
|
||||
if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`;
|
||||
return JSON.stringify(v ?? null);
|
||||
}
|
||||
|
||||
async function publishedSource(ctx: Ctx): Promise<Source | null> {
|
||||
return (await publishedSnapshot(ctx))?.snapshot.source ?? null;
|
||||
}
|
||||
|
||||
export async function changes(ctx: Ctx): Promise<Change[]> {
|
||||
const w = await readWorkingCopy(ctx);
|
||||
const now = items(toSource(w));
|
||||
const then = items(await publishedSource(ctx));
|
||||
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
|
||||
// Who changed it last, and when: the row's own, or (for a page) its latest section's.
|
||||
const who = new Map<string, { by: string | null; at: Date | null }>();
|
||||
if (w.design) who.set('design', { by: w.design.updatedBy, at: w.design.updatedAt });
|
||||
for (const p of w.pages) {
|
||||
const latest = [p, ...p.sections].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0]!;
|
||||
who.set(`page:${p.id}`, { by: latest.updatedBy, at: latest.updatedAt });
|
||||
}
|
||||
for (const x of w.ministries) who.set(`ministry:${x.id}`, { by: x.updatedBy, at: x.updatedAt });
|
||||
for (const x of w.leaders) who.set(`leader:${x.id}`, { by: x.updatedBy, at: x.updatedAt });
|
||||
|
||||
const out: Change[] = [];
|
||||
const meta = (key: string) => {
|
||||
const h = who.get(key);
|
||||
return { by: h?.by ? names.get(h.by) ?? null : null, at: h?.at?.toISOString() ?? null };
|
||||
};
|
||||
for (const [key, item] of now) {
|
||||
const before = then.get(key);
|
||||
if (!before) out.push({ key, kind: 'added', what: item.what, label: item.label, ...meta(key) });
|
||||
else if (stable(before.value) !== stable(item.value)) out.push({ key, kind: 'changed', what: item.what, label: item.label, ...meta(key) });
|
||||
}
|
||||
for (const [key, item] of then) if (!now.has(key)) out.push({ key, kind: 'removed', what: item.what, label: item.label, by: null, at: null });
|
||||
return out;
|
||||
}
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
/** Puts one item of `source` into the working copy as it is there (or archives it when absent). */
|
||||
async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
|
||||
const db = ctx.db;
|
||||
const [what, id] = key.split(':') as [string, string | undefined];
|
||||
const stamp = { updatedBy: by.id };
|
||||
if (what === 'design') {
|
||||
if (!source?.design) throw new ApiError(409, 'NOTHING_PUBLISHED', 'The design has never been published, so there\'s nothing to go back to.');
|
||||
const d = source.design;
|
||||
const data = { template: d.template, variants: d.variants as never, home: d.home as never, style: d.style as never, ...stamp };
|
||||
await db.siteDesign.upsert({ where: { id: 1 }, create: { id: 1, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
if (!id) throw new ApiError(400, 'BAD_KEY', 'That isn\'t a change.');
|
||||
if (what === 'page') {
|
||||
const p = source?.pages.find((x) => x.id === id);
|
||||
if (!p) {
|
||||
await db.page.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } });
|
||||
return;
|
||||
}
|
||||
// A page that was added since takes the slug: move it aside first.
|
||||
const clash = await db.page.findFirst({ where: { slug: p.slug, NOT: { id } } });
|
||||
if (clash) await db.page.update({ where: { id: clash.id }, data: { slug: `${clash.slug}-${clash.id.slice(0, 6)}` } });
|
||||
const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp };
|
||||
await db.page.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
await db.section.deleteMany({ where: { pageId: id } });
|
||||
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } });
|
||||
return;
|
||||
}
|
||||
if (what === 'ministry') {
|
||||
const m = source?.ministries.find((x) => x.id === id);
|
||||
if (!m) return void (await db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
|
||||
const data = { slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position, archivedAt: null, ...stamp };
|
||||
await db.ministry.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
if (what === 'leader') {
|
||||
const l = source?.leaders.find((x) => x.id === id);
|
||||
if (!l) return void (await db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position, archivedAt: null, ...stamp };
|
||||
await db.leader.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
throw new ApiError(400, 'BAD_KEY', 'That isn\'t a change.');
|
||||
}
|
||||
|
||||
/** Discard (§4): one pending change goes back to its published value. */
|
||||
export async function discard(ctx: Ctx, key: string, by: Who) {
|
||||
const pending = (await changes(ctx)).find((c) => c.key === key);
|
||||
if (!pending) throw new ApiError(404, 'NO_SUCH_CHANGE', 'That change isn\'t pending any more.');
|
||||
await apply(ctx, key, await publishedSource(ctx), by);
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'change_discarded', targetType: pending.what, targetId: key, metadata: { label: pending.label, kind: pending.kind } });
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Restore (§4): version `number` back into the working copy, to preview and publish. */
|
||||
export async function restore(ctx: Ctx, number: number, by: Who) {
|
||||
const v = await ctx.db.siteVersion.findUnique({ where: { number } });
|
||||
const source = (v?.snapshot as { source?: Source } | null)?.source;
|
||||
if (!v || !source) throw new ApiError(404, 'NO_SUCH_VERSION', 'That version can\'t be restored.');
|
||||
const keys = new Set([...items(toSource(await readWorkingCopy(ctx))).keys(), ...items(source).keys()]);
|
||||
for (const key of keys) {
|
||||
if (key === 'design' && !source.design) continue;
|
||||
await apply(ctx, key, source, by);
|
||||
}
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'version_restored', targetType: 'site_version', targetId: String(number) });
|
||||
return { restored: number, pending: (await changes(ctx)).length };
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { loadDemo } from '../src/demo/demoChurch.js';
|
||||
import { hashToken } from '../src/lib/crypto.js';
|
||||
import { dimensions, sniff } from '../src/admin/media.js';
|
||||
import { harness, SITE } from './support/harness.js';
|
||||
|
||||
type Role = 'owner' | 'admin' | 'editor' | 'ministry_leader' | 'viewer';
|
||||
|
||||
/** The demo church, and a signed-in admin with `role`. Returns a request helper with their cookie. */
|
||||
async function signedIn(role: Role = 'editor', opts: { ministryId?: string | null } = {}) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-admin-'));
|
||||
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
|
||||
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
|
||||
const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor', 'ministry_leader', 'viewer'].indexOf(role) + 1}`;
|
||||
await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role, ministryId: opts.ministryId ?? null } });
|
||||
await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
|
||||
const cookie = `ccw_session=token-${role}`;
|
||||
const as = {
|
||||
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie),
|
||||
put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
|
||||
post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
|
||||
del: (p: string) => request(h.app).delete(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE),
|
||||
upload: (p: string, bytes: Buffer) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(bytes),
|
||||
};
|
||||
const pages = (await as.get('/pages')).body as { id: string; kind: string; slug: string }[];
|
||||
return { ...h, as, id, dir, cookie, page: (kind: string) => pages.find((p) => p.kind === kind)!.id };
|
||||
}
|
||||
|
||||
describe('the admin: who may do what (§10)', () => {
|
||||
it('lets a Viewer look but change nothing', async () => {
|
||||
const { as, page } = await signedIn('viewer');
|
||||
assert.equal((await as.get('/overview')).status, 200);
|
||||
assert.equal((await as.put(`/pages/${page('about')}`, { title: 'Us' })).status, 403);
|
||||
assert.equal((await as.post('/publish')).status, 403);
|
||||
});
|
||||
|
||||
it('lets a Ministry leader change their own ministry only, and not publish', async () => {
|
||||
const { as, db } = await signedIn('ministry_leader');
|
||||
const list = (await as.get('/ministries')).body as { id: string; name: string }[];
|
||||
await db.websiteUser.update({ where: { id: '00000000-0000-4000-8000-000000000004' }, data: { ministryId: list[0]!.id } });
|
||||
assert.equal((await as.put(`/ministries/${list[0]!.id}`, { name: 'Kids church', summary: 'Ages 3 to 12' })).status, 200);
|
||||
assert.equal((await as.put(`/ministries/${list[1]!.id}`, { name: 'Youth' })).status, 403);
|
||||
assert.equal((await as.post('/publish')).status, 403);
|
||||
});
|
||||
|
||||
it('refuses a change that didn\'t come from the site itself', async () => {
|
||||
const { app, cookie, page } = await signedIn('editor');
|
||||
const res = await request(app).put(`/api/v1/admin/pages/${page('about')}`).set('Cookie', cookie).set('Origin', 'https://evil.example').send({ title: 'x' });
|
||||
assert.equal(res.status, 403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('editing, publishing, discarding, restoring (§4)', () => {
|
||||
it('lists a change with who made it; Publish puts it live; nothing left to publish', async () => {
|
||||
const { as, page, app } = await signedIn('editor');
|
||||
assert.deepEqual((await as.get('/changes')).body, []);
|
||||
const r = await as.put(`/pages/${page('about')}`, { title: 'Our story' });
|
||||
assert.equal(r.status, 200);
|
||||
const pending = (await as.get('/changes')).body;
|
||||
assert.equal(pending.length, 1);
|
||||
assert.equal(pending[0].kind, 'changed');
|
||||
assert.equal(pending[0].label, 'Our story');
|
||||
assert.equal(pending[0].by, 'Sam the editor');
|
||||
|
||||
// Visitors still see the published title until Publish.
|
||||
const before = (await request(app).get('/api/v1/site/content')).body;
|
||||
assert.equal(before.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').title, 'About us');
|
||||
assert.equal(before.snapshot.source, undefined, 'never sent to visitors');
|
||||
|
||||
const pub = await as.post('/publish', { note: 'New page title' });
|
||||
assert.equal(pub.status, 200);
|
||||
assert.equal(pub.body.number, 2);
|
||||
const after = (await request(app).get('/api/v1/site/content')).body;
|
||||
assert.equal(after.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').title, 'Our story');
|
||||
assert.equal((await as.post('/publish')).body.error.code, 'NOTHING_TO_PUBLISH');
|
||||
});
|
||||
|
||||
it('discards one change, back to its published value; an added page is archived', async () => {
|
||||
const { as, page } = await signedIn('editor');
|
||||
await as.put(`/pages/${page('about')}`, { title: 'Changed' });
|
||||
const added = await as.post('/pages', { title: 'Youth camp', slug: 'youth-camp' });
|
||||
assert.equal(added.status, 200);
|
||||
assert.equal((await as.get('/changes')).body.length, 2);
|
||||
|
||||
assert.equal((await as.post('/discard', { key: `page:${page('about')}` })).status, 200);
|
||||
assert.equal((await as.get(`/pages/${page('about')}`)).body.title, 'About us');
|
||||
await as.post('/discard', { key: `page:${added.body.id}` });
|
||||
assert.deepEqual((await as.get('/changes')).body, []);
|
||||
assert.equal((await as.get(`/pages/${added.body.id}`)).status, 404);
|
||||
assert.equal((await as.post('/discard', { key: 'page:nope' })).status, 404);
|
||||
});
|
||||
|
||||
it('restores an older version into the working copy, to preview and publish', async () => {
|
||||
const { as, page } = await signedIn('editor');
|
||||
await as.put(`/pages/${page('about')}`, { title: 'Version two' });
|
||||
await as.post('/publish');
|
||||
await as.del(`/pages/${page('give')}`);
|
||||
await as.post('/publish');
|
||||
const r = await as.post('/versions/1/restore');
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal((await as.get(`/pages/${page('about')}`)).body.title, 'About us');
|
||||
assert.equal((await as.get(`/pages/${page('give')}`)).status, 200, 'the removed page is back');
|
||||
assert.equal(r.body.pending, 2);
|
||||
const versions = (await as.get('/versions')).body;
|
||||
assert.deepEqual(versions.map((v: { number: number }) => v.number), [3, 2, 1]);
|
||||
});
|
||||
|
||||
it('switches template, keeping the church\'s own choices, and says what moved', async () => {
|
||||
const { as } = await signedIn('editor');
|
||||
await as.put('/design', { variants: { team: 'list' } });
|
||||
const r = await as.put('/design', { template: 'bold' });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.design.template, 'bold');
|
||||
assert.equal(r.body.design.variants.team, 'list', 'kept');
|
||||
assert.equal(r.body.design.variants.hero, 'video', 'moved to Bold\'s default');
|
||||
assert.ok(r.body.moved.some((m: { what: string }) => m.what === 'hero.variant'));
|
||||
assert.equal((await as.put('/design', { variants: { hero: 'spinning' } })).status, 400);
|
||||
assert.equal((await as.put('/design', { style: { header: 'centred' } })).status, 400, 'a Heritage header on Bold');
|
||||
});
|
||||
|
||||
it('checks a section\'s data and says which field is wrong', async () => {
|
||||
const { as, page } = await signedIn('editor');
|
||||
const bad = await as.put(`/pages/${page('home')}/home/hero`, { data: { headline: '', button: { label: 'Go', href: 'javascript:x' } } });
|
||||
assert.equal(bad.status, 400);
|
||||
assert.ok(bad.body.error.fields.headline);
|
||||
assert.ok(bad.body.error.fields['button.href']);
|
||||
const good = await as.put(`/pages/${page('home')}/home/hero`, { data: { headline: 'Welcome home' } });
|
||||
assert.equal(good.status, 200);
|
||||
});
|
||||
|
||||
it('adds, moves and removes blocks on a page; refuses an address the site uses', async () => {
|
||||
const { as, page } = await signedIn('editor');
|
||||
const id = page('about');
|
||||
const added = (await as.post(`/pages/${id}/blocks`, { type: 'quote' })).body;
|
||||
assert.equal(added.sections.at(-1).type, 'quote');
|
||||
const quote = added.sections.at(-1).id;
|
||||
const moved = (await as.post(`/pages/${id}/blocks/${quote}/move`, { direction: 'up' })).body;
|
||||
assert.equal(moved.sections.at(-2).id, quote);
|
||||
assert.equal((await as.del(`/pages/${id}/blocks/${quote}`)).body.sections.some((s: { id: string }) => s.id === quote), false);
|
||||
assert.equal((await as.post('/pages', { title: 'Admin', slug: 'admin' })).status, 400);
|
||||
assert.equal((await as.post('/pages', { title: 'Visit', slug: 'visit' })).body.error.code, 'SLUG_TAKEN');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the preview (§4)', () => {
|
||||
it('shows the working copy to a signed-in admin, never to anyone else', async () => {
|
||||
const { as, app, cookie, page } = await signedIn('editor');
|
||||
await as.put(`/pages/${page('about')}`, { title: 'Draft title' });
|
||||
assert.equal((await request(app).get('/api/v1/site/preview')).status, 401);
|
||||
const p = await request(app).get('/api/v1/site/preview').set('Cookie', cookie);
|
||||
assert.equal(p.status, 200);
|
||||
assert.equal(p.body.snapshot.pages.find((x: { kind: string }) => x.kind === 'about').title, 'Draft title');
|
||||
assert.equal(p.body.preview.canPublish, true);
|
||||
assert.match(String(p.headers['x-robots-tag']), /noindex/);
|
||||
});
|
||||
|
||||
it('a shared link works signed out for 7 days, until revoked', async () => {
|
||||
const { as, app } = await signedIn('editor');
|
||||
const link = (await as.post('/preview-links')).body;
|
||||
const token = link.url.split('/preview/')[1];
|
||||
const p = await request(app).get('/api/v1/site/preview').set('x-preview-token', token);
|
||||
assert.equal(p.status, 200);
|
||||
assert.equal(p.body.preview.canPublish, false);
|
||||
await as.del(`/preview-links/${link.id}`);
|
||||
assert.equal((await request(app).get('/api/v1/site/preview').set('x-preview-token', token)).status, 401);
|
||||
assert.equal((await as.get('/preview-links')).body[0].active, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploads and storage (§10, decision 12)', () => {
|
||||
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]), Buffer.from('IHDR'), Buffer.from([0, 0, 2, 128, 0, 0, 1, 224]), Buffer.alloc(40)]);
|
||||
|
||||
it('knows a photo by its bytes, and its size', () => {
|
||||
assert.deepEqual(sniff(png), { ext: 'png', mime: 'image/png' });
|
||||
assert.deepEqual(dimensions(png, { ext: 'png', mime: 'image/png' }), { width: 640, height: 480 });
|
||||
assert.equal(sniff(Buffer.from('<svg>')), null);
|
||||
});
|
||||
|
||||
it('stores an upload, refuses what isn\'t a photo, and stops when storage is full', async () => {
|
||||
const { as, db, dir } = await signedIn('editor');
|
||||
const up = await as.upload('/media?alt=The%20hall', png);
|
||||
assert.equal(up.status, 200);
|
||||
assert.equal(up.body.width, 640);
|
||||
assert.ok(fs.existsSync(path.join(dir, up.body.filename)));
|
||||
const notPhoto = await as.upload('/media', Buffer.from('<svg onload=alert(1)>'));
|
||||
assert.equal(notPhoto.status, 415);
|
||||
// Full: the media library already holds the included 5 GB.
|
||||
await db.mediaAsset.create({ data: { filename: 'big.jpg', mime: 'image/jpeg', bytes: 5 * 1024 ** 3 } });
|
||||
const full = await as.upload('/media', png);
|
||||
assert.equal(full.status, 409);
|
||||
assert.equal(full.body.error.code, 'STORAGE_FULL');
|
||||
assert.equal((await as.get('/media')).body.storage.full, true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* The admin's flows (WEBSITE-1.0-PLAN §13): edit → preview (click through the site) → publish →
|
||||
* the public site changes; discard one change; a shared preview link works signed out and stops
|
||||
* after revoking; restore an older version; switch template in preview without losing anything.
|
||||
* Runs on the e2e server (e2e/server.ts): the demo church on Heritage, an admin signed in directly.
|
||||
*/
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { expect, test, type BrowserContext, type Page } from "@playwright/test";
|
||||
|
||||
const BACKEND = "http://127.0.0.1:5310";
|
||||
|
||||
async function reset(page: Page) {
|
||||
expect((await page.request.post(`${BACKEND}/test/demo?template=heritage`)).ok()).toBeTruthy();
|
||||
}
|
||||
|
||||
async function signIn(context: BrowserContext, role = "editor") {
|
||||
const res = await context.request.post(`${BACKEND}/test/session?role=${role}`);
|
||||
const { cookie } = await res.json();
|
||||
await context.addCookies([{ name: cookie.name, value: cookie.value, url: "http://localhost:3310" }]);
|
||||
}
|
||||
|
||||
async function aboutTitle(page: Page, title: string) {
|
||||
await page.goto("/admin/pages");
|
||||
await page.getByRole("link", { name: "About us", exact: true }).first().click();
|
||||
// The list page has a Title field too (Add a page): wait for the page's own editor.
|
||||
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
|
||||
await expect(page.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
|
||||
await page.getByLabel("Title", { exact: true }).fill(title);
|
||||
await page.getByRole("button", { name: "Save details" }).click();
|
||||
await expect(page.getByText("Saved as a draft.")).toBeVisible();
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => reset(page));
|
||||
|
||||
test("edit, preview the whole site, publish: then visitors see it", async ({ page, context, browser }) => {
|
||||
await signIn(context);
|
||||
await aboutTitle(page, "Our story");
|
||||
await page.goto("/admin");
|
||||
await expect(page.getByRole("link", { name: "1 change not published" })).toBeVisible();
|
||||
|
||||
// Preview: the real addresses, with the bar; click through to the changed page.
|
||||
await page.getByRole("link", { name: "Preview", exact: true }).click();
|
||||
await expect(page.getByRole("region", { name: "Preview" })).toBeVisible();
|
||||
await page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Our story" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1, name: "Our story" })).toBeVisible();
|
||||
|
||||
// Someone else still sees the published site.
|
||||
const visitor = await browser.newPage();
|
||||
await visitor.goto("/about");
|
||||
await expect(visitor.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
|
||||
await expect(visitor.getByRole("region", { name: "Preview" })).toHaveCount(0);
|
||||
|
||||
await page.getByRole("button", { name: "Publish" }).click();
|
||||
await expect(page).toHaveURL(/\/admin\/publish/);
|
||||
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
|
||||
await visitor.goto("/about");
|
||||
await expect(visitor.getByRole("heading", { level: 1, name: "Our story" })).toBeVisible();
|
||||
await visitor.close();
|
||||
});
|
||||
|
||||
test("discard one change", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await aboutTitle(page, "Changed my mind");
|
||||
await page.goto("/admin/publish");
|
||||
await expect(page.getByRole("heading", { name: "1 change not published" })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Discard" }).click();
|
||||
await expect(page.getByText("Discarded: back to the published version.")).toBeVisible();
|
||||
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
|
||||
});
|
||||
|
||||
test("a shared preview link works signed out, and stops when revoked", async ({ page, context, browser }) => {
|
||||
await signIn(context);
|
||||
await aboutTitle(page, "For the pastor");
|
||||
await page.goto("/admin/publish");
|
||||
await page.getByRole("button", { name: "Make a preview link" }).click();
|
||||
const url = (await page.locator("code").textContent())!.trim();
|
||||
|
||||
const pastor = await browser.newContext();
|
||||
const p = await pastor.newPage();
|
||||
await p.goto(new URL(url).pathname);
|
||||
await expect(p.getByRole("region", { name: "Preview" })).toBeVisible();
|
||||
await expect(p.getByRole("button", { name: "Publish" })).toHaveCount(0);
|
||||
await p.goto("/about");
|
||||
await expect(p.getByRole("heading", { level: 1, name: "For the pastor" })).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Stop it" }).click();
|
||||
await expect(page.getByText("The link stopped working.")).toBeVisible();
|
||||
await p.goto("/about");
|
||||
await expect(p.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
|
||||
await expect(p.getByRole("region", { name: "Preview" })).toHaveCount(0);
|
||||
await pastor.close();
|
||||
});
|
||||
|
||||
test("restore an older version, then publish it", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await aboutTitle(page, "Version two");
|
||||
await page.goto("/admin/publish");
|
||||
await page.getByRole("button", { name: "Publish all changes" }).click();
|
||||
await expect(page.getByText("Published: visitors see it now.")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Restore" }).click();
|
||||
await expect(page.getByText("Version 1 is back in your drafts")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Publish all changes" }).click();
|
||||
await page.goto("/about");
|
||||
await expect(page.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("switch template in the preview, and back, without losing anything", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await page.goto("/admin/template");
|
||||
await page.getByRole("button", { name: /^Bold/ }).click();
|
||||
await expect(page.getByText("Switched to Bold.")).toBeVisible();
|
||||
await page.goto("/preview/start");
|
||||
await expect(page.locator("html")).toHaveAttribute("data-template", "bold");
|
||||
await expect(page.getByRole("heading", { level: 1, name: "A home for everyone on the hill" })).toBeVisible();
|
||||
await page.goto("/admin/template");
|
||||
await page.getByRole("button", { name: /^Heritage/ }).click();
|
||||
await expect(page.getByText("Switched to Heritage.")).toBeVisible();
|
||||
await page.goto("/admin/publish");
|
||||
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
|
||||
});
|
||||
|
||||
test("signed out, the admin sends people to sign in and back to the same page", async ({ page }) => {
|
||||
const res = await page.request.get("/admin/pages", { maxRedirects: 0 });
|
||||
expect([303, 307, 308]).toContain(res.status());
|
||||
expect(res.headers().location).toContain("/api/auth/signin?returnTo=%2Fadmin%2Fpages");
|
||||
});
|
||||
|
||||
test("a Viewer sees the admin but can't publish", async ({ page, context }) => {
|
||||
await signIn(context, "viewer");
|
||||
await page.goto("/admin/publish");
|
||||
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: /Publish/ })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("the admin's screens are accessible", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/media", "/admin/publish"]) {
|
||||
await page.goto(path);
|
||||
await expect(page.getByRole("heading", { level: 1 })).toBeVisible();
|
||||
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
|
||||
expect(axe.violations.map((v) => `${path}: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]);
|
||||
}
|
||||
});
|
||||
@@ -15,6 +15,7 @@ import { createApp } from '../backend/src/app.js';
|
||||
import { createCtx } from '../backend/src/context.js';
|
||||
import { loadDemo } from '../backend/src/demo/demoChurch.js';
|
||||
import { loadConfig } from '../backend/src/lib/config.js';
|
||||
import { hashToken } from '../backend/src/lib/crypto.js';
|
||||
import { publish } from '../backend/src/site/snapshot.js';
|
||||
import { memoryDb } from '../backend/tests/support/memoryDb.js';
|
||||
|
||||
@@ -43,5 +44,14 @@ app.post('/test/design', express.json(), async (req, res) => {
|
||||
const v = await publish(ctx, { id: 'e2e', role: 'system' });
|
||||
res.json({ ok: true, version: v.number });
|
||||
});
|
||||
// A signed-in admin without Accounts: the role's user and a session; the spec sets the cookie.
|
||||
app.post('/test/session', async (req, res) => {
|
||||
const role = String(req.query.role ?? 'editor');
|
||||
const id = `00000000-0000-4000-8000-${String(Math.floor(Math.random() * 1e12)).padStart(12, '0')}`;
|
||||
const token = `e2e-${id}`;
|
||||
await db.websiteUser.create({ data: { id, name: `Test ${role}`, email: `${id}@hope.test`, role: role as never } });
|
||||
await db.session.create({ data: { tokenHash: hashToken(token), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
|
||||
res.json({ cookie: { name: 'ccw_session', value: token } });
|
||||
});
|
||||
app.use(createApp(ctx));
|
||||
app.listen(5310, '127.0.0.1', () => console.log('[e2e] Website backend on 5310 with the demo church.'));
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{ "name": "WEBSITE_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" }
|
||||
{ "name": "WEBSITE_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" },
|
||||
{ "name": "WEBSITE_CONTENT_CACHE_SECONDS", "layer": "defaults", "default": "30", "description": "How long the public pages keep the published site; Publish clears it at once" }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
/** A list of things the church keeps (ministries, its team): add, edit, remove. Drafts until Publish. */
|
||||
import { useState } from "react";
|
||||
import { api } from "./api";
|
||||
import { ImagePicker } from "./media";
|
||||
import { Btn, Field, inputClass, Loading, Notice, Panel, useAction, useAdmin } from "./ui";
|
||||
|
||||
export type ListField = { key: string; label: string; kind: "text" | "textarea" | "image"; max?: number; hint?: string };
|
||||
|
||||
type Row = Record<string, unknown> & { id: string };
|
||||
|
||||
function Editor({ fields, initial, onSave, onCancel, busy, errors }: { fields: ListField[]; initial: Row | Record<string, unknown>; onSave: (v: Record<string, unknown>) => void; onCancel: () => void; busy: boolean; errors: Record<string, string> }) {
|
||||
const [v, setV] = useState<Record<string, unknown>>(initial);
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{fields.map((f) => f.kind === "image"
|
||||
? <ImagePicker key={f.key} label={f.label} value={(v[f.key] as string) ?? null} onChange={(id) => setV({ ...v, [f.key]: id })} />
|
||||
: (
|
||||
<Field key={f.key} label={f.label} hint={f.hint} error={errors[f.key]}>
|
||||
{f.kind === "text"
|
||||
? <input className={inputClass} value={(v[f.key] as string) ?? ""} maxLength={f.max} onChange={(e) => setV({ ...v, [f.key]: e.target.value || null })} />
|
||||
: <textarea className={inputClass} rows={4} value={(v[f.key] as string) ?? ""} maxLength={f.max} onChange={(e) => setV({ ...v, [f.key]: e.target.value || null })} />}
|
||||
</Field>
|
||||
))}
|
||||
<div className="flex gap-2"><Btn kind="primary" busy={busy} onClick={() => onSave(v)}>Save</Btn><Btn onClick={onCancel}>Cancel</Btn></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ListEditor({ path, fields, nameKey, subKey, addLabel, canAdd }: { path: string; fields: ListField[]; nameKey: string; subKey: string; addLabel: string; canAdd: boolean }) {
|
||||
const { data, error, reload } = useAdmin<Row[]>(path);
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
const { busy, message, fields: errors, run } = useAction();
|
||||
if (!data) return <Loading error={error} />;
|
||||
const save = (id: string | null, v: Record<string, unknown>) => run(async () => {
|
||||
const body = Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null]));
|
||||
await api(id ? `${path}/${id}` : path, { method: id ? "PUT" : "POST", body });
|
||||
setEditing(null);
|
||||
await reload();
|
||||
}, "Saved as a draft.");
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{message && <Notice tone={message.tone}>{message.text}</Notice>}
|
||||
<Panel>
|
||||
{data.length === 0 && <p className="text-gray-600">None yet.</p>}
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{data.map((row) => (
|
||||
<li key={row.id} className="py-3">
|
||||
{editing === row.id ? (
|
||||
<Editor fields={fields} initial={row} busy={busy} errors={errors} onCancel={() => setEditing(null)} onSave={(v) => save(row.id, v)} />
|
||||
) : (
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div><p className="font-medium">{String(row[nameKey])}</p>{row[subKey] ? <p className="text-sm text-gray-600">{String(row[subKey])}</p> : null}</div>
|
||||
<div className="flex gap-2">
|
||||
<Btn onClick={() => setEditing(row.id)}>Edit</Btn>
|
||||
{canAdd && <Btn kind="danger" onClick={() => run(async () => { await api(`${path}/${row.id}`, { method: "DELETE" }); await reload(); }, "Removed (until you publish, you can discard this).")}>Remove</Btn>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Panel>
|
||||
{canAdd && (
|
||||
<Panel title={addLabel}>
|
||||
{editing === "new"
|
||||
? <Editor fields={fields} initial={{}} busy={busy} errors={errors} onCancel={() => setEditing(null)} onSave={(v) => save(null, v)} />
|
||||
: <Btn kind="primary" onClick={() => setEditing("new")}>{addLabel}</Btn>}
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
/** The admin's frame: navigation, the pending change count, Preview and Sign out (§4, §10). */
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { ROLE_NAMES } from "./api";
|
||||
import { cx, useAdmin } from "./ui";
|
||||
|
||||
const NAV = [
|
||||
{ href: "/admin", label: "Dashboard" },
|
||||
{ href: "/admin/template", label: "Template and style" },
|
||||
{ href: "/admin/pages", label: "Pages" },
|
||||
{ href: "/admin/ministries", label: "Ministries" },
|
||||
{ href: "/admin/leaders", label: "Leadership" },
|
||||
{ href: "/admin/media", label: "Media library" },
|
||||
{ href: "/admin/publish", label: "Publish and history" },
|
||||
];
|
||||
|
||||
export function AdminShell({ user, children }: { user: { name: string; role: string }; children: React.ReactNode }) {
|
||||
const path = usePathname();
|
||||
const { data } = useAdmin<{ pending: number }>(`/overview?for=${encodeURIComponent(path)}`);
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 font-sans text-gray-900">
|
||||
<header className="border-b border-gray-200 bg-white">
|
||||
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-3">
|
||||
<Link href="/admin" className="font-semibold">Website admin</Link>
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
{data && data.pending > 0 && <Link href="/admin/publish" className="rounded-full bg-amber-100 px-3 py-1 font-medium text-amber-900">{data.pending} {data.pending === 1 ? "change" : "changes"} not published</Link>}
|
||||
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that sets the preview cookie: a full page load, not a client navigation */}
|
||||
<a href="/preview/start" className="rounded-md border border-gray-300 px-3 py-1.5 font-semibold hover:bg-gray-50">Preview</a>
|
||||
<span className="text-gray-600">{user.name} · {ROLE_NAMES[user.role] ?? user.role}</span>
|
||||
<form method="post" action="/api/auth/signout"><button type="submit" className="text-gray-600 underline-offset-4 hover:underline">Sign out</button></form>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div className="mx-auto grid max-w-6xl gap-6 px-4 py-6 md:grid-cols-[13rem_1fr]">
|
||||
<nav aria-label="Admin">
|
||||
<ul className="flex gap-1 overflow-x-auto md:flex-col">
|
||||
{NAV.map((n) => {
|
||||
const current = n.href === "/admin" ? path === "/admin" : path.startsWith(n.href);
|
||||
return (
|
||||
<li key={n.href}>
|
||||
<Link href={n.href} aria-current={current ? "page" : undefined}
|
||||
className={cx("block whitespace-nowrap rounded-md px-3 py-2 text-sm", current ? "bg-brand text-brand-on" : "text-gray-700 hover:bg-gray-100")}>{n.label}</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</nav>
|
||||
<main>{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
/** The admin API from the browser (same origin: the session cookie goes along, and so does Origin). */
|
||||
export class AdminError extends Error {
|
||||
constructor(message: string, public code: string, public status: number, public fields: Record<string, string> = {}) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export async function api<T = unknown>(path: string, opts: { method?: string; body?: unknown; raw?: Blob } = {}): Promise<T> {
|
||||
const res = await fetch(`/api/v1/admin${path}`, {
|
||||
method: opts.method ?? (opts.body !== undefined || opts.raw ? "POST" : "GET"),
|
||||
headers: opts.raw ? { "Content-Type": "application/octet-stream" } : opts.body !== undefined ? { "Content-Type": "application/json" } : undefined,
|
||||
body: opts.raw ?? (opts.body !== undefined ? JSON.stringify(opts.body) : undefined),
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
const e = (data as { error?: { message?: string; code?: string; fields?: Record<string, string> } } | null)?.error;
|
||||
// Signed out: off to sign in (a route on the backend), and back to this page.
|
||||
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
|
||||
if (res.status === 401) window.location.href = `/api/auth/signin?returnTo=${encodeURIComponent(window.location.pathname)}`;
|
||||
throw new AdminError(e?.message ?? `Something went wrong (${res.status}).`, e?.code ?? "ERROR", res.status, e?.fields ?? {});
|
||||
}
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export const ROLE_NAMES: Record<string, string> = { owner: "Owner", admin: "Admin", editor: "Editor", ministry_leader: "Ministry leader", viewer: "Viewer" };
|
||||
export const canEdit = (role: string) => ["owner", "admin", "editor"].includes(role);
|
||||
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* 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 { ImagePicker } from "./media";
|
||||
import { Btn, Field, inputClass } from "./ui";
|
||||
|
||||
type Spec =
|
||||
| { key: string; kind: "text" | "textarea"; label: string; hint?: string; max?: number }
|
||||
| { key: string; kind: "number"; label: string; min: number; max: number }
|
||||
| { key: string; kind: "image"; label: string }
|
||||
| { key: string; kind: "images"; label: string; max: number }
|
||||
| { key: string; kind: "button"; label: string }
|
||||
| { key: string; kind: "group"; label: string; fields: Spec[] };
|
||||
|
||||
const heading: Spec = { key: "heading", kind: "text", label: "Heading", max: 120 };
|
||||
const button: Spec = { key: "button", kind: "button", label: "Button" };
|
||||
|
||||
export const SECTION_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
|
||||
hero: { name: "Top of the page (hero)", fields: [
|
||||
{ key: "headline", kind: "text", label: "Headline", max: 120 },
|
||||
{ key: "subline", kind: "textarea", label: "Under the headline", max: 300 },
|
||||
{ key: "images", kind: "images", label: "Photos (the first for Photo and Split; up to three for Collage)", max: 3 },
|
||||
button,
|
||||
] },
|
||||
serviceTimes: { name: "Service times and location", fields: [heading, { key: "note", kind: "textarea", label: "A note for visitors", hint: "The times and address come from your church profile.", max: 300 }] },
|
||||
welcome: { name: "Welcome", fields: [
|
||||
heading,
|
||||
{ key: "mission", kind: "text", label: "Mission (one line)", max: 200 },
|
||||
{ key: "body", kind: "textarea", label: "Introduction", hint: "Leave an empty line between paragraphs.", max: 4000 },
|
||||
{ key: "imageId", kind: "image", label: "Photo (Image and text layout)" },
|
||||
{ key: "pastor", kind: "group", label: "Pastor's photo and quote (With pastor layout)", fields: [
|
||||
{ key: "name", kind: "text", label: "Name", max: 120 }, { key: "role", kind: "text", label: "Role", max: 80 },
|
||||
{ key: "quote", kind: "textarea", label: "Quote", max: 400 }, { key: "photoId", kind: "image", label: "Photo" },
|
||||
] },
|
||||
] },
|
||||
ministries: { name: "Ministries", fields: [heading, { key: "intro", kind: "textarea", label: "Introduction", max: 400 }] },
|
||||
team: { name: "Team", fields: [heading, { key: "intro", kind: "textarea", label: "Introduction", max: 400 }] },
|
||||
events: { name: "Upcoming events", fields: [heading, { key: "count", kind: "number", label: "How many to show", min: 2, max: 12 }] },
|
||||
latestMessage: { name: "Latest message", fields: [heading] },
|
||||
invitation: { name: "Invitation", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button, { key: "imageId", kind: "image", label: "Background photo (Image background layout)" }] },
|
||||
};
|
||||
|
||||
export const BLOCK_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
|
||||
text: { name: "Text", fields: [heading, { key: "body", kind: "textarea", label: "Text", hint: "Leave an empty line between paragraphs.", max: 20000 }] },
|
||||
"image-text": { name: "Image and text", fields: [heading, { key: "body", kind: "textarea", label: "Text", max: 4000 }, { key: "imageId", kind: "image", label: "Photo" }, button] },
|
||||
quote: { name: "Quote", fields: [{ key: "quote", kind: "textarea", label: "Quote", max: 600 }, { key: "by", kind: "text", label: "Who said it", max: 120 }] },
|
||||
cta: { name: "Call to action", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button] },
|
||||
};
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
|
||||
export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record<string, string>; prefix?: string }) {
|
||||
const set = (k: string, v: unknown) => onChange({ ...value, [k]: v });
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{fields.map((f) => {
|
||||
const err = errors[`${prefix}${f.key}`];
|
||||
const v = value[f.key];
|
||||
switch (f.kind) {
|
||||
case "text":
|
||||
return <Field key={f.key} label={f.label} hint={f.hint} error={err}><input className={inputClass} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || null)} /></Field>;
|
||||
case "textarea":
|
||||
return <Field key={f.key} label={f.label} hint={f.hint} error={err}><textarea className={inputClass} rows={f.key === "body" ? 6 : 3} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || (f.key === "body" ? "" : null))} /></Field>;
|
||||
case "number":
|
||||
return <Field key={f.key} label={f.label} error={err}><input type="number" className={`${inputClass} w-24`} min={f.min} max={f.max} value={(v as number) ?? f.min} onChange={(e) => set(f.key, Number(e.target.value))} /></Field>;
|
||||
case "image":
|
||||
return <div key={f.key}><ImagePicker label={f.label} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>;
|
||||
case "images": {
|
||||
const list = Array.isArray(v) ? (v as string[]) : [];
|
||||
return (
|
||||
<div key={f.key} className="space-y-2">
|
||||
<p className="text-sm font-medium text-gray-800">{f.label}</p>
|
||||
{list.map((id, i) => <ImagePicker key={i} label={`Photo ${i + 1}`} value={id} onChange={(n) => set(f.key, n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i))} />)}
|
||||
{list.length < f.max && <ImagePicker label={`Photo ${list.length + 1}`} value={null} onChange={(n) => n && set(f.key, [...list, n])} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case "button": {
|
||||
const b = v as { label: string; href: string } | null;
|
||||
return (
|
||||
<fieldset key={f.key} className="rounded border border-gray-200 p-3">
|
||||
<legend className="px-1 text-sm font-medium text-gray-800">{f.label}</legend>
|
||||
{b ? (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label="Says" error={errors[`${prefix}${f.key}.label`]}><input className={inputClass} value={b.label} maxLength={60} onChange={(e) => set(f.key, { ...b, label: e.target.value })} /></Field>
|
||||
<Field label="Goes to" hint="A page here (/visit) or https://…" error={errors[`${prefix}${f.key}.href`]}><input className={inputClass} value={b.href} onChange={(e) => set(f.key, { ...b, href: e.target.value })} /></Field>
|
||||
<Btn kind="link" onClick={() => set(f.key, null)}>No button</Btn>
|
||||
</div>
|
||||
) : <Btn onClick={() => set(f.key, { label: "Plan your visit", href: "/visit" })}>Add a button</Btn>}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
case "group": {
|
||||
const g = v as Data | null;
|
||||
return (
|
||||
<fieldset key={f.key} className="rounded border border-gray-200 p-3">
|
||||
<legend className="px-1 text-sm font-medium text-gray-800">{f.label}</legend>
|
||||
{g ? (
|
||||
<>
|
||||
<DataForm fields={f.fields} value={g} onChange={(n) => set(f.key, n)} errors={errors} prefix={`${prefix}${f.key}.`} />
|
||||
<Btn kind="link" className="mt-3" onClick={() => set(f.key, null)}>Remove</Btn>
|
||||
</>
|
||||
) : <Btn onClick={() => set(f.key, { name: "", role: null, quote: null, photoId: null })}>Add</Btn>}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
/** The media library: pick an image, or upload one (with its alt text) and pick it. */
|
||||
import { useRef, useState } from "react";
|
||||
import { api } from "./api";
|
||||
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 Storage = { usedBytes: number; limitBytes: number; full: boolean; percent: number };
|
||||
|
||||
export const gb = (n: number) => `${(n / 1024 ** 3).toFixed(n < 1024 ** 3 ? 2 : 1)} GB`;
|
||||
|
||||
export function StorageMeter({ s }: { s: Storage }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="h-2 w-full overflow-hidden rounded bg-gray-200" role="progressbar" aria-valuenow={s.percent} aria-valuemin={0} aria-valuemax={100} aria-label="Storage used">
|
||||
<div className={cx("h-full", s.percent >= 100 ? "bg-red-600" : s.percent >= 80 ? "bg-amber-500" : "bg-brand")} style={{ width: `${s.percent}%` }} />
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-600">{gb(s.usedBytes)} of {gb(s.limitBytes)} used</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Upload form: a photo and what it shows (alt text is required, §3 "Every image needs alt text"). */
|
||||
export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem) => void; disabled?: boolean }) {
|
||||
const file = useRef<HTMLInputElement>(null);
|
||||
const [alt, setAlt] = useState("");
|
||||
const { busy, message, run } = useAction();
|
||||
const go = () => run(async () => {
|
||||
const f = file.current?.files?.[0];
|
||||
if (!f) throw new Error("Choose a photo first.");
|
||||
if (!alt.trim()) throw new Error("Say what the photo shows (for people who can't see it).");
|
||||
const m = await api<MediaItem & { filename: string }>(`/media?alt=${encodeURIComponent(alt.trim())}`, { raw: f });
|
||||
setAlt("");
|
||||
if (file.current) file.current.value = "";
|
||||
onUploaded(m);
|
||||
}, "Uploaded.");
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Field label="Photo" hint="JPEG, PNG or WebP, up to 15 MB. Landscape photos of people work best for the top of a page.">
|
||||
<input ref={file} type="file" accept="image/jpeg,image/png,image/webp" className="block text-sm" disabled={disabled} />
|
||||
</Field>
|
||||
<Field label="What the photo shows" hint="Read out to people who can't see it, e.g. “Families at the church picnic”.">
|
||||
<input className={inputClass} value={alt} onChange={(e) => setAlt(e.target.value)} maxLength={500} disabled={disabled} />
|
||||
</Field>
|
||||
<Btn kind="primary" onClick={go} busy={busy} disabled={disabled}>Upload</Btn>
|
||||
{message && <Notice tone={message.tone}>{message.text}</Notice>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null);
|
||||
const chosen = data?.items.find((m) => m.id === value);
|
||||
return (
|
||||
<div>
|
||||
<span className="block text-sm font-medium text-gray-800">{label}</span>
|
||||
<div className="mt-1 flex items-center gap-3">
|
||||
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
|
||||
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-400">No image</span>}
|
||||
</div>
|
||||
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
|
||||
{value && <Btn kind="link" onClick={() => onChange(null)}>Remove</Btn>}
|
||||
</div>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-label="Choose an image">
|
||||
<div className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Choose an image</h2>
|
||||
<Btn onClick={() => setOpen(false)}>Close</Btn>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3 sm:grid-cols-4">
|
||||
{data?.items.map((m) => (
|
||||
<button key={m.id} type="button" onClick={() => { onChange(m.id); setOpen(false); }}
|
||||
className={cx("overflow-hidden rounded border-2 text-left", m.id === value ? "border-brand" : "border-transparent hover:border-gray-300")}>
|
||||
<img src={m.url} alt="" className="aspect-[4/3] w-full object-cover" />
|
||||
<span className="block truncate p-1 text-xs text-gray-600">{m.alt || "No description"}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-6 border-t border-gray-200 pt-4">
|
||||
<h3 className="mb-2 font-semibold">Upload a new one</h3>
|
||||
{data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. To get more (5 GB at a time), contact Cross Code.</Notice>}
|
||||
<Uploader disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"use client";
|
||||
|
||||
/** The admin's own building blocks: plain, calm, the church's colour for the main action. */
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api, AdminError } from "./api";
|
||||
|
||||
export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
|
||||
|
||||
export function Title({ children, sub, actions }: { children: React.ReactNode; sub?: React.ReactNode; actions?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="mb-6 flex flex-wrap items-end justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">{children}</h1>
|
||||
{sub && <p className="mt-1 text-gray-600">{sub}</p>}
|
||||
</div>
|
||||
{actions && <div className="flex flex-wrap gap-2">{actions}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Panel({ children, className, title }: { children: React.ReactNode; className?: string; title?: string }) {
|
||||
return (
|
||||
<section className={cx("rounded-lg border border-gray-200 bg-white p-5 shadow-sm", className)}>
|
||||
{title && <h2 className="mb-4 text-lg font-semibold text-gray-900">{title}</h2>}
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type BtnProps = React.ButtonHTMLAttributes<HTMLButtonElement> & { kind?: "primary" | "secondary" | "danger" | "link"; busy?: boolean };
|
||||
|
||||
export function Btn({ kind = "secondary", busy, className, children, disabled, ...rest }: BtnProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
{...rest}
|
||||
disabled={disabled || busy}
|
||||
className={cx(
|
||||
"inline-flex items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-50",
|
||||
kind === "primary" && "bg-brand text-brand-on hover:bg-brand-dark",
|
||||
kind === "secondary" && "border border-gray-300 bg-white text-gray-800 hover:bg-gray-50",
|
||||
kind === "danger" && "border border-red-300 bg-white text-red-700 hover:bg-red-50",
|
||||
kind === "link" && "px-0 py-0 text-brand-text underline-offset-4 hover:underline",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{busy ? "Working…" : children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Field({ label, hint, error, children }: { label: string; hint?: React.ReactNode; error?: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<label className="block">
|
||||
<span className="block text-sm font-medium text-gray-800">{label}</span>
|
||||
<span className="mt-1 block">{children}</span>
|
||||
{hint && !error && <span className="mt-1 block text-xs text-gray-500">{hint}</span>}
|
||||
{error && <span className="mt-1 block text-xs font-medium text-red-700" role="alert">{error}</span>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export const inputClass = "w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-brand focus:outline-none focus:ring-2 focus:ring-brand/30";
|
||||
|
||||
export function Notice({ tone = "info", children }: { tone?: "info" | "error" | "success" | "warning"; children: React.ReactNode }) {
|
||||
const tones = { info: "border-blue-200 bg-blue-50 text-blue-900", error: "border-red-200 bg-red-50 text-red-900", success: "border-green-200 bg-green-50 text-green-900", warning: "border-amber-200 bg-amber-50 text-amber-900" };
|
||||
return <div role={tone === "error" ? "alert" : "status"} className={cx("rounded-md border px-4 py-3 text-sm", tones[tone])}>{children}</div>;
|
||||
}
|
||||
|
||||
/** Loads `path` from the admin API; `reload` fetches it again. */
|
||||
export function useAdmin<T>(path: string | null) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const load = useCallback(async () => {
|
||||
if (!path) return;
|
||||
try {
|
||||
setData(await api<T>(path));
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
}, [path]);
|
||||
useEffect(() => {
|
||||
// Fetching on mount is this hook's job.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
load();
|
||||
}, [load]);
|
||||
return { data, error, reload: load, setData };
|
||||
}
|
||||
|
||||
/** Runs an action, keeping its busy state, message and field errors. */
|
||||
export function useAction() {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState<{ tone: "error" | "success"; text: string } | null>(null);
|
||||
const [fields, setFields] = useState<Record<string, string>>({});
|
||||
const run = useCallback(async <T,>(fn: () => Promise<T>, success?: string): Promise<T | null> => {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
setFields({});
|
||||
try {
|
||||
const out = await fn();
|
||||
if (success) setMessage({ tone: "success", text: success });
|
||||
return out;
|
||||
} catch (e) {
|
||||
setMessage({ tone: "error", text: (e as Error).message });
|
||||
if (e instanceof AdminError) setFields(e.fields);
|
||||
return null;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, []);
|
||||
return { busy, message, fields, run, setMessage };
|
||||
}
|
||||
|
||||
export function Loading({ error }: { error?: string | null }) {
|
||||
return error ? <Notice tone="error">{error}</Notice> : <p className="text-gray-500">Loading…</p>;
|
||||
}
|
||||
|
||||
export const when = (iso: string | null) => (iso ? new Intl.DateTimeFormat("en-ZA", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }).format(new Date(iso)) : "");
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { AdminShell } from "@/admin/Shell";
|
||||
import { loadMe, signInHref } from "@/lib/admin";
|
||||
|
||||
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Every admin page: signed in through the church's Accounts (§10), else off to sign in and back. */
|
||||
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const me = await loadMe();
|
||||
if (!me) {
|
||||
const path = (await headers()).get("x-ccw-path") || "/admin";
|
||||
redirect(signInHref(path.startsWith("/admin") ? path : "/admin"));
|
||||
}
|
||||
return <AdminShell user={me.user}>{children}</AdminShell>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { canEdit } from "@/admin/api";
|
||||
import { ListEditor } from "@/admin/ListEditor";
|
||||
import { Title, useAdmin } from "@/admin/ui";
|
||||
|
||||
/** The team (§6): shown on the Leadership page and the home page's Team section. */
|
||||
export default function Leaders() {
|
||||
const { data } = useAdmin<{ user: { role: string } }>("/me");
|
||||
return (
|
||||
<>
|
||||
<Title sub="The people who lead your church. The first is shown largest in the Featured layout.">Leadership</Title>
|
||||
<ListEditor path="/leaders" nameKey="name" subKey="role" addLabel="Add a person" canAdd={!!data && canEdit(data.user.role)} fields={[
|
||||
{ key: "name", label: "Name", kind: "text", max: 120 },
|
||||
{ key: "role", label: "Role", kind: "text", max: 120, hint: "E.g. “Lead pastor”." },
|
||||
{ key: "bio", label: "About them", kind: "textarea", max: 4000 },
|
||||
{ key: "photoId", label: "Photo", kind: "image" },
|
||||
]} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { api } from "@/admin/api";
|
||||
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
|
||||
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
/** The media library (§10): uploads, what each photo shows (alt text), and storage used. */
|
||||
export default function Media() {
|
||||
const { data, error, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>("/media");
|
||||
const [alts, setAlts] = useState<Record<string, string>>({});
|
||||
const { busy, message, run } = useAction();
|
||||
if (!data) return <Loading error={error} />;
|
||||
const s = data.storage;
|
||||
return (
|
||||
<>
|
||||
<Title sub="Photos for your pages. Sermon audio and video are linked (YouTube, Spotify), never uploaded.">Media library</Title>
|
||||
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
||||
<Panel>
|
||||
{message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>}
|
||||
{data.items.length === 0 && <p className="text-gray-600">No photos yet.</p>}
|
||||
<ul className="grid gap-4 sm:grid-cols-2">
|
||||
{data.items.map((m) => (
|
||||
<li key={m.id} className="space-y-2">
|
||||
<img src={m.url} alt={m.alt} className="aspect-[4/3] w-full rounded object-cover" />
|
||||
<label className="block text-xs text-gray-600">What it shows
|
||||
<input className={inputClass} value={alts[m.id] ?? m.alt} maxLength={500} onChange={(e) => setAlts({ ...alts, [m.id]: e.target.value })} />
|
||||
</label>
|
||||
{alts[m.id] !== undefined && alts[m.id] !== m.alt && (
|
||||
<Btn busy={busy} onClick={() => run(async () => { await api(`/media/${m.id}`, { method: "PUT", body: { alt: alts[m.id] } }); await reload(); }, "Saved.")}>Save</Btn>
|
||||
)}
|
||||
{!m.alt && <p className="text-xs font-medium text-amber-800">Add what it shows, for people who can't see it.</p>}
|
||||
<p className="text-xs text-gray-500">{m.width && m.height ? `${m.width} × ${m.height}` : ""} · {gb(m.bytes)}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Panel>
|
||||
<div className="space-y-6">
|
||||
<Panel title="Storage">
|
||||
<StorageMeter s={s} />
|
||||
{s.percent >= 80 && <div className="mt-3"><Notice tone={s.full ? "error" : "warning"}>{s.full ? "Storage is full: uploads have stopped until more storage is added." : "Storage is nearly full."} More comes in 5 GB steps (R20 a month each): contact Cross Code.</Notice></div>}
|
||||
</Panel>
|
||||
<Panel title="Upload a photo">
|
||||
{s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader onUploaded={() => reload()} />}
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { canEdit } from "@/admin/api";
|
||||
import { ListEditor } from "@/admin/ListEditor";
|
||||
import { Title, useAdmin } from "@/admin/ui";
|
||||
|
||||
/** Ministries (§6): shown on the Ministries page and the home page's Ministries section. */
|
||||
export default function Ministries() {
|
||||
const { data } = useAdmin<{ user: { role: string } }>("/me");
|
||||
return (
|
||||
<>
|
||||
<Title sub="Your ministries' pages. A ministry leader can edit their own; an editor publishes it.">Ministries</Title>
|
||||
<ListEditor path="/ministries" nameKey="name" subKey="summary" addLabel="Add a ministry" canAdd={!!data && canEdit(data.user.role)} fields={[
|
||||
{ key: "name", label: "Name", kind: "text", max: 120 },
|
||||
{ key: "summary", label: "In one line", kind: "text", max: 300, hint: "E.g. “Ages 3 to 12, every Sunday at 10:00.”" },
|
||||
{ key: "body", label: "More about it", kind: "textarea", max: 8000 },
|
||||
{ key: "imageId", label: "Photo", kind: "image" },
|
||||
]} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +1,48 @@
|
||||
import type { Metadata } from "next";
|
||||
import { redirect } from "next/navigation";
|
||||
import { loadMe, ROLE_NAMES, signInHref } from "@/lib/admin";
|
||||
"use client";
|
||||
|
||||
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
|
||||
export const dynamic = "force-dynamic";
|
||||
import Link from "next/link";
|
||||
import { StorageMeter, type Storage } from "@/admin/media";
|
||||
import { Loading, Notice, Panel, Title, useAdmin, when } from "@/admin/ui";
|
||||
|
||||
// The admin (docs/WEBSITE-1.0-PLAN.md §10), signed in through the church's Accounts. The screens
|
||||
// (template and style, pages, messages, events, publish) come next.
|
||||
export default async function Admin() {
|
||||
const me = await loadMe();
|
||||
if (!me) redirect(signInHref("/admin"));
|
||||
type Overview = {
|
||||
pending: number;
|
||||
lastPublished: { number: number; at: string } | null;
|
||||
storage: Storage;
|
||||
colourNotes: string[];
|
||||
checklist: { key: string; label: string; done: boolean; href: string | null }[];
|
||||
};
|
||||
|
||||
/** The dashboard (§10): the setup checklist, what's waiting to be published, storage. */
|
||||
export default function Dashboard() {
|
||||
const { data, error } = useAdmin<Overview>("/overview");
|
||||
if (!data) return <Loading error={error} />;
|
||||
return (
|
||||
<main className="mx-auto max-w-xl px-4 py-16">
|
||||
<h1 className="text-2xl font-semibold">Website admin</h1>
|
||||
<p className="mt-2 text-gray-600">
|
||||
Signed in as {me.user.name} ({me.user.email}), {ROLE_NAMES[me.user.role]}.
|
||||
</p>
|
||||
<form method="post" action="/api/auth/signout" className="mt-6">
|
||||
<button type="submit" className="rounded border border-gray-300 px-4 py-2 text-sm hover:bg-gray-50">
|
||||
Sign out
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
<>
|
||||
<Title sub={data.lastPublished ? `Last published ${when(data.lastPublished.at)} (version ${data.lastPublished.number}).` : "Your site shows Coming soon until you publish it."}>Dashboard</Title>
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Panel title="Getting your site ready">
|
||||
<ol className="space-y-3">
|
||||
{data.checklist.map((c) => (
|
||||
<li key={c.key} className="flex items-start gap-3">
|
||||
<span aria-hidden="true" className={c.done ? "text-green-700" : "text-gray-400"}>{c.done ? "✓" : "○"}</span>
|
||||
<span className={c.done ? "text-gray-500 line-through" : ""}>{c.href ? <Link href={c.href} className="underline-offset-4 hover:underline">{c.label}</Link> : c.label}</span>
|
||||
<span className="sr-only">{c.done ? "(done)" : "(to do)"}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</Panel>
|
||||
<div className="space-y-6">
|
||||
<Panel title="Waiting to be published">
|
||||
{data.pending ? (
|
||||
<p>{data.pending} {data.pending === 1 ? "change" : "changes"}. <Link href="/admin/publish" className="font-semibold text-brand-text underline-offset-4 hover:underline">Review and publish</Link></p>
|
||||
) : <p className="text-gray-600">Nothing: the site shows everything you've done.</p>}
|
||||
</Panel>
|
||||
<Panel title="Storage"><StorageMeter s={data.storage} /></Panel>
|
||||
{data.colourNotes.length > 0 && (
|
||||
<Notice tone="info"><p className="font-semibold">About your colours</p><ul className="mt-1 list-disc pl-5">{data.colourNotes.map((n) => <li key={n}>{n}</li>)}</ul></Notice>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* One page (§6): its title, address, menu and search engine details, then its content. The home
|
||||
* page has one of each homepage section (their layouts are set under Template and style); every
|
||||
* other page is built from blocks, which can be added, moved and removed.
|
||||
*/
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { api } from "@/admin/api";
|
||||
import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
|
||||
import { ImagePicker } from "@/admin/media";
|
||||
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown> };
|
||||
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; sections: Section[] };
|
||||
|
||||
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
|
||||
const LISTS: Record<string, string> = {
|
||||
ministries: "This page lists your ministries (under Ministries); blocks you add show after them.",
|
||||
leadership: "This page lists your team (under Leadership); blocks you add show after them.",
|
||||
events: "This page lists your events; blocks you add show after them.",
|
||||
messages: "This page lists your messages; blocks you add show after them.",
|
||||
contact: "This page shows your church's contact details and service times from your church profile.",
|
||||
};
|
||||
|
||||
function SectionEditor({ title, fields, initial, onSave, extra }: { title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>; onSave: (data: Record<string, unknown>) => Promise<unknown>; extra?: React.ReactNode }) {
|
||||
const [value, setValue] = useState(initial);
|
||||
const [open, setOpen] = useState(false);
|
||||
const { busy, message, fields: errors, run } = useAction();
|
||||
return (
|
||||
<Panel>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h3 className="font-semibold">{title}</h3>
|
||||
<div className="flex gap-2">{extra}<Btn onClick={() => setOpen(!open)} aria-expanded={open}>{open ? "Close" : "Edit"}</Btn></div>
|
||||
</div>
|
||||
{open && (
|
||||
<div className="mt-4 space-y-4">
|
||||
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} />
|
||||
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave(value), "Saved as a draft.")}>Save</Btn>
|
||||
{message && <Notice tone={message.tone}>{message.text}</Notice>}
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EditPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const { data: page, error, setData } = useAdmin<PageData>(`/pages/${id}`);
|
||||
const details = useAction();
|
||||
const blocks = useAction();
|
||||
const [form, setForm] = useState<Partial<PageData> | null>(null);
|
||||
if (!page) return <Loading error={error} />;
|
||||
const f = { ...page, ...form };
|
||||
const saveDetails = () => details.run(async () => {
|
||||
const p = await api<PageData>(`/pages/${id}`, { method: "PUT", body: { title: f.title, slug: f.slug, seoTitle: f.seoTitle, description: f.description, navLabel: f.navLabel, inNav: f.inNav, imageId: f.imageId } });
|
||||
setData(p);
|
||||
setForm(null);
|
||||
}, "Saved as a draft.");
|
||||
const blockCall = (path: string, method: string, body?: unknown) => blocks.run(async () => setData(await api<PageData>(`/pages/${id}${path}`, { method, body })));
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title sub={page.kind === "home" ? "Your home page" : `Your site/${page.slug}`}
|
||||
actions={page.kind !== "home" && <Btn kind="danger" onClick={() => details.run(async () => { await api(`/pages/${id}`, { method: "DELETE" }); router.push("/admin/pages"); })}>Remove page</Btn>}>
|
||||
{page.title}
|
||||
</Title>
|
||||
<div className="space-y-6">
|
||||
<Panel title="Page details">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Title" error={details.fields.title}><input className={inputClass} value={f.title ?? ""} maxLength={120} onChange={(e) => setForm({ ...form, title: e.target.value })} /></Field>
|
||||
{page.kind !== "home" && <Field label="Address" hint={`Your site/${f.slug}`} error={details.fields.slug}><input className={inputClass} value={f.slug ?? ""} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></Field>}
|
||||
{page.kind !== "home" && <Field label="Name in the menu" hint="Leave empty to use the title."><input className={inputClass} value={f.navLabel ?? ""} maxLength={40} onChange={(e) => setForm({ ...form, navLabel: e.target.value || null })} /></Field>}
|
||||
{page.kind !== "home" && <label className="flex items-center gap-2 self-end pb-2 text-sm"><input type="checkbox" checked={!!f.inNav} onChange={(e) => setForm({ ...form, inNav: e.target.checked })} />Show in the menu</label>}
|
||||
<Field label="Title in search results" hint={`${(f.seoTitle ?? f.title ?? "").length} of 60 characters`} error={details.fields.seoTitle}><input className={inputClass} value={f.seoTitle ?? ""} maxLength={70} onChange={(e) => setForm({ ...form, seoTitle: e.target.value || null })} placeholder={f.title} /></Field>
|
||||
<Field label="Description in search results" hint={`${(f.description ?? "").length} of 155 characters${f.description ? "" : ": add one, so search engines show what this page is about"}`} error={details.fields.description}>
|
||||
<textarea className={inputClass} rows={2} value={f.description ?? ""} maxLength={300} onChange={(e) => setForm({ ...form, description: e.target.value || null })} />
|
||||
</Field>
|
||||
<div className="sm:col-span-2"><ImagePicker label="Image when shared (optional)" value={f.imageId ?? null} onChange={(imageId) => setForm({ ...form, imageId })} /></div>
|
||||
</div>
|
||||
{/* A Google-style preview of the search result (ROADMAP-v3 §11). */}
|
||||
<div className="mt-4 rounded border border-gray-200 p-3" aria-label="How it may look in search results">
|
||||
<p className="truncate text-lg text-blue-800">{f.seoTitle || f.title}</p>
|
||||
<p className="line-clamp-2 text-sm text-gray-600">{f.description || "No description yet."}</p>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center gap-3">
|
||||
<Btn kind="primary" busy={details.busy} onClick={saveDetails}>Save details</Btn>
|
||||
{details.message && <Notice tone={details.message.tone}>{details.message.text}</Notice>}
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
{page.kind === "home" ? (
|
||||
<>
|
||||
<p className="text-sm text-gray-600">Each section's layout, order and whether it shows are under Template and style.</p>
|
||||
{HOME_ORDER.map((type) => {
|
||||
const s = page.sections.find((x) => x.type === type);
|
||||
const spec = SECTION_FIELDS[type]!;
|
||||
return <SectionEditor key={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data } }))} />;
|
||||
})}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{LISTS[page.kind] && <Notice>{LISTS[page.kind]}</Notice>}
|
||||
{page.sections.map((s, i) => {
|
||||
const spec = BLOCK_FIELDS[s.type];
|
||||
if (!spec) return null;
|
||||
return (
|
||||
<SectionEditor key={s.id} title={`${spec.name}${s.hidden ? " (hidden)" : ""}`} fields={spec.fields} initial={s.data}
|
||||
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data } }))}
|
||||
extra={<>
|
||||
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "up" })} disabled={i === 0} aria-label="Move up">↑</Btn>
|
||||
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "down" })} disabled={i === page.sections.length - 1} aria-label="Move down">↓</Btn>
|
||||
<Btn onClick={() => blockCall(`/blocks/${s.id}`, "PUT", { hidden: !s.hidden })}>{s.hidden ? "Show" : "Hide"}</Btn>
|
||||
<Btn kind="danger" onClick={() => blockCall(`/blocks/${s.id}`, "DELETE")}>Remove</Btn>
|
||||
</>} />
|
||||
);
|
||||
})}
|
||||
<Panel title="Add a block">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(BLOCK_FIELDS).map(([type, spec]) => <Btn key={type} busy={blocks.busy} onClick={() => blockCall("/blocks", "POST", { type })}>{spec.name}</Btn>)}
|
||||
</div>
|
||||
{blocks.message && <div className="mt-3"><Notice tone={blocks.message.tone}>{blocks.message.text}</Notice></div>}
|
||||
</Panel>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { api } from "@/admin/api";
|
||||
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
type PageRow = { id: string; kind: string; slug: string; title: string; inNav: boolean; path: string };
|
||||
|
||||
const KINDS: Record<string, string> = { home: "Home", visit: "Plan your visit", about: "About", leadership: "Leadership", ministries: "Ministries", events: "Events", messages: "Messages", give: "Give", contact: "Contact", terms: "Terms", safeguarding: "Safeguarding", custom: "Your own page" };
|
||||
|
||||
/** Pages (§6): the fixed ones and the church's own, built from blocks. */
|
||||
export default function Pages() {
|
||||
const { data, error } = useAdmin<PageRow[]>("/pages");
|
||||
const router = useRouter();
|
||||
const [title, setTitle] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const { busy, message, fields, run } = useAction();
|
||||
if (!data) return <Loading error={error} />;
|
||||
const create = () => run(async () => {
|
||||
const p = await api<{ id: string }>("/pages", { body: { title, slug } });
|
||||
router.push(`/admin/pages/${p.id}`);
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<Title sub="Each page is a draft until you publish.">Pages</Title>
|
||||
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
||||
<Panel>
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{data.map((p) => (
|
||||
<li key={p.id} className="flex items-center justify-between gap-3 py-3">
|
||||
<div>
|
||||
<Link href={`/admin/pages/${p.id}`} className="font-medium underline-offset-4 hover:underline">{p.title}</Link>
|
||||
<p className="text-xs text-gray-500">{KINDS[p.kind] ?? p.kind} · {p.path}{!p.inNav && p.kind !== "home" && " · not in the menu"}</p>
|
||||
</div>
|
||||
<Link href={`/admin/pages/${p.id}`} className="text-sm font-semibold text-brand-text">Edit</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Panel>
|
||||
<Panel title="Add a page">
|
||||
<div className="space-y-3">
|
||||
<Field label="Title" error={fields.title}><input className={inputClass} value={title} maxLength={120} onChange={(e) => { setTitle(e.target.value); setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "")); }} /></Field>
|
||||
<Field label="Address" hint={`Your site/${slug || "…"}`} error={fields.slug}><input className={inputClass} value={slug} maxLength={80} onChange={(e) => setSlug(e.target.value)} /></Field>
|
||||
<Btn kind="primary" busy={busy} onClick={create} disabled={!title || !slug}>Add page</Btn>
|
||||
{message && <Notice tone={message.tone}>{message.text}</Notice>}
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Publish and history (WEBSITE-1.0-PLAN §4): every pending change (what, who, when), Discard for
|
||||
* any one, one Publish for the whole site; links to share the preview; every published version,
|
||||
* any of which can be restored into the working copy.
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { api, canEdit } from "@/admin/api";
|
||||
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
|
||||
|
||||
type Change = { key: string; kind: "added" | "changed" | "removed"; what: string; label: string; by: string | null; at: string | null };
|
||||
type Version = { number: number; publishedAt: string; by: string | null; note: string | null };
|
||||
type Link = { id: string; createdAt: string; expiresAt: string; by: string | null; active: boolean };
|
||||
|
||||
const WHAT: Record<string, string> = { design: "Template and style", page: "Page", ministry: "Ministry", leader: "Team" };
|
||||
const KIND: Record<string, string> = { added: "Added", changed: "Changed", removed: "Removed" };
|
||||
|
||||
export default function Publish() {
|
||||
const me = useAdmin<{ user: { role: string } }>("/me");
|
||||
const pending = useAdmin<Change[]>("/changes");
|
||||
const versions = useAdmin<Version[]>("/versions");
|
||||
const editor = !!me.data && canEdit(me.data.user.role);
|
||||
const links = useAdmin<Link[]>(editor ? "/preview-links" : null);
|
||||
const [note, setNote] = useState("");
|
||||
const [newLink, setNewLink] = useState<string | null>(null);
|
||||
const { busy, message, run } = useAction();
|
||||
if (!pending.data || !versions.data) return <Loading error={pending.error ?? versions.error} />;
|
||||
const first = versions.data.length === 0;
|
||||
const reloadAll = async () => { await Promise.all([pending.reload(), versions.reload(), links.reload()]); };
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title sub={first ? "Until you publish, visitors see Coming soon." : "Visitors see the last version published."}
|
||||
actions={<>
|
||||
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that sets the preview cookie: a full page load, not a client navigation */}
|
||||
<a href="/preview/start" className="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-semibold hover:bg-gray-50">Preview the whole site</a>
|
||||
</>}>
|
||||
Publish and history
|
||||
</Title>
|
||||
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
|
||||
<div className="space-y-6">
|
||||
<Panel title={pending.data.length ? `${pending.data.length} ${pending.data.length === 1 ? "change" : "changes"} not published` : "Nothing waiting to be published"}>
|
||||
{pending.data.length > 0 && (
|
||||
<ul className="mb-4 divide-y divide-gray-200">
|
||||
{pending.data.map((c) => (
|
||||
<li key={c.key} className="flex flex-wrap items-center justify-between gap-3 py-2">
|
||||
<div>
|
||||
<p><span className="font-medium">{KIND[c.kind]}:</span> {WHAT[c.what]} {c.what !== "design" && <>“{c.label}”</>}</p>
|
||||
<p className="text-xs text-gray-500">{[c.by, when(c.at)].filter(Boolean).join(", ")}</p>
|
||||
</div>
|
||||
{editor && <Btn busy={busy} onClick={() => run(async () => { await api("/discard", { body: { key: c.key } }); await reloadAll(); }, "Discarded: back to the published version.")}>Discard</Btn>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{editor ? (
|
||||
(pending.data.length > 0 || first) && (
|
||||
<div className="space-y-3">
|
||||
<Field label="A note for the history (optional)"><input className={inputClass} value={note} maxLength={500} onChange={(e) => setNote(e.target.value)} placeholder="E.g. Christmas service times" /></Field>
|
||||
<Btn kind="primary" busy={busy} onClick={() => run(async () => {
|
||||
const r = await api<{ number: number }>("/publish", { body: { note } });
|
||||
// Visitors get it at once, not after the 30-second cache.
|
||||
await fetch("/revalidate", { method: "POST" }).catch(() => {});
|
||||
setNote("");
|
||||
await reloadAll();
|
||||
return r;
|
||||
}, first ? "Published: your site is live." : "Published: visitors see it now.")}>{first ? "Publish your site" : "Publish all changes"}</Btn>
|
||||
</div>
|
||||
)
|
||||
) : <p className="text-sm text-gray-600">An editor publishes your changes.</p>}
|
||||
</Panel>
|
||||
|
||||
{editor && (
|
||||
<Panel title="Share the preview">
|
||||
<p className="mb-3 text-sm text-gray-600">A link for someone without an account (your pastor, say) to see the whole site as it would look published. It works for 7 days, or until you stop it, and can't change anything.</p>
|
||||
<Btn busy={busy} onClick={() => run(async () => { const l = await api<{ url: string }>("/preview-links", { body: {} }); setNewLink(l.url); await links.reload(); })}>Make a preview link</Btn>
|
||||
{newLink && (
|
||||
<div className="mt-3"><Notice tone="success">Copy this link now (it isn't shown again): <code className="break-all font-mono">{newLink}</code></Notice></div>
|
||||
)}
|
||||
{links.data && links.data.length > 0 && (
|
||||
<ul className="mt-4 divide-y divide-gray-200 text-sm">
|
||||
{links.data.map((l) => (
|
||||
<li key={l.id} className="flex items-center justify-between gap-3 py-2">
|
||||
<span>Made {when(l.createdAt)}{l.by && ` by ${l.by}`} · {l.active ? `works until ${when(l.expiresAt)}` : "stopped"}</span>
|
||||
{l.active && <Btn kind="danger" onClick={() => run(async () => { await api(`/preview-links/${l.id}`, { method: "DELETE" }); await links.reload(); }, "The link stopped working.")}>Stop it</Btn>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
<Panel title="History">
|
||||
{versions.data.length === 0 ? <p className="text-gray-600">Not published yet.</p> : (
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{versions.data.map((v, i) => (
|
||||
<li key={v.number} className="flex flex-wrap items-center justify-between gap-3 py-2">
|
||||
<div>
|
||||
<p className="font-medium">Version {v.number}{i === 0 && " (live)"}{v.note && <span className="font-normal text-gray-600"> · {v.note}</span>}</p>
|
||||
<p className="text-xs text-gray-500">{when(v.publishedAt)}{v.by && `, ${v.by}`}</p>
|
||||
</div>
|
||||
{editor && i > 0 && <Btn onClick={() => run(async () => { await api(`/versions/${v.number}/restore`, { body: {} }); await reloadAll(); }, `Version ${v.number} is back in your drafts: preview it, then publish.`)}>Restore</Btn>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Template and style (WEBSITE-1.0-PLAN §3): the template, each homepage section's layout
|
||||
* (recommended first), the homepage order, and the style settings. Fonts and corners are the
|
||||
* church's brand style, shared with its other sites, so they're set in its church profile.
|
||||
*/
|
||||
import { api } from "@/admin/api";
|
||||
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
type Design = { template: string; variants: Record<string, string>; home: { section: string; hidden: boolean }[]; style: Record<string, string> };
|
||||
type Options = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> };
|
||||
|
||||
const TEMPLATES = [
|
||||
{ id: "heritage", name: "Heritage", text: "Traditional and dignified: centred, framed images, serif headings." },
|
||||
{ id: "bold", name: "Bold", text: "Modern and energetic: full-screen photos, big headlines, bands." },
|
||||
{ id: "community", name: "Community", text: "Warm and friendly: cards, rounded shapes, faces up front." },
|
||||
{ id: "clean", name: "Clean", text: "Minimal and calm: lots of space, good without photos." },
|
||||
];
|
||||
|
||||
const SECTIONS: Record<string, string> = { hero: "Top of the page", serviceTimes: "Service times", welcome: "Welcome", ministries: "Ministries", team: "Team", events: "Upcoming events", latestMessage: "Latest message", invitation: "Invitation" };
|
||||
const VARIANT_NAMES: Record<string, string> = {
|
||||
photo: "Photo", video: "Video", collage: "Collage", split: "Split", text: "Text only", panel: "Panel", strip: "Inline strip", map: "With map",
|
||||
"image-text": "Image and text", pastor: "With pastor", cards: "Cards", list: "List", bands: "Alternating bands", faces: "Faces", featured: "Featured",
|
||||
calendar: "Calendar strip", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
|
||||
};
|
||||
const ALL_VARIANTS: Record<string, string[]> = {
|
||||
hero: ["photo", "video", "collage", "split", "text"], serviceTimes: ["panel", "strip", "map"], welcome: ["text", "image-text", "pastor"], ministries: ["cards", "list", "bands"],
|
||||
team: ["faces", "list", "featured"], events: ["cards", "list", "calendar"], latestMessage: ["video", "card", "compact"], invitation: ["banner", "centred", "image"],
|
||||
};
|
||||
const HEADER_NAMES: Record<string, string> = {
|
||||
centred: "Centred", "centred-top-bar": "Centred, with a top bar", transparent: "Over the photo, solid when scrolling", solid: "Solid",
|
||||
"logo-left-button": "Logo left, with a Plan your visit button", "logo-left-tinted": "Logo left, on a tinted bar", small: "Small", "small-menu": "Small, menu on every screen",
|
||||
};
|
||||
const STYLE = [
|
||||
{ key: "sectionColour", label: "Section colour", options: { light: "Light", tinted: "Tinted (your colour, softly)", mixed: "Mixed, with dark bands" } },
|
||||
{ key: "spacing", label: "Spacing", options: { airy: "Airy", compact: "Compact" } },
|
||||
{ key: "buttons", label: "Buttons", options: { solid: "Solid", outline: "Outline", pill: "Pill" } },
|
||||
{ key: "images", label: "Photos", options: { natural: "Natural", mono: "Black and white", duotone: "Duotone in your colour" } },
|
||||
];
|
||||
|
||||
export default function TemplatePage() {
|
||||
const { data, error, setData } = useAdmin<{ design: Design; options: Options }>("/design");
|
||||
const { busy, message, run } = useAction();
|
||||
if (!data) return <Loading error={error} />;
|
||||
const { design, options } = data;
|
||||
const save = (patch: Partial<Design> & { template?: string }, done = "Saved. Preview to see it, then publish.") => run(async () => {
|
||||
const r = await api<{ design: Design; moved: { what: string }[] }>("/design", { method: "PUT", body: patch });
|
||||
setData({ ...data, design: r.design });
|
||||
return r;
|
||||
}, done);
|
||||
const move = (i: number, d: -1 | 1) => {
|
||||
const home = [...design.home];
|
||||
const j = i + d;
|
||||
if (j < 0 || j >= home.length) return;
|
||||
[home[i], home[j]] = [home[j]!, home[i]!];
|
||||
save({ home });
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Title sub="Changes here are drafts: preview them, then publish.">Template and style</Title>
|
||||
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
|
||||
<div className="space-y-6">
|
||||
<Panel title="Template">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{TEMPLATES.map((t) => (
|
||||
<button key={t.id} type="button" disabled={busy} onClick={() => t.id !== design.template && save({ template: t.id }, `Switched to ${t.name}. Your own choices are kept; the rest moved to ${t.name}'s defaults.`)}
|
||||
aria-pressed={t.id === design.template}
|
||||
className={cx("rounded-lg border-2 p-4 text-left", t.id === design.template ? "border-brand bg-brand-tint" : "border-gray-200 hover:border-gray-400")}>
|
||||
<span className="block font-semibold">{t.name}{t.id === design.template && " (in use)"}</span>
|
||||
<span className="mt-1 block text-sm text-gray-600">{t.text}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Home page: sections and layouts">
|
||||
<p className="mb-4 text-sm text-gray-600">Every layout works in every template; the first ones listed suit {TEMPLATES.find((t) => t.id === design.template)?.name} best.</p>
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{design.home.map((e, i) => {
|
||||
const recommended = options.variants[design.template]?.[e.section] ?? [];
|
||||
const ordered = [...recommended, ...ALL_VARIANTS[e.section]!.filter((v) => !recommended.includes(v))];
|
||||
return (
|
||||
<li key={e.section} className="flex flex-wrap items-center gap-3 py-3">
|
||||
<span className="w-40 font-medium">{SECTIONS[e.section]}</span>
|
||||
<select aria-label={`${SECTIONS[e.section]} layout`} className={`${inputClass} w-56`} value={design.variants[e.section]} disabled={busy}
|
||||
onChange={(ev) => save({ variants: { [e.section]: ev.target.value } })}>
|
||||
{ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)}
|
||||
</select>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={!e.hidden} disabled={busy} onChange={(ev) => save({ home: design.home.map((x) => (x.section === e.section ? { ...x, hidden: !ev.target.checked } : x)) })} />
|
||||
Show
|
||||
</label>
|
||||
<span className="ml-auto flex gap-1">
|
||||
<Btn onClick={() => move(i, -1)} disabled={busy || i === 0} aria-label={`Move ${SECTIONS[e.section]} up`}>↑</Btn>
|
||||
<Btn onClick={() => move(i, 1)} disabled={busy || i === design.home.length - 1} aria-label={`Move ${SECTIONS[e.section]} down`}>↓</Btn>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Style">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Header">
|
||||
<select className={inputClass} value={design.style.header} disabled={busy} onChange={(e) => save({ style: { header: e.target.value } })}>
|
||||
{(options.headers[design.template] ?? []).map((h) => <option key={h} value={h}>{HEADER_NAMES[h] ?? h}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
{STYLE.map((s) => (
|
||||
<Field key={s.key} label={s.label}>
|
||||
<select className={inputClass} value={design.style[s.key]} disabled={busy} onChange={(e) => save({ style: { [s.key]: e.target.value } })}>
|
||||
{Object.entries(s.options).map(([v, label]) => <option key={v} value={v}>{label}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-4 text-sm text-gray-600">Fonts and corners are your church's brand style, shared with your Events and sign-in pages: change them in your church profile.</p>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,35 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import "@crosscode/ui/fonts.css";
|
||||
import "./globals.css";
|
||||
import { brandAttributes } from "@crosscode/ui";
|
||||
import { loadContent } from "@/site/load";
|
||||
import { PreviewBar } from "@/site/PreviewBar";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const c = await loadContent();
|
||||
const name = c.church?.name ?? "Church Website";
|
||||
return { title: { default: name, template: `%s · ${name}` }, icons: c.church?.branding.iconUrl ? { icon: c.church.branding.iconUrl } : undefined };
|
||||
return {
|
||||
title: { default: name, template: `%s · ${name}` },
|
||||
icons: c.church?.branding.iconUrl ? { icon: c.church.branding.iconUrl } : undefined,
|
||||
// A preview is never indexed (§4).
|
||||
...(c.mode === "published" && c.preview ? { robots: { index: false, follow: false } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Every page: the church's fonts and corners (shared brand style), the template and the style
|
||||
* settings as attributes (globals.css), and its colours, made safe by the backend, as variables.
|
||||
* While previewing, the site's pages get the preview bar above them.
|
||||
*/
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const c = await loadContent();
|
||||
const path = (await headers()).get("x-ccw-path") ?? "/";
|
||||
const p = c.palette;
|
||||
const template = c.mode === "published" ? c.snapshot.design.template : c.template;
|
||||
const s = c.mode === "published" ? c.snapshot.design.style : null;
|
||||
const vars = `:root{--brand:${p.brand};--brand-dark:${p.brandDark};--on-brand:${p.onBrand};--brand-text:${p.brandText};--brand-tint:${p.brandTint};--accent:${p.accent};--on-accent:${p.onAccent}}`;
|
||||
const bar = c.mode === "published" && c.preview && !path.startsWith("/admin") && !path.startsWith("/preview") ? c.preview : null;
|
||||
return (
|
||||
<html
|
||||
lang="en-ZA"
|
||||
@@ -33,7 +43,10 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
<head>
|
||||
<style>{vars.replace(/[<>]/g, "")}</style>
|
||||
</head>
|
||||
<body>{children}</body>
|
||||
<body>
|
||||
{bar && <PreviewBar preview={bar} />}
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* A shared preview link (§4): keeps its token in a cookie for the rest of the visit, so every page
|
||||
* shows the working copy. The backend checks the token (7 days, until revoked) on every page.
|
||||
*/
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ token: string }> }) {
|
||||
const { token } = await params;
|
||||
const res = NextResponse.redirect(new URL("/", request.url), 303);
|
||||
if (/^[A-Za-z0-9_-]{20,100}$/.test(token)) {
|
||||
res.cookies.set("ccw_preview", token, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/", maxAge: 7 * 86400 });
|
||||
}
|
||||
res.headers.set("X-Robots-Tag", "noindex, nofollow");
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/** Leaves the preview: an admin goes back to editing, someone with a shared link to the live site. */
|
||||
export function GET(request: NextRequest) {
|
||||
const admin = request.cookies.get("ccw_preview")?.value === "admin";
|
||||
const to = admin ? (request.nextUrl.searchParams.get("published") ? "/admin/publish" : "/admin") : "/";
|
||||
const res = NextResponse.redirect(new URL(to, request.url), 303);
|
||||
res.cookies.delete("ccw_preview");
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Metadata } from "next";
|
||||
import { PreviewBar } from "@/site/PreviewBar";
|
||||
import { loadContent } from "@/site/load";
|
||||
|
||||
export const metadata: Metadata = { title: "Preview", robots: { index: false, follow: false } };
|
||||
|
||||
const WIDTHS: Record<string, number> = { phone: 390, tablet: 820 };
|
||||
|
||||
/**
|
||||
* The preview at phone or tablet width (§4): the site in a frame of that width, so its layout is
|
||||
* exactly what a phone shows. The bar stays outside the frame.
|
||||
*/
|
||||
export default async function Frame({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
|
||||
const q = await searchParams;
|
||||
const size = q.size === "tablet" ? "tablet" : "phone";
|
||||
const c = await loadContent();
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-200">
|
||||
{c.mode === "published" && c.preview && <PreviewBar preview={c.preview} size={size} />}
|
||||
<div className="flex justify-center py-6">
|
||||
<iframe src="/" title={`The site at ${size} width`} style={{ width: WIDTHS[size], height: "calc(100vh - 7rem)" }} className="rounded-lg border border-gray-300 bg-white shadow-xl" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* Preview (WEBSITE-1.0-PLAN §4): a signed-in admin sees the working copy on the site's own
|
||||
* addresses, fully clickable. The cookie only asks for it; the backend checks the admin's session
|
||||
* on every page (site/preview), so it shows nothing to anyone else.
|
||||
*/
|
||||
export function GET(request: NextRequest) {
|
||||
const res = NextResponse.redirect(new URL("/", request.url), 303);
|
||||
res.cookies.set("ccw_preview", "admin", { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/" });
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { revalidateTag } from "next/cache";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
|
||||
|
||||
/**
|
||||
* Publish (WEBSITE-1.0-PLAN §1, §4) refreshes the public pages at once: the admin calls this right
|
||||
* after publishing, and the next visitor gets the new version (no stale copy). Only a signed-in
|
||||
* admin can ask.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const session = request.cookies.get("ccw_session")?.value;
|
||||
const me = session ? await fetch(`${api}/api/auth/me`, { headers: { Cookie: `ccw_session=${encodeURIComponent(session)}` }, cache: "no-store" }).catch(() => null) : null;
|
||||
if (!me?.ok) return NextResponse.json({ error: { code: "SIGNED_OUT", message: "Please sign in." } }, { status: 401 });
|
||||
revalidateTag("site-content", { expire: 0 });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* The address a page was asked for, for the layouts: the admin's, so signing in comes back to
|
||||
* that exact page (ROADMAP-v3 §3, "Sign-in always returns you to where you came from"), and the
|
||||
* root layout's, which shows the preview bar on the site's pages only.
|
||||
*/
|
||||
export function proxy(request: NextRequest) {
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set("x-ccw-path", `${request.nextUrl.pathname}${request.nextUrl.search}`);
|
||||
return NextResponse.next({ request: { headers } });
|
||||
}
|
||||
|
||||
// Never Next's own paths (/_next: its files and the development connection).
|
||||
export const config = { matcher: ["/((?!api|_next|favicon.ico).*)"] };
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* The preview bar (WEBSITE-1.0-PLAN §4): above the page (so the page is laid out exactly as it
|
||||
* will be), with phone / tablet / desktop width, Back to editing, and Publish for an editor. Inside
|
||||
* the width frame it hides itself: the frame page has its own.
|
||||
*/
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admin" | "link"; canPublish: boolean }; size?: "phone" | "tablet" | "desktop" }) {
|
||||
const [inFrame, setInFrame] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
// Only the browser knows whether this page is inside the width frame.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setInFrame(window.self !== window.top);
|
||||
}, []);
|
||||
if (inFrame) return null;
|
||||
const publish = async () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/v1/admin/publish", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
|
||||
if (res.ok) {
|
||||
await fetch("/revalidate", { method: "POST" }).catch(() => {});
|
||||
// A full page load: the route clears the preview cookie.
|
||||
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
|
||||
window.location.href = "/preview/exit?published=1";
|
||||
}
|
||||
else {
|
||||
setError(((await res.json().catch(() => null)) as { error?: { message?: string } } | null)?.error?.message ?? "Publishing didn't work.");
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const width = (s: string, label: string, href: string) => (
|
||||
<a href={href} aria-current={size === s ? "true" : undefined} className={`rounded px-2 py-1 ${size === s ? "bg-white text-gray-900" : "hover:bg-white/10"}`}>{label}</a>
|
||||
);
|
||||
return (
|
||||
<div className="bg-gray-900 font-sans text-sm text-white" role="region" aria-label="Preview">
|
||||
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-2">
|
||||
<p><strong>Preview</strong> · {preview.by === "admin" ? "your changes, not live yet" : "not live yet"}</p>
|
||||
<div className="flex items-center gap-1" aria-label="Width">
|
||||
{width("phone", "Phone", "/preview/frame?size=phone")}
|
||||
{width("tablet", "Tablet", "/preview/frame?size=tablet")}
|
||||
{width("desktop", "Desktop", "/")}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{error && <span role="alert" className="text-amber-300">{error}</span>}
|
||||
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that clears the preview cookie: a full page load, not a client navigation */}
|
||||
<a href="/preview/exit" className="underline-offset-4 hover:underline">{preview.by === "admin" ? "Back to editing" : "Leave the preview"}</a>
|
||||
{preview.canPublish && (
|
||||
<button type="button" onClick={publish} disabled={busy} className="rounded bg-white px-3 py-1.5 font-semibold text-gray-900 disabled:opacity-60">{busy ? "Publishing…" : "Publish"}</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { cache } from "react";
|
||||
import type { Image, Published, SiteContent, Template } from "./types";
|
||||
|
||||
@@ -13,14 +14,33 @@ const FALLBACK: SiteContent = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The site as visitors see it: one fetch per request (React `cache`), kept by Next for 30 seconds,
|
||||
* so Publish shows within half a minute. While the backend can't answer: Coming soon, never an
|
||||
* error page.
|
||||
* The site as visitors see it: one fetch per request (React `cache`), kept by Next for
|
||||
* WEBSITE_CONTENT_CACHE_SECONDS (30; tag `site-content`, which Publish clears at once through
|
||||
* app/revalidate). While the backend can't answer: Coming soon, never an error page.
|
||||
*/
|
||||
export const loadContent = cache(async (): Promise<SiteContent> => {
|
||||
// Previewing (§4): the working copy, if the backend agrees this is an admin or a live share link.
|
||||
const jar = await cookies();
|
||||
const preview = jar.get("ccw_preview")?.value;
|
||||
if (preview) {
|
||||
try {
|
||||
const session = jar.get("ccw_session")?.value;
|
||||
const res = await fetch(`${api}/api/v1/site/preview`, {
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
...(session ? { Cookie: `ccw_session=${encodeURIComponent(session)}` } : {}),
|
||||
...(preview !== "admin" ? { "x-preview-token": preview } : {}),
|
||||
},
|
||||
});
|
||||
if (res.ok) return (await res.json()) as SiteContent;
|
||||
} catch {
|
||||
// Falls back to the live site.
|
||||
}
|
||||
}
|
||||
try {
|
||||
// In development (and the e2e run) always fresh, so a Publish shows at once.
|
||||
const res = await fetch(`${api}/api/v1/site/content`, process.env.NODE_ENV === "production" ? { next: { revalidate: 30 } } : { cache: "no-store" });
|
||||
// Not kept in development, or when set to 0 (the e2e run changes content behind Next's back).
|
||||
const seconds = process.env.NODE_ENV === "production" ? Number(process.env.WEBSITE_CONTENT_CACHE_SECONDS ?? 30) : 0;
|
||||
const res = await fetch(`${api}/api/v1/site/content`, seconds > 0 ? { next: { revalidate: seconds, tags: ["site-content"] } } : { cache: "no-store" });
|
||||
if (res.ok) return (await res.json()) as SiteContent;
|
||||
} catch {
|
||||
// Starting or down.
|
||||
|
||||
@@ -78,6 +78,8 @@ export type Published = Common & {
|
||||
transparentHeader: Record<string, boolean>;
|
||||
messages: SiteMessage[];
|
||||
events: SiteEvent[];
|
||||
/** Only when previewing the working copy (§4). */
|
||||
preview?: { by: "admin" | "link"; canPublish: boolean };
|
||||
};
|
||||
|
||||
export type SiteContent = ComingSoon | Published;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
// The Website end to end (docs/WEBSITE-1.0-PLAN.md §13): the real backend on an in-memory database
|
||||
// with the demo church (e2e/server.ts), and the Next.js pages. Run with `npx playwright test` in
|
||||
// with the demo church (e2e/server.ts), and the Next.js pages (a production build). Run with `npx playwright test` in
|
||||
// apps/website. Nothing needs a database.
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
@@ -23,12 +23,13 @@ export default defineConfig({
|
||||
stdout: "pipe",
|
||||
},
|
||||
{
|
||||
command: "npx next dev -p 3310",
|
||||
// A production build, as churches run it (next dev's Fast Refresh remounts pages mid-test).
|
||||
command: "npx next build && npx next start -p 3310",
|
||||
cwd: "frontend",
|
||||
url: "http://localhost:3310/robots.txt",
|
||||
timeout: 180_000,
|
||||
timeout: 300_000,
|
||||
reuseExistingServer: false,
|
||||
env: { WEBSITE_API_URL: "http://127.0.0.1:5310" },
|
||||
env: { WEBSITE_API_URL: "http://127.0.0.1:5310", WEBSITE_CONTENT_CACHE_SECONDS: "0" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
+1
-1
@@ -102,7 +102,7 @@ out").
|
||||
[WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): decisions all confirmed 2026-11-21. Font pairings
|
||||
confirmed 2026-11-24 (§3). Order: ~~contracts 1.17.0~~ → ~~Accounts 1.7.0~~ (both released 2026-11-24; Accounts
|
||||
ships with contracts because it answers the new `church.update`) → ~~Events 3.7.0~~ (shared fonts and footer; released 2026-11-24) → ~~Hub 2.21.0~~ (released
|
||||
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (skeleton in `apps/website` 2026-11-25: backend, frontend, content model, the section variants in `src/site/variants.ts`) → Hope Family Church → a second
|
||||
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (being built in `apps/website` since 2026-11-25: signing in, the four templates and public site, the admin with preview, publish and restore; next: roles, messages and events, image sizes, the event feed, Lighthouse, the VM test) → Hope Family Church → a second
|
||||
church → crosscode-site 1.7.0.
|
||||
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
|
||||
before Hub 2.10.0, and the Hub's own site, has `location ^~ /api/`.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Phase **5** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§6, §9, §10, §11; decisions 19, 20, 40–47).
|
||||
Written 2026-11-21. **All decisions confirmed by Joshua on 2026-11-21** (12 changed: a full
|
||||
storage stops uploads). **Being built:** the skeleton, signing in, `website.sh`, and the four templates with the public site are in `apps/website` (2026-11-25).
|
||||
storage stops uploads). **Being built:** the skeleton, signing in, `website.sh`, the four templates with the public site, and the admin with drafts, preview, publish and restore are in `apps/website` (2026-11-25).
|
||||
|
||||
**Updated 2026-11-24:** the Hub release is **2.21.0**, not 2.13.0 (the Hub reached 2.20.0 on
|
||||
2026-11-23 with other work). The 8 font pairings in §3 ("Font pairings") were **confirmed by Joshua
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{ "name": "WEBSITE_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" }
|
||||
{ "name": "WEBSITE_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" },
|
||||
{ "name": "WEBSITE_CONTENT_CACHE_SECONDS", "layer": "defaults", "default": "30", "description": "How long the public pages keep the published site; Publish clears it at once" }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user