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.
- package/README.md +500 -25
- package/dist/admin/diff/changes.js +8 -0
- package/dist/admin/editor/Inspector.js +49 -4
- package/dist/admin/editor/Outline.js +12 -10
- package/dist/admin/editor/actions.d.ts +9 -1
- package/dist/admin/editor/actions.js +38 -3
- package/dist/admin/editor/empty/EmptyStart.js +29 -3
- package/dist/admin/editor/fields/GroupField.d.ts +5 -2
- package/dist/admin/editor/fields/GroupField.js +6 -2
- package/dist/admin/editor/fields/WhereField.d.ts +17 -0
- package/dist/admin/editor/fields/WhereField.js +67 -0
- package/dist/admin/editor/fields/fields.scss +89 -0
- package/dist/admin/editor/fields/whereRows.d.ts +28 -0
- package/dist/admin/editor/fields/whereRows.js +118 -0
- package/dist/admin/editor/icons.d.ts +1 -0
- package/dist/admin/editor/icons.js +2 -0
- package/dist/admin/editor/locale/LocaleField.d.ts +1 -1
- package/dist/admin/editor/locale/LocaleField.js +3 -1
- package/dist/admin/editor/menu/blockMenu.js +5 -1
- package/dist/admin/editor/motion/MotionPanel.js +1 -1
- package/dist/admin/editor/motion/model.js +2 -2
- package/dist/admin/editor/renderField.d.ts +3 -1
- package/dist/admin/editor/renderField.js +13 -4
- package/dist/admin/editor/runtime.js +1 -0
- package/dist/admin/editor/styles/SiteClasses.d.ts +9 -0
- package/dist/admin/editor/styles/SiteClasses.js +31 -0
- package/dist/admin/editor/styles/StylesPanel.d.ts +3 -1
- package/dist/admin/editor/styles/StylesPanel.js +9 -6
- package/dist/admin/editor/styles/context.d.ts +9 -2
- package/dist/admin/editor/styles/context.js +14 -9
- package/dist/admin/editor/styles/controls.js +2 -2
- package/dist/admin/editor/styles/sections.js +1 -1
- package/dist/admin/editor/styles/styles.scss +54 -0
- package/dist/admin/editor/templates/Bindable.d.ts +13 -5
- package/dist/admin/editor/templates/Bindable.js +73 -17
- package/dist/admin/editor/templates/binding.d.ts +11 -4
- package/dist/admin/editor/templates/binding.js +23 -3
- package/dist/ai/prompt.js +8 -2
- package/dist/ai/tools.js +11 -2
- package/dist/blocks/builtins/carousel.d.ts +32 -0
- package/dist/blocks/builtins/carousel.js +122 -0
- package/dist/blocks/builtins/disclosure.d.ts +13 -0
- package/dist/blocks/builtins/disclosure.js +107 -0
- package/dist/blocks/builtins/faq.d.ts +17 -0
- package/dist/blocks/builtins/faq.js +88 -0
- package/dist/blocks/builtins/filterLink.d.ts +22 -0
- package/dist/blocks/builtins/filterLink.js +76 -0
- package/dist/blocks/builtins/headingId.d.ts +15 -0
- package/dist/blocks/builtins/headingId.js +36 -0
- package/dist/blocks/builtins/icon.d.ts +8 -0
- package/dist/blocks/builtins/icon.js +45 -0
- package/dist/blocks/builtins/index.d.ts +35 -0
- package/dist/blocks/builtins/index.js +50 -0
- package/dist/blocks/builtins/lightbox.d.ts +43 -0
- package/dist/blocks/builtins/lightbox.js +93 -0
- package/dist/blocks/builtins/mediaBackdrop.d.ts +11 -0
- package/dist/blocks/builtins/mediaBackdrop.js +79 -0
- package/dist/blocks/builtins/sectionRef.d.ts +26 -0
- package/dist/blocks/builtins/sectionRef.js +78 -0
- package/dist/blocks/builtins/shared.d.ts +33 -0
- package/dist/blocks/builtins/shared.js +70 -0
- package/dist/blocks/builtins/tableOfContents.d.ts +3 -0
- package/dist/blocks/builtins/tableOfContents.js +44 -0
- package/dist/blocks/defaults.d.ts +19 -1
- package/dist/blocks/defaults.js +413 -20
- package/dist/blocks/index.d.ts +4 -2
- package/dist/blocks/index.js +3 -1
- package/dist/core/attrs.d.ts +27 -0
- package/dist/core/attrs.js +132 -0
- package/dist/core/bindings.d.ts +122 -11
- package/dist/core/bindings.js +504 -19
- package/dist/core/blocks.d.ts +46 -1
- package/dist/core/blocks.js +136 -0
- package/dist/core/classes.d.ts +10 -2
- package/dist/core/classes.js +34 -5
- package/dist/core/headings.d.ts +21 -0
- package/dist/core/headings.js +47 -0
- package/dist/core/index.d.ts +4 -2
- package/dist/core/index.js +4 -2
- package/dist/core/motion.d.ts +18 -9
- package/dist/core/motion.js +20 -12
- package/dist/core/operations.js +59 -2
- package/dist/core/payloadBlocks.js +3 -1
- package/dist/core/schema.js +20 -0
- package/dist/core/tree.js +24 -1
- package/dist/core/types.d.ts +87 -0
- package/dist/core/validate.js +29 -4
- package/dist/css/tokens.d.ts +6 -3
- package/dist/css/tokens.js +48 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +50 -13
- package/dist/mcp/shared.d.ts +3 -0
- package/dist/mcp/shared.js +23 -8
- package/dist/plugin/index.d.ts +8 -0
- package/dist/plugin/index.js +26 -8
- package/dist/plugin/listCollections.d.ts +17 -2
- package/dist/plugin/listCollections.js +44 -7
- package/dist/plugin/references.d.ts +5 -0
- package/dist/plugin/references.js +1 -1
- package/dist/plugin/templates.d.ts +4 -0
- package/dist/plugin/templates.js +23 -4
- package/dist/protocol/index.d.ts +2 -0
- package/dist/react/canvas/BuilderCanvas.js +5 -3
- package/dist/react/canvas/fetchDocs.d.ts +16 -2
- package/dist/react/canvas/fetchDocs.js +42 -9
- package/dist/react/canvas/measure.d.ts +3 -1
- package/dist/react/canvas/measure.js +26 -2
- package/dist/react/canvas/resolveLayout.d.ts +1 -1
- package/dist/react/canvas/resolveLayout.js +17 -6
- package/dist/react/canvas/serverBlocks.d.ts +11 -0
- package/dist/react/canvas/serverBlocks.js +28 -1
- package/dist/react/components/Button.d.ts +11 -2
- package/dist/react/components/Button.js +43 -6
- package/dist/react/components/CollectionList.d.ts +6 -3
- package/dist/react/components/CollectionList.js +21 -7
- package/dist/react/components/Container.js +4 -1
- package/dist/react/components/Field.js +13 -2
- package/dist/react/components/Heading.js +9 -2
- package/dist/react/components/Image.d.ts +9 -0
- package/dist/react/components/Image.js +16 -1
- package/dist/react/components/List.d.ts +1 -0
- package/dist/react/components/List.js +6 -0
- package/dist/react/components/Menu.d.ts +16 -0
- package/dist/react/components/Menu.js +83 -19
- package/dist/react/components/RichText.d.ts +8 -3
- package/dist/react/components/RichText.js +25 -4
- package/dist/react/components/builtins/Accordion.d.ts +9 -0
- package/dist/react/components/builtins/Accordion.js +37 -0
- package/dist/react/components/builtins/BackdropVideo.d.ts +13 -0
- package/dist/react/components/builtins/BackdropVideo.js +16 -0
- package/dist/react/components/builtins/Carousel.d.ts +13 -0
- package/dist/react/components/builtins/Carousel.js +134 -0
- package/dist/react/components/builtins/Disclosure.d.ts +7 -0
- package/dist/react/components/builtins/Disclosure.js +13 -0
- package/dist/react/components/builtins/FilterLink.d.ts +8 -0
- package/dist/react/components/builtins/FilterLink.js +30 -0
- package/dist/react/components/builtins/Icon.d.ts +14 -0
- package/dist/react/components/builtins/Icon.js +28 -0
- package/dist/react/components/builtins/Lightbox.d.ts +45 -0
- package/dist/react/components/builtins/Lightbox.js +252 -0
- package/dist/react/components/builtins/MediaBackdrop.d.ts +14 -0
- package/dist/react/components/builtins/MediaBackdrop.js +61 -0
- package/dist/react/components/builtins/SectionRef.d.ts +7 -0
- package/dist/react/components/builtins/SectionRef.js +17 -0
- package/dist/react/components/builtins/TableOfContents.d.ts +7 -0
- package/dist/react/components/builtins/TableOfContents.js +21 -0
- package/dist/react/components/builtins/glyphs.d.ts +8 -0
- package/dist/react/components/builtins/glyphs.js +7 -0
- package/dist/react/components/builtins/index.d.ts +32 -0
- package/dist/react/components/builtins/index.js +36 -0
- package/dist/react/components/index.js +2 -0
- package/dist/react/index.d.ts +3 -1
- package/dist/react/index.js +3 -1
- package/dist/react/motion/runtime.js +10 -6
- package/dist/react/render/RenderLayout.d.ts +1 -1
- package/dist/react/render/RenderLayout.js +76 -23
- package/dist/react/render/lists.d.ts +107 -5
- package/dist/react/render/lists.js +284 -9
- package/dist/react/render/resolve.d.ts +22 -2
- package/dist/react/render/resolve.js +45 -22
- package/dist/react/render/sections.d.ts +9 -0
- package/dist/react/render/sections.js +51 -0
- package/dist/react/render/types.d.ts +6 -1
- package/dist/react/server.d.ts +3 -1
- package/dist/react/server.js +53 -2
- package/dist/react/theme/ThemeStyle.d.ts +13 -2
- package/dist/react/theme/ThemeStyle.js +12 -2
- package/package.json +1 -1
package/dist/mcp/shared.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// Texts and helpers shared by the MCP tools (src/mcp) and the editor's AI assistant (src/ai).
|
|
2
2
|
// No zod and no Payload runtime here, so the assistant does not need the MCP dependencies.
|
|
3
|
-
import { COLLECTION_LIST_BLOCK, FIELD_BLOCK, URL_PATH } from '../core/bindings.js';
|
|
3
|
+
import { COLLECTION_LIST_BLOCK, FIELD_BLOCK, INDEX_PATH, ITEM_PATH, PAGE_PATH, PARENT_PATH, REPEAT_BLOCK, URL_PATH, VISIBLE_BINDING } from '../core/bindings.js';
|
|
4
|
+
import { classFields } from '../core/classes.js';
|
|
4
5
|
import { dataFields, optionValues } from '../core/fields.js';
|
|
6
|
+
import { htmlIdsOf, withoutTakenHtmlIds } from '../core/attrs.js';
|
|
5
7
|
import { createId } from '../core/ids.js';
|
|
6
8
|
import { MOTION_EASING_INFO, MOTION_KINDS, MOTION_PRESET_INFO, MOTION_SPECS } from '../core/motion.js';
|
|
7
9
|
import { DEFAULT_SLOT, indexLayout } from '../core/tree.js';
|
|
@@ -37,7 +39,7 @@ export function motionGuide() {
|
|
|
37
39
|
*/
|
|
38
40
|
export function layoutGuide(blocksFrom) {
|
|
39
41
|
return `
|
|
40
|
-
LAYOUT MODEL. A layout is JSON: { "version": 1, "blocks": Block[] }. A Block is { id, type, props?, className?, slots?, bindings?, hidden?, motion? }.
|
|
42
|
+
LAYOUT MODEL. A layout is JSON: { "version": 1, "blocks": Block[] }. A Block is { id, type, props?, className?, slots?, bindings?, hidden?, motion?, attrs?, slotClassName? }.
|
|
41
43
|
- id: a string, unique in the whole layout. Operations target blocks by id, never by array index. New blocks need new ids: use "b_" plus 6 lowercase letters or digits (e.g. "b_k3x9qa").
|
|
42
44
|
- type: a block type from ${blocksFrom}.
|
|
43
45
|
- props: the block's own values. Get the exact shape with getBlockSchema. Upload and relationship props hold document IDs.
|
|
@@ -45,6 +47,8 @@ LAYOUT MODEL. A layout is JSON: { "version": 1, "blocks": Block[] }. A Block is
|
|
|
45
47
|
- slots: child blocks by slot name, e.g. { "children": [ ...blocks ] }. Only block types with slots take children. ${blocksFrom} shows which types each slot accepts. A type with "onlyInside" goes only directly inside those types (e.g. "listItem" only in a "list"). A slot with "maxBlocks" holds at most that many direct children: inserting into a full slot fails, so replace (update or remove) the block there instead. A slot with "minBlocks" needs that many before the page can be published.
|
|
46
48
|
- bindings: (templates and collection list items only) prop path -> document field path, e.g. { "text": "title" }, { "image": "featuredImage" }, { "link": "$url" }. At render time the prop takes the document's value; when the document has no value the literal prop stays. Get field paths from getBindingSources.
|
|
47
49
|
- motion: animations of the block (see MOTION below). Leave it out when the block has none.
|
|
50
|
+
- slotClassName: Tailwind classes of a slot's own element, by slot name, e.g. { "empty": "col-span-full text-center" }. Only slots marked with "classes" in ${blocksFrom} take them. In "update" it merges per slot; null removes a slot's classes.
|
|
51
|
+
- attrs: HTML attributes of the block element: { id?, ariaLabel?, ariaHidden? }. "id" is an anchor for "#id" links (e.g. "contact"), unique in the layout, letters, digits, - and _, starting with a letter; never the block id. "ariaLabel" names the element for screen readers (e.g. a nav or an icon-only link). "ariaHidden": true hides decorative blocks from screen readers. Copies of a section or a block leave out an id the page already uses.
|
|
48
52
|
- Canonical form: leave out empty props, slots, bindings and motion objects and empty slot lists. Set hidden only when true.
|
|
49
53
|
POSITION = { parentId, slot?, index }. parentId null means the page root, whose only slot is "children". slot defaults to "children". index is the block's FINAL index in the target list (0 = first; the list length = append). For a move inside the same list, count positions after the block is taken out.
|
|
50
54
|
${motionGuide()}`.trim();
|
|
@@ -52,10 +56,16 @@ ${motionGuide()}`.trim();
|
|
|
52
56
|
export const BINDINGS_GUIDE = [
|
|
53
57
|
'BINDINGS. A block in a template (or in a collection list item) binds props to document fields: "bindings": { "<prop path>": "<field path>" }.',
|
|
54
58
|
'Examples: heading { "text": "title" }, text { "text": "excerpt" }, image { "image": "featuredImage" }, button or link { "link": "$url" }.',
|
|
55
|
-
`"${URL_PATH}" is the document's page URL. Nested props use dots: { "link.url": "$url" }.`,
|
|
59
|
+
`"${URL_PATH}" is the document's page URL. Nested props use dots: { "link.url": "$url" }. "<relationship path>.${URL_PATH}" is the page URL of a related document, e.g. { "link": "categories.0.${URL_PATH}" } (the first category of a listed model).`,
|
|
56
60
|
'Values are converted to the prop type: rich text and dates become plain text in text props. When the document has no value, the literal prop stays, so bound props may stay empty.',
|
|
57
61
|
`The "${FIELD_BLOCK}" block shows any field by its type (rich text, image, date, text): props { "path": "content" }.`,
|
|
58
62
|
`In a "${COLLECTION_LIST_BLOCK}" block, blocks in the "item" slot bind to each LISTED document, not to the page.`,
|
|
63
|
+
`In a "${REPEAT_BLOCK}" block (props { "path": "faqs" }), blocks in the "item" slot bind to each ROW of that list field: the row's fields ("question"), "${ITEM_PATH}" (the row value, e.g. an upload for an image) and "${INDEX_PATH}" (the row number from 1).`,
|
|
64
|
+
`Inside any list or repeat item: "${PARENT_PATH}.<field>" reads the enclosing document (e.g. "${PARENT_PATH}.name"), "${PAGE_PATH}.<field>" the page's own document, "${INDEX_PATH}" the item number.`,
|
|
65
|
+
'Fallbacks: "heading|name" uses the first path with a value.',
|
|
66
|
+
'Formatters after the paths: "publishedAt|date:en-AU:Australia/Brisbane", "price|currency:AUD" ($1,200), "price|number", "bio|firstSentence".',
|
|
67
|
+
'Template strings: a binding with {{…}} is text with expressions, e.g. { "text": "Enquire about {{name}}" } or "From {{price|currency:AUD}}". A missing expression becomes empty; when all are missing the literal prop stays.',
|
|
68
|
+
`Conditional blocks: "${VISIBLE_BINDING}" in bindings shows the block only when the condition holds: "availableToday" (filled; false counts as empty), "!availableToday" (empty), "district=north" (equals; for lists, any item or document id), "district!=north", and for numbers "price>100", "price>=100", "age<30", "age<=30". "field#" is the number of items of a list: "galleryImages#>=3" (at least 3 photos), "services#=0". A hidden block renders nothing on the site.`,
|
|
59
69
|
].join('\n');
|
|
60
70
|
/** Copies a block tree with new ids that are not in `used`. */
|
|
61
71
|
export function withNewIds(block, used) {
|
|
@@ -135,14 +145,17 @@ export function sectionInsertOps(layout, section, at) {
|
|
|
135
145
|
if (start < 0 || start > list.length)
|
|
136
146
|
return `Index ${start} is out of range (0-${list.length})`;
|
|
137
147
|
const used = new Set(index.keys());
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
148
|
+
// A second copy of a section leaves out the HTML ids the page already uses.
|
|
149
|
+
const taken = htmlIdsOf(layout.blocks);
|
|
150
|
+
return section.blocks.map((block, i) => {
|
|
151
|
+
const copy = withoutTakenHtmlIds(withNewIds(block, used), taken);
|
|
152
|
+
htmlIdsOf([copy], taken);
|
|
153
|
+
return { type: 'insert', block: copy, to: { parentId, slot, index: start + i } };
|
|
154
|
+
});
|
|
143
155
|
}
|
|
144
156
|
/** A block type as plain data for AI models: props, slots, where it may go, description and example. */
|
|
145
157
|
export function describeBlock(def) {
|
|
158
|
+
const classProps = new Set(classFields(def).map((f) => f.name));
|
|
146
159
|
const props = dataFields(def.fields).map((f) => {
|
|
147
160
|
const options = f.type === 'select' || f.type === 'radio' ? optionValues(f) : undefined;
|
|
148
161
|
return {
|
|
@@ -152,6 +165,7 @@ export function describeBlock(def) {
|
|
|
152
165
|
...(f.hasMany ? { hasMany: true } : {}),
|
|
153
166
|
...(options?.length ? { options } : {}),
|
|
154
167
|
...(f.relationTo ? { relationTo: f.relationTo } : {}),
|
|
168
|
+
...(classProps.has(f.name) ? { holds: 'Tailwind classes (compiled like className)' } : {}),
|
|
155
169
|
};
|
|
156
170
|
});
|
|
157
171
|
const slots = def.slots
|
|
@@ -162,6 +176,7 @@ export function describeBlock(def) {
|
|
|
162
176
|
accepts: slot.allow && !slot.allow.includes('*') ? slot.allow : 'any block',
|
|
163
177
|
...(typeof slot.min === 'number' ? { minBlocks: slot.min } : {}),
|
|
164
178
|
...(typeof slot.max === 'number' ? { maxBlocks: slot.max } : {}),
|
|
179
|
+
...(slot.styles ? { classes: 'takes its own classes in "slotClassName"' } : {}),
|
|
165
180
|
},
|
|
166
181
|
]))
|
|
167
182
|
: undefined;
|
package/dist/plugin/index.d.ts
CHANGED
|
@@ -78,6 +78,8 @@ export type TemplatesOptions = {
|
|
|
78
78
|
slug?: string;
|
|
79
79
|
/** Hooks for the templates collection, e.g. `afterChange` to revalidate the pages that use templates. */
|
|
80
80
|
hooks?: CollectionConfig['hooks'];
|
|
81
|
+
/** Merged into the collection's `admin` options (e.g. `group`, `hidden`). */
|
|
82
|
+
admin?: CollectionConfig['admin'];
|
|
81
83
|
/** `false`: template layouts are not translated. Default: as the collections (`'props'`). */
|
|
82
84
|
localization?: 'props' | false;
|
|
83
85
|
};
|
|
@@ -86,6 +88,12 @@ export type WebsiteBuilderOptions = {
|
|
|
86
88
|
collections: Record<string, BuilderCollectionOptions>;
|
|
87
89
|
/** Default: defaultBlocks(). */
|
|
88
90
|
blocks?: BlockDefinition[];
|
|
91
|
+
/**
|
|
92
|
+
* More collections the collection list block can show, after the collections with a `url`:
|
|
93
|
+
* data collections without pages of their own, such as testimonials or team members. Their
|
|
94
|
+
* items have no `$url`. Each slug must be a collection of the config.
|
|
95
|
+
*/
|
|
96
|
+
listCollections?: string[];
|
|
89
97
|
css: {
|
|
90
98
|
/** Path to the app's Tailwind entry CSS, absolute or relative to process.cwd(). */
|
|
91
99
|
entry: string;
|
package/dist/plugin/index.js
CHANGED
|
@@ -3,8 +3,8 @@ import { AI_PATH, aiEndpoints } from '../ai/endpoint.js';
|
|
|
3
3
|
import { aiClientConfig } from '../ai/config.js';
|
|
4
4
|
import { AI_IMAGES_KEY, createImageService } from '../ai/images/service.js';
|
|
5
5
|
import { defaultBlocks } from '../blocks/index.js';
|
|
6
|
-
import { richTextFieldName } from '../core/blocks.js';
|
|
7
|
-
import { DEFAULT_TEMPLATES_SLUG, DOCUMENT_TEMPLATE_FIELD, TEMPLATE_TARGET_FIELD } from '../core/bindings.js';
|
|
6
|
+
import { richTextFieldName, sectionsWithDefaultClassNames, sectionsWithVariants } from '../core/blocks.js';
|
|
7
|
+
import { bindingRelations, DEFAULT_TEMPLATES_SLUG, DOCUMENT_TEMPLATE_FIELD, TEMPLATE_TARGET_FIELD } from '../core/bindings.js';
|
|
8
8
|
import { localeSettingsOf } from '../core/locale.js';
|
|
9
9
|
import { resolveRegions } from '../core/regions.js';
|
|
10
10
|
import { decodePayloadBlocks, payloadBlocksProblems, payloadBlocksStorage } from '../core/payloadBlocks.js';
|
|
@@ -23,7 +23,7 @@ import { DEFAULT_SAVED_SECTIONS_SLUG, SAVED_SECTIONS_CONFIG_KEY, savedSectionsCo
|
|
|
23
23
|
import { syncSectionBlocks } from './sectionsBuilder.js';
|
|
24
24
|
import { toJsonSafe } from './jsonSafe.js';
|
|
25
25
|
import { collectionLabel } from './labels.js';
|
|
26
|
-
import {
|
|
26
|
+
import { listableCollections, prepareBlocks } from './listCollections.js';
|
|
27
27
|
import { addReferences, REFERENCES_CONFIG_KEY, resolveReferences } from './references.js';
|
|
28
28
|
import { bindingSources, documentTemplateField, hasFieldNamed, requireBlocksForDefault, TEMPLATE_LAYOUT_FIELD, TEMPLATES_CONFIG_KEY, templatesCollection, } from './templates.js';
|
|
29
29
|
/**
|
|
@@ -109,6 +109,13 @@ export function websiteBuilder(options) {
|
|
|
109
109
|
const targets = Object.entries(options.collections).filter(([, o]) => o.templates).map(([slug]) => slug);
|
|
110
110
|
const templatesSlug = options.templates?.slug ?? DEFAULT_TEMPLATES_SLUG;
|
|
111
111
|
const withUrl = new Set(Object.entries(options.collections).filter(([, o]) => o.url).map(([slug]) => slug));
|
|
112
|
+
for (const slug of options.listCollections ?? []) {
|
|
113
|
+
if (!sourceCollections.some((c) => c.slug === slug)) {
|
|
114
|
+
throw new Error(`[websiteBuilder] \`listCollections\` names "${slug}", which is not a collection. Known collections: ${sourceCollections.map((c) => c.slug).join(', ')}.`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// The collections the collection list block can show: with a `url`, then `listCollections`.
|
|
118
|
+
const listable = listableCollections(options.collections, options.listCollections);
|
|
112
119
|
const builderOptions = { ...options.collections };
|
|
113
120
|
let collections = sourceCollections;
|
|
114
121
|
if (targets.length > 0) {
|
|
@@ -128,11 +135,17 @@ export function websiteBuilder(options) {
|
|
|
128
135
|
targets,
|
|
129
136
|
targetLabels: Object.fromEntries(sourceCollections.filter((c) => targets.includes(c.slug)).map((c) => [c.slug, collectionLabel(c)])),
|
|
130
137
|
hooks: options.templates?.hooks,
|
|
138
|
+
admin: options.templates?.admin,
|
|
131
139
|
}),
|
|
132
140
|
];
|
|
133
141
|
builderOptions[templatesSlug] = { field: TEMPLATE_LAYOUT_FIELD, ...(options.templates?.localization === false ? { localization: false } : {}) };
|
|
134
142
|
}
|
|
135
|
-
|
|
143
|
+
// Inline blocks (`inline: true`) may sit in a link: they join its `allow` list.
|
|
144
|
+
const blocks = prepareBlocks(options.blocks ?? defaultBlocks(), listable);
|
|
145
|
+
// Each section variant is listed as a section of its own (`<id>/<variant id>`).
|
|
146
|
+
const appSections = sectionsWithVariants(options.sections ?? []);
|
|
147
|
+
// A section block without a className gets its type's default classes (JSON layouts only).
|
|
148
|
+
const sections = sectionsWithDefaultClassNames(appSections, blocks);
|
|
136
149
|
const duplicate = blocks.find((b, i) => blocks.findIndex((other) => other.type === b.type) !== i);
|
|
137
150
|
if (duplicate) {
|
|
138
151
|
throw new Error(`[websiteBuilder] Two blocks have the type "${duplicate.type}". Every block type must be unique. For blocks made with fromPayloadBlocks(), set \`prefix\` (for example \`prefix: 'site'\` makes "${duplicate.type}" "site${duplicate.type.charAt(0).toUpperCase()}${duplicate.type.slice(1)}").`);
|
|
@@ -182,6 +195,8 @@ export function websiteBuilder(options) {
|
|
|
182
195
|
options: options.references,
|
|
183
196
|
collections,
|
|
184
197
|
blocks,
|
|
198
|
+
// Live saved sections (sectionRef): the section lists the pages that show it, and stays while one does.
|
|
199
|
+
...(savedSections ? { shared: [savedSections.slug] } : {}),
|
|
185
200
|
sources: {
|
|
186
201
|
...Object.fromEntries(Object.entries(builderOptions).map(([slug, o]) => {
|
|
187
202
|
const storage = blocksStorageOf[slug];
|
|
@@ -212,6 +227,8 @@ export function websiteBuilder(options) {
|
|
|
212
227
|
regionsOf[slug] = resolveRegions(slug, source?.fields ?? [], o.regions, { fields: new Set(own), legacy: new Set(o.legacyFields ?? []) });
|
|
213
228
|
}
|
|
214
229
|
const clientBlocks = toJsonSafe(blocks);
|
|
230
|
+
// Relationship targets of every collection, so the canvas resolves `<path>.$url` bindings.
|
|
231
|
+
const relations = bindingRelations(collections);
|
|
215
232
|
const css = {
|
|
216
233
|
entry: path.resolve(process.cwd(), options.css.entry),
|
|
217
234
|
plugins: options.css.plugins,
|
|
@@ -239,7 +256,7 @@ export function websiteBuilder(options) {
|
|
|
239
256
|
collection: templatesSlug,
|
|
240
257
|
sources: bindingSources({
|
|
241
258
|
collections: collections.filter((c) => c.slug !== templatesSlug),
|
|
242
|
-
slugs: [...new Set([...targets, ...
|
|
259
|
+
slugs: [...new Set([...targets, ...listable])],
|
|
243
260
|
skip: Object.fromEntries(Object.entries(builderOptions).map(([slug, o]) => {
|
|
244
261
|
const field = o.field ?? 'layout';
|
|
245
262
|
const plugin = [field, cssFieldName(field), richTextFieldName(field), DOCUMENT_TEMPLATE_FIELD];
|
|
@@ -300,8 +317,8 @@ export function websiteBuilder(options) {
|
|
|
300
317
|
tokensEndpoint: `${apiRoute}${STYLE_TOKENS_PATH}`,
|
|
301
318
|
// Only sections the field can store as they are.
|
|
302
319
|
sections: storage
|
|
303
|
-
?
|
|
304
|
-
:
|
|
320
|
+
? appSections.filter((section) => payloadBlocksProblems({ version: 1, blocks: section.blocks }, storage).length === 0)
|
|
321
|
+
: sections,
|
|
305
322
|
liveEndpoint: `${apiRoute}${LIVE_PATH}`,
|
|
306
323
|
templates: clientTemplates,
|
|
307
324
|
ai: options.ai ? aiClientConfig(options.ai, `${apiRoute}${AI_PATH}`) : null,
|
|
@@ -312,6 +329,7 @@ export function websiteBuilder(options) {
|
|
|
312
329
|
localization: localizationOf(collection.slug),
|
|
313
330
|
...(regionsOf[collection.slug] ? { regions: toJsonSafe(regionsOf[collection.slug]) } : {}),
|
|
314
331
|
...(storage ? { storage: 'payload-blocks', payloadRootTypes: [...storage.rootTypes] } : {}),
|
|
332
|
+
...(Object.keys(relations).length > 0 ? { relations } : {}),
|
|
315
333
|
};
|
|
316
334
|
const isSections = collection.slug === savedSections?.slug;
|
|
317
335
|
const built = addBuilder(collection, {
|
|
@@ -371,7 +389,7 @@ export function websiteBuilder(options) {
|
|
|
371
389
|
images: imageService ?? undefined,
|
|
372
390
|
collections: liveCollections,
|
|
373
391
|
blocks,
|
|
374
|
-
sections
|
|
392
|
+
sections,
|
|
375
393
|
savedSections,
|
|
376
394
|
getTokens: () => getStyleTokens(css),
|
|
377
395
|
templates: templates ? { slug: templatesSlug, sources: templates.sources } : null,
|
|
@@ -1,7 +1,22 @@
|
|
|
1
1
|
import type { BlockDefinition } from '../core/types.js';
|
|
2
2
|
/**
|
|
3
|
-
* The collection list block shows only collections
|
|
4
|
-
* becomes a select of them, so the editor offers a list and validation rejects other values.
|
|
3
|
+
* The collection list block shows only the given collections (see `listableCollections`): its `collection` text field
|
|
4
|
+
* (and the field list's optional one, for `$url`) becomes a select of them, so the editor offers a list and validation rejects other values.
|
|
5
5
|
* Returns the same list when there is nothing to change.
|
|
6
6
|
*/
|
|
7
7
|
export declare function listCollectionsOf(blocks: BlockDefinition[], slugs: string[]): BlockDefinition[];
|
|
8
|
+
/**
|
|
9
|
+
* The collections the collection list block can show: the collections with a `url`, then the
|
|
10
|
+
* `listCollections` option (data collections without pages), each once.
|
|
11
|
+
*/
|
|
12
|
+
export declare function listableCollections(collections: Record<string, {
|
|
13
|
+
url?: unknown;
|
|
14
|
+
}>, extra?: readonly string[]): string[];
|
|
15
|
+
/**
|
|
16
|
+
* The block list as `websiteBuilder` and `builderMcpTools` use it: `listCollectionsOf` (the
|
|
17
|
+
* collection list's `collection` and `ids` point to `listCollections`, the collections with a
|
|
18
|
+
* `url` and the `listCollections` option), then `withInlineBlocks` (inline blocks may go straight into a link). Run it on the
|
|
19
|
+
* site's own list too, so a seed's `validateLayout` agrees with the editor. Running it twice
|
|
20
|
+
* changes nothing.
|
|
21
|
+
*/
|
|
22
|
+
export declare function prepareBlocks(blocks: BlockDefinition[], listCollections?: string[]): BlockDefinition[];
|
|
@@ -1,18 +1,55 @@
|
|
|
1
|
-
import { COLLECTION_LIST_BLOCK } from '../core/bindings.js';
|
|
1
|
+
import { COLLECTION_LIST_BLOCK, REPEAT_BLOCK } from '../core/bindings.js';
|
|
2
|
+
import { withInlineBlocks } from '../core/blocks.js';
|
|
2
3
|
/**
|
|
3
|
-
* The collection list block shows only collections
|
|
4
|
-
* becomes a select of them, so the editor offers a list and validation rejects other values.
|
|
4
|
+
* The collection list block shows only the given collections (see `listableCollections`): its `collection` text field
|
|
5
|
+
* (and the field list's optional one, for `$url`) becomes a select of them, so the editor offers a list and validation rejects other values.
|
|
5
6
|
* Returns the same list when there is nothing to change.
|
|
6
7
|
*/
|
|
7
8
|
export function listCollectionsOf(blocks, slugs) {
|
|
8
9
|
if (slugs.length === 0)
|
|
9
10
|
return blocks;
|
|
10
11
|
return blocks.map((block) => {
|
|
11
|
-
if (block.type !== COLLECTION_LIST_BLOCK)
|
|
12
|
+
if (block.type !== COLLECTION_LIST_BLOCK && block.type !== REPEAT_BLOCK)
|
|
12
13
|
return block;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
// A field list's collection is optional (only for `$url`).
|
|
15
|
+
const required = block.type === COLLECTION_LIST_BLOCK;
|
|
16
|
+
const fields = block.fields.map((field) => {
|
|
17
|
+
if (!('name' in field))
|
|
18
|
+
return field;
|
|
19
|
+
if (field.name === 'collection' && field.type === 'text') {
|
|
20
|
+
return { name: 'collection', type: 'select', label: field.label ?? 'Collection', options: slugs, required, admin: { description: field.admin?.description } };
|
|
21
|
+
}
|
|
22
|
+
// Picked documents: a relationship to the collections the list can show.
|
|
23
|
+
if (block.type === COLLECTION_LIST_BLOCK && field.name === 'ids' && field.type === 'text') {
|
|
24
|
+
return {
|
|
25
|
+
name: 'ids',
|
|
26
|
+
type: 'relationship',
|
|
27
|
+
label: 'Picked documents',
|
|
28
|
+
relationTo: slugs.length === 1 ? slugs[0] : slugs,
|
|
29
|
+
hasMany: true,
|
|
30
|
+
admin: { description: field.admin?.description },
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return field;
|
|
34
|
+
});
|
|
16
35
|
return { ...block, fields };
|
|
17
36
|
});
|
|
18
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* The collections the collection list block can show: the collections with a `url`, then the
|
|
40
|
+
* `listCollections` option (data collections without pages), each once.
|
|
41
|
+
*/
|
|
42
|
+
export function listableCollections(collections, extra = []) {
|
|
43
|
+
const routed = Object.entries(collections).filter(([, o]) => o.url).map(([slug]) => slug);
|
|
44
|
+
return [...new Set([...routed, ...extra])];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The block list as `websiteBuilder` and `builderMcpTools` use it: `listCollectionsOf` (the
|
|
48
|
+
* collection list's `collection` and `ids` point to `listCollections`, the collections with a
|
|
49
|
+
* `url` and the `listCollections` option), then `withInlineBlocks` (inline blocks may go straight into a link). Run it on the
|
|
50
|
+
* site's own list too, so a seed's `validateLayout` agrees with the editor. Running it twice
|
|
51
|
+
* changes nothing.
|
|
52
|
+
*/
|
|
53
|
+
export function prepareBlocks(blocks, listCollections = []) {
|
|
54
|
+
return withInlineBlocks(listCollectionsOf(blocks, listCollections));
|
|
55
|
+
}
|
|
@@ -62,6 +62,11 @@ export declare function resolveReferences(args: {
|
|
|
62
62
|
collections: CollectionConfig[];
|
|
63
63
|
sources: Record<string, Pick<ReferenceSource, 'layout' | 'blocksOnly' | 'decode'>>;
|
|
64
64
|
blocks: BlockDefinition[];
|
|
65
|
+
/**
|
|
66
|
+
* More collections that get "Used in" and delete protection by default when a block points at
|
|
67
|
+
* them, like upload collections: the saved sections (live `sectionRef` blocks).
|
|
68
|
+
*/
|
|
69
|
+
shared?: string[];
|
|
65
70
|
}): ReferencesServerConfig | null;
|
|
66
71
|
type Id = string | number;
|
|
67
72
|
/**
|
|
@@ -29,7 +29,7 @@ export function resolveReferences(args) {
|
|
|
29
29
|
const isUpload = (slug) => Boolean(bySlug.get(slug)?.upload);
|
|
30
30
|
const targets = referenceTargets(blocks);
|
|
31
31
|
const field = options?.field ?? DEFAULT_REFERENCES_FIELD;
|
|
32
|
-
const uploads = targets.collections.filter(isUpload);
|
|
32
|
+
const uploads = targets.collections.filter((slug) => isUpload(slug) || Boolean(args.shared?.includes(slug)));
|
|
33
33
|
const usedIn = options?.usedIn ?? uploads;
|
|
34
34
|
const protectDelete = options?.protectDelete ?? uploads;
|
|
35
35
|
for (const slug of [...usedIn, ...protectDelete]) {
|
|
@@ -37,6 +37,8 @@ export declare const requireBlocksForDefault: CollectionBeforeChangeHook;
|
|
|
37
37
|
* ticking "Default template" takes effect on Publish.
|
|
38
38
|
*/
|
|
39
39
|
export declare const keepOneDefault: CollectionAfterChangeHook;
|
|
40
|
+
/** Conditions are empty or a where query (a JSON object). Payload checks the fields when the query runs. */
|
|
41
|
+
export declare function validateConditions(value: unknown): true | string;
|
|
40
42
|
/** The templates collection, before the builder field is added (the plugin adds it like any builder collection). */
|
|
41
43
|
export declare function templatesCollection(args: {
|
|
42
44
|
slug: string;
|
|
@@ -44,6 +46,8 @@ export declare function templatesCollection(args: {
|
|
|
44
46
|
/** Labels of the target collections, for the "Collection" select. Default: the slugs. */
|
|
45
47
|
targetLabels?: Record<string, string>;
|
|
46
48
|
hooks?: CollectionConfig['hooks'];
|
|
49
|
+
/** Merged into the collection's `admin` options (e.g. `group`, `hidden`). */
|
|
50
|
+
admin?: CollectionConfig['admin'];
|
|
47
51
|
}): CollectionConfig;
|
|
48
52
|
/** The `template` relationship added to a template-enabled collection (sidebar). */
|
|
49
53
|
export declare function documentTemplateField(target: string, templatesSlug: string): RelationshipField;
|
package/dist/plugin/templates.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Templates for collection documents (docs/architecture.md section 11): the templates collection,
|
|
2
2
|
// the `template` relationship on each target collection, and the bindable field list per collection.
|
|
3
3
|
import { ValidationError, } from 'payload';
|
|
4
|
-
import { DOCUMENT_TEMPLATE_FIELD, TEMPLATE_DEFAULT_FIELD, TEMPLATE_LAYOUT_FIELD, TEMPLATE_PREVIEW_FIELD, TEMPLATE_TARGET_FIELD, URL_PATH, } from '../core/bindings.js';
|
|
4
|
+
import { DOCUMENT_TEMPLATE_FIELD, TEMPLATE_CONDITIONS_FIELD, TEMPLATE_DEFAULT_FIELD, TEMPLATE_LAYOUT_FIELD, TEMPLATE_PREVIEW_FIELD, TEMPLATE_TARGET_FIELD, URL_PATH, } from '../core/bindings.js';
|
|
5
5
|
import { dataFields, textOf } from '../core/fields.js';
|
|
6
6
|
import { normalizeLayout } from '../core/tree.js';
|
|
7
7
|
/** Server-only key in `config.custom`: the templates data (`TemplatesClientConfig`) for the MCP tools. */
|
|
@@ -207,16 +207,26 @@ export const keepOneDefault = async ({ collection, context, doc, req }) => {
|
|
|
207
207
|
}
|
|
208
208
|
return doc;
|
|
209
209
|
};
|
|
210
|
+
/** Conditions are empty or a where query (a JSON object). Payload checks the fields when the query runs. */
|
|
211
|
+
export function validateConditions(value) {
|
|
212
|
+
if (value === null || value === undefined || value === '')
|
|
213
|
+
return true;
|
|
214
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
215
|
+
return 'Conditions must be a where query: a JSON object such as {"tier": {"equals": "vip"}}, or empty.';
|
|
216
|
+
}
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
210
219
|
/** The templates collection, before the builder field is added (the plugin adds it like any builder collection). */
|
|
211
220
|
export function templatesCollection(args) {
|
|
212
|
-
const { slug, targets, hooks, targetLabels } = args;
|
|
221
|
+
const { slug, targets, hooks, targetLabels, admin } = args;
|
|
213
222
|
return {
|
|
214
223
|
slug,
|
|
215
224
|
labels: { singular: 'Template', plural: 'Templates' },
|
|
216
225
|
admin: {
|
|
217
226
|
useAsTitle: 'name',
|
|
218
227
|
defaultColumns: ['name', TEMPLATE_TARGET_FIELD, TEMPLATE_DEFAULT_FIELD, '_status', 'updatedAt'],
|
|
219
|
-
description: 'Layouts for collection documents. Each document renders through its own template or the default one.',
|
|
228
|
+
description: 'Layouts for collection documents. Each document renders through its own template, the first template whose conditions match it, or the default one.',
|
|
229
|
+
...admin,
|
|
220
230
|
},
|
|
221
231
|
versions: { maxPerDoc: 20, drafts: { autosave: { interval: 300 } } },
|
|
222
232
|
hooks: {
|
|
@@ -246,6 +256,15 @@ export function templatesCollection(args) {
|
|
|
246
256
|
components: { Cell: 'payload-canvas/client#TemplateDefaultCell' },
|
|
247
257
|
},
|
|
248
258
|
},
|
|
259
|
+
{
|
|
260
|
+
name: TEMPLATE_CONDITIONS_FIELD,
|
|
261
|
+
type: 'json',
|
|
262
|
+
label: 'Conditions',
|
|
263
|
+
validate: validateConditions,
|
|
264
|
+
admin: {
|
|
265
|
+
description: 'Optional. A Payload where query against the document, for example {"tier": {"equals": "vip"}}. A document without a template of its own uses the first published template (by name) whose conditions match, before the default template.',
|
|
266
|
+
},
|
|
267
|
+
},
|
|
249
268
|
{
|
|
250
269
|
name: TEMPLATE_PREVIEW_FIELD,
|
|
251
270
|
type: 'relationship',
|
|
@@ -265,7 +284,7 @@ export function documentTemplateField(target, templatesSlug) {
|
|
|
265
284
|
label: 'Template',
|
|
266
285
|
relationTo: templatesSlug,
|
|
267
286
|
filterOptions: { [TEMPLATE_TARGET_FIELD]: { equals: target } },
|
|
268
|
-
admin: { position: 'sidebar', description: 'Leave empty to use the default template.' },
|
|
287
|
+
admin: { position: 'sidebar', description: 'Leave empty to use the first template whose conditions match, else the default template.' },
|
|
269
288
|
};
|
|
270
289
|
}
|
|
271
290
|
export function hasFieldNamed(fields, name) {
|
package/dist/protocol/index.d.ts
CHANGED
|
@@ -22,6 +22,8 @@ export type CanvasInit = {
|
|
|
22
22
|
* the layout alone.
|
|
23
23
|
*/
|
|
24
24
|
regions?: RegionConfig[];
|
|
25
|
+
/** Collection -> relationship field path -> related collection, for `<path>.$url` bindings. */
|
|
26
|
+
relations?: Record<string, Record<string, string>>;
|
|
25
27
|
};
|
|
26
28
|
export type PointerKind = 'move' | 'leave' | 'click';
|
|
27
29
|
/** One section to picture. The iframe answers with a `thumbnail` message with the same `key`. */
|
|
@@ -543,6 +543,8 @@ function EditorCanvas({ blocks, components, plugins, resolveLink, server }) {
|
|
|
543
543
|
case 'docChanged':
|
|
544
544
|
forgetDoc(message.collection, message.id);
|
|
545
545
|
setDocsVersion((version) => version + 1);
|
|
546
|
+
// Server blocks may show the document too (an image's alt text).
|
|
547
|
+
serverBlocks?.refresh();
|
|
546
548
|
// A media document of a region (its alt text) or the page itself changed.
|
|
547
549
|
setFrameVersion((version) => version + 1);
|
|
548
550
|
return;
|
|
@@ -746,7 +748,7 @@ function EditorCanvas({ blocks, components, plugins, resolveLink, server }) {
|
|
|
746
748
|
observer.current?.disconnect();
|
|
747
749
|
cancelAnimationFrame(frameRequest.current);
|
|
748
750
|
};
|
|
749
|
-
}, [scheduleMeasure, startInline, stopInline, drag, motion, mapper]);
|
|
751
|
+
}, [scheduleMeasure, startInline, stopInline, drag, motion, mapper, serverBlocks]);
|
|
750
752
|
// The CSS endpoint comes from the admin, or from `?cssEndpoint=` when the page is opened alone.
|
|
751
753
|
const cssEndpoint = init?.cssEndpoint ?? null;
|
|
752
754
|
useEffect(() => {
|
|
@@ -783,7 +785,7 @@ function EditorCanvas({ blocks, components, plugins, resolveLink, server }) {
|
|
|
783
785
|
if (!layout || !init || !definitions)
|
|
784
786
|
return;
|
|
785
787
|
const run = ++resolveRun.current;
|
|
786
|
-
resolveCanvasLayout(layout, context, init.api, definitions, linkResolver, locale)
|
|
788
|
+
resolveCanvasLayout(layout, context, init.api, definitions, linkResolver, locale, init.relations)
|
|
787
789
|
.then((next) => {
|
|
788
790
|
if (run !== resolveRun.current)
|
|
789
791
|
return;
|
|
@@ -942,7 +944,7 @@ function EditorCanvas({ blocks, components, plugins, resolveLink, server }) {
|
|
|
942
944
|
// A drop in the smooth drag mode animates once its layout is on screen, before the browser paints.
|
|
943
945
|
useLayoutEffect(() => drag.rendered(resolvedFrom.current), [shown, drag]);
|
|
944
946
|
// A render for another reason (a new layout still loading its data) reuses the element.
|
|
945
|
-
const rendered = useMemo(() => visible ? (_jsx(RenderLayout, { layout: shown, blocks: definitions, components: canvasComponents, css: css, mode: "canvas", resolveLink: resolveLink, context: context, pageData: pageData })) : null, [visible, shown, definitions, canvasComponents, css, resolveLink, context, pageData]);
|
|
947
|
+
const rendered = useMemo(() => visible ? (_jsx(RenderLayout, { layout: shown, blocks: definitions, components: canvasComponents, css: css, mode: "canvas", resolveLink: resolveLink, context: context, pageData: pageData, relations: init?.relations })) : null, [visible, shown, definitions, canvasComponents, css, resolveLink, context, pageData, init?.relations]);
|
|
946
948
|
const layoutContent = (_jsxs(_Fragment, { children: [visible && shown.blocks.length === 0 && _jsx("div", { "data-builder-empty-page": "" }), _jsx(ServerBlocksContext.Provider, { value: serverContext, children: rendered })] }));
|
|
947
949
|
let page = layoutContent;
|
|
948
950
|
if (frame.status !== 'off' && visible) {
|
|
@@ -6,12 +6,26 @@ type Doc = Record<string, unknown>;
|
|
|
6
6
|
* is not cached.
|
|
7
7
|
*/
|
|
8
8
|
export declare function createRestFetchDocs(api: string, locale?: string | null): FetchDocs;
|
|
9
|
+
/**
|
|
10
|
+
* Payload's REST bracket query for a `where`, e.g. `where[and][0][services][in][0]=5`, as
|
|
11
|
+
* `[name, value]` pairs. Arrays and objects nest; other values become strings.
|
|
12
|
+
*/
|
|
13
|
+
export declare function whereParams(value: unknown, prefix?: string): Array<[string, string]>;
|
|
9
14
|
/**
|
|
10
15
|
* Loads a collection list's documents over REST (`depth=1`, latest drafts, in `locale`), cached
|
|
11
16
|
* for the life of the iframe. The page's own document is filtered out here, so one request serves
|
|
12
|
-
* every page.
|
|
17
|
+
* every page. The query's `where` goes along as Payload's bracket query. A filter that matches
|
|
18
|
+
* nothing (`none`) loads nothing.
|
|
19
|
+
*/
|
|
20
|
+
export declare function fetchListItems(api: string, query: ListQuery, locale?: string | null, seed?: number): Promise<Doc[]>;
|
|
21
|
+
/**
|
|
22
|
+
* `fetchListItems` with the number of pages Payload reports (for a paginated list's page links).
|
|
23
|
+
* Picked ids keep their order, and `$random` lists shuffle with `seed`.
|
|
13
24
|
*/
|
|
14
|
-
export declare function
|
|
25
|
+
export declare function fetchListPage(api: string, query: ListQuery, locale?: string | null, seed?: number): Promise<{
|
|
26
|
+
docs: Doc[];
|
|
27
|
+
totalPages: number;
|
|
28
|
+
}>;
|
|
15
29
|
/**
|
|
16
30
|
* Drops a document from the cache (every locale) and the list results of its collection, so the
|
|
17
31
|
* next layout render loads them again. Used when the editor changed a document outside the layout.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { arrangeListDocs, listRequest } from '../render/lists.js';
|
|
1
2
|
/** One promise per document, shared by every layout render. Key: api + locale + collection + id. */
|
|
2
3
|
const cache = new Map();
|
|
3
4
|
/**
|
|
@@ -46,33 +47,65 @@ export function createRestFetchDocs(api, locale) {
|
|
|
46
47
|
return result;
|
|
47
48
|
};
|
|
48
49
|
}
|
|
49
|
-
/** One promise per list query. Key: api + locale + collection + limit + sort. */
|
|
50
|
+
/** One promise per list query. Key: api + locale + collection + limit + sort + depth + where. */
|
|
50
51
|
const listCache = new Map();
|
|
52
|
+
/**
|
|
53
|
+
* Payload's REST bracket query for a `where`, e.g. `where[and][0][services][in][0]=5`, as
|
|
54
|
+
* `[name, value]` pairs. Arrays and objects nest; other values become strings.
|
|
55
|
+
*/
|
|
56
|
+
export function whereParams(value, prefix = 'where') {
|
|
57
|
+
if (value === undefined || value === null)
|
|
58
|
+
return [];
|
|
59
|
+
if (typeof value !== 'object')
|
|
60
|
+
return [[prefix, String(value)]];
|
|
61
|
+
return Object.entries(value).flatMap(([key, inner]) => whereParams(inner, `${prefix}[${key}]`));
|
|
62
|
+
}
|
|
51
63
|
/**
|
|
52
64
|
* Loads a collection list's documents over REST (`depth=1`, latest drafts, in `locale`), cached
|
|
53
65
|
* for the life of the iframe. The page's own document is filtered out here, so one request serves
|
|
54
|
-
* every page.
|
|
66
|
+
* every page. The query's `where` goes along as Payload's bracket query. A filter that matches
|
|
67
|
+
* nothing (`none`) loads nothing.
|
|
68
|
+
*/
|
|
69
|
+
export function fetchListItems(api, query, locale, seed = 0) {
|
|
70
|
+
return fetchListPage(api, query, locale, seed).then((result) => result.docs);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* `fetchListItems` with the number of pages Payload reports (for a paginated list's page links).
|
|
74
|
+
* Picked ids keep their order, and `$random` lists shuffle with `seed`.
|
|
55
75
|
*/
|
|
56
|
-
export function
|
|
57
|
-
|
|
58
|
-
|
|
76
|
+
export function fetchListPage(api, query, locale, seed = 0) {
|
|
77
|
+
if (query.none)
|
|
78
|
+
return Promise.resolve({ docs: [], totalPages: 0 });
|
|
79
|
+
const wanted = listRequest(query);
|
|
80
|
+
const limit = wanted.limit + (query.exclude === undefined ? 0 : 1);
|
|
81
|
+
const depth = String(query.depth ?? 1);
|
|
82
|
+
const where = whereParams(query.ids ? (query.where ? { and: [{ id: { in: query.ids } }, query.where] } : { id: { in: query.ids } }) : query.where);
|
|
83
|
+
const page = wanted.page ? String(wanted.page) : '';
|
|
84
|
+
const key = `${api}\u0000${locale ?? ''}\u0000${query.collection}\u0000${limit}\u0000${wanted.sort}\u0000${depth}\u0000${JSON.stringify(where)}\u0000${page}`;
|
|
59
85
|
let request = listCache.get(key);
|
|
60
86
|
if (!request) {
|
|
61
|
-
const params = withLocale(new URLSearchParams({ limit: String(limit), sort:
|
|
87
|
+
const params = withLocale(new URLSearchParams({ limit: String(limit), sort: wanted.sort, depth, draft: 'true' }), locale);
|
|
88
|
+
if (page)
|
|
89
|
+
params.set('page', page);
|
|
90
|
+
for (const [name, value] of where)
|
|
91
|
+
params.append(name, value);
|
|
62
92
|
request = fetch(`${api}/${encodeURIComponent(query.collection)}?${params}`, { credentials: 'include' })
|
|
63
93
|
.then(async (res) => {
|
|
64
94
|
if (!res.ok)
|
|
65
95
|
throw new Error(`${res.status} ${res.statusText}`);
|
|
66
96
|
const body = (await res.json());
|
|
67
|
-
return body.docs ?? [];
|
|
97
|
+
return { docs: body.docs ?? [], totalPages: body.totalPages ?? 1 };
|
|
68
98
|
})
|
|
69
99
|
.catch(() => {
|
|
70
100
|
listCache.delete(key);
|
|
71
|
-
return [];
|
|
101
|
+
return { docs: [], totalPages: 0 };
|
|
72
102
|
});
|
|
73
103
|
listCache.set(key, request);
|
|
74
104
|
}
|
|
75
|
-
return request.then((
|
|
105
|
+
return request.then((result) => ({
|
|
106
|
+
docs: arrangeListDocs(result.docs.filter((doc) => query.exclude === undefined || String(doc.id) !== String(query.exclude)), query, seed),
|
|
107
|
+
totalPages: result.totalPages,
|
|
108
|
+
}));
|
|
76
109
|
}
|
|
77
110
|
/**
|
|
78
111
|
* Drops a document from the cache (every locale) and the list results of its collection, so the
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import type { Axis, CanvasMeasurement } from '../../core/index.js';
|
|
1
|
+
import type { Axis, CanvasMeasurement, Rect } from '../../core/index.js';
|
|
2
2
|
/** True when two measurements are equal. Stops at the first difference (scrolling changes `scroll` first). */
|
|
3
3
|
export declare function sameMeasurement(a: CanvasMeasurement | null, b: CanvasMeasurement): boolean;
|
|
4
|
+
/** The smallest rect around all the rects that have a size. Null when none has. */
|
|
5
|
+
export declare function unionRect(rects: readonly Rect[]): Rect | null;
|
|
4
6
|
/** The direction children flow in: from flex direction or the number of grid columns. */
|
|
5
7
|
export declare function axisOf(el: Element): Axis;
|
|
6
8
|
/**
|
|
@@ -35,9 +35,33 @@ export function sameMeasurement(a, b) {
|
|
|
35
35
|
function toRect(r) {
|
|
36
36
|
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
37
37
|
}
|
|
38
|
+
/** The smallest rect around all the rects that have a size. Null when none has. */
|
|
39
|
+
export function unionRect(rects) {
|
|
40
|
+
const sized = rects.filter((r) => r.width > 0 || r.height > 0);
|
|
41
|
+
if (sized.length === 0)
|
|
42
|
+
return null;
|
|
43
|
+
const left = Math.min(...sized.map((r) => r.x));
|
|
44
|
+
const top = Math.min(...sized.map((r) => r.y));
|
|
45
|
+
const right = Math.max(...sized.map((r) => r.x + r.width));
|
|
46
|
+
const bottom = Math.max(...sized.map((r) => r.y + r.height));
|
|
47
|
+
return { x: left, y: top, width: right - left, height: bottom - top };
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The element's box. An element with `display: contents` (a repeat without a wrapper, or a block
|
|
51
|
+
* with the `contents` class) has no box of its own: it gets the box around its children.
|
|
52
|
+
*/
|
|
53
|
+
function boxOf(el) {
|
|
54
|
+
const own = toRect(el.getBoundingClientRect());
|
|
55
|
+
if (own.width > 0 || own.height > 0 || getComputedStyle(el).display !== 'contents')
|
|
56
|
+
return own;
|
|
57
|
+
return unionRect(Array.from(el.children, boxOf)) ?? own;
|
|
58
|
+
}
|
|
38
59
|
/** The direction children flow in: from flex direction or the number of grid columns. */
|
|
39
60
|
export function axisOf(el) {
|
|
40
61
|
const style = getComputedStyle(el);
|
|
62
|
+
// No box of its own: its children flow in the parent.
|
|
63
|
+
if (style.display === 'contents' && el.parentElement)
|
|
64
|
+
return axisOf(el.parentElement);
|
|
41
65
|
if (style.display.includes('flex'))
|
|
42
66
|
return style.flexDirection.startsWith('row') ? 'x' : 'y';
|
|
43
67
|
if (style.display.includes('grid')) {
|
|
@@ -53,7 +77,7 @@ export function axisOf(el) {
|
|
|
53
77
|
export function measure(root) {
|
|
54
78
|
const blocks = Array.from(root.querySelectorAll('[data-block-id]'), (el) => ({
|
|
55
79
|
id: el.dataset.blockId ?? '',
|
|
56
|
-
rect:
|
|
80
|
+
rect: boxOf(el),
|
|
57
81
|
}));
|
|
58
82
|
const slots = new Map();
|
|
59
83
|
for (const el of root.querySelectorAll('[data-slot-owner]')) {
|
|
@@ -65,7 +89,7 @@ export function measure(root) {
|
|
|
65
89
|
continue;
|
|
66
90
|
// An empty placeholder takes the container's axis, so the drop indicator matches the layout.
|
|
67
91
|
const axis = empty && el.parentElement ? axisOf(el.parentElement) : axisOf(el);
|
|
68
|
-
slots.set(key, { ownerId, slot, rect:
|
|
92
|
+
slots.set(key, { ownerId, slot, rect: boxOf(el), axis, empty });
|
|
69
93
|
}
|
|
70
94
|
// In a page frame the layout fills its outlet, not the whole canvas: the root list's axis and
|
|
71
95
|
// box come from the outlet, so fixed regions never count as part of the layout.
|