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,5 +1,6 @@
1
1
  import type { Payload } from 'payload';
2
- import { type BlockDefinition, type Layout, type TemplateContext } from '../../core/index.js';
2
+ import { type BindingRelations, type BlockDefinition, type Layout, type TemplateContext } from '../../core/index.js';
3
+ import { type ListQueryParams } from './lists.js';
3
4
  import type { FetchDocs, ResolveLink } from './types.js';
4
5
  import { type RenderLocale } from './locale.js';
5
6
  /** Replaces upload/relationship IDs in block props with documents, using `fetchDocs`. Never mutates. */
@@ -17,17 +18,36 @@ export type LoadLayoutOptions = RenderLocale & {
17
18
  context?: TemplateContext | null;
18
19
  /** The site's link resolver, for the `$url` binding path. `RenderLayout` resolves it otherwise. */
19
20
  resolveLink?: ResolveLink;
21
+ /** Which collection each relationship field points to (`bindingRelations`), for `<path>.$url` bindings. */
22
+ relations?: BindingRelations | null;
20
23
  /**
21
24
  * The visitor (the signed-in user, or none). Collection lists load their documents with this
22
25
  * user's access (`overrideAccess: false`), so a list never shows documents or populated fields
23
26
  * the visitor may not read, such as a user's email. Pass the user in draft mode.
24
27
  */
25
28
  user?: unknown;
29
+ /**
30
+ * The request's URL query (`URLSearchParams`, or a Next.js page's awaited `searchParams`).
31
+ * Collection lists apply their `queryFilters` with it. Without it the filters are off. A route
32
+ * that filters lists by the URL should send `noindex, follow` for filtered URLs.
33
+ */
34
+ query?: ListQueryParams | null;
35
+ /**
36
+ * The page's path (`/guides`). The page links of paginated lists start with it, so the link to
37
+ * page 1 is the bare path. Without it they are relative (`?page=2`, and `?` for page 1).
38
+ */
39
+ path?: string;
40
+ /**
41
+ * The seed of `sort: "$random"` lists: the same seed gives the same order. Default: a new seed
42
+ * per call, so a cached page shuffles once per cache build.
43
+ */
44
+ randomSeed?: number;
26
45
  };
27
46
  /**
28
47
  * Server helper: prepares a layout for `RenderLayout` with Payload's Local API.
48
+ * 0. Puts the current blocks of each live saved section (`sectionRef`) into the layout.
29
49
  * 1. Resolves bindings and Field blocks against `options.context` (when given).
30
- * 2. Loads every collection list's documents (`depth: 1`; published only unless `draft`), with the
50
+ * 2. Loads every collection list's documents (`depth: 1` or the list's `depth`; published only unless `draft`), with the
31
51
  * access of `options.user` (anonymous without it).
32
52
  * 3. Replaces upload/relationship IDs in block props with documents (one batched `find` per collection).
33
53
  */
@@ -1,8 +1,9 @@
1
1
  // Replaces upload/relationship IDs in block props with documents.
2
2
  import { resolveBindings } from '../../core/index.js';
3
3
  import { isRecord, mapFieldValues } from './fields.js';
4
- import { attachListItems, listQueries } from './lists.js';
4
+ import { arrangeListDocs, attachListItems, listQueries, listRequest, pageLinks, withPageParams } from './lists.js';
5
5
  import { localeArgs, localizeLayout } from './locale.js';
6
+ import { attachSections } from './sections.js';
6
7
  const isId = (value) => typeof value === 'string' || typeof value === 'number';
7
8
  /** Maps one relationship/upload value (single or hasMany, plain or polymorphic). */
8
9
  function mapReference(value, field, resolve) {
@@ -114,8 +115,9 @@ export function urlResolver(resolveLink) {
114
115
  }
115
116
  /**
116
117
  * Server helper: prepares a layout for `RenderLayout` with Payload's Local API.
118
+ * 0. Puts the current blocks of each live saved section (`sectionRef`) into the layout.
117
119
  * 1. Resolves bindings and Field blocks against `options.context` (when given).
118
- * 2. Loads every collection list's documents (`depth: 1`; published only unless `draft`), with the
120
+ * 2. Loads every collection list's documents (`depth: 1` or the list's `depth`; published only unless `draft`), with the
119
121
  * access of `options.user` (anonymous without it).
120
122
  * 3. Replaces upload/relationship IDs in block props with documents (one batched `find` per collection).
121
123
  */
@@ -124,17 +126,7 @@ export async function loadLayoutData(layout, blocks, payload, options) {
124
126
  const context = options?.context ?? null;
125
127
  // Localized sites: the layout and its documents in the render's locale (render/locale.ts).
126
128
  const locale = localeArgs(options);
127
- const localized = localizeLayout(layout, blocks, payload, options);
128
- const bound = context
129
- ? resolveBindings(localized, context, blocks, options?.resolveLink ? { url: urlResolver(options.resolveLink) } : undefined)
130
- : localized;
131
- const queries = listQueries(bound, context);
132
- const items = new Map();
133
- await Promise.all(queries.map(async (query) => {
134
- items.set(query.blockId, await findListItems(payload, query, draft, options?.user ?? null, locale));
135
- }));
136
- const withItems = attachListItems(bound, items);
137
- return resolveLayoutData(withItems, blocks, async (collection, ids) => {
129
+ const fetchDocs = async (collection, ids) => {
138
130
  const result = await payload.find({
139
131
  // The collection slug is dynamic, so it cannot match the generated slug union.
140
132
  collection: collection,
@@ -148,35 +140,66 @@ export async function loadLayoutData(layout, blocks, payload, options) {
148
140
  ...locale,
149
141
  });
150
142
  return new Map(result.docs.map((doc) => [doc.id, doc]));
151
- });
143
+ };
144
+ // Live saved sections first, so their blocks get the same bindings, lists and documents.
145
+ const withSections = await attachSections(layout, blocks, fetchDocs);
146
+ const localized = localizeLayout(withSections, blocks, payload, options);
147
+ const bound = context
148
+ ? resolveBindings(localized, context, blocks, {
149
+ ...(options?.resolveLink ? { url: urlResolver(options.resolveLink) } : {}),
150
+ ...(options?.relations ? { relations: options.relations } : {}),
151
+ })
152
+ : localized;
153
+ const queries = listQueries(bound, context, options?.query);
154
+ const items = new Map();
155
+ const pages = new Map();
156
+ const seed = options?.randomSeed ?? Math.floor(Math.random() * 4_294_967_296);
157
+ await Promise.all(queries.map(async (query) => {
158
+ const result = await findListItems(payload, query, draft, options?.user ?? null, locale);
159
+ items.set(query.blockId, arrangeListDocs(result.docs, query, seed));
160
+ if (query.page)
161
+ pages.set(query.blockId, pageLinks(options?.query, query.page, result.totalPages, query.pageParam, options?.path));
162
+ }));
163
+ const withItems = withPageParams(attachListItems(bound, items, pages), queries);
164
+ return resolveLayoutData(withItems, blocks, fetchDocs);
152
165
  }
153
- /** One collection list's documents. An unknown collection or a failed query gives an empty list. */
166
+ /**
167
+ * One collection list's documents. An unknown collection, a filter that matches nothing (`none`) or
168
+ * a failed query gives an empty list.
169
+ */
154
170
  async function findListItems(payload, query, draft, user, locale) {
155
171
  const config = payload.collections[query.collection]?.config;
156
- if (!config)
157
- return [];
172
+ if (!config || query.none)
173
+ return { docs: [], totalPages: 0 };
158
174
  const where = [];
159
175
  if (query.exclude !== undefined)
160
176
  where.push({ id: { not_equals: query.exclude } });
177
+ if (query.ids)
178
+ where.push({ id: { in: query.ids } });
179
+ if (query.where)
180
+ where.push(query.where);
181
+ const request = listRequest(query);
161
182
  if (!draft && config.versions?.drafts)
162
183
  where.push({ _status: { equals: 'published' } });
163
184
  try {
164
185
  const result = await payload.find({
165
186
  collection: query.collection,
166
187
  where: where.length > 0 ? { and: where } : {},
167
- sort: query.sort,
168
- limit: query.limit,
169
- depth: 1,
188
+ sort: request.sort,
189
+ // Payload has no offset: load the skipped documents too (`arrangeListDocs` drops them).
190
+ limit: request.limit,
191
+ ...(request.page ? { page: request.page } : {}),
192
+ depth: query.depth ?? 1,
170
193
  draft,
171
194
  // The visitor's access: unreadable documents and relationships stay out (or stay IDs).
172
195
  overrideAccess: false,
173
196
  user: user,
174
197
  ...locale,
175
198
  });
176
- return result.docs;
199
+ return { docs: result.docs, totalPages: result.totalPages ?? 1 };
177
200
  }
178
201
  catch (error) {
179
202
  payload.logger.error({ err: error, msg: `[builder] Collection list "${query.collection}" failed to load.` });
180
- return [];
203
+ return { docs: [], totalPages: 0 };
181
204
  }
182
205
  }
@@ -0,0 +1,9 @@
1
+ import type { BlockDefinition, Layout } from '../../core/index.js';
2
+ import type { FetchDocs } from './types.js';
3
+ /**
4
+ * Fills the runtime slot (`SECTION_REF_SLOT`) of every `sectionRef` block with its saved section's
5
+ * blocks, loaded with `fetchDocs` (one call). One level: a sectionRef inside a saved section stays
6
+ * empty, so a section can never include itself. A missing section leaves the slot out. Returns
7
+ * the same layout when there is nothing to load. Never mutates.
8
+ */
9
+ export declare function attachSections(layout: Layout, blocks: readonly BlockDefinition[], fetchDocs: FetchDocs): Promise<Layout>;
@@ -0,0 +1,51 @@
1
+ // Live saved sections: puts the current blocks of each `sectionRef` block's saved section into its
2
+ // runtime slot, before the rest of the data loading (so the section's lists, images and
3
+ // translations load like the page's own). Shared by `loadLayoutData` and the canvas.
4
+ import { SECTION_REF_BLOCK, SECTION_REF_SLOT, sectionRefBlocks, sectionRefId } from '../../blocks/builtins/sectionRef.js';
5
+ /** The collection the sectionRef definition's `section` field points at. */
6
+ function sectionsCollectionOf(blocks) {
7
+ const field = blocks.find((def) => def.type === SECTION_REF_BLOCK)?.fields.find((f) => 'name' in f && f.name === 'section');
8
+ const relationTo = field && 'relationTo' in field ? field.relationTo : null;
9
+ return typeof relationTo === 'string' ? relationTo : null;
10
+ }
11
+ function collectIds(blocks, ids) {
12
+ for (const block of blocks) {
13
+ if (block.type === SECTION_REF_BLOCK) {
14
+ const id = sectionRefId(block.props?.section);
15
+ if (id !== null)
16
+ ids.add(id);
17
+ }
18
+ for (const list of Object.values(block.slots ?? {}))
19
+ collectIds(list, ids);
20
+ }
21
+ }
22
+ /**
23
+ * Fills the runtime slot (`SECTION_REF_SLOT`) of every `sectionRef` block with its saved section's
24
+ * blocks, loaded with `fetchDocs` (one call). One level: a sectionRef inside a saved section stays
25
+ * empty, so a section can never include itself. A missing section leaves the slot out. Returns
26
+ * the same layout when there is nothing to load. Never mutates.
27
+ */
28
+ export async function attachSections(layout, blocks, fetchDocs) {
29
+ const collection = sectionsCollectionOf(blocks);
30
+ if (!collection)
31
+ return layout;
32
+ const ids = new Set();
33
+ collectIds(layout.blocks, ids);
34
+ if (ids.size === 0)
35
+ return layout;
36
+ const docs = await fetchDocs(collection, [...ids]);
37
+ const docOf = (id) => docs.get(id) ?? docs.get(String(id)) ?? docs.get(Number(id));
38
+ const fill = (list) => list.map((block) => {
39
+ if (block.type === SECTION_REF_BLOCK) {
40
+ const id = sectionRefId(block.props?.section);
41
+ const doc = id === null ? undefined : docOf(id);
42
+ if (!doc)
43
+ return block;
44
+ return { ...block, slots: { ...block.slots, [SECTION_REF_SLOT]: sectionRefBlocks(block.id, doc.blocks) } };
45
+ }
46
+ if (!block.slots)
47
+ return block;
48
+ return { ...block, slots: Object.fromEntries(Object.entries(block.slots).map(([name, children]) => [name, fill(children)])) };
49
+ });
50
+ return { ...layout, blocks: fill(layout.blocks) };
51
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ComponentType, ReactNode } from 'react';
2
- import type { Block, BlockDefinition, Layout, TemplateContext } from '../../core/index.js';
2
+ import type { BindingRelations, Block, BlockDefinition, Layout, TemplateContext } from '../../core/index.js';
3
3
  /**
4
4
  * "site" renders the public page. "canvas" adds editor attributes and empty-slot placeholders.
5
5
  * In canvas mode, repeated collection list items after the first get `data-builder-repeat`
@@ -92,6 +92,11 @@ export type RenderLayoutProps = {
92
92
  * Load it with `depth: 1` and pass the same context to `loadLayoutData`.
93
93
  */
94
94
  context?: TemplateContext | null;
95
+ /**
96
+ * Which collection each relationship field points to (`bindingRelations(payload.config.collections)`
97
+ * from `payload-canvas/core`), for `<path>.$url` bindings such as `categories.0.$url`.
98
+ */
99
+ relations?: BindingRelations | null;
95
100
  /**
96
101
  * Data the page loads once for all its blocks (plain data). Components marked with
97
102
  * `withPageData`, and `fromPayloadComponent` components, get it as `pageData`. In the canvas it
@@ -2,6 +2,7 @@ import type { Payload } from 'payload';
2
2
  import { type Layout } from '../core/index.js';
3
3
  import { type RenderLocale } from './render/locale.js';
4
4
  export { loadLayoutData, type LoadLayoutOptions } from './render/resolve.js';
5
+ export { loadedLists, type LoadedList } from './render/lists.js';
5
6
  export { localeArgs, localizeLayout, type RenderLocale } from './render/locale.js';
6
7
  export { createCanvasServer, type CanvasFrameArgs, type CanvasServerOptions, type PageDataArgs } from './render/canvasServer.js';
7
8
  export { siteRegion, type RegionMark } from './render/regions.js';
@@ -27,7 +28,8 @@ export type LoadTemplateArgs = RenderLocale & {
27
28
  };
28
29
  /**
29
30
  * The template a document renders through: the document's own template (its `template` field),
30
- * else the collection's default template, else `null`. Templates with an empty layout are
31
+ * else the first template (by name) whose `conditions` match the document, else the collection's
32
+ * default template, else `null`. Templates with an empty layout are
31
33
  * skipped: an empty own template falls back to the default, and an empty default falls back to
32
34
  * the next most recently changed default (the plugin refuses to publish an empty default, so
33
35
  * this only matters for older data).
@@ -1,11 +1,12 @@
1
1
  // Server-only helpers: `payload-canvas/react/server`. They call Payload's Local API, so
2
2
  // keep them out of client components (the main entry stays client-safe).
3
3
  import { siteCssConfigOf } from '../plugin/index.js';
4
- import { collectClasses, DEFAULT_TEMPLATES_SLUG, DOCUMENT_TEMPLATE_FIELD, normalizeLayout, TEMPLATE_DEFAULT_FIELD, TEMPLATE_LAYOUT_FIELD, TEMPLATE_TARGET_FIELD, } from '../core/index.js';
4
+ import { collectClasses, DEFAULT_TEMPLATES_SLUG, DOCUMENT_TEMPLATE_FIELD, normalizeLayout, TEMPLATE_CONDITIONS_FIELD, TEMPLATE_DEFAULT_FIELD, TEMPLATE_LAYOUT_FIELD, TEMPLATE_TARGET_FIELD, templateConditions, } from '../core/index.js';
5
5
  import { compileClasses } from '../css/index.js';
6
6
  import { isRecord } from './render/fields.js';
7
7
  import { localeArgs } from './render/locale.js';
8
8
  export { loadLayoutData } from './render/resolve.js';
9
+ export { loadedLists } from './render/lists.js';
9
10
  export { localeArgs, localizeLayout } from './render/locale.js';
10
11
  export { createCanvasServer } from './render/canvasServer.js';
11
12
  export { siteRegion } from './render/regions.js';
@@ -28,11 +29,38 @@ function usable(template, collection, draft) {
28
29
  return null;
29
30
  return { template, layout, css: cssOf(template) };
30
31
  }
32
+ /** How many templates with conditions `loadTemplate` tries, in name order. */
33
+ const CONDITION_CANDIDATES = 100;
34
+ /**
35
+ * Whether the stored document (the latest draft in draft mode) matches a template's conditions:
36
+ * one Payload query, so every operator and field path Payload knows works. A query Payload
37
+ * refuses (an unknown field) counts as no match and is logged.
38
+ */
39
+ async function matchesConditions(payload, collection, id, where, draft, locale) {
40
+ try {
41
+ const found = await payload.find({
42
+ collection: collection,
43
+ where: { and: [{ id: { equals: id } }, where] },
44
+ draft,
45
+ depth: 0,
46
+ limit: 1,
47
+ pagination: false,
48
+ select: { id: true },
49
+ ...locale,
50
+ });
51
+ return found.docs.length > 0;
52
+ }
53
+ catch (error) {
54
+ payload.logger.error({ err: error, msg: '[builder] Template conditions failed. The template is skipped.' });
55
+ return false;
56
+ }
57
+ }
31
58
  /** How many default templates `loadTemplate` looks at (one normally; more only with old data). */
32
59
  const DEFAULT_CANDIDATES = 5;
33
60
  /**
34
61
  * The template a document renders through: the document's own template (its `template` field),
35
- * else the collection's default template, else `null`. Templates with an empty layout are
62
+ * else the first template (by name) whose `conditions` match the document, else the collection's
63
+ * default template, else `null`. Templates with an empty layout are
36
64
  * skipped: an empty own template falls back to the default, and an empty default falls back to
37
65
  * the next most recently changed default (the plugin refuses to publish an empty default, so
38
66
  * this only matters for older data).
@@ -67,6 +95,29 @@ export async function loadTemplate(payload, args) {
67
95
  // A deleted template falls back to the default.
68
96
  }
69
97
  }
98
+ const docId = doc.id;
99
+ if (typeof docId === 'string' || typeof docId === 'number') {
100
+ // Only the conditions are read here; the matching template loads in full below.
101
+ const candidates = await payload.find({
102
+ collection: slug,
103
+ where: { and: [{ [TEMPLATE_TARGET_FIELD]: { equals: collection } }, ...(draft ? [] : [{ _status: { equals: 'published' } }])] },
104
+ sort: 'name',
105
+ depth: 0,
106
+ limit: CONDITION_CANDIDATES,
107
+ draft,
108
+ select: { [TEMPLATE_CONDITIONS_FIELD]: true },
109
+ ...locale,
110
+ });
111
+ for (const candidate of candidates.docs) {
112
+ const where = templateConditions(candidate);
113
+ if (!where || !(await matchesConditions(payload, collection, docId, where, draft, locale)))
114
+ continue;
115
+ const template = (await payload.findByID({ collection: slug, id: candidate.id, depth: 0, draft, ...locale }));
116
+ const found = usable(template, collection, draft);
117
+ if (found)
118
+ return found;
119
+ }
120
+ }
70
121
  const result = await payload.find({
71
122
  collection: slug,
72
123
  where: {
@@ -12,7 +12,11 @@ export type LoadedTheme = ThemeOutput & {
12
12
  */
13
13
  export declare const loadTheme: (payload: Payload) => Promise<LoadedTheme | null>;
14
14
  export type ThemeStyleProps = {
15
- payload: Payload;
15
+ /**
16
+ * The Payload instance, or the promise from `getPayload({ config })`. Pass the promise under
17
+ * Cache Components: then the connection is made inside the component's `<Suspense>` boundary.
18
+ */
19
+ payload: Payload | Promise<Payload>;
16
20
  /** Load the theme's Google Fonts (`<link>` tags). Default `true`. `false` when you host fonts yourself. */
17
21
  fonts?: boolean;
18
22
  /**
@@ -25,5 +29,12 @@ export type ThemeStyleProps = {
25
29
  * The theme for the `<head>`: a `<style>` tag with the theme variables and the Google Fonts links.
26
30
  * Put it in the site's root layout and in the canvas layout (with `live`). Renders nothing with
27
31
  * `theme: false`.
32
+ *
33
+ * The database read sits in its own `<Suspense>` boundary (fallback: nothing), so a route with
34
+ * Next's Cache Components (`cacheComponents: true`) does not fail on it. To keep the theme in the
35
+ * static shell, render it inside your own `'use cache'` component (see the README's "Cache
36
+ * Components").
28
37
  */
29
- export declare function ThemeStyle({ payload, fonts, live }: ThemeStyleProps): Promise<import("react").JSX.Element | null>;
38
+ export declare function ThemeStyle(props: ThemeStyleProps): import("react").JSX.Element;
39
+ /** The tags of `ThemeStyle`, after the read. */
40
+ export declare function ThemeTags({ payload: payloadOrPromise, fonts, live }: ThemeStyleProps): Promise<import("react").JSX.Element | null>;
@@ -1,7 +1,7 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // Server-only: the theme global as CSS variables and Google Fonts links, for the `<head>`.
3
3
  import { themeConfigOf, themeOutput } from '../../theme/index.js';
4
- import { cache } from 'react';
4
+ import { cache, Suspense } from 'react';
5
5
  import { THEME_PRECEDENCE, themeStyleHref } from './constants.js';
6
6
  import { ThemeLive } from './ThemeLive.js';
7
7
  /**
@@ -21,8 +21,18 @@ export const loadTheme = cache(async (payload) => {
21
21
  * The theme for the `<head>`: a `<style>` tag with the theme variables and the Google Fonts links.
22
22
  * Put it in the site's root layout and in the canvas layout (with `live`). Renders nothing with
23
23
  * `theme: false`.
24
+ *
25
+ * The database read sits in its own `<Suspense>` boundary (fallback: nothing), so a route with
26
+ * Next's Cache Components (`cacheComponents: true`) does not fail on it. To keep the theme in the
27
+ * static shell, render it inside your own `'use cache'` component (see the README's "Cache
28
+ * Components").
24
29
  */
25
- export async function ThemeStyle({ payload, fonts = true, live = false }) {
30
+ export function ThemeStyle(props) {
31
+ return (_jsx(Suspense, { fallback: null, children: _jsx(ThemeTags, { ...props }) }));
32
+ }
33
+ /** The tags of `ThemeStyle`, after the read. */
34
+ export async function ThemeTags({ payload: payloadOrPromise, fonts = true, live = false }) {
35
+ const payload = await payloadOrPromise;
26
36
  const theme = await loadTheme(payload);
27
37
  const config = themeConfigOf(payload);
28
38
  if (!theme || !config)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payload-canvas",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Payload Canvas: a visual drag-and-drop website builder for Payload CMS 3. Nested layout blocks, Tailwind styling, sections, templates, live AI editing over MCP, and the React renderer for your site.",
5
5
  "keywords": [
6
6
  "payload",