@peak-ai/canvas 1.4.27 → 1.4.28-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/GrapesjsCanvas.js CHANGED
@@ -1,11 +1,14 @@
1
1
  import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _extends from"@babel/runtime/helpers/extends";import _regeneratorRuntime from"@babel/runtime/regenerator";/* eslint-disable @typescript-eslint/no-explicit-any */import React,{useEffect,useRef}from"react";// eslint-disable-next-line import/no-named-as-default
2
- import grapesjs from"grapesjs";import"grapesjs/dist/css/grapes.min.css";import tailwind from"grapesjs-tailwind";import{TypesToRegister}from"./constants";import{toKebabCase}from"./helpers";import{tailwindCompiledCss}from"./helpers/css";import{datePickerCss}from"./helpers/date-picker";import{createGrapesjsShadcnGenericPlugin}from"./plugins/grapejs-plugin";import{StyledEditor}from"./index.styles";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";function setComponentProperties(editor,isPreview){function setPropertiesRecursively(comp){comp.set({editable:!isPreview,draggable:!isPreview,droppable:!isPreview&&comp.getName()!=="Shadcn-generic",selectable:!isPreview,hoverable:!isPreview,highlightable:!isPreview,copyable:false,resizable:false,removable:!isPreview,badgable:false});if(!isPreview){comp.set("toolbar",[{attributes:{"class":"fa fa-arrows"},command:"tlb-move"},{attributes:{"class":"fa fa-trash"},command:"tlb-delete"}])}comp.components().forEach(setPropertiesRecursively)}if(isPreview){editor.runCommand("core:preview")}else{editor.stopCommand("core:preview")}var wrapper=editor.getWrapper();wrapper==null||wrapper.find("*").forEach(setPropertiesRecursively)}function convertStyles(stylesArray){return stylesArray.map(function(block){var selectors=Array.isArray(block.selectors)?block.selectors.join(", "):block.selectors;var declarations=Object.entries(block.style).map(function(_ref){var prop=_ref[0],value=_ref[1];return toKebabCase(prop)+": "+value+";"}).join(" ");return selectors+" { "+declarations+" }"}).join("\n")}function createActionCardConfig(action){var icon=action.icon,title=action.title,description=action.description;return{type:"shadcn-generic",componentName:"ActionCard",badgable:false,copyable:false,removable:true,draggable:true,componentProps:{icon:icon,headerContent:title,bodyContent:description}}}function expandActions(node){if(node.type==="shadcn-generic"&&node.componentName==="Actions"){var _node$componentProps;var actions=(_node$componentProps=node.componentProps)==null?void 0:_node$componentProps.actions;if(Array.isArray(actions)&&actions.length>0){return _extends({},node,{type:"div",classes:["dashboard-cards"].concat(node.classes||[]),componentName:undefined,componentProps:undefined,components:actions.map(function(action,i){return _extends({},createActionCardConfig(action),{id:node.id+"--action-card-"+i})})})}return node}if(Array.isArray(node.components)){return _extends({},node,{components:node.components.map(expandActions)})}return node}function setInteracting(renderedComponents,components,inProgress){components.forEach(function(component){var componentId=component.componentId,showLoader=component.showLoader;if(!showLoader){return}var gjsModel=renderedComponents[componentId];if(gjsModel){gjsModel.set("attributes",_extends({},gjsModel.get("attributes"),{interactionApiInProgress:inProgress}))}})}function expandActionsComponent(model,actions){model.components("");actions.forEach(function(action){model.append(createActionCardConfig(action))});model.set("type","div");model.addClass("dashboard-cards");model.set("componentName",undefined);model.set("componentProps",{})}function GrapesjsCanvas(_ref2){var json=_ref2.json,_ref2$mode=_ref2.mode,mode=_ref2$mode===void 0?"preview":_ref2$mode,setEditor=_ref2.setEditor,performInteraction=_ref2.performInteraction,_ref2$newDataNotifier=_ref2.newDataNotifier,newDataNotifier=_ref2$newDataNotifier===void 0?function(){// no op
2
+ import grapesjs from"grapesjs";import"grapesjs/dist/css/grapes.min.css";import tailwind from"grapesjs-tailwind";import{TypesToRegister}from"./constants";import{toKebabCase}from"./helpers";import{tailwindCompiledCss}from"./helpers/css";import{datePickerCss}from"./helpers/date-picker";import{exportEditorToPDF}from"./helpers/pdf-export";import{createGrapesjsShadcnGenericPlugin}from"./plugins/grapejs-plugin";import{StyledEditor}from"./index.styles";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";function setComponentProperties(editor,isPreview){function setPropertiesRecursively(comp){comp.set({editable:!isPreview,draggable:!isPreview,droppable:!isPreview&&comp.getName()!=="Shadcn-generic",selectable:!isPreview,hoverable:!isPreview,highlightable:!isPreview,copyable:false,resizable:false,removable:!isPreview,badgable:false});if(!isPreview){comp.set("toolbar",[{attributes:{"class":"fa fa-arrows"},command:"tlb-move"},{attributes:{"class":"fa fa-trash"},command:"tlb-delete"}])}comp.components().forEach(setPropertiesRecursively)}if(isPreview){editor.runCommand("core:preview")}else{editor.stopCommand("core:preview")}var wrapper=editor.getWrapper();wrapper==null||wrapper.find("*").forEach(setPropertiesRecursively)}function convertStyles(stylesArray){return stylesArray.map(function(block){var selectors=Array.isArray(block.selectors)?block.selectors.join(", "):block.selectors;var declarations=Object.entries(block.style).map(function(_ref){var prop=_ref[0],value=_ref[1];return toKebabCase(prop)+": "+value+";"}).join(" ");return selectors+" { "+declarations+" }"}).join("\n")}function createActionCardConfig(action){var icon=action.icon,title=action.title,description=action.description;return{type:"shadcn-generic",componentName:"ActionCard",badgable:false,copyable:false,removable:true,draggable:true,componentProps:{icon:icon,headerContent:title,bodyContent:description}}}function expandActions(node){if(node.type==="shadcn-generic"&&node.componentName==="Actions"){var _node$componentProps;var actions=(_node$componentProps=node.componentProps)==null?void 0:_node$componentProps.actions;if(Array.isArray(actions)&&actions.length>0){return _extends({},node,{type:"div",classes:["dashboard-cards"].concat(node.classes||[]),componentName:undefined,componentProps:undefined,components:actions.map(function(action,i){return _extends({},createActionCardConfig(action),{id:node.id+"--action-card-"+i})})})}return node}if(Array.isArray(node.components)){return _extends({},node,{components:node.components.map(expandActions)})}return node}function setInteracting(renderedComponents,components,inProgress){components.forEach(function(component){var componentId=component.componentId,showLoader=component.showLoader;if(!showLoader){return}var gjsModel=renderedComponents[componentId];if(gjsModel){gjsModel.set("attributes",_extends({},gjsModel.get("attributes"),{interactionApiInProgress:inProgress}))}})}function expandActionsComponent(model,actions){model.components("");actions.forEach(function(action){model.append(createActionCardConfig(action))});model.set("type","div");model.addClass("dashboard-cards");model.set("componentName",undefined);model.set("componentProps",{})}function GrapesjsCanvas(_ref2){var json=_ref2.json,_ref2$mode=_ref2.mode,mode=_ref2$mode===void 0?"preview":_ref2$mode,setEditor=_ref2.setEditor,performInteraction=_ref2.performInteraction,_ref2$newDataNotifier=_ref2.newDataNotifier,newDataNotifier=_ref2$newDataNotifier===void 0?function(){// no op
3
3
  }:_ref2$newDataNotifier,_ref2$setHasChanged=_ref2.setHasChanged,setHasChanged=_ref2$setHasChanged===void 0?function(){// no op
4
4
  }:_ref2$setHasChanged,isStreaming=_ref2.isStreaming;var editorRef=useRef(null);var editorInstance=useRef(null);var renderedComponents=useRef({});var isStreamingRef=useRef(isStreaming);var isSystemUpdateRef=useRef(false);var lastJsonRef=useRef("");var isEditorAliveRef=useRef(false);useEffect(function(){isStreamingRef.current=isStreaming},[isStreaming]);function notificationHandler(props){if(!props){return true}var componentId=props.componentId,_props$newProps=props.newProps,newProps=_props$newProps===void 0?{}:_props$newProps,_props$newAttributes=props.newAttributes,newAttributes=_props$newAttributes===void 0?{}:_props$newAttributes;var model=renderedComponents.current[componentId];if(!model){return false}// Filter out complex placeholder objects by setting them to null
5
5
  // This ensures placeholder values are properly cleared and don't cause stale data issues
6
6
  var filteredProps=_extends({},newProps);Object.keys(filteredProps).forEach(function(key){var value=filteredProps[key];if(value&&typeof value==="object"&&value.name==="__peak_placeholder"){filteredProps[key]=null}});var parsedNewProps=_extends({},filteredProps);if(filteredProps.pagination){parsedNewProps.pagination=_extends({},model.get("componentProps").pagination||{},filteredProps.pagination)}// Handle Actions component: expand into ActionCards when data arrives via streaming
7
- var isActionsComponent=model.get("componentName")==="Actions";var hasValidActionsData=parsedNewProps.actions&&parsedNewProps.actions!==null&&Array.isArray(parsedNewProps.actions)&&parsedNewProps.actions.length>0;if(isActionsComponent&&hasValidActionsData){var _model$components$at;var isAlreadyExpanded=model.components().length>0&&((_model$components$at=model.components().at(0))==null?void 0:_model$components$at.get("componentName"))==="ActionCard";if(!isAlreadyExpanded){expandActionsComponent(model,parsedNewProps.actions);return true}}model.set("componentProps",_extends({},model.get("componentProps"),parsedNewProps));model.set("attributes",_extends({},model.get("attributes"),newAttributes));return true}useEffect(function(){newDataNotifier(notificationHandler)},[]);function performInteractionWrapper(_x){return _performInteractionWrapper.apply(this,arguments)}function _performInteractionWrapper(){_performInteractionWrapper=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(payload){var _editorInstance$curre;var updatedJson,apiResponse,componentUpdates;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=2;return(_editorInstance$curre=editorInstance.current)==null?void 0:_editorInstance$curre.store();case 2:updatedJson=_context4.sent;setInteracting(renderedComponents.current,payload.affectedComponents,true);_context4.prev=4;_context4.next=7;return performInteraction(_extends({},payload,{json:updatedJson}));case 7:apiResponse=_context4.sent;componentUpdates=apiResponse||{};Object.entries(componentUpdates).forEach(function(_ref6){var key=_ref6[0],value=_ref6[1];var model=renderedComponents.current[key];if(model){model.set("attributes",_extends({},model.get("attributes"),{error:undefined}));model.set("componentProps",_extends({},model.get("componentProps"),value,{error:undefined,isMissing:undefined}))}});return _context4.abrupt("return",componentUpdates);case 13:_context4.prev=13;_context4.t0=_context4["catch"](4);payload.affectedComponents.forEach(function(componentId){var model=renderedComponents.current[componentId];if(model){var errorMessage=_context4.t0 instanceof Error?_context4.t0.message:"Something went wrong. Please try again.";model.set("attributes",_extends({},model.get("attributes"),{error:errorMessage}));model.set("componentProps",_extends({},model.get("componentProps"),{error:errorMessage,isMissing:undefined}))}});throw _context4.t0;case 17:_context4.prev=17;setInteracting(renderedComponents.current,payload.affectedComponents,false);return _context4.finish(17);case 20:case"end":return _context4.stop()}},_callee4,null,[[4,13,17,20]])}));return _performInteractionWrapper.apply(this,arguments)}useEffect(function(){var _json$pages,_json$pages$0$frames;if(!editorRef.current){return function(){// no op
8
- }}if(editorInstance.current){editorInstance.current.destroy();editorInstance.current=null;isEditorAliveRef.current=false}var currentMode=mode;var editor=grapesjs.init({container:editorRef.current,height:"100%",plugins:[tailwind,createGrapesjsShadcnGenericPlugin(currentMode,performInteractionWrapper,renderedComponents.current,setHasChanged)],storageManager:{type:"none"},richTextEditor:{actions:["bold","italic","underline","strikethrough"]},canvas:{customBadgeLabel:function customBadgeLabel(component){var tagName=component.get("tagName");return tagName==="body"?"":tagName||""}}});isEditorAliveRef.current=true;var injectionAttempts=0;function injectStylesEarly(){var _editor$Canvas;var iframeDoc=(_editor$Canvas=editor.Canvas)==null||_editor$Canvas.getDocument==null?void 0:_editor$Canvas.getDocument();if(iframeDoc&&iframeDoc.head){if(!iframeDoc.head.querySelector("[data-grapesjs-styles]")){var style=iframeDoc.createElement("style");var fullCss="\n "+tailwindCompiledCss+"\n "+datePickerCss+"\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");style.setAttribute("data-grapesjs-styles","true");iframeDoc.head.appendChild(style)}}else if(injectionAttempts<50){injectionAttempts+=1;requestAnimationFrame(injectStylesEarly)}}requestAnimationFrame(injectStylesEarly);function checkDirty(){return _checkDirty.apply(this,arguments)}function _checkDirty(){_checkDirty=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var stored,newJson;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:if(!(isStreamingRef.current||isSystemUpdateRef.current)){_context3.next=2;break}return _context3.abrupt("return");case 2:if(!(!isEditorAliveRef.current||!editorInstance.current)){_context3.next=4;break}return _context3.abrupt("return");case 4:stored=null;_context3.prev=5;_context3.next=8;return editorInstance.current.store();case 8:stored=_context3.sent;_context3.next=14;break;case 11:_context3.prev=11;_context3.t0=_context3["catch"](5);return _context3.abrupt("return");case 14:if(stored){_context3.next=16;break}return _context3.abrupt("return");case 16:newJson=JSON.stringify(stored);if(newJson!==lastJsonRef.current){setHasChanged(true);lastJsonRef.current=newJson}case 18:case"end":return _context3.stop()}},_callee3,null,[[5,11]])}));return _checkDirty.apply(this,arguments)}var debouncedCheckDirty=function(){var timeout=null;return function(){if(timeout){clearTimeout(timeout)}timeout=setTimeout(checkDirty,200)}}();["component:add","component:remove","component:update:content","style:update","component:drag:end","rte:change"].forEach(function(evt){editor.on(evt,debouncedCheckDirty)});editor.on("component:update",function(model,prop){if(["attributes","componentProps","content"].includes(prop)){debouncedCheckDirty()}});// Tailwind CSS rules aren't fully added to our component
7
+ var isActionsComponent=model.get("componentName")==="Actions";var hasValidActionsData=parsedNewProps.actions&&parsedNewProps.actions!==null&&Array.isArray(parsedNewProps.actions)&&parsedNewProps.actions.length>0;if(isActionsComponent&&hasValidActionsData){var _model$components$at;var isAlreadyExpanded=model.components().length>0&&((_model$components$at=model.components().at(0))==null?void 0:_model$components$at.get("componentName"))==="ActionCard";if(!isAlreadyExpanded){expandActionsComponent(model,parsedNewProps.actions);return true}}model.set("componentProps",_extends({},model.get("componentProps"),parsedNewProps));model.set("attributes",_extends({},model.get("attributes"),newAttributes));return true}useEffect(function(){newDataNotifier(notificationHandler)},[]);function performInteractionWrapper(_x){return _performInteractionWrapper.apply(this,arguments)}function _performInteractionWrapper(){_performInteractionWrapper=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(payload){var _editorInstance$curre;var updatedJson,apiResponse,componentUpdates;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:_context5.next=2;return(_editorInstance$curre=editorInstance.current)==null?void 0:_editorInstance$curre.store();case 2:updatedJson=_context5.sent;setInteracting(renderedComponents.current,payload.affectedComponents,true);_context5.prev=4;_context5.next=7;return performInteraction(_extends({},payload,{json:updatedJson}));case 7:apiResponse=_context5.sent;componentUpdates=apiResponse||{};Object.entries(componentUpdates).forEach(function(_ref7){var key=_ref7[0],value=_ref7[1];var model=renderedComponents.current[key];if(model){model.set("attributes",_extends({},model.get("attributes"),{error:undefined}));model.set("componentProps",_extends({},model.get("componentProps"),value,{error:undefined,isMissing:undefined}))}});return _context5.abrupt("return",componentUpdates);case 13:_context5.prev=13;_context5.t0=_context5["catch"](4);payload.affectedComponents.forEach(function(componentId){var model=renderedComponents.current[componentId];if(model){var errorMessage=_context5.t0 instanceof Error?_context5.t0.message:"Something went wrong. Please try again.";model.set("attributes",_extends({},model.get("attributes"),{error:errorMessage}));model.set("componentProps",_extends({},model.get("componentProps"),{error:errorMessage,isMissing:undefined}))}});throw _context5.t0;case 17:_context5.prev=17;setInteracting(renderedComponents.current,payload.affectedComponents,false);return _context5.finish(17);case 20:case"end":return _context5.stop()}},_callee5,null,[[4,13,17,20]])}));return _performInteractionWrapper.apply(this,arguments)}useEffect(function(){var _json$pages,_json$pages$0$frames;if(!editorRef.current){return function(){// no op
8
+ }}if(editorInstance.current){editorInstance.current.destroy();editorInstance.current=null;isEditorAliveRef.current=false}var currentMode=mode;var editor=grapesjs.init({container:editorRef.current,height:"100%",plugins:[tailwind,createGrapesjsShadcnGenericPlugin(currentMode,performInteractionWrapper,renderedComponents.current,setHasChanged)],storageManager:{type:"none"},richTextEditor:{actions:["bold","italic","underline","strikethrough"]},canvas:{customBadgeLabel:function customBadgeLabel(component){var tagName=component.get("tagName");return tagName==="body"?"":tagName||""}}});isEditorAliveRef.current=true;var injectionAttempts=0;function injectStylesEarly(){var _editor$Canvas;var iframeDoc=(_editor$Canvas=editor.Canvas)==null||_editor$Canvas.getDocument==null?void 0:_editor$Canvas.getDocument();if(iframeDoc&&iframeDoc.head){if(!iframeDoc.head.querySelector("[data-grapesjs-styles]")){var style=iframeDoc.createElement("style");var fullCss="\n "+tailwindCompiledCss+"\n "+datePickerCss+"\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");style.setAttribute("data-grapesjs-styles","true");iframeDoc.head.appendChild(style)}}else if(injectionAttempts<50){injectionAttempts+=1;requestAnimationFrame(injectStylesEarly)}}requestAnimationFrame(injectStylesEarly);function checkDirty(){return _checkDirty.apply(this,arguments)}function _checkDirty(){_checkDirty=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var stored,newJson;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:if(!(isStreamingRef.current||isSystemUpdateRef.current)){_context4.next=2;break}return _context4.abrupt("return");case 2:if(!(!isEditorAliveRef.current||!editorInstance.current)){_context4.next=4;break}return _context4.abrupt("return");case 4:stored=null;_context4.prev=5;_context4.next=8;return editorInstance.current.store();case 8:stored=_context4.sent;_context4.next=14;break;case 11:_context4.prev=11;_context4.t0=_context4["catch"](5);return _context4.abrupt("return");case 14:if(stored){_context4.next=16;break}return _context4.abrupt("return");case 16:newJson=JSON.stringify(stored);if(newJson!==lastJsonRef.current){setHasChanged(true);lastJsonRef.current=newJson}case 18:case"end":return _context4.stop()}},_callee4,null,[[5,11]])}));return _checkDirty.apply(this,arguments)}var debouncedCheckDirty=function(){var timeout=null;return function(){if(timeout){clearTimeout(timeout)}timeout=setTimeout(checkDirty,200)}}();["component:add","component:remove","component:update:content","style:update","component:drag:end","rte:change"].forEach(function(evt){editor.on(evt,debouncedCheckDirty)});editor.on("component:update",function(model,prop){if(["attributes","componentProps","content"].includes(prop)){debouncedCheckDirty()}});// Tailwind CSS rules aren't fully added to our component
9
9
  // So, adding them from here!
10
- editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var canvasDoc,canvasHead,style,fullCss;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:canvasDoc=editor.Canvas.getDocument();canvasHead=canvasDoc.head;if(!canvasHead.querySelector("[data-grapesjs-styles]")){style=canvasDoc.createElement("style");fullCss="\n "+tailwindCompiledCss+"\n "+datePickerCss+"\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");style.setAttribute("data-grapesjs-styles","true");canvasHead.appendChild(style)}isSystemUpdateRef.current=true;setComponentProperties(editor,mode==="preview");_context.t0=JSON;_context.next=8;return editor.store();case 8:_context.t1=_context.sent;lastJsonRef.current=_context.t0.stringify.call(_context.t0,_context.t1);isSystemUpdateRef.current=false;case 11:case"end":return _context.stop()}},_callee)})));editorInstance.current=editor;if(setEditor){setEditor(editor)}TypesToRegister.forEach(function(_ref4){var type=_ref4.type,tagName=_ref4.tagName;if(!editor.DomComponents.getType(type)){editor.DomComponents.addType(type,{model:{defaults:{tagName:tagName}},view:{}})}});if(json&&((_json$pages=json.pages)==null?void 0:_json$pages.length)>0&&((_json$pages$0$frames=json.pages[0].frames)==null?void 0:_json$pages$0$frames.length)>0){isSystemUpdateRef.current=true;var raw=json.pages[0].frames[0].component;var processed=expandActions(raw);editor.setComponents(processed);var cssText=convertStyles(json.styles||[]);editor.setStyle(cssText);editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.t0=JSON;_context2.next=3;return editor.store();case 3:_context2.t1=_context2.sent;lastJsonRef.current=_context2.t0.stringify.call(_context2.t0,_context2.t1);isSystemUpdateRef.current=false;case 6:case"end":return _context2.stop()}},_callee2)})))}return function cleanup(){editor.destroy();isEditorAliveRef.current=false}},[json,mode]);return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(StyledEditor,{}),/*#__PURE__*/_jsx("div",{ref:editorRef,id:"grapesjs-editor"})]})}export default GrapesjsCanvas;
10
+ editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var canvasDoc,canvasHead,style,fullCss;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:canvasDoc=editor.Canvas.getDocument();canvasHead=canvasDoc.head;if(!canvasHead.querySelector("[data-grapesjs-styles]")){style=canvasDoc.createElement("style");fullCss="\n "+tailwindCompiledCss+"\n "+datePickerCss+"\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");style.setAttribute("data-grapesjs-styles","true");canvasHead.appendChild(style)}isSystemUpdateRef.current=true;setComponentProperties(editor,mode==="preview");_context.t0=JSON;_context.next=8;return editor.store();case 8:_context.t1=_context.sent;lastJsonRef.current=_context.t0.stringify.call(_context.t0,_context.t1);isSystemUpdateRef.current=false;case 11:case"end":return _context.stop()}},_callee)})));editorInstance.current=editor;if(setEditor){setEditor(editor)}// Add PDF download button as a floating button
11
+ var downloadBtnContainer=document.createElement("div");downloadBtnContainer.id="canvas-pdf-download-container";downloadBtnContainer.style.cssText="\n position: fixed;\n top: 10px;\n right: 10px;\n z-index: 10000;\n display: flex;\n align-items: center;\n gap: 8px;\n ";var downloadBtn=document.createElement("button");downloadBtn.innerHTML="\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"></path>\n <polyline points=\"7 10 12 15 17 10\"></polyline>\n <line x1=\"12\" y1=\"15\" x2=\"12\" y2=\"3\"></line>\n </svg>\n <span>Download PDF</span>\n ";downloadBtn.className="canvas-pdf-download-btn";downloadBtn.title="Download canvas as PDF";downloadBtn.style.cssText="\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 16px;\n background: #4f46e5;\n color: white;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n transition: background-color 0.2s;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n ";downloadBtn.addEventListener("mouseenter",function(){downloadBtn.style.background="#4338ca"});downloadBtn.addEventListener("mouseleave",function(){downloadBtn.style.background="#4f46e5"});downloadBtn.addEventListener("click",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.prev=0;downloadBtn.disabled=true;downloadBtn.style.opacity="0.6";downloadBtn.style.cursor="wait";_context2.next=6;return exportEditorToPDF(editor,"canvas-export.pdf");case 6:downloadBtn.disabled=false;downloadBtn.style.opacity="1";downloadBtn.style.cursor="pointer";_context2.next=18;break;case 11:_context2.prev=11;_context2.t0=_context2["catch"](0);// eslint-disable-next-line no-console
12
+ console.error("Failed to export PDF:",_context2.t0);alert("Failed to export PDF. Please try again or check the console for details.");downloadBtn.disabled=false;downloadBtn.style.opacity="1";downloadBtn.style.cursor="pointer";case 18:case"end":return _context2.stop()}},_callee2,null,[[0,11]])})));downloadBtnContainer.appendChild(downloadBtn);document.body.appendChild(downloadBtnContainer);TypesToRegister.forEach(function(_ref5){var type=_ref5.type,tagName=_ref5.tagName;if(!editor.DomComponents.getType(type)){editor.DomComponents.addType(type,{model:{defaults:{tagName:tagName}},view:{}})}});if(json&&((_json$pages=json.pages)==null?void 0:_json$pages.length)>0&&((_json$pages$0$frames=json.pages[0].frames)==null?void 0:_json$pages$0$frames.length)>0){isSystemUpdateRef.current=true;var raw=json.pages[0].frames[0].component;var processed=expandActions(raw);editor.setComponents(processed);var cssText=convertStyles(json.styles||[]);editor.setStyle(cssText);editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.t0=JSON;_context3.next=3;return editor.store();case 3:_context3.t1=_context3.sent;lastJsonRef.current=_context3.t0.stringify.call(_context3.t0,_context3.t1);isSystemUpdateRef.current=false;case 6:case"end":return _context3.stop()}},_callee3)})))}return function cleanup(){// Remove download button on cleanup
13
+ var downloadContainer=document.getElementById("canvas-pdf-download-container");if(downloadContainer){document.body.removeChild(downloadContainer)}editor.destroy();isEditorAliveRef.current=false}},[json,mode]);return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(StyledEditor,{}),/*#__PURE__*/_jsx("div",{ref:editorRef,id:"grapesjs-editor"})]})}export default GrapesjsCanvas;
11
14
  //# sourceMappingURL=GrapesjsCanvas.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","createGrapesjsShadcnGenericPlugin","StyledEditor","jsx","_jsx","jsxs","_jsxs","setComponentProperties","editor","isPreview","setPropertiesRecursively","comp","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","attributes","command","components","forEach","runCommand","stopCommand","wrapper","getWrapper","find","convertStyles","stylesArray","map","block","selectors","Array","isArray","join","declarations","Object","entries","style","_ref","prop","value","createActionCardConfig","action","icon","title","description","type","componentName","componentProps","headerContent","bodyContent","expandActions","node","_node$componentProps","actions","length","_extends","classes","concat","undefined","i","id","setInteracting","renderedComponents","inProgress","component","componentId","showLoader","gjsModel","get","interactionApiInProgress","expandActionsComponent","model","append","addClass","GrapesjsCanvas","_ref2","json","_ref2$mode","mode","setEditor","performInteraction","_ref2$newDataNotifier","newDataNotifier","_ref2$setHasChanged","setHasChanged","isStreaming","editorRef","editorInstance","isStreamingRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","current","notificationHandler","props","_props$newProps","newProps","_props$newAttributes","newAttributes","filteredProps","keys","key","name","parsedNewProps","pagination","isActionsComponent","hasValidActionsData","_model$components$at","isAlreadyExpanded","at","performInteractionWrapper","_x","_performInteractionWrapper","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee4","payload","_editorInstance$curre","updatedJson","apiResponse","componentUpdates","wrap","_callee4$","_context4","prev","next","store","sent","affectedComponents","_ref6","error","isMissing","abrupt","t0","errorMessage","Error","message","finish","stop","_json$pages","_json$pages$0$frames","destroy","currentMode","init","container","height","plugins","storageManager","richTextEditor","canvas","customBadgeLabel","tagName","injectionAttempts","injectStylesEarly","_editor$Canvas","iframeDoc","Canvas","getDocument","head","querySelector","createElement","fullCss","innerHTML","setAttribute","appendChild","requestAnimationFrame","checkDirty","_checkDirty","_callee3","stored","newJson","_callee3$","_context3","JSON","stringify","debouncedCheckDirty","timeout","clearTimeout","setTimeout","evt","on","includes","_callee","canvasDoc","canvasHead","_callee$","_context","t1","call","_ref4","DomComponents","getType","addType","defaults","view","pages","frames","raw","processed","setComponents","cssText","styles","setStyle","_callee2","_callee2$","_context2","cleanup","Fragment","children","ref"],"sources":["../src/GrapesjsCanvas.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { useEffect, useRef } from 'react';\n// eslint-disable-next-line import/no-named-as-default\nimport grapesjs, { Component, Editor } from 'grapesjs';\nimport 'grapesjs/dist/css/grapes.min.css';\nimport tailwind from 'grapesjs-tailwind';\n\nimport { TypesToRegister } from './constants';\nimport { toKebabCase } from './helpers';\nimport { tailwindCompiledCss } from './helpers/css';\nimport { datePickerCss } from './helpers/date-picker';\nimport { createGrapesjsShadcnGenericPlugin } from './plugins/grapejs-plugin';\nimport { StyledEditor } from './index.styles';\n\ntype NotificationHandler = (newData: {\n componentId: string;\n newProps: Record<string, any>;\n newAttributes: Record<string, any>;\n}) => boolean;\n\ntype GrapesjsCanvasProps = {\n json: any;\n mode?: 'editor' | 'preview';\n setEditor: (editor: Editor) => void;\n performInteraction: (payload: Record<string, any>) => Promise<Record<string, any> | undefined>;\n newDataNotifier: (notifHandler: NotificationHandler) => void;\n setHasChanged: (hasChanged: boolean) => void;\n isStreaming: boolean;\n};\n\nfunction setComponentProperties(editor: Editor, isPreview: boolean) {\n function setPropertiesRecursively(comp: Component) {\n comp.set({\n editable: !isPreview,\n draggable: !isPreview,\n droppable: !isPreview && comp.getName() !== 'Shadcn-generic',\n selectable: !isPreview,\n hoverable: !isPreview,\n highlightable: !isPreview,\n copyable: false,\n resizable: false,\n removable: !isPreview,\n badgable: false,\n });\n\n if (!isPreview) {\n comp.set('toolbar', [\n { attributes: { class: 'fa fa-arrows' }, command: 'tlb-move' },\n { attributes: { class: 'fa fa-trash' }, command: 'tlb-delete' },\n ]);\n }\n\n comp.components().forEach(setPropertiesRecursively);\n }\n\n if (isPreview) {\n editor.runCommand('core:preview');\n } else {\n editor.stopCommand('core:preview');\n }\n\n const wrapper = editor.getWrapper();\n wrapper?.find('*').forEach(setPropertiesRecursively);\n}\n\nfunction convertStyles(stylesArray: any[]): string {\n return stylesArray\n .map((block) => {\n const selectors = Array.isArray(block.selectors)\n ? block.selectors.join(', ')\n : block.selectors;\n const declarations = Object.entries(block.style)\n .map(([prop, value]) => `${toKebabCase(prop)}: ${value};`)\n .join(' ');\n\n return `${selectors} { ${declarations} }`;\n })\n .join('\\n');\n}\n\nfunction createActionCardConfig(action: any): any {\n const { icon, title, description } = action;\n\n return {\n type: 'shadcn-generic',\n componentName: 'ActionCard',\n badgable: false,\n copyable: false,\n removable: true,\n draggable: true,\n componentProps: {\n icon,\n headerContent: title,\n bodyContent: description,\n },\n };\n}\n\nfunction expandActions(node: any): any {\n if (node.type === 'shadcn-generic' && node.componentName === 'Actions') {\n const actions = node.componentProps?.actions;\n\n if (Array.isArray(actions) && actions.length > 0) {\n return {\n ...node,\n type: 'div',\n classes: ['dashboard-cards', ...(node.classes || [])],\n componentName: undefined,\n componentProps: undefined,\n components: actions.map((action: any, i: number) => ({\n ...createActionCardConfig(action),\n id: `${node.id}--action-card-${i}`,\n })),\n };\n }\n\n return node;\n }\n\n if (Array.isArray(node.components)) {\n return {\n ...node,\n components: node.components.map(expandActions),\n };\n }\n\n return node;\n}\n\nfunction setInteracting(\n renderedComponents: Record<string, Component>,\n components: { componentId: string; showLoader: boolean }[],\n inProgress: boolean,\n) {\n components.forEach((component) => {\n const { componentId, showLoader } = component;\n\n if (!showLoader) {\n return;\n }\n\n const gjsModel = renderedComponents[componentId];\n\n if (gjsModel) {\n gjsModel.set('attributes', {\n ...gjsModel.get('attributes'),\n interactionApiInProgress: inProgress,\n });\n }\n });\n}\n\nfunction expandActionsComponent(model: Component, actions: any[]): void {\n model.components('');\n\n actions.forEach((action: any) => {\n model.append(createActionCardConfig(action));\n });\n\n model.set('type', 'div');\n model.addClass('dashboard-cards');\n model.set('componentName', undefined);\n model.set('componentProps', {});\n}\n\nfunction GrapesjsCanvas({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n newDataNotifier = () => {\n // no op\n },\n setHasChanged = () => {\n // no op\n },\n isStreaming,\n}: GrapesjsCanvasProps) {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<Editor | null>(null);\n const renderedComponents = useRef<Record<string, Component>>({});\n const isStreamingRef = useRef(isStreaming);\n const isSystemUpdateRef = useRef(false);\n const lastJsonRef = useRef<string>('');\n const isEditorAliveRef = useRef(false);\n\n useEffect(() => {\n isStreamingRef.current = isStreaming;\n }, [isStreaming]);\n\n function notificationHandler(\n props: Parameters<NotificationHandler>[0],\n ): ReturnType<NotificationHandler> {\n if (!props) {\n return true;\n }\n\n const { componentId, newProps = {}, newAttributes = {} } = props;\n\n const model = renderedComponents.current[componentId];\n\n if (!model) {\n return false;\n }\n\n // Filter out complex placeholder objects by setting them to null\n // This ensures placeholder values are properly cleared and don't cause stale data issues\n const filteredProps = { ...newProps };\n\n Object.keys(filteredProps).forEach((key) => {\n const value = filteredProps[key];\n\n if (value && typeof value === 'object' && value.name === '__peak_placeholder') {\n filteredProps[key] = null;\n }\n });\n\n const parsedNewProps = {\n ...filteredProps,\n };\n\n if (filteredProps.pagination) {\n parsedNewProps.pagination = {\n ...(model.get('componentProps').pagination || {}),\n ...filteredProps.pagination,\n };\n }\n\n // Handle Actions component: expand into ActionCards when data arrives via streaming\n const isActionsComponent = model.get('componentName') === 'Actions';\n const hasValidActionsData =\n parsedNewProps.actions &&\n parsedNewProps.actions !== null &&\n Array.isArray(parsedNewProps.actions) &&\n parsedNewProps.actions.length > 0;\n\n if (isActionsComponent && hasValidActionsData) {\n const isAlreadyExpanded =\n model.components().length > 0 &&\n model.components().at(0)?.get('componentName') === 'ActionCard';\n\n if (!isAlreadyExpanded) {\n expandActionsComponent(model, parsedNewProps.actions);\n\n return true;\n }\n }\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...parsedNewProps,\n });\n\n model.set('attributes', {\n ...model.get('attributes'),\n ...newAttributes,\n });\n\n return true;\n }\n\n useEffect(() => {\n newDataNotifier(notificationHandler);\n }, []);\n\n async function performInteractionWrapper(payload: Record<string, any>) {\n const updatedJson = await editorInstance.current?.store();\n setInteracting(renderedComponents.current, payload.affectedComponents, true);\n\n try {\n const apiResponse = await performInteraction({\n ...payload,\n json: updatedJson,\n });\n\n const componentUpdates = apiResponse || {};\n\n Object.entries(componentUpdates).forEach(([key, value]) => {\n const model = renderedComponents.current[key];\n\n if (model) {\n model.set('attributes', {\n ...model.get('attributes'),\n error: undefined,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...value,\n error: undefined,\n isMissing: undefined,\n });\n }\n });\n\n return componentUpdates;\n } catch (error) {\n payload.affectedComponents.forEach((componentId: string) => {\n const model = renderedComponents.current[componentId];\n\n if (model) {\n const errorMessage =\n error instanceof Error ? error.message : 'Something went wrong. Please try again.';\n\n model.set('attributes', {\n ...model.get('attributes'),\n error: errorMessage,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n error: errorMessage,\n isMissing: undefined,\n });\n }\n });\n\n throw error;\n } finally {\n setInteracting(renderedComponents.current, payload.affectedComponents, false);\n }\n }\n\n useEffect(() => {\n if (!editorRef.current) {\n return () => {\n // no op\n };\n }\n\n if (editorInstance.current) {\n editorInstance.current.destroy();\n editorInstance.current = null;\n isEditorAliveRef.current = false;\n }\n\n const currentMode = mode;\n\n const editor = grapesjs.init({\n container: editorRef.current,\n height: '100%',\n plugins: [\n tailwind,\n createGrapesjsShadcnGenericPlugin(\n currentMode,\n performInteractionWrapper,\n renderedComponents.current,\n setHasChanged,\n ),\n ],\n storageManager: { type: 'none' },\n richTextEditor: {\n actions: ['bold', 'italic', 'underline', 'strikethrough'],\n },\n canvas: {\n customBadgeLabel: (component) => {\n const tagName = component.get('tagName');\n\n return tagName === 'body' ? '' : tagName || '';\n },\n },\n });\n\n isEditorAliveRef.current = true;\n\n let injectionAttempts = 0;\n\n function injectStylesEarly() {\n const iframeDoc = editor.Canvas?.getDocument?.();\n\n if (iframeDoc && iframeDoc.head) {\n if (!iframeDoc.head.querySelector('[data-grapesjs-styles]')) {\n const style = iframeDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n iframeDoc.head.appendChild(style);\n }\n } else if (injectionAttempts < 50) {\n injectionAttempts += 1;\n requestAnimationFrame(injectStylesEarly);\n }\n }\n\n requestAnimationFrame(injectStylesEarly);\n\n async function checkDirty() {\n if (isStreamingRef.current || isSystemUpdateRef.current) {\n return;\n }\n\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n let stored = null;\n\n try {\n stored = await editorInstance.current.store();\n } catch (err) {\n return;\n }\n\n if (!stored) {\n return;\n }\n\n const newJson = JSON.stringify(stored);\n\n if (newJson !== lastJsonRef.current) {\n setHasChanged(true);\n lastJsonRef.current = newJson;\n }\n }\n\n const debouncedCheckDirty = (() => {\n let timeout: NodeJS.Timeout | null = null;\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(checkDirty, 200);\n };\n })();\n\n [\n 'component:add',\n 'component:remove',\n 'component:update:content',\n 'style:update',\n 'component:drag:end',\n 'rte:change',\n ].forEach((evt) => {\n editor.on(evt, debouncedCheckDirty);\n });\n\n editor.on('component:update', (model, prop) => {\n if (['attributes', 'componentProps', 'content'].includes(prop)) {\n debouncedCheckDirty();\n }\n });\n\n // Tailwind CSS rules aren't fully added to our component\n // So, adding them from here!\n editor.on('load', async () => {\n const canvasDoc = editor.Canvas.getDocument();\n const canvasHead = canvasDoc.head;\n\n if (!canvasHead.querySelector('[data-grapesjs-styles]')) {\n const style = canvasDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n canvasHead.appendChild(style);\n }\n\n isSystemUpdateRef.current = true;\n setComponentProperties(editor, mode === 'preview');\n lastJsonRef.current = JSON.stringify(await editor.store());\n isSystemUpdateRef.current = false;\n });\n\n editorInstance.current = editor;\n\n if (setEditor) {\n setEditor(editor);\n }\n\n TypesToRegister.forEach(({ type, tagName }) => {\n if (!editor.DomComponents.getType(type)) {\n editor.DomComponents.addType(type, {\n model: {\n defaults: { tagName },\n },\n view: {},\n });\n }\n });\n\n if (json && json.pages?.length > 0 && json.pages[0].frames?.length > 0) {\n isSystemUpdateRef.current = true;\n const raw = json.pages[0].frames[0].component;\n const processed = expandActions(raw);\n editor.setComponents(processed);\n\n const cssText = convertStyles(json.styles || []);\n editor.setStyle(cssText);\n\n editor.on('load', async () => {\n lastJsonRef.current = JSON.stringify(await editor.store());\n isSystemUpdateRef.current = false;\n });\n }\n\n return function cleanup() {\n editor.destroy();\n isEditorAliveRef.current = false;\n };\n }, [json, mode]);\n\n return (\n <React.Fragment>\n <StyledEditor />\n <div ref={editorRef} id=\"grapesjs-editor\" />\n </React.Fragment>\n );\n}\n\nexport default GrapesjsCanvas;\n"],"mappings":"wLAAA,uDACA,MAAO,CAAAA,KAAK,EAAIC,SAAS,CAAEC,MAAM,KAAQ,OAAO,CAChD;AACA,MAAO,CAAAC,QAAQ,KAA6B,UAAU,CACtD,MAAO,kCAAkC,CACzC,MAAO,CAAAC,QAAQ,KAAM,mBAAmB,CAExC,OAASC,eAAe,KAAQ,aAAa,CAC7C,OAASC,WAAW,KAAQ,WAAW,CACvC,OAASC,mBAAmB,KAAQ,eAAe,CACnD,OAASC,aAAa,KAAQ,uBAAuB,CACrD,OAASC,iCAAiC,KAAQ,0BAA0B,CAC5E,OAASC,YAAY,KAAQ,gBAAgB,CAAC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAkB9C,QAAS,CAAAC,sBAAsBA,CAACC,MAAc,CAAEC,SAAkB,CAAE,CAClE,QAAS,CAAAC,wBAAwBA,CAACC,IAAe,CAAE,CACjDA,IAAI,CAACC,GAAG,CAAC,CACPC,QAAQ,CAAE,CAACJ,SAAS,CACpBK,SAAS,CAAE,CAACL,SAAS,CACrBM,SAAS,CAAE,CAACN,SAAS,EAAIE,IAAI,CAACK,OAAO,CAAC,CAAC,GAAK,gBAAgB,CAC5DC,UAAU,CAAE,CAACR,SAAS,CACtBS,SAAS,CAAE,CAACT,SAAS,CACrBU,aAAa,CAAE,CAACV,SAAS,CACzBW,QAAQ,CAAE,KAAK,CACfC,SAAS,CAAE,KAAK,CAChBC,SAAS,CAAE,CAACb,SAAS,CACrBc,QAAQ,CAAE,KACZ,CAAC,CAAC,CAEF,GAAI,CAACd,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,SAAS,CAAAc,IAAA,CAAAiB,SAAA,CAAAxE,EAAA,CAAAwE,SAAA,CAAAlB,EAAA,EACpCrG,iBAAiB,CAACG,OAAO,CAAG,KAAK,CAAC,wBAAAoH,SAAA,CAAAnE,IAAA,KAAAiE,QAAA,EACnC,GACH,CAEA,MAAO,SAAS,CAAAG,OAAOA,CAAA,CAAG,CACxBjN,MAAM,CAACgJ,OAAO,CAAC,CAAC,CAChBrD,gBAAgB,CAACC,OAAO,CAAG,KAC7B,CACF,CAAC,CAAE,CAAChB,IAAI,CAAEE,IAAI,CAAC,CAAC,CAEhB,mBACEhF,KAAA,CAACd,KAAK,CAACkO,QAAQ,EAAAC,QAAA,eACbvN,IAAA,CAACF,YAAY,GAAE,CAAC,cAChBE,IAAA,QAAKwN,GAAG,CAAE9H,SAAU,CAAC1B,EAAE,CAAC,iBAAiB,CAAE,CAAC,EAC9B,CAEpB,CAEA,cAAe,CAAAc,cAAc","ignoreList":[]}
1
+ {"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","exportEditorToPDF","createGrapesjsShadcnGenericPlugin","StyledEditor","jsx","_jsx","jsxs","_jsxs","setComponentProperties","editor","isPreview","setPropertiesRecursively","comp","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","attributes","command","components","forEach","runCommand","stopCommand","wrapper","getWrapper","find","convertStyles","stylesArray","map","block","selectors","Array","isArray","join","declarations","Object","entries","style","_ref","prop","value","createActionCardConfig","action","icon","title","description","type","componentName","componentProps","headerContent","bodyContent","expandActions","node","_node$componentProps","actions","length","_extends","classes","concat","undefined","i","id","setInteracting","renderedComponents","inProgress","component","componentId","showLoader","gjsModel","get","interactionApiInProgress","expandActionsComponent","model","append","addClass","GrapesjsCanvas","_ref2","json","_ref2$mode","mode","setEditor","performInteraction","_ref2$newDataNotifier","newDataNotifier","_ref2$setHasChanged","setHasChanged","isStreaming","editorRef","editorInstance","isStreamingRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","current","notificationHandler","props","_props$newProps","newProps","_props$newAttributes","newAttributes","filteredProps","keys","key","name","parsedNewProps","pagination","isActionsComponent","hasValidActionsData","_model$components$at","isAlreadyExpanded","at","performInteractionWrapper","_x","_performInteractionWrapper","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee5","payload","_editorInstance$curre","updatedJson","apiResponse","componentUpdates","wrap","_callee5$","_context5","prev","next","store","sent","affectedComponents","_ref7","error","isMissing","abrupt","t0","errorMessage","Error","message","finish","stop","_json$pages","_json$pages$0$frames","destroy","currentMode","init","container","height","plugins","storageManager","richTextEditor","canvas","customBadgeLabel","tagName","injectionAttempts","injectStylesEarly","_editor$Canvas","iframeDoc","Canvas","getDocument","head","querySelector","createElement","fullCss","innerHTML","setAttribute","appendChild","requestAnimationFrame","checkDirty","_checkDirty","_callee4","stored","newJson","_callee4$","_context4","JSON","stringify","debouncedCheckDirty","timeout","clearTimeout","setTimeout","evt","on","includes","_callee","canvasDoc","canvasHead","_callee$","_context","t1","call","downloadBtnContainer","document","cssText","downloadBtn","className","addEventListener","background","_callee2","_callee2$","_context2","disabled","opacity","cursor","console","alert","body","_ref5","DomComponents","getType","addType","defaults","view","pages","frames","raw","processed","setComponents","styles","setStyle","_callee3","_callee3$","_context3","cleanup","downloadContainer","getElementById","removeChild","Fragment","children","ref"],"sources":["../src/GrapesjsCanvas.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { useEffect, useRef } from 'react';\n// eslint-disable-next-line import/no-named-as-default\nimport grapesjs, { Component, Editor } from 'grapesjs';\nimport 'grapesjs/dist/css/grapes.min.css';\nimport tailwind from 'grapesjs-tailwind';\n\nimport { TypesToRegister } from './constants';\nimport { toKebabCase } from './helpers';\nimport { tailwindCompiledCss } from './helpers/css';\nimport { datePickerCss } from './helpers/date-picker';\nimport { exportEditorToPDF } from './helpers/pdf-export';\nimport { createGrapesjsShadcnGenericPlugin } from './plugins/grapejs-plugin';\nimport { StyledEditor } from './index.styles';\n\ntype NotificationHandler = (newData: {\n componentId: string;\n newProps: Record<string, any>;\n newAttributes: Record<string, any>;\n}) => boolean;\n\ntype GrapesjsCanvasProps = {\n json: any;\n mode?: 'editor' | 'preview';\n setEditor: (editor: Editor) => void;\n performInteraction: (payload: Record<string, any>) => Promise<Record<string, any> | undefined>;\n newDataNotifier: (notifHandler: NotificationHandler) => void;\n setHasChanged: (hasChanged: boolean) => void;\n isStreaming: boolean;\n};\n\nfunction setComponentProperties(editor: Editor, isPreview: boolean) {\n function setPropertiesRecursively(comp: Component) {\n comp.set({\n editable: !isPreview,\n draggable: !isPreview,\n droppable: !isPreview && comp.getName() !== 'Shadcn-generic',\n selectable: !isPreview,\n hoverable: !isPreview,\n highlightable: !isPreview,\n copyable: false,\n resizable: false,\n removable: !isPreview,\n badgable: false,\n });\n\n if (!isPreview) {\n comp.set('toolbar', [\n { attributes: { class: 'fa fa-arrows' }, command: 'tlb-move' },\n { attributes: { class: 'fa fa-trash' }, command: 'tlb-delete' },\n ]);\n }\n\n comp.components().forEach(setPropertiesRecursively);\n }\n\n if (isPreview) {\n editor.runCommand('core:preview');\n } else {\n editor.stopCommand('core:preview');\n }\n\n const wrapper = editor.getWrapper();\n wrapper?.find('*').forEach(setPropertiesRecursively);\n}\n\nfunction convertStyles(stylesArray: any[]): string {\n return stylesArray\n .map((block) => {\n const selectors = Array.isArray(block.selectors)\n ? block.selectors.join(', ')\n : block.selectors;\n const declarations = Object.entries(block.style)\n .map(([prop, value]) => `${toKebabCase(prop)}: ${value};`)\n .join(' ');\n\n return `${selectors} { ${declarations} }`;\n })\n .join('\\n');\n}\n\nfunction createActionCardConfig(action: any): any {\n const { icon, title, description } = action;\n\n return {\n type: 'shadcn-generic',\n componentName: 'ActionCard',\n badgable: false,\n copyable: false,\n removable: true,\n draggable: true,\n componentProps: {\n icon,\n headerContent: title,\n bodyContent: description,\n },\n };\n}\n\nfunction expandActions(node: any): any {\n if (node.type === 'shadcn-generic' && node.componentName === 'Actions') {\n const actions = node.componentProps?.actions;\n\n if (Array.isArray(actions) && actions.length > 0) {\n return {\n ...node,\n type: 'div',\n classes: ['dashboard-cards', ...(node.classes || [])],\n componentName: undefined,\n componentProps: undefined,\n components: actions.map((action: any, i: number) => ({\n ...createActionCardConfig(action),\n id: `${node.id}--action-card-${i}`,\n })),\n };\n }\n\n return node;\n }\n\n if (Array.isArray(node.components)) {\n return {\n ...node,\n components: node.components.map(expandActions),\n };\n }\n\n return node;\n}\n\nfunction setInteracting(\n renderedComponents: Record<string, Component>,\n components: { componentId: string; showLoader: boolean }[],\n inProgress: boolean,\n) {\n components.forEach((component) => {\n const { componentId, showLoader } = component;\n\n if (!showLoader) {\n return;\n }\n\n const gjsModel = renderedComponents[componentId];\n\n if (gjsModel) {\n gjsModel.set('attributes', {\n ...gjsModel.get('attributes'),\n interactionApiInProgress: inProgress,\n });\n }\n });\n}\n\nfunction expandActionsComponent(model: Component, actions: any[]): void {\n model.components('');\n\n actions.forEach((action: any) => {\n model.append(createActionCardConfig(action));\n });\n\n model.set('type', 'div');\n model.addClass('dashboard-cards');\n model.set('componentName', undefined);\n model.set('componentProps', {});\n}\n\nfunction GrapesjsCanvas({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n newDataNotifier = () => {\n // no op\n },\n setHasChanged = () => {\n // no op\n },\n isStreaming,\n}: GrapesjsCanvasProps) {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<Editor | null>(null);\n const renderedComponents = useRef<Record<string, Component>>({});\n const isStreamingRef = useRef(isStreaming);\n const isSystemUpdateRef = useRef(false);\n const lastJsonRef = useRef<string>('');\n const isEditorAliveRef = useRef(false);\n\n useEffect(() => {\n isStreamingRef.current = isStreaming;\n }, [isStreaming]);\n\n function notificationHandler(\n props: Parameters<NotificationHandler>[0],\n ): ReturnType<NotificationHandler> {\n if (!props) {\n return true;\n }\n\n const { componentId, newProps = {}, newAttributes = {} } = props;\n\n const model = renderedComponents.current[componentId];\n\n if (!model) {\n return false;\n }\n\n // Filter out complex placeholder objects by setting them to null\n // This ensures placeholder values are properly cleared and don't cause stale data issues\n const filteredProps = { ...newProps };\n\n Object.keys(filteredProps).forEach((key) => {\n const value = filteredProps[key];\n\n if (value && typeof value === 'object' && value.name === '__peak_placeholder') {\n filteredProps[key] = null;\n }\n });\n\n const parsedNewProps = {\n ...filteredProps,\n };\n\n if (filteredProps.pagination) {\n parsedNewProps.pagination = {\n ...(model.get('componentProps').pagination || {}),\n ...filteredProps.pagination,\n };\n }\n\n // Handle Actions component: expand into ActionCards when data arrives via streaming\n const isActionsComponent = model.get('componentName') === 'Actions';\n const hasValidActionsData =\n parsedNewProps.actions &&\n parsedNewProps.actions !== null &&\n Array.isArray(parsedNewProps.actions) &&\n parsedNewProps.actions.length > 0;\n\n if (isActionsComponent && hasValidActionsData) {\n const isAlreadyExpanded =\n model.components().length > 0 &&\n model.components().at(0)?.get('componentName') === 'ActionCard';\n\n if (!isAlreadyExpanded) {\n expandActionsComponent(model, parsedNewProps.actions);\n\n return true;\n }\n }\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...parsedNewProps,\n });\n\n model.set('attributes', {\n ...model.get('attributes'),\n ...newAttributes,\n });\n\n return true;\n }\n\n useEffect(() => {\n newDataNotifier(notificationHandler);\n }, []);\n\n async function performInteractionWrapper(payload: Record<string, any>) {\n const updatedJson = await editorInstance.current?.store();\n setInteracting(renderedComponents.current, payload.affectedComponents, true);\n\n try {\n const apiResponse = await performInteraction({\n ...payload,\n json: updatedJson,\n });\n\n const componentUpdates = apiResponse || {};\n\n Object.entries(componentUpdates).forEach(([key, value]) => {\n const model = renderedComponents.current[key];\n\n if (model) {\n model.set('attributes', {\n ...model.get('attributes'),\n error: undefined,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...value,\n error: undefined,\n isMissing: undefined,\n });\n }\n });\n\n return componentUpdates;\n } catch (error) {\n payload.affectedComponents.forEach((componentId: string) => {\n const model = renderedComponents.current[componentId];\n\n if (model) {\n const errorMessage =\n error instanceof Error ? error.message : 'Something went wrong. Please try again.';\n\n model.set('attributes', {\n ...model.get('attributes'),\n error: errorMessage,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n error: errorMessage,\n isMissing: undefined,\n });\n }\n });\n\n throw error;\n } finally {\n setInteracting(renderedComponents.current, payload.affectedComponents, false);\n }\n }\n\n useEffect(() => {\n if (!editorRef.current) {\n return () => {\n // no op\n };\n }\n\n if (editorInstance.current) {\n editorInstance.current.destroy();\n editorInstance.current = null;\n isEditorAliveRef.current = false;\n }\n\n const currentMode = mode;\n\n const editor = grapesjs.init({\n container: editorRef.current,\n height: '100%',\n plugins: [\n tailwind,\n createGrapesjsShadcnGenericPlugin(\n currentMode,\n performInteractionWrapper,\n renderedComponents.current,\n setHasChanged,\n ),\n ],\n storageManager: { type: 'none' },\n richTextEditor: {\n actions: ['bold', 'italic', 'underline', 'strikethrough'],\n },\n canvas: {\n customBadgeLabel: (component) => {\n const tagName = component.get('tagName');\n\n return tagName === 'body' ? '' : tagName || '';\n },\n },\n });\n\n isEditorAliveRef.current = true;\n\n let injectionAttempts = 0;\n\n function injectStylesEarly() {\n const iframeDoc = editor.Canvas?.getDocument?.();\n\n if (iframeDoc && iframeDoc.head) {\n if (!iframeDoc.head.querySelector('[data-grapesjs-styles]')) {\n const style = iframeDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n iframeDoc.head.appendChild(style);\n }\n } else if (injectionAttempts < 50) {\n injectionAttempts += 1;\n requestAnimationFrame(injectStylesEarly);\n }\n }\n\n requestAnimationFrame(injectStylesEarly);\n\n async function checkDirty() {\n if (isStreamingRef.current || isSystemUpdateRef.current) {\n return;\n }\n\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n let stored = null;\n\n try {\n stored = await editorInstance.current.store();\n } catch (err) {\n return;\n }\n\n if (!stored) {\n return;\n }\n\n const newJson = JSON.stringify(stored);\n\n if (newJson !== lastJsonRef.current) {\n setHasChanged(true);\n lastJsonRef.current = newJson;\n }\n }\n\n const debouncedCheckDirty = (() => {\n let timeout: NodeJS.Timeout | null = null;\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(checkDirty, 200);\n };\n })();\n\n [\n 'component:add',\n 'component:remove',\n 'component:update:content',\n 'style:update',\n 'component:drag:end',\n 'rte:change',\n ].forEach((evt) => {\n editor.on(evt, debouncedCheckDirty);\n });\n\n editor.on('component:update', (model, prop) => {\n if (['attributes', 'componentProps', 'content'].includes(prop)) {\n debouncedCheckDirty();\n }\n });\n\n // Tailwind CSS rules aren't fully added to our component\n // So, adding them from here!\n editor.on('load', async () => {\n const canvasDoc = editor.Canvas.getDocument();\n const canvasHead = canvasDoc.head;\n\n if (!canvasHead.querySelector('[data-grapesjs-styles]')) {\n const style = canvasDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n canvasHead.appendChild(style);\n }\n\n isSystemUpdateRef.current = true;\n setComponentProperties(editor, mode === 'preview');\n lastJsonRef.current = JSON.stringify(await editor.store());\n isSystemUpdateRef.current = false;\n });\n\n editorInstance.current = editor;\n\n if (setEditor) {\n setEditor(editor);\n }\n\n // Add PDF download button as a floating button\n const downloadBtnContainer = document.createElement('div');\n downloadBtnContainer.id = 'canvas-pdf-download-container';\n downloadBtnContainer.style.cssText = `\n position: fixed;\n top: 10px;\n right: 10px;\n z-index: 10000;\n display: flex;\n align-items: center;\n gap: 8px;\n `;\n\n const downloadBtn = document.createElement('button');\n downloadBtn.innerHTML = `\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"></path>\n <polyline points=\"7 10 12 15 17 10\"></polyline>\n <line x1=\"12\" y1=\"15\" x2=\"12\" y2=\"3\"></line>\n </svg>\n <span>Download PDF</span>\n `;\n downloadBtn.className = 'canvas-pdf-download-btn';\n downloadBtn.title = 'Download canvas as PDF';\n downloadBtn.style.cssText = `\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 16px;\n background: #4f46e5;\n color: white;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n transition: background-color 0.2s;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n `;\n \n downloadBtn.addEventListener('mouseenter', () => {\n downloadBtn.style.background = '#4338ca';\n });\n \n downloadBtn.addEventListener('mouseleave', () => {\n downloadBtn.style.background = '#4f46e5';\n });\n\n downloadBtn.addEventListener('click', async () => {\n try {\n downloadBtn.disabled = true;\n downloadBtn.style.opacity = '0.6';\n downloadBtn.style.cursor = 'wait';\n \n await exportEditorToPDF(editor, 'canvas-export.pdf');\n \n downloadBtn.disabled = false;\n downloadBtn.style.opacity = '1';\n downloadBtn.style.cursor = 'pointer';\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to export PDF:', error);\n alert('Failed to export PDF. Please try again or check the console for details.');\n \n downloadBtn.disabled = false;\n downloadBtn.style.opacity = '1';\n downloadBtn.style.cursor = 'pointer';\n }\n });\n\n downloadBtnContainer.appendChild(downloadBtn);\n document.body.appendChild(downloadBtnContainer);\n\n TypesToRegister.forEach(({ type, tagName }) => {\n if (!editor.DomComponents.getType(type)) {\n editor.DomComponents.addType(type, {\n model: {\n defaults: { tagName },\n },\n view: {},\n });\n }\n });\n\n if (json && json.pages?.length > 0 && json.pages[0].frames?.length > 0) {\n isSystemUpdateRef.current = true;\n const raw = json.pages[0].frames[0].component;\n const processed = expandActions(raw);\n editor.setComponents(processed);\n\n const cssText = convertStyles(json.styles || []);\n editor.setStyle(cssText);\n\n editor.on('load', async () => {\n lastJsonRef.current = JSON.stringify(await editor.store());\n isSystemUpdateRef.current = false;\n });\n }\n\n return function cleanup() {\n // Remove download button on cleanup\n const downloadContainer = document.getElementById('canvas-pdf-download-container');\n\n if (downloadContainer) {\n document.body.removeChild(downloadContainer);\n }\n\n editor.destroy();\n isEditorAliveRef.current = false;\n };\n }, [json, mode]);\n\n return (\n <React.Fragment>\n <StyledEditor />\n <div ref={editorRef} id=\"grapesjs-editor\" />\n </React.Fragment>\n );\n}\n\nexport default GrapesjsCanvas;\n"],"mappings":"wLAAA,uDACA,MAAO,CAAAA,KAAK,EAAIC,SAAS,CAAEC,MAAM,KAAQ,OAAO,CAChD;AACA,MAAO,CAAAC,QAAQ,KAA6B,UAAU,CACtD,MAAO,kCAAkC,CACzC,MAAO,CAAAC,QAAQ,KAAM,mBAAmB,CAExC,OAASC,eAAe,KAAQ,aAAa,CAC7C,OAASC,WAAW,KAAQ,WAAW,CACvC,OAASC,mBAAmB,KAAQ,eAAe,CACnD,OAASC,aAAa,KAAQ,uBAAuB,CACrD,OAASC,iBAAiB,KAAQ,sBAAsB,CACxD,OAASC,iCAAiC,KAAQ,0BAA0B,CAC5E,OAASC,YAAY,KAAQ,gBAAgB,CAAC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAkB9C,QAAS,CAAAC,sBAAsBA,CAACC,MAAc,CAAEC,SAAkB,CAAE,CAClE,QAAS,CAAAC,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AAG,OAAOA,CAAA,CAAG,CACxB;AACA,GAAM,CAAAC,iBAAiB,CAAGhC,QAAQ,CAACiC,cAAc,CAAC,+BAA+B,CAAC,CAElF,GAAID,iBAAiB,CAAE,CACrBhC,QAAQ,CAACc,IAAI,CAACoB,WAAW,CAACF,iBAAiB,CAC7C,CAEAjO,MAAM,CAACgJ,OAAO,CAAC,CAAC,CAChBrD,gBAAgB,CAACC,OAAO,CAAG,KAC7B,CACF,CAAC,CAAE,CAAChB,IAAI,CAAEE,IAAI,CAAC,CAAC,CAEhB,mBACEhF,KAAA,CAACf,KAAK,CAACqP,QAAQ,EAAAC,QAAA,eACbzO,IAAA,CAACF,YAAY,GAAE,CAAC,cAChBE,IAAA,QAAK0O,GAAG,CAAEhJ,SAAU,CAAC1B,EAAE,CAAC,iBAAiB,CAAE,CAAC,EAC9B,CAEpB,CAEA,cAAe,CAAAc,cAAc","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ import { Editor } from 'grapesjs';
2
+ export declare function exportEditorToPDF(editor: Editor, filename?: string): Promise<void>;
@@ -0,0 +1,25 @@
1
+ import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _regeneratorRuntime from"@babel/runtime/regenerator";/* eslint-disable @typescript-eslint/no-explicit-any *//**
2
+ * Loads html2pdf.js from CDN if not already available
3
+ */function loadHtml2Pdf(){return new Promise(function(resolve,reject){if(typeof window.html2pdf!=="undefined"){resolve();return}// Load html2pdf.js from CDN
4
+ var script=document.createElement("script");script.src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js";script.onload=function(){return resolve()};script.onerror=function(){return reject(new Error("Failed to load html2pdf.js"))};document.head.appendChild(script)})}/**
5
+ * Exports the GrapesJS editor content as PDF
6
+ * @param editor - The GrapesJS editor instance
7
+ * @param filename - Optional filename for the PDF (default: 'canvas-export.pdf')
8
+ */export function exportEditorToPDF(_x,_x2){return _exportEditorToPDF.apply(this,arguments)}function _exportEditorToPDF(){_exportEditorToPDF=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(editor,filename){var canvasDoc,canvasBody,canvasWindow,clonedBody,printContainer,canvasStyles,styleContainer,opt,printWindow,allStyles;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(filename===void 0){filename="canvas-export.pdf"}_context.prev=1;// Get the canvas iframe document
9
+ canvasDoc=editor.Canvas.getDocument();canvasBody=canvasDoc.body;canvasWindow=editor.Canvas.getWindow();if(!(!canvasBody||!canvasWindow)){_context.next=7;break}throw new Error("Unable to access canvas content");case 7:// Create a clone of the body to avoid modifying the original
10
+ clonedBody=canvasBody.cloneNode(true);// Create a temporary container for PDF generation
11
+ printContainer=document.createElement("div");printContainer.style.position="absolute";printContainer.style.left="-9999px";printContainer.style.width="210mm";// A4 width
12
+ printContainer.style.background="white";printContainer.style.padding="20mm";printContainer.style.fontSize="12pt";document.body.appendChild(printContainer);// Copy styles from the canvas
13
+ canvasStyles=canvasDoc.querySelectorAll("style, link[rel=\"stylesheet\"]");styleContainer=document.createElement("div");canvasStyles.forEach(function(style){var clonedStyle=style.cloneNode(true);styleContainer.appendChild(clonedStyle)});// Note: We don't need to inline computed styles here as html2pdf.js/html2canvas
14
+ // will handle rendering, and the browser print fallback will use the stylesheets
15
+ // Append cloned content to print container
16
+ printContainer.appendChild(styleContainer);printContainer.appendChild(clonedBody);// Wait for fonts and images to load
17
+ _context.next=23;return new Promise(function(resolve){setTimeout(resolve,500)});case 23:_context.prev=23;_context.next=26;return loadHtml2Pdf();case 26:opt={filename:filename,html2canvas:{letterRendering:true,logging:false,scale:2,useCORS:true,windowHeight:canvasWindow.innerHeight,windowWidth:canvasWindow.innerWidth},image:{quality:0.98,type:"jpeg"},jsPDF:{format:"a4",orientation:"portrait",unit:"mm"},margin:[10,10,10,10]};_context.next=29;return window.html2pdf().set(opt).from(printContainer).save();case 29:_context.next=42;break;case 31:_context.prev=31;_context.t0=_context["catch"](23);// Fallback: Use browser print functionality
18
+ // eslint-disable-next-line no-console
19
+ console.warn("html2pdf.js not available, using browser print fallback:",_context.t0);printWindow=window.open("","_blank");if(printWindow){_context.next=37;break}throw new Error("Popup blocked. Please allow popups for this site.");case 37:// Collect all styles from the canvas
20
+ allStyles=Array.from(canvasDoc.querySelectorAll("style")).map(function(style){return style.textContent}).join("\n");printWindow.document.write("\n <!DOCTYPE html>\n <html>\n <head>\n <title>"+filename.replace(".pdf","")+"</title>\n <meta charset=\"utf-8\">\n <style>\n @media print {\n @page {\n margin: 0;\n size: A4;\n }\n body {\n margin: 0;\n padding: 20mm;\n }\n }\n body {\n margin: 0;\n padding: 20mm;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: white;\n }\n "+allStyles+"\n </style>\n </head>\n <body>\n "+clonedBody.innerHTML+"\n </body>\n </html>\n ");printWindow.document.close();_context.next=42;return new Promise(function(resolve){printWindow.onload=function(){setTimeout(function(){printWindow.print();// Close window after print dialog
21
+ setTimeout(function(){printWindow.close();resolve()},1000)},500)};// Fallback if onload doesn't fire
22
+ setTimeout(function(){if(printWindow.document.readyState==="complete"){printWindow.print();setTimeout(function(){printWindow.close();resolve()},1000)}},1000)});case 42:// Cleanup
23
+ if(printContainer.parentNode){document.body.removeChild(printContainer)}_context.next=49;break;case 45:_context.prev=45;_context.t1=_context["catch"](1);// eslint-disable-next-line no-console
24
+ console.error("Error exporting to PDF:",_context.t1);throw _context.t1;case 49:case"end":return _context.stop()}},_callee,null,[[1,45],[23,31]])}));return _exportEditorToPDF.apply(this,arguments)}
25
+ //# sourceMappingURL=pdf-export.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pdf-export.js","names":["loadHtml2Pdf","Promise","resolve","reject","window","html2pdf","script","document","createElement","src","onload","onerror","Error","head","appendChild","exportEditorToPDF","_x","_x2","_exportEditorToPDF","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","editor","filename","canvasDoc","canvasBody","canvasWindow","clonedBody","printContainer","canvasStyles","styleContainer","opt","printWindow","allStyles","wrap","_callee$","_context","prev","next","Canvas","getDocument","body","getWindow","cloneNode","style","position","left","width","background","padding","fontSize","querySelectorAll","forEach","clonedStyle","setTimeout","html2canvas","letterRendering","logging","scale","useCORS","windowHeight","innerHeight","windowWidth","innerWidth","image","quality","type","jsPDF","format","orientation","unit","margin","set","from","save","t0","console","warn","open","Array","map","textContent","join","write","replace","innerHTML","close","print","readyState","parentNode","removeChild","t1","error","stop"],"sources":["../../src/helpers/pdf-export.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Editor } from 'grapesjs';\n\n/**\n * Loads html2pdf.js from CDN if not already available\n */\nfunction loadHtml2Pdf(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (typeof (window as any).html2pdf !== 'undefined') {\n resolve();\n\n return;\n }\n\n // Load html2pdf.js from CDN\n const script = document.createElement('script');\n script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js';\n script.onload = () => resolve();\n script.onerror = () => reject(new Error('Failed to load html2pdf.js'));\n document.head.appendChild(script);\n });\n}\n\n/**\n * Exports the GrapesJS editor content as PDF\n * @param editor - The GrapesJS editor instance\n * @param filename - Optional filename for the PDF (default: 'canvas-export.pdf')\n */\nexport async function exportEditorToPDF(\n editor: Editor,\n filename = 'canvas-export.pdf',\n): Promise<void> {\n try {\n // Get the canvas iframe document\n const canvasDoc = editor.Canvas.getDocument();\n const canvasBody = canvasDoc.body;\n const canvasWindow = editor.Canvas.getWindow();\n\n if (!canvasBody || !canvasWindow) {\n throw new Error('Unable to access canvas content');\n }\n\n // Create a clone of the body to avoid modifying the original\n const clonedBody = canvasBody.cloneNode(true) as HTMLElement;\n\n // Create a temporary container for PDF generation\n const printContainer = document.createElement('div');\n printContainer.style.position = 'absolute';\n printContainer.style.left = '-9999px';\n printContainer.style.width = '210mm'; // A4 width\n printContainer.style.background = 'white';\n printContainer.style.padding = '20mm';\n printContainer.style.fontSize = '12pt';\n document.body.appendChild(printContainer);\n\n // Copy styles from the canvas\n const canvasStyles = canvasDoc.querySelectorAll('style, link[rel=\"stylesheet\"]');\n const styleContainer = document.createElement('div');\n \n canvasStyles.forEach((style) => {\n const clonedStyle = style.cloneNode(true);\n styleContainer.appendChild(clonedStyle);\n });\n\n // Note: We don't need to inline computed styles here as html2pdf.js/html2canvas\n // will handle rendering, and the browser print fallback will use the stylesheets\n\n // Append cloned content to print container\n printContainer.appendChild(styleContainer);\n printContainer.appendChild(clonedBody);\n\n // Wait for fonts and images to load\n await new Promise((resolve) => {\n setTimeout(resolve, 500);\n });\n\n try {\n // Try to load and use html2pdf.js\n await loadHtml2Pdf();\n\n const opt = {\n filename,\n html2canvas: {\n letterRendering: true,\n logging: false,\n scale: 2,\n useCORS: true,\n windowHeight: canvasWindow.innerHeight,\n windowWidth: canvasWindow.innerWidth,\n },\n image: { quality: 0.98, type: 'jpeg' },\n jsPDF: {\n format: 'a4',\n orientation: 'portrait',\n unit: 'mm',\n },\n margin: [10, 10, 10, 10],\n };\n\n await (window as any).html2pdf().set(opt).from(printContainer).save();\n } catch (html2pdfError) {\n // Fallback: Use browser print functionality\n // eslint-disable-next-line no-console\n console.warn('html2pdf.js not available, using browser print fallback:', html2pdfError);\n \n const printWindow = window.open('', '_blank');\n \n if (!printWindow) {\n throw new Error('Popup blocked. Please allow popups for this site.');\n }\n\n // Collect all styles from the canvas\n const allStyles = Array.from(canvasDoc.querySelectorAll('style'))\n .map((style) => style.textContent)\n .join('\\n');\n\n printWindow.document.write(`\n <!DOCTYPE html>\n <html>\n <head>\n <title>${filename.replace('.pdf', '')}</title>\n <meta charset=\"utf-8\">\n <style>\n @media print {\n @page {\n margin: 0;\n size: A4;\n }\n body {\n margin: 0;\n padding: 20mm;\n }\n }\n body {\n margin: 0;\n padding: 20mm;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: white;\n }\n ${allStyles}\n </style>\n </head>\n <body>\n ${clonedBody.innerHTML}\n </body>\n </html>\n `);\n\n printWindow.document.close();\n\n await new Promise<void>((resolve) => {\n printWindow.onload = () => {\n setTimeout(() => {\n printWindow.print();\n // Close window after print dialog\n setTimeout(() => {\n printWindow.close();\n resolve();\n }, 1000);\n }, 500);\n };\n \n // Fallback if onload doesn't fire\n setTimeout(() => {\n if (printWindow.document.readyState === 'complete') {\n printWindow.print();\n setTimeout(() => {\n printWindow.close();\n resolve();\n }, 1000);\n }\n }, 1000);\n });\n }\n\n // Cleanup\n if (printContainer.parentNode) {\n document.body.removeChild(printContainer);\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error exporting to PDF:', error);\n\n throw error;\n }\n}\n\n"],"mappings":"mIAAA,uDAGA;AACA;AACA,GACA,QAAS,CAAAA,YAAYA,CAAA,CAAkB,CACrC,MAAO,IAAI,CAAAC,OAAO,CAAC,SAACC,OAAO,CAAEC,MAAM,CAAK,CACtC,GAAI,MAAQ,CAAAC,MAAM,CAASC,QAAQ,GAAK,WAAW,CAAE,CACnDH,OAAO,CAAC,CAAC,CAET,MACF,CAEA;AACA,GAAM,CAAAI,MAAM,CAAGC,QAAQ,CAACC,aAAa,CAAC,QAAQ,CAAC,CAC/CF,MAAM,CAACG,GAAG,CAAG,kFAAkF,CAC/FH,MAAM,CAACI,MAAM,CAAG,iBAAM,CAAAR,OAAO,CAAC,CAAC,EAC/BI,MAAM,CAACK,OAAO,CAAG,iBAAM,CAAAR,MAAM,CAAC,GAAI,CAAAS,KAAK,CAAC,4BAA4B,CAAC,CAAC,EACtEL,QAAQ,CAACM,IAAI,CAACC,WAAW,CAACR,MAAM,CAClC,CAAC,CACH,CAEA;AACA;AACA;AACA;AACA,GACA,eAAsB,CAAAS,iBAAiBA,CAAAC,EAAA,CAAAC,GAAA,SAAAC,kBAAA,CAAAC,KAAA,MAAAC,SAAA,EA6JtC,SAAAF,mBAAA,EAAAA,kBAAA,CAAAG,iBAAA,cAAAC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D,KAAK,CAAC,CAAC,CACnBjC,UAAU,CAAC,UAAM,CACftB,WAAW,CAACsD,KAAK,CAAC,CAAC,CACnBvF,OAAO,CAAC,CACV,CAAC,CAAE,IAAI,CACT,CACF,CAAC,CAAE,IAAI,CACT,CAAC,CAAC,SAGJ;AACA,GAAI6B,cAAc,CAAC6D,UAAU,CAAE,CAC7BrF,QAAQ,CAACqC,IAAI,CAACiD,WAAW,CAAC9D,cAAc,CAC1C,CAACQ,QAAA,CAAAE,IAAA,kBAAAF,QAAA,CAAAC,IAAA,IAAAD,QAAA,CAAAuD,EAAA,CAAAvD,QAAA,aAED;AACAwC,OAAO,CAACgB,KAAK,CAAC,yBAAyB,CAAAxD,QAAA,CAAAuD,EAAO,CAAC,CAAC,MAAAvD,QAAA,CAAAuD,EAAA,0BAAAvD,QAAA,CAAAyD,IAAA,KAAAxE,OAAA,wBAInD,UAAAN,kBAAA,CAAAC,KAAA,MAAAC,SAAA","ignoreList":[]}
package/index.styles.js CHANGED
@@ -1,2 +1,2 @@
1
- import{createGlobalStyle}from"styled-components";export var StyledEditor=createGlobalStyle([".gs-sidebar-left,.gs-sidebar-top,.gs-sidebar-right,.gjs-pn-panels,.gjs-pn-views,.gjs-off-prv,.gjs-pn-devices{display:none !important;}.gjs-badge-label{display:none !important;}.gjs-cv-canvas{height:100% !important;width:100% !important;top:0 !important;}.gjs-hovered,.gjs-selected,[data-gjs-type],[data-highlightable]{outline:none !important;}.gjs-highlighter,.gjs-highlighter-sel,.gjs-selected-parent,.gjs-toolbar{outline:none !important;border:none !important;box-shadow:none !important;}.gjs-frame{outline:none !important;border:none !important;}.gjs-selected::before,.gjs-selected::after,.gjs-hovered::before,.gjs-hovered::after{display:none !important;background:none !important;}.gjs-com-badge,.gjs-badge{display:none !important;}"]);
1
+ import{createGlobalStyle}from"styled-components";export var StyledEditor=createGlobalStyle([".gs-sidebar-left,.gs-sidebar-top,.gs-sidebar-right,.gjs-pn-views,.gjs-off-prv,.gjs-pn-devices{display:none !important;}.gjs-pn-panels{display:none !important;}#canvas-pdf-download-container{position:fixed !important;top:10px !important;right:10px !important;z-index:10000 !important;}.canvas-pdf-download-btn:hover{background:#4338ca !important;}.canvas-pdf-download-btn:disabled{opacity:0.6 !important;cursor:wait !important;}.gjs-badge-label{display:none !important;}.gjs-cv-canvas{height:100% !important;width:100% !important;top:0 !important;}.gjs-hovered,.gjs-selected,[data-gjs-type],[data-highlightable]{outline:none !important;}.gjs-highlighter,.gjs-highlighter-sel,.gjs-selected-parent,.gjs-toolbar{outline:none !important;border:none !important;box-shadow:none !important;}.gjs-frame{outline:none !important;border:none !important;}.gjs-selected::before,.gjs-selected::after,.gjs-hovered::before,.gjs-hovered::after{display:none !important;background:none !important;}.gjs-com-badge,.gjs-badge{display:none !important;}"]);
2
2
  //# sourceMappingURL=index.styles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.styles.js","names":["createGlobalStyle","StyledEditor"],"sources":["../src/index.styles.ts"],"sourcesContent":["import { createGlobalStyle } from 'styled-components';\n\nexport const StyledEditor = createGlobalStyle`\n /* Hide GrapesJS panels */\n .gs-sidebar-left,\n .gs-sidebar-top,\n .gs-sidebar-right,\n .gjs-pn-panels,\n .gjs-pn-views,\n .gjs-off-prv,\n .gjs-pn-devices {\n display: none !important;\n }\n\n .gjs-badge-label {\n display: none !important;\n }\n\n .gjs-cv-canvas {\n height: 100% !important;\n width: 100% !important;\n top: 0 !important;\n }\n\n .gjs-hovered, \n .gjs-selected,\n [data-gjs-type],\n [data-highlightable] {\n outline: none !important;\n }\n\n .gjs-highlighter, \n .gjs-highlighter-sel,\n .gjs-selected-parent,\n .gjs-toolbar {\n outline: none !important;\n border: none !important;\n box-shadow: none !important;\n }\n\n .gjs-frame {\n outline: none !important;\n border: none !important;\n }\n\n .gjs-selected::before,\n .gjs-selected::after,\n .gjs-hovered::before,\n .gjs-hovered::after {\n display: none !important;\n background: none !important;\n }\n\n .gjs-com-badge,\n .gjs-badge {\n display: none !important;\n }\n`;\n"],"mappings":"AAAA,OAASA,iBAAiB,KAAQ,mBAAmB,CAErD,MAAO,IAAM,CAAAC,YAAY,CAAGD,iBAAiB,suBAuD5C","ignoreList":[]}
1
+ {"version":3,"file":"index.styles.js","names":["createGlobalStyle","StyledEditor"],"sources":["../src/index.styles.ts"],"sourcesContent":["import { createGlobalStyle } from 'styled-components';\n\nexport const StyledEditor = createGlobalStyle`\n /* Hide GrapesJS panels */\n .gs-sidebar-left,\n .gs-sidebar-top,\n .gs-sidebar-right,\n .gjs-pn-views,\n .gjs-off-prv,\n .gjs-pn-devices {\n display: none !important;\n }\n\n /* Hide all panels */\n .gjs-pn-panels {\n display: none !important;\n }\n\n /* Style for PDF download button */\n #canvas-pdf-download-container {\n position: fixed !important;\n top: 10px !important;\n right: 10px !important;\n z-index: 10000 !important;\n }\n\n .canvas-pdf-download-btn:hover {\n background: #4338ca !important;\n }\n\n .canvas-pdf-download-btn:disabled {\n opacity: 0.6 !important;\n cursor: wait !important;\n }\n\n .gjs-badge-label {\n display: none !important;\n }\n\n .gjs-cv-canvas {\n height: 100% !important;\n width: 100% !important;\n top: 0 !important;\n }\n\n .gjs-hovered, \n .gjs-selected,\n [data-gjs-type],\n [data-highlightable] {\n outline: none !important;\n }\n\n .gjs-highlighter, \n .gjs-highlighter-sel,\n .gjs-selected-parent,\n .gjs-toolbar {\n outline: none !important;\n border: none !important;\n box-shadow: none !important;\n }\n\n .gjs-frame {\n outline: none !important;\n border: none !important;\n }\n\n .gjs-selected::before,\n .gjs-selected::after,\n .gjs-hovered::before,\n .gjs-hovered::after {\n display: none !important;\n background: none !important;\n }\n\n .gjs-com-badge,\n .gjs-badge {\n display: none !important;\n }\n`;\n"],"mappings":"AAAA,OAASA,iBAAiB,KAAQ,mBAAmB,CAErD,MAAO,IAAM,CAAAC,YAAY,CAAGD,iBAAiB,2gCA4E5C","ignoreList":[]}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@peak-ai/canvas",
3
3
  "author": "squad-builder-experience",
4
4
  "license": "UNLICENSED",
5
- "version": "1.4.27",
5
+ "version": "1.4.28-rc.1",
6
6
  "description": "",
7
7
  "dependencies": {
8
8
  "@emotion/react": "^11.11.4",