drupal-canvas 0.3.1 → 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 CHANGED
@@ -376,6 +376,47 @@ export default function MyComponent({ photo }) {
376
376
  }
377
377
  ```
378
378
 
379
+ ### Region / RegionsProvider
380
+
381
+ Render Drupal Canvas global regions inside a layout component.
382
+ `<Region name="..." />` slots in the region whose machine name matches `name`,
383
+ and `<RegionsProvider regions={...}>` supplies the region node map. On the
384
+ Drupal side, region placement is handled by the active theme; these components
385
+ are used by standalone renderers (such as
386
+ [Workbench](https://project.pages.drupalcode.org/canvas/code-components/workbench/regions))
387
+ that compose a page with its surrounding regions on their own.
388
+
389
+ ```jsx
390
+ import { Region } from 'drupal-canvas';
391
+
392
+ export default function Layout({ children }) {
393
+ return (
394
+ <>
395
+ <Region name="header" />
396
+ <main>{children}</main>
397
+ <Region name="footer" />
398
+ </>
399
+ );
400
+ }
401
+ ```
402
+
403
+ Pass a `fallback` to render placeholder content when a region is not provided:
404
+
405
+ ```jsx
406
+ <Region name="sidebar" fallback={<aside>No sidebar configured</aside>} />
407
+ ```
408
+
409
+ When composing a renderer outside of Drupal or Workbench, wrap the tree in
410
+ `RegionsProvider` with a map of region machine names to React nodes:
411
+
412
+ ```jsx
413
+ import { RegionsProvider } from 'drupal-canvas';
414
+
415
+ <RegionsProvider regions={{ header: <SiteHeader />, footer: <SiteFooter /> }}>
416
+ <Layout>{pageContent}</Layout>
417
+ </RegionsProvider>;
418
+ ```
419
+
379
420
  ## Development
380
421
 
381
422
  The following scripts are available for developing this package:
@@ -36,6 +36,15 @@ interface PageData {
36
36
  breadcrumbs: Array<BreadcrumbLink>;
37
37
  mainEntity: EntityMetadata | null;
38
38
  }
39
+ interface ThemeAssets {
40
+ logo: {
41
+ url: string;
42
+ };
43
+ favicon: {
44
+ url: string;
45
+ mimeType: string;
46
+ };
47
+ }
39
48
  interface SiteData {
40
49
  branding: {
41
50
  homeUrl: string;
@@ -43,6 +52,7 @@ interface SiteData {
43
52
  siteSlogan: string;
44
53
  };
45
54
  baseUrl: string;
55
+ themeAssets: ThemeAssets;
46
56
  }
47
57
  declare const getPageData: () => PageData;
48
58
  declare const getSiteData: () => SiteData;
@@ -55,7 +55,14 @@ const getSiteData = () => {
55
55
  siteName: "",
56
56
  siteSlogan: ""
57
57
  },
58
- baseUrl: window.drupalSettings?.canvasData?.v0?.baseUrl || "/"
58
+ baseUrl: window.drupalSettings?.canvasData?.v0?.baseUrl || "/",
59
+ themeAssets: window.drupalSettings?.canvasData?.v0?.themeAssets || {
60
+ logo: { url: "" },
61
+ favicon: {
62
+ url: "",
63
+ mimeType: ""
64
+ }
65
+ }
59
66
  };
60
67
  window.parent.postMessage({
61
68
  type: "_canvas_useswr_data_fetch",
@@ -1,2 +1,2 @@
1
- import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-DNru9pSM.js";
1
+ import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-C5s72hSd.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-Dhu6eUg-.js";
1
+ import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-CqS6lCsl.js";
2
2
 
3
3
  export { getPageData, getSiteData, sortMenu };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,29 @@
1
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";
2
+ import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-C5s72hSd.js";
3
3
  import { t as CanvasJsonApiClient } from "./jsonapi-client-UDKOwuXX.js";
4
4
  import { n as sortMenu$1, t as getNodePath } from "./jsonapi-utils-DUAnKdKa.js";
5
5
  import { t as Image } from "./next-image-standalone-wADMJCIZ.js";
6
6
  import { t as cn } from "./utils-DyhCn7lR.js";
7
- export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
7
+ import * as react_jsx_runtime1 from "react/jsx-runtime";
8
+ import { ReactNode } from "react";
9
+
10
+ //#region src/Region.d.ts
11
+ type RegionsMap = Record<string, ReactNode>;
12
+ type RegionsProviderProps = {
13
+ regions: RegionsMap;
14
+ children: ReactNode;
15
+ };
16
+ declare function RegionsProvider({
17
+ regions,
18
+ children
19
+ }: RegionsProviderProps): react_jsx_runtime1.JSX.Element;
20
+ type RegionProps = {
21
+ name: string;
22
+ fallback?: ReactNode;
23
+ };
24
+ declare function Region({
25
+ name,
26
+ fallback
27
+ }: RegionProps): react_jsx_runtime1.JSX.Element;
28
+ //#endregion
29
+ export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, Region, RegionsProvider, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
package/dist/index.js CHANGED
@@ -1,8 +1,24 @@
1
- import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-Dhu6eUg-.js";
1
+ import { n as getSiteData, r as sortMenu, t as getPageData } from "./drupal-utils-CqS6lCsl.js";
2
2
  import { t as FormattedText } from "./FormattedText-C1aZH-9n.js";
3
3
  import { t as CanvasJsonApiClient } from "./jsonapi-client-Wpf6rG0C.js";
4
4
  import { n as sortMenu$1, t as getNodePath } from "./jsonapi-utils-BA2DcHP4.js";
5
5
  import { t as Image } from "./next-image-standalone-Cp3o4ile.js";
6
6
  import { t as cn } from "./utils-DuVWmMX9.js";
7
+ import { Fragment, jsx } from "react/jsx-runtime";
8
+ import { createContext, useContext } from "react";
7
9
 
8
- export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
10
+ //#region src/Region.tsx
11
+ const RegionsContext = createContext({});
12
+ function RegionsProvider({ regions, children }) {
13
+ return /* @__PURE__ */ jsx(RegionsContext.Provider, {
14
+ value: regions,
15
+ children
16
+ });
17
+ }
18
+ function Region({ name, fallback = null }) {
19
+ const node = useContext(RegionsContext)[name];
20
+ return /* @__PURE__ */ jsx(Fragment, { children: node ?? fallback });
21
+ }
22
+
23
+ //#endregion
24
+ export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, Region, RegionsProvider, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
@@ -1,11 +1,11 @@
1
1
  import { ComponentType } from "react";
2
- import * as zod0 from "zod";
2
+ import { z } from "zod";
3
3
  import * as _json_render_core0 from "@json-render/core";
4
4
  import { Spec } from "@json-render/core";
5
- import * as zod_v4_core0 from "zod/v4/core";
6
5
  import { ComponentMetadata } from "@drupal-canvas/discovery";
7
6
 
8
7
  //#region src/json-render-utils.d.ts
8
+
9
9
  /**
10
10
  * Drupal Canvas component tree node.
11
11
  * @see canvas.component_tree_node in config/schema/canvas.schema.yml
@@ -17,6 +17,7 @@ interface CanvasComponentTreeNode {
17
17
  component_id: string;
18
18
  component_version: string | null;
19
19
  inputs: Record<string, unknown>;
20
+ inputs_resolved?: Record<string, unknown> | null;
20
21
  label: string | null;
21
22
  }
22
23
  /**
@@ -24,6 +25,18 @@ interface CanvasComponentTreeNode {
24
25
  * @see canvas.component_tree in config/schema/canvas.schema.yml
25
26
  */
26
27
  type CanvasComponentTree = CanvasComponentTreeNode[];
28
+ /**
29
+ * Authored page spec element. The local file representation of a component
30
+ * instance, as opposed to CanvasComponentTreeNode which is the API representation.
31
+ */
32
+ interface AuthoredSpecElement {
33
+ type: string;
34
+ props?: unknown;
35
+ slots?: AuthoredSpecSlots;
36
+ _provenance?: Record<string, unknown>;
37
+ }
38
+ type AuthoredSpecElementMap = Record<string, AuthoredSpecElement>;
39
+ type AuthoredSpecSlots = Record<string, string[]>;
27
40
  /**
28
41
  * Converts an array of Drupal Canvas components to json-render spec format.
29
42
  *
@@ -106,11 +119,39 @@ declare function defineComponentCatalog(metadata: ComponentMetadata[]): _json_re
106
119
  }, {
107
120
  components: {
108
121
  [k: string]: {
109
- props: zod0.ZodType<unknown, unknown, zod_v4_core0.$ZodTypeInternals<unknown, unknown>>;
122
+ props: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
110
123
  slots: string[];
111
124
  };
112
125
  };
113
126
  actions: {};
114
- }>;
127
+ }> & {
128
+ validate(spec: unknown): {
129
+ success: true;
130
+ data: {
131
+ root: string;
132
+ elements: Record<string, {
133
+ type: string;
134
+ props: unknown;
135
+ children: string[];
136
+ slots: Record<string, string[]>;
137
+ visible?: any;
138
+ }>;
139
+ };
140
+ error?: undefined;
141
+ } | {
142
+ success: false;
143
+ error: z.ZodError<{
144
+ root: string;
145
+ elements: Record<string, {
146
+ type: string;
147
+ props: unknown;
148
+ children: string[];
149
+ slots: Record<string, string[]>;
150
+ visible?: any;
151
+ }>;
152
+ }>;
153
+ data?: undefined;
154
+ };
155
+ };
115
156
  //#endregion
116
- export { CanvasComponentTree, CanvasComponentTreeNode, ComponentRegistry, canvasTreeToSpec, defineComponentCatalog, defineComponentRegistry, renderCanvasTree, renderSpec, specToCanvasTree };
157
+ export { AuthoredSpecElement, AuthoredSpecElementMap, AuthoredSpecSlots, CanvasComponentTree, CanvasComponentTreeNode, ComponentRegistry, canvasTreeToSpec, defineComponentCatalog, defineComponentRegistry, renderCanvasTree, renderSpec, specToCanvasTree };
@@ -1,9 +1,363 @@
1
1
  import { Fragment, jsx } from "react/jsx-runtime";
2
2
  import { cloneElement, createElement, isValidElement } from "react";
3
- import { fromJSONSchema } from "zod";
3
+ import { fromJSONSchema, z } from "zod";
4
4
  import { defineCatalog, resolveElementProps } from "@json-render/core";
5
5
  import { schema } from "@json-render/react/schema";
6
6
 
7
+ //#region ../../schema.json
8
+ var $defs = {
9
+ "heading-element": {
10
+ "title": "Heading element",
11
+ "type": "string",
12
+ "enum": [
13
+ "div",
14
+ "h1",
15
+ "h2",
16
+ "h3",
17
+ "h4",
18
+ "h5",
19
+ "h6"
20
+ ],
21
+ "meta:enum": {
22
+ "div": "Container",
23
+ "h1": "Header 1",
24
+ "h2": "Header 2",
25
+ "h3": "Header 3",
26
+ "h4": "Header 4",
27
+ "h5": "Header 5",
28
+ "h6": "Header 6"
29
+ }
30
+ },
31
+ "column-width": {
32
+ "title": "Column Width",
33
+ "type": "integer",
34
+ "enum": [
35
+ 25,
36
+ 33,
37
+ 50,
38
+ 66,
39
+ 75
40
+ ],
41
+ "meta:enum": {
42
+ "25": "25%",
43
+ "33": "33%",
44
+ "50": "50%",
45
+ "66": "66%",
46
+ "75": "75%"
47
+ }
48
+ },
49
+ "background-color": {
50
+ "title": "Background Color",
51
+ "type": "string",
52
+ "enum": [
53
+ "",
54
+ "primary",
55
+ "secondary",
56
+ "white"
57
+ ],
58
+ "meta:enum": {
59
+ "": "None",
60
+ "primary": "Primary",
61
+ "secondary": "Secondary",
62
+ "white": "White"
63
+ }
64
+ },
65
+ "date-range": {
66
+ "title": "date range",
67
+ "type": "object",
68
+ "required": ["from", "to"],
69
+ "properties": {
70
+ "from": {
71
+ "title": "Start date",
72
+ "type": "string",
73
+ "format": "date"
74
+ },
75
+ "to": {
76
+ "title": "End date",
77
+ "type": "string",
78
+ "format": "date"
79
+ }
80
+ }
81
+ },
82
+ "stream-wrapper-uri": {
83
+ "title": "Stream wrapper URI",
84
+ "type": "string",
85
+ "format": "uri",
86
+ "x-allowed-schemes": ["public"]
87
+ },
88
+ "stream-wrapper-image-uri": {
89
+ "title": "Stream wrapper image URI",
90
+ "type": "string",
91
+ "format": "uri",
92
+ "contentMediaType": "image/*",
93
+ "x-allowed-schemes": ["public"]
94
+ },
95
+ "image-uri": {
96
+ "title": "Image URL",
97
+ "type": "string",
98
+ "format": "uri-reference",
99
+ "contentMediaType": "image/*",
100
+ "x-allowed-schemes": ["http", "https"]
101
+ },
102
+ "heading": {
103
+ "title": "Heading",
104
+ "type": "object",
105
+ "required": ["text", "element"],
106
+ "properties": {
107
+ "text": {
108
+ "type": "string",
109
+ "title": "Text",
110
+ "description": "The heading text.",
111
+ "examples": ["A heading element"]
112
+ },
113
+ "style": {
114
+ "type": "string",
115
+ "title": "Style",
116
+ "description": "The heading style to use.",
117
+ "enum": ["primary", "secondary"],
118
+ "meta:enum": {
119
+ "primary": "Primary",
120
+ "secondary": "Secondary"
121
+ },
122
+ "examples": ["primary", "secondary"]
123
+ },
124
+ "element": {
125
+ "type": "string",
126
+ "title": "Element",
127
+ "description": "The HTML element to use.",
128
+ "enum": [
129
+ "div",
130
+ "h1",
131
+ "h2",
132
+ "h3",
133
+ "h4",
134
+ "h5",
135
+ "h6"
136
+ ],
137
+ "meta:enum": {
138
+ "div": "Container",
139
+ "h1": "Header 1",
140
+ "h2": "Header 2",
141
+ "h3": "Header 3",
142
+ "h4": "Header 4",
143
+ "h5": "Header 5",
144
+ "h6": "Header 6"
145
+ },
146
+ "examples": [
147
+ "h1",
148
+ "h2",
149
+ "h3",
150
+ "h4",
151
+ "h5",
152
+ "h6",
153
+ "div"
154
+ ]
155
+ }
156
+ }
157
+ },
158
+ "text": {
159
+ "title": "Text",
160
+ "type": "object",
161
+ "properties": { "text": {
162
+ "type": "string",
163
+ "title": "Text",
164
+ "description": "The text to display.",
165
+ "examples": ["This is some text"]
166
+ } }
167
+ },
168
+ "shoe-icon": {
169
+ "title": "Icon",
170
+ "type": "object",
171
+ "properties": {
172
+ "name": {
173
+ "type": "string",
174
+ "title": "Name",
175
+ "description": "The badge’s theme variant.",
176
+ "default": "moon-stars-fill",
177
+ "enum": [
178
+ "moon-stars-fill",
179
+ "moon-stars",
180
+ "star-fill",
181
+ "star",
182
+ "stars",
183
+ "rocket-fill",
184
+ "rocket-takeoff-fill",
185
+ "rocket-takeoff",
186
+ "rocket"
187
+ ],
188
+ "meta:enum": {
189
+ "moon-stars-fill": "Moon Stars (Filled)",
190
+ "moon-stars": "Moon Stars",
191
+ "star-fill": "Star (Filled)",
192
+ "star": "Star",
193
+ "stars": "Stars",
194
+ "rocket-fill": "Rocket (Filled)",
195
+ "rocket-takeoff-fill": "Rocket Takeoff (Filled)",
196
+ "rocket-takeoff": "Rocket Takeoff",
197
+ "rocket": "Rocket"
198
+ },
199
+ "examples": [
200
+ "moon-stars-fill",
201
+ "moon-stars",
202
+ "star-fill",
203
+ "star",
204
+ "stars",
205
+ "rocket-fill",
206
+ "rocket-takeoff-fill",
207
+ "rocket-takeoff",
208
+ "rocket"
209
+ ]
210
+ },
211
+ "label": {
212
+ "type": "string",
213
+ "title": "Label",
214
+ "description": "An alternate description to use for assistive devices. If omitted, the icon will be considered presentational and ignored by assistive devices.",
215
+ "default": "This is an icon",
216
+ "examples": ["This is an icon"]
217
+ },
218
+ "size": {
219
+ "type": "string",
220
+ "title": "Size",
221
+ "description": "The icon size.",
222
+ "default": "",
223
+ "enum": [
224
+ "",
225
+ "base",
226
+ "l",
227
+ "s",
228
+ "xs",
229
+ "xxs"
230
+ ],
231
+ "meta:enum": {
232
+ "": "None",
233
+ "base": "Base",
234
+ "l": "Large",
235
+ "s": "Small",
236
+ "xs": "Extra-Small",
237
+ "xxs": "Extra-Extra-Small"
238
+ },
239
+ "examples": [
240
+ "",
241
+ "base",
242
+ "l",
243
+ "s",
244
+ "xs",
245
+ "xxs"
246
+ ]
247
+ },
248
+ "color": {
249
+ "type": "string",
250
+ "title": "Color",
251
+ "description": "The icon color",
252
+ "default": "",
253
+ "enum": [
254
+ "",
255
+ "gray",
256
+ "primary",
257
+ "neutral-soft",
258
+ "neutral-medium",
259
+ "neutral-loud",
260
+ "primary-medium",
261
+ "primary-loud",
262
+ "black",
263
+ "white",
264
+ "red",
265
+ "gold",
266
+ "green"
267
+ ],
268
+ "meta:enum": {
269
+ "": "None",
270
+ "gray": "Gray",
271
+ "primary": "Primary",
272
+ "neutral-soft": "Neutral Soft",
273
+ "neutral-medium": "Neutral Medium",
274
+ "neutral-loud": "Neutral Loud",
275
+ "primary-medium": "Primary Medium",
276
+ "primary-loud": "Primary Loud",
277
+ "black": "Black",
278
+ "white": "White",
279
+ "red": "Red",
280
+ "gold": "Gold",
281
+ "green": "Green"
282
+ },
283
+ "examples": [
284
+ "",
285
+ "gray",
286
+ "primary",
287
+ "neutral-soft",
288
+ "neutral-medium",
289
+ "neutral-loud",
290
+ "primary-medium",
291
+ "primary-loud",
292
+ "black",
293
+ "white",
294
+ "red",
295
+ "gold",
296
+ "green"
297
+ ]
298
+ },
299
+ "slot": {
300
+ "type": "string",
301
+ "title": "Slot",
302
+ "description": "The slot the icon should appear in",
303
+ "examples": []
304
+ }
305
+ }
306
+ },
307
+ "image": {
308
+ "title": "image",
309
+ "type": "object",
310
+ "required": ["src"],
311
+ "properties": {
312
+ "src": {
313
+ "title": "Image URL",
314
+ "$ref": "json-schema-definitions://canvas.module/image-uri"
315
+ },
316
+ "alt": {
317
+ "title": "Alternative text",
318
+ "type": "string"
319
+ },
320
+ "width": {
321
+ "title": "Image width",
322
+ "type": "integer"
323
+ },
324
+ "height": {
325
+ "title": "Image height",
326
+ "type": "integer"
327
+ }
328
+ }
329
+ },
330
+ "video": {
331
+ "title": "video",
332
+ "type": "object",
333
+ "required": ["src"],
334
+ "properties": {
335
+ "src": {
336
+ "title": "Video URL",
337
+ "type": "string",
338
+ "format": "uri-reference",
339
+ "contentMediaType": "video/*",
340
+ "x-allowed-schemes": ["http", "https"]
341
+ },
342
+ "poster": {
343
+ "title": "Poster image URL",
344
+ "$ref": "json-schema-definitions://canvas.module/image-uri"
345
+ }
346
+ }
347
+ },
348
+ "content-entity-reference": {
349
+ "title": "Content entity reference",
350
+ "type": "object",
351
+ "x-allowed-entity-type-id": null
352
+ },
353
+ "config-entity-id": {
354
+ "title": "config entity id",
355
+ "type": "string",
356
+ "pattern": "^[a-z0-9_\\.]+$"
357
+ }
358
+ };
359
+
360
+ //#endregion
7
361
  //#region src/json-render-utils.tsx
8
362
  /**
9
363
  * Converts an array of Drupal Canvas components to json-render spec format.
@@ -167,11 +521,50 @@ function renderSpec(spec, registry) {
167
521
  function renderCanvasTree(components, registry) {
168
522
  return renderSpec(canvasTreeToSpec(components), registry);
169
523
  }
524
+ /**
525
+ * Canvas JSON Schema `$ref` prefix used in component metadata.
526
+ */
527
+ const CANVAS_REF_PREFIX = "json-schema-definitions://canvas.module/";
528
+ /**
529
+ * Rewrites Canvas-specific `$ref` URIs to local JSON Pointer refs (`#/$defs/...`)
530
+ * that Zod's `fromJSONSchema` can resolve natively.
531
+ */
532
+ function rewriteCanvasRefs(node) {
533
+ if (!node || typeof node !== "object" || Array.isArray(node)) return node;
534
+ const record = node;
535
+ const result = {};
536
+ for (const [key, value] of Object.entries(record)) if (key === "$ref" && typeof value === "string" && value.startsWith(CANVAS_REF_PREFIX)) result.$ref = `#/$defs/${value.slice(40)}`;
537
+ else result[key] = rewriteCanvasRefs(value);
538
+ return result;
539
+ }
540
+ /**
541
+ * Pre-rewritten Canvas $defs with local refs.
542
+ */
543
+ const canvasDefs = rewriteCanvasRefs($defs);
544
+ /**
545
+ * Recursively walks a JSON schema object, stripping `uri-reference` and
546
+ * `iri-reference` format keywords and collecting the property paths where
547
+ * they appeared. Follows `$defs` and nested `properties`/`items`.
548
+ */
549
+ function stripUriRefFormats(node, currentPath, paths, visited = /* @__PURE__ */ new WeakSet()) {
550
+ if (!node || typeof node !== "object") return;
551
+ const obj = node;
552
+ if (visited.has(obj)) return;
553
+ visited.add(obj);
554
+ if (obj.format === "uri-reference" || obj.format === "iri-reference") {
555
+ delete obj.format;
556
+ if (currentPath.length > 0) paths.push([...currentPath]);
557
+ }
558
+ if (obj.properties && typeof obj.properties === "object") for (const [key, prop] of Object.entries(obj.properties)) stripUriRefFormats(prop, [...currentPath, key], paths, visited);
559
+ if (obj.items) stripUriRefFormats(obj.items, currentPath, paths, visited);
560
+ if (obj.$defs && typeof obj.$defs === "object") for (const def of Object.values(obj.$defs)) stripUriRefFormats(def, currentPath, paths, visited);
561
+ }
170
562
  function metadataToCatalogEntry(metadata) {
171
563
  const jsonSchema = {
172
564
  type: "object",
173
565
  ...metadata.props
174
566
  };
567
+ jsonSchema.$defs = canvasDefs;
175
568
  if (metadata.required.length > 0) jsonSchema.required = metadata.required;
176
569
  const slotNames = Object.keys(metadata.slots);
177
570
  if (slotNames.length > 0) {
@@ -179,8 +572,32 @@ function metadataToCatalogEntry(metadata) {
179
572
  for (const [slotName, slot] of Object.entries(metadata.slots)) properties[slotName] = { description: slot.title ?? `${slotName} slot` };
180
573
  jsonSchema.properties = properties;
181
574
  }
575
+ const rewritten = rewriteCanvasRefs(jsonSchema);
576
+ const uriRefPaths = [];
577
+ stripUriRefFormats(rewritten, [], uriRefPaths);
578
+ let zodSchema = fromJSONSchema(rewritten);
579
+ if (uriRefPaths.length > 0) zodSchema = zodSchema.superRefine((val, ctx) => {
580
+ for (const path of uriRefPaths) {
581
+ let current = val;
582
+ for (const segment of path) if (current && typeof current === "object") current = current[segment];
583
+ else {
584
+ current = void 0;
585
+ break;
586
+ }
587
+ if (typeof current !== "string") continue;
588
+ try {
589
+ new URL(current, "http://localhost");
590
+ } catch {
591
+ ctx.addIssue({
592
+ code: "custom",
593
+ message: `Invalid URI reference: ${current}`,
594
+ path
595
+ });
596
+ }
597
+ }
598
+ });
182
599
  return {
183
- props: fromJSONSchema(jsonSchema),
600
+ props: zodSchema,
184
601
  slots: slotNames
185
602
  };
186
603
  }
@@ -227,10 +644,38 @@ async function defineComponentRegistry(components) {
227
644
  * @returns A json-render `Catalog` instance
228
645
  */
229
646
  function defineComponentCatalog(metadata) {
230
- return defineCatalog(schema, {
231
- components: Object.fromEntries(metadata.map((m) => [toComponentId(m.machineName), metadataToCatalogEntry(m)])),
647
+ const components = Object.fromEntries(metadata.map((m) => [toComponentId(m.machineName), metadataToCatalogEntry(m)]));
648
+ components["canvas:component-tree"] = {
649
+ props: z.object({}),
650
+ slots: ["children"]
651
+ };
652
+ const catalog = defineCatalog(schema, {
653
+ components,
232
654
  actions: {}
233
655
  });
656
+ const elementVariants = Object.entries(components).map(([name, entry]) => z.object({
657
+ type: z.literal(name),
658
+ props: entry.props,
659
+ children: z.array(z.string()),
660
+ slots: z.record(z.string(), z.array(z.string())),
661
+ visible: z.any().optional()
662
+ }));
663
+ const elementSchema = elementVariants.length >= 2 ? z.discriminatedUnion("type", elementVariants) : elementVariants[0];
664
+ const specSchema = z.object({
665
+ root: z.string(),
666
+ elements: z.record(z.string(), elementSchema)
667
+ });
668
+ return Object.assign(catalog, { validate(spec) {
669
+ const result = specSchema.safeParse(spec);
670
+ if (result.success) return {
671
+ success: true,
672
+ data: result.data
673
+ };
674
+ return {
675
+ success: false,
676
+ error: result.error
677
+ };
678
+ } });
234
679
  }
235
680
 
236
681
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drupal-canvas",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Utilities and base components for building Drupal Canvas Code Components",
5
5
  "license": "MIT",
6
6
  "repository": {