Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/customer-grid/CatalogView.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 113 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/customer-grid/CatalogView.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/customer-grid/CatalogView.tsx
-
curl -L -o CatalogView.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/customer-grid/CatalogView.tsx
113 kB
// ---------------------------------------------------------------------------
// 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<string, CatalogViewItem> {
const out = new Map<string, CatalogViewItem>();
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<string, Field> | 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<string, Field>;
poolRows: Row[];
filteredCodes: string[];
identityField: Field;
onSave: (catalogs: CatalogSpec[], catalogSpec: CatalogViewSpec) => Promise<void>;
}
/** The library needs only the permission while rows load. The editor waits for the full editor data. */
export type CatalogPendingEditor = Pick<CatalogApplicationEditor, "canEdit">;
/** 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 (
<CatalogLibrary
key={definition.id}
definition={definition}
fieldByKey={"fieldByKey" in editor ? editor.fieldByKey : undefined}
canEdit={editor.canEdit}
priceField={"fieldByKey" in editor ? editor.fieldByKey.get(definition.fieldMap.price ?? "") : undefined}
rows={!rowsPending && "poolRows" in editor ? editor.poolRows : NO_ROWS}
rowsPending={rowsPending}
onOpen={onOpen}
/>
);
}
return (
<section className="cg-app-catalog" aria-label={`${definition.name} catalog`}>
<header className="cg-app-catalog-head">
<div>
<p className="cg-app-catalog-kicker">Catalog app</p>
<h2>{definition.name}</h2>
</div>
<span className="cg-app-catalog-count">
{items.length.toLocaleString()} {items.length === 1 ? "record" : "records"}
</span>
</header>
{items.length ? (
<div className="cg-app-catalog-grid">
{items.map((item) => (
<button
key={item.pid}
type="button"
className="cg-app-catalog-card"
onClick={() => onOpen(item.pid)}
aria-label={`Open ${item.title}`}
>
<span className="cg-app-catalog-image">
{item.image ? (
<img src={applicationImageUrl(item.image)} alt="" loading="lazy" />
) : (
<span>No image</span>
)}
</span>
<span className="cg-app-catalog-copy">
<strong>{item.title}</strong>
<span>{item.key}</span>
</span>
</button>
))}
</div>
) : (
<p className="cg-app-catalog-empty">No records have a value in the mapped key field.</p>
)}
</section>
);
});
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<string, Field>;
canEdit: boolean;
rows: Row[];
priceField?: Field;
rowsPending?: CatalogRowsPending;
onOpen: (pid: number, row?: Row) => void;
}) {
const [catalogs, setCatalogs] = useState<CatalogRecord[]>([]);
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<string | null>(() => catalogHashId());
const [menu, setMenu] = useState<{ catalog: CatalogRecord; anchor: HTMLButtonElement } | null>(null);
const [action, setAction] = useState<CatalogAction | null>(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 <CatalogRecordOpener key={openId} appId={definition.id} id={openId}
definition={definition} fieldByKey={fieldByKey} priceField={priceField} canEdit={canEdit} rows={rows} rowsPending={rowsPending}
onOpen={onOpen} onBack={() => { 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 <section className="cg-catalog-library" aria-label="Catalog library">
<div className="cg-catalog-library-head">
<h2>Catalogs</h2>
{canEdit && (pending || error || catalogs.length > 0) && <button type="button" className="cg-btn cg-btn--primary" disabled={pending || busy}
onClick={() => begin({ kind: "create" })}><IconPlus /> New catalog</button>}
</div>
{error && <div className="cg-catalog-library-error" role="alert"><span>{error}</span>
<button type="button" className="cg-btn" onClick={() => setAttempt((value) => value + 1)}>Retry</button></div>}
<div className="cg-catalog-library-grid" style={{ "--catalog-page-size": size } as CSSProperties}
aria-busy={pending || undefined}>
{pending ? <div className="cg-catalog-library-loading" role="status">Loading catalogs</div> :
!catalogs.length && !error ? <div className="cg-catalog-library-empty">
<h3>No catalogs yet</h3>
{canEdit && <button type="button" className="cg-btn cg-btn--primary"
onClick={() => begin({ kind: "create" })}><IconPlus /> New catalog</button>}
</div> : catalogs.slice(pageOffset, pageOffset + size).map((catalog) => <article
key={catalog.id} className="cg-catalog-library-card" data-catalog-id={catalog.id}>
<button type="button" className="cg-catalog-library-open" onClick={() => { setMenu(null); setOpenId(catalog.id); catalogHashId(catalog.id); }}
aria-label={`Open ${catalog.name}`}>
<span className="cg-catalog-library-cover">
{catalog.thumbnail ? <img src={catalog.thumbnail} alt="" loading="lazy" /> :
<svg viewBox="0 0 48 60" aria-hidden="true"><path d="M8 2h24l8 8v48H8zM32 2v10h8M16 26h16M16 34h16M16 42h10" /></svg>}
</span>
<span className="cg-catalog-library-copy"><strong>{catalog.name}</strong>
<span>{catalog.pages.length} {catalog.pages.length === 1 ? "page" : "pages"}</span>
<span>Edited <time dateTime={catalog.updatedAt}>{editedDate(catalog.updatedAt)}</time></span>
</span>
</button>
{canEdit && <button type="button" className="cg-catalog-library-more" aria-label={`More actions for ${catalog.name}`}
aria-haspopup="menu" aria-expanded={menu?.catalog.id === catalog.id} disabled={busy}
onClick={(event) => setMenu(menu?.catalog.id === catalog.id ? null : { catalog, anchor: event.currentTarget })}>
<svg width="20" height="20" viewBox="0 0 20 20" aria-hidden="true"><circle cx="4" cy="10" r="1.5" />
<circle cx="10" cy="10" r="1.5" /><circle cx="16" cy="10" r="1.5" /></svg>
</button>}
</article>)}
</div>
{catalogs.length > 10 && <GridPager offset={pageOffset} size={size} sizes={[10, 20]} total={catalogs.length}
pending={pending || busy} itemsLabel="Items" onPage={(next) => { setMenu(null); setOffset(next); }}
onSize={(next) => { setMenu(null); setSize(next); setOffset(0); }} />}
{menu && <AnchoredOverlay anchor={menu.anchor} className="cg-catalog-library-menu" placement="bottom-end"
role="menu" ariaLabel={`Actions for ${menu.catalog.name}`} onDismiss={() => setMenu(null)}
onKeyDown={(event) => {
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
const buttons = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>("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) => <button key={kind} type="button" role="menuitem"
className={kind === "delete" ? "is-destructive" : undefined}
onClick={() => begin({ kind, catalog: menu.catalog })}>{kind === "rename" ? "Rename" :
kind === "duplicate" ? "Duplicate" : "Delete"}</button>)}
</AnchoredOverlay>}
<ConfirmDialog open={action !== null} title={actionTitle} confirmLabel={action?.kind === "create" ? "Create" :
action?.kind === "rename" ? "Save" : action?.kind === "duplicate" ? "Duplicate" : "Delete"}
tone={action?.kind === "delete" ? "destructive" : "primary"} busy={busy}
onCancel={() => setAction(null)} onConfirm={() => { void perform(); }} body={<>
{action?.kind === "delete" ? <p>Delete “{action.catalog?.name}” and its pages?</p> :
action?.kind === "duplicate" ? <p>Duplicate “{action.catalog?.name}” with all its pages?</p> :
<label className="cg-catalog-library-name">Name<input aria-label="Catalog name" value={name}
maxLength={CATALOG_NAME_MAX} disabled={busy} onChange={(event) => setName(event.currentTarget.value)} /></label>}
{actionError && <p className="cg-catalog-library-error" role="alert">{actionError}</p>}
</>} />
</section>;
}
function CatalogRecordOpener({ appId, id, rowsPending, ...props }: {
appId: string; id: string; definition: CatalogApplicationDefinition; canEdit: boolean; rows: Row[];
fieldByKey?: ReadonlyMap<string, Field>; priceField?: Field; rowsPending?: CatalogRowsPending;
onOpen: (pid: number, row?: Row) => void; onBack: () => void; onSaved: (catalog: CatalogRecord) => void;
}) {
const [record, setRecord] = useState<CatalogRecord | null>(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 <CatalogRecordEditor key={record.id} record={record} {...props} />;
return <section className="cg-catalog-record" aria-label="Catalog editor">
<button type="button" className="cg-btn" onClick={props.onBack}>Back to library</button>
{error ? <div className="cg-catalog-library-error" role="alert">{error}
<button type="button" className="cg-btn" onClick={() => setAttempt((value) => value + 1)}>Retry</button></div> :
<LogoLoader className="cg-app-launch-state" />}
</section>;
}
/** 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<string, Field>;
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<CatalogKindTemplates[]>([]);
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<HTMLDivElement>(null);
const canvasRoot = useRef<HTMLDivElement>(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) =>
<CatalogRecordPageView page={candidate} pages={draft.pages} registry={registry} items={items}
templateOverride={previewTemplate} quality={quality}
onOpen={interactive ? (pid) => onOpen(pid, productRows.find((row) => row.pid === pid)) : undefined} />;
return <section className="cg-catalog-record cg-catalog-editor" aria-label="Catalog editor">
<div className="cg-catalog-record-head">
<button type="button" className="cg-btn" disabled={saving} onClick={() => dirty ? setDiscard(true) : onBack()}>
Back to library</button><h2>{draft.name}</h2>
<button type="button" className="cg-btn" aria-controls="catalog-template-panel" aria-expanded={templatesOpen}
onClick={() => setTemplatesOpen((open) => !open)}>Templates</button>
<button type="button" className="cg-btn" disabled={printing || !draft.pages.length || unavailable || !!registryError || placements.loading || !!placements.error}
onClick={() => { setPrintError(""); setPrinting(true); }}><IconPrint /> {printing ? "Preparing print" : "Print"}</button>
{canEdit && <button type="button" className="cg-btn cg-btn--primary" disabled={!dirty || saving}
onClick={() => { void saveDraft(); }}>Save</button>}
</div>
{saveError && <div className="cg-catalog-library-error" role="alert"><span>{saveError}</span>
<button type="button" className="cg-btn" disabled={saving} onClick={() => { void saveDraft(); }}>Retry</button></div>}
{printError && <div className="cg-catalog-library-error" role="alert"><span>{printError}</span>
<button type="button" className="cg-btn" disabled={printing || unavailable || !!registryError || placements.loading || !!placements.error}
onClick={() => { setPrintError(""); setPrinting(true); }}>Retry print</button></div>}
{registryError && <div className="cg-catalog-library-error" role="alert"><span>{registryError}</span>
<button type="button" className="cg-btn" onClick={() => setRegistryAttempt((value) => value + 1)}>Retry templates</button></div>}
{placements.loading && <p role="status">Loading saved products</p>}
{placements.error && <div className="cg-catalog-library-error" role="alert"><span>{placements.error}</span>
<button type="button" className="cg-btn" onClick={placements.retry}>Retry products</button></div>}
{!registryError && registry.length > 0 && unavailable && <p className="cg-catalog-template-warning" role="status">
A page template is unavailable. Open Templates and choose a replacement before printing.</p>}
<div className={`cg-catalog-workspace${templatesOpen ? " has-templates" : ""}`}>
{templatesOpen && <aside className="cg-catalog-template-panel" id="catalog-template-panel" aria-label="Page templates">
<div className="cg-catalog-panel-head"><h3>Templates</h3><span>{page ? catalogKindLabel(normalizeCatalogKind(page.kind)) : ""}</span></div>
{!registry.length && !registryError && <p role="status">Loading templates</p>}
{page && registry.length > 0 && !template && <p role="alert">Template unavailable. Choose a template to restore this page.</p>}
<div className="cg-catalog-template-list">
{page && kindTemplates?.templates.map((candidate) => <button type="button" key={candidate.id}
className="cg-catalog-template-card" data-template-id={candidate.id} aria-pressed={page.template === candidate.id}
disabled={!canEdit} onClick={() => changePages(draft.pages.map((entry) => entry.id === page.id ?
{ ...entry, template: candidate.id } : entry))}>
<span className="cg-catalog-mini" aria-hidden="true">{renderPage(page, candidate)}</span>
<span>{candidate.label}</span>
</button>)}
</div>
{page && canEdit && <div className="cg-catalog-page-fields">
<label>Title<input aria-label="Page title" value={title}
onChange={(event) => changePage({ title: event.currentTarget.value })} /></label>
<label>Text<textarea aria-label="Page text" value={body}
onChange={(event) => changePage({ body: event.currentTarget.value })} /></label>
<label>Products<select multiple aria-label="Page products" value={catalogBoundKeys(bindings)}
onChange={(event) => changePage({ products: Array.from(event.currentTarget.selectedOptions, (option) => option.value) })}>
{items.map((item) => <option key={item.key} value={item.key}>{item.title}</option>)}
</select></label>
</div>}
</aside>}
<div className="cg-catalog-canvas" ref={canvasRoot} aria-label="Page canvas">
{page ? <div className="cg-catalog-canvas-sheet" style={{ width: 816 * scale, height: 1056 * scale }}>
<div className="cg-catalog-canvas-scale" style={{ transform: `scale(${scale})` }}>{renderPage(page, undefined, "web", true)}</div>
</div> : <p className="cg-catalog-library-empty">No pages yet</p>}
</div>
</div>
<div className="cg-catalog-strip">
<nav className="cg-catalog-page-strip" aria-label="Catalog pages">
{draft.pages.map((candidate, index) => <button type="button" className="cg-catalog-page-thumb" key={candidate.id}
data-page-kind={normalizeCatalogKind(candidate.kind)} aria-current={candidate.id === pageId ? "page" : undefined}
onClick={() => setPageId(candidate.id)}>
<span className="cg-catalog-mini" aria-hidden="true">{renderPage(candidate)}</span>
<span>{index + 1}. {String(catalogPageBindings(candidate).title || catalogKindLabel(candidate.kind))}</span>
</button>)}
{canEdit && <div className="cg-catalog-add-wrap">
<button type="button" className="cg-btn cg-catalog-add" aria-expanded={addOpen} aria-controls="catalog-add-page"
disabled={!registry.length || !!registryError} onClick={() => setAddOpen((open) => !open)}><IconPlus /> Add page</button>
{addOpen && <div className="cg-catalog-add-menu" id="catalog-add-page" aria-label="Page kind">
{registry.map((entry) => <button type="button" className="cg-btn" key={entry.kind} onClick={() => {
const next: CatalogRecordPage = { id: newPageId(), kind: entry.kind, template: entry.templates[0].id,
bindings: { title: catalogKindLabel(entry.kind) } };
changePages([...draft.pages, next]); setPageId(next.id); setAddOpen(false);
}}>{catalogKindLabel(entry.kind)}</button>)}
</div>}
</div>}
</nav>
{page && canEdit && <div className="cg-catalog-page-actions">
<button type="button" className="cg-cat-icon-btn" aria-label="Move page up" disabled={draft.pages[0] === page}
onClick={() => movePage(-1)}><IconUp /></button>
<button type="button" className="cg-cat-icon-btn" aria-label="Move page down" disabled={draft.pages[draft.pages.length - 1] === page}
onClick={() => movePage(1)}><IconDown /></button>
<button type="button" className="cg-cat-icon-btn" aria-label="Delete page" onClick={() => {
const next = draft.pages.filter((entry) => entry.id !== page.id);
changePages(next); setPageId(next[Math.min(draft.pages.indexOf(page), next.length - 1)]?.id ?? null);
}}><IconTrash /></button>
</div>}
</div>
{printing && createPortal(<div className="cg-cat-print-portal cg-catalog-print" ref={printRoot}>
{draft.pages.map((candidate) => <CatalogRecordPageView key={candidate.id} page={candidate} pages={draft.pages}
registry={registry} items={items} quality="print" />)}
</div>, document.body)}
<ConfirmDialog open={discard} title="Discard changes" body="Your unsaved page changes will be lost."
confirmLabel="Discard" tone="destructive" onCancel={() => setDiscard(false)} onConfirm={onBack} />
</section>;
}
/** Canvas, previews and print use the same C1 page without rewriting its bindings. */
export function CatalogRecordPageView({ page, pages, registry, items, templateOverride, quality = "web", onOpen }: {
page: CatalogRecordPage; pages: CatalogRecordPage[]; registry: CatalogKindTemplates[];
items: CatalogApplicationItem[]; templateOverride?: CatalogTemplate; quality?: CatalogQuality; onOpen?: (pid: number) => void;
}) {
const kind = normalizeCatalogKind(page.kind);
const templates = registry.find((entry) => entry.kind === kind)?.templates ?? [];
const template = templateOverride ?? templates.find((entry) => entry.id === page.template);
const layout = catalogTemplateLayout(template, templates.findIndex((entry) => entry.id === template?.id));
const bindings = catalogPageBindings(page);
const bindingText = (name: string) => typeof bindings[name] === "string" ? bindings[name] as string : "";
const title = bindingText("title");
const body = bindingText("body") || bindingText("description");
const keys = catalogBoundKeys(bindings);
const products: (Omit<CatalogApplicationItem, "pid"> & { pid?: number })[] = keys.map((key) => items.find((item) => item.key === key || item.sku === key) ??
{ key, title: key, image: "", pid: undefined });
const hero = bindingText("image") || bindingText("imageCode") || products.find((item) => item.image)?.image;
const slotHas = (name: string) => layout.slots.includes(name);
const productCards = <div className="cg-catalog-products" data-slot="products">
{products.map((item, index) => <div className="cg-catalog-product" key={`${item.key}-${index}`}>
{onOpen && item.pid !== undefined ? <button type="button" className="cg-catalog-product-open"
aria-label={`Open ${item.title}`} onClick={() => onOpen(item.pid!)}>
<CatalogProductImage image={item.image} title={item.title} quality={quality} /><span>{item.title}</span>
</button> : <><CatalogProductImage image={item.image} title={item.title} quality={quality} /><span>{item.title}</span></>}
{"price" in item && item.price !== undefined && <span className="cg-catalog-product-price">{item.price}</span>}
{slotHas("sku") && "sku" in item && <span>{item.sku}</span>}
{slotHas("category") && "category" in item && <span>{item.category}</span>}
{slotHas("description") && "description" in item && <p>{item.description}</p>}
{item.pid === undefined && <span>Product unavailable</span>}
</div>)}
</div>;
const heading = <div className="cg-catalog-page-copy"><h3 data-slot="title">{title || catalogKindLabel(kind)}</h3>
{body && <p data-slot="body">{body}</p>}</div>;
let content;
switch (kind) {
case "cover":
case "closing":
content = <>{hero && <div className="cg-catalog-hero" data-slot="image"><CatalogProductImage image={hero} title={title} quality={quality} /></div>}{heading}</>;
break;
case "toc":
content = <>{heading}<ol className="cg-catalog-contents" data-slot="contents">
{pages.map((entry, index) => <li key={entry.id}><span>{String(catalogPageBindings(entry).title || catalogKindLabel(normalizeCatalogKind(entry.kind)))}</span>
<span>{index + 1}</span></li>)}
</ol>{products.length > 0 && productCards}</>;
break;
case "product":
case "grid":
content = <>{heading}{productCards}</>;
break;
case "section":
content = <>{heading}{products.length > 0 ? productCards : hero && <div className="cg-catalog-hero" data-slot="image">
<CatalogProductImage image={hero} title={title} quality={quality} /></div>}</>;
break;
default:
content = <p role="alert">Page kind unavailable. Reload the catalog or choose a supported page.</p>;
}
return <article className={`cg-cat-page cg-catalog-sheet cg-catalog-kind-${kind} cg-catalog-variant-${layout.variant}`}
data-page-id={page.id} data-page-kind={kind} data-template-id={template?.id ?? page.template}
data-template-slots={layout.slots.join(" ")} style={{ "--cat-w": "8.5in", "--cat-h": "11in",
"--catalog-columns": layout.columns, "--catalog-align": layout.align, "--catalog-image-fit": layout.fit } as CSSProperties}>
{content}<span className="cg-catalog-folio">{pages.findIndex((entry) => entry.id === page.id) + 1}</span>
</article>;
}
function CatalogProductImage({ image, title, quality }: { image: string; title: string; quality: CatalogQuality }) {
const [failed, setFailed] = useState(false);
useEffect(() => setFailed(false), [image, quality]);
return <span className="cg-catalog-product-image">{image && !failed ?
<img src={applicationImageUrl(image, quality)} alt={title} onError={() => setFailed(true)} /> :
<span>No product image</span>}</span>;
}
// ------------------------------------------------------------------- marks
const STROKE = {
stroke: "currentColor",
strokeWidth: 1.5,
strokeLinecap: "round" as const,
strokeLinejoin: "round" as const,
fill: "none",
};
function IconPlus() {
return (
<svg width="13" height="13" viewBox="0 0 16 16" aria-hidden>
<path d="M8 3.4v9.2M3.4 8h9.2" {...STROKE} />
</svg>
);
}
function IconTrash() {
return (
<svg width="13" height="13" viewBox="0 0 16 16" aria-hidden>
<path d="M3.4 4.6h9.2M6.4 4.6V3.2h3.2v1.4M4.8 4.6l.6 8h5.2l.6-8" {...STROKE} />
</svg>
);
}
function IconUp() {
return (
<svg width="13" height="13" viewBox="0 0 16 16" aria-hidden>
<path d="M4.4 9.6L8 6l3.6 3.6" {...STROKE} />
</svg>
);
}
function IconDown() {
return (
<svg width="13" height="13" viewBox="0 0 16 16" aria-hidden>
<path d="M4.4 6.4L8 10l3.6-3.6" {...STROKE} />
</svg>
);
}
function IconPrint() {
return (
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden>
<path d="M4.6 6.4V2.8h6.8v3.6" {...STROKE} />
<path d="M2.8 6.4h10.4v4.4H11v2.4H5v-2.4H2.8z" {...STROKE} />
<path d="M5 10.8h6" {...STROKE} />
</svg>
);
}
/**
* The Royal crown-diamond mark, drawn as paths.
*
* A row of three diamond outlines over a solid bar — the silhouette the 2027
* catalogue carries on its cover, its footers and its back page. Drawn rather
* than uploaded because a catalog has to print the mark at whatever size the
* page gives it, and because an image dependency for the ONE element on every
* page would make an unreachable asset route into a blank catalogue.
*/
function CrownMark({ className }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 44 26" aria-hidden>
<g fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round">
<path d="M11 4.5l6.5 6.5L11 17.5 4.5 11z" />
<path d="M22 2.5l7.5 7.5L22 17.5 14.5 10z" />
<path d="M33 4.5L39.5 11 33 17.5 26.5 11z" />
</g>
<rect x="4" y="20" width="36" height="2.6" fill="currentColor" />
</svg>
);
}
// ------------------------------------------------------------ page templates
/** The image slot every template shares: the asset, or a STATED gap.
*
* A missing master is drawn as a labelled frame naming the code, never as
* silence — the user has to be able to see, in the designer, that this page
* will print an empty box, and which SKU caused it. */
function Shot({
code,
quality,
missing,
cover,
}: {
code?: string;
quality: CatalogQuality;
missing?: boolean;
cover?: boolean;
}) {
if (!code)
return (
<div className="cg-cat-shot cg-cat-shot-empty">
<span>No image</span>
</div>
);
if (missing)
return (
<div className="cg-cat-shot cg-cat-shot-empty">
<span>
{editorialSlug(code) !== null
? `No editorial image named ${editorialSlug(code)}`
: `No master for ${code}`}
</span>
</div>
);
return (
<div className={cover ? "cg-cat-shot cg-cat-shot-cover" : "cg-cat-shot"}>
<img src={assetUrl(code, quality)} alt="" loading="eager" />
</div>
);
}
function ProductCard({
item,
quality,
layout,
hasAsset,
}: {
item: CatalogItem;
quality: CatalogQuality;
layout: ReturnType<typeof sectionLayout>;
hasAsset: (code: string) => boolean | null;
}) {
// ⭐ Wave-19 R7 — the picture is the ITEM'S image reference, which equals the code on every
// row nobody has overridden. Both the tile and the gap report read the SAME string, or the
// designer could mark a product "no master" while printing a picture it does have.
const known = hasAsset(item.image);
return (
<div className="cg-cat-card">
<Shot code={item.image} quality={quality} missing={known === false} />
{/* CAPS in CSS (`text-transform`), never by upper-casing the string: the
value stays the value, so a copy of it is not shouting. */}
<div className="cg-cat-desc">{item.name ?? (item.known ? "" : "Not in this table")}</div>
{layout.showPack && item.pack ? <div className="cg-cat-pill">{item.pack}</div> : null}
<div className="cg-cat-meta">
<span className="cg-cat-sku">{item.code}</span>
{layout.showColor && item.color ? (
<span className="cg-cat-color">{item.color}</span>
) : null}
</div>
{layout.showPrice && item.price ? <div className="cg-cat-price">{item.price}</div> : null}
</div>
);
}
/** Crown mark left, folio right — exactly the reference's footer, which carries no
* company line (the wordmark's place is the cover). `light` inverts it for the
* pages whose field is dark.
*
* `mark={false}` drops the crown: the intro page's terracotta lattice bleeds through the
* bottom-left corner, and a second terracotta mark sitting inside it reads as a smudge on the
* lattice rather than as the brand. The reference's own letter spread carries no crown there
* either — judged from the rendered page, not assumed. */
function PageFooter({
folio,
light,
mark = true,
}: {
folio: number;
light?: boolean;
mark?: boolean;
}) {
return (
<div className={light ? "cg-cat-foot cg-cat-foot-light" : "cg-cat-foot"}>
{mark ? <CrownMark className="cg-cat-foot-mark" /> : null}
<span className="cg-cat-folio">{folio}</span>
</div>
);
}
/** ONE page, at true paper size. The same component paints the stage and the
* print tree — there is no second renderer that could drift from what the
* screenshot showed. */
const CatalogPageView = memo(function CatalogPageView({
cat,
page,
index,
items,
quality,
hasAsset,
placed,
onPlaceItem,
onOpen,
gridRef,
}: {
cat: CatalogSpec;
page: CatalogPage;
index: number;
items: CatalogItem[];
quality: CatalogQuality;
hasAsset: (code: string) => boolean | null;
/** W37-T33 — this page's placed items, by code. ⛔ ABSENT or EMPTY means every item flows, which
* is every page of every catalog authored before this wave. */
placed?: Map<string, CatalogViewItem>;
/** Absent in the PRINT tree, deliberately: a printed page has nothing to drag. */
onPlaceItem?: (e: React.PointerEvent, code: string) => void;
onOpen?: (code: string) => void;
gridRef?: (n: HTMLDivElement | null) => void;
}) {
const box = pageBox(cat.paper, cat.orientation);
const px = box.unit === "in" ? 96 : 96 / 25.4;
const brand = cat.brand ?? {};
const primary = brand.primary ?? DEFAULT_BRAND.primary;
const accent = brand.accent ?? DEFAULT_BRAND.accent;
const company = brand.company ?? DEFAULT_BRAND.company;
const style = {
"--cat-w": `${box.w * px}px`,
"--cat-h": `${box.h * px}px`,
"--cat-primary": primary,
"--cat-accent": accent,
} as React.CSSProperties;
const folio = index + 1;
const logoKnown = brand.logo ? hasAsset(brand.logo) : null;
const Wordmark = (
<div className="cg-cat-mark">
{brand.logo && logoKnown !== false ? (
<img src={assetUrl(brand.logo, quality)} alt="" />
) : (
<CrownMark className="cg-cat-mark-crown" />
)}
<span className="cg-cat-mark-co">{company}</span>
</div>
);
if (page.kind === "cover") {
const known = page.imageCode ? hasAsset(page.imageCode) : null;
return (
<div className="cg-cat-page cg-cat-p-cover" style={style} data-kind="cover">
<Shot code={page.imageCode} quality={quality} missing={known === false} cover />
<div className="cg-cat-cover-scrim" />
{Wordmark}
<div className="cg-cat-cover-ttl">
<span className="cg-cat-cover-a">{page.title}</span>
{page.body ? <span className="cg-cat-cover-b">{page.body}</span> : null}
</div>
</div>
);
}
if (page.kind === "intro") {
return (
<div className="cg-cat-page cg-cat-p-intro" style={style} data-kind="intro">
<div className="cg-cat-intro-field">
{/* The terracotta lattice bleeding off the left edge — the reference's
own device for the letter spread, drawn from the crown's diamond. */}
<svg className="cg-cat-lattice" viewBox="0 0 200 260" aria-hidden>
<g fill="none" stroke="currentColor" strokeWidth="7">
<path d="M-40 130l60-60 60 60-60 60z" />
<path d="M40 190l60-60 60 60-60 60z" />
<path d="M100 130l40 40 40-90" />
</g>
</svg>
</div>
<div className="cg-cat-intro-body">
<h2 className="cg-cat-intro-ttl">{page.title}</h2>
{/* Paragraphs, not a wall: the reference's letter is set in short
blocks and reads as one because of the spacing between them. */}
{(page.body ?? "").split(/\n{2,}/).map((para, i) =>
para.trim() ? (
<p key={i} className="cg-cat-intro-p">
{para.trim()}
</p>
) : null
)}
<div className="cg-cat-intro-sign">The {company} Team</div>
</div>
<PageFooter folio={folio} light mark={false} />
</div>
);
}
if (page.kind === "gallery") {
const known = page.imageCode ? hasAsset(page.imageCode) : null;
return (
<div className="cg-cat-page cg-cat-p-gallery" style={style} data-kind="gallery">
<Shot code={page.imageCode} quality={quality} missing={known === false} cover />
<div className="cg-cat-gal-wash" />
{page.title ? <div className="cg-cat-gal-ttl">{page.title}</div> : null}
<PageFooter folio={folio} light />
</div>
);
}
const layout = sectionLayout(page);
// How many of this page's items carry coordinates. Zero => the container needs no
// positioning context at all, so an untouched catalog's DOM is unchanged too.
const freeCount = items.reduce((n, it) => n + (isPlaced(placed?.get(it.code)) ? 1 : 0), 0);
const stripKnown = page.imageCode ? hasAsset(page.imageCode) : null;
return (
<div
className={`cg-cat-page cg-cat-p-section${page.imageCode ? " has-strip" : ""}`}
style={style}
data-kind="section"
>
<h2 className="cg-cat-sec-ttl">{page.title}</h2>
{/* ⭐⭐ W37-T33 / R6 — FREE PLACEMENT, AND THE MIGRATION IS THE HARD PART.
An item with BOTH coordinates is positioned absolutely; an item with neither stays in the
grid flow exactly where it has always been. That is not a compatibility shim bolted on
the side, it is the rule C3 states: "the RENDERER turns an absent coordinate into flow
position N". A catalog authored before this wave has no coordinates at all, so every one
of its items takes the second branch and the page prints identically.
⛔ THE MIXED CASE IS DELIBERATE AND IS NOT A BUG: place two of six images and the other
four keep their grid cells. Snapping the whole section to absolute the moment one item
moves would relocate five images the person never touched. */}
<div
className={"cg-cat-grid" + (freeCount ? " cg-cat-slot-free" : "")}
style={{ "--cat-cols": layout.cols } as React.CSSProperties}
ref={gridRef}
>
{items.map((item) => {
const at = placed?.get(item.code);
const free = isPlaced(at);
const open = onOpen && item.known ? () => onOpen(item.code) : undefined;
return (
<div
key={item.code}
className={free ? "cg-cat-item-free" : undefined}
role={open ? "button" : undefined}
tabIndex={open ? 0 : undefined}
aria-label={open ? `Open ${item.name || item.code}` : undefined}
onClick={open}
onKeyDown={open ? (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
if (!event.repeat) open();
}
} : undefined}
// ⚠ `??` on every read, never `||`: `x: 0` is the left edge and a truthy test would
// silently drop an item somebody dragged into the corner back into the flow.
style={
free
? {
left: `${at!.x ?? 0}%`,
top: `${at!.y ?? 0}%`,
width: at!.w != null ? `${at!.w}%` : undefined,
height: at!.h != null ? `${at!.h}%` : undefined,
cursor: open ? "pointer" : onPlaceItem ? undefined : "default",
}
: open ? { cursor: "pointer" } : undefined
}
onPointerDown={onPlaceItem ? (e) => onPlaceItem(e, item.code) : undefined}
>
<ProductCard
item={item}
quality={quality}
layout={layout}
hasAsset={hasAsset}
/>
</div>
);
})}
</div>
{page.imageCode ? (
<div className="cg-cat-strip">
<Shot code={page.imageCode} quality={quality} missing={stripKnown === false} cover />
</div>
) : null}
<PageFooter folio={folio} />
</div>
);
});
// ------------------------------------------------------------------- stage
function CatalogPages({
cat,
itemsFor,
quality,
hasAsset,
scale,
selectedId,
onSelect,
registerSlot,
placedFor,
onPlaceItem,
onOpen,
registerGrid,
}: {
cat: CatalogSpec;
itemsFor: (page: CatalogPage) => CatalogItem[];
quality: CatalogQuality;
hasAsset: (code: string) => boolean | null;
/** Absent = paint at true size (the PRINT tree). */
scale?: number;
selectedId?: string;
onSelect?: (id: string) => void;
/** W37-T33 — this page's placed items, and the gesture that places them. ⛔ Both ABSENT in the
* PRINT tree, which is how a printed page ends up with the same geometry and no interaction. */
placedFor?: (pageId: string) => Map<string, CatalogViewItem>;
onPlaceItem?: (e: React.PointerEvent, code: string) => void;
onOpen?: (code: string) => void;
registerGrid?: (pageId: string, node: HTMLDivElement | null) => void;
/** W37-T32 — each slot registers itself under its PAGE ID so the rail can scroll to it. A ref
* callback rather than a DOM query, because the slots reorder and their positions do not
* identify them for longer than one drag. */
registerSlot?: (id: string, node: HTMLElement | null) => void;
}) {
const box = pageBox(cat.paper, cat.orientation);
const px = box.unit === "in" ? 96 : 96 / 25.4;
return (
<>
{cat.pages.map((page, i) => {
const body = (
<CatalogPageView
cat={cat}
page={page}
index={i}
items={itemsFor(page)}
quality={quality}
hasAsset={hasAsset}
placed={placedFor?.(page.id)}
onPlaceItem={onPlaceItem}
onOpen={onOpen}
gridRef={(n) => registerGrid?.(page.id, n)}
/>
);
if (scale === undefined) return <div key={page.id}>{body}</div>;
return (
<div
key={page.id}
ref={(n) => registerSlot?.(page.id, n)}
className={`cg-cat-slot${selectedId === page.id ? " is-sel" : ""}`}
style={{
width: box.w * px * scale,
height: box.h * px * scale,
"--cat-scale": scale,
} as React.CSSProperties}
onMouseDown={() => onSelect?.(page.id)}
>
{body}
</div>
);
})}
</>
);
}
// ------------------------------------------------------------------- view
export const CatalogView = memo(function CatalogView({
catalogs,
onCatalogs,
fields,
fieldByKey,
poolRows,
filteredCodes,
identityField,
catalogSpec,
onCatalogSpec,
onOpen,
surface,
readOnly = false,
saveError,
}: {
catalogs: CatalogSpec[];
onCatalogs: (next: CatalogSpec[]) => void;
fields: Field[];
fieldByKey: Map<string, Field>;
/** The WHOLE pool — a catalogue keeps painting what it names after the view
* is filtered, so the join must not run over the filtered rows. */
poolRows: Row[];
/** The codes the CURRENT filter kept — the "add what the view shows" door. */
filteredCodes: string[];
/**
* ⭐⭐ W37-T31 — THE COLUMN THAT IDENTIFIES A RECORD ON *THIS* DATABASE.
*
* The catalog was built for products and joins on the literal column `code`
* (`catalogData.CATALOG_CODE_FIELD`), which is both the SKU printed on the page and the key the
* image masters are named for. That coincidence is real and is why the join was hardcoded; it is
* also exactly why a catalog could not be opened on anything else, because no other table has a
* column called `code`. Naming the identity makes the same machinery work anywhere.
*
* ⚠ ABSENT falls back to `code`, so every product catalog authored before this wave joins
* byte-identically. This is a widening, not a migration.
*/
identityField?: Field;
/**
* ⭐⭐ W37-T31 / R5 / C3 — THE PER-VIEW CATALOG SETTINGS, stored by the host at
* `views[<id>].config.display.catalog`.
*
* ⛔ PER VIEW, WHICH IS THE WHOLE OF R5: two catalog views over one database may show different
* pictures and different titles, because a trade catalog and a lookbook are the same records
* presented differently. Putting these on the CATALOG instead would have made that impossible
* without duplicating the records.
*/
catalogSpec?: CatalogViewSpec;
onCatalogSpec?: (next: CatalogViewSpec) => void;
onOpen?: (pid: number) => void;
/** Only the App opts into editing; saved Data Catalog views are legacy readers. */
surface?: "app";
/** Shared by App viewers and legacy saved Catalog Views. Navigation and Print stay available. */
readOnly?: boolean;
saveError?: string;
}) {
const legacy = surface !== "app";
const locked = readOnly || legacy;
const legacyNote = legacy && <span className="cg-cat-note">Catalogs are edited in Apps.</span>;
const [openId, setOpenId] = useState<string | null>(catalogs[0]?.id ?? null);
const [pageId, setPageId] = useState<string | null>(catalogs[0]?.pages[0]?.id ?? null);
const [search, setSearch] = useState("");
const [picked, setPicked] = useState<Set<string>>(() => new Set());
const [assetCodes, setAssetCodes] = useState<Set<string> | null>(null);
const [editorialSlugs, setEditorialSlugs] = useState<Set<string> | null>(null);
const edFileRef = useRef<HTMLInputElement | null>(null);
const [printing, setPrinting] = useState<{ cat: CatalogSpec; quality: CatalogQuality } | null>(
null
);
const [askQuality, setAskQuality] = useState<CatalogSpec | null>(null);
// W-113: the quality prompt is a modal, so Escape cancels it through the one arbiter.
useEscapeClose(askQuality !== null, () => setAskQuality(null));
const stageRef = useRef<HTMLDivElement | null>(null);
const printRef = useRef<HTMLDivElement | null>(null);
const [stageW, setStageW] = useState(0);
const cat = catalogs.find((c) => c.id === openId) ?? null;
const page = cat?.pages.find((p) => p.id === pageId) ?? null;
// The manifest, once. `null` means "we do not know" and the designer stays
// quiet — a false gap report sends the user hunting for images that are there.
useEffect(() => {
let live = true;
void fetchAssetCodes().then((codes) => {
if (live) setAssetCodes(codes);
});
void fetchEditorialSlugs().then((slugs) => {
if (live) setEditorialSlugs(slugs);
});
return () => {
live = false;
};
}, []);
const hasAsset = useCallback(
(code: string): boolean | null => {
// `ed:` codes resolve against the EDITORIAL library (DEBT-5); everything
// else stays a product code. Unknown-library (null) keeps the designer
// quiet, same as the product manifest's own rule.
const slug = editorialSlug(code);
if (slug !== null) return editorialSlugs ? editorialSlugs.has(slug) : null;
// ⭐ Wave-19 R7 — a `rec:` upload has NO manifest to check against, and inventing one
// would be a per-tenant listing endpoint built for a designer badge. `null` is the
// vocabulary this function already has for "I do not know", and it is the truthful
// answer: an uploaded picture was validated at upload, so the far likelier state is that
// it is there. Marking it missing would send the user hunting for a file that exists.
if (code.startsWith(RECORD_IMAGE_PREFIX)) return null;
// A stored Amazon picture has no manifest either; the refresh wrote it only once stored.
if (code.startsWith(AMAZON_IMAGE_PREFIX)) return null;
return assetCodes ? assetCodes.has(code) : null;
},
[assetCodes, editorialSlugs]
);
useLayoutEffect(() => {
const el = stageRef.current;
if (!el || typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(() => setStageW(el.clientWidth));
ro.observe(el);
setStageW(el.clientWidth);
return () => ro.disconnect();
}, []);
/**
* ⭐⭐ W37-T31 — THE JOIN, GENERALISED. `indexByCode` reads the literal column `code`; this reads
* whichever column identifies a record on the open database, defaulting to `code` so every
* product catalog resolves exactly as before.
*
* ⚠ TEMPORARILY LOCAL. `catalogData.ts` is where it belongs, beside the constant it generalises,
* and it is in no lane's fence (`ASK D-14`). Written here so the ticket is not blocked on the
* grant; the moment `catalogData.ts` is mine this becomes `indexByKey` there and this local goes.
* ⛔ `indexByCode` is deliberately NOT imported any more: two joins in one path is the divergence
* this generalisation exists to prevent, so there is exactly ONE live indexer for a catalog.
*/
const identityKey = identityField?.key || CATALOG_CODE_FIELD;
const byCode = useMemo(() => {
const out = new Map<string, Row>();
for (const r of poolRows) {
const v = r[identityKey];
// ⚠ Numbers are stringified rather than skipped. `code` is text on the product table, but a
// generic identity column is often an int id, and refusing those would mean the catalog
// silently found nothing on exactly the databases this ticket is about.
const k = typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
if (k && !out.has(k)) out.set(k, r);
}
return out;
}, [poolRows, identityKey]);
const openItem = useCallback((code: string) => {
const row = byCode.get(code);
if (row) onOpen?.(row.pid);
}, [byCode, onOpen]);
/**
* ⭐⭐ W37-T31 / R5 — THE VIEW'S OWN PICTURE AND TITLE, LAYERED OVER THE RESOLVED ITEM.
*
* `resolveItems` picks the picture with `imageFieldKey()`, which returns the FIRST `image`-typed
* field on the TABLE. That is a sensible default and it is not what R5 asks for: the choice
* belongs to the VIEW, so two catalog views over one database can print different pictures.
*
* ⛔ LAYERED RATHER THAN REPLACED, deliberately. Everything `resolveItems` decides stays
* decided, including the STATED GAP for a record that is not in the pool (`known: false`, which
* prints a labelled empty frame naming the reference). Re-implementing that here to thread two
* extra arguments would put a second resolver in the tree and would eventually disagree with the
* first about what a missing record looks like.
* ⚠ `rowImageRef` is REUSED for the override rather than reading the cell directly, so the
* per-view picture obeys the same "trimmed, non-empty, else fall back" rule as the default one.
*/
const itemsFor = useCallback(
(p: CatalogPage) => {
const base = resolveItems(p.products ?? [], byCode, cat?.fields, formatDisplay, fieldByKey);
const imgKey = catalogSpec?.imageField;
const titleKey = catalogSpec?.titleField;
if (!imgKey && !titleKey) return base;
return base.map((it) => {
const row = byCode.get(it.code);
if (!row) return it;
const picture = imgKey ? rowImageRef(row, imgKey) : "";
const titleField = titleKey ? fieldByKey.get(titleKey) : undefined;
const title = titleField ? formatDisplay(titleField, row[titleKey!]) : "";
return {
...it,
...(picture ? { image: picture } : {}),
...(title ? { name: title } : {}),
};
});
},
[byCode, cat?.fields, fieldByKey, catalogSpec?.imageField, catalogSpec?.titleField]
);
const scale = useMemo(() => {
if (!cat || !stageW) return 0.5;
const box = pageBox(cat.paper, cat.orientation);
const px = box.unit === "in" ? 96 : 96 / 25.4;
return Math.min(1, Math.max(0.2, (stageW - 56) / (box.w * px)));
}, [cat, stageW]);
// ------------------------------------------------------------- mutation
const write = useCallback(
(next: CatalogSpec[]) => {
if (!locked) onCatalogs(next);
},
[onCatalogs, locked]
);
const patchCat = useCallback(
(id: string, patch: Partial<CatalogSpec>) => {
write(catalogs.map((c) => (c.id === id ? { ...c, ...patch } : c)));
},
[catalogs, write]
);
const patchPage = useCallback(
(catId: string, pgId: string, patch: Partial<CatalogPage>) => {
write(
catalogs.map((c) =>
c.id !== catId
? c
: { ...c, pages: c.pages.map((p) => (p.id === pgId ? { ...p, ...patch } : p)) }
)
);
},
[catalogs, write]
);
const addCatalog = () => {
if (catalogs.length >= MAX_CATALOGS) return;
const made = newCatalog(`Catalog ${catalogs.length + 1}`, fields);
write([...catalogs, made]);
setOpenId(made.id);
setPageId(made.pages[0]?.id ?? null);
};
const addPage = (kind: CatalogPageKind) => {
if (!cat || cat.pages.length >= MAX_CATALOG_PAGES) return;
const made = newPage(kind);
patchCat(cat.id, { pages: [...cat.pages, made] });
setPageId(made.id);
};
const movePage = (delta: number) => {
if (!cat || !page) return;
const i = cat.pages.findIndex((p) => p.id === page.id);
const j = i + delta;
if (i < 0 || j < 0 || j >= cat.pages.length) return;
const pages = [...cat.pages];
[pages[i], pages[j]] = [pages[j], pages[i]];
patchCat(cat.id, { pages });
};
/**
* ⭐⭐ W37-T32 / R6 — DRAG A PAGE TO REORDER IT.
*
* ⛔ PAGES REORDER, THEY DO NOT FREE-FLOAT, and that is R6's exact wording. A page has a POSITION
* IN A SEQUENCE because a printed document is a sequence; only the IMAGES inside a section carry
* free x/y (T33). Reading R6 as "everything drags anywhere" would have produced a page that can
* be dropped between two others and print in a third place.
*
* ⭐ IT MOVES, IT DOES NOT SWAP. `movePage`'s up/down buttons swap neighbours, which is right for
* a one-step nudge and wrong for a drag: dragging page 1 onto page 5 should leave 2, 3 and 4 in
* their order with 1 behind them, and a swap would put page 5 where page 1 was. Two gestures,
* two behaviours, both correct for what they are.
*/
/**
* ⛔⛔ THE DRAGGED ID LIVES IN A REF, AND THE STATE BESIDE IT IS ONLY FOR THE LOOK.
*
* `dragstart` and `drop` are separate events, so the obvious shape is `useState`. It is racy:
* the drop handler closes over the value from ITS render, and if no render has happened between
* the two events the handler still sees `null` and the drop silently does nothing. A human drag
* takes hundreds of milliseconds and React always flushes in between, which is exactly why this
* class of bug ships: it is invisible to the hand and reproducible only when the two events
* arrive in one task. MEASURED here, on the render probe, by dispatching both synchronously.
* The ref is read at EVENT time, so the gesture cannot depend on a render having occurred.
*/
const dragPageRef = useRef<string | null>(null);
const [dragPageId, setDragPageId] = useState<string | null>(null);
const [dropPageId, setDropPageId] = useState<string | null>(null);
const dropPageOn = useCallback(
(targetId: string) => {
const held = dragPageRef.current;
if (!cat || !held || held === targetId) return;
const from = cat.pages.findIndex((p) => p.id === held);
const to = cat.pages.findIndex((p) => p.id === targetId);
if (from < 0 || to < 0) return;
const pages = [...cat.pages];
pages.splice(to, 0, pages.splice(from, 1)[0]);
patchCat(cat.id, { pages });
},
[cat, patchCat]
);
/**
* W37-T32 — CLICKING A PAGE SCROLLS THE CANVAS TO IT.
*
* ⚠ A MAP OF LIVE NODES, not a query at click time. The stage is a scroller of page slots and a
* `querySelector` would have to encode the slot's position in the DOM, which changes the moment
* pages reorder. Registering each slot under its page id means the lookup survives every reorder
* this ticket also introduces.
*/
/**
* ⭐⭐ W37-T33 / R6 — DRAG AN IMAGE ANYWHERE INSIDE ITS SECTION.
*
* Pointer events rather than HTML5 drag-and-drop, and the two are not interchangeable here. A
* `dragstart` gives you a drag IMAGE and drop TARGETS, which is exactly right for reordering a
* list (T32) and exactly wrong for placing something at a coordinate: the browser paints a ghost,
* the position only arrives at the end, and there is no live preview. `setPointerCapture` gives
* continuous coordinates and keeps them coming when the cursor leaves the page box.
*
* ⛔ WRITTEN IN PERCENT OF THE PAGE, so the number means the same thing in the designer (scaled
* to fit the stage) and in the print tree (true paper size). Storing pixels would have made a
* catalog print at a different layout from the one it was designed at, which is the single most
* expensive kind of wrong for a print feature.
* ⚠ CLAMPED to 0..96 rather than 0..100: an item positioned exactly at 100% starts where the
* page ends and prints nothing at all.
*/
const gridRefs = useRef(new Map<string, HTMLDivElement>());
const placeRef = useRef<{ code: string; pageId: string; el: HTMLElement } | null>(null);
const writeItem = useCallback(
(pageId: string, code: string, patch: Partial<CatalogViewItem>) => {
if (locked || !onCatalogSpec) return;
const spec: CatalogViewSpec = { ...(catalogSpec || {}) };
const pages = [...(spec.pages || [])];
let pi = pages.findIndex((p) => p.id === pageId);
if (pi < 0) {
pages.push({ id: pageId, sections: [{ id: `${pageId}-s1`, items: [] }] });
pi = pages.length - 1;
}
const page = { ...pages[pi] };
const sections = [...(page.sections || [])];
if (!sections.length) sections.push({ id: `${pageId}-s1`, items: [] });
const sec = { ...sections[0], items: [...(sections[0].items || [])] };
const ii = sec.items.findIndex((it) => it.code === code);
if (ii < 0) sec.items.push({ code, ...patch });
else sec.items[ii] = { ...sec.items[ii], ...patch };
sections[0] = sec;
page.sections = sections;
pages[pi] = page;
onCatalogSpec({ ...spec, pages });
},
[catalogSpec, onCatalogSpec, locked]
);
const onPlaceItem = useCallback(
(e: React.PointerEvent, code: string) => {
if (locked || !onCatalogSpec || !page) return;
const el = e.currentTarget as HTMLElement;
// ⛔⛔ MEASURED AGAINST THE PAGE, NOT THE GRID, and the two are not interchangeable.
// A placed item is out of flow, so the grid SHRINKS as items are placed: measure against it
// and the coordinate space moves while you are using it, until placing the last item collapses
// the grid to zero height and drops everything at the top. `.cg-cat-page` is the sheet of
// paper -- `position: relative`, explicit `height: var(--cat-h)`, `overflow: hidden` -- so a
// percentage of it is stable, and identical in the designer and the print tree.
const grid = el.closest(".cg-cat-page") as HTMLElement | null;
if (!grid) return;
e.preventDefault();
// ⛔ CAPTURE IS AN ENHANCEMENT, NOT A PRECONDITION, and it used to be able to kill the whole
// gesture. `setPointerCapture` THROWS on a pointer id the browser does not consider active,
// and it sat above the listener registration: one throw and the drag was never wired up at
// all, silently. What capture buys is events continuing when the cursor leaves the page box;
// without it a drag still works, it just stops at the edge. Losing the edge case is a small
// cost. Losing the feature is not.
try {
el.setPointerCapture(e.pointerId);
} catch {
/* not capturable: the drag still tracks while the pointer is over the item */
}
placeRef.current = { code, pageId: page.id, el };
const box = grid.getBoundingClientRect();
// The grab OFFSET, so the image does not jump its own top-left corner under the cursor the
// instant you touch it. Without this every drag begins with a visible snap.
const item = el.getBoundingClientRect();
const dx = e.clientX - item.left;
const dy = e.clientY - item.top;
const move = (ev: PointerEvent) => {
const x = ((ev.clientX - dx - box.left) / box.width) * 100;
const y = ((ev.clientY - dy - box.top) / box.height) * 100;
const cx = Math.max(0, Math.min(96, Math.round(x * 100) / 100));
const cy = Math.max(0, Math.min(96, Math.round(y * 100) / 100));
// Painted straight onto the node during the drag. Writing through state on every
// pointermove would round-trip the whole catalog document per frame.
el.classList.add("cg-cat-item-free", "is-dragging");
el.style.left = `${cx}%`;
el.style.top = `${cy}%`;
grid.classList.add("cg-cat-slot-free");
};
const up = (ev: PointerEvent) => {
el.removeEventListener("pointermove", move);
el.removeEventListener("pointerup", up);
el.removeEventListener("pointercancel", up);
el.classList.remove("is-dragging");
const x = ((ev.clientX - dx - box.left) / box.width) * 100;
const y = ((ev.clientY - dy - box.top) / box.height) * 100;
placeRef.current = null;
writeItem(page.id, code, {
x: Math.max(0, Math.min(96, Math.round(x * 100) / 100)),
y: Math.max(0, Math.min(96, Math.round(y * 100) / 100)),
});
};
el.addEventListener("pointermove", move);
el.addEventListener("pointerup", up);
el.addEventListener("pointercancel", up);
},
[onCatalogSpec, page, writeItem, locked]
);
const slotRefs = useRef(new Map<string, HTMLElement>());
const openPage = useCallback((id: string) => {
setPageId(id);
const node = slotRefs.current.get(id);
// `block: "start"` rather than "center": a page is taller than the viewport at most zooms, so
// centring it puts its header off the top, which is the half you are navigating BY.
if (node) node.scrollIntoView({ behavior: "smooth", block: "start" });
}, []);
// ------------------------------------------------------------ the picker
const matches = useMemo(() => {
if (!cat) return [];
const q = search.trim().toLowerCase();
const nameKey = catalogSpec?.titleField || cat.fields?.name;
const out: { code: string; label: string }[] = [];
for (const r of poolRows) {
const value = r[identityKey];
const code = typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
if (!code) continue;
const nameField = nameKey ? fieldByKey.get(nameKey) : undefined;
const label = nameField ? formatDisplay(nameField, r[nameKey as string]) : "";
if (q && !code.toLowerCase().includes(q) && !label.toLowerCase().includes(q)) continue;
out.push({ code, label });
if (out.length >= 200) break;
}
return out;
}, [cat, poolRows, search, fieldByKey, identityKey, catalogSpec?.titleField]);
const commitCodes = (codes: string[]) => {
if (!cat || !page) return;
const res = addCodes(cat, page.id, codes);
patchCat(cat.id, { pages: res.pages });
setPicked(new Set());
if (res.skippedCap || res.skippedDuplicate) {
const parts: string[] = [];
if (res.skippedDuplicate) parts.push(`${res.skippedDuplicate} already on the page`);
if (res.skippedCap)
parts.push(`${res.skippedCap} over the ${MAX_CATALOG_CODES}-product catalog limit`);
setNote(`Added ${res.added}. Skipped ${parts.join("; ")}.`);
} else {
setNote(`Added ${res.added}.`);
}
};
const moveProduct = (code: string, delta: number) => {
if (!cat || !page) return;
const products = [...(page.products ?? [])];
const from = products.indexOf(code);
const to = from + delta;
if (from < 0 || to < 0 || to >= products.length) return;
[products[from], products[to]] = [products[to], products[from]];
patchPage(cat.id, page.id, { products });
};
const [note, setNote] = useState("");
// DEBT-5: one editorial master in, `ed:<slug>` bound to the open page. The server
// owns validation (admin wall, charset, opens-as-an-image); this just reports honestly.
const uploadEditorialFile = async (f: File) => {
const slug = slugFromFilename(f.name);
if (!slug) {
setNote("That filename does not reduce to a usable name. Rename the file first.");
return;
}
setNote(`Uploading ${slug}…`);
try {
const stored = await uploadEditorial(slug, f);
setEditorialSlugs(await fetchEditorialSlugs());
if (cat && page) patchPage(cat.id, page.id, { imageCode: `${EDITORIAL_PREFIX}${stored}` });
setNote(`Editorial image "${stored}" stored and bound to this page.`);
} catch (e) {
setNote(e instanceof Error ? e.message : "The upload failed.");
}
};
// ------------------------------------------------------------- printing
useEffect(() => {
if (!printing) return;
let cancelled = false;
void (async () => {
// One frame so the print tree is in the DOM before its images are awaited.
await new Promise<void>((res) => requestAnimationFrame(() => res()));
await awaitImages(printRef.current);
if (cancelled) return;
const drop = applyPrintCss(printing.cat);
await printOnce();
drop();
if (!cancelled) setPrinting(null);
})();
return () => {
cancelled = true;
};
}, [printing]);
// ----------------------------------------------------------------- paint
if (!catalogs.length)
return (
<div className="cg-cat cg-cat-blank" onPointerDown={foldNavOnWorkSurface}>
<div className="cg-cat-blank-in">
<CrownMark className="cg-cat-blank-mark" />
<h3>No catalogs yet</h3>
{legacyNote}
{!locked && (
<button type="button" className="cg-btn cg-btn--primary" onClick={addCatalog}>
<IconPlus /> New catalog
</button>
)}
{saveError ? <div className="cg-cat-note" role="alert">{saveError}</div> : null}
</div>
</div>
);
const used = cat ? codesUsed(cat) : 0;
return (
<div
className="cg-cat"
style={locked ? { gridTemplateColumns: "var(--cg-catalog-legacy-columns, 232px minmax(0, 1fr))" } : undefined}
onPointerDown={foldNavOnWorkSurface}
>
{/* ------------------------------------------------------------ rail */}
<aside className="cg-cat-rail">
<div className="cg-cat-rail-head">
<span>Catalogs</span>
{!locked && <button
type="button"
className="cg-cat-icon-btn"
title={
catalogs.length >= MAX_CATALOGS
? `A view holds ${MAX_CATALOGS} catalogs.`
: "New catalog"
}
aria-label="New catalog"
disabled={catalogs.length >= MAX_CATALOGS}
onClick={addCatalog}
>
<IconPlus />
</button>}
</div>
<ul className="cg-cat-list">
{catalogs.map((c) => (
<li key={c.id}>
<button
type="button"
className={`cg-cat-item${c.id === openId ? " is-open" : ""}`}
onClick={() => {
setOpenId(c.id);
setPageId(c.pages[0]?.id ?? null);
}}
>
<span className="cg-cat-item-name">{c.name || "Untitled catalog"}</span>
<span className="cg-cat-item-meta">
{c.pages.length} {c.pages.length === 1 ? "page" : "pages"}
</span>
</button>
</li>
))}
</ul>
{cat ? (
<>
<div className="cg-cat-rail-head cg-cat-rail-sub">
<span>Pages</span>
<span className="cg-cat-count">
{cat.pages.length}/{MAX_CATALOG_PAGES}
</span>
</div>
<ul className="cg-cat-pagelist">
{cat.pages.map((p, i) => (
<li
key={p.id}
// ⚠ THE DRAG LIVES ON THE <li>, NOT ON THE <button> INSIDE IT. A draggable
// button is a browser-by-browser coin toss: some start a drag, some fire a
// click, and Firefox does neither reliably. The row wraps the control, so the
// gesture is unambiguous and the button keeps being a button.
draggable={locked ? undefined : true}
className={locked ? undefined :
"cg-cat-pagerow" +
(p.id === dragPageId ? " is-dragging" : "") +
(p.id === dropPageId && p.id !== dragPageId ? " is-dropzone" : "")
}
onDragStart={locked ? undefined : (e) => {
dragPageRef.current = p.id;
setDragPageId(p.id);
e.dataTransfer.effectAllowed = "move";
// Firefox refuses to start a drag at all without data on the transfer.
e.dataTransfer.setData("text/plain", p.id);
}}
onDragOver={locked ? undefined : (e) => {
if (!dragPageRef.current) return;
e.preventDefault(); // without this the drop never fires
e.dataTransfer.dropEffect = "move";
if (dropPageId !== p.id) setDropPageId(p.id);
}}
onDrop={locked ? undefined : (e) => {
e.preventDefault();
dropPageOn(p.id);
dragPageRef.current = null;
setDragPageId(null);
setDropPageId(null);
}}
// ⛔ `onDragEnd` CLEARS TOO, and it is not redundant with `onDrop`: a drag
// abandoned outside the list fires no drop at all, and without this the row
// stays visually held forever with no way to release it.
onDragEnd={() => {
dragPageRef.current = null;
setDragPageId(null);
setDropPageId(null);
}}
>
<button
type="button"
className={`cg-cat-pageitem${p.id === pageId ? " is-sel" : ""}`}
onClick={() => openPage(p.id)}
title={locked ? `Go to page ${i + 1}.` : `Go to page ${i + 1}. Drag to move it.`}
>
<span className="cg-cat-pageno">{i + 1}</span>
<span className="cg-cat-pagettl">
{p.title || PAGE_KIND_LABELS[p.kind]}
</span>
<span className="cg-cat-pagekind">{PAGE_KIND_LABELS[p.kind]}</span>
</button>
</li>
))}
</ul>
{!locked && <div className="cg-cat-addrow">
{CATALOG_PAGE_KINDS.map((k) => (
<button
key={k}
type="button"
className="cg-btn"
disabled={cat.pages.length >= MAX_CATALOG_PAGES}
onClick={() => addPage(k)}
>
<IconPlus /> {PAGE_KIND_LABELS[k]}
</button>
))}
</div>}
</>
) : null}
</aside>
{/* ----------------------------------------------------------- stage */}
<div className="cg-cat-stage" ref={stageRef}>
{cat ? (
<>
<div className="cg-cat-bar">
{locked ? (
<span className="cg-cat-name">{cat.name || "Untitled catalog"}</span>
) : (
<>
<input
className="cg-input cg-cat-name"
value={cat.name}
maxLength={CATALOG_NAME_MAX}
aria-label="Catalog name"
onChange={(e) => patchCat(cat.id, { name: e.target.value })}
/>
<select
className="cg-select"
aria-label="Paper size"
value={cat.paper}
onChange={(e) => patchCat(cat.id, { paper: e.target.value as CatalogPaper })}
>
{CATALOG_PAPERS.map((p) => (
<option key={p} value={p}>
{PAPER_LABELS[p]}
</option>
))}
</select>
<select
className="cg-select"
aria-label="Orientation"
value={cat.orientation}
onChange={(e) =>
patchCat(cat.id, { orientation: e.target.value as CatalogOrientation })
}
>
{CATALOG_ORIENTATIONS.map((o) => (
<option key={o} value={o}>
{o === "portrait" ? "Portrait" : "Landscape"}
</option>
))}
</select>
</>
)}
<span className="cg-cat-budget" title="Products placed across this catalog's pages">
{used}/{MAX_CATALOG_CODES} products
</span>
{legacyNote}
<button
type="button"
className="cg-btn cg-btn--primary cg-cat-print"
onClick={() => setAskQuality(cat)}
>
<IconPrint /> Print
</button>
</div>
{saveError ? <div className="cg-cat-note" role="alert">{saveError}</div> : null}
<div className="cg-cat-scroll">
<CatalogPages
cat={cat}
itemsFor={itemsFor}
quality="web"
hasAsset={hasAsset}
scale={scale}
selectedId={pageId ?? undefined}
onSelect={setPageId}
placedFor={(id) => placedItems(catalogSpec, id)}
onPlaceItem={locked ? undefined : onPlaceItem}
onOpen={locked && onOpen ? openItem : undefined}
registerGrid={(id, node) => {
if (node) gridRefs.current.set(id, node);
else gridRefs.current.delete(id);
}}
registerSlot={(id, node) => {
// ⚠ DELETE on unmount rather than storing null. A map that accumulates dead ids
// would let a scroll target a node that is no longer in the document, and
// `scrollIntoView` on a detached element does nothing at all -- a click that
// silently goes nowhere, which is the hardest kind of dead control to notice.
if (node) slotRefs.current.set(id, node);
else slotRefs.current.delete(id);
}}
/>
</div>
</>
) : (
<div className="cg-mode-empty">Pick a catalog to open it.</div>
)}
</div>
{/* ------------------------------------------------------- inspector */}
{!locked && <aside className="cg-cat-insp">
{cat && page ? (
<>
<div className="cg-cat-insp-head">
<span>{PAGE_KIND_LABELS[page.kind]}</span>
<span className="cg-cat-insp-tools">
<button
type="button"
className="cg-cat-icon-btn"
aria-label="Move page up"
onClick={() => movePage(-1)}
>
<IconUp />
</button>
<button
type="button"
className="cg-cat-icon-btn"
aria-label="Move page down"
onClick={() => movePage(1)}
>
<IconDown />
</button>
<button
type="button"
className="cg-cat-icon-btn cg-cat-del"
aria-label="Delete page"
onClick={() =>
patchCat(cat.id, { pages: cat.pages.filter((p) => p.id !== page.id) })
}
>
<IconTrash />
</button>
</span>
</div>
<label className="cg-cat-fld">
<span>Title</span>
<input
className="cg-input"
value={page.title ?? ""}
onChange={(e) => patchPage(cat.id, page.id, { title: e.target.value })}
/>
</label>
{page.kind === "cover" || page.kind === "intro" ? (
<label className="cg-cat-fld">
<span>{page.kind === "cover" ? "Second line" : "Body"}</span>
<textarea
className="cg-input cg-cat-area"
rows={page.kind === "cover" ? 2 : 9}
value={page.body ?? ""}
onChange={(e) => patchPage(cat.id, page.id, { body: e.target.value })}
/>
</label>
) : null}
{page.kind !== "intro" ? (
<>
<label className="cg-cat-fld">
<span>{page.kind === "section" ? "Footer image (code)" : "Image (code)"}</span>
<input
className="cg-input"
value={page.imageCode ?? ""}
placeholder="e.g. CRY-2003 or ed:showroom"
onChange={(e) => patchPage(cat.id, page.id, { imageCode: e.target.value })}
/>
{page.imageCode && hasAsset(page.imageCode) === false ? (
<em className="cg-cat-warn">
{editorialSlug(page.imageCode) !== null
? "No editorial image is stored under this name, so the page will print an empty frame."
: "No image is archived under this code, so the page will print an empty frame."}
</em>
) : (
<em className="cg-cat-hint">
Fills the width edge to edge, so a wide photograph reads best here. A cut-out
product render will be cropped and enlarged to fill it.
</em>
)}
</label>
<label className="cg-cat-fld">
<span>Editorial library</span>
<select
className="cg-select"
value={editorialSlug(page.imageCode ?? "") ?? ""}
onChange={(e) =>
patchPage(cat.id, page.id, {
imageCode: e.target.value ? `${EDITORIAL_PREFIX}${e.target.value}` : "",
})
}
>
<option value="">(use a product code above)</option>
{[...(editorialSlugs ?? [])].sort().map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
<button
type="button"
className="cg-btn"
onClick={() => edFileRef.current?.click()}
>
Upload a photograph…
</button>
<input
ref={edFileRef}
type="file"
accept="image/png,image/jpeg"
style={{ display: "none" }}
onChange={(e) => {
const f = e.target.files?.[0];
if (f) void uploadEditorialFile(f);
e.target.value = "";
}}
/>
<em className="cg-cat-hint">
Lifestyle photography without a SKU lives here. Storing a new one needs an
admin login; everyone can pick from the library.
</em>
</label>
</>
) : null}
{page.kind === "section" ? (
<>
<div className="cg-cat-insp-sub">Layout</div>
<div className="cg-cat-row">
<label className="cg-cat-fld cg-cat-fld-inline">
<span>Columns</span>
<select
className="cg-select"
value={sectionLayout(page).cols}
onChange={(e) =>
patchPage(cat.id, page.id, {
layout: { ...page.layout, cols: Number(e.target.value) },
})
}
>
{CATALOG_COLS.map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
</label>
</div>
{(
[
["showPack", "Pack line", false],
["showColor", "Colour", false],
["showPrice", "Price", true],
] as const
).map(([key, label, optIn]) => {
const l = sectionLayout(page);
const on = key === "showPrice" ? l.showPrice : key === "showPack" ? l.showPack : l.showColor;
return (
<label key={key} className="cg-check-row">
<input
type="checkbox"
checked={on}
onChange={() => {
// Literal-only storage: the toggle writes the opt-out (or the
// opt-in) and DELETES the key to go back to the default, so the
// default has exactly one spelling on the wire.
const next = { ...page.layout };
if (optIn) {
if (on) delete next.showPrice;
else next.showPrice = true;
} else if (key === "showPack") {
if (on) next.showPack = false;
else delete next.showPack;
} else {
if (on) next.showColor = false;
else delete next.showColor;
}
patchPage(cat.id, page.id, {
layout: Object.keys(next).length ? next : undefined,
});
}}
/>
<span>{label}</span>
</label>
);
})}
<div className="cg-cat-insp-sub">
Products
<span className="cg-cat-count">{page.products?.length ?? 0} on this page</span>
</div>
<div className="cg-cat-picked">
{(page.products ?? []).map((code) => (
<span key={code} className="cg-cat-chip">
{code}
<button
type="button"
aria-label={`Move ${code} up`}
disabled={page.products?.[0] === code}
onClick={() => moveProduct(code, -1)}
>
<IconUp />
</button>
<button
type="button"
aria-label={`Move ${code} down`}
disabled={page.products?.[page.products.length - 1] === code}
onClick={() => moveProduct(code, 1)}
>
<IconDown />
</button>
{isPlaced(placedItems(catalogSpec, page.id).get(code)) && (
<button
type="button"
aria-label={`Return ${code} to page flow`}
title="Reset placement"
onClick={() => writeItem(page.id, code, {
x: undefined, y: undefined, w: undefined, h: undefined,
})}
>
Flow
</button>
)}
<button
type="button"
aria-label={`Remove ${code}`}
onClick={() =>
patchPage(cat.id, page.id, {
products: (page.products ?? []).filter((c) => c !== code),
})
}
>
×
</button>
</span>
))}
</div>
<button
type="button"
className="cg-btn cg-cat-addfiltered"
disabled={!filteredCodes.length}
onClick={() => commitCodes(filteredCodes)}
>
<IconPlus /> Add the {filteredCodes.length} records this view shows
</button>
<input
className="cg-input"
placeholder="Search products by SKU or name"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
{/* S68-T42: the inspector is a scrolling flex column, and a scrolling child's
automatic minimum height is zero, so this list collapsed to 0 px whenever
the page settings outgrew the inspector and no product could be picked. */}
<div className="cg-cat-results" style={{ flexShrink: 0 }}>
{matches.map((m) => (
<label key={m.code} className="cg-check-row">
<input
type="checkbox"
checked={picked.has(m.code)}
onChange={() =>
setPicked((prev) => {
const next = new Set(prev);
if (next.has(m.code)) next.delete(m.code);
else next.add(m.code);
return next;
})
}
/>
<span className="cg-cat-res-code">{m.code}</span>
<span className="cg-cat-res-name">{m.label}</span>
</label>
))}
{/* The 200 is STATED, never silent: a search that stops early has
to say so or the user reads absence as "we do not stock it". */}
{matches.length >= 200 ? (
<div className="cg-cat-more">
Showing the first 200 matches. Narrow the search to see the rest.
</div>
) : null}
</div>
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={!picked.size}
onClick={() => commitCodes([...picked])}
>
Add {picked.size} selected
</button>
{note ? <div className="cg-cat-note">{note}</div> : null}
</>
) : null}
<div className="cg-cat-insp-sub">Brand</div>
<div className="cg-cat-row">
<label className="cg-cat-fld cg-cat-fld-inline">
<span>Primary</span>
<input
type="color"
className="cg-cat-swatch"
value={cat.brand?.primary ?? DEFAULT_BRAND.primary}
onChange={(e) =>
patchCat(cat.id, { brand: { ...cat.brand, primary: e.target.value } })
}
/>
</label>
<label className="cg-cat-fld cg-cat-fld-inline">
<span>Accent</span>
<input
type="color"
className="cg-cat-swatch"
value={cat.brand?.accent ?? DEFAULT_BRAND.accent}
onChange={(e) =>
patchCat(cat.id, { brand: { ...cat.brand, accent: e.target.value } })
}
/>
</label>
</div>
<label className="cg-cat-fld">
<span>Company</span>
<input
className="cg-input"
value={cat.brand?.company ?? ""}
placeholder={DEFAULT_BRAND.company}
onChange={(e) =>
patchCat(cat.id, { brand: { ...cat.brand, company: e.target.value } })
}
/>
</label>
{/* ⭐⭐ W37-T31 / R5 — THE TWO PICKERS THAT MAKE THIS WORK ON ANY DATABASE, and they sit
ABOVE the listing columns because they are the questions that decide whether there
is a catalog at all: what is the picture, and what is the title.
⛔ THESE TWO ARE PER *VIEW*, and the ones below are per CATALOG. That is not an
inconsistency, it is R5: a trade catalog and a lookbook over the same records are
two VIEWS wanting different pictures, while the four listing lines belong to the
printed artifact. The subheading says so, because a person cannot be expected to
infer which settings travel with which thing. */}
{onCatalogSpec && (
<>
<div className="cg-cat-insp-sub">This view</div>
{(
[
["imageField", "Picture from", "The column holding each record's image"],
["titleField", "Title from", "The column printed as the item's name"],
] as const
).map(([slot, label, hint]) => (
<label key={slot} className="cg-cat-fld cg-cat-fld-inline" title={hint}>
<span>{label}</span>
<select
className="cg-select"
value={catalogSpec?.[slot] ?? ""}
onChange={(e) => {
const next = { ...(catalogSpec || {}) };
if (e.target.value) next[slot] = e.target.value;
else delete next[slot];
onCatalogSpec(next);
}}
>
{/* The wave-7 trap again: a <select> whose value is not among its options
renders the FIRST one, so "unset" needs a row rather than an absence. */}
<option value="">
{slot === "imageField" ? "The table's image column" : "The description line"}
</option>
{fields.map((f) => (
<option key={f.key} value={f.key}>
{f.label}
</option>
))}
</select>
</label>
))}
</>
)}
<div className="cg-cat-insp-sub">Listing columns</div>
{(
[
["name", "Description"],
["pack", "Pack line"],
["color", "Colour"],
["price", "Price"],
] as const
).map(([slot, label]) => (
<label key={slot} className="cg-cat-fld cg-cat-fld-inline">
<span>{label}</span>
<select
className="cg-select"
value={cat.fields?.[slot] ?? ""}
onChange={(e) => {
const next = { ...cat.fields };
if (e.target.value) next[slot] = e.target.value;
else delete next[slot];
patchCat(cat.id, { fields: Object.keys(next).length ? next : undefined });
}}
>
{/* An explicit empty option — the wave-7 trap: a <select> whose value
is not among its options renders the FIRST one, so "unbound" needs a
row of its own rather than being the absence of one. */}
<option value="">Not shown</option>
{fields.map((f) => (
<option key={f.key} value={f.key}>
{f.label}
</option>
))}
</select>
</label>
))}
<button
type="button"
className="cg-btn"
onClick={() => {
const guess = autoBind(fields);
patchCat(cat.id, { fields: Object.keys(guess).length ? guess : undefined });
}}
>
Guess from this table
</button>
<div className="cg-cat-insp-foot">
<button
type="button"
className="cg-btn cg-btn--danger"
onClick={() => {
const next = catalogs.filter((c) => c.id !== cat.id);
write(next);
setOpenId(next[0]?.id ?? null);
setPageId(null);
}}
>
<IconTrash /> Delete this catalog
</button>
</div>
</>
) : (
<div className="cg-cat-insp-blank">Select a page to edit it.</div>
)}
</aside>}
{/* --------------------------------------------------- quality prompt */}
{askQuality ? (
<div className="cg-cat-modal-wrap" role="dialog" aria-modal="true" aria-label="Print quality">
<div className="cg-cat-modal">
<h3>Print “{askQuality.name || "Untitled catalog"}”</h3>
<p>
Your browser’s print dialog opens next. Choose “Save as PDF” there.
Pick the image quality first.
</p>
<button
type="button"
className="cg-cat-choice"
onClick={() => {
setPrinting({ cat: askQuality, quality: "print" });
setAskQuality(null);
}}
>
<strong>High quality</strong>
<em>Original master images. Slower, and a much larger PDF, so use this for print.</em>
</button>
<button
type="button"
className="cg-cat-choice"
onClick={() => {
setPrinting({ cat: askQuality, quality: "web" });
setAskQuality(null);
}}
>
<strong>Standard</strong>
<em>The same images you see here. Fast, small file, fine for a proof or email.</em>
</button>
<button type="button" className="cg-btn" onClick={() => setAskQuality(null)}>
Cancel
</button>
</div>
</div>
) : null}
{/* ------------------------------------------------------ print tree */}
{printing
? createPortal(
<div className="cg-cat-print-portal" ref={printRef}>
<CatalogPages
cat={printing.cat}
itemsFor={itemsFor}
quality={printing.quality}
hasAsset={hasAsset}
// ⛔⛔ W37-T33 — THE SAME PLACEMENTS, AND NO GESTURE. The done-when is that an image
// stays where it was put "across a reload AND in the printed output", so the print
// tree has to read the identical layout the designer wrote. `onPlaceItem` is
// deliberately NOT passed: a printed page has nothing to drag, and a pointer
// handler in the print portal would be dead code sitting on top of the artifact.
// ⭐ This is the pairing that would have been easiest to miss and hardest to
// notice: the designer would look perfect and the PDF would print the flow layout.
placedFor={(id) => placedItems(catalogSpec, id)}
/>
</div>,
document.body
)
: null}
</div>
);
});
export default CatalogView;
// ---------------------------------------------------------------------------
// 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";