import React, { Fragment, useMemo } from 'react'; import type { ComponentType, ElementType, ReactNode } from 'react'; import { PageLayout, PageSection } from '../components/Layout'; import { getComponent, hasComponent } from '../registry'; import { COMPONENTS_READING_ASSET_OBJECTS, normalizeAssets } from './assets'; import { resolveLinkRefs } from './links'; import { isLinkRefUid } from '../contract/links'; import { PlainField, fieldKind, hasComponentFields, hasPlainContent, resolveFieldOverride } from './plainFields'; import type { StackablesFieldOverrides } from './plainFields'; import { resolveComponentName } from './resolve'; import { PAGE_SYSTEM_FIELDS, globalFieldUid, isMultipleReference, referenceTargets, sectionWidthOf } from './schema'; import { DEFAULT_NON_RENDERING_COMPONENTS, type StackablesPageConfig, type StackablesSiteConfig } from './siteConfig'; import type { StackablesBlock, StackablesEntryData, StackablesField } from './types'; // The one component a Stackables site needs: hand it an entry and that entry's // content-type schema and it renders the whole page. It walks the schema the // way the static generator walks it at build time (see frontendTemplates.js // there) — a `global_field` field is one component, a `reference` field is // one component per referenced entry, a `group` is a run of sibling sections, // a `blocks` field is one component per block — but decides everything at // render time, from data, so the page keeps up with whatever Stackables // publishes to the stack without regenerating code. // // A page type made directly in Contentstack — a "custom page", with no // Stackables layout — renders the same way, plus its plain fields (text, rich // text, files, links) as a document: see renderPlainFields and plainFields.tsx. type AnyComponent = ComponentType; export interface UnknownSectionInfo { /** The content type / global field uid the field points at. */ uid: string | undefined; /** The component name that uid resolved to (undefined when nothing mapped it). */ componentName: string | undefined; /** Dotted path of the field holding the value, e.g. "content_blocks.highlight.feature_card". */ path: string; /** The value was an unresolved reference stub — the entry was fetched without this reference path. */ unresolved?: boolean; } export interface StackablesEntryProps { /** The fetched entry (references resolved — see referencePaths in schema.ts). */ entry: StackablesEntryData | null | undefined; /** The entry's content-type schema, with global field schemas included. */ schema: StackablesField[] | null | undefined; /** The site config Stackables published (uid → component map, non-rendering components). */ config?: StackablesSiteConfig | null; /** This page's layout metadata: container cap, per-section widths, page component. */ page?: StackablesPageConfig | null; /** Extra or overriding components, by name — consulted before the library registry. */ components?: Record; /** * Your own component for a content type / global field uid — rendered for * every field that points at that uid, whether or not the library (or the * site config) has a component for it. Checked before the name lookup, so it * also takes a library-rendered content type over. A uid equal to the entry's * own content type (see `contentType`) takes over the page component. */ componentsByUid?: Record; /** The entry's own content type uid — lets `componentsByUid` take over the whole page type. */ contentType?: string | null; /** Top-level fields rendered elsewhere (the site header / footer) and so skipped here. */ omitFields?: string[]; /** Overrides the uid → component-name mapping for one field; return undefined to fall through. */ resolveComponent?: (uid: string | undefined, field: StackablesField | StackablesBlock) => string | undefined; /** What to render for a field whose component can't be found. Default: nothing. */ renderUnknown?: (info: UnknownSectionInfo) => ReactNode; /** * Render plain fields — text, rich text (HTML or JSON), files, links, numbers, * dates — as page content, not only the fields that point at components. * * Defaults to on exactly when there is no Stackables `page`: a page type made * directly in Contentstack (a custom page), which is usually a title and a * body and would otherwise render blank. A page designed in Stackables keeps * its plain fields as metadata, as it always has. Consecutive plain fields * share one section in the container; a custom page with no components at * all also gets its title as a heading. */ renderPlainFields?: boolean; /** * Your own rendering for plain fields (text, Markdown, booleans, selects, * custom fields, JSON, taxonomies…): by kind, by field uid or dotted path, * or by custom-field extension uid; `null` hides a field. See * StackablesFieldOverrides in plainFields.tsx for the order. A `uids.title` * entry replaces a custom page's title heading. */ fields?: StackablesFieldOverrides; /** The page wrapper element — defaults to
. */ as?: ElementType; className?: string; } interface RenderContext { componentNameFor: (uid: string | undefined, field: StackablesField | StackablesBlock) => string | undefined; componentFor: (name: string | undefined) => AnyComponent | undefined; componentByUid: (uid: string | undefined) => AnyComponent | undefined; nonRendering: ReadonlySet; omit: ReadonlySet; /** Width for a section: its own entry value first, then the site config's designed value for its path; undefined when the page has no container at all ('full' cap). */ widthFor: (path: string, value: unknown) => string | undefined; renderUnknown?: (info: UnknownSectionInfo) => ReactNode; /** Plain fields render as content (see renderPlainFields). */ plain: boolean; /** Width of a run of plain content: in the container, or none when the page has no container ('full' cap). */ plainWidth: string | undefined; /** Field overrides (the `fields` prop). */ fields?: StackablesFieldOverrides; /** The page entry — handed to field overrides. */ entry?: StackablesEntryData; } /** * A reference the Delivery API did not resolve: `{ uid, _content_type_uid }` and * nothing else (bar bookkeeping). Rendering it would hand a component no props * at all and show its placeholder copy as if it were content — so it counts as * "nothing renders" and goes to renderUnknown instead. */ const STUB_KEYS = new Set(['uid', '_content_type_uid', '_version', 'locale', '$', '_metadata']); function isUnresolvedReference(value: unknown): boolean { if (!value || typeof value !== 'object' || Array.isArray(value)) return false; const record = value as Record; return typeof record._content_type_uid === 'string' && Object.keys(record).every((key) => STUB_KEYS.has(key)); } const itemKey = (item: unknown, index: number): string | number => { if (item && typeof item === 'object') { const record = item as Record; if (typeof record.uid === 'string') return record.uid; const metadata = record._metadata as Record | undefined; if (metadata && typeof metadata.uid === 'string') return metadata.uid; } return index; }; interface SectionProps { component: AnyComponent; componentName: string; value: StackablesEntryData; containerWidth: string | undefined; } /** * One rendered component. Registry components apply `container_width` * themselves (they're wrapped in withSectionWidth); anything else handed in * via `components` gets the same PageSection wrapper put around it. */ function EntrySection({ component: Component, componentName, value, containerWidth }: SectionProps) { const props = useMemo( () => resolveLinkRefs(COMPONENTS_READING_ASSET_OBJECTS.has(componentName) ? value : normalizeAssets(value)), [componentName, value], ); if (getComponent(componentName) === Component) { return containerWidth === undefined ? : ; } const inner = ; return containerWidth === undefined ? inner : {inner}; } /** * A run of consecutive plain fields, as one section: in the container like any * other section, with document typography (the `.sk-plain` styles). One * section per run rather than per field, so a subtitle and the body under it * read as one piece instead of two blocks with a section gap between them. */ function PlainSection({ width, children }: { width: string | undefined; children: ReactNode }) { const body =
{children}
; return width === undefined ? body : {body}; } /** * The class Contentstack's Visual Builder looks for on an EMPTY modular blocks * field's element (`VB_EmptyBlockParentClass` in @contentstack/live-preview-utils), * so an editor can add the first block. Only a modular blocks field gets it. */ export const VB_EMPTY_BLOCK_PARENT_CLASS = 'visual-builder__empty-block-parent'; type EditTagMap = Record> | undefined; /** * The items of a multiple field (modular blocks, a repeatable group or global * field, a multi-entry reference), wrapped for Live Preview / Visual Builder. * The list element carries the field's own tag (`$.content_blocks`), which is * what lets the builder add to the field; each item carries its index tag * (`$.content_blocks__0`) for add-after / move / delete. Items that render * nothing get no wrapper. An empty list renders only in the preview (where * `$` exists), and only a modular blocks field then gets the builder's * empty-block-parent class, with a little height so it can be clicked. * * `sk-list` / `sk-list-item` are structural: unstyled, and looked through by * PageLayout's auto spacing (see sectionSpacing childrenOf), so the sections * inside space apart exactly as they would as direct children of the page. */ function renderList( field: StackablesField, items: unknown[], editTags: EditTagMap, render: (item: unknown, index: number) => ReactNode | ReactNode[], { emptyBlock = false }: { emptyBlock?: boolean } = {}, ): ReactNode { const parentTag = editTags?.[field.uid]; const shown: ReactNode[] = []; items.forEach((item, index) => { const node = render(item, index); const rendered = Array.isArray(node) ? node.length > 0 : node !== null && node !== undefined && node !== false; if (!rendered) return; shown.push(
{node}
, ); }); if (!shown.length && !parentTag) return null; const empty = !shown.length && emptyBlock; return (
{shown}
); } function renderComponent( uid: string | undefined, field: StackablesField | StackablesBlock, value: unknown, path: string[], key: string | number, ctx: RenderContext, ): ReactNode { if (!value || typeof value !== 'object') return null; const dotted = path.join('.'); if (isUnresolvedReference(value)) { return ctx.renderUnknown ? ( {ctx.renderUnknown({ uid, componentName: undefined, path: dotted, unresolved: true })} ) : null; } // A component the site supplies for this content type / global field uid // outranks everything: the site config's mapping, the library, the // non-rendering list. This is how a content type the library has never // heard of gets rendered — and how a page can swap one it has. const own = ctx.componentByUid(uid); if (own && uid) { return ( ); } const componentName = ctx.componentNameFor(uid, field); if (componentName && ctx.nonRendering.has(componentName)) return null; const component = ctx.componentFor(componentName); if (!component) { return ctx.renderUnknown ? ( {ctx.renderUnknown({ uid, componentName, path: dotted })} ) : null; } return ( ); } /** * The sections a run of schema fields produces off `value` — the entry at the * top level, a group item or a block's own object further down. Fields that * point at a component render as sections. Plain fields (text, rich text, * files…) render only when `ctx.plain` is on — a custom page — and then as * runs: consecutive plain fields collect into one PlainSection, closed by the * next component or the end. The page's own title/url/seo never render here. * * `lead` opens the first plain run — the custom page's title heading — so it * shares a section with the text under it. */ function renderFields( fields: StackablesField[] | null | undefined, value: StackablesEntryData | null | undefined, path: string[], ctx: RenderContext, lead?: ReactNode, ): ReactNode[] { const out: ReactNode[] = []; if (!value || typeof value !== 'object') return out; let run: ReactNode[] = lead ? [lead] : []; let runKey = `plain-${path.join('.') || 'lead'}`; const flush = () => { if (!run.length) return; out.push( {run} , ); run = []; }; // Anything that is not plain content closes the current run first — but only // if it actually renders, so an unmapped field that yields nothing does not // split one run of text into two sections. const emit = (...nodes: ReactNode[]) => { if (nodes.some((node) => node !== null && node !== undefined && node !== false)) flush(); out.push(...nodes); }; const editTags = (value as { $?: EditTagMap }).$; for (const field of fields ?? []) { if (!field?.uid) continue; if (path.length === 0 && (PAGE_SYSTEM_FIELDS.has(field.uid) || ctx.omit.has(field.uid))) continue; const fieldPath = [...path, field.uid]; const fieldValue = value[field.uid]; switch (field.data_type) { case 'global_field': { // The value is the component's props (or an array of them when repeatable). const uid = globalFieldUid(field); if (field.multiple) { emit( renderList(field, Array.isArray(fieldValue) ? fieldValue : [], editTags, (item, index) => renderComponent(uid, field, item, fieldPath, `${field.uid}-${itemKey(item, index)}`, ctx), ), ); } else { emit(renderComponent(uid, field, fieldValue, fieldPath, field.uid, ctx)); } break; } case 'reference': { // A button's page link (sk__ref — see contract/links) is not a // section: it is read by resolveLinkRefs into its link's href. It can // sit at the top level of a page that IS a catalog component. if (isLinkRefUid(field.uid)) break; // Always an ARRAY of resolved entries, even when the field holds one — // being single only limits the UI to one selection (see // isMultipleReference for how a multi-entry one is marked). Each entry // says which content type it is; the field's reference_to is the // fallback for one that wasn't resolved. const items = Array.isArray(fieldValue) ? fieldValue : []; const [defaultTarget] = referenceTargets(field); const renderReference = (item: unknown, index: number) => { const record = item as { _content_type_uid?: unknown } | null | undefined; const uid = typeof record?._content_type_uid === 'string' ? record._content_type_uid : defaultTarget; return renderComponent(uid, field, item, fieldPath, `${field.uid}-${itemKey(item, index)}`, ctx); }; if (isMultipleReference(field)) emit(renderList(field, items, editTags, renderReference)); else items.slice(0, 1).forEach((item, index) => emit(renderReference(item, index))); break; } case 'group': { // Not a section itself: its members are siblings, each with its own width. if (field.multiple) { emit( renderList(field, Array.isArray(fieldValue) ? fieldValue : [], editTags, (item) => renderFields(field.schema, item as StackablesEntryData, fieldPath, ctx), ), ); } else { emit(...renderFields(field.schema, fieldValue, fieldPath, ctx)); } break; } case 'blocks': { // Each item carries exactly one block, keyed by that block's uid — // `{ hero_section: { ... } }`. A block that IS a global field // (reference_to) holds the component's props directly; any other // block nests its fields under its own uid. emit( renderList( field, Array.isArray(fieldValue) ? fieldValue : [], editTags, (item, index) => { if (!item || typeof item !== 'object') return null; const record = item as Record; const block = (field.blocks ?? []).find((candidate) => candidate?.uid && candidate.uid in record); if (!block) return null; const blockValue = record[block.uid]; const blockPath = [...fieldPath, block.uid]; const key = `${field.uid}-${itemKey(item, index)}`; if (block.reference_to) return renderComponent(block.reference_to, block, blockValue, blockPath, key, ctx); return renderFields(block.schema, blockValue as StackablesEntryData, blockPath, ctx); }, { emptyBlock: true }, ), ); break; } default: { // Plain content. A field override (the `fields` prop) comes first — it // can take any field, the kinds the library doesn't render included; // otherwise the library renders it, only on a custom page and only if // there is something to show. const dotted = fieldPath.join('.'); const Override = resolveFieldOverride(ctx.fields, field, dotted, { types: ctx.plain }); if (Override === null) break; // mapped to null: hidden on purpose const libraryRenders = ctx.plain && hasPlainContent(field, fieldValue); const own = libraryRenders ? ( ) : null; if (Override === undefined) { if (!own) break; if (!run.length) runKey = `plain-${dotted}`; run.push(own); break; } if (fieldValue === undefined || fieldValue === null) break; if (!run.length) runKey = `plain-${dotted}`; run.push( {own} , ); break; } } } flush(); return out; } export function StackablesEntry({ entry, schema, config, page, components, componentsByUid, contentType, omitFields, resolveComponent, renderUnknown, renderPlainFields, fields, as = 'main', className, }: StackablesEntryProps) { // The container cap is one value for the whole site: the site config entry's // own `max_container_width` dropdown (which an editor can change in // Contentstack), else the library default. 'full' is the one cap that means // "no container": with none, all three width modes render alike, so no width // is passed and the library emits no wrapper at all rather than one with // nothing to do. const containerWidth = config?.maxContainerWidth ?? null; const capped = containerWidth !== 'full'; // No Stackables page layout means a page type made in Contentstack. const plain = renderPlainFields ?? !page; const ctx = useMemo(() => { const isKnown = (name: string) => !!components?.[name] || hasComponent(name); const widths = page?.widths ?? {}; return { componentNameFor: (uid, field) => resolveComponent?.(uid, field) ?? resolveComponentName(uid, config, isKnown), componentFor: (name) => (name ? components?.[name] ?? getComponent(name) : undefined), componentByUid: (uid) => (uid ? componentsByUid?.[uid] : undefined), nonRendering: new Set(config?.nonRendering ?? DEFAULT_NON_RENDERING_COMPONENTS), omit: new Set(omitFields ?? []), // Each section's own `sk_section_width` first — the entry is the source // of truth once deployed — then the width Stackables designed for this // path, for an entry that leaves the dropdown empty. widthFor: (path, value) => (capped ? sectionWidthOf(value) ?? widths[path] ?? 'inherit' : undefined), renderUnknown, plain, plainWidth: capped ? 'inherit' : undefined, fields, }; }, [components, componentsByUid, config, page, omitFields, resolveComponent, renderUnknown, capped, plain, fields]); if (!entry) return null; // A catalog page component renders from the entry itself — its fields are // top-level on the content type, not nested under a field uid. A page content // type carries `sk_section_width` too (it can also be placed as a section on // another page), so that is its width here, defaulting to the container. // A component supplied for the page's own content type uid takes the whole // page type over: it renders the entry itself and nothing else follows — // the sections are its to render (or not). Without one, the site config's // catalog page component (if any) renders first, then the sections. const ownPageComponent = ctx.componentByUid(contentType ?? page?.contentType); const pageComponentName = ownPageComponent ? contentType ?? page?.contentType ?? undefined : page?.pageComponent ?? undefined; const pageComponent = ownPageComponent ?? ctx.componentFor(pageComponentName); // A custom page built only of plain fields is a document, so its title leads // as the heading; one built of components has its headings in them already // (see hasComponentFields). A takeover renders the page itself, title and all. // A `uids.title` field override replaces that heading — and, since asking // for it is explicit, shows it on a custom page built of components too; // mapped to null, it hides it. const title = typeof entry.title === 'string' ? entry.title.trim() : ''; const titleField: StackablesField = schema?.find((f) => f?.uid === 'title') ?? { uid: 'title', data_type: 'text', display_name: 'Title' }; const TitleOverride = resolveFieldOverride(fields, titleField, 'title', { types: false }); const defaultHeading = (

{title}

); const showsHeading = plain && !ownPageComponent && !!title && TitleOverride !== null; const lead = !showsHeading ? undefined : TitleOverride ? ( {hasComponentFields(schema) ? null : defaultHeading} ) : hasComponentFields(schema) ? undefined : defaultHeading; const sections = ownPageComponent ? [] : renderFields(schema, entry, [], { ...ctx, entry }, lead); // A page component the site config names but nothing provides is reported, not swallowed. const missingPageComponent = !pageComponent && pageComponentName && ctx.renderUnknown ? ctx.renderUnknown({ uid: contentType ?? page?.contentType, componentName: pageComponentName, path: '' }) : null; return ( {pageComponent && pageComponentName && (ownPageComponent || !ctx.nonRendering.has(pageComponentName)) ? ( ) : ( missingPageComponent )} {sections} ); }