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
@@ -46,6 +46,142 @@ export function starterSlots(blocks, type, makeId) {
46
46
  export function defineBlock(def) {
47
47
  return def;
48
48
  }
49
+ /** The blocks with every missing id filled as `<prefix>_1`, `_2`, … (see `defineSection`). */
50
+ function fillBlockIds(owner, prefix, blocks) {
51
+ const given = new Set();
52
+ const collect = (list) => {
53
+ for (const block of list) {
54
+ if (block.id) {
55
+ if (given.has(block.id))
56
+ throw new Error(`defineSection("${owner}"): two blocks have the id "${block.id}".`);
57
+ given.add(block.id);
58
+ }
59
+ for (const children of Object.values(block.slots ?? {}))
60
+ collect(children);
61
+ }
62
+ };
63
+ collect(blocks);
64
+ let count = 0;
65
+ const nextId = () => {
66
+ let id;
67
+ do
68
+ id = `${prefix}_${++count}`;
69
+ while (given.has(id));
70
+ return id;
71
+ };
72
+ const fill = (list) => list.map(({ slots, ...rest }) => {
73
+ const block = { ...rest, id: rest.id || nextId() };
74
+ if (slots)
75
+ block.slots = Object.fromEntries(Object.entries(slots).map(([name, children]) => [name, fill(children)]));
76
+ return block;
77
+ });
78
+ return fill(blocks);
79
+ }
80
+ /**
81
+ * A section with every missing block id filled: `<section id>_1`, `_2`, … in walk order (each
82
+ * block before its slots, slots in their order), skipping ids that are given. A variant's blocks
83
+ * get `<section id>_<variant id>_1`, … The same input always gives the same ids. Throws when `id`
84
+ * or `label` is missing (also on a variant), two variants share an id, or two blocks of one tree
85
+ * share an id.
86
+ */
87
+ export function defineSection(input) {
88
+ if (typeof input.id !== 'string' || !input.id.trim())
89
+ throw new Error('defineSection: the section needs an "id".');
90
+ if (typeof input.label !== 'string' || !input.label.trim())
91
+ throw new Error(`defineSection("${input.id}"): the section needs a "label".`);
92
+ const { variants, ...rest } = input;
93
+ const section = { ...rest, blocks: fillBlockIds(input.id, input.id, input.blocks) };
94
+ if (variants) {
95
+ checkVariants(input.id, variants);
96
+ section.variants = variants.map((variant) => ({ ...variant, blocks: fillBlockIds(input.id, `${input.id}_${variant.id}`, variant.blocks) }));
97
+ }
98
+ return section;
99
+ }
100
+ function checkVariants(section, variants) {
101
+ const seen = new Set();
102
+ for (const variant of variants) {
103
+ if (typeof variant.id !== 'string' || !variant.id.trim())
104
+ throw new Error(`Section "${section}": a variant needs an "id".`);
105
+ if (typeof variant.label !== 'string' || !variant.label.trim())
106
+ throw new Error(`Section "${section}": variant "${variant.id}" needs a "label".`);
107
+ if (seen.has(variant.id))
108
+ throw new Error(`Section "${section}": two variants have the id "${variant.id}".`);
109
+ seen.add(variant.id);
110
+ }
111
+ }
112
+ /**
113
+ * The sections with each variant as a section of its own, right after its section: id
114
+ * `<section id>/<variant id>`, label `<section label> (<variant label>)`, the section's category,
115
+ * its description unless the variant has one, and `variantOf` set to the section id. The section
116
+ * itself stays the first version and loses its `variants` key. The plugin and `builderMcpTools`
117
+ * run it on the app's `sections`, so the library, the insert picker, MCP and the assistant all
118
+ * list the variants. Throws on a variant without id or label, or two variants with one id.
119
+ */
120
+ export function sectionsWithVariants(sections) {
121
+ return sections.flatMap(({ variants, ...section }) => {
122
+ if (!variants?.length)
123
+ return [section];
124
+ checkVariants(section.id, variants);
125
+ return [
126
+ section,
127
+ ...variants.map((variant) => ({
128
+ id: `${section.id}/${variant.id}`,
129
+ label: `${section.label} (${variant.label})`,
130
+ ...(variant.description ?? section.description ? { description: variant.description ?? section.description } : {}),
131
+ ...(section.category ? { category: section.category } : {}),
132
+ blocks: variant.blocks,
133
+ variantOf: section.id,
134
+ })),
135
+ ];
136
+ });
137
+ }
138
+ /**
139
+ * The blocks with each block's `defaultClassName` filled where the block has no `className` key, at
140
+ * any depth. A `className` of `''` stays empty. Blocks of unknown types stay as they are. The
141
+ * plugin and `builderMcpTools` run it on the app's `sections`, so a section tree may leave out a
142
+ * block's default classes. Seeds that build layouts by hand can run it too.
143
+ */
144
+ export function withDefaultClassNames(list, definitions) {
145
+ return list.map((block) => {
146
+ const next = { ...block };
147
+ const fallback = block.className === undefined ? getBlockDefinition(definitions, block.type)?.defaultClassName : undefined;
148
+ if (fallback)
149
+ next.className = fallback;
150
+ if (block.slots) {
151
+ next.slots = Object.fromEntries(Object.entries(block.slots).map(([name, children]) => [name, withDefaultClassNames(children, definitions)]));
152
+ }
153
+ return next;
154
+ });
155
+ }
156
+ /** `withDefaultClassNames` on the blocks of every section and its variants. */
157
+ export function sectionsWithDefaultClassNames(sections, definitions) {
158
+ return sections.map((section) => ({
159
+ ...section,
160
+ blocks: withDefaultClassNames(section.blocks, definitions),
161
+ ...(section.variants ? { variants: section.variants.map((v) => ({ ...v, blocks: withDefaultClassNames(v.blocks, definitions) })) } : {}),
162
+ }));
163
+ }
164
+ /**
165
+ * The blocks with every `allowInline` slot accepting the block types marked `inline: true`: they
166
+ * join the slot's `allow` list. The plugin and `builderMcpTools` run it on their block list, so
167
+ * the editor, the checks and the AI tools all see the same rule. Returns the same list when no
168
+ * block is inline.
169
+ */
170
+ export function withInlineBlocks(blocks) {
171
+ const inline = blocks.filter((b) => b.inline).map((b) => b.type);
172
+ if (inline.length === 0)
173
+ return blocks;
174
+ return blocks.map((def) => {
175
+ const slots = def.slots;
176
+ if (!slots || !Object.values(slots).some((slot) => slot.allowInline && slot.allow))
177
+ return def;
178
+ const next = Object.fromEntries(Object.entries(slots).map(([name, slot]) => [
179
+ name,
180
+ slot.allowInline && slot.allow ? { ...slot, allow: [...new Set([...slot.allow, ...inline.filter((t) => !slot.disallow?.includes(t))])] } : slot,
181
+ ]));
182
+ return { ...def, slots: next };
183
+ });
184
+ }
49
185
  export function getBlockDefinition(blocks, type) {
50
186
  return blocks.find((b) => b.type === type);
51
187
  }
@@ -1,6 +1,14 @@
1
+ import { type DataField } from './fields.js';
1
2
  import type { BlockDefinition, Layout } from './types.js';
2
3
  /**
3
- * Every distinct class the layout needs, sorted: each block's `className` (hidden blocks too),
4
- * plus `BlockDefinition.classes` of every block type in the layout when `blocks` is given.
4
+ * The block's top-level text props that hold Tailwind classes: fields with
5
+ * `admin: { custom: { builderClasses: true } }`, for example a carousel's `arrowClassName`.
6
+ * The save hook and the canvas compile their values (and their `defaultValue`) like `className`.
7
+ */
8
+ export declare function classFields(def: Pick<BlockDefinition, 'fields'> | undefined): DataField[];
9
+ /**
10
+ * Every distinct class the layout needs, sorted: each block's `className` and `slotClassName` (hidden blocks too),
11
+ * plus, when `blocks` is given, `BlockDefinition.classes` of every block type in the layout and the
12
+ * values of its class props (`classFields`) in every locale, with their defaults.
5
13
  */
6
14
  export declare function collectClasses(layout: Layout, blocks?: readonly BlockDefinition[]): string[];
@@ -1,4 +1,16 @@
1
- import { walkBlocks } from './tree.js';
1
+ import { dataFields } from './fields.js';
2
+ import { isPlainObject, walkBlocks } from './tree.js';
3
+ /**
4
+ * The block's top-level text props that hold Tailwind classes: fields with
5
+ * `admin: { custom: { builderClasses: true } }`, for example a carousel's `arrowClassName`.
6
+ * The save hook and the canvas compile their values (and their `defaultValue`) like `className`.
7
+ */
8
+ export function classFields(def) {
9
+ return dataFields(def?.fields).filter((field) => {
10
+ const admin = field.admin;
11
+ return field.type === 'text' && isPlainObject(admin) && isPlainObject(admin.custom) && admin.custom.builderClasses === true;
12
+ });
13
+ }
2
14
  function addClasses(target, value) {
3
15
  for (const name of value.split(/\s+/)) {
4
16
  if (name)
@@ -6,24 +18,41 @@ function addClasses(target, value) {
6
18
  }
7
19
  }
8
20
  /**
9
- * Every distinct class the layout needs, sorted: each block's `className` (hidden blocks too),
10
- * plus `BlockDefinition.classes` of every block type in the layout when `blocks` is given.
21
+ * Every distinct class the layout needs, sorted: each block's `className` and `slotClassName` (hidden blocks too),
22
+ * plus, when `blocks` is given, `BlockDefinition.classes` of every block type in the layout and the
23
+ * values of its class props (`classFields`) in every locale, with their defaults.
11
24
  */
12
25
  export function collectClasses(layout, blocks) {
13
26
  const classes = new Set();
14
27
  const types = new Set();
28
+ const propsOf = new Map((blocks ?? []).map((def) => [def.type, classFields(def)]));
15
29
  walkBlocks(layout, (block) => {
16
30
  types.add(block.type);
17
31
  if (typeof block.className === 'string')
18
32
  addClasses(classes, block.className);
33
+ for (const value of Object.values(block.slotClassName ?? {}))
34
+ if (typeof value === 'string')
35
+ addClasses(classes, value);
36
+ for (const field of propsOf.get(block.type) ?? []) {
37
+ for (const values of [block.props, ...Object.values(block.locales ?? {})]) {
38
+ const value = values?.[field.name];
39
+ if (typeof value === 'string')
40
+ addClasses(classes, value);
41
+ }
42
+ }
19
43
  });
20
44
  for (const definition of blocks ?? []) {
21
- if (!types.has(definition.type) || !Array.isArray(definition.classes))
45
+ if (!types.has(definition.type))
22
46
  continue;
23
- for (const value of definition.classes) {
47
+ for (const value of definition.classes ?? []) {
24
48
  if (typeof value === 'string')
25
49
  addClasses(classes, value);
26
50
  }
51
+ for (const field of propsOf.get(definition.type) ?? []) {
52
+ const fallback = field.defaultValue;
53
+ if (typeof fallback === 'string')
54
+ addClasses(classes, fallback);
55
+ }
27
56
  }
28
57
  return [...classes].toSorted();
29
58
  }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * An id from a heading's text: accents removed, lowercase, every run of other characters than
3
+ * letters and digits (any script) turned into "-", no "-" at the ends. "Über uns & Preise" gives
4
+ * "uber-uns-preise". Empty text gives "".
5
+ */
6
+ export declare function headingId(text: string): string;
7
+ export type RichTextHeading = {
8
+ /** The heading's id: `headingId` of its text, with "-2", "-3", … for repeated texts. */
9
+ id: string;
10
+ text: string;
11
+ /** 1 to 6, from the tag (`h2` is 2). */
12
+ level: number;
13
+ /** The Lexical heading node, as stored. */
14
+ node: Record<string, unknown>;
15
+ };
16
+ /**
17
+ * The headings of a Lexical rich text value, in document order, each with a unique id. The field
18
+ * block (`headingIds`) puts the same ids on the headings it renders. A heading without letters or
19
+ * digits gets "section".
20
+ */
21
+ export declare function richTextHeadings(value: unknown): RichTextHeading[];
@@ -0,0 +1,47 @@
1
+ // Ids for rich text headings, so a table of contents can link to them (`#id`). Pure: no React.
2
+ /**
3
+ * An id from a heading's text: accents removed, lowercase, every run of other characters than
4
+ * letters and digits (any script) turned into "-", no "-" at the ends. "Über uns & Preise" gives
5
+ * "uber-uns-preise". Empty text gives "".
6
+ */
7
+ export function headingId(text) {
8
+ return text
9
+ .normalize('NFKD')
10
+ .replace(/\p{M}+/gu, '')
11
+ .toLowerCase()
12
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
13
+ .replace(/^-+|-+$/g, '');
14
+ }
15
+ const childrenOf = (node) => Array.isArray(node.children) ? node.children.filter((c) => typeof c === 'object' && c !== null) : [];
16
+ function textOf(node) {
17
+ if (typeof node.text === 'string')
18
+ return node.text;
19
+ return childrenOf(node).map(textOf).join('');
20
+ }
21
+ /**
22
+ * The headings of a Lexical rich text value, in document order, each with a unique id. The field
23
+ * block (`headingIds`) puts the same ids on the headings it renders. A heading without letters or
24
+ * digits gets "section".
25
+ */
26
+ export function richTextHeadings(value) {
27
+ const root = typeof value === 'object' && value !== null ? value.root : null;
28
+ if (typeof root !== 'object' || root === null)
29
+ return [];
30
+ const out = [];
31
+ const used = new Map();
32
+ const visit = (node) => {
33
+ if (node.type === 'heading') {
34
+ const text = textOf(node).trim();
35
+ const base = headingId(text) || 'section';
36
+ const seen = (used.get(base) ?? 0) + 1;
37
+ used.set(base, seen);
38
+ const level = typeof node.tag === 'string' ? Number(node.tag.slice(1)) || 1 : 1;
39
+ out.push({ id: seen === 1 ? base : `${base}-${seen}`, text, level, node: node });
40
+ return;
41
+ }
42
+ for (const child of childrenOf(node))
43
+ visit(child);
44
+ };
45
+ visit(root);
46
+ return out;
47
+ }
@@ -1,9 +1,11 @@
1
1
  export * from './types.js';
2
+ export { checkAttrs, htmlAttributes, htmlIdClash, htmlIdProblem, htmlIdsOf, patchAttrs, withoutTakenHtmlIds } from './attrs.js';
2
3
  export { createId } from './ids.js';
3
4
  export { findBlock, findLocation, walkBlocks, isSelfOrDescendant, normalizeLayout, type BlockLocation } from './tree.js';
4
5
  export { applyOperation, applyOperations, type ApplyOptions } from './operations.js';
5
6
  export { deepestBlockAt, canvasDropTarget, outlineDropTarget } from './dropTarget.js';
6
- export { collectClasses } from './classes.js';
7
+ export { classFields, collectClasses } from './classes.js';
8
+ export { headingId, richTextHeadings, type RichTextHeading } from './headings.js';
7
9
  export { blockJsonSchema, layoutJsonSchema } from './schema.js';
8
10
  export { validateLayout, isBlockingError, isLayoutWarning, PUBLISH_ONLY_CODES, type LayoutError, type LayoutErrorCode, type ValidateOptions } from './validate.js';
9
11
  export { blockInLocale, createLocaleView, fallbackChain, hasLocaleValues, hasLocalizedProps, hasOwnValue, knownLocale, localeLabel, localeSettingsOf, localeWithValue, localesIn, localizedKeys, localizedValue, localizeOperations, mergeLocaleView, missingDefaultKeys, ownValue, resolveLayoutLocale, stampLocale, untranslatedKeys, type FallbackLocale, } from './locale.js';
@@ -11,7 +13,7 @@ export * from './styles.js';
11
13
  export * from './motion.js';
12
14
  export * from './bindings.js';
13
15
  export { TEXT_LIST_BLOCK, TEXT_LIST_ITEM_BLOCK, TEXT_LIST_SLOT, joinListItem, splitListItem, type ListItemEdit } from './textList.js';
14
- export { blockName, defineBlock, fitsParent, getBlockDefinition, placementError, slotAccepts, slotAcceptsAt, slotNames, starterSlots } from './blocks.js';
16
+ export { blockName, defineBlock, defineSection, type SectionBlockInput, type SectionInput, fitsParent, getBlockDefinition, placementError, sectionsWithDefaultClassNames, sectionsWithVariants, slotAccepts, slotAcceptsAt, slotNames, starterSlots, withDefaultClassNames, withInlineBlocks } from './blocks.js';
15
17
  export { FORMATS, formatProblem, isPlayableVideoUrl, parseVideoUrl, videoUrlProblem, type FormatCheck, type VideoEmbed, type VideoOptions } from './formats.js';
16
18
  export { describeLayoutErrors, summarizeProblems, type LayoutIssue } from './issues.js';
17
19
  export { conditionFromFunction, conditionMet, readCondition, type BuilderCondition } from './conditions.js';
@@ -1,11 +1,13 @@
1
1
  // Public core API: pure functions, safe on the server, in the admin and in the canvas iframe.
2
2
  // Owner: core agent. Signatures here are the contract other parts build against.
3
3
  export * from './types.js';
4
+ export { checkAttrs, htmlAttributes, htmlIdClash, htmlIdProblem, htmlIdsOf, patchAttrs, withoutTakenHtmlIds } from './attrs.js';
4
5
  export { createId } from './ids.js';
5
6
  export { findBlock, findLocation, walkBlocks, isSelfOrDescendant, normalizeLayout } from './tree.js';
6
7
  export { applyOperation, applyOperations } from './operations.js';
7
8
  export { deepestBlockAt, canvasDropTarget, outlineDropTarget } from './dropTarget.js';
8
- export { collectClasses } from './classes.js';
9
+ export { classFields, collectClasses } from './classes.js';
10
+ export { headingId, richTextHeadings } from './headings.js';
9
11
  export { blockJsonSchema, layoutJsonSchema } from './schema.js';
10
12
  export { validateLayout, isBlockingError, isLayoutWarning, PUBLISH_ONLY_CODES } from './validate.js';
11
13
  export { blockInLocale, createLocaleView, fallbackChain, hasLocaleValues, hasLocalizedProps, hasOwnValue, knownLocale, localeLabel, localeSettingsOf, localeWithValue, localesIn, localizedKeys, localizedValue, localizeOperations, mergeLocaleView, missingDefaultKeys, ownValue, resolveLayoutLocale, stampLocale, untranslatedKeys, } from './locale.js';
@@ -13,7 +15,7 @@ export * from './styles.js';
13
15
  export * from './motion.js';
14
16
  export * from './bindings.js';
15
17
  export { TEXT_LIST_BLOCK, TEXT_LIST_ITEM_BLOCK, TEXT_LIST_SLOT, joinListItem, splitListItem } from './textList.js';
16
- export { blockName, defineBlock, fitsParent, getBlockDefinition, placementError, slotAccepts, slotAcceptsAt, slotNames, starterSlots } from './blocks.js';
18
+ export { blockName, defineBlock, defineSection, fitsParent, getBlockDefinition, placementError, sectionsWithDefaultClassNames, sectionsWithVariants, slotAccepts, slotAcceptsAt, slotNames, starterSlots, withDefaultClassNames, withInlineBlocks } from './blocks.js';
17
19
  export { FORMATS, formatProblem, isPlayableVideoUrl, parseVideoUrl, videoUrlProblem } from './formats.js';
18
20
  export { describeLayoutErrors, summarizeProblems } from './issues.js';
19
21
  export { conditionFromFunction, conditionMet, readCondition } from './conditions.js';
@@ -2,7 +2,7 @@ import type { Block } from './types.js';
2
2
  export declare const ENTER_PRESETS: readonly ['fade', 'fade-up', 'fade-down', 'fade-left', 'fade-right', 'zoom-in', 'zoom-out', 'blur-in', 'wipe-up', 'wipe-down', 'wipe-left', 'wipe-right'];
3
3
  export declare const HOVER_PRESETS: readonly ['lift', 'grow', 'tilt'];
4
4
  export declare const PRESS_PRESETS: readonly ['shrink'];
5
- export declare const SCROLL_PRESETS: readonly ['parallax', 'fade', 'zoom'];
5
+ export declare const SCROLL_PRESETS: readonly ['parallax', 'fade', 'zoom', 'recede'];
6
6
  export declare const LOOP_PRESETS: readonly ['float', 'pulse'];
7
7
  export declare const MOTION_EASINGS: readonly ['ease-out', 'ease-in-out', 'linear', 'spring', 'bouncy'];
8
8
  export declare const ENTER_TRIGGERS: readonly ['view', 'load'];
@@ -60,7 +60,7 @@ export type ScrollMotion = {
60
60
  preset: ScrollPreset;
61
61
  /** "parallax": pixels the block moves against the scroll over its pass. Negative moves with it. Default 60. */
62
62
  distance?: number;
63
- /** "zoom": the scale it starts from at the bottom of the window. Default 0.9. */
63
+ /** "zoom": the scale it starts from at the bottom of the window. "recede": the scale it shrinks to. Default 0.9. */
64
64
  scale?: number;
65
65
  };
66
66
  /** Plays again and again while the block is in view. */
@@ -126,6 +126,8 @@ export declare const SCROLL_DEFAULTS: {
126
126
  distance: number;
127
127
  scale: number;
128
128
  };
129
+ /** "recede": the brightness a block dims to while the next block covers it. */
130
+ export declare const RECEDE_BRIGHTNESS = 0.7;
129
131
  export declare const LOOP_DEFAULTS: {
130
132
  float: {
131
133
  duration: number;
@@ -203,16 +205,23 @@ export declare function interactTransform(hover: HoverMotion | undefined, press:
203
205
  pressed: boolean;
204
206
  tilt?: [number, number];
205
207
  }): string;
208
+ /** The properties a scroll effect animates. They add to the block's own transform and to the other effects. */
209
+ export type ScrollProperty = 'translate' | 'opacity' | 'scale' | 'filter';
206
210
  /**
207
- * A scroll-linked effect: keyframes of one CSS property over the block's pass through the window.
208
- * `offset` pairs are [block progress, window progress] (Motion's `scroll` offsets): [0, 1] is the
209
- * block's top at the window's bottom, [1, 0] its bottom at the window's top. Null with reduced motion for effects that move.
211
+ * A scroll-linked effect: keyframes of CSS properties over a pass through the window.
212
+ * `offset` pairs are [element progress, window progress] (Motion's `scroll` offsets): [0, 1] is the
213
+ * element's top at the window's bottom, [1, 0] its bottom at the window's top. `target` names the
214
+ * element whose pass drives it: the block itself, or the block's next sibling (the card that slides
215
+ * over a receding card). Every offset here maps to a native ViewTimeline range, so the browser
216
+ * runs the effect off the main thread where it can.
210
217
  */
211
- export declare function scrollPlan(scroll: ScrollMotion, reduced?: boolean): {
212
- property: 'translate' | 'opacity' | 'scale';
213
- keyframes: Array<string | number>;
218
+ export type ScrollPlan = {
219
+ keyframes: Partial<Record<ScrollProperty, Array<string | number>>>;
214
220
  offset: [[number, number], [number, number]];
215
- } | null;
221
+ target: 'self' | 'next';
222
+ };
223
+ /** The plan of a scroll effect. Null with reduced motion for effects that move or scale. */
224
+ export declare function scrollPlan(scroll: ScrollMotion, reduced?: boolean): ScrollPlan | null;
216
225
  /** A loop: one CSS property, there and back forever. Null with reduced motion. */
217
226
  export declare function loopPlan(loop: LoopMotion, reduced?: boolean): {
218
227
  property: 'translate' | 'scale';
@@ -24,7 +24,7 @@ export const ENTER_PRESETS = [
24
24
  ];
25
25
  export const HOVER_PRESETS = ['lift', 'grow', 'tilt'];
26
26
  export const PRESS_PRESETS = ['shrink'];
27
- export const SCROLL_PRESETS = ['parallax', 'fade', 'zoom'];
27
+ export const SCROLL_PRESETS = ['parallax', 'fade', 'zoom', 'recede'];
28
28
  export const LOOP_PRESETS = ['float', 'pulse'];
29
29
  export const MOTION_EASINGS = ['ease-out', 'ease-in-out', 'linear', 'spring', 'bouncy'];
30
30
  export const ENTER_TRIGGERS = ['view', 'load'];
@@ -63,6 +63,8 @@ export const DEFAULT_STAGGER = 80;
63
63
  export const HOVER_DEFAULTS = { distance: 4, scale: 1.03, angle: 6 };
64
64
  export const PRESS_DEFAULTS = { scale: 0.97 };
65
65
  export const SCROLL_DEFAULTS = { distance: 60, scale: 0.9 };
66
+ /** "recede": the brightness a block dims to while the next block covers it. */
67
+ export const RECEDE_BRIGHTNESS = 0.7;
66
68
  export const LOOP_DEFAULTS = { float: { duration: 3000, distance: 8 }, pulse: { duration: 1500, scale: 1.04 } };
67
69
  /** Labels and one-line descriptions, in menu order. */
68
70
  export const MOTION_PRESET_INFO = {
@@ -90,6 +92,7 @@ export const MOTION_PRESET_INFO = {
90
92
  { value: 'parallax', label: 'Parallax', description: 'Moves slower or faster than the page while you scroll.' },
91
93
  { value: 'fade', label: 'Fade', description: 'Fades in as it rises into the window.' },
92
94
  { value: 'zoom', label: 'Zoom', description: 'Grows to full size as it rises into the window.' },
95
+ { value: 'recede', label: 'Recede', description: 'Shrinks and dims while the next block scrolls over it. For stacked sticky cards.' },
93
96
  ],
94
97
  loop: [
95
98
  { value: 'float', label: 'Float', description: 'Floats gently up and down.' },
@@ -313,22 +316,27 @@ export function interactTransform(hover, press, state) {
313
316
  return parts.length > 0 ? parts.join(' ') : 'none';
314
317
  }
315
318
  const round = (n) => Math.round(n * 100) / 100;
316
- /**
317
- * A scroll-linked effect: keyframes of one CSS property over the block's pass through the window.
318
- * `offset` pairs are [block progress, window progress] (Motion's `scroll` offsets): [0, 1] is the
319
- * block's top at the window's bottom, [1, 0] its bottom at the window's top. Null with reduced motion for effects that move.
320
- */
319
+ /** The plan of a scroll effect. Null with reduced motion for effects that move or scale. */
321
320
  export function scrollPlan(scroll, reduced = false) {
322
- // Fade and zoom finish when the block's middle reaches the window's bottom edge. Both offsets
323
- // map to a native ViewTimeline range, so the browser runs them off the main thread.
321
+ // Fade and zoom finish when the block's middle reaches the window's bottom edge.
324
322
  if (scroll.preset === 'fade')
325
- return { property: 'opacity', keyframes: [0, 1], offset: [[0, 1], [0.5, 1]] };
323
+ return { keyframes: { opacity: [0, 1] }, offset: [[0, 1], [0.5, 1]], target: 'self' };
326
324
  if (reduced)
327
325
  return null;
328
326
  if (scroll.preset === 'zoom')
329
- return { property: 'scale', keyframes: [scroll.scale ?? SCROLL_DEFAULTS.scale, 1], offset: [[0, 1], [0.5, 1]] };
327
+ return { keyframes: { scale: [scroll.scale ?? SCROLL_DEFAULTS.scale, 1] }, offset: [[0, 1], [0.5, 1]], target: 'self' };
328
+ if (scroll.preset === 'recede') {
329
+ // Follows the next block from the window's bottom to its top. The next block's own pass is
330
+ // never affected by `position: sticky` on this block, and it ends when the next card reaches
331
+ // the top, where a stacked card sticks and covers this one. The last block has no next one.
332
+ return {
333
+ keyframes: { scale: [1, scroll.scale ?? SCROLL_DEFAULTS.scale], filter: ['brightness(1)', `brightness(${RECEDE_BRIGHTNESS})`] },
334
+ offset: [[0, 1], [0, 0]],
335
+ target: 'next',
336
+ };
337
+ }
330
338
  const d = scroll.distance ?? SCROLL_DEFAULTS.distance;
331
- return { property: 'translate', keyframes: [`0px ${d}px`, `0px ${-d}px`], offset: [[0, 1], [1, 0]] };
339
+ return { keyframes: { translate: [`0px ${d}px`, `0px ${-d}px`] }, offset: [[0, 1], [1, 0]], target: 'self' };
332
340
  }
333
341
  /** A loop: one CSS property, there and back forever. Null with reduced motion. */
334
342
  export function loopPlan(loop, reduced = false) {
@@ -463,7 +471,7 @@ export function motionJsonSchema() {
463
471
  }),
464
472
  scroll: kindSchema('scroll', 'Follows the scroll position while the block passes through the window.', {
465
473
  distance: numberSchema('scroll', 'distance', 'parallax: pixels it moves against the scroll. Negative moves with it. Default 60.'),
466
- scale: numberSchema('scroll', 'scale', 'zoom: the scale it starts from. Default 0.9.'),
474
+ scale: numberSchema('scroll', 'scale', 'zoom: the scale it starts from. recede: the scale it shrinks to. Default 0.9.'),
467
475
  }),
468
476
  loop: kindSchema('loop', 'Plays again and again while in view. Use rarely, on small decorative blocks.', {
469
477
  duration: numberSchema('loop', 'duration', 'Milliseconds one way. Default 3000 (float) or 1500 (pulse).'),
@@ -4,6 +4,7 @@
4
4
  // Canonical form (see tree.ts): no empty slot lists, no empty `slots`/`props`/`bindings` objects,
5
5
  // `hidden` only when true. Operations keep this form. When a slot list becomes empty, its key is
6
6
  // deleted. This is what makes every inverse restore the exact previous layout.
7
+ import { checkAttrs, htmlIdClash, htmlIdsOf, patchAttrs, withoutTakenHtmlIds } from './attrs.js';
7
8
  import { placementError, slotFullError } from './blocks.js';
8
9
  import { createId } from './ids.js';
9
10
  import { checkMotion, motionInverse, patchMotion } from './motion.js';
@@ -63,6 +64,9 @@ function insert(layout, rawBlock, rawTo, blocks) {
63
64
  const refused = blocks ? placementError(blocks, layout, to.parentId, to.slot, checked, index) : null;
64
65
  if (refused)
65
66
  return fail(refused);
67
+ const clash = htmlIdClash(layout, checked);
68
+ if (clash)
69
+ return fail(clash);
66
70
  const next = mapList(layout, to.parentId, to.slot, (list) => insertAt(list, to.index, checked));
67
71
  return ok(next, [{ type: 'remove', id: checked.id }]);
68
72
  }
@@ -111,7 +115,8 @@ function duplicate(layout, id, newId, blocks) {
111
115
  return fail(full);
112
116
  const used = new Set(index.keys());
113
117
  used.add(newId);
114
- const copy = cloneWithNewIds(entry.block, newId, used);
118
+ // The copy leaves out the HTML ids: each id is unique in the layout.
119
+ const copy = withoutTakenHtmlIds(cloneWithNewIds(entry.block, newId, used), htmlIdsOf(layout.blocks));
115
120
  const next = mapList(layout, entry.parentId, entry.slot, (list) => insertAt(list, entry.index + 1, copy));
116
121
  return ok(next, [{ type: 'remove', id: newId }]);
117
122
  }
@@ -236,6 +241,41 @@ function update(layout, op) {
236
241
  else
237
242
  delete next.motion;
238
243
  }
244
+ if (op.slotClassName !== undefined) {
245
+ if (!isPlainObject(op.slotClassName))
246
+ return fail('`slotClassName` must be an object of slot name -> classes');
247
+ const old = before.slotClassName ?? {};
248
+ const merged = { ...old };
249
+ const inv = {};
250
+ for (const [slot, value] of Object.entries(op.slotClassName)) {
251
+ if (value !== null && typeof value !== 'string')
252
+ return fail(`slotClassName.${slot} must be a string or null`);
253
+ setOwn(inv, slot, Object.hasOwn(old, slot) ? old[slot] : null);
254
+ if (value?.trim())
255
+ setOwn(merged, slot, value);
256
+ else
257
+ delete merged[slot];
258
+ }
259
+ inverse.slotClassName = inv;
260
+ if (Object.keys(merged).length > 0)
261
+ next.slotClassName = merged;
262
+ else
263
+ delete next.slotClassName;
264
+ }
265
+ if (op.attrs !== undefined) {
266
+ const patched = patchAttrs(before.attrs, op.attrs);
267
+ if (typeof patched === 'string')
268
+ return fail(patched);
269
+ inverse.attrs = patched.inverse;
270
+ if (patched.attrs)
271
+ next.attrs = patched.attrs;
272
+ else
273
+ delete next.attrs;
274
+ const id = patched.attrs?.id;
275
+ const owner = id && id !== before.attrs?.id ? htmlIdsOf(layout.blocks).get(id) : undefined;
276
+ if (owner)
277
+ return fail(`The HTML id "${id}" is already used by block "${owner}". Every id is unique in a layout.`);
278
+ }
239
279
  const result = mapList(layout, entry.parentId, entry.slot, (list) => replaceAt(list, entry.index, next));
240
280
  return ok(result, [inverse]);
241
281
  }
@@ -341,6 +381,10 @@ function cloneWithNewIds(block, id, used) {
341
381
  clone.locales = structuredClone(block.locales);
342
382
  if (block.bindings)
343
383
  clone.bindings = { ...block.bindings };
384
+ if (block.attrs)
385
+ clone.attrs = { ...block.attrs };
386
+ if (block.slotClassName)
387
+ clone.slotClassName = { ...block.slotClassName };
344
388
  if (block.slots) {
345
389
  clone.slots = Object.fromEntries(Object.entries(block.slots).map(([name, children]) => [
346
390
  name,
@@ -363,7 +407,7 @@ function freshId(used) {
363
407
  function checkBlock(value, used, path = 'block') {
364
408
  if (!isPlainObject(value))
365
409
  return `${path} must be an object`;
366
- const { id, type, props, className, slots, bindings, hidden, label, locales, motion } = value;
410
+ const { id, type, props, className, slots, bindings, hidden, label, locales, motion, attrs, slotClassName } = value;
367
411
  if (typeof id !== 'string' || id === '')
368
412
  return `${path}.id must be a non-empty string`;
369
413
  if (used.has(id))
@@ -444,5 +488,18 @@ function checkBlock(value, used, path = 'block') {
444
488
  if (checked)
445
489
  block.motion = checked;
446
490
  }
491
+ if (slotClassName !== undefined) {
492
+ if (!isPlainObject(slotClassName) || !Object.values(slotClassName).every((v) => typeof v === 'string')) {
493
+ return `${path}.slotClassName must be an object of slot name -> classes`;
494
+ }
495
+ const kept = Object.fromEntries(Object.entries(slotClassName).filter(([, v]) => v.trim()));
496
+ if (Object.keys(kept).length > 0)
497
+ block.slotClassName = kept;
498
+ }
499
+ const checkedAttrs = checkAttrs(attrs);
500
+ if (typeof checkedAttrs === 'string')
501
+ return `${path}.${checkedAttrs}`;
502
+ if (checkedAttrs)
503
+ block.attrs = checkedAttrs;
447
504
  return block;
448
505
  }
@@ -105,10 +105,12 @@ export function payloadBlocksProblems(layout, storage) {
105
105
  }
106
106
  if (allowed && !allowed.includes(block.type))
107
107
  problems.push(`${name} blocks are not allowed here.`);
108
- if (block.className)
108
+ if (block.className || block.slotClassName)
109
109
  problems.push(`${name}: this field cannot store Tailwind classes.`);
110
110
  if (block.motion)
111
111
  problems.push(`${name}: this field cannot store animations.`);
112
+ if (block.attrs)
113
+ problems.push(`${name}: this field cannot store HTML attributes (id, aria-label, aria-hidden).`);
112
114
  if (block.bindings)
113
115
  problems.push(`${name}: this field cannot store bindings.`);
114
116
  if (block.hidden)
@@ -119,6 +119,15 @@ function blockSchema(def, all) {
119
119
  additionalProperties: false,
120
120
  };
121
121
  }
122
+ const styled = Object.entries(def.slots ?? {}).filter(([, slot]) => slot.styles);
123
+ if (styled.length > 0) {
124
+ properties.slotClassName = {
125
+ type: 'object',
126
+ description: `Tailwind classes of a slot's own element, by slot name. Only these slots take classes: ${styled.map(([name]) => name).join(', ')}.`,
127
+ properties: Object.fromEntries(styled.map(([name]) => [name, { type: 'string' }])),
128
+ additionalProperties: false,
129
+ };
130
+ }
122
131
  properties.bindings = {
123
132
  type: 'object',
124
133
  description: 'Prop path -> document field path. Bound props take the document\'s value at render time.',
@@ -126,6 +135,17 @@ function blockSchema(def, all) {
126
135
  };
127
136
  properties.hidden = { type: 'boolean', description: 'Hidden blocks stay in the data but do not render.' };
128
137
  properties.motion = { $ref: `#/$defs/${encodeURIComponent(MOTION_DEF)}` };
138
+ properties.attrs = {
139
+ type: 'object',
140
+ description: 'HTML attributes of the block element. id: an anchor for "#id" links, unique in the layout (letters, digits, "-" and "_", starting with a letter). ' +
141
+ 'ariaLabel: the name screen readers read (aria-label). ariaHidden: true hides a decorative block from screen readers (aria-hidden).',
142
+ properties: {
143
+ id: { type: 'string', pattern: '^[A-Za-z][\\w-]*$' },
144
+ ariaLabel: { type: 'string' },
145
+ ariaHidden: { type: 'boolean' },
146
+ },
147
+ additionalProperties: false,
148
+ };
129
149
  properties.label = {
130
150
  type: 'string',
131
151
  description: 'Optional name for editors, shown in the outline (e.g. "Hero", "Pricing"). Never rendered on the site.',