Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
405 lines
17 KiB
TypeScript
405 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { useRouter, useSearchParams } from "next/navigation";
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
|
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
|
import { emptyBlock, emptyPage, pageBody, withTitle, type BlockType, type CmsBlock, type CmsPage, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
|
|
import { setField } from "./CmsEdit";
|
|
import { deletePage, discardPage, getPage, publishPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
|
|
import { listAdminEvents } from "@/app/lib/services/adminEvents";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import type { EventOption } from "./BlockFields";
|
|
|
|
// The landing-page editor's state and actions, shared by the form editor and the on-page editor
|
|
// (add-page-visual-editor). Every block carries a stable key, so a chosen image follows its block through moves and
|
|
// removals. Block images upload on Save, just before the page is saved, each at most once even when a later step fails.
|
|
|
|
export interface Row {
|
|
key: number;
|
|
block: CmsBlock;
|
|
}
|
|
|
|
export function readDataUrl(file: File): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
const reader = new FileReader();
|
|
reader.onload = () => resolve(reader.result as string);
|
|
reader.onerror = () => reject(reader.error);
|
|
reader.readAsDataURL(file);
|
|
});
|
|
}
|
|
|
|
/** The list with one item moved from one place to another. */
|
|
export function moveItem<T>(list: T[], from: number, to: number): T[] {
|
|
const next = [...list];
|
|
const [item] = next.splice(from, 1);
|
|
next.splice(to, 0, item);
|
|
return next;
|
|
}
|
|
|
|
type Pending = Record<number, { file: File; preview?: string }>;
|
|
/** One undo step: the page as it was. */
|
|
interface Snapshot { draft: CmsPageDraft; rows: Row[]; pending: Pending }
|
|
const HISTORY = 50;
|
|
|
|
const malaysiaToday = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
|
|
|
|
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
|
|
export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
|
|
const t = useT();
|
|
const router = useRouter();
|
|
const { isSuper, companyCode } = useAdminAuth();
|
|
const scope = useCompanyScope();
|
|
const justSaved = useSearchParams()?.get("saved") === "1";
|
|
const [draft, setDraft] = useState<CmsPageDraft>(() => ({ ...emptyPage(), companyId: scope.companyId }));
|
|
const [rows, setRows] = useState<Row[]>(() => (initialBlocks ?? []).map((block, i) => ({ key: -1 - i, block })));
|
|
const [pending, setPending] = useState<Pending>({});
|
|
// The page as last loaded or saved: what "View page" points at.
|
|
const [saved, setSaved] = useState<{ slug: string; status: PageStatus } | null>(null);
|
|
const [dirty, setDirty] = useState(false);
|
|
const loadId = pageId ?? fromId;
|
|
const [loading, setLoading] = useState(loadId != null);
|
|
const [loadError, setLoadError] = useState<string | null>(null);
|
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
|
const [summary, setSummary] = useState<string | null>(null);
|
|
const [notice, setNotice] = useState<string | null>(justSaved ? "PagesSaved" : null);
|
|
const [saving, setSaving] = useState(false);
|
|
// A published page's edits are saved as a draft; visitors see the live version until Publish changes.
|
|
const [hasDraft, setHasDraft] = useState(false);
|
|
// Bumped when a save leaves a draft, so the editor can bring its banner into view.
|
|
const [revealDraft, setRevealDraft] = useState(0);
|
|
const [events, setEvents] = useState<EventOption[]>([]);
|
|
const [branding, setBranding] = useState<CmsPage["company"]>(undefined);
|
|
// The on-page editor (add-page-visual-editor): the selected block, and a block to bring into view (a refusal).
|
|
const [selected, setSelected] = useState<number | null>(null);
|
|
const [revealed, setRevealed] = useState<{ index: number; n: number } | null>(null);
|
|
// Custom HTML blocks as last loaded or saved, by block key: the canvas shows that version until the next save.
|
|
const [savedHtml, setSavedHtml] = useState<Record<number, { index: number; html?: string }>>({});
|
|
const [frameVersion, setFrameVersion] = useState(0);
|
|
const [past, setPast] = useState<Snapshot[]>([]);
|
|
const [future, setFuture] = useState<Snapshot[]>([]);
|
|
// The field being typed into: typing on in it stays one undo step.
|
|
const typing = useRef<string | null>(null);
|
|
const nextKey = useRef(0);
|
|
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
|
|
const isNew = draft.id == null;
|
|
|
|
const remember = (rs: Row[]) => {
|
|
setSavedHtml(Object.fromEntries(rs.flatMap((r, index) => (r.block.type === "HTML" ? [[r.key, { index, html: r.block.html }]] : []))));
|
|
setFrameVersion((v) => v + 1);
|
|
};
|
|
|
|
/** Shows a loaded page: its draft when there is one, else the live content. */
|
|
function show(p: CmsPage) {
|
|
const c = p.draft ?? p;
|
|
setDraft({ id: p.id, companyId: p.companyId, slug: c.slug, slugTouched: true, title: c.title, metaDescription: c.metaDescription ?? "", status: p.status, hideHeader: !!c.hideHeader, blocks: [] });
|
|
if (p.company) setBranding(p.company);
|
|
const loadedRows = toRows(c.blocks ?? []);
|
|
setRows(loadedRows);
|
|
remember(loadedRows);
|
|
setPending({});
|
|
setSaved({ slug: p.slug, status: p.status });
|
|
setHasDraft(!!p.draft);
|
|
setDirty(false);
|
|
}
|
|
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
|
|
|
|
useEffect(() => {
|
|
if (loadId == null) return;
|
|
let cancelled = false;
|
|
getPage(loadId)
|
|
.then((p) => {
|
|
if (cancelled) return;
|
|
show(p);
|
|
if (pageId == null) {
|
|
// Duplicate: the same company's content as a new, unsaved draft page.
|
|
setDraft((d) => ({ ...d, id: undefined, status: "DRAFT", title: `${d.title} (copy)`, slug: `${d.slug}-copy` }));
|
|
setSaved(null);
|
|
setHasDraft(false);
|
|
setDirty(true);
|
|
}
|
|
})
|
|
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); })
|
|
.finally(() => { if (!cancelled) setLoading(false); });
|
|
return () => { cancelled = true; };
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- show only sets state; load again only for another page.
|
|
}, [loadId]);
|
|
|
|
// The FORM picker: the page company's enabled events that have not ended (Malaysia dates).
|
|
const eventsCompany = isSuper ? draft.companyId : undefined;
|
|
useEffect(() => {
|
|
if (isSuper && !eventsCompany) return;
|
|
let live = true;
|
|
const today = malaysiaToday();
|
|
listAdminEvents({ enabled: "Y", page: 1, pageSize: 100, sortBy: "name", sortDir: "asc", companyId: eventsCompany })
|
|
.then((r) => { if (live) setEvents(r.items.filter((e) => !e.endDate || e.endDate >= today).map((e) => ({ uuid: e.uuid, name: e.name, ticketsEnabled: e.ticketsEnabled }))); })
|
|
.catch(() => {}); // the picker stays empty; a saved event still shows as unavailable
|
|
return () => { live = false; };
|
|
}, [isSuper, eventsCompany]);
|
|
|
|
// Unsaved edits: the browser asks before a reload or close.
|
|
useEffect(() => {
|
|
if (!dirty) return;
|
|
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
|
|
window.addEventListener("beforeunload", warn);
|
|
return () => window.removeEventListener("beforeunload", warn);
|
|
}, [dirty]);
|
|
|
|
/**
|
|
* Starts a change: one undo step per action, and per field while it is typed into (`field`), until another field
|
|
* or action. Marks the page unsaved.
|
|
*/
|
|
const step = (field: string | null) => {
|
|
if (field === null || typing.current !== field) {
|
|
setPast((p) => [...p, { draft, rows, pending }].slice(-HISTORY));
|
|
setFuture([]);
|
|
}
|
|
typing.current = field;
|
|
setDirty(true);
|
|
};
|
|
/** Typing in a field ended (it lost focus): the next change is a new step. */
|
|
const endTyping = () => { typing.current = null; };
|
|
/** Puts back a snapshot, keeping the page's identity (an undo past the first save must not create a second page). */
|
|
const restore = (s: Snapshot) => {
|
|
setDraft({ ...s.draft, id: draft.id, companyId: draft.id != null ? draft.companyId : s.draft.companyId });
|
|
setRows(s.rows);
|
|
setPending(s.pending);
|
|
typing.current = null;
|
|
setDirty(true);
|
|
};
|
|
const undo = () => {
|
|
const prev = past.at(-1);
|
|
if (!prev) return;
|
|
setPast(past.slice(0, -1));
|
|
setFuture([{ draft, rows, pending }, ...future]);
|
|
restore(prev);
|
|
};
|
|
const redo = () => {
|
|
const next = future[0];
|
|
if (!next) return;
|
|
setFuture(future.slice(1));
|
|
setPast([...past, { draft, rows, pending }].slice(-HISTORY));
|
|
restore(next);
|
|
};
|
|
|
|
const patch = (next: Partial<CmsPageDraft>) => {
|
|
step(`page:${Object.keys(next).join()}`);
|
|
setDraft((d) => ({ ...d, ...next }));
|
|
};
|
|
const setTitle = (title: string) => {
|
|
step("page:title");
|
|
setDraft((d) => withTitle(d, title));
|
|
};
|
|
/**
|
|
* A super admin's new page changes company: FORM blocks and hero sign-up forms lose their event, which belongs to the old one,
|
|
* and a hero's form heading, form text and thank-you text go with its form (add-hero-full-width, add-landing-thanks-and-footer).
|
|
*/
|
|
const changeCompany = (companyId: number) => {
|
|
step(null);
|
|
setDraft((d) => ({ ...d, companyId }));
|
|
setRows((rs) => rs.map((r) => {
|
|
if (!r.block.eventUuid) return r;
|
|
const { formHeading: _h, formText: _t, thanksText: _k, ...block } = r.block;
|
|
return { ...r, block: { ...block, eventUuid: null } };
|
|
}));
|
|
};
|
|
const setBlock = (key: number, update: (block: CmsBlock) => CmsBlock) =>
|
|
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
|
|
/** A change from the block's fields (form or side panel). */
|
|
const updateBlock = (key: number, update: (block: CmsBlock) => CmsBlock) => {
|
|
step(`panel:${key}`);
|
|
setBlock(key, update);
|
|
};
|
|
/** A plain text field typed into on the canvas. */
|
|
const text = (key: number, path: string, value: string) => {
|
|
step(`${key}:${path}`);
|
|
setBlock(key, (b) => setField(b, path, value));
|
|
};
|
|
/** Rich text typed into on the canvas. */
|
|
const html = (key: number, value: string) => {
|
|
step(`${key}:html`);
|
|
setBlock(key, (b) => ({ ...b, html: value }));
|
|
};
|
|
/** Brings a section into view on the canvas: one just added, copied, moved, or refused by the server. */
|
|
const reveal = (index: number) => setRevealed((r) => ({ index, n: (r?.n ?? 0) + 1 }));
|
|
const moveBlockTo = (from: number, to: number) => {
|
|
if (from === to) return;
|
|
step(null);
|
|
setRows((rs) => moveItem(rs, from, to));
|
|
setSelected((s) => (s === from ? to : s));
|
|
reveal(to);
|
|
};
|
|
const moveBlock = (index: number, delta: -1 | 1) => moveBlockTo(index, index + delta);
|
|
const removeBlock = (key: number) => {
|
|
step(null);
|
|
setRows((rs) => rs.filter((r) => r.key !== key));
|
|
setPending(({ [key]: _dropped, ...rest }) => rest);
|
|
setSelected(null);
|
|
};
|
|
/** A new block of that type at that place, selected. */
|
|
const insertBlock = (at: number, type: BlockType) => {
|
|
step(null);
|
|
setRows((rs) => [...rs.slice(0, at), { key: ++nextKey.current, block: emptyBlock(type) }, ...rs.slice(at)]);
|
|
setSelected(at);
|
|
reveal(at);
|
|
};
|
|
const addBlock = (type: BlockType) => insertBlock(rows.length, type);
|
|
/** A copy of the block below it, selected; a chosen image not saved yet goes with it. */
|
|
const duplicateBlock = (index: number) => {
|
|
const row = rows[index];
|
|
if (!row) return;
|
|
step(null);
|
|
const key = ++nextKey.current;
|
|
setRows((rs) => [...rs.slice(0, index + 1), { key, block: structuredClone(row.block) }, ...rs.slice(index + 1)]);
|
|
if (pending[row.key]) setPending((p) => ({ ...p, [key]: p[row.key] }));
|
|
setSelected(index + 1);
|
|
reveal(index + 1);
|
|
};
|
|
/** A Custom HTML block whose canvas frame does not show its current HTML: changed or moved since the last save. */
|
|
const stale = (index: number) => {
|
|
const row = rows[index];
|
|
if (row?.block.type !== "HTML") return false;
|
|
const saved = savedHtml[row.key];
|
|
return draft.id == null || !saved || saved.index !== index || saved.html !== row.block.html;
|
|
};
|
|
const chooseImage = (key: number, file: File) => {
|
|
step(null);
|
|
setPending((p) => ({ ...p, [key]: { file } }));
|
|
readDataUrl(file)
|
|
.then((preview) => setPending((p) => (p[key]?.file === file ? { ...p, [key]: { file, preview } } : p)))
|
|
.catch(() => {});
|
|
};
|
|
|
|
function showError(err: unknown) {
|
|
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: string } } | undefined) : undefined;
|
|
const field = data?.details?.field;
|
|
const message = data?.code ? t(data.code) : t("PagesSaveFailed");
|
|
if (field) setErrors({ [field === "file" ? "blocks" : field]: message });
|
|
else setSummary(message);
|
|
// The on-page editor selects the refused block and brings it into view; a page field shows in the page settings.
|
|
const block = field?.match(/^blocks\[(\d+)\]/);
|
|
if (block) {
|
|
const index = Number(block[1]);
|
|
setSelected(index);
|
|
reveal(index);
|
|
} else if (field) setSelected(null);
|
|
}
|
|
|
|
async function save(): Promise<boolean> {
|
|
setSummary(null);
|
|
setNotice(null);
|
|
setErrors({});
|
|
if (isNew && isSuper && !draft.companyId) {
|
|
setErrors({ companyId: t("ChooseCompany") });
|
|
return false;
|
|
}
|
|
setSaving(true);
|
|
const next = rows.map((r) => ({ ...r }));
|
|
const left = { ...pending };
|
|
try {
|
|
for (const row of next) {
|
|
if (!left[row.key]) continue;
|
|
const data = (await readDataUrl(left[row.key].file)).split(",")[1];
|
|
row.block = { ...row.block, imageId: (await uploadPageImage(draft.companyId, data)).id };
|
|
delete left[row.key];
|
|
}
|
|
const page = await savePage(draft.id, pageBody({ ...draft, blocks: next.map((r) => r.block) }));
|
|
setDraft((d) => ({ ...d, id: page.id, companyId: page.companyId }));
|
|
setSaved({ slug: page.slug, status: page.status });
|
|
setHasDraft(!!page.draft);
|
|
if (page.draft) setRevealDraft((n) => n + 1);
|
|
setDirty(false);
|
|
remember(next);
|
|
setNotice("PagesSaved");
|
|
if (isNew) router.replace(`/pages/${page.id}?saved=1`);
|
|
return true;
|
|
} catch (err) {
|
|
showError(err);
|
|
return false;
|
|
} finally {
|
|
// Uploaded images stay on their blocks and leave the pending set, success or not.
|
|
setRows(next);
|
|
setPending(left);
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* add-html-image-upload: uploads an image for a Custom HTML block at once, for the page's company. Resolves to its id;
|
|
* rejects with the reason to show (no company yet, or the server's refusal).
|
|
*/
|
|
async function uploadImage(file: File): Promise<number> {
|
|
if (isSuper && !draft.companyId) throw new Error(t("ChooseCompany"));
|
|
try {
|
|
return (await uploadPageImage(draft.companyId, (await readDataUrl(file)).split(",")[1])).id;
|
|
} catch (err) {
|
|
const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined;
|
|
throw new Error(t(code ?? "PagesSaveFailed"));
|
|
}
|
|
}
|
|
|
|
/** Saves the current edits, then makes the draft live. */
|
|
async function publishChanges() {
|
|
if (draft.id == null || !(await save())) return;
|
|
setSaving(true);
|
|
try {
|
|
show(await publishPage(draft.id));
|
|
setNotice("PagesChangesPublished");
|
|
} catch (err) {
|
|
setNotice(null);
|
|
showError(err);
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
async function discardChanges() {
|
|
if (draft.id == null) return;
|
|
setSaving(true);
|
|
setSummary(null);
|
|
setErrors({});
|
|
try {
|
|
show(await discardPage(draft.id));
|
|
setNotice("PagesChangesDiscarded");
|
|
} catch (err) {
|
|
showError(err);
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
/** Deletes the page and leaves for the list; false when refused. */
|
|
async function remove(): Promise<boolean> {
|
|
if (draft.id == null) return false;
|
|
setSaving(true);
|
|
try {
|
|
await deletePage(draft.id);
|
|
setDirty(false);
|
|
router.push("/pages");
|
|
return true;
|
|
} catch (err) {
|
|
showError(err);
|
|
return false;
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
/** The refusals for one block, keyed by its own field path. */
|
|
const blockErrors = (index: number) => {
|
|
const prefix = `blocks[${index}].`;
|
|
return Object.fromEntries(Object.entries(errors).flatMap(([path, m]) => (path.startsWith(prefix) ? [[path.slice(prefix.length), m]] : [])));
|
|
};
|
|
|
|
return {
|
|
draft, rows, pending, saved, dirty, loading, loadError, errors, summary, notice, saving, hasDraft, revealDraft, events,
|
|
code, isNew, isSuper, companies: scope.companies, branding,
|
|
selected, select: setSelected, revealed, frameVersion, stale,
|
|
canUndo: past.length > 0, canRedo: future.length > 0, undo, redo, endTyping,
|
|
patch, setTitle, changeCompany, updateBlock, text, html, moveBlock, moveBlockTo, removeBlock, addBlock, insertBlock, duplicateBlock,
|
|
chooseImage, uploadImage, blockErrors,
|
|
save, publishChanges, discardChanges, remove,
|
|
};
|
|
}
|