@webstudio-is/react-sdk 0.0.0-021f2d4

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/lib/index.js ADDED
@@ -0,0 +1,1095 @@
1
+ // src/remix.ts
2
+ var getRemixSegment = (segment) => {
3
+ if (segment === "*") {
4
+ return "$";
5
+ }
6
+ const match = segment.match(/^:(?<name>\w+)(?<modifier>\*|\?)?$/);
7
+ const name = match?.groups?.name;
8
+ const modifier = match?.groups?.modifier;
9
+ if (name) {
10
+ if (modifier === "*") {
11
+ return "$";
12
+ }
13
+ if (modifier === "?") {
14
+ return `($${name})`;
15
+ }
16
+ return `$${name}`;
17
+ }
18
+ return `[${segment}]`;
19
+ };
20
+ var generateRemixRoute = (pathname) => {
21
+ if (pathname.startsWith("/")) {
22
+ pathname = pathname.slice(1);
23
+ }
24
+ if (pathname === "") {
25
+ return `_index`;
26
+ }
27
+ const base = pathname.split("/").map(getRemixSegment).join(".");
28
+ const tail = pathname.endsWith("*") ? "" : "._index";
29
+ return `${base}${tail}`;
30
+ };
31
+ var generateRemixParams = (pathname) => {
32
+ const name = pathname.match(/:(?<name>\w+)\*$/)?.groups?.name;
33
+ let generated = "";
34
+ generated += `type Params = Record<string, string | undefined>;
35
+ `;
36
+ generated += `export const getRemixParams = ({ ...params }: Params): Params => {
37
+ `;
38
+ if (name) {
39
+ generated += ` params["${name}"] = params["*"]
40
+ `;
41
+ generated += ` delete params["*"]
42
+ `;
43
+ }
44
+ if (pathname.endsWith("/*")) {
45
+ generated += ` params[0] = params["*"]
46
+ `;
47
+ generated += ` delete params["*"]
48
+ `;
49
+ }
50
+ generated += ` return params
51
+ `;
52
+ generated += `}
53
+ `;
54
+ return generated;
55
+ };
56
+
57
+ // src/css/global-rules.ts
58
+ import { getFontFaces } from "@webstudio-is/fonts";
59
+ var addGlobalRules = (sheet, { assets, assetBaseUrl }) => {
60
+ const fontAssets = [];
61
+ for (const asset of assets.values()) {
62
+ if (asset.type === "font") {
63
+ fontAssets.push(asset);
64
+ }
65
+ }
66
+ const fontFaces = getFontFaces(fontAssets, { assetBaseUrl });
67
+ for (const fontFace of fontFaces) {
68
+ sheet.addFontFaceRule(fontFace);
69
+ }
70
+ };
71
+
72
+ // src/css/css.ts
73
+ import {
74
+ createRegularStyleSheet,
75
+ generateAtomic
76
+ } from "@webstudio-is/css-engine";
77
+ import {
78
+ ROOT_INSTANCE_ID,
79
+ createScope,
80
+ parseComponentName,
81
+ descendantComponent,
82
+ rootComponent
83
+ } from "@webstudio-is/sdk";
84
+ import { kebabCase } from "change-case";
85
+ var createImageValueTransformer = (assets, { assetBaseUrl }) => (styleValue) => {
86
+ if (styleValue.type === "image" && styleValue.value.type === "asset") {
87
+ const asset = assets.get(styleValue.value.value);
88
+ if (asset === void 0) {
89
+ return { type: "keyword", value: "none" };
90
+ }
91
+ const url = `${assetBaseUrl}${asset.name}`;
92
+ return {
93
+ type: "image",
94
+ value: {
95
+ type: "url",
96
+ url
97
+ },
98
+ hidden: styleValue.hidden
99
+ };
100
+ }
101
+ };
102
+ var normalizeClassName = (name) => kebabCase(name);
103
+ var generateCss = ({
104
+ assets,
105
+ instances,
106
+ props,
107
+ breakpoints,
108
+ styles,
109
+ styleSourceSelections,
110
+ componentMetas,
111
+ assetBaseUrl,
112
+ atomic
113
+ }) => {
114
+ const globalSheet = createRegularStyleSheet({ name: "ssr" });
115
+ const sheet = createRegularStyleSheet({ name: "ssr" });
116
+ addGlobalRules(globalSheet, { assets, assetBaseUrl });
117
+ globalSheet.addMediaRule("presets");
118
+ const presetClasses = /* @__PURE__ */ new Map();
119
+ const scope = createScope([], normalizeClassName, "-");
120
+ for (const [component, meta] of componentMetas) {
121
+ const [_namespace, componentName] = parseComponentName(component);
122
+ const className = `w-${scope.getName(component, meta.label ?? componentName)}`;
123
+ const presetStyle = Object.entries(meta.presetStyle ?? {});
124
+ if (presetStyle.length > 0) {
125
+ presetClasses.set(component, className);
126
+ }
127
+ for (const [tag, styles2] of presetStyle) {
128
+ const selector = component === rootComponent ? ":root" : `:where(${tag}.${className})`;
129
+ const rule = globalSheet.addNestingRule(selector);
130
+ for (const declaration of styles2) {
131
+ rule.setDeclaration({
132
+ breakpoint: "presets",
133
+ selector: declaration.state ?? "",
134
+ property: declaration.property,
135
+ value: declaration.value
136
+ });
137
+ }
138
+ }
139
+ }
140
+ for (const breakpoint of breakpoints.values()) {
141
+ sheet.addMediaRule(breakpoint.id, breakpoint);
142
+ }
143
+ const imageValueTransformer = createImageValueTransformer(assets, {
144
+ assetBaseUrl
145
+ });
146
+ sheet.setTransformer(imageValueTransformer);
147
+ for (const styleDecl of styles.values()) {
148
+ const rule = sheet.addMixinRule(styleDecl.styleSourceId);
149
+ rule.setDeclaration({
150
+ breakpoint: styleDecl.breakpointId,
151
+ selector: styleDecl.state ?? "",
152
+ property: styleDecl.property,
153
+ value: styleDecl.value
154
+ });
155
+ }
156
+ const classes = /* @__PURE__ */ new Map();
157
+ const parentIdByInstanceId = /* @__PURE__ */ new Map();
158
+ for (const instance of instances.values()) {
159
+ const presetClass = presetClasses.get(instance.component);
160
+ if (presetClass) {
161
+ classes.set(instance.id, [presetClass]);
162
+ }
163
+ for (const child of instance.children) {
164
+ if (child.type === "id") {
165
+ parentIdByInstanceId.set(child.value, instance.id);
166
+ }
167
+ }
168
+ }
169
+ const descendantSelectorByInstanceId = /* @__PURE__ */ new Map();
170
+ for (const prop of props.values()) {
171
+ if (prop.name === "selector" && prop.type === "string") {
172
+ descendantSelectorByInstanceId.set(prop.instanceId, prop.value);
173
+ }
174
+ }
175
+ const instanceByRule = /* @__PURE__ */ new Map();
176
+ for (const selection of styleSourceSelections.values()) {
177
+ let { instanceId } = selection;
178
+ const { values } = selection;
179
+ if (instanceId === ROOT_INSTANCE_ID) {
180
+ const rule2 = sheet.addNestingRule(`:root`);
181
+ rule2.applyMixins(values);
182
+ continue;
183
+ }
184
+ let descendantSuffix = "";
185
+ const instance = instances.get(instanceId);
186
+ if (instance === void 0) {
187
+ continue;
188
+ }
189
+ if (instance.component === descendantComponent) {
190
+ const parentId = parentIdByInstanceId.get(instanceId);
191
+ const descendantSelector = descendantSelectorByInstanceId.get(instanceId);
192
+ if (parentId && descendantSelector) {
193
+ descendantSuffix = descendantSelector;
194
+ instanceId = parentId;
195
+ }
196
+ }
197
+ const meta = componentMetas.get(instance.component);
198
+ const [_namespace, shortName] = parseComponentName(instance.component);
199
+ const baseName = instance.label ?? meta?.label ?? shortName;
200
+ const className = `w-${scope.getName(instanceId, baseName)}`;
201
+ if (atomic === false) {
202
+ let classList = classes.get(instanceId);
203
+ if (classList === void 0) {
204
+ classList = [];
205
+ classes.set(instanceId, classList);
206
+ }
207
+ classList.push(className);
208
+ }
209
+ const rule = sheet.addNestingRule(`.${className}`, descendantSuffix);
210
+ rule.applyMixins(values);
211
+ instanceByRule.set(rule, instanceId);
212
+ }
213
+ if (atomic) {
214
+ const { cssText } = generateAtomic(sheet, {
215
+ getKey: (rule) => instanceByRule.get(rule),
216
+ transformValue: imageValueTransformer,
217
+ classes
218
+ });
219
+ return { cssText: `${globalSheet.cssText}
220
+ ${cssText}`, classes };
221
+ }
222
+ return {
223
+ cssText: `${globalSheet.cssText}
224
+ ${sheet.cssText}`,
225
+ classes
226
+ };
227
+ };
228
+
229
+ // src/props.ts
230
+ import {
231
+ getPagePath,
232
+ findPageByIdOrPath
233
+ } from "@webstudio-is/sdk";
234
+ var normalizeProps = ({
235
+ props,
236
+ assetBaseUrl,
237
+ assets,
238
+ uploadingImageAssets,
239
+ pages,
240
+ source
241
+ }) => {
242
+ const newProps = [];
243
+ for (const prop of props) {
244
+ if (prop.type === "asset") {
245
+ const assetId = prop.value;
246
+ const asset = assets.get(assetId) ?? uploadingImageAssets.find((asset2) => asset2.id === assetId);
247
+ if (asset === void 0) {
248
+ continue;
249
+ }
250
+ const propBase = {
251
+ id: prop.id,
252
+ name: prop.name,
253
+ required: prop.required,
254
+ instanceId: prop.instanceId
255
+ };
256
+ if (prop.name === "width" && asset.type === "image") {
257
+ newProps.push({
258
+ ...propBase,
259
+ type: "number",
260
+ value: asset.meta.width
261
+ });
262
+ continue;
263
+ }
264
+ if (prop.name === "height" && asset.type === "image") {
265
+ newProps.push({
266
+ ...propBase,
267
+ type: "number",
268
+ value: asset.meta.height
269
+ });
270
+ continue;
271
+ }
272
+ newProps.push({
273
+ ...propBase,
274
+ type: "string",
275
+ value: `${assetBaseUrl}${asset.name}`
276
+ });
277
+ if (source === "canvas") {
278
+ newProps.push({
279
+ id: `${prop.instanceId}-${asset.id}-assetId`,
280
+ name: "$webstudio$canvasOnly$assetId",
281
+ required: false,
282
+ instanceId: prop.instanceId,
283
+ type: "string",
284
+ value: asset.id
285
+ });
286
+ }
287
+ continue;
288
+ }
289
+ if (prop.type === "page") {
290
+ let idProp;
291
+ const pageId = typeof prop.value === "string" ? prop.value : prop.value.pageId;
292
+ const page = findPageByIdOrPath(pageId, pages);
293
+ if (page === void 0) {
294
+ continue;
295
+ }
296
+ if (typeof prop.value !== "string") {
297
+ const { instanceId } = prop.value;
298
+ idProp = props.find(
299
+ (prop2) => prop2.instanceId === instanceId && prop2.name === "id"
300
+ );
301
+ }
302
+ const path = getPagePath(page.id, pages);
303
+ const url = new URL(path, "https://any-valid.url");
304
+ let value = url.pathname;
305
+ if (idProp?.type === "string") {
306
+ const hash = idProp.value;
307
+ url.hash = encodeURIComponent(hash);
308
+ value = `${url.pathname}${url.hash}`;
309
+ }
310
+ newProps.push({
311
+ id: prop.id,
312
+ name: prop.name,
313
+ required: prop.required,
314
+ instanceId: prop.instanceId,
315
+ type: "string",
316
+ value
317
+ });
318
+ continue;
319
+ }
320
+ newProps.push(prop);
321
+ }
322
+ return newProps;
323
+ };
324
+ var idAttribute = "data-ws-id";
325
+ var selectorIdAttribute = "data-ws-selector";
326
+ var componentAttribute = "data-ws-component";
327
+ var showAttribute = "data-ws-show";
328
+ var indexAttribute = "data-ws-index";
329
+ var collapsedAttribute = "data-ws-collapsed";
330
+ var textContentAttribute = "data-ws-text-content";
331
+ var editablePlaceholderVariable = "--data-ws-editable-placeholder";
332
+ var editingPlaceholderVariable = "--data-ws-editing-placeholder";
333
+ var attributeNameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
334
+ var attributeNameChar = attributeNameStartChar + ":\\-0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
335
+ var validAttributeNameRegex = new RegExp(
336
+ // eslint-disable-next-line no-misleading-character-class
337
+ "^[" + attributeNameStartChar + "][" + attributeNameChar + "]*$"
338
+ );
339
+ var illegalAttributeNameCache = /* @__PURE__ */ new Map();
340
+ var validatedAttributeNameCache = /* @__PURE__ */ new Map();
341
+ var isAttributeNameSafe = (attributeName) => {
342
+ if (validatedAttributeNameCache.has(attributeName)) {
343
+ return true;
344
+ }
345
+ if (illegalAttributeNameCache.has(attributeName)) {
346
+ return false;
347
+ }
348
+ if (validAttributeNameRegex.test(attributeName)) {
349
+ validatedAttributeNameCache.set(attributeName, true);
350
+ return true;
351
+ }
352
+ illegalAttributeNameCache.set(attributeName, true);
353
+ return false;
354
+ };
355
+
356
+ // src/embed-template.ts
357
+ import { nanoid } from "nanoid";
358
+ import {
359
+ encodeDataSourceVariable,
360
+ transpileExpression
361
+ } from "@webstudio-is/sdk";
362
+ var getVariablValue = (value) => {
363
+ if (typeof value === "string") {
364
+ return { type: "string", value };
365
+ }
366
+ if (typeof value === "number") {
367
+ return { type: "number", value };
368
+ }
369
+ if (typeof value === "boolean") {
370
+ return { type: "boolean", value };
371
+ }
372
+ if (Array.isArray(value)) {
373
+ return { type: "string[]", value };
374
+ }
375
+ return { type: "json", value };
376
+ };
377
+ var createInstancesFromTemplate = (treeTemplate, instances, props, dataSourceByRef, styleSourceSelections, styleSources, styles, metas, defaultBreakpointId, generateId) => {
378
+ const parentChildren = [];
379
+ for (const item of treeTemplate) {
380
+ if (item.type === "instance") {
381
+ const instanceId = generateId();
382
+ if (item.variables) {
383
+ for (const [name, variable] of Object.entries(item.variables)) {
384
+ if (dataSourceByRef.has(name)) {
385
+ throw Error(`${name} data source already defined`);
386
+ }
387
+ dataSourceByRef.set(name, {
388
+ type: "variable",
389
+ id: generateId(),
390
+ scopeInstanceId: instanceId,
391
+ name: variable.alias ?? name,
392
+ value: getVariablValue(variable.initialValue)
393
+ });
394
+ }
395
+ }
396
+ if (item.props) {
397
+ for (const prop of item.props) {
398
+ const propId = generateId();
399
+ if (prop.type === "expression") {
400
+ props.push({
401
+ id: propId,
402
+ instanceId,
403
+ name: prop.name,
404
+ type: "expression",
405
+ // replace all references with variable names
406
+ value: transpileExpression({
407
+ expression: prop.code,
408
+ replaceVariable: (ref) => {
409
+ const id = dataSourceByRef.get(ref)?.id ?? ref;
410
+ return encodeDataSourceVariable(id);
411
+ }
412
+ })
413
+ });
414
+ continue;
415
+ }
416
+ if (prop.type === "action") {
417
+ props.push({
418
+ id: propId,
419
+ instanceId,
420
+ type: "action",
421
+ name: prop.name,
422
+ value: prop.value.map((value) => {
423
+ const args = value.args ?? [];
424
+ return {
425
+ type: "execute",
426
+ args,
427
+ // replace all references with variable names
428
+ code: transpileExpression({
429
+ expression: value.code,
430
+ replaceVariable: (ref) => {
431
+ if (args.includes(ref)) {
432
+ return;
433
+ }
434
+ const id = dataSourceByRef.get(ref)?.id ?? ref;
435
+ return encodeDataSourceVariable(id);
436
+ }
437
+ })
438
+ };
439
+ })
440
+ });
441
+ continue;
442
+ }
443
+ if (prop.type === "parameter") {
444
+ const dataSourceId = generateId();
445
+ dataSourceByRef.set(prop.variableName, {
446
+ type: "parameter",
447
+ id: dataSourceId,
448
+ scopeInstanceId: instanceId,
449
+ name: prop.variableAlias ?? prop.variableName
450
+ });
451
+ props.push({
452
+ id: propId,
453
+ instanceId,
454
+ name: prop.name,
455
+ type: "parameter",
456
+ // replace variable reference with variable id
457
+ value: dataSourceId
458
+ });
459
+ continue;
460
+ }
461
+ props.push({ id: propId, instanceId, ...prop });
462
+ }
463
+ }
464
+ const styleSourceIds = [];
465
+ if (item.styles) {
466
+ const styleSourceId = generateId();
467
+ styleSources.push({
468
+ type: "local",
469
+ id: styleSourceId
470
+ });
471
+ styleSourceIds.push(styleSourceId);
472
+ for (const styleDecl of item.styles) {
473
+ styles.push({
474
+ breakpointId: defaultBreakpointId,
475
+ styleSourceId,
476
+ state: styleDecl.state,
477
+ property: styleDecl.property,
478
+ value: styleDecl.value
479
+ });
480
+ }
481
+ }
482
+ if (styleSourceIds.length > 0) {
483
+ styleSourceSelections.push({
484
+ instanceId,
485
+ values: styleSourceIds
486
+ });
487
+ }
488
+ const instance = {
489
+ type: "instance",
490
+ id: instanceId,
491
+ label: item.label,
492
+ component: item.component,
493
+ children: []
494
+ };
495
+ instances.push(instance);
496
+ instance.children = createInstancesFromTemplate(
497
+ item.children,
498
+ instances,
499
+ props,
500
+ dataSourceByRef,
501
+ styleSourceSelections,
502
+ styleSources,
503
+ styles,
504
+ metas,
505
+ defaultBreakpointId,
506
+ generateId
507
+ );
508
+ parentChildren.push({
509
+ type: "id",
510
+ value: instanceId
511
+ });
512
+ }
513
+ if (item.type === "text") {
514
+ parentChildren.push({
515
+ type: "text",
516
+ value: item.value,
517
+ placeholder: item.placeholder
518
+ });
519
+ }
520
+ if (item.type === "expression") {
521
+ parentChildren.push({
522
+ type: "expression",
523
+ // replace all references with variable names
524
+ value: transpileExpression({
525
+ expression: item.value,
526
+ replaceVariable: (ref) => {
527
+ const id = dataSourceByRef.get(ref)?.id ?? ref;
528
+ return encodeDataSourceVariable(id);
529
+ }
530
+ })
531
+ });
532
+ }
533
+ }
534
+ return parentChildren;
535
+ };
536
+ var generateDataFromEmbedTemplate = (treeTemplate, metas, generateId = nanoid) => {
537
+ const instances = [];
538
+ const props = [];
539
+ const dataSourceByRef = /* @__PURE__ */ new Map();
540
+ const styleSourceSelections = [];
541
+ const styleSources = [];
542
+ const styles = [];
543
+ const baseBreakpointId = generateId();
544
+ const children = createInstancesFromTemplate(
545
+ treeTemplate,
546
+ instances,
547
+ props,
548
+ dataSourceByRef,
549
+ styleSourceSelections,
550
+ styleSources,
551
+ styles,
552
+ metas,
553
+ baseBreakpointId,
554
+ generateId
555
+ );
556
+ const breakpoints = [];
557
+ if (styles.length > 0) {
558
+ breakpoints.push({
559
+ id: baseBreakpointId,
560
+ label: ""
561
+ });
562
+ }
563
+ return {
564
+ children,
565
+ instances,
566
+ props,
567
+ dataSources: Array.from(dataSourceByRef.values()),
568
+ styleSourceSelections,
569
+ styleSources,
570
+ styles,
571
+ breakpoints,
572
+ assets: [],
573
+ resources: []
574
+ };
575
+ };
576
+ var namespaceEmbedTemplateComponents = (template, namespace, components) => {
577
+ return template.map((item) => {
578
+ if (item.type === "text") {
579
+ return item;
580
+ }
581
+ if (item.type === "expression") {
582
+ return item;
583
+ }
584
+ if (item.type === "instance") {
585
+ const prefix = components.has(item.component) ? `${namespace}:` : "";
586
+ return {
587
+ ...item,
588
+ component: `${prefix}${item.component}`,
589
+ children: namespaceEmbedTemplateComponents(
590
+ item.children,
591
+ namespace,
592
+ components
593
+ )
594
+ };
595
+ }
596
+ item;
597
+ throw Error("Impossible case");
598
+ });
599
+ };
600
+ var namespaceMatcher = (namespace, matcher) => {
601
+ const newMatcher = structuredClone(matcher);
602
+ if (newMatcher.component?.$eq) {
603
+ newMatcher.component.$eq = `${namespace}:${newMatcher.component.$eq}`;
604
+ }
605
+ if (newMatcher.component?.$neq) {
606
+ newMatcher.component.$neq = `${namespace}:${newMatcher.component.$neq}`;
607
+ }
608
+ if (newMatcher.component?.$in) {
609
+ newMatcher.component.$in = newMatcher.component.$in.map(
610
+ (component) => `${namespace}:${component}`
611
+ );
612
+ }
613
+ if (newMatcher.component?.$nin) {
614
+ newMatcher.component.$nin = newMatcher.component.$nin.map(
615
+ (component) => `${namespace}:${component}`
616
+ );
617
+ }
618
+ return newMatcher;
619
+ };
620
+ var namespaceMeta = (meta, namespace, components) => {
621
+ const newMeta = { ...meta };
622
+ if (newMeta.constraints) {
623
+ if (Array.isArray(newMeta.constraints)) {
624
+ newMeta.constraints = newMeta.constraints.map(
625
+ (matcher) => namespaceMatcher(namespace, matcher)
626
+ );
627
+ } else {
628
+ newMeta.constraints = namespaceMatcher(namespace, newMeta.constraints);
629
+ }
630
+ }
631
+ if (newMeta.indexWithinAncestor) {
632
+ newMeta.indexWithinAncestor = components.has(newMeta.indexWithinAncestor) ? `${namespace}:${newMeta.indexWithinAncestor}` : newMeta.indexWithinAncestor;
633
+ }
634
+ if (newMeta.template) {
635
+ newMeta.template = namespaceEmbedTemplateComponents(
636
+ newMeta.template,
637
+ namespace,
638
+ components
639
+ );
640
+ }
641
+ return newMeta;
642
+ };
643
+
644
+ // src/instance-utils.ts
645
+ var getIndexesWithinAncestors = (metas, instances, rootIds) => {
646
+ const ancestors = /* @__PURE__ */ new Set();
647
+ for (const meta of metas.values()) {
648
+ if (meta.indexWithinAncestor !== void 0) {
649
+ ancestors.add(meta.indexWithinAncestor);
650
+ }
651
+ }
652
+ const indexes = /* @__PURE__ */ new Map();
653
+ const traverseInstances = (instances2, instanceId, latestIndexes2 = /* @__PURE__ */ new Map()) => {
654
+ const instance = instances2.get(instanceId);
655
+ if (instance === void 0) {
656
+ return;
657
+ }
658
+ const meta = metas.get(instance.component);
659
+ if (meta === void 0) {
660
+ return;
661
+ }
662
+ if (ancestors.has(instance.component)) {
663
+ latestIndexes2 = new Map(latestIndexes2);
664
+ latestIndexes2.set(instance.component, /* @__PURE__ */ new Map());
665
+ }
666
+ if (meta.indexWithinAncestor !== void 0) {
667
+ const ancestorIndexes = latestIndexes2.get(meta.indexWithinAncestor);
668
+ if (ancestorIndexes !== void 0) {
669
+ let index = ancestorIndexes.get(instance.component) ?? -1;
670
+ index += 1;
671
+ ancestorIndexes.set(instance.component, index);
672
+ indexes.set(instance.id, index);
673
+ }
674
+ }
675
+ for (const child of instance.children) {
676
+ if (child.type === "id") {
677
+ traverseInstances(instances2, child.value, latestIndexes2);
678
+ }
679
+ }
680
+ };
681
+ const latestIndexes = /* @__PURE__ */ new Map();
682
+ for (const instanceId of rootIds) {
683
+ traverseInstances(instances, instanceId, latestIndexes);
684
+ }
685
+ return indexes;
686
+ };
687
+
688
+ // src/component-generator.ts
689
+ import {
690
+ parseComponentName as parseComponentName2,
691
+ generateExpression,
692
+ decodeDataSourceVariable,
693
+ transpileExpression as transpileExpression2,
694
+ blockComponent,
695
+ blockTemplateComponent,
696
+ collectionComponent,
697
+ descendantComponent as descendantComponent2
698
+ } from "@webstudio-is/sdk";
699
+ var generateAction = ({
700
+ scope,
701
+ prop,
702
+ dataSources,
703
+ usedDataSources
704
+ }) => {
705
+ const setters = /* @__PURE__ */ new Set();
706
+ let args = [];
707
+ let assignersCode = "";
708
+ for (const value of prop.value) {
709
+ args = value.args;
710
+ assignersCode += transpileExpression2({
711
+ expression: value.code,
712
+ executable: true,
713
+ replaceVariable: (identifier, assignee) => {
714
+ if (args?.includes(identifier)) {
715
+ return;
716
+ }
717
+ const depId = decodeDataSourceVariable(identifier);
718
+ const dep = depId ? dataSources.get(depId) : void 0;
719
+ if (dep) {
720
+ usedDataSources.set(dep.id, dep);
721
+ if (assignee) {
722
+ setters.add(dep);
723
+ }
724
+ const valueName = scope.getName(dep.id, dep.name);
725
+ return valueName;
726
+ }
727
+ console.error(`Unknown dependency "${identifier}"`);
728
+ }
729
+ });
730
+ assignersCode += `
731
+ `;
732
+ }
733
+ let settersCode = "";
734
+ for (const dataSource of setters) {
735
+ const valueName = scope.getName(dataSource.id, dataSource.name);
736
+ const setterName = scope.getName(
737
+ `set$${dataSource.id}`,
738
+ `set$${dataSource.name}`
739
+ );
740
+ settersCode += `${setterName}(${valueName})
741
+ `;
742
+ }
743
+ const argsList = args.map((arg) => `${arg}: any`).join(", ");
744
+ let generated = "";
745
+ generated += `(${argsList}) => {
746
+ `;
747
+ generated += assignersCode;
748
+ generated += settersCode;
749
+ generated += `}`;
750
+ return generated;
751
+ };
752
+ var generatePropValue = ({
753
+ scope,
754
+ prop,
755
+ dataSources,
756
+ usedDataSources
757
+ }) => {
758
+ if (prop.type === "asset" || prop.type === "page") {
759
+ return;
760
+ }
761
+ if (prop.type === "string" || prop.type === "number" || prop.type === "boolean" || prop.type === "string[]" || prop.type === "json") {
762
+ return JSON.stringify(prop.value);
763
+ }
764
+ if (prop.type === "parameter") {
765
+ const dataSource = dataSources.get(prop.value);
766
+ if (dataSource === void 0) {
767
+ return;
768
+ }
769
+ usedDataSources.set(dataSource.id, dataSource);
770
+ return scope.getName(dataSource.id, dataSource.name);
771
+ }
772
+ if (prop.type === "expression") {
773
+ return generateExpression({
774
+ expression: prop.value,
775
+ dataSources,
776
+ usedDataSources,
777
+ scope
778
+ });
779
+ }
780
+ if (prop.type === "action") {
781
+ return generateAction({ scope, prop, dataSources, usedDataSources });
782
+ }
783
+ if (prop.type === "resource") {
784
+ return JSON.stringify(scope.getName(prop.value, prop.name));
785
+ }
786
+ prop;
787
+ };
788
+ var generateJsxElement = ({
789
+ context = "jsx",
790
+ scope,
791
+ instance,
792
+ props,
793
+ dataSources,
794
+ usedDataSources,
795
+ indexesWithinAncestors,
796
+ children,
797
+ classesMap
798
+ }) => {
799
+ if (instance.component === descendantComponent2) {
800
+ return "";
801
+ }
802
+ let generatedProps = "";
803
+ const index = indexesWithinAncestors.get(instance.id);
804
+ if (index !== void 0) {
805
+ generatedProps += `
806
+ ${indexAttribute}="${index}"`;
807
+ }
808
+ let conditionValue;
809
+ let collectionDataValue;
810
+ let collectionItemValue;
811
+ let classNameValue;
812
+ for (const prop of props.values()) {
813
+ if (prop.instanceId !== instance.id) {
814
+ continue;
815
+ }
816
+ const propValue = generatePropValue({
817
+ scope,
818
+ prop,
819
+ dataSources,
820
+ usedDataSources
821
+ });
822
+ if (isAttributeNameSafe(prop.name) === false) {
823
+ continue;
824
+ }
825
+ if (prop.name === showAttribute) {
826
+ if (propValue === "true") {
827
+ continue;
828
+ }
829
+ if (propValue === "false") {
830
+ return "";
831
+ }
832
+ conditionValue = propValue;
833
+ continue;
834
+ }
835
+ if (instance.component === collectionComponent) {
836
+ if (prop.name === "data") {
837
+ collectionDataValue = propValue;
838
+ }
839
+ if (prop.name === "item") {
840
+ collectionItemValue = propValue;
841
+ }
842
+ continue;
843
+ }
844
+ if (prop.name === "className" && propValue !== void 0) {
845
+ classNameValue = propValue;
846
+ continue;
847
+ }
848
+ if (propValue !== void 0) {
849
+ generatedProps += `
850
+ ${prop.name}={${propValue}}`;
851
+ }
852
+ }
853
+ const classMapArray = classesMap?.get(instance.id);
854
+ if (classMapArray || classNameValue) {
855
+ let classNameTemplate = classMapArray ? classMapArray.join(" ") : "";
856
+ if (classNameValue) {
857
+ if (classNameTemplate) {
858
+ classNameTemplate += " ";
859
+ }
860
+ classNameTemplate += "${" + classNameValue + "}";
861
+ }
862
+ generatedProps += "\nclassName={`" + classNameTemplate + "`}";
863
+ }
864
+ let generatedElement = "";
865
+ if (instance.component === blockTemplateComponent) {
866
+ return "";
867
+ }
868
+ if (instance.component === collectionComponent) {
869
+ if (collectionDataValue === void 0 || collectionItemValue === void 0) {
870
+ return "";
871
+ }
872
+ const indexVariable = scope.getName(`${instance.id}-index`, "index");
873
+ generatedElement += `{${collectionDataValue}?.map((${collectionItemValue}: any, ${indexVariable}: number) =>
874
+ `;
875
+ generatedElement += `<Fragment key={${indexVariable}}>
876
+ `;
877
+ generatedElement += children;
878
+ generatedElement += `</Fragment>
879
+ `;
880
+ generatedElement += `)}
881
+ `;
882
+ } else if (instance.component === blockComponent) {
883
+ generatedElement += children;
884
+ } else {
885
+ const [_namespace, shortName] = parseComponentName2(instance.component);
886
+ const componentVariable = scope.getName(instance.component, shortName);
887
+ if (instance.children.length === 0) {
888
+ generatedElement += `<${componentVariable}${generatedProps} />
889
+ `;
890
+ } else {
891
+ generatedElement += `<${componentVariable}${generatedProps}>
892
+ `;
893
+ generatedElement += children;
894
+ generatedElement += `</${componentVariable}>
895
+ `;
896
+ }
897
+ }
898
+ if (conditionValue) {
899
+ let conditionalElement = "";
900
+ let before = "";
901
+ let after = "";
902
+ if (context === "jsx") {
903
+ before = "{";
904
+ after = "}";
905
+ }
906
+ conditionalElement += `${before}(${conditionValue}) &&
907
+ `;
908
+ if (instance.component === collectionComponent) {
909
+ conditionalElement += "<>\n";
910
+ conditionalElement += generatedElement;
911
+ conditionalElement += "</>\n";
912
+ } else {
913
+ conditionalElement += generatedElement;
914
+ }
915
+ conditionalElement += `${after}
916
+ `;
917
+ return conditionalElement;
918
+ }
919
+ return generatedElement;
920
+ };
921
+ var generateJsxChildren = ({
922
+ scope,
923
+ children,
924
+ instances,
925
+ props,
926
+ dataSources,
927
+ usedDataSources,
928
+ indexesWithinAncestors,
929
+ classesMap,
930
+ excludePlaceholders
931
+ }) => {
932
+ let generatedChildren = "";
933
+ for (const child of children) {
934
+ if (child.type === "text") {
935
+ if (excludePlaceholders && child.placeholder === true) {
936
+ continue;
937
+ }
938
+ generatedChildren += child.value.split("\n").map((line) => `{${JSON.stringify(line)}}
939
+ `).join(`<br />
940
+ `);
941
+ continue;
942
+ }
943
+ if (child.type === "expression") {
944
+ const expression = generateExpression({
945
+ expression: child.value,
946
+ dataSources,
947
+ usedDataSources,
948
+ scope
949
+ });
950
+ generatedChildren = `{${expression}}
951
+ `;
952
+ continue;
953
+ }
954
+ if (child.type === "id") {
955
+ const instanceId = child.value;
956
+ const instance = instances.get(instanceId);
957
+ if (instance === void 0) {
958
+ continue;
959
+ }
960
+ generatedChildren += generateJsxElement({
961
+ context: "jsx",
962
+ scope,
963
+ instance,
964
+ props,
965
+ dataSources,
966
+ usedDataSources,
967
+ indexesWithinAncestors,
968
+ classesMap,
969
+ children: generateJsxChildren({
970
+ classesMap,
971
+ scope,
972
+ children: instance.children,
973
+ instances,
974
+ props,
975
+ dataSources,
976
+ usedDataSources,
977
+ indexesWithinAncestors,
978
+ excludePlaceholders
979
+ })
980
+ });
981
+ continue;
982
+ }
983
+ child;
984
+ }
985
+ return generatedChildren;
986
+ };
987
+ var generateWebstudioComponent = ({
988
+ scope,
989
+ name,
990
+ rootInstanceId,
991
+ parameters,
992
+ instances,
993
+ props,
994
+ dataSources,
995
+ indexesWithinAncestors,
996
+ classesMap
997
+ }) => {
998
+ const instance = instances.get(rootInstanceId);
999
+ if (instance === void 0) {
1000
+ return "";
1001
+ }
1002
+ const usedDataSources = /* @__PURE__ */ new Map();
1003
+ const generatedJsx = generateJsxElement({
1004
+ context: "expression",
1005
+ scope,
1006
+ instance,
1007
+ props,
1008
+ dataSources,
1009
+ usedDataSources,
1010
+ indexesWithinAncestors,
1011
+ classesMap,
1012
+ children: generateJsxChildren({
1013
+ scope,
1014
+ children: instance.children,
1015
+ instances,
1016
+ props,
1017
+ dataSources,
1018
+ usedDataSources,
1019
+ indexesWithinAncestors,
1020
+ classesMap
1021
+ })
1022
+ });
1023
+ let generatedProps = "";
1024
+ if (parameters.length > 0) {
1025
+ let generatedPropsValue = "{ ";
1026
+ let generatedPropsType = "{ ";
1027
+ for (const parameter of parameters) {
1028
+ const dataSource = usedDataSources.get(parameter.value);
1029
+ if (dataSource) {
1030
+ const valueName = scope.getName(dataSource.id, dataSource.name);
1031
+ generatedPropsValue += `${parameter.name}: ${valueName}, `;
1032
+ }
1033
+ generatedPropsType += `${parameter.name}: any; `;
1034
+ }
1035
+ generatedPropsValue += `}`;
1036
+ generatedPropsType += `}`;
1037
+ generatedProps = `${generatedPropsValue}: ${generatedPropsType}`;
1038
+ }
1039
+ let generatedDataSources = "";
1040
+ for (const dataSource of usedDataSources.values()) {
1041
+ if (dataSource.type === "variable") {
1042
+ const valueName = scope.getName(dataSource.id, dataSource.name);
1043
+ const setterName = scope.getName(
1044
+ `set$${dataSource.id}`,
1045
+ `set$${dataSource.name}`
1046
+ );
1047
+ const initialValue = dataSource.value.value;
1048
+ const initialValueString = JSON.stringify(initialValue);
1049
+ generatedDataSources += `let [${valueName}, ${setterName}] = useVariableState<any>(${initialValueString})
1050
+ `;
1051
+ }
1052
+ if (dataSource.type === "resource") {
1053
+ const valueName = scope.getName(dataSource.id, dataSource.name);
1054
+ const resourceName = scope.getName(
1055
+ dataSource.resourceId,
1056
+ dataSource.name
1057
+ );
1058
+ const resourceNameString = JSON.stringify(resourceName);
1059
+ generatedDataSources += `let ${valueName} = useResource(${resourceNameString})
1060
+ `;
1061
+ }
1062
+ }
1063
+ let generatedComponent = "";
1064
+ generatedComponent += `const ${name} = (${generatedProps}) => {
1065
+ `;
1066
+ generatedComponent += `${generatedDataSources}`;
1067
+ generatedComponent += `return ${generatedJsx}`;
1068
+ generatedComponent += `}
1069
+ `;
1070
+ return generatedComponent;
1071
+ };
1072
+ export {
1073
+ addGlobalRules,
1074
+ collapsedAttribute,
1075
+ componentAttribute,
1076
+ createImageValueTransformer,
1077
+ editablePlaceholderVariable,
1078
+ editingPlaceholderVariable,
1079
+ generateCss,
1080
+ generateDataFromEmbedTemplate,
1081
+ generateJsxChildren,
1082
+ generateJsxElement,
1083
+ generateRemixParams,
1084
+ generateRemixRoute,
1085
+ generateWebstudioComponent,
1086
+ getIndexesWithinAncestors,
1087
+ idAttribute,
1088
+ indexAttribute,
1089
+ isAttributeNameSafe,
1090
+ namespaceMeta,
1091
+ normalizeProps,
1092
+ selectorIdAttribute,
1093
+ showAttribute,
1094
+ textContentAttribute
1095
+ };