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
@@ -1,7 +1,8 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Fragment, memo } from 'react';
3
- import { blocksHaveMotion, COLLECTION_LIST_BLOCK, motionAttributes, staggersChildren, LIST_ITEM_SLOT, LIST_ITEMS_PROP, resolveBlockBindings, } from '../../core/index.js';
4
- import { defaultBlocks, isLinkField, withBuilderCssClass } from '../../blocks/index.js';
3
+ import { blocksHaveMotion, COLLECTION_LIST_BLOCK, htmlAttributes, isRepeatSlot, LIST_EMPTY_SLOT, listItemContext, motionAttributes, staggersChildren, LIST_ITEM_SLOT, LIST_ITEMS_PROP, repeatRowContext, resolveBlockBindings, } from '../../core/index.js';
4
+ import { defaultBlocks, isLinkField, SECTION_REF_SLOT, withBuilderCssClass } from '../../blocks/index.js';
5
+ import { classFields } from '../../core/classes.js';
5
6
  import { defaultComponents } from '../components/index.js';
6
7
  import { fieldFor } from '../components/Field.js';
7
8
  import { richTextFor } from '../components/RichText.js';
@@ -56,26 +57,39 @@ function renderSlot(block, slot, ctx) {
56
57
  return null;
57
58
  return (_jsx("div", { "data-slot-empty": "", "data-slot-owner": block.id, "data-slot": slot, style: PLACEHOLDER_STYLE }));
58
59
  }
60
+ /** The contexts a list block's `item` slot renders with: one per listed document or repeat row. */
61
+ function repeatContexts(block, around) {
62
+ const collection = typeof block.props?.collection === 'string' ? block.props.collection : '';
63
+ if (block.type === COLLECTION_LIST_BLOCK)
64
+ return listItemsOf(block.props).map((doc, i) => listItemContext(doc, i, around, collection));
65
+ const rows = block.props?.[LIST_ITEMS_PROP];
66
+ return Array.isArray(rows) ? rows.map((row, i) => repeatRowContext(row, i, around, collection)) : [];
67
+ }
68
+ /** True when a collection list shows its `empty` slot: it has no documents. */
69
+ const showsEmpty = (block) => block.type === COLLECTION_LIST_BLOCK && listItemsOf(block.props).length === 0;
59
70
  /**
60
- * The `item` slot of a collection list, once per loaded document. Each repetition binds to its
61
- * own document. With no documents, the editor still shows the item design once.
71
+ * The `item` slot of a collection list (once per loaded document) or a repeat (once per row).
72
+ * Each repetition binds to its own document or row. On the canvas only the first one is
73
+ * editable; the others are repeats. With nothing to repeat, the editor still shows the item
74
+ * design once, and the site shows nothing.
62
75
  */
63
76
  function renderListItems(block, ctx) {
64
- const items = listItemsOf(block.props);
65
- const collection = typeof block.props?.collection === 'string' ? block.props.collection : '';
77
+ const contexts = repeatContexts(block, ctx.context);
66
78
  const children = block.slots?.[LIST_ITEM_SLOT] ?? [];
67
- if (items.length === 0) {
79
+ if (contexts.length === 0) {
68
80
  if (ctx.mode !== 'canvas')
69
81
  return null;
70
- return renderSlot(block, LIST_ITEM_SLOT, { ...ctx, context: { collection, doc: {} } });
82
+ const collection = block.type === COLLECTION_LIST_BLOCK && typeof block.props?.collection === 'string' ? block.props.collection : '';
83
+ return renderSlot(block, LIST_ITEM_SLOT, { ...ctx, context: listItemContext({}, 0, ctx.context, collection) });
71
84
  }
72
85
  if (children.length === 0)
73
86
  return renderSlot(block, LIST_ITEM_SLOT, ctx);
74
- return items.map((doc, i) => (_jsx(Fragment, { children: renderBlocks(children, {
87
+ return contexts.map((context, i) => (_jsx(Fragment, { children: renderBlocks(children, {
75
88
  ...ctx,
76
- context: { collection, doc },
89
+ context,
77
90
  repeat: ctx.repeat || (ctx.mode === 'canvas' && i > 0),
78
- }, staggersChildren(block.motion)) }, typeof doc.id === 'string' || typeof doc.id === 'number' ? doc.id : i)));
91
+ copy: ctx.copy || i > 0,
92
+ }, staggersChildren(block.motion)) }, typeof context.doc.id === 'string' || typeof context.doc.id === 'number' ? context.doc.id : i)));
79
93
  }
80
94
  /** The block's props with every link group resolved to plain data (`ResolvedLink`). */
81
95
  function componentPropsOf(block, ctx) {
@@ -85,8 +99,21 @@ function componentPropsOf(block, ctx) {
85
99
  const { [LIST_ITEMS_PROP]: _items, ...rest } = props;
86
100
  props = rest;
87
101
  }
88
- const fields = ctx.definitions.get(block.type)?.fields;
89
- return fields ? mapFieldValues(props, fields, ctx.resolveLinks) : props;
102
+ const definition = ctx.definitions.get(block.type);
103
+ const fields = definition?.fields;
104
+ const mapped = fields ? mapFieldValues(props, fields, ctx.resolveLinks) : props;
105
+ // Class props get the marker class, so the generated CSS reaches them. A missing one gets its default.
106
+ const own = classFields(definition);
107
+ if (own.length === 0)
108
+ return mapped;
109
+ const marked = { ...mapped };
110
+ for (const field of own) {
111
+ const fallback = field.defaultValue;
112
+ const value = field.name in marked ? marked[field.name] : fallback;
113
+ if (typeof value === 'string')
114
+ marked[field.name] = withBuilderCssClass(value);
115
+ }
116
+ return marked;
90
117
  }
91
118
  /**
92
119
  * One block. `preview`: the block renders on the server for the canvas (`renderPreviewBlock`).
@@ -101,6 +128,9 @@ function renderBlock(stored, ctx, preview = false, item = false) {
101
128
  const block = ctx.context
102
129
  ? resolveBlockBindings(stored, ctx.context, ctx.definitions.get(stored.type), ctx.binding)
103
130
  : stored;
131
+ // A `$visible` binding that does not hold hides the block (the canvas shows it dimmed).
132
+ if (block.hidden && !editor)
133
+ return null;
104
134
  const attributes = preview
105
135
  ? {}
106
136
  : editor
@@ -110,6 +140,13 @@ function renderBlock(stored, ctx, preview = false, item = false) {
110
140
  : {};
111
141
  if (editor && !preview && block.hidden)
112
142
  attributes['data-builder-hidden'] = 'true';
143
+ // The block's own HTML attributes (id, aria-label, aria-hidden). Copies of a list row leave out the id.
144
+ if (stored.attrs) {
145
+ const own = htmlAttributes(stored.attrs);
146
+ if (ctx.copy)
147
+ delete own.id;
148
+ Object.assign(attributes, own);
149
+ }
113
150
  // Animations: settings for the motion runtime (the canvas plays them only on request).
114
151
  if (!preview && (stored.motion || item))
115
152
  Object.assign(attributes, motionAttributes(stored.motion, item));
@@ -124,13 +161,28 @@ function renderBlock(stored, ctx, preview = false, item = false) {
124
161
  }
125
162
  const slots = {};
126
163
  const slotAttributes = {};
127
- const isList = block.type === COLLECTION_LIST_BLOCK;
164
+ const isList = isRepeatSlot(block.type, LIST_ITEM_SLOT);
128
165
  for (const slot of slotNamesOf(block, ctx)) {
166
+ if (slot === SECTION_REF_SLOT) {
167
+ // A live saved section: its blocks render as repeats on the canvas (the ref is what the
168
+ // editor selects), and its runtime slot is never a drop target.
169
+ slots[slot] = renderBlocks(block.slots?.[slot] ?? [], { ...ctx, repeat: ctx.repeat || canvas });
170
+ slotAttributes[slot] = {};
171
+ continue;
172
+ }
129
173
  if (preview)
130
174
  slots[slot] = _jsx(SlotOutlet, { name: slot });
175
+ else if (isRepeatSlot(block.type, slot))
176
+ slots[slot] = renderListItems(block, ctx);
177
+ else if (block.type === COLLECTION_LIST_BLOCK && slot === LIST_EMPTY_SLOT)
178
+ slots[slot] = showsEmpty(block) ? renderSlot(block, slot, ctx) : null;
131
179
  else
132
- slots[slot] = isList && slot === LIST_ITEM_SLOT ? renderListItems(block, ctx) : renderSlot(block, slot, ctx);
180
+ slots[slot] = renderSlot(block, slot, ctx);
133
181
  slotAttributes[slot] = editor ? { 'data-slot-owner': block.id, 'data-slot': slot } : {};
182
+ // A slot with its own element takes its own classes (`styles: true` on the slot).
183
+ const slotClass = ctx.definitions.get(block.type)?.slots?.[slot]?.styles ? withBuilderCssClass(stored.slotClassName?.[slot]) : undefined;
184
+ if (slotClass)
185
+ slotAttributes[slot].className = slotClass;
134
186
  }
135
187
  if (isList && !(LIST_ITEM_SLOT in slots)) {
136
188
  slots[LIST_ITEM_SLOT] = renderListItems(block, ctx);
@@ -151,16 +203,17 @@ function renderBlock(stored, ctx, preview = false, item = false) {
151
203
  componentProps.pageData = ctx.pageData;
152
204
  return _jsx(Component, { ...componentProps }, block.id);
153
205
  }
154
- function createContext(mode, components, blocks, resolveLink, context, pageData) {
206
+ function createContext(mode, components, blocks, resolveLink, context, pageData, relations = null) {
155
207
  return {
156
208
  mode,
157
209
  // The built-in rich text and Field blocks get the resolver through a closure, never through props.
158
210
  components: { ...defaultComponents, richText: richTextFor(resolveLink), field: fieldFor(resolveLink), ...components },
159
211
  definitions: new Map((blocks ?? DEFAULT_DEFINITIONS).map((definition) => [definition.type, definition])),
160
212
  resolveLinks: linkVisitor(resolveLink),
161
- binding: { url: urlResolver(resolveLink) },
213
+ binding: { url: urlResolver(resolveLink), ...(relations ? { relations } : {}) },
162
214
  context,
163
215
  repeat: false,
216
+ copy: false,
164
217
  pageData,
165
218
  };
166
219
  }
@@ -170,13 +223,13 @@ let canvasContext = null;
170
223
  * The render context. On the canvas it stays the same object while its inputs stay the same, so
171
224
  * memoized blocks can skip. The site builds a fresh one per render (nothing is kept between requests).
172
225
  */
173
- function contextFor(mode, components, blocks, resolveLink, context, pageData) {
226
+ function contextFor(mode, components, blocks, resolveLink, context, pageData, relations) {
174
227
  if (mode !== 'canvas')
175
- return createContext(mode, components, blocks, resolveLink, context, pageData);
176
- const inputs = [components, blocks, resolveLink, context, pageData];
228
+ return createContext(mode, components, blocks, resolveLink, context, pageData, relations);
229
+ const inputs = [components, blocks, resolveLink, context, pageData, relations];
177
230
  if (canvasContext && canvasContext.inputs.every((input, i) => input === inputs[i]))
178
231
  return canvasContext.ctx;
179
- canvasContext = { inputs, ctx: createContext(mode, components, blocks, resolveLink, context, pageData) };
232
+ canvasContext = { inputs, ctx: createContext(mode, components, blocks, resolveLink, context, pageData, relations) };
180
233
  return canvasContext.ctx;
181
234
  }
182
235
  function linkVisitor(resolveLink) {
@@ -188,8 +241,8 @@ function linkVisitor(resolveLink) {
188
241
  * With `context`, bound props and Field blocks read that document. Collection lists render their
189
242
  * `item` slot once per document (load them with `loadLayoutData`).
190
243
  */
191
- export function RenderLayout({ layout, components, css, mode = 'site', blocks, resolveLink = defaultResolveLink, context, pageData, }) {
192
- const ctx = contextFor(mode, components, blocks, resolveLink, context ?? null, pageData ?? null);
244
+ export function RenderLayout({ layout, components, css, mode = 'site', blocks, resolveLink = defaultResolveLink, context, pageData, relations, }) {
245
+ const ctx = contextFor(mode, components, blocks, resolveLink, context ?? null, pageData ?? null, relations ?? null);
193
246
  const motion = mode === 'site' && blocksHaveMotion(layout.blocks);
194
247
  return (_jsxs(_Fragment, { children: [_jsx(BuilderStyle, { css: css }), motion && _jsx(MotionStyle, { blocks: layout.blocks }), renderBlocks(layout.blocks, ctx), motion && _jsx(MotionRuntime, {})] }));
195
248
  }
@@ -1,4 +1,5 @@
1
- import { type Layout, type TemplateContext } from '../../core/index.js';
1
+ import type { Where } from 'payload';
2
+ import { PAGE_PARAM, type Layout, type TemplateContext } from '../../core/index.js';
2
3
  export type Doc = Record<string, unknown>;
3
4
  /** What one collection list block shows. */
4
5
  export type ListQuery = {
@@ -9,10 +10,111 @@ export type ListQuery = {
9
10
  sort: string;
10
11
  /** The id of the page's own document, left out of the list. */
11
12
  exclude?: string | number;
13
+ /** Payload `where`: the `filterField` filter and the block's static `where`, AND-ed. */
14
+ where?: Where;
15
+ /** True when the filter matches no documents (the current document has no values): do not query. */
16
+ none?: true;
17
+ /** Documents to skip after the sort (and after leaving out the current document). */
18
+ offset?: number;
19
+ /** Depth of related documents, when more than 1. */
20
+ depth?: 2;
21
+ /** Picked documents (`ids`): only these, in this order. `limit`, `offset`, `sort` and pages do not apply. */
22
+ ids?: Id[];
23
+ /** `sort: "$random"`: a shuffle of the newest 100 matches, then `offset` and `limit`. */
24
+ random?: true;
25
+ /** `paginate: "pages"`: the page to show, from 1 (the URL's `?page=`). */
26
+ page?: number;
27
+ /** The list's own page parameter (`pageParam`), when it is not `page`. */
28
+ pageParam?: string;
12
29
  };
13
- /** The query of every collection list block in the layout (also inside other lists' items). */
14
- export declare function listQueries(layout: Layout, context?: TemplateContext | null): ListQuery[];
15
- /** Puts the loaded documents on each list block as the runtime-only `$items` prop. Never mutates. */
16
- export declare function attachListItems(layout: Layout, items: ReadonlyMap<string, Doc[]>): Layout;
30
+ /** The runtime prop that carries a paginated list's page links (`ListPages`). Never stored. */
31
+ export declare const LIST_PAGES_PROP = "$pages";
32
+ export { PAGE_PARAM };
33
+ /** `sort` value that shuffles the list. */
34
+ export declare const RANDOM_SORT = "$random";
35
+ /**
36
+ * A paginated list's page links, for the collection list component. Long lists show the first,
37
+ * the last and the pages next to the current one; `gapBefore` marks a link after left-out pages.
38
+ */
39
+ export type ListPages = {
40
+ current: number;
41
+ links: Array<{
42
+ page: number;
43
+ href: string;
44
+ current: boolean;
45
+ gapBefore?: true;
46
+ }>;
47
+ };
48
+ /** The runtime prop of filter links that holds the page parameters of the layout's lists (`withPageParams`). */
49
+ export declare const LIST_PAGE_PARAMS_PROP = "$pageParams";
50
+ /** A list's page parameter: its `pageParam` prop when that is a valid name, else `page`. */
51
+ export declare function pageParamOf(props: Record<string, unknown> | undefined): string;
52
+ /**
53
+ * The pages a pager shows, in order: the first, the last, the current one and one on each side.
54
+ * A gap of a single page shows that page instead. Seven pages or fewer: all of them.
55
+ */
56
+ export declare function pageWindow(current: number, totalPages: number): number[];
57
+ /**
58
+ * The request's URL query, for collection lists' `queryFilters`: `URLSearchParams`, or the
59
+ * `searchParams` object of a Next.js page.
60
+ */
61
+ export type ListQueryParams = URLSearchParams | Record<string, string | string[] | undefined>;
62
+ /**
63
+ * Date tokens in where values: `$now`, `$now-30d`, `$now+12h` become ISO dates. `now` is rounded
64
+ * down to the minute, so the canvas cache keeps one key per minute.
65
+ */
66
+ export declare function withDateTokens<T>(value: T, now?: number): T;
67
+ /** How `filterField` relates the listed documents to the current document. */
68
+ export type ListFilterBy = 'current' | 'shared' | 'linked';
69
+ type Id = string | number;
70
+ /** The page of the URL query (`?page=3`, or the list's own `param`), from 1. */
71
+ export declare function pageOf(query?: ListQueryParams | null, param?: string): number;
72
+ /**
73
+ * The page links of a paginated list: `path?page=N` (or the list's own `param`) with the rest of
74
+ * the URL query kept (filters and other lists' pages), and no page param for page 1: page 1 of
75
+ * `/guides` is `/guides`. Without a `path` the links are relative (`?page=2`), and page 1 with no
76
+ * other values is `?`. Long lists get gaps (`pageWindow`). Empty with one page or fewer.
77
+ */
78
+ export declare function pageLinks(query: ListQueryParams | null | undefined, current: number, totalPages: number, param?: string, path?: string): ListPages;
79
+ /** What to ask Payload for: the number of documents, the sort and the page. */
80
+ export declare function listRequest(query: ListQuery): {
81
+ limit: number;
82
+ sort: string;
83
+ page?: number;
84
+ };
85
+ /**
86
+ * The loaded documents in the list's order: picked ids in pick order, a seeded shuffle for
87
+ * `$random` (the seed and the block id pick the order), else after `offset`, at most `limit`.
88
+ */
89
+ export declare function arrangeListDocs(docs: Doc[], query: ListQuery, seed?: number): Doc[];
90
+ /**
91
+ * The query of every collection list block in the layout (also inside other lists' items).
92
+ * `filterField` needs the current document (`context`); without one the list is unfiltered.
93
+ * `queryFilters` need the URL query (`query`); without one they are off (the canvas).
94
+ */
95
+ export declare function listQueries(layout: Layout, context?: TemplateContext | null, query?: ListQueryParams | null): ListQuery[];
96
+ /**
97
+ * Puts the loaded documents on each list block as the runtime-only `$items` prop, and a paginated
98
+ * list's page links as `$pages` (`pages`). Never mutates.
99
+ */
100
+ export declare function attachListItems(layout: Layout, items: ReadonlyMap<string, Doc[]>, pages?: ReadonlyMap<string, ListPages>): Layout;
101
+ /**
102
+ * Gives every filter link the page parameters of the layout's paginated lists that do not use
103
+ * `page` (`$pageParams`), so a new filter starts those lists at page 1 too. `page` is always
104
+ * dropped. Returns the same layout when no list has its own parameter.
105
+ */
106
+ export declare function withPageParams(layout: Layout, queries: readonly ListQuery[]): Layout;
107
+ /** One collection list of a loaded layout (`loadedLists`). */
108
+ export type LoadedList = {
109
+ blockId: string;
110
+ collection: string;
111
+ docs: Doc[];
112
+ };
113
+ /**
114
+ * The collection lists of a layout after `loadLayoutData`, with the documents each one shows, in
115
+ * order: for ItemList JSON-LD without a second query. Hidden blocks (and lists inside them) are
116
+ * left out. A list inside another list's item counts once.
117
+ */
118
+ export declare function loadedLists(layout: Layout): LoadedList[];
17
119
  /** The documents a list block carries (`$items`), or an empty list. */
18
120
  export declare function listItemsOf(props: Record<string, unknown> | undefined): Doc[];
@@ -1,12 +1,223 @@
1
1
  // Collection list blocks: which documents each one needs, and attaching the loaded documents.
2
2
  // Shared by `loadLayoutData` (Local API) and the canvas (REST).
3
- import { COLLECTION_LIST_BLOCK, LIST_ITEMS_PROP, walkBlocks, } from '../../core/index.js';
3
+ import { COLLECTION_LIST_BLOCK, getByPath, LIST_ITEMS_PROP, PAGE_PARAM, walkBlocks, } from '../../core/index.js';
4
+ import { FILTER_LINK_BLOCK } from '../../blocks/builtins/filterLink.js';
4
5
  import { isRecord } from './fields.js';
6
+ /** The runtime prop that carries a paginated list's page links (`ListPages`). Never stored. */
7
+ export const LIST_PAGES_PROP = '$pages';
8
+ export { PAGE_PARAM };
9
+ /** `sort` value that shuffles the list. */
10
+ export const RANDOM_SORT = '$random';
11
+ /** The runtime prop of filter links that holds the page parameters of the layout's lists (`withPageParams`). */
12
+ export const LIST_PAGE_PARAMS_PROP = '$pageParams';
13
+ /** A page parameter name: letters, digits, `_` and `-`. */
14
+ const PARAM_NAME = /^[\w-]+$/;
15
+ /** A list's page parameter: its `pageParam` prop when that is a valid name, else `page`. */
16
+ export function pageParamOf(props) {
17
+ const raw = typeof props?.pageParam === 'string' ? props.pageParam.trim() : '';
18
+ return PARAM_NAME.test(raw) ? raw : PAGE_PARAM;
19
+ }
20
+ /**
21
+ * The pages a pager shows, in order: the first, the last, the current one and one on each side.
22
+ * A gap of a single page shows that page instead. Seven pages or fewer: all of them.
23
+ */
24
+ export function pageWindow(current, totalPages) {
25
+ const shown = new Set([1, totalPages, current - 1, current, current + 1]);
26
+ const pages = [];
27
+ for (let page = 1; page <= totalPages; page++) {
28
+ // A gap of one page shows that page: "…" would take the same room.
29
+ if (totalPages <= 7 || shown.has(page) || (shown.has(page - 1) && shown.has(page + 1)))
30
+ pages.push(page);
31
+ }
32
+ return pages;
33
+ }
34
+ /** The values of one URL parameter: repeated (`?a=x&a=y`) or comma-separated (`?a=x,y`). */
35
+ function paramValues(query, param) {
36
+ const raw = query instanceof URLSearchParams ? query.getAll(param) : [].concat(query[param] ?? []);
37
+ return raw.flatMap((value) => value.split(',')).map((value) => value.trim()).filter(Boolean);
38
+ }
39
+ /**
40
+ * The `queryFilters` of a list for the URL query: `{ [param]: { [value]: Where } }`. Each present
41
+ * `param=value` adds its `Where`; values of one param are OR-ed, params are AND-ed. Unknown values
42
+ * are ignored.
43
+ */
44
+ function queryFiltersOf(filters, query) {
45
+ if (!query || !isRecord(filters))
46
+ return [];
47
+ const out = [];
48
+ for (const [param, byValue] of Object.entries(filters)) {
49
+ if (!isRecord(byValue))
50
+ continue;
51
+ const matched = paramValues(query, param)
52
+ .map((value) => (Object.hasOwn(byValue, value) ? byValue[value] : undefined))
53
+ .filter((where) => isRecord(where) && Object.keys(where).length > 0);
54
+ if (matched.length > 0)
55
+ out.push(matched.length === 1 ? matched[0] : { or: matched });
56
+ }
57
+ return out;
58
+ }
59
+ const DATE_TOKEN = /^\$now(?:([+-])(\d+)([dh]))?$/;
60
+ const UNIT_MS = { d: 86_400_000, h: 3_600_000 };
61
+ /**
62
+ * Date tokens in where values: `$now`, `$now-30d`, `$now+12h` become ISO dates. `now` is rounded
63
+ * down to the minute, so the canvas cache keeps one key per minute.
64
+ */
65
+ export function withDateTokens(value, now = Date.now()) {
66
+ const minute = Math.floor(now / 60_000) * 60_000;
67
+ const visit = (v) => {
68
+ if (typeof v === 'string') {
69
+ const match = DATE_TOKEN.exec(v);
70
+ if (!match)
71
+ return v;
72
+ const [, sign, amount, unit] = match;
73
+ const shift = sign ? (sign === '-' ? -1 : 1) * Number(amount) * UNIT_MS[unit] : 0;
74
+ return new Date(minute + shift).toISOString();
75
+ }
76
+ if (Array.isArray(v))
77
+ return v.map(visit);
78
+ if (isRecord(v))
79
+ return Object.fromEntries(Object.entries(v).map(([k, inner]) => [k, visit(inner)]));
80
+ return v;
81
+ };
82
+ return visit(value);
83
+ }
84
+ const isId = (value) => (typeof value === 'string' && value !== '') || (typeof value === 'number' && Number.isFinite(value));
85
+ /** The ids or values in a field value: populated documents, `{ relationTo, value }` pairs, primitives, single or many. */
86
+ function valuesOf(value) {
87
+ const out = new Set();
88
+ for (const item of Array.isArray(value) ? value : [value]) {
89
+ const inner = isRecord(item) && 'relationTo' in item && 'value' in item ? item.value : item;
90
+ const id = isRecord(inner) ? inner.id : inner;
91
+ if (isId(id))
92
+ out.add(id);
93
+ }
94
+ return [...out];
95
+ }
96
+ /**
97
+ * The `filterField` filter of a list on the current document's page, or `none` when it matches
98
+ * nothing. Undefined without a filter or without a current document (then the list is unfiltered).
99
+ */
100
+ function filterOf(props, context) {
101
+ const field = typeof props.filterField === 'string' ? props.filterField.trim() : '';
102
+ if (!field || !context)
103
+ return undefined;
104
+ const by = props.filterBy === 'shared' || props.filterBy === 'linked' ? props.filterBy : 'current';
105
+ if (by === 'current')
106
+ return isId(context.doc.id) ? { [field]: { in: [context.doc.id] } } : undefined;
107
+ const values = valuesOf(getByPath(context.doc, field));
108
+ if (values.length === 0)
109
+ return 'none';
110
+ return by === 'shared' ? { [field]: { in: values } } : { id: { in: values } };
111
+ }
112
+ /** The ids picked in `ids`: plain ids, populated documents or `{ relationTo, value }` pairs of this collection. */
113
+ function pickedIds(value, collection) {
114
+ if (!Array.isArray(value))
115
+ return [];
116
+ const out = new Set();
117
+ for (const item of value) {
118
+ if (isRecord(item) && 'relationTo' in item && 'value' in item && item.relationTo !== collection)
119
+ continue;
120
+ for (const id of valuesOf(item))
121
+ out.add(id);
122
+ }
123
+ return [...out];
124
+ }
125
+ /** The page of the URL query (`?page=3`, or the list's own `param`), from 1. */
126
+ export function pageOf(query, param = PAGE_PARAM) {
127
+ const raw = query ? paramValues(query, param)[0] : undefined;
128
+ const page = raw ? Number(raw) : 1;
129
+ return Number.isInteger(page) && page >= 1 ? page : 1;
130
+ }
131
+ /**
132
+ * The page links of a paginated list: `path?page=N` (or the list's own `param`) with the rest of
133
+ * the URL query kept (filters and other lists' pages), and no page param for page 1: page 1 of
134
+ * `/guides` is `/guides`. Without a `path` the links are relative (`?page=2`), and page 1 with no
135
+ * other values is `?`. Long lists get gaps (`pageWindow`). Empty with one page or fewer.
136
+ */
137
+ export function pageLinks(query, current, totalPages, param = PAGE_PARAM, path = '') {
138
+ const links = [];
139
+ if (totalPages <= 1)
140
+ return { current, links };
141
+ const base = new URLSearchParams();
142
+ if (query instanceof URLSearchParams)
143
+ for (const [key, value] of query)
144
+ base.append(key, value);
145
+ else if (query)
146
+ for (const [key, value] of Object.entries(query))
147
+ for (const one of [].concat(value ?? []))
148
+ base.append(key, one);
149
+ base.delete(param);
150
+ let previous = 0;
151
+ for (const page of pageWindow(current, totalPages)) {
152
+ const params = new URLSearchParams(base);
153
+ if (page > 1)
154
+ params.set(param, String(page));
155
+ const text = params.toString();
156
+ links.push({ page, href: text ? `${path}?${text}` : path || '?', current: page === current, ...(page > previous + 1 ? { gapBefore: true } : {}) });
157
+ previous = page;
158
+ }
159
+ return { current, links };
160
+ }
161
+ /** What to ask Payload for: the number of documents, the sort and the page. */
162
+ export function listRequest(query) {
163
+ if (query.ids)
164
+ return { limit: Math.max(query.ids.length, 1), sort: DEFAULT_SORT };
165
+ if (query.random)
166
+ return { limit: MAX_LIMIT, sort: DEFAULT_SORT };
167
+ if (query.page)
168
+ return { limit: query.limit, sort: query.sort, page: query.page };
169
+ return { limit: query.limit + (query.offset ?? 0), sort: query.sort };
170
+ }
171
+ /** A small seeded random number generator (mulberry32): the same seed gives the same order. */
172
+ function seededRandom(seed) {
173
+ let a = seed >>> 0;
174
+ return () => {
175
+ a = (a + 0x6d2b79f5) >>> 0;
176
+ let t = a;
177
+ t = Math.imul(t ^ (t >>> 15), t | 1);
178
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
179
+ return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
180
+ };
181
+ }
182
+ function hashText(text) {
183
+ let h = 2_166_136_261;
184
+ for (let i = 0; i < text.length; i++)
185
+ h = Math.imul(h ^ text.charCodeAt(i), 16_777_619);
186
+ return h >>> 0;
187
+ }
188
+ /**
189
+ * The loaded documents in the list's order: picked ids in pick order, a seeded shuffle for
190
+ * `$random` (the seed and the block id pick the order), else after `offset`, at most `limit`.
191
+ */
192
+ export function arrangeListDocs(docs, query, seed = 0) {
193
+ if (query.ids) {
194
+ const byId = new Map(docs.map((doc) => [String(doc.id), doc]));
195
+ return query.ids.map((id) => byId.get(String(id))).filter((doc) => doc !== undefined);
196
+ }
197
+ if (query.page)
198
+ return docs.slice(0, query.limit);
199
+ const offset = query.offset ?? 0;
200
+ if (!query.random)
201
+ return docs.slice(offset, offset + query.limit);
202
+ const random = seededRandom(seed ^ hashText(query.blockId));
203
+ const shuffled = docs.slice();
204
+ for (let i = shuffled.length - 1; i > 0; i--) {
205
+ const j = Math.floor(random() * (i + 1));
206
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
207
+ }
208
+ return shuffled.slice(offset, offset + query.limit);
209
+ }
5
210
  const DEFAULT_LIMIT = 3;
6
211
  const MAX_LIMIT = 100;
212
+ // ponytail: offsets load the skipped documents too; use Payload pages if lists need deep offsets.
213
+ const MAX_OFFSET = 100;
7
214
  const DEFAULT_SORT = '-createdAt';
8
- /** The query of every collection list block in the layout (also inside other lists' items). */
9
- export function listQueries(layout, context) {
215
+ /**
216
+ * The query of every collection list block in the layout (also inside other lists' items).
217
+ * `filterField` needs the current document (`context`); without one the list is unfiltered.
218
+ * `queryFilters` need the URL query (`query`); without one they are off (the canvas).
219
+ */
220
+ export function listQueries(layout, context, query) {
10
221
  const queries = [];
11
222
  walkBlocks(layout, (block) => {
12
223
  if (block.type !== COLLECTION_LIST_BLOCK)
@@ -17,22 +228,50 @@ export function listQueries(layout, context) {
17
228
  return;
18
229
  const rawLimit = typeof props.limit === 'number' && Number.isFinite(props.limit) ? Math.round(props.limit) : DEFAULT_LIMIT;
19
230
  const sort = typeof props.sort === 'string' && props.sort.trim() ? props.sort.trim() : DEFAULT_SORT;
20
- const query = { blockId: block.id, collection, limit: Math.min(Math.max(rawLimit, 1), MAX_LIMIT), sort };
231
+ const list = { blockId: block.id, collection, limit: Math.min(Math.max(rawLimit, 1), MAX_LIMIT), sort };
232
+ const ids = pickedIds(props.ids, collection).slice(0, MAX_LIMIT);
233
+ if (ids.length > 0)
234
+ list.ids = ids;
235
+ else if (sort === RANDOM_SORT)
236
+ list.random = true;
237
+ else if (props.paginate === 'pages') {
238
+ const param = pageParamOf(props);
239
+ list.page = pageOf(query, param);
240
+ if (param !== PAGE_PARAM)
241
+ list.pageParam = param;
242
+ }
21
243
  const id = context?.doc.id;
22
244
  const exclude = props.excludeCurrent !== false && context?.collection === collection;
23
245
  if (exclude && (typeof id === 'string' || typeof id === 'number'))
24
- query.exclude = id;
25
- queries.push(query);
246
+ list.exclude = id;
247
+ const offset = typeof props.offset === 'number' && Number.isFinite(props.offset) ? Math.min(Math.floor(props.offset), MAX_OFFSET) : 0;
248
+ if (offset > 0)
249
+ list.offset = offset;
250
+ if (String(props.depth) === '2')
251
+ list.depth = 2;
252
+ const filter = filterOf(props, context);
253
+ if (filter === 'none')
254
+ list.none = true;
255
+ const where = [filter, props.where, ...queryFiltersOf(props.queryFilters, query)].filter((w) => isRecord(w) && Object.keys(w).length > 0);
256
+ if (!list.none && where.length > 0)
257
+ list.where = withDateTokens(where.length === 1 ? where[0] : { and: where });
258
+ queries.push(list);
26
259
  });
27
260
  return queries;
28
261
  }
29
- /** Puts the loaded documents on each list block as the runtime-only `$items` prop. Never mutates. */
30
- export function attachListItems(layout, items) {
262
+ /**
263
+ * Puts the loaded documents on each list block as the runtime-only `$items` prop, and a paginated
264
+ * list's page links as `$pages` (`pages`). Never mutates.
265
+ */
266
+ export function attachListItems(layout, items, pages) {
31
267
  if (items.size === 0)
32
268
  return layout;
33
269
  const visit = (blocks) => blocks.map((block) => {
34
270
  const docs = items.get(block.id);
35
- const next = docs ? { ...block, props: { ...block.props, [LIST_ITEMS_PROP]: docs } } : block;
271
+ const links = pages?.get(block.id);
272
+ const next = docs
273
+ ? { ...block, props: { ...block.props, [LIST_ITEMS_PROP]: docs, ...(links?.links.length ? { [LIST_PAGES_PROP]: links } : {}) } }
274
+ : block;
36
275
  if (!next.slots)
37
276
  return next;
38
277
  return {
@@ -42,6 +281,42 @@ export function attachListItems(layout, items) {
42
281
  });
43
282
  return { ...layout, blocks: visit(layout.blocks) };
44
283
  }
284
+ /**
285
+ * Gives every filter link the page parameters of the layout's paginated lists that do not use
286
+ * `page` (`$pageParams`), so a new filter starts those lists at page 1 too. `page` is always
287
+ * dropped. Returns the same layout when no list has its own parameter.
288
+ */
289
+ export function withPageParams(layout, queries) {
290
+ const params = [...new Set(queries.flatMap((query) => (query.pageParam ? [query.pageParam] : [])))];
291
+ if (params.length === 0)
292
+ return layout;
293
+ const visit = (blocks) => blocks.map((block) => {
294
+ const next = block.type === FILTER_LINK_BLOCK ? { ...block, props: { ...block.props, [LIST_PAGE_PARAMS_PROP]: params } } : block;
295
+ if (!next.slots)
296
+ return next;
297
+ return { ...next, slots: Object.fromEntries(Object.entries(next.slots).map(([name, children]) => [name, visit(children)])) };
298
+ });
299
+ return { ...layout, blocks: visit(layout.blocks) };
300
+ }
301
+ /**
302
+ * The collection lists of a layout after `loadLayoutData`, with the documents each one shows, in
303
+ * order: for ItemList JSON-LD without a second query. Hidden blocks (and lists inside them) are
304
+ * left out. A list inside another list's item counts once.
305
+ */
306
+ export function loadedLists(layout) {
307
+ const out = [];
308
+ const seen = new Set();
309
+ walkBlocks(layout, (block) => {
310
+ if (block.hidden)
311
+ return false;
312
+ if (block.type !== COLLECTION_LIST_BLOCK || seen.has(block.id) || !Array.isArray(block.props?.[LIST_ITEMS_PROP]))
313
+ return;
314
+ seen.add(block.id);
315
+ const collection = typeof block.props?.collection === 'string' ? block.props.collection.trim() : '';
316
+ out.push({ blockId: block.id, collection, docs: listItemsOf(block.props) });
317
+ });
318
+ return out;
319
+ }
45
320
  /** The documents a list block carries (`$items`), or an empty list. */
46
321
  export function listItemsOf(props) {
47
322
  const value = props?.[LIST_ITEMS_PROP];