drupal-canvas 0.2.0 → 0.3.1

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 (30) hide show
  1. package/README.md +172 -2
  2. package/dist/FormattedText.d.ts +1 -1
  3. package/dist/FormattedText.js +1 -1
  4. package/dist/drupal-utils.d.ts +1 -1
  5. package/dist/drupal-utils.js +1 -1
  6. package/dist/index.d.ts +6 -6
  7. package/dist/index.js +6 -6
  8. package/dist/json-render-utils.d.ts +116 -0
  9. package/dist/json-render-utils.js +237 -0
  10. package/dist/jsonapi-client.d.ts +1 -1
  11. package/dist/jsonapi-client.js +1 -1
  12. package/dist/jsonapi-utils.d.ts +1 -1
  13. package/dist/jsonapi-utils.js +1 -1
  14. package/dist/next-image-standalone.d.ts +1 -1
  15. package/dist/next-image-standalone.js +1 -1
  16. package/dist/utils.d.ts +1 -1
  17. package/dist/utils.js +1 -1
  18. package/package.json +10 -2
  19. /package/dist/{FormattedText-B8Lu3ByU.js → FormattedText-C1aZH-9n.js} +0 -0
  20. /package/dist/{FormattedText-BjQdnNmH.d.ts → FormattedText-yaSCYPpK.d.ts} +0 -0
  21. /package/dist/{drupal-utils-ByF92Aue.d.ts → drupal-utils-DNru9pSM.d.ts} +0 -0
  22. /package/dist/{drupal-utils-C41ZWu0D.js → drupal-utils-Dhu6eUg-.js} +0 -0
  23. /package/dist/{jsonapi-client-BamGkTjn.d.ts → jsonapi-client-UDKOwuXX.d.ts} +0 -0
  24. /package/dist/{jsonapi-client-BydDHnEY.js → jsonapi-client-Wpf6rG0C.js} +0 -0
  25. /package/dist/{jsonapi-utils-oywSkEdN.js → jsonapi-utils-BA2DcHP4.js} +0 -0
  26. /package/dist/{jsonapi-utils-co82I5eL.d.ts → jsonapi-utils-DUAnKdKa.d.ts} +0 -0
  27. /package/dist/{next-image-standalone-B4uHVOA8.js → next-image-standalone-Cp3o4ile.js} +0 -0
  28. /package/dist/{next-image-standalone-BqTHJhzr.d.ts → next-image-standalone-wADMJCIZ.d.ts} +0 -0
  29. /package/dist/{utils-DG-hPO0N.js → utils-DuVWmMX9.js} +0 -0
  30. /package/dist/{utils-Cn7jrjo0.d.ts → utils-DyhCn7lR.d.ts} +0 -0
package/README.md CHANGED
@@ -43,9 +43,13 @@ import { getPageData } from 'drupal-canvas';
43
43
  const { pageTitle, breadcrumbs, mainEntity } = getPageData();
44
44
  const { bundle, entityTypeId, uuid } = mainEntity;
45
45
  ```
46
+
46
47
  #### Main entity metadata
47
- The main entity is the primary Drupal entity (e.g. article, canvas_page, blog) associated with the current page.
48
- Access main entity metadata of the page you are on with `getPageData`. This can be used to construct JSON:API parameters for requests.
48
+
49
+ The main entity is the primary Drupal entity (e.g. article, canvas_page, blog)
50
+ associated with the current page. Access main entity metadata of the page you
51
+ are on with `getPageData`. This can be used to construct JSON:API parameters for
52
+ requests.
49
53
  [View documentation and example here.](https://project.pages.drupalcode.org/canvas/code-components/data-fetching#main-entity-metadata)
50
54
 
51
55
  ### `getSiteData`
@@ -160,6 +164,172 @@ If working outside of Drupal Canvas, you can use the
160
164
  to automatically configure the base URL for you. Otherwise you must explicitly
161
165
  provide a base URL.
162
166
 
167
+ ### json-render Utils
168
+
169
+ Utilities for working with [json-render](https://json-render.dev) specs and
170
+ Drupal Canvas component trees.
171
+
172
+ > **Note:** These utilities currently depend on named slots support proposed for
173
+ > json-render in <https://github.com/vercel-labs/json-render/pull/105>.
174
+
175
+ #### `canvasTreeToSpec`
176
+
177
+ Converts a flat Drupal Canvas component tree to a
178
+ [json-render spec](https://json-render.dev/docs/specs). Canvas stores components
179
+ as a flat array linked by `parent_uuid`; json-render uses a spec object with a
180
+ single root element and a flat map of elements linked by `children` and `slots`.
181
+ This function builds the spec and, when there are multiple root components,
182
+ wraps them in a synthetic `canvas:component-tree` element. Throws an error if
183
+ the tree contains no root component.
184
+
185
+ ```js
186
+ import { canvasTreeToSpec } from 'drupal-canvas/json-render-utils';
187
+
188
+ const components = [
189
+ {
190
+ uuid: '872cde09-809a-4f48-8bf5-88f37127cb55',
191
+ parent_uuid: null,
192
+ slot: null,
193
+ component_id: 'js.card',
194
+ component_version: 'a681ae184a8f6b7f',
195
+ inputs: { title: 'Hello' },
196
+ label: 'Card',
197
+ },
198
+ {
199
+ uuid: '87106237-b8d8-4e19-82f7-c780ad24feb5',
200
+ parent_uuid: '872cde09-809a-4f48-8bf5-88f37127cb55',
201
+ slot: 'body',
202
+ component_id: 'js.text',
203
+ component_version: 'b1e991f726a2a266',
204
+ inputs: { content: 'World' },
205
+ label: 'Text',
206
+ },
207
+ ];
208
+
209
+ const jsonRenderSpec = canvasTreeToSpec(components);
210
+ ```
211
+
212
+ #### `specToCanvasTree`
213
+
214
+ Converts a json-render spec back to a flat Drupal Canvas component tree. Strips
215
+ the synthetic `canvas:component-tree` wrapper if present, so multi-root trees
216
+ round-trip cleanly.
217
+
218
+ ```js
219
+ import { specToCanvasTree } from 'drupal-canvas/json-render-utils';
220
+
221
+ const jsonRenderSpec = {
222
+ root: 'card',
223
+ elements: {
224
+ card: {
225
+ type: 'js.card',
226
+ props: { title: 'Hello' },
227
+ slots: { body: ['text'] },
228
+ },
229
+ text: {
230
+ type: 'js.text',
231
+ props: { content: 'World' },
232
+ },
233
+ },
234
+ };
235
+
236
+ const canvasComponentTree = specToCanvasTree(jsonRenderSpec);
237
+ ```
238
+
239
+ #### `renderSpec`
240
+
241
+ Renders a json-render spec generated from canvas component tree using
242
+ `canvasTreeToSpec`. The synthetic `canvas:component-tree` wrapper used for
243
+ multi-root trees is handled internally and renders transparently. Unknown
244
+ component types render nothing.
245
+
246
+ ```jsx
247
+ import { renderSpec } from 'drupal-canvas/json-render-utils';
248
+
249
+ import registry from './registry';
250
+
251
+ const spec = {
252
+ root: 'card',
253
+ elements: {
254
+ card: {
255
+ type: 'js.card',
256
+ props: { title: 'Hello' },
257
+ children: ['text'],
258
+ },
259
+ text: {
260
+ type: 'js.text',
261
+ props: { content: 'World' },
262
+ },
263
+ },
264
+ };
265
+
266
+ const rendered = renderSpec(spec, registry);
267
+ ```
268
+
269
+ #### `renderCanvasTree`
270
+
271
+ Renders a Canvas component tree. Requires a `ComponentRegistry` for mapping
272
+ component IDs to React components. Converts the tree to a json-render spec
273
+ internally using `canvasTreeToSpec` and delegates to `renderSpec`. Unknown
274
+ component types render nothing.
275
+
276
+ ```jsx
277
+ import { JsonApiClient } from 'drupal-canvas';
278
+ import { renderCanvasTree } from 'drupal-canvas/json-render-utils';
279
+ import useSWR from 'swr';
280
+
281
+ import registry from './registry';
282
+
283
+ const client = new JsonApiClient();
284
+
285
+ export function CanvasPage({ id }) {
286
+ const { data: page } = useSWR(
287
+ ['canvas_page--canvas_page', id],
288
+ ([type, id]) => client.getResource(type, id),
289
+ );
290
+
291
+ if (!page) return null;
292
+
293
+ return renderCanvasTree(page.components, registry);
294
+ }
295
+ ```
296
+
297
+ #### `defineComponentRegistry`
298
+
299
+ Defines a component registry by dynamically importing each component's
300
+ JavaScript entry file. Accepts an array of objects with `name` and `jsEntryPath`
301
+ — compatible with `DiscoveryResult.components` from `@drupal-canvas/discovery`.
302
+ Each module's default export is expected to be a render function. Components
303
+ without a JS entry or without a default function export are skipped.
304
+
305
+ ```js
306
+ import { defineComponentRegistry } from 'drupal-canvas/json-render-utils';
307
+ import { discoverCanvasProject } from '@drupal-canvas/discovery';
308
+
309
+ const discovery = await discoverCanvasProject({ componentRoot: './src' });
310
+ const registry = await defineComponentRegistry(discovery.components);
311
+ ```
312
+
313
+ #### `defineComponentCatalog`
314
+
315
+ Defines a complete [json-render](https://json-render.dev) catalog from component
316
+ metadata. Converts props from JSON Schema (as defined in `component.yml`) to Zod
317
+ schemas. The returned catalog can be used with `catalog.prompt()` for AI prompt
318
+ generation, `catalog.validate()` for spec validation, etc.
319
+
320
+ ```js
321
+ import { defineComponentCatalog } from 'drupal-canvas/json-render-utils';
322
+ import {
323
+ discoverCanvasProject,
324
+ loadComponentsMetadata,
325
+ } from '@drupal-canvas/discovery';
326
+
327
+ const discovery = await discoverCanvasProject({ componentRoot: './src' });
328
+ const metadata = await loadComponentsMetadata(discovery);
329
+ const catalog = defineComponentCatalog(metadata);
330
+ const systemPrompt = catalog.prompt();
331
+ ```
332
+
163
333
  ## Base Components
164
334
 
165
335
  ### FormattedText
@@ -1,2 +1,2 @@
1
- import { t as FormattedText } from "./FormattedText-BjQdnNmH.js";
1
+ import { t as FormattedText } from "./FormattedText-yaSCYPpK.js";
2
2
  export { FormattedText as default };
@@ -1,3 +1,3 @@
1
- import { t as FormattedText } from "./FormattedText-B8Lu3ByU.js";
1
+ import { t as FormattedText } from "./FormattedText-C1aZH-9n.js";
2
2
 
3
3
  export { FormattedText as default };
@@ -1,2 +1,2 @@
1
- import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-ByF92Aue.js";
1
+ import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-DNru9pSM.js";
2
2
  export { getPageData, getSiteData, sortMenu };
@@ -1,3 +1,3 @@
1
- import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-C41ZWu0D.js";
1
+ import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-Dhu6eUg-.js";
2
2
 
3
3
  export { getPageData, getSiteData, sortMenu };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { t as FormattedText } from "./FormattedText-BjQdnNmH.js";
2
- import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-ByF92Aue.js";
3
- import { t as CanvasJsonApiClient } from "./jsonapi-client-BamGkTjn.js";
4
- import { n as sortMenu$1, t as getNodePath } from "./jsonapi-utils-co82I5eL.js";
5
- import { t as Image } from "./next-image-standalone-BqTHJhzr.js";
6
- import { t as cn } from "./utils-Cn7jrjo0.js";
1
+ import { t as FormattedText } from "./FormattedText-yaSCYPpK.js";
2
+ import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-DNru9pSM.js";
3
+ import { t as CanvasJsonApiClient } from "./jsonapi-client-UDKOwuXX.js";
4
+ import { n as sortMenu$1, t as getNodePath } from "./jsonapi-utils-DUAnKdKa.js";
5
+ import { t as Image } from "./next-image-standalone-wADMJCIZ.js";
6
+ import { t as cn } from "./utils-DyhCn7lR.js";
7
7
  export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-C41ZWu0D.js";
2
- import { t as FormattedText } from "./FormattedText-B8Lu3ByU.js";
3
- import { t as CanvasJsonApiClient } from "./jsonapi-client-BydDHnEY.js";
4
- import { n as sortMenu$1, t as getNodePath } from "./jsonapi-utils-oywSkEdN.js";
5
- import { t as Image } from "./next-image-standalone-B4uHVOA8.js";
6
- import { t as cn } from "./utils-DG-hPO0N.js";
1
+ import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-Dhu6eUg-.js";
2
+ import { t as FormattedText } from "./FormattedText-C1aZH-9n.js";
3
+ import { t as CanvasJsonApiClient } from "./jsonapi-client-Wpf6rG0C.js";
4
+ import { n as sortMenu$1, t as getNodePath } from "./jsonapi-utils-BA2DcHP4.js";
5
+ import { t as Image } from "./next-image-standalone-Cp3o4ile.js";
6
+ import { t as cn } from "./utils-DuVWmMX9.js";
7
7
 
8
8
  export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
@@ -0,0 +1,116 @@
1
+ import { ComponentType } from "react";
2
+ import * as zod0 from "zod";
3
+ import * as _json_render_core0 from "@json-render/core";
4
+ import { Spec } from "@json-render/core";
5
+ import * as zod_v4_core0 from "zod/v4/core";
6
+ import { ComponentMetadata } from "@drupal-canvas/discovery";
7
+
8
+ //#region src/json-render-utils.d.ts
9
+ /**
10
+ * Drupal Canvas component tree node.
11
+ * @see canvas.component_tree_node in config/schema/canvas.schema.yml
12
+ */
13
+ interface CanvasComponentTreeNode {
14
+ parent_uuid: string | null;
15
+ slot: string | null;
16
+ uuid: string;
17
+ component_id: string;
18
+ component_version: string | null;
19
+ inputs: Record<string, unknown>;
20
+ label: string | null;
21
+ }
22
+ /**
23
+ * Drupal Canvas component tree. A flat sequence of component tree nodes linked by parent_uuid.
24
+ * @see canvas.component_tree in config/schema/canvas.schema.yml
25
+ */
26
+ type CanvasComponentTree = CanvasComponentTreeNode[];
27
+ /**
28
+ * Converts an array of Drupal Canvas components to json-render spec format.
29
+ *
30
+ * @param components - Flat array of Canvas component tree nodes
31
+ * @returns json-render spec
32
+ */
33
+ declare function canvasTreeToSpec(components: CanvasComponentTree): Spec;
34
+ /**
35
+ * Converts a json-render spec to Drupal Canvas component tree format.
36
+ *
37
+ * @param jsonRenderSpec - json-render spec
38
+ * @returns Flat array of Canvas component tree nodes
39
+ */
40
+ declare function specToCanvasTree(jsonRenderSpec: Spec): CanvasComponentTree;
41
+ /**
42
+ * Registry of components keyed by component_id.
43
+ */
44
+ type ComponentRegistry = Record<string, ComponentType<Record<string, unknown>>>;
45
+ /**
46
+ * Renders a json-render spec using the given component registry.
47
+ *
48
+ * @param spec - json-render spec to render
49
+ * @param registry - Component registry to use for rendering.
50
+ * @see {@link defineComponentRegistry}
51
+ */
52
+ declare function renderSpec(spec: Spec, registry: ComponentRegistry): React.ReactNode;
53
+ /**
54
+ * Renders a Drupal Canvas component tree.
55
+ *
56
+ * @param components - Canvas component tree to render
57
+ * @param registry - Component registry to use for rendering.
58
+ * @see {@link defineComponentRegistry}
59
+ */
60
+ declare function renderCanvasTree(components: CanvasComponentTree, registry: ComponentRegistry): React.ReactNode;
61
+ /**
62
+ * Defines a component registry by dynamically importing each component's
63
+ * JavaScript entry file from the discovery results.
64
+ *
65
+ * Components are keyed by their Drupal Canvas component_id (`js.<machineName>`)
66
+ * to match the `component_id` used in Canvas component trees.
67
+ *
68
+ * @param components - Array of discovered components from `discoverCanvasProject()`
69
+ * @returns A component registry that can be passed to `renderCanvasTree()`
70
+ */
71
+ declare function defineComponentRegistry(components: {
72
+ name: string;
73
+ jsEntryPath: string | null;
74
+ }[]): Promise<ComponentRegistry>;
75
+ /**
76
+ * Defines a complete json-render catalog from component metadata using the
77
+ * `@json-render/react` schema. Converts props from JSON Schema (as defined
78
+ * in component.yml) to Zod schemas.
79
+ *
80
+ * @param metadata - Array of component metadata from `loadComponentsMetadata()`
81
+ * @returns A json-render `Catalog` instance
82
+ */
83
+ declare function defineComponentCatalog(metadata: ComponentMetadata[]): _json_render_core0.Catalog<{
84
+ spec: _json_render_core0.SchemaType<"object", {
85
+ root: _json_render_core0.SchemaType<"string", unknown>;
86
+ elements: _json_render_core0.SchemaType<"record", _json_render_core0.SchemaType<"object", {
87
+ type: _json_render_core0.SchemaType<"ref", string>;
88
+ props: _json_render_core0.SchemaType<"propsOf", string>;
89
+ children: _json_render_core0.SchemaType<"array", _json_render_core0.SchemaType<"string", unknown>>;
90
+ slots: _json_render_core0.SchemaType<"record", _json_render_core0.SchemaType<"array", _json_render_core0.SchemaType<"string", unknown>>>;
91
+ visible: _json_render_core0.SchemaType<"any", unknown>;
92
+ }>>;
93
+ }>;
94
+ catalog: _json_render_core0.SchemaType<"object", {
95
+ components: _json_render_core0.SchemaType<"map", {
96
+ props: _json_render_core0.SchemaType<"zod", unknown>;
97
+ slots: _json_render_core0.SchemaType<"array", _json_render_core0.SchemaType<"string", unknown>>;
98
+ description: _json_render_core0.SchemaType<"string", unknown>;
99
+ example: _json_render_core0.SchemaType<"any", unknown>;
100
+ }>;
101
+ actions: _json_render_core0.SchemaType<"map", {
102
+ params: _json_render_core0.SchemaType<"zod", unknown>;
103
+ description: _json_render_core0.SchemaType<"string", unknown>;
104
+ }>;
105
+ }>;
106
+ }, {
107
+ components: {
108
+ [k: string]: {
109
+ props: zod0.ZodType<unknown, unknown, zod_v4_core0.$ZodTypeInternals<unknown, unknown>>;
110
+ slots: string[];
111
+ };
112
+ };
113
+ actions: {};
114
+ }>;
115
+ //#endregion
116
+ export { CanvasComponentTree, CanvasComponentTreeNode, ComponentRegistry, canvasTreeToSpec, defineComponentCatalog, defineComponentRegistry, renderCanvasTree, renderSpec, specToCanvasTree };
@@ -0,0 +1,237 @@
1
+ import { Fragment, jsx } from "react/jsx-runtime";
2
+ import { cloneElement, createElement, isValidElement } from "react";
3
+ import { fromJSONSchema } from "zod";
4
+ import { defineCatalog, resolveElementProps } from "@json-render/core";
5
+ import { schema } from "@json-render/react/schema";
6
+
7
+ //#region src/json-render-utils.tsx
8
+ /**
9
+ * Converts an array of Drupal Canvas components to json-render spec format.
10
+ *
11
+ * @param components - Flat array of Canvas component tree nodes
12
+ * @returns json-render spec
13
+ */
14
+ function canvasTreeToSpec(components) {
15
+ const elements = {};
16
+ const rootUuids = [];
17
+ for (const component of components) {
18
+ let inputs;
19
+ if (typeof component.inputs === "string") try {
20
+ inputs = JSON.parse(component.inputs);
21
+ } catch {
22
+ throw new Error(`Component "${component.uuid}" has malformed JSON inputs: ${component.inputs}`);
23
+ }
24
+ else inputs = component.inputs;
25
+ if (component.parent_uuid === null) {
26
+ elements[component.uuid] = {
27
+ type: component.component_id,
28
+ props: inputs
29
+ };
30
+ rootUuids.push(component.uuid);
31
+ } else {
32
+ if (component.slot === null) throw new Error(`Component "${component.uuid}" has a parent_uuid but no slot.`);
33
+ const parent = elements[component.parent_uuid];
34
+ if (!parent) throw new Error(`Component "${component.uuid}" references unknown or out-of-order parent "${component.parent_uuid}".`);
35
+ elements[component.uuid] = {
36
+ type: component.component_id,
37
+ props: inputs
38
+ };
39
+ if (component.slot === "children") {
40
+ if (!parent.children) parent.children = [];
41
+ parent.children.push(component.uuid);
42
+ } else {
43
+ if (!parent.slots) parent.slots = {};
44
+ if (!parent.slots[component.slot]) parent.slots[component.slot] = [];
45
+ parent.slots[component.slot].push(component.uuid);
46
+ }
47
+ }
48
+ }
49
+ if (rootUuids.length === 0) throw new Error("Canvas component tree has no root component (no component with null parent_uuid).");
50
+ if (rootUuids.length > 1) {
51
+ elements["canvas:component-tree"] = {
52
+ type: "canvas:component-tree",
53
+ props: {},
54
+ children: rootUuids
55
+ };
56
+ return {
57
+ root: "canvas:component-tree",
58
+ elements
59
+ };
60
+ }
61
+ return {
62
+ root: rootUuids[0],
63
+ elements
64
+ };
65
+ }
66
+ /**
67
+ * Converts a json-render spec subtree rooted at key to flat Canvas nodes,
68
+ * appending each node to result.
69
+ */
70
+ function convertSpecElement(key, elements, result, parentUuid, slot, ctx) {
71
+ const element = elements[key];
72
+ if (!element) throw new Error(`Element key "${key}" not found in elements map.`);
73
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(key) ? key : crypto.randomUUID();
74
+ result.push({
75
+ uuid,
76
+ parent_uuid: parentUuid,
77
+ slot,
78
+ component_id: element.type,
79
+ component_version: null,
80
+ inputs: resolveElementProps(element.props, ctx),
81
+ label: null
82
+ });
83
+ for (const childKey of element.children ?? []) convertSpecElement(childKey, elements, result, uuid, "children", ctx);
84
+ for (const [slotName, childKeys] of Object.entries(element.slots ?? {})) for (const childKey of childKeys) convertSpecElement(childKey, elements, result, uuid, slotName, ctx);
85
+ }
86
+ /**
87
+ * Converts a json-render spec to Drupal Canvas component tree format.
88
+ *
89
+ * @param jsonRenderSpec - json-render spec
90
+ * @returns Flat array of Canvas component tree nodes
91
+ */
92
+ function specToCanvasTree(jsonRenderSpec) {
93
+ const result = [];
94
+ const rootElement = jsonRenderSpec.elements[jsonRenderSpec.root];
95
+ if (!rootElement) throw new Error(`Root element "${jsonRenderSpec.root}" not found in elements map.`);
96
+ const ctx = { stateModel: jsonRenderSpec.state ?? {} };
97
+ if (rootElement.type === "canvas:component-tree") {
98
+ for (const childKey of rootElement.children ?? []) convertSpecElement(childKey, jsonRenderSpec.elements, result, null, null, ctx);
99
+ return result;
100
+ }
101
+ convertSpecElement(jsonRenderSpec.root, jsonRenderSpec.elements, result, null, null, ctx);
102
+ return result;
103
+ }
104
+ /**
105
+ * Normalizes Canvas prop payloads into component-friendly values.
106
+ *
107
+ * Current special cases for prop values:
108
+ * - Rich text wrappers like `{ value, format }` are reduced to `value` string.
109
+ * - Image wrappers with metadata (for example `sourceType`) are unwrapped from
110
+ * `{ sourceType, value: { src, ... } }` to the inner image object.
111
+ */
112
+ function normalizeCanvasProps(value) {
113
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
114
+ const record = value;
115
+ return Object.fromEntries(Object.entries(record).map(([key, item]) => {
116
+ if (!item || typeof item !== "object" || Array.isArray(item)) return [key, item];
117
+ const nestedRecord = item;
118
+ const nestedKeys = Object.keys(nestedRecord);
119
+ if (nestedKeys.length > 0 && nestedKeys.every((nestedKey) => nestedKey === "value" || nestedKey === "format") && typeof nestedRecord.value === "string" && typeof nestedRecord.format === "string") return [key, nestedRecord.value];
120
+ if (typeof nestedRecord.sourceType === "string" && nestedRecord.value && typeof nestedRecord.value === "object" && typeof nestedRecord.value.src === "string") return [key, nestedRecord.value];
121
+ return [key, item];
122
+ }));
123
+ }
124
+ /**
125
+ * Renders a single element from a json-render spec, recursively resolving
126
+ * children and named slots.
127
+ */
128
+ function renderSpecElement(key, elements, registry, ctx) {
129
+ const element = elements[key];
130
+ if (!element) throw new Error(`Element key "${key}" not found in elements map.`);
131
+ if (element.type === "canvas:component-tree") return /* @__PURE__ */ jsx(Fragment, { children: (element.children ?? []).map((childKey) => renderSpecChild(childKey, elements, registry, ctx)) });
132
+ const component = registry[element.type];
133
+ if (!component) return null;
134
+ const normalizedProps = normalizeCanvasProps(resolveElementProps(element.props, ctx));
135
+ const children = (element.children ?? []).map((childKey) => renderSpecChild(childKey, elements, registry, ctx));
136
+ const slots = {};
137
+ for (const [slotName, childKeys] of Object.entries(element.slots ?? {})) slots[slotName] = childKeys.map((childKey) => renderSpecChild(childKey, elements, registry, ctx));
138
+ return createElement(component, {
139
+ ...normalizedProps,
140
+ ...slots,
141
+ ...children.length > 0 ? { children } : {}
142
+ });
143
+ }
144
+ function renderSpecChild(key, elements, registry, ctx) {
145
+ const child = renderSpecElement(key, elements, registry, ctx);
146
+ if (isValidElement(child)) return cloneElement(child, { key });
147
+ return child;
148
+ }
149
+ /**
150
+ * Renders a json-render spec using the given component registry.
151
+ *
152
+ * @param spec - json-render spec to render
153
+ * @param registry - Component registry to use for rendering.
154
+ * @see {@link defineComponentRegistry}
155
+ */
156
+ function renderSpec(spec, registry) {
157
+ const ctx = { stateModel: spec.state ?? {} };
158
+ return renderSpecElement(spec.root, spec.elements, registry, ctx);
159
+ }
160
+ /**
161
+ * Renders a Drupal Canvas component tree.
162
+ *
163
+ * @param components - Canvas component tree to render
164
+ * @param registry - Component registry to use for rendering.
165
+ * @see {@link defineComponentRegistry}
166
+ */
167
+ function renderCanvasTree(components, registry) {
168
+ return renderSpec(canvasTreeToSpec(components), registry);
169
+ }
170
+ function metadataToCatalogEntry(metadata) {
171
+ const jsonSchema = {
172
+ type: "object",
173
+ ...metadata.props
174
+ };
175
+ if (metadata.required.length > 0) jsonSchema.required = metadata.required;
176
+ const slotNames = Object.keys(metadata.slots);
177
+ if (slotNames.length > 0) {
178
+ const properties = jsonSchema.properties ?? {};
179
+ for (const [slotName, slot] of Object.entries(metadata.slots)) properties[slotName] = { description: slot.title ?? `${slotName} slot` };
180
+ jsonSchema.properties = properties;
181
+ }
182
+ return {
183
+ props: fromJSONSchema(jsonSchema),
184
+ slots: slotNames
185
+ };
186
+ }
187
+ /**
188
+ * Derives the Drupal Canvas component_id from a component's machineName.
189
+ *
190
+ * Canvas component_ids for JS components follow the format `js.<machineName>`.
191
+ */
192
+ function toComponentId(machineName) {
193
+ return `js.${machineName}`;
194
+ }
195
+ /**
196
+ * Defines a component registry by dynamically importing each component's
197
+ * JavaScript entry file from the discovery results.
198
+ *
199
+ * Components are keyed by their Drupal Canvas component_id (`js.<machineName>`)
200
+ * to match the `component_id` used in Canvas component trees.
201
+ *
202
+ * @param components - Array of discovered components from `discoverCanvasProject()`
203
+ * @returns A component registry that can be passed to `renderCanvasTree()`
204
+ */
205
+ async function defineComponentRegistry(components) {
206
+ const registry = {};
207
+ const entries = await Promise.all(components.filter((c) => c.jsEntryPath !== null).map(async (c) => {
208
+ const renderFn = (await import(
209
+ /* @vite-ignore */
210
+ c.jsEntryPath
211
+ )).default;
212
+ if (typeof renderFn !== "function") return null;
213
+ return {
214
+ names: c.name.startsWith("js.") ? [c.name] : [c.name, toComponentId(c.name.toLowerCase())],
215
+ renderFn
216
+ };
217
+ }));
218
+ for (const entry of entries) if (entry !== null) for (const name of entry.names) registry[name] = entry.renderFn;
219
+ return registry;
220
+ }
221
+ /**
222
+ * Defines a complete json-render catalog from component metadata using the
223
+ * `@json-render/react` schema. Converts props from JSON Schema (as defined
224
+ * in component.yml) to Zod schemas.
225
+ *
226
+ * @param metadata - Array of component metadata from `loadComponentsMetadata()`
227
+ * @returns A json-render `Catalog` instance
228
+ */
229
+ function defineComponentCatalog(metadata) {
230
+ return defineCatalog(schema, {
231
+ components: Object.fromEntries(metadata.map((m) => [toComponentId(m.machineName), metadataToCatalogEntry(m)])),
232
+ actions: {}
233
+ });
234
+ }
235
+
236
+ //#endregion
237
+ export { canvasTreeToSpec, defineComponentCatalog, defineComponentRegistry, renderCanvasTree, renderSpec, specToCanvasTree };
@@ -1,3 +1,3 @@
1
- import { t as CanvasJsonApiClient } from "./jsonapi-client-BamGkTjn.js";
1
+ import { t as CanvasJsonApiClient } from "./jsonapi-client-UDKOwuXX.js";
2
2
  export * from "@drupal-api-client/json-api-client";
3
3
  export { CanvasJsonApiClient as JsonApiClient };
@@ -1,4 +1,4 @@
1
- import { t as CanvasJsonApiClient } from "./jsonapi-client-BydDHnEY.js";
1
+ import { t as CanvasJsonApiClient } from "./jsonapi-client-Wpf6rG0C.js";
2
2
 
3
3
  export * from "@drupal-api-client/json-api-client"
4
4
 
@@ -1,2 +1,2 @@
1
- import { n as sortMenu, t as getNodePath } from "./jsonapi-utils-co82I5eL.js";
1
+ import { n as sortMenu, t as getNodePath } from "./jsonapi-utils-DUAnKdKa.js";
2
2
  export { getNodePath, sortMenu };
@@ -1,3 +1,3 @@
1
- import { n as sortMenu, t as getNodePath } from "./jsonapi-utils-oywSkEdN.js";
1
+ import { n as sortMenu, t as getNodePath } from "./jsonapi-utils-BA2DcHP4.js";
2
2
 
3
3
  export { getNodePath, sortMenu };
@@ -1,2 +1,2 @@
1
- import { t as Image } from "./next-image-standalone-BqTHJhzr.js";
1
+ import { t as Image } from "./next-image-standalone-wADMJCIZ.js";
2
2
  export { Image as default };
@@ -1,3 +1,3 @@
1
- import { t as Image } from "./next-image-standalone-B4uHVOA8.js";
1
+ import { t as Image } from "./next-image-standalone-Cp3o4ile.js";
2
2
 
3
3
  export { Image as default };
package/dist/utils.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { t as cn } from "./utils-Cn7jrjo0.js";
1
+ import { t as cn } from "./utils-DyhCn7lR.js";
2
2
  export { cn };
package/dist/utils.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as cn } from "./utils-DG-hPO0N.js";
1
+ import { t as cn } from "./utils-DuVWmMX9.js";
2
2
 
3
3
  export { cn };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drupal-canvas",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Utilities and base components for building Drupal Canvas Code Components",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -15,6 +15,10 @@
15
15
  "import": "./dist/index.js",
16
16
  "types": "./dist/index.d.ts"
17
17
  },
18
+ "./json-render-utils": {
19
+ "import": "./dist/json-render-utils.js",
20
+ "types": "./dist/json-render-utils.d.ts"
21
+ },
18
22
  "./FormattedText": {
19
23
  "import": "./dist/FormattedText.js",
20
24
  "types": "./dist/FormattedText.d.ts"
@@ -49,11 +53,15 @@
49
53
  "canvas",
50
54
  "drupal"
51
55
  ],
56
+ "//": "TODO: replace @json-render fork packages with official versions once https://github.com/vercel-labs/json-render/pull/105 is merged.",
52
57
  "dependencies": {
53
58
  "@drupal-api-client/json-api-client": "^1.4.0",
59
+ "@json-render/core": "npm:@wotnak/json-render-core@slots",
60
+ "@json-render/react": "npm:@wotnak/json-render-react@slots",
54
61
  "clsx": "^2.1.1",
55
62
  "next-image-standalone": "^0.1.3",
56
- "tailwind-merge": "^3.0.2"
63
+ "tailwind-merge": "^3.0.2",
64
+ "zod": "^4.2.0"
57
65
  },
58
66
  "devDependencies": {
59
67
  "tsdown": "^0.17.0-beta.5",
File without changes