feat(pages): selection, section actions, undo and refusal mapping in the page draft
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
af1bab4afa
commit
d31661fd3e
3 files changed
+280
-22
No files matched your search
@@ -0,0 +1,136 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getPage: vi.fn(), savePage: vi.fn(), listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage, savePage: mocks.savePage }));
|
||||
vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import { moveItem, usePageDraft } from "./usePageDraft";
|
||||
|
||||
// add-page-visual-editor: the on-page editor's selection, section actions, undo and refusal mapping.
|
||||
const stored = {
|
||||
id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "DRAFT" as const,
|
||||
company: { code: "INS", name: "INS Sdn Bhd", logoImageId: 4, accentColor: null },
|
||||
blocks: [
|
||||
{ type: "HERO" as const, heading: "Hi" },
|
||||
{ type: "FAQ" as const, items: [{ question: "Q", answer: "A" }] },
|
||||
{ type: "HTML" as const, html: "<p>x</p>" },
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
memoryRouter.reset("/pages/5");
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
|
||||
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: () => "INS" });
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.getPage.mockResolvedValue(stored);
|
||||
mocks.savePage.mockImplementation(async (id: number, body: object) => ({ ...stored, ...body, id }));
|
||||
});
|
||||
|
||||
async function loaded() {
|
||||
const hook = renderHook(() => usePageDraft({ pageId: 5 }));
|
||||
await waitFor(() => expect(hook.result.current.loading).toBe(false));
|
||||
return hook;
|
||||
}
|
||||
const types = (r: { current: ReturnType<typeof usePageDraft> }) => r.current.rows.map((row) => row.block.type);
|
||||
|
||||
describe("moveItem", () => {
|
||||
it("moves one item to a new place, keeping the others in order", () => {
|
||||
expect(moveItem(["a", "b", "c", "d"], 0, 2)).toEqual(["b", "c", "a", "d"]);
|
||||
expect(moveItem(["a", "b", "c", "d"], 3, 1)).toEqual(["a", "d", "b", "c"]);
|
||||
expect(moveItem(["a", "b"], 1, 1)).toEqual(["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("usePageDraft for the on-page editor", () => {
|
||||
it("keeps the company's branding from the loaded page", async () => {
|
||||
const { result } = await loaded();
|
||||
expect(result.current.branding).toEqual(stored.company);
|
||||
});
|
||||
|
||||
it("duplicates a section below itself and selects the copy", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.duplicateBlock(1));
|
||||
expect(types(result)).toEqual(["HERO", "FAQ", "FAQ", "HTML"]);
|
||||
expect(result.current.rows[2].block).toEqual(result.current.rows[1].block);
|
||||
expect(result.current.rows[2].key).not.toBe(result.current.rows[1].key);
|
||||
expect(result.current.selected).toBe(2);
|
||||
});
|
||||
|
||||
it("adds a section between two and selects it", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.insertBlock(1, "STEPS"));
|
||||
expect(types(result)).toEqual(["HERO", "STEPS", "FAQ", "HTML"]);
|
||||
expect(result.current.selected).toBe(1);
|
||||
});
|
||||
|
||||
it("drags a section to a new place, and the selection follows it", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.select(0));
|
||||
act(() => result.current.moveBlockTo(0, 2));
|
||||
expect(types(result)).toEqual(["FAQ", "HTML", "HERO"]);
|
||||
expect(result.current.selected).toBe(2);
|
||||
});
|
||||
|
||||
it("undoes typing in one field as one step, redoes it, and keeps history across a save", async () => {
|
||||
const { result } = await loaded();
|
||||
const key = result.current.rows[0].key;
|
||||
act(() => result.current.text(key, "heading", "Ho"));
|
||||
act(() => result.current.text(key, "heading", "Hot"));
|
||||
act(() => result.current.text(key, "heading", "Hotel week"));
|
||||
await act(async () => { await result.current.save(); });
|
||||
expect(result.current.canUndo).toBe(true);
|
||||
act(() => result.current.undo());
|
||||
expect(result.current.rows[0].block.heading).toBe("Hi");
|
||||
expect(result.current.canUndo).toBe(false);
|
||||
act(() => result.current.redo());
|
||||
expect(result.current.rows[0].block.heading).toBe("Hotel week");
|
||||
});
|
||||
|
||||
it("brings a deleted section back in its place with its content", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.removeBlock(result.current.rows[1].key));
|
||||
expect(types(result)).toEqual(["HERO", "HTML"]);
|
||||
act(() => result.current.undo());
|
||||
expect(types(result)).toEqual(["HERO", "FAQ", "HTML"]);
|
||||
expect(result.current.rows[1].block.items).toEqual([{ question: "Q", answer: "A" }]);
|
||||
});
|
||||
|
||||
it("keeps at most 50 steps", async () => {
|
||||
const { result } = await loaded();
|
||||
for (let i = 0; i < 55; i++) act(() => result.current.insertBlock(0, "CTA"));
|
||||
let undone = 0;
|
||||
while (result.current.canUndo) { act(() => result.current.undo()); undone++; }
|
||||
expect(undone).toBe(50);
|
||||
});
|
||||
|
||||
it("marks a Custom HTML block stale once its HTML or place differs from the saved page, until the next save", async () => {
|
||||
const { result } = await loaded();
|
||||
expect(result.current.stale(2)).toBe(false);
|
||||
act(() => result.current.updateBlock(result.current.rows[2].key, (b) => ({ ...b, html: "<p>y</p>" })));
|
||||
expect(result.current.stale(2)).toBe(true);
|
||||
const version = result.current.frameVersion;
|
||||
await act(async () => { await result.current.save(); });
|
||||
expect(result.current.stale(2)).toBe(false);
|
||||
expect(result.current.frameVersion).toBe(version + 1);
|
||||
act(() => result.current.moveBlockTo(2, 0));
|
||||
expect(result.current.stale(0)).toBe(true);
|
||||
});
|
||||
|
||||
it("selects the block a refusal names, and clears the selection for a page field", async () => {
|
||||
const { result } = await loaded();
|
||||
mocks.savePage.mockRejectedValueOnce(new ApiError("x", 422, { code: "PagesEventRequired", details: { field: "blocks[1].eventUuid" } }));
|
||||
await act(async () => { await result.current.save(); });
|
||||
expect(result.current.selected).toBe(1);
|
||||
expect(result.current.revealed).toEqual({ index: 1, n: 1 });
|
||||
mocks.savePage.mockRejectedValueOnce(new ApiError("x", 422, { code: "PagesSlugTaken", details: { field: "slug" } }));
|
||||
await act(async () => { await result.current.save(); });
|
||||
expect(result.current.selected).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ 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";
|
||||
@@ -29,6 +30,19 @@ export function readDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
/** 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). */
|
||||
@@ -40,7 +54,7 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
|
||||
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 }>>({});
|
||||
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);
|
||||
@@ -56,15 +70,34 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
|
||||
// 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: [] });
|
||||
setRows(toRows(c.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);
|
||||
@@ -113,37 +146,113 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
|
||||
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)));
|
||||
/**
|
||||
* 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 lose their event, which belongs to the old one. */
|
||||
const changeCompany = (companyId: number) => {
|
||||
patch({ companyId });
|
||||
step(null);
|
||||
setDraft((d) => ({ ...d, 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);
|
||||
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);
|
||||
};
|
||||
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;
|
||||
});
|
||||
/** 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 }));
|
||||
};
|
||||
const moveBlockTo = (from: number, to: number) => {
|
||||
if (from === to) return;
|
||||
step(null);
|
||||
setRows((rs) => moveItem(rs, from, to));
|
||||
setSelected((s) => (s === from ? to : s));
|
||||
};
|
||||
const moveBlock = (index: number, delta: -1 | 1) => moveBlockTo(index, index + delta);
|
||||
const removeBlock = (key: number) => {
|
||||
setDirty(true);
|
||||
step(null);
|
||||
setRows((rs) => rs.filter((r) => r.key !== key));
|
||||
setPending(({ [key]: _dropped, ...rest }) => rest);
|
||||
setSelected(null);
|
||||
};
|
||||
const addBlock = (type: BlockType) => {
|
||||
setDirty(true);
|
||||
setRows((rs) => [...rs, { key: ++nextKey.current, block: emptyBlock(type) }]);
|
||||
/** 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);
|
||||
};
|
||||
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);
|
||||
};
|
||||
/** 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) => {
|
||||
setDirty(true);
|
||||
step(null);
|
||||
setPending((p) => ({ ...p, [key]: { file } }));
|
||||
readDataUrl(file)
|
||||
.then((preview) => setPending((p) => (p[key]?.file === file ? { ...p, [key]: { file, preview } } : p)))
|
||||
@@ -156,6 +265,13 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
|
||||
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);
|
||||
setRevealed((r) => ({ index, n: (r?.n ?? 0) + 1 }));
|
||||
} else if (field) setSelected(null);
|
||||
}
|
||||
|
||||
async function save(): Promise<boolean> {
|
||||
@@ -182,6 +298,7 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
|
||||
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;
|
||||
@@ -251,8 +368,11 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
|
||||
|
||||
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,
|
||||
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, blockErrors,
|
||||
save, publishChanges, discardChanges, remove,
|
||||
};
|
||||
}
|
||||
@@ -76,6 +76,8 @@ export interface CmsPage {
|
||||
draft?: PageContent | null;
|
||||
/** List rows: the page has unpublished changes. */
|
||||
hasDraft?: boolean;
|
||||
/** The page company's branding, on a single page read (the editor's canvas and preview render with it). */
|
||||
company?: { code: string; name: string; logoImageId?: number | null; accentColor?: string | null };
|
||||
}
|
||||
|
||||
/** What a draft holds; status and company stay on the page. */
|
||||
|
||||
Reference in new issue
Block a user