@crombolo/render 0.29.0 → 0.30.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/render",
3
- "version": "0.29.0",
3
+ "version": "0.30.2",
4
4
  "description": "TSX server rendering and the published-content model for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -32,7 +32,7 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@crombolo/core": "0.29.0",
35
+ "@crombolo/core": "0.30.2",
36
36
  "@types/react": "^19.3.0"
37
37
  }
38
38
  }
package/src/blocks.ts ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Blocks render their own components (story 184). `<Blocks items={…} />` renders
3
+ * each block of a Block List or Block Grid with `components/blocks/<element
4
+ * alias>.tsx`, so a new kind of block is one new file, not an edit to every
5
+ * template that lists blocks. A grid renders Umbraco's block-grid markup, so its
6
+ * default stylesheet and CSS written for it apply unchanged.
7
+ */
8
+ import { blockComponentLoader, isPreview } from './context.ts'
9
+ import { escapeHtml, RawHtml } from './html.ts'
10
+ import { type Child, renderToString } from './jsx-runtime.ts'
11
+ import type {
12
+ BlockGridArea,
13
+ BlockGridItem,
14
+ BlockItem,
15
+ PublishedElement,
16
+ TypedElement,
17
+ } from './values.ts'
18
+
19
+ /** What a block's component is given. */
20
+ // biome-ignore lint/suspicious/noExplicitAny: an untyped block, as `TypedElement` defaults to.
21
+ export interface BlockProps<Content = any, Settings = any> {
22
+ content: TypedElement<Content>
23
+ settings: TypedElement<Settings> | null
24
+ /** The block itself: its keys, and in a grid its spans and areas. */
25
+ block: BlockItem | BlockGridItem
26
+ /** In a grid, the block's areas, rendered: put `{children}` where they go. */
27
+ children?: RawHtml
28
+ }
29
+
30
+ // biome-ignore lint/suspicious/noExplicitAny: a block component takes whichever props it declares.
31
+ type BlockComponent = (props: BlockProps<any, any>) => Child | Promise<Child>
32
+
33
+ export interface BlocksProps {
34
+ /** A Block List or Block Grid property's value: `model.value('sections')`. */
35
+ items: readonly BlockItem[] | null | undefined
36
+ /** Components for some element types, in place of `components/blocks/`, here only. */
37
+ components?: Readonly<Record<string, BlockComponent>>
38
+ /** A grid's columns, when its value does not carry them; 12 otherwise. */
39
+ columns?: number
40
+ }
41
+
42
+ const isGrid = (items: readonly BlockItem[]): items is readonly BlockGridItem[] =>
43
+ items.some((item) => 'areas' in item && Array.isArray((item as BlockGridItem).areas))
44
+
45
+ const aliasOf = (element: PublishedElement) => element.contentType.alias ?? ''
46
+
47
+ const css = (vars: Record<string, number>) =>
48
+ Object.entries(vars)
49
+ .map(([name, value]) => `${name}: ${value};`)
50
+ .join(' ')
51
+
52
+ /** Renders each block with its own component. */
53
+ export async function Blocks(props: BlocksProps): Promise<RawHtml> {
54
+ const items = props.items ?? []
55
+ if (items.length === 0) return new RawHtml('')
56
+ if (!isGrid(items)) {
57
+ const parts = await Promise.all(items.map((item) => renderBlock(item, props.components)))
58
+ return new RawHtml(parts.join(''))
59
+ }
60
+ const columns = props.columns ?? (items as Partial<{ gridColumns: number }>).gridColumns ?? 12
61
+ return new RawHtml(
62
+ `<div class="umb-block-grid" data-grid-columns="${columns}" style="${css({ '--umb-block-grid--grid-columns': columns })}">${await layout(items, columns, props.components)}</div>`,
63
+ )
64
+ }
65
+
66
+ /** One grid level: the container and its items, each with its areas. */
67
+ async function layout(
68
+ items: readonly BlockGridItem[],
69
+ columns: number,
70
+ components: BlocksProps['components'],
71
+ ): Promise<string> {
72
+ const rendered = await Promise.all(
73
+ items.map(async (item) => {
74
+ const columnSpan = item.columnSpan ?? columns
75
+ const rowSpan = item.rowSpan ?? 1
76
+ const areaColumns = item.areaGridColumns ?? columns
77
+ const areas =
78
+ item.areas.length > 0
79
+ ? `<div class="umb-block-grid__area-container" style="${css({ '--umb-block-grid--area-grid-columns': areaColumns })}">${(
80
+ await Promise.all(item.areas.map((area) => areaHtml(area, areaColumns, components)))
81
+ ).join('')}</div>`
82
+ : ''
83
+ const alias = escapeHtml(aliasOf(item.content))
84
+ const inner = await renderBlock(item, components, areas ? new RawHtml(areas) : undefined)
85
+ return `<div class="umb-block-grid__layout-item" data-content-element-type-alias="${alias}" data-content-element-type-key="${escapeHtml(item.content.contentType.key)}" data-element-key="${escapeHtml(item.contentKey)}" data-col-span="${columnSpan}" data-row-span="${rowSpan}" style="${css({ '--umb-block-grid--item-column-span': columnSpan, '--umb-block-grid--item-row-span': rowSpan })}">${inner}</div>`
86
+ }),
87
+ )
88
+ return `<div class="umb-block-grid__layout-container">${rendered.join('')}</div>`
89
+ }
90
+
91
+ async function areaHtml(
92
+ area: BlockGridArea,
93
+ columns: number,
94
+ components: BlocksProps['components'],
95
+ ): Promise<string> {
96
+ const columnSpan = area.columnSpan ?? columns
97
+ const rowSpan = area.rowSpan ?? 1
98
+ const alias = area.alias === null ? '' : ` data-area-alias="${escapeHtml(area.alias)}"`
99
+ return `<div class="umb-block-grid__area"${alias} data-area-col-span="${columnSpan}" data-area-row-span="${rowSpan}" style="${css({ '--umb-block-grid--grid-columns': columnSpan, '--umb-block-grid--area-column-span': columnSpan, '--umb-block-grid--area-row-span': rowSpan })}">${await layout(area.items, columnSpan, components)}</div>`
100
+ }
101
+
102
+ /** A block through its component, or nothing (a placeholder in preview) when it has none. */
103
+ async function renderBlock(
104
+ item: BlockItem,
105
+ components: BlocksProps['components'],
106
+ children?: RawHtml,
107
+ ): Promise<string> {
108
+ const alias = aliasOf(item.content)
109
+ const component =
110
+ (alias ? components?.[alias] : undefined) ??
111
+ (alias ? await blockComponentLoader()?.(alias) : undefined)
112
+ if (!component) {
113
+ if (!isPreview()) return children?.value ?? ''
114
+ const file = `components/blocks/${alias || '<element type>'}.tsx`
115
+ return `<div class="crombolo-block-missing" style="padding: 12px; border: 1px dashed #b45309; color: #b45309; font: 14px sans-serif;">No component renders the “${escapeHtml(alias || 'unknown')}” block. Create <code>${escapeHtml(file)}</code>. Visitors see nothing here.</div>${children?.value ?? ''}`
116
+ }
117
+ const props: BlockProps = {
118
+ content: item.content as BlockProps['content'],
119
+ settings: item.settings as BlockProps['settings'],
120
+ block: item,
121
+ ...(children ? { children } : {}),
122
+ }
123
+ return renderToString((component as BlockComponent)(props) as Child)
124
+ }
package/src/context.ts CHANGED
@@ -23,6 +23,22 @@ interface RenderScope {
23
23
  contexts: ReadonlyMap<symbol, unknown>
24
24
  /** Shared by every scope a provider opens inside one render, so ids stay unique. */
25
25
  ids: { next: number }
26
+ /** A block's component by element type alias, from the page's own views generation. */
27
+ blockComponent?: BlockComponentLoader
28
+ /** A draft is being previewed in the back office. */
29
+ preview?: boolean
30
+ }
31
+
32
+ /** Loads `components/blocks/<alias>.tsx`'s default export, or nothing when there is none. */
33
+ export type BlockComponentLoader = (
34
+ alias: string,
35
+ ) => Promise<((props: never) => Child | Promise<Child>) | undefined>
36
+
37
+ /** What a page render carries besides its props: the search, blocks, and whether it is a preview. */
38
+ export interface RenderScopeOptions {
39
+ search?: SiteSearchPort
40
+ blockComponent?: BlockComponentLoader
41
+ preview?: boolean
26
42
  }
27
43
 
28
44
  /**
@@ -35,8 +51,12 @@ if (!shared[KEY]) shared[KEY] = new AsyncLocalStorage<RenderScope>()
35
51
  const store = shared[KEY] as AsyncLocalStorage<RenderScope>
36
52
 
37
53
  /** Runs a render with `page` available to `usePage()`, and ids counted from zero. */
38
- export function renderScope<T>(page: PageProps, render: () => T, search?: SiteSearchPort): T {
39
- return store.run({ page, search, contexts: new Map(), ids: { next: 0 } }, render)
54
+ export function renderScope<T>(
55
+ page: PageProps,
56
+ render: () => T,
57
+ options: RenderScopeOptions = {},
58
+ ): T {
59
+ return store.run({ page, ...options, contexts: new Map(), ids: { next: 0 } }, render)
40
60
  }
41
61
 
42
62
  /** Runs an e-mail template's render: ids and context work, and there is no page. */
@@ -141,3 +161,13 @@ export function useContext<T>(context: Context<T>): T {
141
161
  const contexts = store.getStore()?.contexts
142
162
  return contexts?.has(context.key) ? (contexts.get(context.key) as T) : context.defaultValue
143
163
  }
164
+
165
+ /** The page's block-component loader (story 184), for `Blocks`; undefined outside a page render. */
166
+ export function blockComponentLoader(): BlockComponentLoader | undefined {
167
+ return store.getStore()?.blockComponent
168
+ }
169
+
170
+ /** Whether the page rendering is a back-office preview, which shows what visitors do not. */
171
+ export function isPreview(): boolean {
172
+ return store.getStore()?.preview === true
173
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './blocks.ts'
1
2
  export * from './cache-policy.ts'
2
3
  export * from './context.ts'
3
4
  export * from './email.ts'
package/src/renderer.ts CHANGED
@@ -99,6 +99,8 @@ export interface RenderRequest {
99
99
  signal?: AbortSignal
100
100
  /** Site search scoped to whoever is asking, for `search()`. */
101
101
  search?: SiteSearchPort
102
+ /** A back-office preview of a draft: blocks with no component say so (story 184). */
103
+ preview?: boolean
102
104
  }
103
105
 
104
106
  /**
@@ -368,7 +370,11 @@ export class Renderer {
368
370
  }
369
371
 
370
372
  // Inside the page's scope, so any component can ask for it with `usePage()`.
371
- return renderScope(props, () => this.#renderLayouts(alias, props, rendering), request.search)
373
+ return renderScope(props, () => this.#renderLayouts(alias, props, rendering), {
374
+ search: request.search,
375
+ preview: request.preview,
376
+ blockComponent: (blockAlias) => this.blockComponent(blockAlias),
377
+ })
372
378
  }
373
379
 
374
380
  /** Generic over its props: a page's, or an e-mail's. */
@@ -401,6 +407,17 @@ export class Renderer {
401
407
  return body === undefined ? undefined : withDoctype(body.value)
402
408
  }
403
409
 
410
+ /**
411
+ * A block's component (story 184): `components/blocks/<alias>.tsx` and
412
+ * nowhere else. The alias is one plain segment, so an element type alias can
413
+ * never reach outside `blocks/`.
414
+ */
415
+ async blockComponent(alias: string) {
416
+ if (!/^[A-Za-z0-9_-]+$/.test(alias)) return undefined
417
+ const module = await this.#load(`blocks/${alias}`)
418
+ return module?.default as ((props: never) => Child | Promise<Child>) | undefined
419
+ }
420
+
404
421
  async #load(alias: string): Promise<ComponentModule | undefined> {
405
422
  const file = this.componentPath(alias)
406
423
  if (!file) return undefined
package/src/values.ts CHANGED
@@ -46,15 +46,24 @@ export interface BlockItem {
46
46
 
47
47
  export interface BlockGridArea {
48
48
  key: string
49
+ /** The area's alias from the data type, when its block type still declares it. */
50
+ alias: string | null
51
+ columnSpan: number | null
52
+ rowSpan: number | null
49
53
  items: BlockGridItem[]
50
54
  }
51
55
 
52
56
  export interface BlockGridItem extends BlockItem {
53
57
  columnSpan: number | null
54
58
  rowSpan: number | null
59
+ /** The columns this block's areas lay out in; the grid's own when its block type says none. */
60
+ areaGridColumns: number | null
55
61
  areas: BlockGridArea[]
56
62
  }
57
63
 
64
+ /** A Block Grid's items, carrying the grid's column count for its markup. */
65
+ export type BlockGridValue = BlockGridItem[] & { gridColumns: number }
66
+
58
67
  const references = (value: unknown): string[] => {
59
68
  if (Array.isArray(value)) return value.flatMap((v) => (typeof v === 'string' ? [v] : []))
60
69
  if (typeof value === 'string')
@@ -153,6 +162,12 @@ function elementFrom(data: BlockData | undefined, context?: ValueContext): Publi
153
162
  )
154
163
  }
155
164
 
165
+ interface GridBlockConfig {
166
+ contentElementTypeKey?: string
167
+ areaGridColumns?: unknown
168
+ areas?: Array<{ key?: string; alias?: unknown; columnSpan?: unknown; rowSpan?: unknown }>
169
+ }
170
+
156
171
  function blockItems<T extends BlockItem>(
157
172
  value: unknown,
158
173
  layoutAlias: string,
@@ -304,21 +319,42 @@ export function convertValue(
304
319
  }
305
320
  case 'Umbraco.BlockList':
306
321
  return blockItems<BlockItem>(value, 'Umbraco.BlockList', context, (_, item) => item)
307
- case 'Umbraco.BlockGrid':
308
- return blockItems<BlockGridItem>(
322
+ case 'Umbraco.BlockGrid': {
323
+ // What the data type says of each block type's areas: their aliases and spans.
324
+ const blockTypes = Array.isArray(config.blocks) ? (config.blocks as GridBlockConfig[]) : []
325
+ const typeOf = (key: string | undefined) =>
326
+ blockTypes.find(
327
+ (b) => String(b.contentElementTypeKey ?? '').toLowerCase() === (key ?? '').toLowerCase(),
328
+ )
329
+ const number = (value: unknown) => (typeof value === 'number' ? value : null)
330
+ const items = blockItems<BlockGridItem>(
309
331
  value,
310
332
  'Umbraco.BlockGrid',
311
333
  context,
312
- (layout, item, build) => ({
313
- ...item,
314
- columnSpan: layout.columnSpan ?? null,
315
- rowSpan: layout.rowSpan ?? null,
316
- areas: (layout.areas ?? []).map((area) => ({
317
- key: area.key,
318
- items: build(area.items ?? []),
319
- })),
320
- }),
334
+ (layout, item, build) => {
335
+ const type = typeOf(item.content.contentType.key)
336
+ return {
337
+ ...item,
338
+ columnSpan: layout.columnSpan ?? null,
339
+ rowSpan: layout.rowSpan ?? null,
340
+ areaGridColumns: number(type?.areaGridColumns),
341
+ areas: (layout.areas ?? []).map((area) => {
342
+ const declared = type?.areas?.find(
343
+ (a) => String(a.key ?? '').toLowerCase() === area.key.toLowerCase(),
344
+ )
345
+ return {
346
+ key: area.key,
347
+ alias: typeof declared?.alias === 'string' ? declared.alias : null,
348
+ columnSpan: number(declared?.columnSpan),
349
+ rowSpan: number(declared?.rowSpan),
350
+ items: build(area.items ?? []),
351
+ }
352
+ }),
353
+ }
354
+ },
321
355
  )
356
+ return Object.assign(items, { gridColumns: Number(config.gridColumns) || 12 })
357
+ }
322
358
  default:
323
359
  return value
324
360
  }