@orion-studios/payload-studio 0.6.0-beta.43 → 0.6.0-beta.44

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.
@@ -0,0 +1,753 @@
1
+ 'use client';
2
+ "use strict";
3
+ "use client";
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
+
32
+ // src/builder-v2/client.ts
33
+ var client_exports = {};
34
+ __export(client_exports, {
35
+ GrapesPageEditor: () => GrapesPageEditor
36
+ });
37
+ module.exports = __toCommonJS(client_exports);
38
+
39
+ // src/builder-v2/editor/GrapesPageEditor.tsx
40
+ var import_react = require("react");
41
+
42
+ // src/shared/clientImageUploadOptimization.ts
43
+ var MAX_DIRECT_UPLOAD_BYTES = 4e6;
44
+ var extensionForMimeType = (mimeType) => {
45
+ switch (mimeType) {
46
+ case "image/webp":
47
+ return ".webp";
48
+ case "image/png":
49
+ return ".png";
50
+ default:
51
+ return ".jpg";
52
+ }
53
+ };
54
+ var detectCanvasTransparency = (context, width, height) => {
55
+ try {
56
+ const { data } = context.getImageData(0, 0, width, height);
57
+ for (let index = 3; index < data.length; index += 4) {
58
+ if (data[index] < 255) {
59
+ return true;
60
+ }
61
+ }
62
+ } catch {
63
+ }
64
+ return false;
65
+ };
66
+ var resolveOutputMimeTypes = (sourceMime, hasTransparency) => {
67
+ const candidates = [];
68
+ if (hasTransparency) {
69
+ candidates.push("image/webp", "image/png");
70
+ } else if (sourceMime === "image/webp") {
71
+ candidates.push("image/webp", "image/jpeg");
72
+ } else if (sourceMime === "image/png") {
73
+ candidates.push("image/webp", "image/jpeg", "image/png");
74
+ } else {
75
+ candidates.push("image/jpeg", "image/webp");
76
+ }
77
+ return [...new Set(candidates)];
78
+ };
79
+ async function optimizeImageForUpload(file) {
80
+ if (!file.type.startsWith("image/")) {
81
+ return file;
82
+ }
83
+ const objectURL = URL.createObjectURL(file);
84
+ try {
85
+ const image = await new Promise((resolve, reject) => {
86
+ const nextImage = new Image();
87
+ nextImage.onload = () => resolve(nextImage);
88
+ nextImage.onerror = () => reject(new Error("Could not read image for upload optimization."));
89
+ nextImage.src = objectURL;
90
+ });
91
+ const canvas = document.createElement("canvas");
92
+ canvas.width = Math.max(1, image.width);
93
+ canvas.height = Math.max(1, image.height);
94
+ const context = canvas.getContext("2d");
95
+ if (!context) {
96
+ return file;
97
+ }
98
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
99
+ const sourceMime = file.type.toLowerCase();
100
+ const hasTransparency = detectCanvasTransparency(context, canvas.width, canvas.height);
101
+ const outputMimes = resolveOutputMimeTypes(sourceMime, hasTransparency);
102
+ const qualityPasses = [0.82, 0.74, 0.66, 0.58, 0.5, 0.42, 0.36, 0.3, 0.26];
103
+ let bestFile = null;
104
+ for (const outputMime of outputMimes) {
105
+ const passes = outputMime === "image/png" ? [void 0] : qualityPasses;
106
+ for (const quality of passes) {
107
+ const blob = await new Promise((resolve) => {
108
+ canvas.toBlob((value) => resolve(value), outputMime, quality);
109
+ });
110
+ if (!blob) {
111
+ continue;
112
+ }
113
+ const optimizedName = file.name.replace(/\.[^/.]+$/, extensionForMimeType(outputMime));
114
+ const optimized = new File([blob], optimizedName, {
115
+ lastModified: Date.now(),
116
+ type: outputMime
117
+ });
118
+ if (!bestFile || optimized.size < bestFile.size) {
119
+ bestFile = optimized;
120
+ }
121
+ if (optimized.size <= MAX_DIRECT_UPLOAD_BYTES) {
122
+ break;
123
+ }
124
+ }
125
+ }
126
+ if (!bestFile) {
127
+ return file;
128
+ }
129
+ return bestFile.size < file.size ? bestFile : file;
130
+ } finally {
131
+ URL.revokeObjectURL(objectURL);
132
+ }
133
+ }
134
+
135
+ // src/builder-v2/projectData.ts
136
+ var isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
137
+ var createEmptyBuilderV2ProjectData = (title = "Untitled Page") => ({
138
+ assets: [],
139
+ pages: [
140
+ {
141
+ component: {
142
+ components: [
143
+ {
144
+ attributes: {
145
+ class: "orion-builder-v2-section"
146
+ },
147
+ components: [
148
+ {
149
+ content: title,
150
+ tagName: "h1",
151
+ type: "text"
152
+ },
153
+ {
154
+ content: "Start building this page by dragging blocks from the panel.",
155
+ tagName: "p",
156
+ type: "text"
157
+ }
158
+ ],
159
+ tagName: "section"
160
+ }
161
+ ],
162
+ type: "wrapper"
163
+ },
164
+ id: "page",
165
+ name: title
166
+ }
167
+ ],
168
+ styles: []
169
+ });
170
+ var normalizeBuilderV2ProjectData = (value, fallbackTitle = "Untitled Page") => {
171
+ if (!isRecord(value)) {
172
+ return createEmptyBuilderV2ProjectData(fallbackTitle);
173
+ }
174
+ return value;
175
+ };
176
+
177
+ // src/builder-v2/runtime/placeholders.ts
178
+ var placeholderPattern = /<(?<tag>[a-zA-Z][a-zA-Z0-9-]*)\b(?<attrs>[^>]*)data-orion-component=["'](?<component>[^"']+)["'](?<rest>[^>]*)>(?<content>.*?)<\/\k<tag>>/gis;
179
+ var attrPattern = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)=(?:"([^"]*)"|'([^']*)')/g;
180
+ var decodeHtmlAttribute = (value) => value.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
181
+ var parseAttributes = (value) => {
182
+ const props = {};
183
+ let match;
184
+ while ((match = attrPattern.exec(value)) !== null) {
185
+ const name = match[1];
186
+ const rawValue = match[2] ?? match[3] ?? "";
187
+ if (!name.startsWith("data-")) {
188
+ continue;
189
+ }
190
+ if (name === "data-orion-component" || name === "data-orion-id") {
191
+ continue;
192
+ }
193
+ const propName = name.replace(/^data-orion-/, "").replace(/^data-/, "").replace(/-([a-z])/g, (_, char) => char.toUpperCase());
194
+ props[propName] = decodeHtmlAttribute(rawValue);
195
+ }
196
+ return props;
197
+ };
198
+ var extractAttribute = (attrs, name) => {
199
+ const pattern = new RegExp(`${name}=["']([^"']+)["']`, "i");
200
+ const match = attrs.match(pattern);
201
+ return match ? decodeHtmlAttribute(match[1]) : null;
202
+ };
203
+ var parseBuilderV2DynamicComponents = (html) => {
204
+ const instances = [];
205
+ let match;
206
+ while ((match = placeholderPattern.exec(html)) !== null) {
207
+ const attrs = `${match.groups?.attrs ?? ""} ${match.groups?.rest ?? ""}`;
208
+ const component = match.groups?.component ?? "";
209
+ if (!component) {
210
+ continue;
211
+ }
212
+ instances.push({
213
+ component,
214
+ id: extractAttribute(attrs, "data-orion-id") || `component-${instances.length + 1}`,
215
+ props: parseAttributes(attrs)
216
+ });
217
+ }
218
+ return instances;
219
+ };
220
+
221
+ // src/builder-v2/sanitize.ts
222
+ var import_sanitize_html = __toESM(require("sanitize-html"));
223
+ var allowedTags = import_sanitize_html.default.defaults.allowedTags.concat([
224
+ "article",
225
+ "aside",
226
+ "button",
227
+ "figure",
228
+ "figcaption",
229
+ "footer",
230
+ "header",
231
+ "main",
232
+ "nav",
233
+ "section",
234
+ "source",
235
+ "video"
236
+ ]);
237
+ var allowedAttributes = {
238
+ ...import_sanitize_html.default.defaults.allowedAttributes,
239
+ "*": [
240
+ "aria-*",
241
+ "class",
242
+ "data-*",
243
+ "id",
244
+ "role",
245
+ "style",
246
+ "title"
247
+ ],
248
+ a: ["aria-*", "class", "data-*", "href", "id", "name", "rel", "style", "target", "title"],
249
+ button: ["aria-*", "class", "data-*", "disabled", "id", "style", "title", "type"],
250
+ iframe: ["allow", "allowfullscreen", "class", "data-*", "height", "loading", "src", "style", "title", "width"],
251
+ img: ["alt", "class", "data-*", "height", "id", "loading", "sizes", "src", "srcset", "style", "title", "width"],
252
+ source: ["media", "src", "srcset", "type"],
253
+ video: ["autoplay", "class", "controls", "height", "loop", "muted", "playsinline", "poster", "preload", "src", "style", "width"]
254
+ };
255
+ var allowedIframeHosts = [
256
+ "calendar.google.com",
257
+ "calendly.com",
258
+ "player.vimeo.com",
259
+ "www.youtube.com",
260
+ "youtube.com"
261
+ ];
262
+ var sanitizeBuilderHtml = (value) => {
263
+ if (typeof value !== "string" || value.trim().length === 0) {
264
+ return "";
265
+ }
266
+ return (0, import_sanitize_html.default)(value, {
267
+ allowedAttributes,
268
+ allowedIframeHostnames: allowedIframeHosts,
269
+ allowedSchemes: ["http", "https", "mailto", "tel"],
270
+ allowedSchemesByTag: {
271
+ img: ["http", "https", "data"]
272
+ },
273
+ allowedTags,
274
+ allowProtocolRelative: false,
275
+ parseStyleAttributes: false
276
+ });
277
+ };
278
+ var sanitizeBuilderCss = (value) => {
279
+ if (typeof value !== "string" || value.trim().length === 0) {
280
+ return "";
281
+ }
282
+ return value.replace(/@import\s+[^;]+;/gi, "").replace(/expression\s*\(/gi, "").replace(/javascript\s*:/gi, "");
283
+ };
284
+
285
+ // src/builder-v2/editor/defaultBlocks.ts
286
+ var registerOrionBuilderV2Blocks = (editor) => {
287
+ const blocks = editor.Blocks;
288
+ blocks.add("orion-section", {
289
+ category: "Layout",
290
+ content: `
291
+ <section class="orion-builder-v2-section">
292
+ <div class="orion-builder-v2-container">
293
+ <h2>Section Heading</h2>
294
+ <p>Add supporting content here.</p>
295
+ </div>
296
+ </section>
297
+ `,
298
+ label: "Section"
299
+ });
300
+ blocks.add("orion-hero", {
301
+ category: "Sections",
302
+ content: `
303
+ <section class="orion-builder-v2-hero">
304
+ <div class="orion-builder-v2-container">
305
+ <p class="orion-builder-v2-kicker">Optional kicker</p>
306
+ <h1>Build a stronger website</h1>
307
+ <p>Use this area for a clear value proposition and call to action.</p>
308
+ <a class="orion-builder-v2-button" href="/contact">Get started</a>
309
+ </div>
310
+ </section>
311
+ `,
312
+ label: "Hero"
313
+ });
314
+ blocks.add("orion-columns", {
315
+ category: "Layout",
316
+ content: `
317
+ <section class="orion-builder-v2-section">
318
+ <div class="orion-builder-v2-container orion-builder-v2-grid is-3">
319
+ <article class="orion-builder-v2-card"><h3>Column One</h3><p>Add content.</p></article>
320
+ <article class="orion-builder-v2-card"><h3>Column Two</h3><p>Add content.</p></article>
321
+ <article class="orion-builder-v2-card"><h3>Column Three</h3><p>Add content.</p></article>
322
+ </div>
323
+ </section>
324
+ `,
325
+ label: "Columns"
326
+ });
327
+ blocks.add("orion-button", {
328
+ category: "Basic",
329
+ content: '<a class="orion-builder-v2-button" href="/contact">Button</a>',
330
+ label: "Button"
331
+ });
332
+ blocks.add("orion-image", {
333
+ category: "Basic",
334
+ content: '<img alt="Image" class="orion-builder-v2-image" src="https://placehold.co/1200x700" />',
335
+ label: "Image"
336
+ });
337
+ blocks.add("orion-form-embed", {
338
+ category: "Dynamic",
339
+ content: `
340
+ <div
341
+ class="orion-builder-v2-dynamic-placeholder"
342
+ data-orion-component="formEmbed"
343
+ data-orion-form-slug="contact"
344
+ >
345
+ <strong>Form Embed</strong>
346
+ <span>contact</span>
347
+ </div>
348
+ `,
349
+ label: "Form"
350
+ });
351
+ };
352
+
353
+ // src/builder-v2/editor/projectComponents.ts
354
+ var normalizeDefinition = (type, value) => {
355
+ if (!value || typeof value === "function") {
356
+ return null;
357
+ }
358
+ return {
359
+ ...value,
360
+ type: value.type || type
361
+ };
362
+ };
363
+ var registerProjectDynamicComponents = (editor, adapter) => {
364
+ const components = adapter?.components || {};
365
+ Object.keys(components).forEach((type) => {
366
+ const definition = normalizeDefinition(type, components[type]);
367
+ if (!definition) {
368
+ return;
369
+ }
370
+ editor.DomComponents.addType(`orion-${type}`, {
371
+ model: {
372
+ defaults: {
373
+ attributes: {
374
+ "data-orion-component": type,
375
+ "data-orion-id": `${type}-${Date.now()}`
376
+ },
377
+ components: definition.editorPreview?.({}) || `<div class="orion-builder-v2-dynamic-placeholder"><strong>${definition.label}</strong></div>`,
378
+ droppable: false,
379
+ tagName: "div",
380
+ traits: [
381
+ {
382
+ label: "Component",
383
+ name: "data-orion-component",
384
+ type: "text"
385
+ },
386
+ ...(definition.traits || []).map((trait) => ({
387
+ label: trait.label,
388
+ name: `data-orion-${trait.name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)}`,
389
+ options: trait.options,
390
+ placeholder: trait.placeholder,
391
+ type: trait.type
392
+ }))
393
+ ]
394
+ }
395
+ }
396
+ });
397
+ editor.Blocks.add(`orion-dynamic-${type}`, {
398
+ category: "Project",
399
+ content: {
400
+ type: `orion-${type}`
401
+ },
402
+ label: definition.label
403
+ });
404
+ });
405
+ };
406
+
407
+ // src/builder-v2/editor/GrapesPageEditor.tsx
408
+ var import_jsx_runtime = require("react/jsx-runtime");
409
+ var postToParent = (payload) => {
410
+ window.parent?.postMessage(
411
+ {
412
+ source: "payload-visual-builder-child",
413
+ ...payload
414
+ },
415
+ "*"
416
+ );
417
+ };
418
+ var buildSavePayload = (editor, status, projectData) => ({
419
+ builderMode: "grapes-v2",
420
+ compiledCss: sanitizeBuilderCss(editor.getCss()),
421
+ compiledHtml: sanitizeBuilderHtml(editor.getHtml()),
422
+ projectData,
423
+ status
424
+ });
425
+ var parsePayloadErrorMessage = async (response, fallback) => {
426
+ try {
427
+ const json = await response.json();
428
+ return json.errors?.[0]?.message || json.message || fallback;
429
+ } catch {
430
+ const raw = await response.text();
431
+ return raw.trim() || fallback;
432
+ }
433
+ };
434
+ var getRelationID = (value) => {
435
+ if (typeof value === "number" || typeof value === "string") {
436
+ return value;
437
+ }
438
+ if (!value || typeof value !== "object") {
439
+ return null;
440
+ }
441
+ const id = value.id;
442
+ return typeof id === "number" || typeof id === "string" ? id : null;
443
+ };
444
+ var mediaDocToAsset = (doc) => {
445
+ const id = getRelationID(doc);
446
+ const filename = typeof doc.filename === "string" ? doc.filename : "";
447
+ const src = typeof doc.url === "string" && doc.url.length > 0 ? doc.url : filename ? `/api/media/file/${encodeURIComponent(filename)}` : "";
448
+ if (id === null || !src) {
449
+ return null;
450
+ }
451
+ return {
452
+ alt: typeof doc.alt === "string" ? doc.alt : "",
453
+ id,
454
+ name: filename || String(id),
455
+ src,
456
+ type: "image"
457
+ };
458
+ };
459
+ var extractUploadedMedia = (value) => {
460
+ const candidate = value && typeof value === "object" && "doc" in value ? value.doc : value;
461
+ if (!candidate || typeof candidate !== "object") {
462
+ return null;
463
+ }
464
+ const id = getRelationID(candidate);
465
+ if (id === null) {
466
+ return null;
467
+ }
468
+ const typed = candidate;
469
+ return {
470
+ alt: typeof typed.alt === "string" ? typed.alt : "",
471
+ filename: typeof typed.filename === "string" ? typed.filename : "",
472
+ id,
473
+ url: typeof typed.url === "string" ? typed.url : ""
474
+ };
475
+ };
476
+ var loadPayloadMediaAssets = async (editor) => {
477
+ const response = await fetch(`/api/media?depth=1&limit=100&sort=-updatedAt&_=${Date.now()}`, {
478
+ cache: "no-store",
479
+ credentials: "include"
480
+ });
481
+ if (!response.ok) {
482
+ return;
483
+ }
484
+ const json = await response.json();
485
+ const assets = (Array.isArray(json.docs) ? json.docs : []).map((doc) => mediaDocToAsset(doc)).filter((asset) => asset !== null);
486
+ editor.AssetManager.add(assets);
487
+ };
488
+ var uploadPayloadMediaAssets = async (editor, files) => {
489
+ const fileArray = Array.from(files);
490
+ const uploadedAssets = [];
491
+ for (const file of fileArray) {
492
+ const optimizedFile = await optimizeImageForUpload(file);
493
+ if (optimizedFile.size > MAX_DIRECT_UPLOAD_BYTES) {
494
+ throw new Error("Image is too large. Use an image under 4MB or lower-resolution export.");
495
+ }
496
+ const fallbackAlt = file.name.replace(/\.[^/.]+$/, "").trim();
497
+ const formData = new FormData();
498
+ formData.set("_payload", JSON.stringify({ alt: fallbackAlt || "Uploaded image" }));
499
+ formData.set("alt", fallbackAlt || "Uploaded image");
500
+ formData.set("file", optimizedFile);
501
+ const response = await fetch("/api/media", {
502
+ body: formData,
503
+ credentials: "include",
504
+ method: "POST"
505
+ });
506
+ if (!response.ok) {
507
+ throw new Error(await parsePayloadErrorMessage(response, "Could not upload image."));
508
+ }
509
+ const uploaded = extractUploadedMedia(await response.json());
510
+ const asset = uploaded ? mediaDocToAsset(uploaded) : null;
511
+ if (asset) {
512
+ uploadedAssets.push(asset);
513
+ }
514
+ }
515
+ if (uploadedAssets.length > 0) {
516
+ editor.AssetManager.add(uploadedAssets);
517
+ }
518
+ };
519
+ function GrapesPageEditor({ adapter, initialData, pageID }) {
520
+ const containerRef = (0, import_react.useRef)(null);
521
+ const editorRef = (0, import_react.useRef)(null);
522
+ const [error, setError] = (0, import_react.useState)("");
523
+ const [loading, setLoading] = (0, import_react.useState)(true);
524
+ const [saving, setSaving] = (0, import_react.useState)(null);
525
+ (0, import_react.useEffect)(() => {
526
+ let active = true;
527
+ const init = async () => {
528
+ if (!containerRef.current || editorRef.current) {
529
+ return;
530
+ }
531
+ try {
532
+ const grapesjs = (await import("grapesjs")).default;
533
+ if (!active || !containerRef.current) {
534
+ return;
535
+ }
536
+ const projectData = normalizeBuilderV2ProjectData(initialData?.projectData, initialData?.title);
537
+ const editor = grapesjs.init({
538
+ assetManager: {
539
+ uploadFile: async (event) => {
540
+ const target = event.target;
541
+ const dataTransfer = "dataTransfer" in event ? event.dataTransfer : null;
542
+ const files = dataTransfer?.files || target?.files;
543
+ if (!files || files.length === 0) {
544
+ return void 0;
545
+ }
546
+ await uploadPayloadMediaAssets(editorRef.current || editor, files).catch((uploadError) => {
547
+ setError(uploadError instanceof Error ? uploadError.message : "Could not upload image.");
548
+ });
549
+ }
550
+ },
551
+ blockManager: {
552
+ appendTo: "#orion-builder-v2-blocks"
553
+ },
554
+ container: containerRef.current,
555
+ deviceManager: {
556
+ devices: [
557
+ { id: "desktop", name: "Desktop", width: "" },
558
+ { id: "tablet", name: "Tablet", width: "768px" },
559
+ { id: "mobile", name: "Mobile", width: "390px" }
560
+ ]
561
+ },
562
+ fromElement: false,
563
+ height: "100%",
564
+ panels: {
565
+ defaults: []
566
+ },
567
+ projectData,
568
+ selectorManager: {
569
+ componentFirst: true
570
+ },
571
+ storageManager: false,
572
+ styleManager: {
573
+ sectors: [
574
+ {
575
+ name: "Layout",
576
+ open: true,
577
+ properties: ["display", "position", "top", "right", "bottom", "left", "width", "height", "min-height", "margin", "padding"]
578
+ },
579
+ {
580
+ name: "Typography",
581
+ open: true,
582
+ properties: ["font-family", "font-size", "font-weight", "line-height", "letter-spacing", "color", "text-align"]
583
+ },
584
+ {
585
+ name: "Decoration",
586
+ open: true,
587
+ properties: ["background-color", "background", "border", "border-radius", "box-shadow", "opacity"]
588
+ },
589
+ {
590
+ name: "Flex",
591
+ open: false,
592
+ properties: ["flex-direction", "justify-content", "align-items", "gap", "flex-wrap"]
593
+ }
594
+ ]
595
+ },
596
+ traitManager: {
597
+ appendTo: "#orion-builder-v2-traits"
598
+ },
599
+ width: "auto"
600
+ });
601
+ editorRef.current = editor;
602
+ registerOrionBuilderV2Blocks(editor);
603
+ registerProjectDynamicComponents(editor, adapter);
604
+ editor.loadProjectData(projectData);
605
+ void loadPayloadMediaAssets(editor);
606
+ editor.on("update", () => {
607
+ postToParent({ dirty: editor.getDirtyCount() > 0, type: "dirty-state" });
608
+ postToParent({
609
+ canRedo: editor.UndoManager.hasRedo(),
610
+ canUndo: editor.UndoManager.hasUndo(),
611
+ type: "history-state"
612
+ });
613
+ });
614
+ setLoading(false);
615
+ } catch (initError) {
616
+ setError(initError instanceof Error ? initError.message : "Could not load the website builder.");
617
+ setLoading(false);
618
+ }
619
+ };
620
+ void init();
621
+ return () => {
622
+ active = false;
623
+ editorRef.current?.destroy();
624
+ editorRef.current = null;
625
+ };
626
+ }, [adapter, initialData?.projectData, initialData?.title]);
627
+ const save = async (status) => {
628
+ const editor = editorRef.current;
629
+ if (!editor || saving) {
630
+ return;
631
+ }
632
+ setSaving(status);
633
+ try {
634
+ const projectData = editor.getProjectData();
635
+ const payload = buildSavePayload(editor, status, projectData);
636
+ const dynamicComponents = parseBuilderV2DynamicComponents(String(payload.compiledHtml || ""));
637
+ const endpoint = status === "draft" ? `/api/pages/${pageID}?draft=true` : `/api/pages/${pageID}`;
638
+ const response = await fetch(endpoint, {
639
+ body: JSON.stringify(
640
+ status === "published" ? {
641
+ _status: "published",
642
+ builderDynamicComponents: dynamicComponents,
643
+ builderMode: "grapes-v2",
644
+ builderProjectData: projectData,
645
+ builderPublishedProjectData: projectData,
646
+ builderValidationIssues: [],
647
+ compiledCss: payload.compiledCss,
648
+ compiledHtml: payload.compiledHtml
649
+ } : {
650
+ _status: "draft",
651
+ builderDynamicComponents: dynamicComponents,
652
+ builderMode: "grapes-v2",
653
+ builderProjectData: projectData,
654
+ builderValidationIssues: [],
655
+ compiledCss: payload.compiledCss,
656
+ compiledHtml: payload.compiledHtml
657
+ }
658
+ ),
659
+ credentials: "include",
660
+ headers: {
661
+ "Content-Type": "application/json"
662
+ },
663
+ method: "PATCH"
664
+ });
665
+ if (!response.ok) {
666
+ if (response.status === 401 || response.status === 403) {
667
+ postToParent({ type: "session-expired" });
668
+ }
669
+ throw new Error(await parsePayloadErrorMessage(response, "Could not save this page."));
670
+ }
671
+ editor.clearDirtyCount();
672
+ postToParent({
673
+ dirty: false,
674
+ type: "dirty-state"
675
+ });
676
+ postToParent({
677
+ message: status === "published" ? "Published." : "Draft saved.",
678
+ ok: true,
679
+ status,
680
+ type: "save-result"
681
+ });
682
+ } catch (saveError) {
683
+ postToParent({
684
+ message: saveError instanceof Error ? saveError.message : "Could not save.",
685
+ ok: false,
686
+ status,
687
+ type: "save-result"
688
+ });
689
+ } finally {
690
+ setSaving(null);
691
+ }
692
+ };
693
+ (0, import_react.useEffect)(() => {
694
+ const onMessage = (event) => {
695
+ const data = event.data;
696
+ const editor = editorRef.current;
697
+ if (!data || data.source !== "payload-visual-builder-parent" || !editor) {
698
+ return;
699
+ }
700
+ if (data.type === "dirty-check-request") {
701
+ postToParent({ dirty: editor.getDirtyCount() > 0, type: "dirty-state" });
702
+ postToParent({
703
+ canRedo: editor.UndoManager.hasRedo(),
704
+ canUndo: editor.UndoManager.hasUndo(),
705
+ type: "history-state"
706
+ });
707
+ return;
708
+ }
709
+ if (data.type === "history-check-request") {
710
+ postToParent({
711
+ canRedo: editor.UndoManager.hasRedo(),
712
+ canUndo: editor.UndoManager.hasUndo(),
713
+ type: "history-state"
714
+ });
715
+ return;
716
+ }
717
+ if (data.type === "undo") {
718
+ editor.UndoManager.undo();
719
+ return;
720
+ }
721
+ if (data.type === "redo") {
722
+ editor.UndoManager.redo();
723
+ return;
724
+ }
725
+ if (data.type === "save" && (data.status === "draft" || data.status === "published")) {
726
+ void save(data.status);
727
+ }
728
+ };
729
+ window.addEventListener("message", onMessage);
730
+ return () => window.removeEventListener("message", onMessage);
731
+ }, [saving]);
732
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "orion-builder-v2-editor", children: [
733
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("aside", { className: "orion-builder-v2-sidebar", children: [
734
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "orion-builder-v2-panel", children: [
735
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { children: "Blocks" }),
736
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { id: "orion-builder-v2-blocks" })
737
+ ] }),
738
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "orion-builder-v2-panel", children: [
739
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { children: "Settings" }),
740
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { id: "orion-builder-v2-traits" })
741
+ ] })
742
+ ] }),
743
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("main", { className: "orion-builder-v2-main", children: [
744
+ loading ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "orion-builder-v2-status", children: "Loading builder..." }) : null,
745
+ error ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "orion-builder-v2-error", children: error }) : null,
746
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "orion-builder-v2-canvas", ref: containerRef })
747
+ ] })
748
+ ] });
749
+ }
750
+ // Annotate the CommonJS export names for ESM import in node:
751
+ 0 && (module.exports = {
752
+ GrapesPageEditor
753
+ });