// --------------------------------------------------------------------------- // customer-grid / CatalogView.tsx // Wave-18 owner item 4 (contract C6-CATALOG) — the CATALOG view. // // A view holds several catalogs; a catalog is an ordered list of pages; a // section page names product CODES and joins them to the live pool at paint // time. Three columns: the rail (catalogs, then that catalog's pages), the // stage (the pages themselves, at true paper size, scaled to fit), and the // inspector (everything about the selected page, plus the catalog's brand, // paper and column bindings). // // FIDELITY. The default templates reproduce `Royal Collection 2027.pdf`, which // was rendered and read before this file was written: // · section header — letterspaced caps, navy, light weight, top-left // · product renders on WHITE (the C2-ASSET web derivative is alpha-preserving // PNG precisely so this works) // · description in caps, centred, two lines // · a full-width navy PILL carrying the pack line // · SKU in terracotta bold on the left, colour name on the right // · a full-bleed lifestyle strip under the grid // · crown mark bottom-left, folio bottom-right // · gallery pages full-bleed with a letterspaced caps title // // TYPE. Catalog pages use a display SERIF for titles (`--cat-serif`, a system // Didone/old-style stack — Didot, Bodoni, Playfair, Cormorant, Georgia). That is // deliberate and it is the ONLY place it appears: app chrome stays Inter, per // the owner constant. Listing text is Inter with wide tracking, which is what // the reference's geometric sans reads as at listing size. NO EMOJIS anywhere — // every mark here is a drawn path. // --------------------------------------------------------------------------- import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import type { CSSProperties } from "react"; import { createPortal } from "react-dom"; import { useEscapeClose } from "../ui/useEscapeClose"; import { LogoLoader } from "../ui/LogoLoader"; import { ConfirmDialog } from "../ui/ConfirmDialog"; import { AnchoredOverlay } from "./OverlaySurface"; import { GridPager } from "./GridPager"; import { useCatalogPlacements } from "./catalogPlacements"; import { catalogWriteQueue, createCatalog, deleteCatalog, duplicateCatalog, getCatalog, listCatalogs, patchCatalog, } from "./catalogApi"; import type { CatalogRecord, CatalogRecordPage } from "./catalogApi"; import { catalogKindLabel, catalogPageBindings, catalogTemplateLayout, fetchCatalogTemplates, normalizeCatalogKind, } from "./catalogKinds"; import type { CatalogKindTemplates, CatalogTemplate } from "./catalogKinds"; import { foldNavOnWorkSurface } from "./navFold"; import { CATALOG_COLS, CATALOG_NAME_MAX, CATALOG_ORIENTATIONS, CATALOG_PAGE_KINDS, CATALOG_PAPERS, MAX_CATALOGS, MAX_CATALOG_PAGES, MAX_CATALOG_CODES, } from "./types"; import type { CatalogOrientation, CatalogPage, CatalogPageKind, CatalogPaper, CatalogQuality, CatalogSpec, Field, Row, } from "./types"; import { CATALOG_CODE_FIELD, DEFAULT_BRAND, EDITORIAL_PREFIX, PAGE_KIND_LABELS, PAPER_LABELS, addCodes, assetUrl, autoBind, catalogBoundKeys, codesUsed, editorialSlug, fetchAssetCodes, fetchEditorialSlugs, newCatalog, newPage, newPageId, pageBox, resolveItems, rowImageRef, sectionLayout, slugFromFilename, uploadEditorial, } from "./catalogData"; import type { CatalogItem } from "./catalogData"; // Wave-19 R7 — the record-image namespace, so the gap report can say "I do not know" about an // upload rather than marking every one of them missing. import { AMAZON_IMAGE_PREFIX, RECORD_IMAGE_PREFIX } from "./types"; import { applyPrintCss, awaitImages, printOnce } from "./catalogPrint"; import { formatDisplay } from "./display"; import "./catalog.css"; import "../styles/sdlc76/catalog-library.css"; import "../styles/sdlc76/catalog-editor.css"; /** * ⭐⭐ W37 CONTRACT C3 — THE PER-VIEW CATALOG SPEC, client side. Mirrors * `aios_grid._clean_catalog_spec` key for key. * * ⛔⛔ AN ABSENT COORDINATE IS NOT ZERO, AND THAT ONE SENTENCE IS THE WHOLE MIGRATION. * Every catalog item authored before this wave has no `x`/`y`. `0` is the top-left corner and is a * real, storable position; ABSENT means "wherever the flow puts you", which is exactly where the * item is today. Read the two as the same thing and every pre-existing item piles up at the origin * the first time somebody opens an old catalog: a catalog that silently loses its layout, which R6 * names as a FAIL rather than a migration. So every coordinate is `number | undefined` and every * read of one uses `??`, never `||` and never a truthiness test. * ⚠ `w`/`h` carry the OPPOSITE asymmetry, matching the host: a zero WIDTH is an invisible item, so * absent means "the renderer's default size" and zero is refused before it ever gets here. * * ⭐ THE UNIT IS PERCENT OF THE PAGE, 0..100. The host deliberately does not care ("D owns what the * numbers MEAN"), and percent is the only choice that survives the designer's zoom-to-fit scale AND * the print tree's true-paper-size rendering without being recomputed for either. */ export interface CatalogViewItem { code: string; x?: number; y?: number; w?: number; h?: number; } export interface CatalogViewSection { id: string; items: CatalogViewItem[]; } export interface CatalogViewPage { id: string; order?: number; sections: CatalogViewSection[]; } export interface CatalogViewSpec { imageField?: string; titleField?: string; pages?: CatalogViewPage[]; } /** The placed items of one page, by code. ⛔ Returns an EMPTY map for a page with no stored * layout, which is every page of every catalog authored before this wave, and an empty map means * "everything flows" rather than "everything at the origin". */ export function placedItems( spec: CatalogViewSpec | undefined, pageId: string ): Map { const out = new Map(); const page = spec?.pages?.find((p) => p.id === pageId); for (const sec of page?.sections ?? []) { for (const it of sec.items ?? []) { if (it && typeof it.code === "string" && it.code) out.set(it.code, it); } } return out; } /** True only when BOTH coordinates are present. ⚠ `!= null` and not truthiness: `x: 0, y: 0` is the * top-left corner, a position somebody deliberately chose, and a truthy test drops it back into * the flow the moment they drag an item to the corner. */ export function isPlaced(it: CatalogViewItem | undefined): boolean { return !!it && it.x != null && it.y != null; } /** The registry's Catalog field bindings also supply the embedded Sheet projection. */ export interface CatalogApplicationDefinition { id: string; name: string; templateKind: "catalog"; sourceDatabase: string; fieldMap: { key: string; title: string; image?: string; sku?: string; price?: string; category?: string; description?: string }; } export interface CatalogApplicationItem { pid: number; key: string; title: string; image: string; sku?: string; price?: string; category?: string; description?: string; } function applicationImageUrl(value: string, quality: CatalogQuality = "web"): string { if (/^https?:\/\//i.test(value) || /^data:image\/(png|jpeg|webp|gif);base64,/i.test(value)) return value; return assetUrl(value, quality); } /** Pure role projection shared by the renderer and its negative-control gate. */ export function catalogApplicationItems( rows: Row[], fieldMap: CatalogApplicationDefinition["fieldMap"], fields?: ReadonlyMap | Field, ): CatalogApplicationItem[] { const items: CatalogApplicationItem[] = []; // The price reads through the grid formatter, so a currency field shows its symbol and cents. const priceField = fields && "get" in fields ? (fieldMap.price ? fields.get(fieldMap.price) : undefined) : fields; for (const row of rows) { const key = String(row[fieldMap.key] ?? "").trim(); if (!key) continue; const title = String(row[fieldMap.title] ?? "").trim() || key; const image = fieldMap.image ? String(row[fieldMap.image] ?? "").trim() : ""; const mapped = (role: "sku" | "price" | "category" | "description") => { const field = fieldMap[role]; if (!field || row[field] == null) return undefined; return role === "price" && priceField?.key === field ? formatDisplay(priceField, row[field]) : String(row[field]); }; const price = mapped("price"); items.push({ pid: row.pid, key, title, image, sku: mapped("sku"), price, category: mapped("category"), description: mapped("description") }); } return items; } export interface CatalogApplicationEditor { catalogs: CatalogSpec[]; catalogSpec: CatalogViewSpec; canEdit: boolean; fields: Field[]; fieldByKey: Map; poolRows: Row[]; filteredCodes: string[]; identityField: Field; onSave: (catalogs: CatalogSpec[], catalogSpec: CatalogViewSpec) => Promise; } /** The library needs only the permission while rows load. The editor waits for the full editor data. */ export type CatalogPendingEditor = Pick; /** Rows the App has read so far, while its record walk is still running. */ export interface CatalogRowsPending { read: number; } const NO_ROWS: Row[] = []; /** Apps read C1 records. Sheets retain their read-only row projection. */ export const CatalogApplicationView = memo(function CatalogApplicationView({ definition, rows, onOpen, editor, rowsPending, }: { definition: CatalogApplicationDefinition; rows: Row[]; onOpen: (pid: number, row?: Row) => void; editor?: CatalogApplicationEditor | CatalogPendingEditor; rowsPending?: CatalogRowsPending; }) { const items = useMemo( () => catalogApplicationItems(rows, definition.fieldMap), [rows, definition.fieldMap], ); if (editor) { return ( ); } return (

Catalog app

{definition.name}

{items.length.toLocaleString()} {items.length === 1 ? "record" : "records"}
{items.length ? (
{items.map((item) => ( ))}
) : (

No records have a value in the mapped key field.

)}
); }); type CatalogAction = { kind: "create" | "rename" | "duplicate" | "delete"; catalog?: CatalogRecord }; function catalogError(error: unknown): string { return error instanceof Error ? error.message : "The catalog could not be saved. Try again."; } function editedDate(value: string): string { const date = new Date(value); return Number.isNaN(date.getTime()) ? "Unknown date" : date.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric", }); } function catalogHashId(next?: string | null): string | null { if (typeof window === "undefined") return null; const [path, query = ""] = window.location.hash.split("?"); const params = new URLSearchParams(query); if (next !== undefined) { if (next) params.set("catalog", next); else params.delete("catalog"); window.history.replaceState(null, "", `${path}?${params}`); } return params.get("catalog"); } /** Child content for the shared AppFrame. Only the editor owns Back to library. */ export function CatalogLibrary({ definition, fieldByKey, priceField, canEdit, rows, rowsPending, onOpen }: { definition: CatalogApplicationDefinition; fieldByKey?: ReadonlyMap; canEdit: boolean; rows: Row[]; priceField?: Field; rowsPending?: CatalogRowsPending; onOpen: (pid: number, row?: Row) => void; }) { const [catalogs, setCatalogs] = useState([]); const [pending, setPending] = useState(true); const [error, setError] = useState(""); const [attempt, setAttempt] = useState(0); const [offset, setOffset] = useState(0); const [size, setSize] = useState(10); const [openId, setOpenId] = useState(() => catalogHashId()); const [menu, setMenu] = useState<{ catalog: CatalogRecord; anchor: HTMLButtonElement } | null>(null); const [action, setAction] = useState(null); const [name, setName] = useState(""); const [busy, setBusy] = useState(false); const [actionError, setActionError] = useState(""); const active = useRef(false); const writing = useRef(false); useEffect(() => { active.current = true; return () => { active.current = false; }; }, []); useEffect(() => { if (typeof window === "undefined") return; const changed = () => setOpenId(catalogHashId()); window.addEventListener("hashchange", changed); return () => window.removeEventListener("hashchange", changed); }, []); useEffect(() => { const controller = new AbortController(); setPending(true); setError(""); void listCatalogs(definition.id, controller.signal).then((records) => { if (controller.signal.aborted) return; setCatalogs(records); setPending(false); }).catch((failure: unknown) => { if (controller.signal.aborted) return; setError(catalogError(failure)); setPending(false); }); return () => controller.abort(); }, [definition.id, attempt]); const pageOffset = Math.min(offset, Math.max(0, Math.ceil(catalogs.length / size) - 1) * size); const begin = (next: CatalogAction) => { setMenu(null); setName(next.kind === "rename" ? next.catalog?.name ?? "" : next.kind === "duplicate" ? `${next.catalog?.name ?? "Catalog"} copy` : "Untitled catalog"); setActionError(""); setAction(next); }; const replace = (saved: CatalogRecord) => setCatalogs((current) => current.map((catalog) => catalog.id === saved.id ? saved : catalog)); const perform = async () => { if (!canEdit || !action || writing.current) return; if ((action.kind === "create" || action.kind === "rename") && !name.trim()) { setActionError("Enter a catalog name."); return; } writing.current = true; setBusy(true); setActionError(""); try { if (action.kind === "delete" && action.catalog) { await deleteCatalog(action.catalog.id); if (active.current) setCatalogs((current) => current.filter((catalog) => catalog.id !== action.catalog!.id)); } else { const saved = action.kind === "create" ? await createCatalog(definition.id, name.trim()) : action.kind === "duplicate" && action.catalog ? await duplicateCatalog(definition.id, action.catalog.id) : action.catalog ? await patchCatalog(definition.id, action.catalog.id, { name: name.trim() }) : null; if (active.current && saved) { if (action.kind === "rename") replace(saved); else { setCatalogs((current) => [saved, ...current.filter((catalog) => catalog.id !== saved.id)]); setOffset(0); } } } if (active.current) setAction(null); } catch (failure: unknown) { if (active.current) setActionError(catalogError(failure)); } finally { writing.current = false; if (active.current) setBusy(false); } }; if (openId) return { setOpenId(null); catalogHashId(null); }} onSaved={replace} />; const actionTitle = action?.kind === "create" ? "New catalog" : action?.kind === "rename" ? "Rename catalog" : action?.kind === "duplicate" ? "Duplicate catalog" : "Delete catalog"; return

Catalogs

{canEdit && (pending || error || catalogs.length > 0) && }
{error &&
{error}
}
{pending ?
Loading catalogs
: !catalogs.length && !error ?

No catalogs yet

{canEdit && }
: catalogs.slice(pageOffset, pageOffset + size).map((catalog) =>
{canEdit && }
)}
{catalogs.length > 10 && { setMenu(null); setOffset(next); }} onSize={(next) => { setMenu(null); setSize(next); setOffset(0); }} />} {menu && setMenu(null)} onKeyDown={(event) => { if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return; const buttons = Array.from(event.currentTarget.querySelectorAll("button")); const current = buttons.indexOf(document.activeElement as HTMLButtonElement); const next = event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : (current + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length; event.preventDefault(); buttons[next]?.focus(); }}> {(["rename", "duplicate", "delete"] as const).map((kind) => )} } setAction(null)} onConfirm={() => { void perform(); }} body={<> {action?.kind === "delete" ?

Delete “{action.catalog?.name}” and its pages?

: action?.kind === "duplicate" ?

Duplicate “{action.catalog?.name}” with all its pages?

: } {actionError &&

{actionError}

} } />
; } function CatalogRecordOpener({ appId, id, rowsPending, ...props }: { appId: string; id: string; definition: CatalogApplicationDefinition; canEdit: boolean; rows: Row[]; fieldByKey?: ReadonlyMap; priceField?: Field; rowsPending?: CatalogRowsPending; onOpen: (pid: number, row?: Row) => void; onBack: () => void; onSaved: (catalog: CatalogRecord) => void; }) { const [record, setRecord] = useState(null); const [error, setError] = useState(""); const [attempt, setAttempt] = useState(0); useEffect(() => { const controller = new AbortController(); setRecord(null); setError(""); void getCatalog(appId, id, controller.signal).then((catalog) => { if (!controller.signal.aborted) setRecord(catalog); }).catch((failure: unknown) => { if (!controller.signal.aborted) setError(catalogError(failure)); }); return () => controller.abort(); }, [appId, id, attempt]); // The editor needs the first page's field map before resolving saved placements. if (record && !rowsPending) return ; return
{error ?
{error}
: }
; } /** Keep the C1 draft intact until its serialized save succeeds. */ export function CatalogRecordEditor({ record, definition, fieldByKey, priceField, canEdit, rows, onOpen, onBack, onSaved }: { record: CatalogRecord; definition: CatalogApplicationDefinition; canEdit: boolean; rows: Row[]; fieldByKey?: ReadonlyMap; priceField?: Field; onOpen: (pid: number, row?: Row) => void; onBack: () => void; onSaved: (catalog: CatalogRecord) => void; }) { const [draft, setDraft] = useState(record); const savedCodes = useMemo(() => draft.pages.flatMap((candidate) => { const bindings = catalogPageBindings(candidate); return [...catalogBoundKeys(bindings), ...(typeof bindings.imageCode === "string" && bindings.imageCode ? [bindings.imageCode] : [])]; }), [draft.pages]); const placements = useCatalogPlacements(definition.sourceDatabase, definition.fieldMap.key, savedCodes); const productRows = useMemo(() => [...new Map([...rows, ...placements.rows].map((row) => [row.pid, row])).values()], [rows, placements.rows]); const [pageId, setPageId] = useState(record.pages[0]?.id ?? null); const [dirty, setDirty] = useState(false); const [saving, setSaving] = useState(false); const [saveError, setSaveError] = useState(""); const [discard, setDiscard] = useState(false); const [registry, setRegistry] = useState([]); const [registryError, setRegistryError] = useState(""); const [registryAttempt, setRegistryAttempt] = useState(0); const [templatesOpen, setTemplatesOpen] = useState(true); const [addOpen, setAddOpen] = useState(false); const [printing, setPrinting] = useState(false); const [printError, setPrintError] = useState(""); const printRoot = useRef(null); const canvasRoot = useRef(null); const [scale, setScale] = useState(0.56); const active = useRef(false); const revision = useRef(0); const inFlight = useRef(false); const save = useMemo(() => catalogWriteQueue(record.appId, record.id), [record.appId, record.id]); useEffect(() => { active.current = true; return () => { active.current = false; }; }, []); useEffect(() => { const controller = new AbortController(); setRegistryError(""); void fetchCatalogTemplates(controller.signal).then((kinds) => { if (!controller.signal.aborted) setRegistry(kinds); }).catch((failure: unknown) => { if (!controller.signal.aborted) setRegistryError(catalogError(failure)); }); return () => controller.abort(); }, [registryAttempt]); useLayoutEffect(() => { const node = canvasRoot.current; if (!node || typeof ResizeObserver === "undefined") return; const resize = () => setScale(Math.min(1, Math.max(0.1, Math.min((node.clientWidth - 48) / 816, (node.clientHeight - 48) / 1056)))); resize(); const observer = new ResizeObserver(resize); observer.observe(node); return () => observer.disconnect(); }, [templatesOpen]); useEffect(() => { if (!printing) return; let cancelled = false; let remove: (() => void) | undefined; void (async () => { try { await awaitImages(printRoot.current); if (cancelled) return; remove = applyPrintCss({ paper: "letter", orientation: "portrait" }); await printOnce(); } catch (failure: unknown) { if (!cancelled) setPrintError(catalogError(failure)); } finally { remove?.(); if (!cancelled) setPrinting(false); } })(); return () => { cancelled = true; remove?.(); }; }, [printing]); const page = draft.pages.find((candidate) => candidate.id === pageId); const items = catalogApplicationItems(productRows, definition.fieldMap, fieldByKey ?? priceField); const kindTemplates = registry.find((entry) => entry.kind === normalizeCatalogKind(page?.kind ?? "")); const template = kindTemplates?.templates.find((entry) => entry.id === page?.template); const changePages = (pages: CatalogRecordPage[]) => { if (!canEdit) return; revision.current += 1; setDraft((current) => ({ ...current, pages })); setDirty(true); }; const changePage = (bindings: CatalogRecordPage["bindings"]) => { if (!canEdit || !page) return; changePages(draft.pages.map((candidate) => candidate.id === page.id ? { ...candidate, bindings: { ...candidate.bindings, ...bindings } } : candidate)); }; const saveDraft = async () => { if (!canEdit || !dirty || inFlight.current) return; const mine = revision.current; inFlight.current = true; setSaving(true); setSaveError(""); try { const saved = await save({ pages: draft.pages }); if (!active.current) return; onSaved(saved); if (revision.current === mine) { setDraft(saved); setDirty(false); } } catch (failure: unknown) { if (active.current) setSaveError(catalogError(failure)); } finally { inFlight.current = false; if (active.current) setSaving(false); } }; const bindings = page ? catalogPageBindings(page) : {}; const title = typeof bindings.title === "string" ? bindings.title : ""; const body = typeof bindings.body === "string" ? bindings.body : ""; const unavailable = draft.pages.some((candidate) => !registry.some((entry) => entry.kind === normalizeCatalogKind(candidate.kind) && entry.templates.some((entry) => entry.id === candidate.template))); const movePage = (direction: -1 | 1) => { if (!page) return; const index = draft.pages.indexOf(page), next = index + direction; if (next < 0 || next >= draft.pages.length) return; const pages = [...draft.pages]; [pages[index], pages[next]] = [pages[next], pages[index]]; changePages(pages); }; const renderPage = (candidate: CatalogRecordPage, previewTemplate?: CatalogTemplate, quality: CatalogQuality = "web", interactive = false) => onOpen(pid, productRows.find((row) => row.pid === pid)) : undefined} />; return

{draft.name}

{canEdit && }
{saveError &&
{saveError}
} {printError &&
{printError}
} {registryError &&
{registryError}
} {placements.loading &&

Loading saved products

} {placements.error &&
{placements.error}
} {!registryError && registry.length > 0 && unavailable &&

A page template is unavailable. Open Templates and choose a replacement before printing.

}
{templatesOpen &&