drupal-canvas 0.3.1 → 0.3.2

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.
@@ -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,17 @@ 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
+ }
37
+ type AuthoredSpecElementMap = Record<string, AuthoredSpecElement>;
38
+ type AuthoredSpecSlots = Record<string, string[]>;
27
39
  /**
28
40
  * Converts an array of Drupal Canvas components to json-render spec format.
29
41
  *
@@ -106,11 +118,39 @@ declare function defineComponentCatalog(metadata: ComponentMetadata[]): _json_re
106
118
  }, {
107
119
  components: {
108
120
  [k: string]: {
109
- props: zod0.ZodType<unknown, unknown, zod_v4_core0.$ZodTypeInternals<unknown, unknown>>;
121
+ props: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
110
122
  slots: string[];
111
123
  };
112
124
  };
113
125
  actions: {};
114
- }>;
126
+ }> & {
127
+ validate(spec: unknown): {
128
+ success: true;
129
+ data: {
130
+ root: string;
131
+ elements: Record<string, {
132
+ type: string;
133
+ props: unknown;
134
+ children: string[];
135
+ slots: Record<string, string[]>;
136
+ visible?: any;
137
+ }>;
138
+ };
139
+ error?: undefined;
140
+ } | {
141
+ success: false;
142
+ error: z.ZodError<{
143
+ root: string;
144
+ elements: Record<string, {
145
+ type: string;
146
+ props: unknown;
147
+ children: string[];
148
+ slots: Record<string, string[]>;
149
+ visible?: any;
150
+ }>;
151
+ }>;
152
+ data?: undefined;
153
+ };
154
+ };
115
155
  //#endregion
116
- export { CanvasComponentTree, CanvasComponentTreeNode, ComponentRegistry, canvasTreeToSpec, defineComponentCatalog, defineComponentRegistry, renderCanvasTree, renderSpec, specToCanvasTree };
156
+ export { AuthoredSpecElement, AuthoredSpecElementMap, AuthoredSpecSlots, CanvasComponentTree, CanvasComponentTreeNode, ComponentRegistry, canvasTreeToSpec, defineComponentCatalog, defineComponentRegistry, renderCanvasTree, renderSpec, specToCanvasTree };
@@ -1,9 +1,358 @@
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
+ "config-entity-id": {
349
+ "title": "config entity id",
350
+ "type": "string",
351
+ "pattern": "^[a-z0-9_\\.]+$"
352
+ }
353
+ };
354
+
355
+ //#endregion
7
356
  //#region src/json-render-utils.tsx
8
357
  /**
9
358
  * Converts an array of Drupal Canvas components to json-render spec format.
@@ -167,11 +516,50 @@ function renderSpec(spec, registry) {
167
516
  function renderCanvasTree(components, registry) {
168
517
  return renderSpec(canvasTreeToSpec(components), registry);
169
518
  }
519
+ /**
520
+ * Canvas JSON Schema `$ref` prefix used in component metadata.
521
+ */
522
+ const CANVAS_REF_PREFIX = "json-schema-definitions://canvas.module/";
523
+ /**
524
+ * Rewrites Canvas-specific `$ref` URIs to local JSON Pointer refs (`#/$defs/...`)
525
+ * that Zod's `fromJSONSchema` can resolve natively.
526
+ */
527
+ function rewriteCanvasRefs(node) {
528
+ if (!node || typeof node !== "object" || Array.isArray(node)) return node;
529
+ const record = node;
530
+ const result = {};
531
+ 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)}`;
532
+ else result[key] = rewriteCanvasRefs(value);
533
+ return result;
534
+ }
535
+ /**
536
+ * Pre-rewritten Canvas $defs with local refs.
537
+ */
538
+ const canvasDefs = rewriteCanvasRefs($defs);
539
+ /**
540
+ * Recursively walks a JSON schema object, stripping `uri-reference` and
541
+ * `iri-reference` format keywords and collecting the property paths where
542
+ * they appeared. Follows `$defs` and nested `properties`/`items`.
543
+ */
544
+ function stripUriRefFormats(node, currentPath, paths, visited = /* @__PURE__ */ new WeakSet()) {
545
+ if (!node || typeof node !== "object") return;
546
+ const obj = node;
547
+ if (visited.has(obj)) return;
548
+ visited.add(obj);
549
+ if (obj.format === "uri-reference" || obj.format === "iri-reference") {
550
+ delete obj.format;
551
+ if (currentPath.length > 0) paths.push([...currentPath]);
552
+ }
553
+ if (obj.properties && typeof obj.properties === "object") for (const [key, prop] of Object.entries(obj.properties)) stripUriRefFormats(prop, [...currentPath, key], paths, visited);
554
+ if (obj.items) stripUriRefFormats(obj.items, currentPath, paths, visited);
555
+ if (obj.$defs && typeof obj.$defs === "object") for (const def of Object.values(obj.$defs)) stripUriRefFormats(def, currentPath, paths, visited);
556
+ }
170
557
  function metadataToCatalogEntry(metadata) {
171
558
  const jsonSchema = {
172
559
  type: "object",
173
560
  ...metadata.props
174
561
  };
562
+ jsonSchema.$defs = canvasDefs;
175
563
  if (metadata.required.length > 0) jsonSchema.required = metadata.required;
176
564
  const slotNames = Object.keys(metadata.slots);
177
565
  if (slotNames.length > 0) {
@@ -179,8 +567,32 @@ function metadataToCatalogEntry(metadata) {
179
567
  for (const [slotName, slot] of Object.entries(metadata.slots)) properties[slotName] = { description: slot.title ?? `${slotName} slot` };
180
568
  jsonSchema.properties = properties;
181
569
  }
570
+ const rewritten = rewriteCanvasRefs(jsonSchema);
571
+ const uriRefPaths = [];
572
+ stripUriRefFormats(rewritten, [], uriRefPaths);
573
+ let zodSchema = fromJSONSchema(rewritten);
574
+ if (uriRefPaths.length > 0) zodSchema = zodSchema.superRefine((val, ctx) => {
575
+ for (const path of uriRefPaths) {
576
+ let current = val;
577
+ for (const segment of path) if (current && typeof current === "object") current = current[segment];
578
+ else {
579
+ current = void 0;
580
+ break;
581
+ }
582
+ if (typeof current !== "string") continue;
583
+ try {
584
+ new URL(current, "http://localhost");
585
+ } catch {
586
+ ctx.addIssue({
587
+ code: "custom",
588
+ message: `Invalid URI reference: ${current}`,
589
+ path
590
+ });
591
+ }
592
+ }
593
+ });
182
594
  return {
183
- props: fromJSONSchema(jsonSchema),
595
+ props: zodSchema,
184
596
  slots: slotNames
185
597
  };
186
598
  }
@@ -227,10 +639,38 @@ async function defineComponentRegistry(components) {
227
639
  * @returns A json-render `Catalog` instance
228
640
  */
229
641
  function defineComponentCatalog(metadata) {
230
- return defineCatalog(schema, {
231
- components: Object.fromEntries(metadata.map((m) => [toComponentId(m.machineName), metadataToCatalogEntry(m)])),
642
+ const components = Object.fromEntries(metadata.map((m) => [toComponentId(m.machineName), metadataToCatalogEntry(m)]));
643
+ components["canvas:component-tree"] = {
644
+ props: z.object({}),
645
+ slots: ["children"]
646
+ };
647
+ const catalog = defineCatalog(schema, {
648
+ components,
232
649
  actions: {}
233
650
  });
651
+ const elementVariants = Object.entries(components).map(([name, entry]) => z.object({
652
+ type: z.literal(name),
653
+ props: entry.props,
654
+ children: z.array(z.string()),
655
+ slots: z.record(z.string(), z.array(z.string())),
656
+ visible: z.any().optional()
657
+ }));
658
+ const elementSchema = elementVariants.length >= 2 ? z.discriminatedUnion("type", elementVariants) : elementVariants[0];
659
+ const specSchema = z.object({
660
+ root: z.string(),
661
+ elements: z.record(z.string(), elementSchema)
662
+ });
663
+ return Object.assign(catalog, { validate(spec) {
664
+ const result = specSchema.safeParse(spec);
665
+ if (result.success) return {
666
+ success: true,
667
+ data: result.data
668
+ };
669
+ return {
670
+ success: false,
671
+ error: result.error
672
+ };
673
+ } });
234
674
  }
235
675
 
236
676
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drupal-canvas",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Utilities and base components for building Drupal Canvas Code Components",
5
5
  "license": "MIT",
6
6
  "repository": {