feat(pages): on-page visual editor for landing pages #64

Merged
ngqile merged 17 commits from add-page-visual-editor into main 2026-12-03 08:19:05 +00:00
3 changed files with 295 additions and 261 deletions
Showing only changes of commit 7e916b77b9 - Show all commits

No files matched your search

@@ -17,7 +17,7 @@ Design: `design.md`. Every task is TDD. Work is serial in the main session, with
On failure, stop and switch to the canvas-route fallback (design Decision 1), noting why.
Passed 2026-12-03 in `next dev` and `next build` + `next start`: 390 px stacks the cards and 1280 px shows three columns; Inter and dark mode follow the editor live; Tiptap typed and applied bold; a plain field kept its caret; dragstart and drop fired inside the scaled frame; a Custom HTML frame grew to 4419 px after 1.2. The frame scrolls inside rather than growing (design Decision 2).
- [x] 1.2 `HtmlFrame` listens on its own document's window (test: a frame inside another document still resizes).
- [ ] 1.3 Move `PageEditor` state and actions into `usePageDraft`, with no behaviour change. All existing `PageEditor*.test.tsx` stay green and unchanged.
- [x] 1.3 Move `PageEditor` state and actions into `usePageDraft`, with no behaviour change. All existing `PageEditor*.test.tsx` stay green and unchanged.
- [ ] 1.4 Leave guard for in-app links in the form editor (test: an in-app link click with unsaved edits asks; Cancel stays, Leave navigates).
## 2. Canvas
@@ -2,7 +2,6 @@
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
@@ -12,254 +11,34 @@ import { Switch } from "@/app/components/ui/switch";
import { Textarea } from "@/app/components/ui/textarea";
import { ErrorState } from "@/app/components/ui/states";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { ApiError } from "@/app/lib/clientApi";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useCompanyScope } from "@/app/lib/CompanyScope";
import { CopyAddress } from "./CopyAddress";
import { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPage, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
import { deletePage, discardPage, getPage, publishPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
import { listAdminEvents } from "@/app/lib/services/adminEvents";
import { BLOCK_LABELS, BLOCK_TYPES, pageAddress, type CmsBlock } from "@/app/lib/cmsPages";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { BlockFields, type EventOption } from "./BlockFields";
import { BlockFields } from "./BlockFields";
import { usePageDraft } from "./usePageDraft";
// The landing-page editor, ported from babyboo's PageEditor. 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.
interface Row {
key: number;
block: CmsBlock;
}
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);
});
}
const malaysiaToday = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
// The landing-page form editor, ported from babyboo's PageEditor. State and actions live in usePageDraft, shared
// with the on-page editor; this is the layout for narrow windows.
function FieldError({ message }: { message?: string }) {
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
}
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
export function PageEditor(props: { 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<Record<number, { file: File; preview?: string }>>({});
// 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);
const p = usePageDraft(props);
const { draft, rows, errors, saving, saved, code } = p;
const [confirmDelete, setConfirmDelete] = useState(false);
const [confirmDiscard, setConfirmDiscard] = 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: Save sits below a long form, so the banner is scrolled into view.
const [revealDraft, setRevealDraft] = useState(0);
// Save sits below a long form, so the unpublished-changes banner is scrolled into view after a save that leaves one.
const draftBanner = useRef<HTMLDivElement>(null);
useEffect(() => {
if (revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
}, [revealDraft]);
const [events, setEvents] = useState<EventOption[]>([]);
const nextKey = useRef(0);
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
const isNew = draft.id == null;
if (p.revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
}, [p.revealDraft]);
/** 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: [] });
setRows(toRows(c.blocks ?? []));
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 }))); })
.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. ponytail: in-app links are not guarded; add a router guard if staff lose work that way.
useEffect(() => {
if (!dirty) return;
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, [dirty]);
const edit = <T,>(fn: (v: T) => void) => (v: T) => { setDirty(true); fn(v); };
const patch = edit((next: Partial<CmsPageDraft>) => setDraft((d) => ({ ...d, ...next })));
const updateBlock = (key: number, update: (block: CmsBlock) => CmsBlock) => {
setDirty(true);
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
};
const moveBlock = (index: number, delta: -1 | 1) => {
setDirty(true);
setRows((rs) => {
const next = [...rs];
[next[index], next[index + delta]] = [next[index + delta], next[index]];
return next;
});
};
const removeBlock = (key: number) => {
setDirty(true);
setRows((rs) => rs.filter((r) => r.key !== key));
setPending(({ [key]: _dropped, ...rest }) => rest);
};
const chooseImage = (key: number, file: File) => {
setDirty(true);
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);
}
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);
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);
}
}
/** 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 {
setConfirmDiscard(false);
setSaving(false);
}
}
async function remove() {
if (draft.id == null) return;
setSaving(true);
try {
await deletePage(draft.id);
setDirty(false);
router.push("/pages");
} catch (err) {
setConfirmDelete(false);
showError(err);
} finally {
setSaving(false);
}
}
if (loadError) return <ErrorState message={t(loadError)} />;
if (loading) return null;
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]] : [])));
};
if (p.loadError) return <ErrorState message={t(p.loadError)} />;
if (p.loading) return null;
return (
<div className="space-y-4">
@@ -281,13 +60,13 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
</Button>
) : null}
</div>
{summary && <p role="alert" className="text-sm text-destructive">{summary}</p>}
{notice && <p role="status" className="text-sm text-positive">{t(notice)}</p>}
{hasDraft && draft.status === "PUBLISHED" ? (
{p.summary && <p role="alert" className="text-sm text-destructive">{p.summary}</p>}
{p.notice && <p role="status" className="text-sm text-positive">{t(p.notice)}</p>}
{p.hasDraft && draft.status === "PUBLISHED" ? (
<div ref={draftBanner} className="flex scroll-mt-20 flex-wrap items-center gap-2 rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-sm">
<p className="mr-auto">{t("PagesDraftBanner")}</p>
<Button type="button" size="sm" variant="outline" disabled={saving} onClick={() => setConfirmDiscard(true)}>{t("PagesDiscardChanges")}</Button>
<Button type="button" size="sm" disabled={saving} onClick={() => void publishChanges()}>{t("PagesPublishChanges")}</Button>
<Button type="button" size="sm" disabled={saving} onClick={() => void p.publishChanges()}>{t("PagesPublishChanges")}</Button>
</div>
) : null}
@@ -296,14 +75,13 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
<Card>
<CardHeader><CardTitle>{t("PagesPageCard")}</CardTitle></CardHeader>
<CardContent className="space-y-4">
{isSuper && isNew ? (
{p.isSuper && p.isNew ? (
<div className="space-y-1.5">
<Label htmlFor="page-company">{t("Company")}</Label>
<Select value={draft.companyId ? String(draft.companyId) : ""} disabled={saving}
onValueChange={(v) => { patch({ companyId: Number(v) }); setRows((rs) => rs.map((r) => (r.block.type === "FORM" ? { ...r, block: { ...r.block, eventUuid: null } } : r))); }}>
<Select value={draft.companyId ? String(draft.companyId) : ""} disabled={saving} onValueChange={(v) => p.changeCompany(Number(v))}>
<SelectTrigger id="page-company" aria-invalid={!!errors.companyId} className="w-full"><SelectValue placeholder={t("SelectCompany")} /></SelectTrigger>
<SelectContent>
{scope.companies.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>)}
{p.companies.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>)}
</SelectContent>
</Select>
<FieldError message={errors.companyId} />
@@ -311,19 +89,18 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
) : null}
<div className="space-y-1.5">
<Label htmlFor="page-title">{t("Title")}</Label>
<Input id="page-title" value={draft.title} disabled={saving} aria-invalid={!!errors.title}
onChange={(e) => { const v = e.target.value; setDirty(true); setDraft((d) => withTitle(d, v)); }} />
<Input id="page-title" value={draft.title} disabled={saving} aria-invalid={!!errors.title} onChange={(e) => p.setTitle(e.target.value)} />
<FieldError message={errors.title} />
</div>
<div className="space-y-1.5">
<Label htmlFor="page-slug">{t("PagesSlug")}</Label>
<Input id="page-slug" value={draft.slug} disabled={saving} aria-invalid={!!errors.slug} onChange={(e) => patch({ slug: e.target.value, slugTouched: true })} />
<Input id="page-slug" value={draft.slug} disabled={saving} aria-invalid={!!errors.slug} onChange={(e) => p.patch({ slug: e.target.value, slugTouched: true })} />
<p className="text-xs text-muted-foreground">{t("PagesAddressHint", { address: pageAddress(code || "…", draft.slug || "…") })}</p>
<FieldError message={errors.slug} />
</div>
<div className="space-y-1.5">
<Label htmlFor="page-meta">{t("PagesMetaDescription")}</Label>
<Textarea id="page-meta" rows={3} value={draft.metaDescription} disabled={saving} aria-invalid={!!errors.metaDescription} onChange={(e) => patch({ metaDescription: e.target.value })} />
<Textarea id="page-meta" rows={3} value={draft.metaDescription} disabled={saving} aria-invalid={!!errors.metaDescription} onChange={(e) => p.patch({ metaDescription: e.target.value })} />
<p className="tabular text-xs text-muted-foreground">{`${draft.metaDescription.trim().length}/160`}</p>
<FieldError message={errors.metaDescription} />
</div>
@@ -337,22 +114,21 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
block={row.block}
index={index}
count={rows.length}
errors={blockErrors(index)}
errors={p.blockErrors(index)}
saving={saving}
events={events}
pendingImage={pending[row.key] && { name: pending[row.key].file.name, preview: pending[row.key].preview }}
onChange={(update) => updateBlock(row.key, update)}
onMove={(delta) => moveBlock(index, delta)}
onRemove={() => removeBlock(row.key)}
onChooseImage={(file) => chooseImage(row.key, file)}
events={p.events}
pendingImage={p.pending[row.key] && { name: p.pending[row.key].file.name, preview: p.pending[row.key].preview }}
onChange={(update) => p.updateBlock(row.key, update)}
onMove={(delta) => p.moveBlock(index, delta)}
onRemove={() => p.removeBlock(row.key)}
onChooseImage={(file) => p.chooseImage(row.key, file)}
/>
))}
<FieldError message={errors.blocks} />
<div className="flex flex-wrap gap-2">
{BLOCK_TYPES.map((type) => (
<Button key={type} type="button" variant="outline" size="sm" disabled={saving}
onClick={() => { setDirty(true); setRows((rs) => [...rs, { key: ++nextKey.current, block: emptyBlock(type) }]); }}>
<Button key={type} type="button" variant="outline" size="sm" disabled={saving} onClick={() => p.addBlock(type)}>
{t("PagesAddBlock", { type: t(BLOCK_LABELS[type]) })}
</Button>
))}
@@ -365,13 +141,13 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
<CardContent className="space-y-2">
{(["DRAFT", "PUBLISHED"] as const).map((s) => (
<label key={s} className="flex items-center gap-2 text-sm">
<input type="radio" name="page-status" value={s} checked={draft.status === s} disabled={saving} onChange={() => patch({ status: s })} />
<input type="radio" name="page-status" value={s} checked={draft.status === s} disabled={saving} onChange={() => p.patch({ status: s })} />
{t(s === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
</label>
))}
<FieldError message={errors.status} />
<div className="flex items-center gap-2 pt-2 text-sm">
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => patch({ hideHeader: on })} />
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => p.patch({ hideHeader: on })} />
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
</div>
</CardContent>
@@ -385,7 +161,7 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
{t("PagesDelete")}
</Button>
) : <span />}
<Button type="button" disabled={saving} onClick={() => void save()}>{t("Save")}</Button>
<Button type="button" disabled={saving} onClick={() => void p.save()}>{t("Save")}</Button>
</div>
{confirmDiscard ? (
@@ -395,7 +171,7 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
confirmLabel={t("PagesDiscardChanges")}
destructive
busy={saving}
onConfirm={() => void discardChanges()}
onConfirm={() => void p.discardChanges().finally(() => setConfirmDiscard(false))}
onCancel={() => setConfirmDiscard(false)}
/>
) : null}
@@ -406,7 +182,7 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
confirmLabel={t("PagesDelete")}
destructive
busy={saving}
onConfirm={() => void remove()}
onConfirm={() => void p.remove().then((ok) => { if (!ok) setConfirmDelete(false); })}
onCancel={() => setConfirmDelete(false)}
/>
) : null}
@@ -0,0 +1,258 @@
"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 { 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);
});
}
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<Record<number, { file: File; preview?: string }>>({});
// 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 nextKey = useRef(0);
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
const isNew = draft.id == null;
/** 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: [] });
setRows(toRows(c.blocks ?? []));
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 }))); })
.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]);
const edit = <T,>(fn: (v: T) => void) => (v: T) => { setDirty(true); fn(v); };
const patch = edit((next: Partial<CmsPageDraft>) => setDraft((d) => ({ ...d, ...next })));
const setTitle = edit((title: string) => setDraft((d) => withTitle(d, title)));
/** A super admin's new page changes company: FORM blocks lose their event, which belongs to the old one. */
const changeCompany = (companyId: number) => {
patch({ companyId });
setRows((rs) => rs.map((r) => (r.block.type === "FORM" ? { ...r, block: { ...r.block, eventUuid: null } } : r)));
};
const updateBlock = (key: number, update: (block: CmsBlock) => CmsBlock) => {
setDirty(true);
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
};
const moveBlock = (index: number, delta: -1 | 1) => {
setDirty(true);
setRows((rs) => {
const next = [...rs];
[next[index], next[index + delta]] = [next[index + delta], next[index]];
return next;
});
};
const removeBlock = (key: number) => {
setDirty(true);
setRows((rs) => rs.filter((r) => r.key !== key));
setPending(({ [key]: _dropped, ...rest }) => rest);
};
const addBlock = (type: BlockType) => {
setDirty(true);
setRows((rs) => [...rs, { key: ++nextKey.current, block: emptyBlock(type) }]);
};
const chooseImage = (key: number, file: File) => {
setDirty(true);
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);
}
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);
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);
}
}
/** 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,
patch, setTitle, changeCompany, updateBlock, moveBlock, removeBlock, addBlock, chooseImage, blockErrors,
save, publishChanges, discardChanges, remove,
};
}