payload-canvas 0.2.0 → 0.4.0

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.
Files changed (170) hide show
  1. package/README.md +500 -25
  2. package/dist/admin/diff/changes.js +8 -0
  3. package/dist/admin/editor/Inspector.js +49 -4
  4. package/dist/admin/editor/Outline.js +12 -10
  5. package/dist/admin/editor/actions.d.ts +9 -1
  6. package/dist/admin/editor/actions.js +38 -3
  7. package/dist/admin/editor/empty/EmptyStart.js +29 -3
  8. package/dist/admin/editor/fields/GroupField.d.ts +5 -2
  9. package/dist/admin/editor/fields/GroupField.js +6 -2
  10. package/dist/admin/editor/fields/WhereField.d.ts +17 -0
  11. package/dist/admin/editor/fields/WhereField.js +67 -0
  12. package/dist/admin/editor/fields/fields.scss +89 -0
  13. package/dist/admin/editor/fields/whereRows.d.ts +28 -0
  14. package/dist/admin/editor/fields/whereRows.js +118 -0
  15. package/dist/admin/editor/icons.d.ts +1 -0
  16. package/dist/admin/editor/icons.js +2 -0
  17. package/dist/admin/editor/locale/LocaleField.d.ts +1 -1
  18. package/dist/admin/editor/locale/LocaleField.js +3 -1
  19. package/dist/admin/editor/menu/blockMenu.js +5 -1
  20. package/dist/admin/editor/motion/MotionPanel.js +1 -1
  21. package/dist/admin/editor/motion/model.js +2 -2
  22. package/dist/admin/editor/renderField.d.ts +3 -1
  23. package/dist/admin/editor/renderField.js +13 -4
  24. package/dist/admin/editor/runtime.js +1 -0
  25. package/dist/admin/editor/styles/SiteClasses.d.ts +9 -0
  26. package/dist/admin/editor/styles/SiteClasses.js +31 -0
  27. package/dist/admin/editor/styles/StylesPanel.d.ts +3 -1
  28. package/dist/admin/editor/styles/StylesPanel.js +9 -6
  29. package/dist/admin/editor/styles/context.d.ts +9 -2
  30. package/dist/admin/editor/styles/context.js +14 -9
  31. package/dist/admin/editor/styles/controls.js +2 -2
  32. package/dist/admin/editor/styles/sections.js +1 -1
  33. package/dist/admin/editor/styles/styles.scss +54 -0
  34. package/dist/admin/editor/templates/Bindable.d.ts +13 -5
  35. package/dist/admin/editor/templates/Bindable.js +73 -17
  36. package/dist/admin/editor/templates/binding.d.ts +11 -4
  37. package/dist/admin/editor/templates/binding.js +23 -3
  38. package/dist/ai/prompt.js +8 -2
  39. package/dist/ai/tools.js +11 -2
  40. package/dist/blocks/builtins/carousel.d.ts +32 -0
  41. package/dist/blocks/builtins/carousel.js +122 -0
  42. package/dist/blocks/builtins/disclosure.d.ts +13 -0
  43. package/dist/blocks/builtins/disclosure.js +107 -0
  44. package/dist/blocks/builtins/faq.d.ts +17 -0
  45. package/dist/blocks/builtins/faq.js +88 -0
  46. package/dist/blocks/builtins/filterLink.d.ts +22 -0
  47. package/dist/blocks/builtins/filterLink.js +76 -0
  48. package/dist/blocks/builtins/headingId.d.ts +15 -0
  49. package/dist/blocks/builtins/headingId.js +36 -0
  50. package/dist/blocks/builtins/icon.d.ts +8 -0
  51. package/dist/blocks/builtins/icon.js +45 -0
  52. package/dist/blocks/builtins/index.d.ts +35 -0
  53. package/dist/blocks/builtins/index.js +50 -0
  54. package/dist/blocks/builtins/lightbox.d.ts +43 -0
  55. package/dist/blocks/builtins/lightbox.js +93 -0
  56. package/dist/blocks/builtins/mediaBackdrop.d.ts +11 -0
  57. package/dist/blocks/builtins/mediaBackdrop.js +79 -0
  58. package/dist/blocks/builtins/sectionRef.d.ts +26 -0
  59. package/dist/blocks/builtins/sectionRef.js +78 -0
  60. package/dist/blocks/builtins/shared.d.ts +33 -0
  61. package/dist/blocks/builtins/shared.js +70 -0
  62. package/dist/blocks/builtins/tableOfContents.d.ts +3 -0
  63. package/dist/blocks/builtins/tableOfContents.js +44 -0
  64. package/dist/blocks/defaults.d.ts +19 -1
  65. package/dist/blocks/defaults.js +413 -20
  66. package/dist/blocks/index.d.ts +4 -2
  67. package/dist/blocks/index.js +3 -1
  68. package/dist/core/attrs.d.ts +27 -0
  69. package/dist/core/attrs.js +132 -0
  70. package/dist/core/bindings.d.ts +122 -11
  71. package/dist/core/bindings.js +504 -19
  72. package/dist/core/blocks.d.ts +46 -1
  73. package/dist/core/blocks.js +136 -0
  74. package/dist/core/classes.d.ts +10 -2
  75. package/dist/core/classes.js +34 -5
  76. package/dist/core/headings.d.ts +21 -0
  77. package/dist/core/headings.js +47 -0
  78. package/dist/core/index.d.ts +4 -2
  79. package/dist/core/index.js +4 -2
  80. package/dist/core/motion.d.ts +18 -9
  81. package/dist/core/motion.js +20 -12
  82. package/dist/core/operations.js +59 -2
  83. package/dist/core/payloadBlocks.js +3 -1
  84. package/dist/core/schema.js +20 -0
  85. package/dist/core/tree.js +24 -1
  86. package/dist/core/types.d.ts +87 -0
  87. package/dist/core/validate.js +29 -4
  88. package/dist/css/tokens.d.ts +6 -3
  89. package/dist/css/tokens.js +48 -2
  90. package/dist/index.d.ts +3 -3
  91. package/dist/index.js +2 -2
  92. package/dist/mcp/index.d.ts +2 -0
  93. package/dist/mcp/index.js +50 -13
  94. package/dist/mcp/shared.d.ts +3 -0
  95. package/dist/mcp/shared.js +23 -8
  96. package/dist/plugin/index.d.ts +8 -0
  97. package/dist/plugin/index.js +26 -8
  98. package/dist/plugin/listCollections.d.ts +17 -2
  99. package/dist/plugin/listCollections.js +44 -7
  100. package/dist/plugin/references.d.ts +5 -0
  101. package/dist/plugin/references.js +1 -1
  102. package/dist/plugin/templates.d.ts +4 -0
  103. package/dist/plugin/templates.js +23 -4
  104. package/dist/protocol/index.d.ts +2 -0
  105. package/dist/react/canvas/BuilderCanvas.js +5 -3
  106. package/dist/react/canvas/fetchDocs.d.ts +16 -2
  107. package/dist/react/canvas/fetchDocs.js +42 -9
  108. package/dist/react/canvas/measure.d.ts +3 -1
  109. package/dist/react/canvas/measure.js +26 -2
  110. package/dist/react/canvas/resolveLayout.d.ts +1 -1
  111. package/dist/react/canvas/resolveLayout.js +17 -6
  112. package/dist/react/canvas/serverBlocks.d.ts +11 -0
  113. package/dist/react/canvas/serverBlocks.js +28 -1
  114. package/dist/react/components/Button.d.ts +11 -2
  115. package/dist/react/components/Button.js +43 -6
  116. package/dist/react/components/CollectionList.d.ts +6 -3
  117. package/dist/react/components/CollectionList.js +21 -7
  118. package/dist/react/components/Container.js +4 -1
  119. package/dist/react/components/Field.js +13 -2
  120. package/dist/react/components/Heading.js +9 -2
  121. package/dist/react/components/Image.d.ts +9 -0
  122. package/dist/react/components/Image.js +16 -1
  123. package/dist/react/components/List.d.ts +1 -0
  124. package/dist/react/components/List.js +6 -0
  125. package/dist/react/components/Menu.d.ts +16 -0
  126. package/dist/react/components/Menu.js +83 -19
  127. package/dist/react/components/RichText.d.ts +8 -3
  128. package/dist/react/components/RichText.js +25 -4
  129. package/dist/react/components/builtins/Accordion.d.ts +9 -0
  130. package/dist/react/components/builtins/Accordion.js +37 -0
  131. package/dist/react/components/builtins/BackdropVideo.d.ts +13 -0
  132. package/dist/react/components/builtins/BackdropVideo.js +16 -0
  133. package/dist/react/components/builtins/Carousel.d.ts +13 -0
  134. package/dist/react/components/builtins/Carousel.js +134 -0
  135. package/dist/react/components/builtins/Disclosure.d.ts +7 -0
  136. package/dist/react/components/builtins/Disclosure.js +13 -0
  137. package/dist/react/components/builtins/FilterLink.d.ts +8 -0
  138. package/dist/react/components/builtins/FilterLink.js +30 -0
  139. package/dist/react/components/builtins/Icon.d.ts +14 -0
  140. package/dist/react/components/builtins/Icon.js +28 -0
  141. package/dist/react/components/builtins/Lightbox.d.ts +45 -0
  142. package/dist/react/components/builtins/Lightbox.js +252 -0
  143. package/dist/react/components/builtins/MediaBackdrop.d.ts +14 -0
  144. package/dist/react/components/builtins/MediaBackdrop.js +61 -0
  145. package/dist/react/components/builtins/SectionRef.d.ts +7 -0
  146. package/dist/react/components/builtins/SectionRef.js +17 -0
  147. package/dist/react/components/builtins/TableOfContents.d.ts +7 -0
  148. package/dist/react/components/builtins/TableOfContents.js +21 -0
  149. package/dist/react/components/builtins/glyphs.d.ts +8 -0
  150. package/dist/react/components/builtins/glyphs.js +7 -0
  151. package/dist/react/components/builtins/index.d.ts +32 -0
  152. package/dist/react/components/builtins/index.js +36 -0
  153. package/dist/react/components/index.js +2 -0
  154. package/dist/react/index.d.ts +3 -1
  155. package/dist/react/index.js +3 -1
  156. package/dist/react/motion/runtime.js +10 -6
  157. package/dist/react/render/RenderLayout.d.ts +1 -1
  158. package/dist/react/render/RenderLayout.js +76 -23
  159. package/dist/react/render/lists.d.ts +107 -5
  160. package/dist/react/render/lists.js +284 -9
  161. package/dist/react/render/resolve.d.ts +22 -2
  162. package/dist/react/render/resolve.js +45 -22
  163. package/dist/react/render/sections.d.ts +9 -0
  164. package/dist/react/render/sections.js +51 -0
  165. package/dist/react/render/types.d.ts +6 -1
  166. package/dist/react/server.d.ts +3 -1
  167. package/dist/react/server.js +53 -2
  168. package/dist/react/theme/ThemeStyle.d.ts +13 -2
  169. package/dist/react/theme/ThemeStyle.js +12 -2
  170. package/package.json +1 -1
@@ -20,8 +20,22 @@ export const TEMPLATE_DEFAULT_FIELD = 'isDefault';
20
20
  export const TEMPLATE_PREVIEW_FIELD = 'previewDocument';
21
21
  /** Templates collection: the layout field. */
22
22
  export const TEMPLATE_LAYOUT_FIELD = 'layout';
23
+ /**
24
+ * Templates collection: an optional Payload `where` query against the document. A document
25
+ * without a template of its own uses the first published template (by name) whose conditions
26
+ * match it, before the default template.
27
+ */
28
+ export const TEMPLATE_CONDITIONS_FIELD = 'conditions';
23
29
  /** Template-enabled collections: the relationship to the document's own template. */
24
30
  export const DOCUMENT_TEMPLATE_FIELD = 'template';
31
+ /**
32
+ * A template's conditions as a `where` query, or `null` when it has none: only a plain object
33
+ * with at least one key counts (an empty object would match every document).
34
+ */
35
+ export function templateConditions(template) {
36
+ const value = template?.[TEMPLATE_CONDITIONS_FIELD];
37
+ return isPlainObject(value) && Object.keys(value).length > 0 ? value : null;
38
+ }
25
39
  /** Virtual binding path: the frontend URL of the context document (from the link resolver). */
26
40
  export const URL_PATH = '$url';
27
41
  /** The Field block: shows the context document's value at `props.path`. */
@@ -37,6 +51,32 @@ export const LIST_ITEM_SLOT = 'item';
37
51
  export const LIST_ITEMS_PROP = '$items';
38
52
  /** Runtime-only prop of the Field block: the resolved value. It is never stored. */
39
53
  export const FIELD_VALUE_PROP = 'value';
54
+ /**
55
+ * The repeat block: renders its `item` slot once per row of an array or hasMany field of the
56
+ * current document (`props.path`). The rows are its runtime-only `$items` prop.
57
+ */
58
+ export const REPEAT_BLOCK = 'repeat';
59
+ /** Collection list slot shown when the list has no documents. */
60
+ export const LIST_EMPTY_SLOT = 'empty';
61
+ /** The URL query parameter of a paginated list's page (`?page=3`). Filter links drop it. */
62
+ export const PAGE_PARAM = 'page';
63
+ /** Virtual binding path inside a repeat item: the row value itself (a document, an upload, a text). */
64
+ export const ITEM_PATH = '$item';
65
+ /** Virtual binding path inside a collection list or repeat item: the item number, from 1. */
66
+ export const INDEX_PATH = '$index';
67
+ /** Virtual path prefix inside a collection list or repeat item: the enclosing document (`$parent.name`). */
68
+ export const PARENT_PATH = '$parent';
69
+ /** Virtual path prefix: the page's own document (`$page.title`), also inside list and repeat items. */
70
+ export const PAGE_PATH = '$page';
71
+ /**
72
+ * Binding key that shows or hides the block: `"field"` shows it when the field is filled,
73
+ * `"!field"` when it is empty, `"field=value"` when it equals the value, `"field!=value"` when not.
74
+ */
75
+ export const VISIBLE_BINDING = '$visible';
76
+ /** True for the slot that repeats per item: the `item` slot of a collection list or a repeat. */
77
+ export function isRepeatSlot(type, slot) {
78
+ return slot === LIST_ITEM_SLOT && (type === COLLECTION_LIST_BLOCK || type === REPEAT_BLOCK);
79
+ }
40
80
  /** A `{ relationTo, value }` pair (polymorphic relationships). */
41
81
  function isRelationPair(value) {
42
82
  return isPlainObject(value) && typeof value.relationTo === 'string' && 'value' in value;
@@ -73,6 +113,51 @@ export function getByPath(doc, path) {
73
113
  }
74
114
  return current;
75
115
  }
116
+ const wholeNumber = (value) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined;
117
+ /**
118
+ * The rows of a repeat: the value at `props.path` in the context (an array field's rows, a hasMany
119
+ * field's documents, IDs or values; one value counts as one row), after `offset` and `limit`.
120
+ * The path may start with `$parent.` or `$page.`.
121
+ */
122
+ export function repeatRows(context, props) {
123
+ const path = typeof props?.path === 'string' ? props.path.trim() : '';
124
+ if (!path)
125
+ return [];
126
+ const value = pathValue(context, path);
127
+ const rows = (Array.isArray(value) ? value : [value]).filter((row) => row !== undefined && row !== null);
128
+ const offset = wholeNumber(props?.offset) ?? 0;
129
+ const limit = wholeNumber(props?.limit);
130
+ return rows.slice(offset, limit === undefined ? undefined : offset + limit);
131
+ }
132
+ /**
133
+ * The context one repeat row binds to: the row's own fields (an array row, or the related document
134
+ * of a relationship or upload), `$item` (the row value), `$index` (from 1), `$parent` (the
135
+ * enclosing document) and `$page`. `collection` is the related collection for `$url`; a
136
+ * `{ relationTo, value }` row names its own.
137
+ */
138
+ export function repeatRowContext(row, index, around, collection = '') {
139
+ const pair = isRelationPair(row);
140
+ const value = pair ? row.value : row;
141
+ return {
142
+ ...itemContext(around, index),
143
+ collection: pair ? row.relationTo : collection,
144
+ doc: isPlainObject(value) ? value : {},
145
+ item: value,
146
+ };
147
+ }
148
+ /** The context of one collection list item (a listed document). */
149
+ export function listItemContext(doc, index, around, collection) {
150
+ return { ...itemContext(around, index), collection, doc };
151
+ }
152
+ /** `$index`, `$parent` and `$page` of an item inside `around`. */
153
+ function itemContext(around, index) {
154
+ const out = { index: index + 1 };
155
+ if (around) {
156
+ out.parent = around.doc;
157
+ out.page = around.page ?? around.doc;
158
+ }
159
+ return out;
160
+ }
76
161
  /** True for values that count as "no value": the literal prop stays. */
77
162
  export function isMissing(value) {
78
163
  return value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0);
@@ -263,22 +348,324 @@ function setByPath(props, path, value) {
263
348
  const nested = isPlainObject(current) ? current : {};
264
349
  return { ...props, [key]: setByPath(nested, rest, value) };
265
350
  }
266
- /** The context document's value at a binding path (`$url` included). */
267
- export function bindingValue(context, path, options) {
351
+ /**
352
+ * The related collection of every relationship and upload field with one `relationTo`, at any
353
+ * depth of groups, named tabs and arrays (blocks fields are left out). Plain JSON: pass it to
354
+ * `RenderLayout` and `loadLayoutData` as `relations`. The plugin sends it to the canvas itself.
355
+ */
356
+ export function bindingRelations(collections) {
357
+ const out = {};
358
+ for (const collection of collections) {
359
+ const into = {};
360
+ walkRelations(collection.fields, '', into);
361
+ if (Object.keys(into).length > 0)
362
+ out[collection.slug] = into;
363
+ }
364
+ return out;
365
+ }
366
+ function walkRelations(fields, prefix, into) {
367
+ for (const field of dataFields(fields)) {
368
+ const path = prefix ? `${prefix}.${field.name}` : field.name;
369
+ if ((field.type === 'relationship' || field.type === 'upload') && typeof field.relationTo === 'string')
370
+ into[path] = field.relationTo;
371
+ else if (field.type === 'group' || field.type === 'array')
372
+ walkRelations(field.fields ?? [], path, into);
373
+ }
374
+ }
375
+ /** `<path>.$url`: the URL of the related document at `path`. */
376
+ const RELATED_URL_SUFFIX = `.${URL_PATH}`;
377
+ /**
378
+ * The collection of the document at `path` of the context document, by `relations`: each
379
+ * relationship on the way moves to its collection. Row numbers are skipped. Undefined when the
380
+ * path does not end on a relationship.
381
+ */
382
+ function relationOf(collection, path, relations) {
383
+ let current = collection;
384
+ let local = '';
385
+ for (const part of path.split('.')) {
386
+ if (/^\d+$/.test(part))
387
+ continue;
388
+ local = local ? `${local}.${part}` : part;
389
+ const next = relations?.[current]?.[local];
390
+ if (next) {
391
+ current = next;
392
+ local = '';
393
+ }
394
+ }
395
+ return local === '' && path !== '' ? current : undefined;
396
+ }
397
+ /**
398
+ * The value at one plain path: a field of the context document, or a virtual path: `$url`,
399
+ * `$item` (and `$item.url`), `$index`, `$parent.<path>`, `$page.<path>`.
400
+ */
401
+ function pathValue(context, path, options) {
268
402
  if (path === URL_PATH)
269
403
  return options?.url?.(context) ?? undefined;
270
- return getByPath(context.doc, path);
404
+ if (path.endsWith(RELATED_URL_SUFFIX)) {
405
+ const target = path.slice(0, -RELATED_URL_SUFFIX.length);
406
+ const value = pathValue(context, target, options);
407
+ const pair = isRelationPair(value);
408
+ const doc = pair ? value.value : value;
409
+ // Only a loaded document has the fields a URL needs (an id alone does not).
410
+ const head = target.split('.')[0];
411
+ const own = head === PARENT_PATH || head === PAGE_PATH || head === ITEM_PATH ? undefined : relationOf(context.collection, target, options?.relations);
412
+ const collection = pair ? value.relationTo : own;
413
+ if (!collection || !isPlainObject(doc))
414
+ return undefined;
415
+ return options?.url?.({ collection, doc }) ?? undefined;
416
+ }
417
+ const dot = path.indexOf('.');
418
+ const head = dot < 0 ? path : path.slice(0, dot);
419
+ const rest = dot < 0 ? '' : path.slice(dot + 1);
420
+ let root;
421
+ switch (head) {
422
+ case ITEM_PATH:
423
+ root = context.item;
424
+ break;
425
+ case INDEX_PATH:
426
+ return rest ? undefined : context.index;
427
+ case PARENT_PATH:
428
+ root = context.parent;
429
+ break;
430
+ case PAGE_PATH:
431
+ root = context.page ?? context.doc;
432
+ break;
433
+ default:
434
+ return getByPath(context.doc, path);
435
+ }
436
+ return rest ? getByPath(root, rest) : root;
437
+ }
438
+ const currencyFormats = new Map();
439
+ /** First sentence of plain text: up to the first ".", "!" or "?" followed by a space or the end. */
440
+ function firstSentence(text) {
441
+ const match = /^.*?[.!?](?=\s|$)/s.exec(text.trim());
442
+ return (match ? match[0] : text).trim();
443
+ }
444
+ /**
445
+ * Formatters for binding expressions (`price|currency:AUD`). Each takes a value that is not
446
+ * missing and returns text, or undefined when it cannot format the value.
447
+ */
448
+ export const BINDING_FORMATTERS = {
449
+ /** `date[:locale[:timeZone]]`, e.g. `date:en-AU:Australia/Brisbane`. Default `en`, UTC. */
450
+ date(value, [locale, timeZone]) {
451
+ const date = value instanceof Date ? value : typeof value === 'string' || typeof value === 'number' ? new Date(value) : null;
452
+ if (!date || Number.isNaN(date.getTime()))
453
+ return undefined;
454
+ try {
455
+ return new Intl.DateTimeFormat(locale || 'en', { dateStyle: 'medium', timeZone: timeZone || 'UTC' }).format(date);
456
+ }
457
+ catch {
458
+ return formatDate(date);
459
+ }
460
+ },
461
+ /** `currency[:code[:locale]]`, e.g. `currency:AUD` gives "$1,200". Whole amounts have no cents. */
462
+ currency(value, [code = 'USD', locale = 'en']) {
463
+ const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : Number.NaN;
464
+ if (!Number.isFinite(n))
465
+ return undefined;
466
+ const whole = Number.isInteger(n);
467
+ const key = `${code}\u0000${locale}\u0000${whole}`;
468
+ try {
469
+ let format = currencyFormats.get(key);
470
+ if (!format) {
471
+ format = new Intl.NumberFormat(locale, {
472
+ style: 'currency',
473
+ currency: code.toUpperCase(),
474
+ currencyDisplay: 'narrowSymbol',
475
+ ...(whole ? { minimumFractionDigits: 0, maximumFractionDigits: 0 } : {}),
476
+ });
477
+ currencyFormats.set(key, format);
478
+ }
479
+ return format.format(n);
480
+ }
481
+ catch {
482
+ return undefined;
483
+ }
484
+ },
485
+ /** `number[:locale]`: digit grouping, e.g. "1,200". */
486
+ number(value, [locale = 'en']) {
487
+ const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : Number.NaN;
488
+ if (!Number.isFinite(n))
489
+ return undefined;
490
+ try {
491
+ return new Intl.NumberFormat(locale).format(n);
492
+ }
493
+ catch {
494
+ return String(n);
495
+ }
496
+ },
497
+ /** `firstSentence`: the first sentence of the plain text (rich text too). */
498
+ firstSentence(value) {
499
+ const text = toPlainText(value);
500
+ return text ? firstSentence(text) : undefined;
501
+ },
502
+ };
503
+ /**
504
+ * A value through one formatter, written as in a binding: "currency:AUD", "date:en-AU:Australia/Brisbane",
505
+ * "number" or "firstSentence". Undefined for an unknown formatter, a missing value or a value the
506
+ * formatter cannot read. The field block's `format` prop uses it.
507
+ */
508
+ export function formatBindingValue(value, format) {
509
+ const formatter = formatterOf(format.trim());
510
+ if (!formatter || isMissing(value))
511
+ return undefined;
512
+ return BINDING_FORMATTERS[formatter.name](value, formatter.args);
513
+ }
514
+ /** One `|` part of an expression: a formatter (by name, after the first part) or a path. */
515
+ function formatterOf(part) {
516
+ const [name = '', ...args] = part.split(':');
517
+ return Object.hasOwn(BINDING_FORMATTERS, name) ? { name, args } : null;
518
+ }
519
+ /**
520
+ * One expression: paths separated by `|` (the first that is not missing wins), then formatters
521
+ * (`a|b|date:en-AU`). The first part is always a path.
522
+ */
523
+ function expressionValue(context, expression, options) {
524
+ const parts = expression.split('|').map((part) => part.trim());
525
+ let value;
526
+ let i = 0;
527
+ for (; i < parts.length; i++) {
528
+ if (i > 0 && formatterOf(parts[i]))
529
+ break;
530
+ if (isMissing(value))
531
+ value = pathValue(context, parts[i], options);
532
+ }
533
+ for (; i < parts.length; i++) {
534
+ const formatter = formatterOf(parts[i]);
535
+ if (!formatter)
536
+ continue;
537
+ if (isMissing(value))
538
+ return undefined;
539
+ value = BINDING_FORMATTERS[formatter.name](value, formatter.args);
540
+ }
541
+ return value;
542
+ }
543
+ const TEMPLATE = /\{\{([^{}]+)\}\}/g;
544
+ /** True when a binding is more than one plain path: a template string, a fallback chain or a formatter. */
545
+ export function isBindingExpression(binding) {
546
+ return binding.includes('{{') || binding.includes('|');
547
+ }
548
+ /**
549
+ * The value of a binding:
550
+ * - a path: `title`, `author.name`, or a virtual path (`$url`, `$item`, `$index`, `$parent.name`, `$page.title`);
551
+ * - a fallback chain: `heading|name` (the first value that is not missing);
552
+ * - formatters after the paths: `publishedAt|date:en-AU:Australia/Brisbane`, `price|currency:AUD`, `bio|firstSentence`;
553
+ * - a template string: `Enquire about {{name}}`. Each `{{expression}}` becomes text; a missing one
554
+ * becomes empty. When every one is missing, the value is missing (the literal prop stays).
555
+ */
556
+ export function bindingValue(context, binding, options) {
557
+ if (!binding.includes('{{'))
558
+ return expressionValue(context, binding, options);
559
+ let found = false;
560
+ const text = binding.replace(TEMPLATE, (_, expression) => {
561
+ const part = toPlainText(expressionValue(context, expression, options));
562
+ if (part === undefined)
563
+ return '';
564
+ found = true;
565
+ return part;
566
+ });
567
+ return found ? text : undefined;
568
+ }
569
+ /** The plain field paths a binding reads (no formatters, no virtual `$url`, `$item`, `$index`). */
570
+ export function bindingPaths(key, binding) {
571
+ const expressions = binding.includes('{{')
572
+ ? [...binding.matchAll(TEMPLATE)].map((m) => m[1])
573
+ : [key === VISIBLE_BINDING ? conditionOf(binding).path : binding];
574
+ return expressions.flatMap((expression) => expression
575
+ .split('|')
576
+ .map((part) => part.trim())
577
+ .filter((part, i) => part && (i === 0 || !formatterOf(part)))
578
+ .map((path) => (path.endsWith(RELATED_URL_SUFFIX) ? path.slice(0, -RELATED_URL_SUFFIX.length) : path))
579
+ .filter((path) => path !== URL_PATH && path.split('.')[0] !== ITEM_PATH && path !== INDEX_PATH));
580
+ }
581
+ /** The first operator wins, so a value may hold "=" or ">" (`title=a=b`). Two-character operators first. */
582
+ const COMPARISON = /^(.+?)\s*(>=|<=|!=|>|<|=)\s*(.*)$/s;
583
+ /** `path#`: the condition counts the items. */
584
+ const counts = (path) => path.endsWith('#');
585
+ const bare = (path) => (counts(path) ? path.slice(0, -1).trim() : path);
586
+ /**
587
+ * `field`, `!field`, `field=value`, `field!=value`, and for numbers `field>3`, `field>=3`,
588
+ * `field<3`, `field<=3`. `field#` is the number of items of a list (0 when empty, 1 for any other
589
+ * filled value), e.g. `galleryImages#>=3`.
590
+ */
591
+ function conditionOf(condition) {
592
+ const text = condition.trim();
593
+ const match = COMPARISON.exec(text);
594
+ if (match && match[1].trim() !== '!') {
595
+ const path = match[1].trim();
596
+ return { path: bare(path), test: match[2], value: match[3].trim(), count: counts(path) };
597
+ }
598
+ if (text.startsWith('!'))
599
+ return { path: bare(text.slice(1).trim()), test: 'empty', value: '', count: counts(text) };
600
+ return { path: bare(text), test: 'filled', value: '', count: counts(text) };
601
+ }
602
+ /** The number of items: a list's length, 0 for an empty value, 1 for any other value. */
603
+ function itemCount(value) {
604
+ if (Array.isArray(value))
605
+ return value.length;
606
+ return isMissing(value) || value === false ? 0 : 1;
607
+ }
608
+ /** A number from a number or a numeric text; null otherwise. */
609
+ function numberOf(value) {
610
+ if (typeof value === 'number')
611
+ return Number.isFinite(value) ? value : null;
612
+ if (typeof value !== 'string' || value.trim() === '')
613
+ return null;
614
+ const parsed = Number(value);
615
+ return Number.isFinite(parsed) ? parsed : null;
616
+ }
617
+ /** True when a value matches `expected`: itself, a document's id, or any item of a list. */
618
+ function matches(value, expected) {
619
+ if (Array.isArray(value))
620
+ return value.some((item) => matches(item, expected));
621
+ if (isRelationPair(value))
622
+ return matches(value.value, expected);
623
+ if (isPlainObject(value))
624
+ return value.id !== undefined && String(value.id) === expected;
625
+ return value !== undefined && value !== null && String(value) === expected;
626
+ }
627
+ /** True when the `$visible` condition holds for the context. `false` counts as empty. */
628
+ export function isVisible(context, condition, options) {
629
+ const { path, test, value: expected, count } = conditionOf(condition);
630
+ const raw = expressionValue(context, path, options);
631
+ const value = count ? itemCount(raw) : raw;
632
+ const filled = count ? value !== 0 : !isMissing(value) && value !== false;
633
+ if (test === 'filled')
634
+ return filled;
635
+ if (test === 'empty')
636
+ return !filled;
637
+ if (test === '=' || test === '!=')
638
+ return matches(value, expected) === (test === '=');
639
+ // Greater and less compare numbers only: a value that is not a number never passes.
640
+ const actual = numberOf(value);
641
+ const limit = numberOf(expected);
642
+ if (actual === null || limit === null)
643
+ return false;
644
+ if (test === '>')
645
+ return actual > limit;
646
+ if (test === '>=')
647
+ return actual >= limit;
648
+ if (test === '<')
649
+ return actual < limit;
650
+ return actual <= limit;
271
651
  }
272
652
  /**
273
653
  * Resolves one block's bindings (not its children). Bound props with a value take it; applied
274
- * bindings are removed from the result, unresolved ones stay. A Field block gets
275
- * `props.value`. Returns the same block when nothing changes.
654
+ * bindings are removed from the result, unresolved ones stay. A `$visible` binding that does not
655
+ * hold makes the block `hidden`. A Field block gets `props.value`, a repeat its rows (`$items`).
656
+ * Returns the same block when nothing changes.
276
657
  */
277
658
  export function resolveBlockBindings(block, context, definition, options) {
278
659
  let props = block.props ?? {};
279
660
  let changed = false;
280
661
  const left = {};
662
+ let hidden = false;
281
663
  for (const [propPath, fieldPath] of Object.entries(block.bindings ?? {})) {
664
+ if (propPath === VISIBLE_BINDING) {
665
+ hidden = !isVisible(context, fieldPath, options);
666
+ changed = true;
667
+ continue;
668
+ }
282
669
  const field = definition ? propField(definition.fields, propPath) : undefined;
283
670
  const value = coerceValue(bindingValue(context, fieldPath, options), field);
284
671
  if (value === undefined) {
@@ -302,9 +689,15 @@ export function resolveBlockBindings(block, context, definition, options) {
302
689
  changed = true;
303
690
  }
304
691
  }
692
+ if (block.type === REPEAT_BLOCK) {
693
+ props = { ...props, [LIST_ITEMS_PROP]: repeatRows(context, props) };
694
+ changed = true;
695
+ }
305
696
  if (!changed)
306
697
  return block;
307
698
  const next = { ...block, props };
699
+ if (hidden)
700
+ next.hidden = true;
308
701
  if (Object.keys(left).length > 0)
309
702
  next.bindings = left;
310
703
  else
@@ -312,9 +705,10 @@ export function resolveBlockBindings(block, context, definition, options) {
312
705
  return next;
313
706
  }
314
707
  /**
315
- * Resolves every block's bindings against the context document. The `item` slot of a collection
316
- * list is left alone: its blocks bind to each listed document at render time. Applied bindings are
317
- * removed, so resolving twice is safe. Never mutates.
708
+ * Resolves every block's bindings against the context document. Repeats get their rows
709
+ * (`$items`). The `item` slot of a collection list or a repeat is left alone: its blocks bind to
710
+ * each listed document or row at render time. Applied bindings are removed, so resolving twice
711
+ * is safe. Never mutates.
318
712
  */
319
713
  export function resolveBindings(layout, context, blocks, options) {
320
714
  const definitions = new Map(blocks.map((d) => [d.type, d]));
@@ -324,7 +718,7 @@ export function resolveBindings(layout, context, blocks, options) {
324
718
  return next;
325
719
  const slots = Object.fromEntries(Object.entries(next.slots).map(([name, children]) => [
326
720
  name,
327
- next.type === COLLECTION_LIST_BLOCK && name === LIST_ITEM_SLOT ? children : visit(children),
721
+ isRepeatSlot(next.type, name) ? children : visit(children),
328
722
  ]));
329
723
  return { ...next, slots };
330
724
  });
@@ -404,23 +798,115 @@ export function bindingProblem(fields, propPath, source) {
404
798
  return 'one-line text cannot show rich text';
405
799
  return null;
406
800
  }
801
+ /** `fields` with the `prefix.` taken off every path (children included). */
802
+ function relativeTo(fields, prefix) {
803
+ return fields.map((field) => {
804
+ const out = { ...field, path: field.path.startsWith(`${prefix}.`) ? field.path.slice(prefix.length + 1) : field.path };
805
+ if (field.children)
806
+ out.children = relativeTo(field.children, prefix);
807
+ return out;
808
+ });
809
+ }
810
+ /** `fields` under a virtual root (`$parent`, `$page`) as one group, without other virtual paths. Null when empty. */
811
+ function underRoot(root, label, fields) {
812
+ const own = (fields ?? []).filter((field) => !field.path.startsWith('$'));
813
+ if (own.length === 0)
814
+ return null;
815
+ const prefix = (list) => list.map((field) => {
816
+ const out = { ...field, path: `${root}.${field.path}` };
817
+ if (field.children)
818
+ out.children = prefix(field.children);
819
+ return out;
820
+ });
821
+ return { path: root, label, type: 'group', children: prefix(own) };
822
+ }
823
+ /**
824
+ * The bindable fields inside a list block's `item` slot. A collection list: its collection's
825
+ * sources. A repeat: `$item`, `$index`, the row's fields (the related collection's sources for a
826
+ * relationship or upload to one collection, with `$url` only when the repeat's `collection` names
827
+ * it; else the field's children, an array row) and `$parent` (the fields around it). Both get
828
+ * `$page` (the page document's `page` fields) when given. `fields` are the sources around the
829
+ * block. Undefined when unknown.
830
+ */
831
+ export function itemSources(block, fields, sources, page) {
832
+ const pageGroup = underRoot(PAGE_PATH, 'Page', page);
833
+ if (block.type === COLLECTION_LIST_BLOCK) {
834
+ const collection = block.props?.collection;
835
+ const listed = typeof collection === 'string' && collection ? sources[collection] : undefined;
836
+ return listed ? [...listed, ...(pageGroup ? [pageGroup] : [])] : undefined;
837
+ }
838
+ const path = typeof block.props?.path === 'string' ? block.props.path.trim() : '';
839
+ const field = path && fields ? findBindingField(fields, path) : undefined;
840
+ if (!field)
841
+ return undefined;
842
+ const relationTo = typeof field.relationTo === 'string' ? field.relationTo : undefined;
843
+ const related = relationTo
844
+ ? sources[relationTo]?.filter((f) => f.path !== URL_PATH || block.props?.collection === relationTo)
845
+ : undefined;
846
+ const { hasMany: _hasMany, children: _children, ...row } = field;
847
+ const parentGroup = underRoot(PARENT_PATH, 'Enclosing document', fields);
848
+ return [
849
+ { ...row, path: ITEM_PATH, label: 'This row' },
850
+ { path: INDEX_PATH, label: 'Row number', type: 'number' },
851
+ ...(related ?? relativeTo(field.children ?? [], field.path)),
852
+ ...(parentGroup ? [parentGroup] : []),
853
+ ...(pageGroup ? [pageGroup] : []),
854
+ ];
855
+ }
856
+ /** The collection lists and repeats whose `item` slot holds the block, outermost first. */
857
+ export function repeatAncestors(layout, id) {
858
+ const path = [];
859
+ const visit = (blocks) => {
860
+ for (const block of blocks) {
861
+ if (block.id === id)
862
+ return true;
863
+ for (const [slot, children] of Object.entries(block.slots ?? {})) {
864
+ path.push({ block, slot });
865
+ if (visit(children))
866
+ return true;
867
+ path.pop();
868
+ }
869
+ }
870
+ return false;
871
+ };
872
+ if (!visit(layout.blocks))
873
+ return [];
874
+ return path.filter(({ block, slot }) => isRepeatSlot(block.type, slot)).map(({ block }) => block);
875
+ }
876
+ /**
877
+ * The bindable fields a block reads: the template collection's sources, narrowed by every
878
+ * collection list and repeat around it. Undefined when unknown (no collection, or a repeat path
879
+ * missing from the sources).
880
+ */
881
+ export function scopeSources(layout, id, sources, collection) {
882
+ const page = collection ? sources[collection] : undefined;
883
+ let fields = page?.slice();
884
+ for (const repeat of repeatAncestors(layout, id))
885
+ fields = itemSources(repeat, fields, sources, page);
886
+ return fields;
887
+ }
407
888
  /**
408
889
  * Checks every binding against the bindable fields of the document it reads: the template's
409
- * target collection, or inside a collection list's `item` slot, the listed collection. Problems
410
- * have the code `binding` (they block publishing only). Paths missing from `sources` are left
411
- * alone: the renderer keeps the literal value.
890
+ * target collection, inside a collection list's `item` slot the listed collection, and inside a
891
+ * repeat's `item` slot the row (`itemSources`). Problems have the code `binding` (they block
892
+ * publishing only). Paths missing from `sources` are left alone: the renderer keeps the literal
893
+ * value. `$item`, `$index`, `$visible` and expressions are always allowed.
412
894
  */
413
895
  export function validateBindings(layout, blocks, sources, collection) {
414
896
  const definitions = new Map(blocks.map((d) => [d.type, d]));
415
897
  const errors = [];
416
- const visit = (list, path, scope) => {
898
+ const visit = (list, path, fields) => {
417
899
  list.forEach((block, i) => {
418
900
  const at = `${path}[${i}]`;
419
901
  const definition = definitions.get(block.type);
420
- const fields = scope ? sources[scope] : undefined;
421
902
  if (definition && fields) {
422
903
  for (const [propPath, fieldPath] of Object.entries(block.bindings ?? {})) {
423
- const source = fieldPath === URL_PATH ? { path: URL_PATH, label: 'Page URL', type: 'text' } : findBindingField(fields, fieldPath);
904
+ // Expressions (templates, fallbacks, formatters), `$visible` and the row's own value are not checked.
905
+ if (propPath === VISIBLE_BINDING || isBindingExpression(fieldPath))
906
+ continue;
907
+ if (fieldPath.split('.')[0] === ITEM_PATH || fieldPath === INDEX_PATH)
908
+ continue;
909
+ const source = fieldPath === URL_PATH || fieldPath.endsWith(RELATED_URL_SUFFIX) ? { path: URL_PATH, label: 'Page URL', type: 'text' } : findBindingField(fields, fieldPath);
424
910
  if (!source)
425
911
  continue;
426
912
  const problem = bindingProblem(definition.fields, propPath, source);
@@ -430,12 +916,11 @@ export function validateBindings(layout, blocks, sources, collection) {
430
916
  }
431
917
  }
432
918
  for (const [name, children] of Object.entries(block.slots ?? {})) {
433
- const listed = block.type === COLLECTION_LIST_BLOCK && name === LIST_ITEM_SLOT;
434
- const next = listed ? (typeof block.props?.collection === 'string' ? block.props.collection : null) : scope;
435
- visit(children, `${at}.slots.${name}`, next);
919
+ visit(children, `${at}.slots.${name}`, isRepeatSlot(block.type, name) ? itemSources(block, fields, sources, page) : fields);
436
920
  }
437
921
  });
438
922
  };
439
- visit(layout.blocks, 'blocks', collection);
923
+ const page = collection ? sources[collection] : undefined;
924
+ visit(layout.blocks, 'blocks', page);
440
925
  return errors;
441
926
  }
@@ -1,5 +1,5 @@
1
1
  import { type IndexedBlock } from './tree.js';
2
- import type { Block, BlockDefinition, Layout, SlotDefinition } from './types.js';
2
+ import type { Block, BlockDefinition, Layout, SectionDefinition, SectionVariant, SlotDefinition } from './types.js';
3
3
  /**
4
4
  * True when the slot accepts the block type as a direct child: `allow` undefined or containing "*"
5
5
  * accepts any type, and `disallow` must not list it. Ancestor slots are not checked here; use
@@ -18,6 +18,51 @@ export declare function fitsParent(blocks: readonly BlockDefinition[], type: str
18
18
  */
19
19
  export declare function starterSlots(blocks: readonly BlockDefinition[], type: string, makeId: () => string): Record<string, Block[]> | null;
20
20
  export declare function defineBlock<T extends BlockDefinition>(def: T): T;
21
+ /** A block in `defineSection` input: like `Block`, but `id` may be left out (here and in every slot). */
22
+ export type SectionBlockInput = Omit<Block, 'id' | 'slots'> & {
23
+ id?: string;
24
+ slots?: Record<string, SectionBlockInput[]>;
25
+ };
26
+ /** `defineSection` input: a `SectionDefinition` whose blocks (and its variants' blocks) may leave out `id`. */
27
+ export type SectionInput = Omit<SectionDefinition, 'blocks' | 'variants'> & {
28
+ blocks: SectionBlockInput[];
29
+ variants?: (Omit<SectionVariant, 'blocks'> & {
30
+ blocks: SectionBlockInput[];
31
+ })[];
32
+ };
33
+ /**
34
+ * A section with every missing block id filled: `<section id>_1`, `_2`, … in walk order (each
35
+ * block before its slots, slots in their order), skipping ids that are given. A variant's blocks
36
+ * get `<section id>_<variant id>_1`, … The same input always gives the same ids. Throws when `id`
37
+ * or `label` is missing (also on a variant), two variants share an id, or two blocks of one tree
38
+ * share an id.
39
+ */
40
+ export declare function defineSection(input: SectionInput): SectionDefinition;
41
+ /**
42
+ * The sections with each variant as a section of its own, right after its section: id
43
+ * `<section id>/<variant id>`, label `<section label> (<variant label>)`, the section's category,
44
+ * its description unless the variant has one, and `variantOf` set to the section id. The section
45
+ * itself stays the first version and loses its `variants` key. The plugin and `builderMcpTools`
46
+ * run it on the app's `sections`, so the library, the insert picker, MCP and the assistant all
47
+ * list the variants. Throws on a variant without id or label, or two variants with one id.
48
+ */
49
+ export declare function sectionsWithVariants(sections: readonly SectionDefinition[]): SectionDefinition[];
50
+ /**
51
+ * The blocks with each block's `defaultClassName` filled where the block has no `className` key, at
52
+ * any depth. A `className` of `''` stays empty. Blocks of unknown types stay as they are. The
53
+ * plugin and `builderMcpTools` run it on the app's `sections`, so a section tree may leave out a
54
+ * block's default classes. Seeds that build layouts by hand can run it too.
55
+ */
56
+ export declare function withDefaultClassNames(list: readonly Block[], definitions: readonly BlockDefinition[]): Block[];
57
+ /** `withDefaultClassNames` on the blocks of every section and its variants. */
58
+ export declare function sectionsWithDefaultClassNames(sections: readonly SectionDefinition[], definitions: readonly BlockDefinition[]): SectionDefinition[];
59
+ /**
60
+ * The blocks with every `allowInline` slot accepting the block types marked `inline: true`: they
61
+ * join the slot's `allow` list. The plugin and `builderMcpTools` run it on their block list, so
62
+ * the editor, the checks and the AI tools all see the same rule. Returns the same list when no
63
+ * block is inline.
64
+ */
65
+ export declare function withInlineBlocks(blocks: BlockDefinition[]): BlockDefinition[];
21
66
  export declare function getBlockDefinition(blocks: readonly BlockDefinition[], type: string): BlockDefinition | undefined;
22
67
  /** Slot names of a block type, in declared order. */
23
68
  export declare function slotNames(def: BlockDefinition | undefined): string[];