@peak-ai/canvas 1.4.53 → 1.4.54
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,7 +1,5 @@
|
|
|
1
1
|
import _extends from"@babel/runtime/helpers/extends";import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _regeneratorRuntime from"@babel/runtime/regenerator";/* eslint-disable @typescript-eslint/no-explicit-any */import React,{useEffect,useRef,useState}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 isEditorCanvasReady(editor){try{var canvas=editor.Canvas;if(!canvas){return false}var canvasDoc=canvas.getDocument==null?void 0:canvas.getDocument();if(!canvasDoc){return false}var canvasBody=canvasDoc.body;if(!canvasBody){return false}return true}catch(_unused){return false}}function safeStoreEditor(_x){return _safeStoreEditor.apply(this,arguments)}function _safeStoreEditor(){_safeStoreEditor=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(editor){var _editor$Pages,wrapper,pages
|
|
3
|
-
console.warn("StorageManager or storables not ready, skipping store operation");return _context5.abrupt("return",null);case 11:_context5.next=13;return editor.store();case 13:return _context5.abrupt("return",_context5.sent);case 16:_context5.prev=16;_context5.t0=_context5["catch"](0);// eslint-disable-next-line no-console
|
|
4
|
-
console.warn("Error during store operation:",_context5.t0);return _context5.abrupt("return",null);case 20:case"end":return _context5.stop()}},_callee5,null,[[0,16]])}));return _safeStoreEditor.apply(this,arguments)}function setComponentProperties(editor,isPreview,isStreaming){if(!editor){return}function setPropertiesRecursively(comp){var isMutable=!isPreview&&!isStreaming;comp.set({editable:isMutable,draggable:isMutable,droppable:isMutable&&comp.getName()!=="Shadcn-generic",selectable:isMutable,hoverable:isMutable,highlightable:isMutable,copyable:false,resizable:false,removable:isMutable,badgable:false});comp.set("attributes",_extends({},comp.get("attributes")||{},{isEditable:isMutable}));if(isMutable){comp.set("toolbar",[{attributes:{"class":"fa fa-arrows"},command:"tlb-move"},{attributes:{"class":"fa fa-trash"},command:"tlb-delete"}])}else{comp.set("toolbar",[])}comp.components().forEach(setPropertiesRecursively)}var wrapper=editor.getWrapper();var components=(wrapper==null?void 0:wrapper.find("*"))||[];components.forEach(setPropertiesRecursively);if(isEditorCanvasReady(editor)){if(isPreview){editor.runCommand("core:preview")}else{editor.stopCommand("core:preview")}}}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{createGrapesjsShadcnGenericPlugin}from"./plugins/grapejs-plugin";import{StyledEditor}from"./index.styles";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";function isEditorCanvasReady(editor){try{var canvas=editor.Canvas;if(!canvas){return false}var canvasDoc=canvas.getDocument==null?void 0:canvas.getDocument();if(!canvasDoc){return false}var canvasBody=canvasDoc.body;if(!canvasBody){return false}return true}catch(_unused){return false}}function safeStoreEditor(_x){return _safeStoreEditor.apply(this,arguments)}function _safeStoreEditor(){_safeStoreEditor=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(editor){var _editor$Pages,wrapper,pages;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:_context5.prev=0;wrapper=editor.getWrapper();if(wrapper){_context5.next=4;break}return _context5.abrupt("return",null);case 4:pages=((_editor$Pages=editor.Pages)==null||_editor$Pages.getAll==null?void 0:_editor$Pages.getAll())||[];if(!(pages.length===0)){_context5.next=7;break}return _context5.abrupt("return",null);case 7:_context5.next=9;return editor.store();case 9:return _context5.abrupt("return",_context5.sent);case 12:_context5.prev=12;_context5.t0=_context5["catch"](0);return _context5.abrupt("return",null);case 15:case"end":return _context5.stop()}},_callee5,null,[[0,12]])}));return _safeStoreEditor.apply(this,arguments)}function setComponentProperties(editor,isPreview,isStreaming){if(!editor){return}function setPropertiesRecursively(comp){var isMutable=!isPreview&&!isStreaming;comp.set({editable:isMutable,draggable:isMutable,droppable:isMutable&&comp.getName()!=="Shadcn-generic",selectable:isMutable,hoverable:isMutable,highlightable:isMutable,copyable:false,resizable:false,removable:isMutable,badgable:false});comp.set("attributes",_extends({},comp.get("attributes")||{},{isEditable:isMutable}));if(isMutable){comp.set("toolbar",[{attributes:{"class":"fa fa-arrows"},command:"tlb-move"},{attributes:{"class":"fa fa-trash"},command:"tlb-delete"}])}else{comp.set("toolbar",[])}comp.components().forEach(setPropertiesRecursively)}var wrapper=editor.getWrapper();var components=(wrapper==null?void 0:wrapper.find("*"))||[];components.forEach(setPropertiesRecursively);if(isEditorCanvasReady(editor)){if(isPreview){editor.runCommand("core:preview")}else{editor.stopCommand("core:preview")}}}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
|
|
5
3
|
}:_ref2$newDataNotifier,_ref2$setHasChanged=_ref2.setHasChanged,setHasChanged=_ref2$setHasChanged===void 0?function(){// no op
|
|
6
4
|
}:_ref2$setHasChanged,isStreaming=_ref2.isStreaming,_ref2$isModeChangeFro=_ref2.isModeChangeFromToggle,isModeChangeFromToggle=_ref2$isModeChangeFro===void 0?false:_ref2$isModeChangeFro,_ref2$isTemplateView=_ref2.isTemplateView,isTemplateView=_ref2$isTemplateView===void 0?false:_ref2$isTemplateView;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);var _useState=useState(false),isTransitioning=_useState[0],setIsTransitioning=_useState[1];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
|
|
7
5
|
// This ensures placeholder values are properly cleared and don't cause stale data issues
|
|
@@ -9,6 +7,5 @@ var filteredProps=_extends({},newProps);Object.keys(filteredProps).forEach(funct
|
|
|
9
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&&editorInstance.current&&isEditorAliveRef.current){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(_x2){return _performInteractionWrapper.apply(this,arguments)}function _performInteractionWrapper(){_performInteractionWrapper=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(payload){var updatedJson,apiResponse,componentUpdates;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:updatedJson=null;if(!editorInstance.current){_context4.next=5;break}_context4.next=4;return safeStoreEditor(editorInstance.current);case 4:updatedJson=_context4.sent;case 5:setInteracting(renderedComponents.current,payload.affectedComponents,true);_context4.prev=6;_context4.next=9;return performInteraction(_extends({},payload,{json:updatedJson}));case 9: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 15:_context4.prev=15;_context4.t0=_context4["catch"](6);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 19:_context4.prev=19;setInteracting(renderedComponents.current,payload.affectedComponents,false);return _context4.finish(19);case 22:case"end":return _context4.stop()}},_callee4,null,[[6,15,19,22]])}));return _performInteractionWrapper.apply(this,arguments)}useEffect(function(){if(!editorRef.current){return function(){// no op
|
|
10
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,isTemplateView,isStreaming)],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 _callee2(){var stored,newJson;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:if(!(isStreamingRef.current||isSystemUpdateRef.current)){_context2.next=2;break}return _context2.abrupt("return");case 2:if(!(!isEditorAliveRef.current||!editorInstance.current)){_context2.next=4;break}return _context2.abrupt("return");case 4:stored=null;_context2.next=7;return safeStoreEditor(editorInstance.current);case 7:stored=_context2.sent;if(stored){_context2.next=10;break}return _context2.abrupt("return");case 10:newJson=JSON.stringify(stored);if(newJson!==lastJsonRef.current){setHasChanged(true);lastJsonRef.current=newJson}case 12:case"end":return _context2.stop()}},_callee2)}));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
|
|
11
9
|
// So, adding them from here!
|
|
12
|
-
editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var canvasDoc,canvasHead,style,fullCss,storeResult;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;_context.next=6;return safeStoreEditor(editor);case 6:storeResult=_context.sent;if(storeResult){lastJsonRef.current=JSON.stringify(storeResult)}isSystemUpdateRef.current=false;setComponentProperties(editor,currentMode==="preview",isStreamingRef.current);case 10: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:{}})}});return function cleanup(){editor.destroy();isEditorAliveRef.current=false}},[]);useEffect(function(){var _json$pages,_json$pages$0$frames;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){var _editorInstance$
|
|
13
|
-
console.error("Error during component restoration:",error)}var cssText=convertStyles(json.styles||[]);(_editorInstance$curre3=editorInstance.current)==null||_editorInstance$curre3.setStyle(cssText);if(editorInstance.current){setComponentProperties(editorInstance.current,mode==="preview",isStreaming);setTimeout(function(){if(editorInstance.current&&isEditorAliveRef.current&&mode==="preview"){setComponentProperties(editorInstance.current,true,isStreaming)}},50)}setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var storeResult;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:if(!(editorInstance.current&&isEditorAliveRef.current)){_context3.next=6;break}_context3.next=3;return safeStoreEditor(editorInstance.current);case 3:storeResult=_context3.sent;if(storeResult){lastJsonRef.current=JSON.stringify(storeResult)}isSystemUpdateRef.current=false;case 6:case"end":return _context3.stop()}},_callee3)})),100)}},[json]);useEffect(function(){if(mode&&editorInstance.current&&isEditorAliveRef.current){isSystemUpdateRef.current=true;if(isModeChangeFromToggle){setIsTransitioning(true)}setComponentProperties(editorInstance.current,mode==="preview",isStreaming);setTimeout(function(){if(isEditorAliveRef.current){isSystemUpdateRef.current=false;setIsTransitioning(false)}},50)}},[mode,isModeChangeFromToggle]);return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(StyledEditor,{}),/*#__PURE__*/_jsx("div",{ref:editorRef,id:"grapesjs-editor",style:{opacity:isTransitioning?0:1,transition:"opacity 0.15s ease-in-out"}})]})}export default GrapesjsCanvas;
|
|
10
|
+
editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var canvasDoc,canvasHead,style,fullCss,storeResult;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;_context.next=6;return safeStoreEditor(editor);case 6:storeResult=_context.sent;if(storeResult){lastJsonRef.current=JSON.stringify(storeResult)}isSystemUpdateRef.current=false;setComponentProperties(editor,currentMode==="preview",isStreamingRef.current);case 10: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:{}})}});return function cleanup(){editor.destroy();isEditorAliveRef.current=false}},[]);useEffect(function(){var _json$pages,_json$pages$0$frames;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){var _editorInstance$curre,_editorInstance$curre2;if(!isEditorAliveRef.current||!editorInstance.current){return}isSystemUpdateRef.current=true;var raw=json.pages[0].frames[0].component;var processed=expandActions(raw);(_editorInstance$curre=editorInstance.current)==null||_editorInstance$curre.setComponents(processed);var cssText=convertStyles(json.styles||[]);(_editorInstance$curre2=editorInstance.current)==null||_editorInstance$curre2.setStyle(cssText);if(editorInstance.current){setComponentProperties(editorInstance.current,mode==="preview",isStreaming);setTimeout(function(){if(editorInstance.current&&isEditorAliveRef.current&&mode==="preview"){setComponentProperties(editorInstance.current,true,isStreaming)}},50)}setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var storeResult;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:if(!(editorInstance.current&&isEditorAliveRef.current)){_context3.next=6;break}_context3.next=3;return safeStoreEditor(editorInstance.current);case 3:storeResult=_context3.sent;if(storeResult){lastJsonRef.current=JSON.stringify(storeResult)}isSystemUpdateRef.current=false;case 6:case"end":return _context3.stop()}},_callee3)})),100)}},[json]);useEffect(function(){if(mode&&editorInstance.current&&isEditorAliveRef.current){isSystemUpdateRef.current=true;if(isModeChangeFromToggle){setIsTransitioning(true)}setComponentProperties(editorInstance.current,mode==="preview",isStreaming);setTimeout(function(){if(isEditorAliveRef.current){isSystemUpdateRef.current=false;setIsTransitioning(false)}},50)}},[mode,isModeChangeFromToggle]);return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(StyledEditor,{}),/*#__PURE__*/_jsx("div",{ref:editorRef,id:"grapesjs-editor",style:{opacity:isTransitioning?0:1,transition:"opacity 0.15s ease-in-out"}})]})}export default GrapesjsCanvas;
|
|
14
11
|
//# sourceMappingURL=GrapesjsCanvas.js.map
|
package/GrapesjsCanvas.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","useState","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","createGrapesjsShadcnGenericPlugin","StyledEditor","jsx","_jsx","jsxs","_jsxs","isEditorCanvasReady","editor","canvas","Canvas","canvasDoc","getDocument","canvasBody","body","_unused","safeStoreEditor","_x","_safeStoreEditor","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee5","_editor$Pages","wrapper","pages","storageManager","wrap","_callee5$","_context5","prev","next","getWrapper","abrupt","Pages","getAll","length","StorageManager","storables","console","warn","store","sent","t0","stop","setComponentProperties","isPreview","isStreaming","setPropertiesRecursively","comp","isMutable","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","_extends","get","isEditable","attributes","command","components","forEach","find","runCommand","stopCommand","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","classes","concat","undefined","i","id","setInteracting","renderedComponents","inProgress","component","componentId","showLoader","gjsModel","interactionApiInProgress","expandActionsComponent","model","append","addClass","GrapesjsCanvas","_ref2","json","_ref2$mode","mode","setEditor","performInteraction","_ref2$newDataNotifier","newDataNotifier","_ref2$setHasChanged","setHasChanged","_ref2$isModeChangeFro","isModeChangeFromToggle","_ref2$isTemplateView","isTemplateView","editorRef","editorInstance","isStreamingRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","_useState","isTransitioning","setIsTransitioning","current","notificationHandler","props","_props$newProps","newProps","_props$newAttributes","newAttributes","filteredProps","keys","key","name","parsedNewProps","pagination","isActionsComponent","hasValidActionsData","_model$components$at","isAlreadyExpanded","at","performInteractionWrapper","_x2","_performInteractionWrapper","_callee4","payload","updatedJson","apiResponse","componentUpdates","_callee4$","_context4","affectedComponents","_ref6","error","isMissing","errorMessage","Error","message","finish","destroy","currentMode","init","container","height","plugins","richTextEditor","customBadgeLabel","tagName","injectionAttempts","injectStylesEarly","_editor$Canvas","iframeDoc","head","querySelector","createElement","fullCss","innerHTML","setAttribute","appendChild","requestAnimationFrame","checkDirty","_checkDirty","_callee2","stored","newJson","_callee2$","_context2","JSON","stringify","debouncedCheckDirty","timeout","clearTimeout","setTimeout","evt","on","includes","_callee","canvasHead","storeResult","_callee$","_context","_ref4","DomComponents","getType","addType","defaults","view","cleanup","_json$pages","_json$pages$0$frames","frames","_editorInstance$curre3","raw","processed","_editorInstance$curre","setComponents","_editorInstance$curre2","domComponents","_domComponents$getWra","allComponents","findType","_comp$view","render","cssText","styles","setStyle","_callee3","_callee3$","_context3","Fragment","children","ref","opacity","transition"],"sources":["../src/GrapesjsCanvas.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { useEffect, useRef, useState } 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 isModeChangeFromToggle?: boolean;\n isTemplateView?: boolean;\n};\n\nfunction isEditorCanvasReady(editor: Editor): boolean {\n try {\n const canvas = editor.Canvas;\n\n if (!canvas) {\n return false;\n }\n\n const canvasDoc = canvas.getDocument?.();\n\n if (!canvasDoc) {\n return false;\n }\n\n const canvasBody = canvasDoc.body;\n\n if (!canvasBody) {\n return false;\n }\n\n return true;\n } catch {\n return false;\n }\n}\n\nasync function safeStoreEditor(editor: Editor): Promise<any | null> {\n try {\n const wrapper = editor.getWrapper();\n\n if (!wrapper) {\n return null;\n }\n\n const pages = editor.Pages?.getAll?.() || [];\n\n if (pages.length === 0) {\n return null;\n }\n\n const storageManager = (editor as any).StorageManager;\n\n if (!storageManager || !storageManager.storables) {\n // eslint-disable-next-line no-console\n console.warn('StorageManager or storables not ready, skipping store operation');\n\n return null;\n }\n\n return await editor.store();\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn('Error during store operation:', error);\n\n return null;\n }\n}\n\nfunction setComponentProperties(editor: Editor, isPreview: boolean, isStreaming: boolean): void {\n if (!editor) {\n return;\n }\n\n function setPropertiesRecursively(comp: Component) {\n const isMutable = !isPreview && !isStreaming;\n\n comp.set({\n editable: isMutable,\n draggable: isMutable,\n droppable: isMutable && comp.getName() !== 'Shadcn-generic',\n selectable: isMutable,\n hoverable: isMutable,\n highlightable: isMutable,\n copyable: false,\n resizable: false,\n removable: isMutable,\n badgable: false,\n });\n\n comp.set('attributes', {\n ...(comp.get('attributes') || {}),\n isEditable: isMutable,\n });\n\n if (isMutable) {\n comp.set('toolbar', [\n { attributes: { class: 'fa fa-arrows' }, command: 'tlb-move' },\n { attributes: { class: 'fa fa-trash' }, command: 'tlb-delete' },\n ]);\n } else {\n comp.set('toolbar', []);\n }\n\n comp.components().forEach(setPropertiesRecursively);\n }\n\n const wrapper = editor.getWrapper();\n const components = wrapper?.find('*') || [];\n\n components.forEach(setPropertiesRecursively);\n\n if (isEditorCanvasReady(editor)) {\n if (isPreview) {\n editor.runCommand('core:preview');\n } else {\n editor.stopCommand('core:preview');\n }\n }\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 isModeChangeFromToggle = false,\n isTemplateView = false,\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 const [isTransitioning, setIsTransitioning] = useState(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 && editorInstance.current && isEditorAliveRef.current) {\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 let updatedJson = null;\n\n if (editorInstance.current) {\n updatedJson = await safeStoreEditor(editorInstance.current);\n }\n\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 isTemplateView,\n isStreaming,\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 stored = await safeStoreEditor(editorInstance.current);\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 const storeResult = await safeStoreEditor(editor);\n\n if (storeResult) {\n lastJsonRef.current = JSON.stringify(storeResult);\n }\n\n isSystemUpdateRef.current = false;\n\n setComponentProperties(editor, currentMode === 'preview', isStreamingRef.current);\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 return function cleanup() {\n editor.destroy();\n isEditorAliveRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (json && json.pages?.length > 0 && json.pages[0].frames?.length > 0) {\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n isSystemUpdateRef.current = true;\n const raw = json.pages[0].frames[0].component;\n const processed = expandActions(raw);\n\n try {\n editorInstance.current?.setComponents(processed);\n\n setTimeout(() => {\n if (editorInstance.current && isEditorAliveRef.current) {\n const domComponents = editorInstance.current?.DomComponents;\n\n if (domComponents) {\n const allComponents = domComponents?.getWrapper()?.findType('shadcn-generic');\n allComponents?.forEach((comp: any) => {\n if (comp.get('componentName') === 'Tabs') {\n comp.view?.render();\n }\n });\n }\n }\n }, 100);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error during component restoration:', error);\n }\n\n const cssText = convertStyles(json.styles || []);\n editorInstance.current?.setStyle(cssText);\n\n if (editorInstance.current) {\n setComponentProperties(editorInstance.current, mode === 'preview', isStreaming);\n\n setTimeout(() => {\n if (editorInstance.current && isEditorAliveRef.current && mode === 'preview') {\n setComponentProperties(editorInstance.current, true, isStreaming);\n }\n }, 50);\n }\n\n setTimeout(async () => {\n if (editorInstance.current && isEditorAliveRef.current) {\n const storeResult = await safeStoreEditor(editorInstance.current);\n\n if (storeResult) {\n lastJsonRef.current = JSON.stringify(storeResult);\n }\n\n isSystemUpdateRef.current = false;\n }\n }, 100);\n }\n }, [json]);\n\n useEffect(() => {\n if (mode && editorInstance.current && isEditorAliveRef.current) {\n isSystemUpdateRef.current = true;\n\n if (isModeChangeFromToggle) {\n setIsTransitioning(true);\n }\n\n setComponentProperties(editorInstance.current as Editor, mode === 'preview', isStreaming);\n\n setTimeout(() => {\n if (isEditorAliveRef.current) {\n isSystemUpdateRef.current = false;\n setIsTransitioning(false);\n }\n }, 50);\n }\n }, [mode, isModeChangeFromToggle]);\n\n return (\n <React.Fragment>\n <StyledEditor />\n <div\n ref={editorRef}\n id=\"grapesjs-editor\"\n style={{\n opacity: isTransitioning ? 0 : 1,\n transition: 'opacity 0.15s ease-in-out',\n }}\n />\n </React.Fragment>\n );\n}\n\nexport default GrapesjsCanvas;\n"],"mappings":"wLAAA,uDACA,MAAO,CAAAA,KAAK,EAAIC,SAAS,CAAEC,MAAM,CAAEC,QAAQ,KAAQ,OAAO,CAC1D;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,yBAoB9C,QAAS,CAAAC,mBAAmBA,CAACC,MAAc,CAAW,CACpD,GAAI,CACF,GAAM,CAAAC,MAAM,CAAGD,MAAM,CAACE,MAAM,CAE5B,GAAI,CAACD,MAAM,CAAE,CACX,MAAO,MACT,CAEA,GAAM,CAAAE,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AEzFqK,UAAU,CAAC,UAAM,CACf,GAAIzE,gBAAgB,CAACI,OAAO,CAAE,CAC5BN,iBAAiB,CAACM,OAAO,CAAG,KAAK,CACjCD,kBAAkB,CAAC,KAAK,CAC1B,CACF,CAAC,CAAE,EAAE,CACP,CACF,CAAC,CAAE,CAACnB,IAAI,CAAEQ,sBAAsB,CAAC,CAAC,CAElC,mBACE/H,KAAA,CAACf,KAAK,CAACoQ,QAAQ,EAAAC,QAAA,eACbxP,IAAA,CAACF,YAAY,GAAE,CAAC,cAChBE,IAAA,QACEyP,GAAG,CAAErH,SAAU,CACf5B,EAAE,CAAC,iBAAiB,CACpBtB,KAAK,CAAE,CACLwK,OAAO,CAAE/G,eAAe,CAAG,CAAC,CAAG,CAAC,CAChCgH,UAAU,CAAE,2BACd,CAAE,CACH,CAAC,EACY,CAEpB,CAEA,cAAe,CAAAtI,cAAc","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","useState","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","createGrapesjsShadcnGenericPlugin","StyledEditor","jsx","_jsx","jsxs","_jsxs","isEditorCanvasReady","editor","canvas","Canvas","canvasDoc","getDocument","canvasBody","body","_unused","safeStoreEditor","_x","_safeStoreEditor","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee5","_editor$Pages","wrapper","pages","wrap","_callee5$","_context5","prev","next","getWrapper","abrupt","Pages","getAll","length","store","sent","t0","stop","setComponentProperties","isPreview","isStreaming","setPropertiesRecursively","comp","isMutable","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","_extends","get","isEditable","attributes","command","components","forEach","find","runCommand","stopCommand","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","classes","concat","undefined","i","id","setInteracting","renderedComponents","inProgress","component","componentId","showLoader","gjsModel","interactionApiInProgress","expandActionsComponent","model","append","addClass","GrapesjsCanvas","_ref2","json","_ref2$mode","mode","setEditor","performInteraction","_ref2$newDataNotifier","newDataNotifier","_ref2$setHasChanged","setHasChanged","_ref2$isModeChangeFro","isModeChangeFromToggle","_ref2$isTemplateView","isTemplateView","editorRef","editorInstance","isStreamingRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","_useState","isTransitioning","setIsTransitioning","current","notificationHandler","props","_props$newProps","newProps","_props$newAttributes","newAttributes","filteredProps","keys","key","name","parsedNewProps","pagination","isActionsComponent","hasValidActionsData","_model$components$at","isAlreadyExpanded","at","performInteractionWrapper","_x2","_performInteractionWrapper","_callee4","payload","updatedJson","apiResponse","componentUpdates","_callee4$","_context4","affectedComponents","_ref6","error","isMissing","errorMessage","Error","message","finish","destroy","currentMode","init","container","height","plugins","storageManager","richTextEditor","customBadgeLabel","tagName","injectionAttempts","injectStylesEarly","_editor$Canvas","iframeDoc","head","querySelector","createElement","fullCss","innerHTML","setAttribute","appendChild","requestAnimationFrame","checkDirty","_checkDirty","_callee2","stored","newJson","_callee2$","_context2","JSON","stringify","debouncedCheckDirty","timeout","clearTimeout","setTimeout","evt","on","includes","_callee","canvasHead","storeResult","_callee$","_context","_ref4","DomComponents","getType","addType","defaults","view","cleanup","_json$pages","_json$pages$0$frames","frames","_editorInstance$curre","_editorInstance$curre2","raw","processed","setComponents","cssText","styles","setStyle","_callee3","_callee3$","_context3","Fragment","children","ref","opacity","transition"],"sources":["../src/GrapesjsCanvas.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { useEffect, useRef, useState } 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 isModeChangeFromToggle?: boolean;\n isTemplateView?: boolean;\n};\n\nfunction isEditorCanvasReady(editor: Editor): boolean {\n try {\n const canvas = editor.Canvas;\n\n if (!canvas) {\n return false;\n }\n\n const canvasDoc = canvas.getDocument?.();\n\n if (!canvasDoc) {\n return false;\n }\n\n const canvasBody = canvasDoc.body;\n\n if (!canvasBody) {\n return false;\n }\n\n return true;\n } catch {\n return false;\n }\n}\n\nasync function safeStoreEditor(editor: Editor): Promise<any | null> {\n try {\n const wrapper = editor.getWrapper();\n\n if (!wrapper) {\n return null;\n }\n\n const pages = editor.Pages?.getAll?.() || [];\n\n if (pages.length === 0) {\n return null;\n }\n\n return await editor.store();\n } catch (error) {\n return null;\n }\n}\n\nfunction setComponentProperties(editor: Editor, isPreview: boolean, isStreaming: boolean): void {\n if (!editor) {\n return;\n }\n\n function setPropertiesRecursively(comp: Component) {\n const isMutable = !isPreview && !isStreaming;\n\n comp.set({\n editable: isMutable,\n draggable: isMutable,\n droppable: isMutable && comp.getName() !== 'Shadcn-generic',\n selectable: isMutable,\n hoverable: isMutable,\n highlightable: isMutable,\n copyable: false,\n resizable: false,\n removable: isMutable,\n badgable: false,\n });\n\n comp.set('attributes', {\n ...(comp.get('attributes') || {}),\n isEditable: isMutable,\n });\n\n if (isMutable) {\n comp.set('toolbar', [\n { attributes: { class: 'fa fa-arrows' }, command: 'tlb-move' },\n { attributes: { class: 'fa fa-trash' }, command: 'tlb-delete' },\n ]);\n } else {\n comp.set('toolbar', []);\n }\n\n comp.components().forEach(setPropertiesRecursively);\n }\n\n const wrapper = editor.getWrapper();\n const components = wrapper?.find('*') || [];\n\n components.forEach(setPropertiesRecursively);\n\n if (isEditorCanvasReady(editor)) {\n if (isPreview) {\n editor.runCommand('core:preview');\n } else {\n editor.stopCommand('core:preview');\n }\n }\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 isModeChangeFromToggle = false,\n isTemplateView = false,\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 const [isTransitioning, setIsTransitioning] = useState(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 && editorInstance.current && isEditorAliveRef.current) {\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 let updatedJson = null;\n\n if (editorInstance.current) {\n updatedJson = await safeStoreEditor(editorInstance.current);\n }\n\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 isTemplateView,\n isStreaming,\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 stored = await safeStoreEditor(editorInstance.current);\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 const storeResult = await safeStoreEditor(editor);\n\n if (storeResult) {\n lastJsonRef.current = JSON.stringify(storeResult);\n }\n\n isSystemUpdateRef.current = false;\n\n setComponentProperties(editor, currentMode === 'preview', isStreamingRef.current);\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 return function cleanup() {\n editor.destroy();\n isEditorAliveRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (json && json.pages?.length > 0 && json.pages[0].frames?.length > 0) {\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n isSystemUpdateRef.current = true;\n const raw = json.pages[0].frames[0].component;\n const processed = expandActions(raw);\n editorInstance.current?.setComponents(processed);\n\n const cssText = convertStyles(json.styles || []);\n editorInstance.current?.setStyle(cssText);\n\n if (editorInstance.current) {\n setComponentProperties(editorInstance.current, mode === 'preview', isStreaming);\n\n setTimeout(() => {\n if (editorInstance.current && isEditorAliveRef.current && mode === 'preview') {\n setComponentProperties(editorInstance.current, true, isStreaming);\n }\n }, 50);\n }\n\n setTimeout(async () => {\n if (editorInstance.current && isEditorAliveRef.current) {\n const storeResult = await safeStoreEditor(editorInstance.current);\n\n if (storeResult) {\n lastJsonRef.current = JSON.stringify(storeResult);\n }\n\n isSystemUpdateRef.current = false;\n }\n }, 100);\n }\n }, [json]);\n\n useEffect(() => {\n if (mode && editorInstance.current && isEditorAliveRef.current) {\n isSystemUpdateRef.current = true;\n\n if (isModeChangeFromToggle) {\n setIsTransitioning(true);\n }\n\n setComponentProperties(editorInstance.current as Editor, mode === 'preview', isStreaming);\n\n setTimeout(() => {\n if (isEditorAliveRef.current) {\n isSystemUpdateRef.current = false;\n setIsTransitioning(false);\n }\n }, 50);\n }\n }, [mode, isModeChangeFromToggle]);\n\n return (\n <React.Fragment>\n <StyledEditor />\n <div\n ref={editorRef}\n id=\"grapesjs-editor\"\n style={{\n opacity: isTransitioning ? 0 : 1,\n transition: 'opacity 0.15s ease-in-out',\n }}\n />\n </React.Fragment>\n );\n}\n\nexport default GrapesjsCanvas;\n"],"mappings":"wLAAA,uDACA,MAAO,CAAAA,KAAK,EAAIC,SAAS,CAAEC,MAAM,CAAEC,QAAQ,KAAQ,OAAO,CAC1D;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,KAA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M,CACd,GAAIgI,IAAI,EAAIY,cAAc,CAACQ,OAAO,EAAIJ,gBAAgB,CAACI,OAAO,CAAE,CAC9DN,iBAAiB,CAACM,OAAO,CAAG,IAAI,CAEhC,GAAIZ,sBAAsB,CAAE,CAC1BW,kBAAkB,CAAC,IAAI,CACzB,CAEAjG,sBAAsB,CAAC0F,cAAc,CAACQ,OAAO,CAAYpB,IAAI,GAAK,SAAS,CAAE5E,WAAW,CAAC,CAEzFsK,UAAU,CAAC,UAAM,CACf,GAAI1E,gBAAgB,CAACI,OAAO,CAAE,CAC5BN,iBAAiB,CAACM,OAAO,CAAG,KAAK,CACjCD,kBAAkB,CAAC,KAAK,CAC1B,CACF,CAAC,CAAE,EAAE,CACP,CACF,CAAC,CAAE,CAACnB,IAAI,CAAEQ,sBAAsB,CAAC,CAAC,CAElC,mBACE1H,KAAA,CAACf,KAAK,CAACyP,QAAQ,EAAAC,QAAA,eACb7O,IAAA,CAACF,YAAY,GAAE,CAAC,cAChBE,IAAA,QACE8O,GAAG,CAAE/G,SAAU,CACf5B,EAAE,CAAC,iBAAiB,CACpBtB,KAAK,CAAE,CACLkK,OAAO,CAAEzG,eAAe,CAAG,CAAC,CAAG,CAAC,CAChC0G,UAAU,CAAE,2BACd,CAAE,CACH,CAAC,EACY,CAEpB,CAEA,cAAe,CAAAhI,cAAc","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import _extends from"@babel/runtime/helpers/extends";/* eslint-disable import/no-named-as-default-member *//* eslint-disable func-names *//* eslint-disable @typescript-eslint/no-explicit-any */import ReactDOM from"react-dom";import{getRenderers}from"./helpers/render-components";import{QueryCacheProvider}from"./helpers/query-cache-context";import{jsx as _jsx}from"react/jsx-runtime";export function createGrapesjsShadcnGenericPlugin(mode,performInteraction,renderedComponents,setHasChanged,isTemplateView,isStreaming){if(renderedComponents===void 0){renderedComponents={}}if(isTemplateView===void 0){isTemplateView=false}if(isStreaming===void 0){isStreaming=false}return function grapesjsShadcnGenericPlugin(editor){editor.DomComponents.addType("shadcn-generic",{model:{defaults:{tagName:"div",droppable:false,componentName:"Card",componentProps:{},traits:[]}},view:{events:{"input [data-slot]":"handleSlotInput"},handleSlotInput:function handleSlotInput(e){var target=e.target;var slot=target.dataset.slot;var text=target.innerText;var props=this.model.get("componentProps")||{};if(!slot){return}if(slot.startsWith("table-header-")){var _props$data;var idx=parseInt(slot.split("-")[2],10);var dataKeys=Object.keys(((_props$data=props.data)==null?void 0:_props$data[0])||{});if(!props.headerMapper){props.headerMapper={}}var key=dataKeys[idx];if(key){props.headerMapper[key]=text}}else{props[slot]=text}this.model.set("componentProps",_extends({},props));if(!["search-input"].includes(slot)){setHasChanged(true)}},render:function render(){var _this=this;var compName=this.model.get("componentName");var compProps=this.model.get("componentProps");if(typeof compProps==="string"){try{compProps=JSON.parse(compProps)}catch(err){// eslint-disable-next-line no-console
|
|
2
|
-
console.error("Invalid JSON in componentProps",err);compProps={}}}compProps.performInteraction=performInteraction;compProps.isTemplateView=isTemplateView;compProps.isEditable=mode==="editor"&&!isStreaming;compProps.onChange=function(data){_this.model.set("componentProps",_extends({},_this.model.get("componentProps"),data))};var renderers=getRenderers();var Renderer=renderers[compName];if(Renderer){if(compName==="Tabs"){
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
console.error("Invalid JSON in componentProps",err);compProps={}}}compProps.performInteraction=performInteraction;compProps.isTemplateView=isTemplateView;compProps.isEditable=mode==="editor"&&!isStreaming;compProps.onChange=function(data){_this.model.set("componentProps",_extends({},_this.model.get("componentProps"),data))};var renderers=getRenderers();var Renderer=renderers[compName];if(Renderer){if(compName==="Tabs"){ReactDOM.render(/*#__PURE__*/_jsx(QueryCacheProvider,{maxCacheSize:100,maxCacheAge:5*60*1000,children:/*#__PURE__*/_jsx(Renderer,_extends({},compProps,{gjsModel:this.model}))}),this.el);var children=this.model.components();var tabsContent=this.el.querySelectorAll(".tabs-content");var tabAttributes=this.model.get("attributes")||{};var hasTabsError=tabAttributes.error||compProps.error;var hasTabsMissing=tabAttributes.isMissing||compProps.isMissing;var isFallback=Array.from(tabsContent).some(function(el){return el.dataset.fallback==="true"});if(!isFallback&&tabsContent.length>0){// Helper function to sync child attributes
|
|
3
|
+
// eslint-disable-next-line no-inner-declarations
|
|
4
|
+
var syncChildAttributes=function syncChildAttributes(childModel){var childAttributes=childModel.get("attributes")||{};var childProps=childModel.get("componentProps")||{};var hasError=hasTabsError||childAttributes.error||childProps.error;var hasMissing=hasTabsMissing||childAttributes.isMissing||childProps.isMissing;if(hasError||hasMissing){var newAttributes=_extends({},childAttributes,{loading:false,error:hasError,isMissing:hasMissing,inheritedFromParent:!!(hasTabsError||hasTabsMissing)});childModel.set("attributes",newAttributes,{silent:false})}};children.each(function(childModel,i){var childView=_this.createView(childModel);if(childView&&tabsContent[i]){childView.render();tabsContent[i].appendChild(childView.el);setTimeout(function(){syncChildAttributes(childModel)},100);childModel.on("change:attributes",function(){syncChildAttributes(childModel)})}})}}else{ReactDOM.render(/*#__PURE__*/_jsx(QueryCacheProvider,{maxCacheSize:100,maxCacheAge:5*60*1000,children:/*#__PURE__*/_jsx(Renderer,_extends({},compProps,{gjsModel:this.model}))}),this.el)}}else{this.el.innerHTML="<div>Unsupported component: "+compName+"</div>"}renderedComponents[this.model.get("id")]=this.model;return this},createView:function createView(model){var _this$em$get$getType;var ComponentView=(_this$em$get$getType=this.em.get("DomComponents").getType(model.get("type")))==null?void 0:_this$em$get$getType.view;if(!ComponentView){// eslint-disable-next-line no-console
|
|
5
|
+
console.warn("No view found for component type:",model.get("type"));return null}var view=new ComponentView({model:model,config:this.config,componentTypes:this.componentTypes});return view},remove:function remove(){// eslint-disable-next-line import/no-named-as-default-member
|
|
5
6
|
ReactDOM.unmountComponentAtNode(this.el);return this}}})}}
|
|
6
7
|
//# sourceMappingURL=grapejs-plugin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grapejs-plugin.js","names":["ReactDOM","getRenderers","QueryCacheProvider","jsx","_jsx","createGrapesjsShadcnGenericPlugin","mode","performInteraction","renderedComponents","setHasChanged","isTemplateView","isStreaming","grapesjsShadcnGenericPlugin","editor","DomComponents","addType","model","defaults","tagName","droppable","componentName","componentProps","traits","view","events","handleSlotInput","e","target","slot","dataset","text","innerText","props","get","startsWith","_props$data","idx","parseInt","split","dataKeys","Object","keys","data","headerMapper","key","set","_extends","includes","render","_this","compName","compProps","JSON","parse","err","console","error","isEditable","onChange","renderers","Renderer","_cleanupTabsSetup","maxCacheSize","maxCacheAge","children","gjsModel","el","components","length","tabAttributes","hasTabsError","hasTabsMissing","isMissing","injectChildren","tabsContent","querySelectorAll","isFallback","Array","from","some","fallback","each","childModel","stopListening","i","container","childView","createView","innerHTML","appendChild","listenTo","childAttributes","childProps","hasError","hasMissing","loading","inheritedFromParent","silent","_tabsTimeoutId","setTimeout","warn","clearTimeout","_this$em$get$getType","ComponentView","em","getType","config","componentTypes","remove","unmountComponentAtNode"],"sources":["../../src/plugins/grapejs-plugin.tsx"],"sourcesContent":["/* eslint-disable import/no-named-as-default-member */\n/* eslint-disable func-names */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport ReactDOM from 'react-dom';\nimport { Editor, Component } from 'grapesjs';\nimport { getRenderers } from './helpers/render-components';\nimport { QueryCacheProvider } from './helpers/query-cache-context';\n\nexport function createGrapesjsShadcnGenericPlugin(\n mode: 'editor' | 'preview',\n performInteraction: (payload: Record<string, any>) => void,\n renderedComponents: Record<string, Component> = {},\n setHasChanged: (hasChanged: boolean) => void,\n isTemplateView = false,\n isStreaming = false,\n) {\n return function grapesjsShadcnGenericPlugin(editor: Editor): void {\n editor.DomComponents.addType('shadcn-generic', {\n model: {\n defaults: {\n tagName: 'div',\n droppable: false,\n componentName: 'Card',\n componentProps: {},\n traits: [],\n },\n },\n view: {\n events: {\n 'input [data-slot]': 'handleSlotInput',\n } as any,\n handleSlotInput(e: Event) {\n const target = e.target as HTMLElement;\n const slot = target.dataset.slot;\n const text = target.innerText;\n\n const props = this.model.get('componentProps') || {};\n\n if (!slot) {\n return;\n }\n\n if (slot.startsWith('table-header-')) {\n const idx = parseInt(slot.split('-')[2], 10);\n const dataKeys = Object.keys(props.data?.[0] || {});\n\n if (!props.headerMapper) {\n props.headerMapper = {};\n }\n\n const key = dataKeys[idx];\n\n if (key) {\n props.headerMapper[key] = text;\n }\n } else {\n props[slot] = text;\n }\n\n this.model.set('componentProps', {\n ...props,\n });\n\n if (!['search-input'].includes(slot)) {\n setHasChanged(true);\n }\n },\n render: function () {\n const compName: string = this.model.get('componentName');\n let compProps: any = this.model.get('componentProps');\n\n if (typeof compProps === 'string') {\n try {\n compProps = JSON.parse(compProps);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Invalid JSON in componentProps', err);\n compProps = {};\n }\n }\n\n compProps.performInteraction = performInteraction;\n compProps.isTemplateView = isTemplateView;\n compProps.isEditable = mode === 'editor' && !isStreaming;\n\n compProps.onChange = (data: Record<string, any>) => {\n this.model.set('componentProps', {\n ...this.model.get('componentProps'),\n ...data,\n });\n };\n\n const renderers = getRenderers();\n const Renderer = renderers[compName];\n\n if (Renderer) {\n if (compName === 'Tabs') {\n this._cleanupTabsSetup();\n\n ReactDOM.render(\n <QueryCacheProvider maxCacheSize={100} maxCacheAge={5 * 60 * 1000}>\n <Renderer {...compProps} gjsModel={this.model} />\n </QueryCacheProvider>,\n this.el,\n );\n\n const children = this.model.components();\n\n if (children.length === 0) {\n return this;\n }\n\n const tabAttributes = this.model.get('attributes') || {};\n const hasTabsError = tabAttributes.error || compProps.error;\n const hasTabsMissing = tabAttributes.isMissing || compProps.isMissing;\n\n const injectChildren = () => {\n const tabsContent = this.el.querySelectorAll('.tabs-content');\n const isFallback = Array.from(tabsContent).some(\n (el: Element) => (el as HTMLElement).dataset.fallback === 'true',\n );\n\n if (isFallback || tabsContent.length === 0) {\n return false;\n }\n\n children.each((childModel: any) => {\n this.stopListening(childModel, 'change:attributes');\n });\n\n children.each((childModel: any, i: number) => {\n const container = tabsContent[i];\n\n if (!container) {\n return;\n }\n\n const childView = this.createView(childModel);\n\n if (childView) {\n container.innerHTML = '';\n childView.render();\n container.appendChild(childView.el);\n\n this.listenTo(childModel, 'change:attributes', () => {\n const childAttributes = childModel.get('attributes') || {};\n const childProps = childModel.get('componentProps') || {};\n const hasError = hasTabsError || childAttributes.error || childProps.error;\n const hasMissing =\n hasTabsMissing || childAttributes.isMissing || childProps.isMissing;\n\n if (hasError || hasMissing) {\n childModel.set(\n 'attributes',\n {\n ...childAttributes,\n loading: false,\n error: hasError,\n isMissing: hasMissing,\n inheritedFromParent: !!(hasTabsError || hasTabsMissing),\n },\n { silent: false },\n );\n }\n });\n }\n });\n\n return true;\n };\n\n if (injectChildren()) {\n return this;\n }\n\n this._tabsTimeoutId = setTimeout(() => {\n if (injectChildren()) {\n return;\n }\n\n // eslint-disable-next-line no-console\n console.warn('Could not inject tabs content after delay');\n }, 100);\n } else {\n ReactDOM.render(\n <QueryCacheProvider maxCacheSize={100} maxCacheAge={5 * 60 * 1000}>\n <Renderer {...compProps} gjsModel={this.model} />\n </QueryCacheProvider>,\n this.el,\n );\n }\n } else {\n this.el.innerHTML = `<div>Unsupported component: ${compName}</div>`;\n }\n\n renderedComponents[this.model.get('id')] = this.model;\n\n return this;\n },\n _cleanupTabsSetup: function () {\n if (this._tabsTimeoutId) {\n clearTimeout(this._tabsTimeoutId);\n this._tabsTimeoutId = null;\n }\n },\n createView(model: any) {\n const ComponentView = this.em.get('DomComponents').getType(model.get('type'))?.view;\n\n if (!ComponentView) {\n // eslint-disable-next-line no-console\n console.warn('No view found for component type:', model.get('type'));\n\n return null;\n }\n\n const view = new ComponentView({\n model,\n config: this.config,\n componentTypes: this.componentTypes,\n });\n\n return view;\n },\n remove: function () {\n this.stopListening();\n\n this._cleanupTabsSetup();\n\n // eslint-disable-next-line import/no-named-as-default-member\n ReactDOM.unmountComponentAtNode(this.el);\n\n return this;\n },\n },\n });\n };\n}\n"],"m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,CAAC,CAAG,IAAI,CAACjB,KAAK,CAErD,MAAO,KACT,CAAC,CACD6C,iBAAiB,CAAE,QAAnB,CAAAA,iBAAiBA,CAAA,CAAc,CAC7B,GAAI,IAAI,CAACqC,cAAc,CAAE,CACvBG,YAAY,CAAC,IAAI,CAACH,cAAc,CAAC,CACjC,IAAI,CAACA,cAAc,CAAG,IACxB,CACF,CAAC,CACDX,UAAU,SAAV,CAAAA,UAAUA,CAACvE,KAAU,CAAE,KAAAsF,oBAAA,CACrB,GAAM,CAAAC,aAAa,EAAAD,oBAAA,CAAG,IAAI,CAACE,EAAE,CAACvE,GAAG,CAAC,eAAe,CAAC,CAACwE,OAAO,CAACzF,KAAK,CAACiB,GAAG,CAAC,MAAM,CAAC,CAAC,eAAvDqE,oBAAA,CAAyD/E,IAAI,CAEnF,GAAI,CAACgF,aAAa,CAAE,CAClB;AACAhD,OAAO,CAAC6C,IAAI,CAAC,mCAAmC,CAAEpF,KAAK,CAACiB,GAAG,CAAC,MAAM,CAAC,CAAC,CAEpE,MAAO,KACT,CAEA,GAAM,CAAAV,IAAI,CAAG,GAAI,CAAAgF,aAAa,CAAC,CAC7BvF,KAAK,CAALA,KAAK,CACL0F,MAAM,CAAE,IAAI,CAACA,MAAM,CACnBC,cAAc,CAAE,IAAI,CAACA,cACvB,CAAC,CAAC,CAEF,MAAO,CAAApF,IACT,CAAC,CACDqF,MAAM,CAAE,QAAR,CAAAA,MAAMA,CAAA,CAAc,CAClB,IAAI,CAACzB,aAAa,CAAC,CAAC,CAEpB,IAAI,CAACtB,iBAAiB,CAAC,CAAC,CAExB;AACA7D,QAAQ,CAAC6G,sBAAsB,CAAC,IAAI,CAAC3C,EAAE,CAAC,CAExC,MAAO,KACT,CACF,CACF,CAAC,CACH,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"grapejs-plugin.js","names":["ReactDOM","getRenderers","QueryCacheProvider","jsx","_jsx","createGrapesjsShadcnGenericPlugin","mode","performInteraction","renderedComponents","setHasChanged","isTemplateView","isStreaming","grapesjsShadcnGenericPlugin","editor","DomComponents","addType","model","defaults","tagName","droppable","componentName","componentProps","traits","view","events","handleSlotInput","e","target","slot","dataset","text","innerText","props","get","startsWith","_props$data","idx","parseInt","split","dataKeys","Object","keys","data","headerMapper","key","set","_extends","includes","render","_this","compName","compProps","JSON","parse","err","console","error","isEditable","onChange","renderers","Renderer","maxCacheSize","maxCacheAge","children","gjsModel","el","components","tabsContent","querySelectorAll","tabAttributes","hasTabsError","hasTabsMissing","isMissing","isFallback","Array","from","some","fallback","length","syncChildAttributes","childModel","childAttributes","childProps","hasError","hasMissing","newAttributes","loading","inheritedFromParent","silent","each","i","childView","createView","appendChild","setTimeout","on","innerHTML","_this$em$get$getType","ComponentView","em","getType","warn","config","componentTypes","remove","unmountComponentAtNode"],"sources":["../../src/plugins/grapejs-plugin.tsx"],"sourcesContent":["/* eslint-disable import/no-named-as-default-member */\n/* eslint-disable func-names */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport ReactDOM from 'react-dom';\nimport { Editor, Component } from 'grapesjs';\nimport { getRenderers } from './helpers/render-components';\nimport { QueryCacheProvider } from './helpers/query-cache-context';\n\nexport function createGrapesjsShadcnGenericPlugin(\n mode: 'editor' | 'preview',\n performInteraction: (payload: Record<string, any>) => void,\n renderedComponents: Record<string, Component> = {},\n setHasChanged: (hasChanged: boolean) => void,\n isTemplateView = false,\n isStreaming = false,\n) {\n return function grapesjsShadcnGenericPlugin(editor: Editor): void {\n editor.DomComponents.addType('shadcn-generic', {\n model: {\n defaults: {\n tagName: 'div',\n droppable: false,\n componentName: 'Card',\n componentProps: {},\n traits: [],\n },\n },\n view: {\n events: {\n 'input [data-slot]': 'handleSlotInput',\n } as any,\n handleSlotInput(e: Event) {\n const target = e.target as HTMLElement;\n const slot = target.dataset.slot;\n const text = target.innerText;\n\n const props = this.model.get('componentProps') || {};\n\n if (!slot) {\n return;\n }\n\n if (slot.startsWith('table-header-')) {\n const idx = parseInt(slot.split('-')[2], 10);\n const dataKeys = Object.keys(props.data?.[0] || {});\n\n if (!props.headerMapper) {\n props.headerMapper = {};\n }\n\n const key = dataKeys[idx];\n\n if (key) {\n props.headerMapper[key] = text;\n }\n } else {\n props[slot] = text;\n }\n\n this.model.set('componentProps', {\n ...props,\n });\n\n if (!['search-input'].includes(slot)) {\n setHasChanged(true);\n }\n },\n render: function () {\n const compName: string = this.model.get('componentName');\n let compProps: any = this.model.get('componentProps');\n\n if (typeof compProps === 'string') {\n try {\n compProps = JSON.parse(compProps);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Invalid JSON in componentProps', err);\n compProps = {};\n }\n }\n\n compProps.performInteraction = performInteraction;\n compProps.isTemplateView = isTemplateView;\n compProps.isEditable = mode === 'editor' && !isStreaming;\n\n compProps.onChange = (data: Record<string, any>) => {\n this.model.set('componentProps', {\n ...this.model.get('componentProps'),\n ...data,\n });\n };\n\n const renderers = getRenderers();\n const Renderer = renderers[compName];\n\n if (Renderer) {\n if (compName === 'Tabs') {\n ReactDOM.render(\n <QueryCacheProvider maxCacheSize={100} maxCacheAge={5 * 60 * 1000}>\n <Renderer {...compProps} gjsModel={this.model} />\n </QueryCacheProvider>,\n this.el,\n );\n\n const children = this.model.components();\n const tabsContent = this.el.querySelectorAll('.tabs-content');\n\n const tabAttributes = this.model.get('attributes') || {};\n const hasTabsError = tabAttributes.error || compProps.error;\n const hasTabsMissing = tabAttributes.isMissing || compProps.isMissing;\n const isFallback = Array.from(tabsContent).some(\n (el: Element) => (el as HTMLElement).dataset.fallback === 'true',\n );\n\n if (!isFallback && tabsContent.length > 0) {\n // Helper function to sync child attributes\n // eslint-disable-next-line no-inner-declarations\n function syncChildAttributes(childModel: any) {\n const childAttributes = childModel.get('attributes') || {};\n const childProps = childModel.get('componentProps') || {};\n\n const hasError = hasTabsError || childAttributes.error || childProps.error;\n const hasMissing =\n hasTabsMissing || childAttributes.isMissing || childProps.isMissing;\n\n if (hasError || hasMissing) {\n const newAttributes = {\n ...childAttributes,\n loading: false,\n error: hasError,\n isMissing: hasMissing,\n inheritedFromParent: !!(hasTabsError || hasTabsMissing),\n };\n\n childModel.set('attributes', newAttributes, { silent: false });\n }\n }\n\n children.each((childModel, i) => {\n const childView = this.createView(childModel);\n\n if (childView && tabsContent[i]) {\n childView.render();\n tabsContent[i].appendChild(childView.el);\n\n setTimeout(() => {\n syncChildAttributes(childModel);\n }, 100);\n\n childModel.on('change:attributes', () => {\n syncChildAttributes(childModel);\n });\n }\n });\n }\n } else {\n ReactDOM.render(\n <QueryCacheProvider maxCacheSize={100} maxCacheAge={5 * 60 * 1000}>\n <Renderer {...compProps} gjsModel={this.model} />\n </QueryCacheProvider>,\n this.el,\n );\n }\n } else {\n this.el.innerHTML = `<div>Unsupported component: ${compName}</div>`;\n }\n\n renderedComponents[this.model.get('id')] = this.model;\n\n return this;\n },\n createView(model: any) {\n const ComponentView = this.em.get('DomComponents').getType(model.get('type'))?.view;\n\n if (!ComponentView) {\n // eslint-disable-next-line no-console\n console.warn('No view found for component type:', model.get('type'));\n\n return null;\n }\n\n const view = new ComponentView({\n model,\n config: this.config,\n componentTypes: this.componentTypes,\n });\n\n return view;\n },\n remove: function () {\n // eslint-disable-next-line import/no-named-as-default-member\n ReactDOM.unmountComponentAtNode(this.el);\n\n return this;\n },\n },\n });\n };\n}\n"],"mappings":"qDAAA,sDACA,+BACA,uDACA,MAAO,CAAAA,QAAQ,KAAM,WAAW,CAEhC,OAASC,YAAY,KAAQ,6BAA6B,CAC1D,OAASC,kBAAkB,KAAQ,+BAA+B,CAAC,OAAAC,GAAA,IAAAC,IAAA,yBAEnE,MAAO,SAAS,CAAAC,iCAAiCA,CAC/CC,IAA0B,CAC1BC,kBAA0D,CAC1DC,kBAA6C,CAC7CC,aAA4C,CAC5CC,cAAc,CACdC,WAAW,CACX,IAJAH,kBAA6C,WAA7CA,kBAA6C,CAAG,CAAC,CAAC,IAElDE,cAAc,WAAdA,cAAc,CAAG,KAAK,IACtBC,WAAW,WA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F,CAAC,CACH,CACF","ignoreList":[]}
|
|
@@ -9,8 +9,7 @@ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _us
|
|
|
9
9
|
var actualChartWidth=Math.max(innerWidth,xScale.range()[1]||0);var bounds={minY:BEESWARM_CONFIG.RADIUS,maxY:innerHeight-BEESWARM_CONFIG.RADIUS,minX:0,maxX:actualChartWidth};var nodes=data.map(function(d){var initialY=yScaleWithPadding(d.value);var clampedY=Math.max(bounds.minY,Math.min(bounds.maxY,initialY));var groupCenterX=(xScale(d.group)||0)+(xScale.bandwidth()||0)/2;var bandwidth=xScale.bandwidth()||0;var maxSpread=bandwidth*BEESWARM_CONFIG.SPREAD_FACTOR;var randomOffset=(Math.random()-0.5)*maxSpread*BEESWARM_CONFIG.RANDOM_FACTOR;return _extends({},d,{groupCenterX:groupCenterX,x:groupCenterX+randomOffset,y:clampedY,radius:BEESWARM_CONFIG.RADIUS,maxSpread:maxSpread})});var simulation=null;try{simulation=forceSimulation(nodes).force("x",forceX(function(d){return d.groupCenterX}).strength(0.15)).force("y",forceY(function(d){var targetY=yScaleWithPadding(d.value);return Math.max(bounds.minY,Math.min(bounds.maxY,targetY))}).strength(1)).force("collide",forceCollide().radius(function(d){return d.radius+BEESWARM_CONFIG.COLLISION_PADDING}).strength(0.9).iterations(3));if(simulation&&typeof simulation.stop==="function"){simulation.stop()}}catch(error){setSimulatedNodes([].concat(nodes));return}var constrainNode=function constrainNode(node,isFinal){if(isFinal===void 0){isFinal=false}var correctY=yScaleWithPadding(node.value);node.y=Math.max(bounds.minY,Math.min(bounds.maxY,correctY));node.vy=0;var nodeMinX=node.groupCenterX-node.maxSpread;var nodeMaxX=node.groupCenterX+node.maxSpread;var constrainedMinX=Math.max(bounds.minX,nodeMinX);var constrainedMaxX=Math.min(bounds.maxX,nodeMaxX);if(isFinal){if(node.x<constrainedMinX){node.x=constrainedMinX}else if(node.x>constrainedMaxX){node.x=constrainedMaxX}}else{var overflowMargin=node.maxSpread*0.1;if(node.x<constrainedMinX-overflowMargin){node.x=constrainedMinX-overflowMargin;node.vx*=0.7}else if(node.x>constrainedMaxX+overflowMargin){node.x=constrainedMaxX+overflowMargin;node.vx*=0.7}}};if(simulation&&typeof simulation.tick==="function"){for(var i=0;i<BEESWARM_CONFIG.SIMULATION_ITERATIONS;i++){try{simulation.tick();nodes.forEach(function(node){return constrainNode(node,false)})}catch(error){break}}}// Final constraint pass
|
|
10
10
|
nodes.forEach(function(node){constrainNode(node,true);node.vx=0});setSimulatedNodes([].concat(nodes))},[scales,data]);if(simulatedNodes.length===0||dimensions.width===0||!scales){return/*#__PURE__*/_jsx("div",{ref:containerRef,style:{width:"100%",height:"250px"}})}var margin={top:20,right:20,bottom:60,left:60};var xScale=scales.xScale,yScale=scales.yScale,innerWidth=scales.innerWidth,innerHeight=scales.innerHeight;var handleMouseOver=function handleMouseOver(event,node){if(containerRef.current){var containerRect=containerRef.current.getBoundingClientRect();var x=event.clientX-containerRect.left+10;var y=event.clientY-containerRect.top-10;showTooltip({tooltipLeft:x,tooltipTop:y,tooltipData:node})}};var actualChartWidth=Math.max(innerWidth,xScale.range()[1]||0);var actualSvgWidth=actualChartWidth+margin.left+margin.right;return/*#__PURE__*/_jsxs("div",{ref:containerRef,style:{width:"100%",height:"250px",position:"relative"},children:[/*#__PURE__*/_jsx("svg",{ref:svgRef,width:Math.max(dimensions.width,actualSvgWidth),height:dimensions.height,onMouseLeave:hideTooltip,children:/*#__PURE__*/_jsxs(Group,{left:margin.left,top:margin.top,children:[/*#__PURE__*/_jsx(GridRows,{scale:yScale,width:actualChartWidth,strokeDasharray:"3,3",stroke:"#e0e0e0",strokeOpacity:0.5}),/*#__PURE__*/_jsx(AxisLeft,{scale:yScale,tickStroke:"#666",stroke:"#666",tickLabelProps:function tickLabelProps(){return{fill:"#666",fontSize:12,textAnchor:"end",dy:"0.33em"}}}),/*#__PURE__*/_jsx(AxisBottom,{top:innerHeight,scale:xScale,tickStroke:"#666",stroke:"#666",tickLabelProps:function tickLabelProps(){return{fill:"#666",fontSize:12,textAnchor:"middle"}}}),simulatedNodes.map(function(node,i){return/*#__PURE__*/_jsx(Circle,{cx:node.x||0,cy:node.y||0,r:node.radius,fill:color,opacity:0.8,stroke:color,strokeWidth:1,onMouseOver:function onMouseOver(e){return handleMouseOver(e,node)},style:{cursor:"pointer"}},i)})]})}),tooltipOpen&&tooltipData&&tooltipLeft!==null&&tooltipLeft!==undefined&&tooltipTop!==null&&tooltipTop!==undefined&&/*#__PURE__*/_jsx(TooltipWithBounds,{left:tooltipLeft,top:tooltipTop,style:_extends({},defaultStyles,{backgroundColor:"white",border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px 12px",boxShadow:"0 2px 8px rgba(0,0,0,0.15)",fontSize:"12px",position:"absolute",zIndex:1000,pointerEvents:"none"}),children:/*#__PURE__*/_jsxs("div",{children:[/*#__PURE__*/_jsxs("div",{style:{marginBottom:"4px",fontWeight:600},children:[groupBy,": ",tooltipData.group]}),/*#__PURE__*/_jsxs("div",{children:[valueKey,": ",tooltipData.value.toLocaleString()]})]})})]})}function renderChartComponent(chartType,data,config){var safeData=Array.isArray(data)?data:[];if(safeData.length===0){return renderNoDataFallback()}switch(chartType){case"pie":return/*#__PURE__*/_jsxs(PieChart,{children:[safeData.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true})}),/*#__PURE__*/_jsx(Pie,{data:safeData,dataKey:config.dataKey,nameKey:config.nameKey,innerRadius:60,strokeWidth:10,label:safeData.length<20?function(_ref3){var name=_ref3.name,percent=_ref3.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]});case"bar":{config.dataKeys=config.dataKeys||[];var barDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];var angle=config.angle?config.angle:0;var radian=Math.abs(angle)*(Math.PI/180);var maxLabelLength=safeData.reduce(function(max,item){var label=String(item[config.xAxis]||"");return Math.max(max,Math.min(label.length,28))},0);var multiplier=Math.floor(Math.max(Math.sin(radian),0.3)*6);var axisHeight=40+maxLabelLength*multiplier;return/*#__PURE__*/_jsxs(BarChart,_extends({data:safeData},config.chartUi,barDataKeys.length>1&&{barGap:0},{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,_extends({dataKey:config.xAxis},config.angle&&{interval:0,angle:angle,height:axisHeight,textAnchor:"end"},{tickFormatter:function tickFormatter(value){return value.length>25?value.slice(0,25)+"...":value}})),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(Legend,{align:"left",wrapperStyle:{marginLeft:20}}),barDataKeys.map(function(_ref4){var key=_ref4.key,name=_ref4.name,color=_ref4.color;return/*#__PURE__*/_jsx(Bar,{dataKey:key,fill:color!=null?color:"#4caf50",name:name,radius:2},key)}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})})]}))}case"line":{config.dataKeys=config.dataKeys||[];var safeDataKeysLine=Array.isArray(config.dataKeys)?config.dataKeys:[];return/*#__PURE__*/_jsxs(LineChart,_extends({data:safeData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:config.xAxis}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})}),safeDataKeysLine.map(function(_ref5){var key=_ref5.key,name=_ref5.name,color=_ref5.color;return/*#__PURE__*/_jsx(Line,{type:"monotone",dataKey:key,stroke:color!=null?color:"#4caf50",name:name},key)}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"scatter":{config.dataKeys=config.dataKeys||[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];var scatterData=transformDataForScatter(safeData,config.xAxis,config.yAxis,safeDataKeys);if(scatterData.length===0){return renderNoDataFallback()}var colors=safeDataKeys.length>0?safeDataKeys.map(function(_ref6){var color=_ref6.color;return color!=null?color:"#2A44D4"}):["#2A44D4"];return/*#__PURE__*/_jsxs(ScatterChart,_extends({data:scatterData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{type:"number",dataKey:config.xAxis,name:config.xAxis||"X Axis",domain:["auto","auto"]}),/*#__PURE__*/_jsx(YAxis,{type:"number",dataKey:config.yAxis,name:config.yAxis||"Y Axis",domain:["auto","auto"]}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:{strokeDasharray:"3 3"},content:/*#__PURE__*/_jsx(ChartTooltipContent,{})}),safeDataKeys.length>0?safeDataKeys.map(function(_ref7,index){var key=_ref7.key,name=_ref7.name,color=_ref7.color;return/*#__PURE__*/_jsx(Scatter,{name:name||key,dataKey:key||config.yAxis,fill:color!=null?color:colors[index%colors.length]},key)}):/*#__PURE__*/_jsx(Scatter,{name:"Data",dataKey:config.yAxis,fill:colors[0]}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"histogram":{config.dataKeys=config.dataKeys||[];var _safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];var valueKey=_safeDataKeys.length>0?_safeDataKeys[0].key:config.xAxis;var bins=config.bins||10;var binnedData=binDataForHistogram(safeData,valueKey,bins);if(binnedData.length===0){return renderNoDataFallback()}var color=_safeDataKeys.length>0?_safeDataKeys[0].color:"#2A44D4";return/*#__PURE__*/_jsxs(BarChart,_extends({data:binnedData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:"bin",angle:-45,textAnchor:"end",height:80}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})}),/*#__PURE__*/_jsx(Bar,{dataKey:"frequency",fill:color,radius:2,children:binnedData.map(function(entry,index){return/*#__PURE__*/_jsx(Cell,{fill:color},"cell-"+index)})}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"beeswarm":{var _config$dataKeys$,_config$dataKeys$2;var groupBy=config.groupBy||config.xAxis;var _valueKey=config.valueKey||config.dataKeys&&((_config$dataKeys$=config.dataKeys[0])==null?void 0:_config$dataKeys$.key)||"value";var _transformDataForBees=transformDataForBeeswarm(safeData,groupBy,_valueKey),nodes=_transformDataForBees.nodes,groups=_transformDataForBees.groups;if(nodes.length===0||groups.length===0){return renderNoDataFallback()}var _color=config.dataKeys&&(_config$dataKeys$2=config.dataKeys[0])!=null&&_config$dataKeys$2.color?config.dataKeys[0].color:"#2A44D4";return/*#__PURE__*/_jsx(BeeswarmChart,{data:nodes,groups:groups,color:_color,groupBy:groupBy,valueKey:_valueKey})}default:return/*#__PURE__*/_jsxs(PieChart,{children:[safeData.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true})}),/*#__PURE__*/_jsx(Pie,{data:safeData,dataKey:config.dataKey,nameKey:config.nameKey,innerRadius:60,strokeWidth:10,label:safeData.length<20?function(_ref8){var name=_ref8.name,percent=_ref8.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]})}}export function renderChart(props){var _attributes$isEditabl2;var gjsModel=props.gjsModel,_props$performInterac2=props.performInteraction,performInteraction=_props$performInterac2===void 0?function(){return Promise.resolve({})}:_props$performInterac2,_props$isTemplateView3=props.isTemplateView,isTemplateView=_props$isTemplateView3===void 0?false:_props$isTemplateView3,rest=_objectWithoutPropertiesLoose(props,_excluded3);// Memoize filtered props to avoid re-filtering on every render
|
|
11
11
|
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState8=useState(initialData),allData=_useState8[0],setAllData=_useState8[1];var _useState9=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState9[0],setAttributes=_useState9[1];var isEditable=(_attributes$isEditabl2=attributes.isEditable)!=null?_attributes$isEditabl2:false;var containerRef=useRef(null);var _useState10=useState(0),containerWidth=_useState10[0],setContainerWidth=_useState10[1];useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){var newAttributes=gjsModel.get("attributes");setAttributes(_extends({},newAttributes))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);useEffect(function(){var updateContainerWidth=function updateContainerWidth(){if(containerRef.current){setContainerWidth(containerRef.current.offsetWidth||0)}};var resizeObserver=new ResizeObserver(function(entries){for(var _iterator3=_createForOfIteratorHelperLoose(entries),_step3;!(_step3=_iterator3()).done;){var entry=_step3.value;setContainerWidth(entry.contentRect.width||0)}});updateContainerWidth();var timeoutId=setTimeout(updateContainerWidth,50);if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateContainerWidth);return function(){clearTimeout(timeoutId);resizeObserver.disconnect();window.removeEventListener("resize",updateContainerWidth)}},[]);var _allData$config=allData.config,config=_allData$config===void 0?{}:_allData$config,_allData$chartType=allData.chartType,chartType=_allData$chartType===void 0?"pie":_allData$chartType,_allData$chartData=allData.chartData,chartData=_allData$chartData===void 0?[]:_allData$chartData,className=allData.className,_allData$title=allData.title,title=_allData$title===void 0?"Title":_allData$title,_allData$subTitle=allData.subTitle,subTitle=_allData$subTitle===void 0?"Subtitle":_allData$subTitle,sampleData=allData.sampleData;var effectiveChartData=isTemplateView&&sampleData!==undefined?sampleData:chartData;var defaultClasses="aspect-auto w-full min-w-[200px] min-h-[200px]";var mergedClasses=className?cn(defaultClasses,className):defaultClasses;if(chartType==="pie"){var safeChartData=Array.isArray(effectiveChartData)?effectiveChartData:[];var colors=getNColors(safeChartData.length);safeChartData.forEach(function(data,i){if(!data.fill){data.fill=colors[i]}})}else if(!config.color){var safeBaseColors=Array.isArray(baseColors)?baseColors:[];if(safeBaseColors.length>0){config.color=safeBaseColors[Math.floor(Math.random()*safeBaseColors.length)]}}var totalDataPoints=0;if(chartType==="bar"||chartType==="line"||chartType==="scatter"||chartType==="histogram"||chartType==="beeswarm"){var _safeChartData=Array.isArray(effectiveChartData)?effectiveChartData:[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];if(chartType==="bar"){totalDataPoints=_safeChartData.length*Math.max(1,safeDataKeys.length)}else{totalDataPoints=_safeChartData.length}}var getScrollableWidth=function getScrollableWidth(){if(chartType==="line"){return totalDataPoints*20}if(chartType==="bar"){return totalDataPoints*20+(Array.isArray(config.dataKeys)?config.dataKeys.length:0)*8*(Array.isArray(chartData)?chartData.length:0)+(Array.isArray(chartData)?chartData.length:0)*15}return 800};var scrollWidth=getScrollableWidth();var shouldScroll=(chartType==="bar"||chartType==="line"||chartType==="beeswarm"||chartType==="histogram"||chartType==="scatter")&&totalDataPoints>15&&scrollWidth>containerWidth;var adjustedHeight=250;var angle=config.angle?config.angle:0;var radian=Math.abs(angle)*(Math.PI/180);if(chartType==="bar"&&chartData&&Array.isArray(chartData)&&config.angle){var maxLabelLength=chartData.reduce(function(max,item){var label=String(item[config.xAxis]||"");return Math.max(max,Math.min(label.length,28))},0);var multiplier=Math.floor(Math.max(Math.sin(radian),0.3)*5);var axisHeight=40+maxLabelLength*multiplier;adjustedHeight=250+axisHeight}var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=(attributes.interactionApiInProgress||attributes.loading)&&!hasError&&!hasMissing;var ChartWrapper=function ChartWrapper(_ref9){var children=_ref9.children;if(shouldScroll){return/*#__PURE__*/_jsx("div",{className:"w-full overflow-x-auto",children:/*#__PURE__*/_jsx("div",{style:{minWidth:scrollWidth+"px",height:adjustedHeight+"px"},children:children})})}return/*#__PURE__*/_jsx("div",{className:"w-full",style:{height:adjustedHeight+"px"},children:children})};var chartUi=isLoading?/*#__PURE__*/_jsx(ChartLoader,{}):hasError||hasMissing||!effectiveChartData?renderNoDataFallback():/*#__PURE__*/_jsx(ChartWrapper,{children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:config,className:mergedClasses,style:{height:adjustedHeight+"px"},children:renderChartComponent(chartType,effectiveChartData,config)}))});return/*#__PURE__*/_jsxs(Card,{className:"shadow border mt-2 mb-2 relative",children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{ref:containerRef,"data-slot":"bodyContent",className:"px-6",style:{minHeight:"250px"},children:chartUi}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]})}export function renderTable(props){var _attributes$isEditabl3;var gjsModel=props.gjsModel,_props$performInterac3=props.performInteraction,performInteraction=_props$performInterac3===void 0?function(){}:_props$performInterac3,_props$isTemplateView4=props.isTemplateView,isTemplateView=_props$isTemplateView4===void 0?false:_props$isTemplateView4,rest=_objectWithoutPropertiesLoose(props,_excluded4);// Memoize filtered props to avoid re-filtering on every render
|
|
12
|
-
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState11=useState(initialData),allData=_useState11[0],setAllData=_useState11[1];var cardRef=useRef(null);var _useState12=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState12[0],setAttributes=_useState12[1];var isEditable=(_attributes$isEditabl3=attributes.isEditable)!=null?_attributes$isEditabl3:false;var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$title2=allData.title,title=_allData$title2===void 0?"Title":_allData$title2,_allData$subTitle2=allData.subTitle,subTitle=_allData$subTitle2===void 0?"Subtitle":_allData$subTitle2,_allData$actions=allData.actions,actions=_allData$actions===void 0?[]:_allData$actions,pagination=allData.pagination,sampleData=allData.sampleData;var effectiveRawData=isTemplateView&&sampleData!==undefined?sampleData:rawData;var data=Array.isArray(effectiveRawData)?effectiveRawData:[];var headerMapper=function(){var cleaned=_extends({},rawHeaderMapper);if("id"in cleaned){delete cleaned.id}if(data.length>0){var dataKeys=Object.keys(data[0]||{});return Object.fromEntries(Object.entries(cleaned).filter(function(_ref10){var key=_ref10[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref12){var _ref11=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref11.sortColumn,sortDirection=_ref11.sortDirection;return sortColumn&&sortDirection?(_ref12={},_ref12[sortColumn]=sortDirection,_ref12):{}}();var _useState13=useState(0),viewportWidth=_useState13[0],setViewportWidth=_useState13[1];var _useState14=useState(250),scrollAreaHeight=_useState14[0],setScrollAreaHeight=_useState14[1];var calculateTableHeight=function calculateTableHeight(tableWidth,rowCount){if(viewportWidth>0){var _gjsModel$collection;var widthRatio=tableWidth/viewportWidth;var baseTableHeight=250;var targetScrollAreaHeight=baseTableHeight;if(widthRatio>=0.8){var headerHeight=48;var rowHeight=40;var calculatedHeight=headerHeight+rowCount*rowHeight;targetScrollAreaHeight=Math.min(calculatedHeight,baseTableHeight)}var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection=gjsModel.collection)==null?void 0:_gjsModel$collection.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(tableElement){var headerElement=tableElement.querySelector("[data-slot=\"card-header\"]");if(headerElement&&headerElement.offsetHeight>0){var actualHeaderHeight=headerElement.offsetHeight;var standardHeaderHeight=58;var heightDifference=actualHeaderHeight-standardHeaderHeight;if(heightDifference>0){targetScrollAreaHeight=targetScrollAreaHeight-heightDifference}}}setScrollAreaHeight(targetScrollAreaHeight)}};useEffect(function(){var updateViewportWidth=function updateViewportWidth(){var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;var iframeDocument=iframeWindow==null?void 0:iframeWindow.document;if(iframeDocument){var dashboardRoot=iframeDocument.getElementById("dashboard-root");var effectiveViewportWidth=(dashboardRoot==null?void 0:dashboardRoot.clientWidth)||iframeDocument.documentElement.clientWidth;setViewportWidth(effectiveViewportWidth)}};updateViewportWidth();window.addEventListener("resize",updateViewportWidth);var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;if(iframeWindow){iframeWindow.addEventListener("resize",updateViewportWidth)}return function(){window.removeEventListener("resize",updateViewportWidth);if(iframeWindow){iframeWindow.removeEventListener("resize",updateViewportWidth)}}},[]);useEffect(function(){var updateTableWidthAndApplyCSS=function updateTableWidthAndApplyCSS(){var _gjsModel$collection2;var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection2=gjsModel.collection)==null?void 0:_gjsModel$collection2.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(!tableElement&&window.parent!==window){tableElement=window.parent.document.querySelector("[data-table-id=\""+tableId+"\"]")}if(!tableElement){return}var tableActualWidth=tableElement.getBoundingClientRect().width;if(tableActualWidth>0){calculateTableHeight(tableActualWidth,Array.isArray(data)?data.length:0)}};var timeoutId=setTimeout(updateTableWidthAndApplyCSS,150);window.addEventListener("resize",updateTableWidthAndApplyCSS);return function(){clearTimeout(timeoutId);window.removeEventListener("resize",updateTableWidthAndApplyCSS)}},[allData,gjsModel,viewportWidth,data,calculateTableHeight]);useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var parsedData=function(){if(typeof data==="object"&&data!==null&&!Array.isArray(data)&&data.name==="__peak_placeholder"){return[]}if(!Array.isArray(data)){return[]}return data.map(function(datum){var newData=_extends({},datum);delete newData.id;return newData})}();function onRowAction(_x,_x2){return _onRowAction.apply(this,arguments)}function _onRowAction(){_onRowAction=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(rowIndex,actionId){var id;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:id=gjsModel.get("id");_context.next=3;return performInteraction({id:actionId,interactionType:"tableButton",payload:{row:data[rowIndex],tableId:id},affectedComponents:[]});case 3:case"end":return _context.stop()}},_callee)}));return _onRowAction.apply(this,arguments)}function onPageChange(_x3,_x4){return _onPageChange.apply(this,arguments)}function _onPageChange(){_onPageChange=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(pageNumber,pageSize){var _gjsModel$get2;var id,_ref13,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:id=gjsModel.get("id");_ref13=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref13.sortColumn,sortDirection=_ref13.sortDirection;_context2.next=4;return performInteraction({id:id,interactionType:"pagination",payload:_extends({pageNumber:pageNumber,pageSize:pageSize},sortColumn&&sortDirection&&{sortColumn:sortColumn,sortDirection:sortDirection}),affectedComponents:getAffectedComponentsWithLoader([id],true)});case 4:case"end":return _context2.stop()}},_callee2)}));return _onPageChange.apply(this,arguments)}function handleSort(_x5,_x6){return _handleSort.apply(this,arguments)}function _handleSort(){_handleSort=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(column,direction){var currentProps,id;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:currentProps=gjsModel.get("componentProps");id=gjsModel.get("id");gjsModel.set("componentProps",_extends({},currentProps,{sortColumn:direction?column:null,sortDirection:direction}));_context3.next=5;return performInteraction({id:id,interactionType:"tableSort",payload:{sortColumn:direction?column:null,sortDirection:direction,tableId:id},affectedComponents:getAffectedComponentsWithLoader([id],true)});case 5:case"end":return _context3.stop()}},_callee3)}));return _handleSort.apply(this,arguments)}return/*#__PURE__*/_jsxs(Card,{ref:cardRef,className:"shadow border relative flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-1 flex flex-col overflow-hidden",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing?renderNoDataFallback():/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:attributes.interactionApiInProgress||attributes.loading,onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,otherProps:rest,height:scrollAreaHeight})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",tableActions:actions,firstRowData:Array.isArray(data)&&data.length>0?data[0]:{},isVisible:isEditable,componentProps:allData})]})}export function renderTab(props){var tabsWidth=157;var safeTabs=Array.isArray(props.tabs)?props.tabs:[];var showFallback=safeTabs.length===0;if(safeTabs.length>4){tabsWidth=157}var defaultValue=props.defaultValue||(safeTabs.length>0?safeTabs[0]:undefined);useEffect(function(){if(props.gjsModel){var componentId=props.gjsModel.get("id");var childrenCount=props.gjsModel.components().length;if(safeTabs.length>0&&childrenCount===0){// eslint-disable-next-line no-console
|
|
13
|
-
console.warn("Tab component "+componentId+" has "+safeTabs.length+" tabs but no child components. This may indicate lost tab content.")}}},[safeTabs.length,props.gjsModel]);return/*#__PURE__*/_jsxs(Tabs,{defaultValue:defaultValue,children:[/*#__PURE__*/_jsx("div",{className:"text-center mb-4",children:/*#__PURE__*/_jsx(TabsList,{className:"bg-[#F9F9FE] border border-[#D4D5DE] p-1 rounded-lg h-auto",children:safeTabs.length>0?safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsTrigger,{value:tab,className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},children:tab},tab)}):/*#__PURE__*/_jsx(TabsTrigger,{value:"no-data",className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},disabled:true,children:"No tabs"})})}),showFallback?/*#__PURE__*/_jsx(TabsContent,{value:defaultValue||"no-data",className:"tabs-content","data-fallback":"true",children:renderNoDataFallback()}):safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsContent,{value:tab,className:"tabs-content"},tab)})]})}export function renderMarkdown(props){var _attributes$isEditabl4;var gjsModel=props.gjsModel,_props$isTemplateView5=props.isTemplateView,isTemplateView=_props$isTemplateView5===void 0?false:_props$isTemplateView5,rest=_objectWithoutPropertiesLoose(props,_excluded5);// Memoize filtered props to avoid re-filtering on every render
|
|
12
|
+
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState11=useState(initialData),allData=_useState11[0],setAllData=_useState11[1];var cardRef=useRef(null);var _useState12=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState12[0],setAttributes=_useState12[1];var isEditable=(_attributes$isEditabl3=attributes.isEditable)!=null?_attributes$isEditabl3:false;var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$title2=allData.title,title=_allData$title2===void 0?"Title":_allData$title2,_allData$subTitle2=allData.subTitle,subTitle=_allData$subTitle2===void 0?"Subtitle":_allData$subTitle2,_allData$actions=allData.actions,actions=_allData$actions===void 0?[]:_allData$actions,pagination=allData.pagination,sampleData=allData.sampleData;var effectiveRawData=isTemplateView&&sampleData!==undefined?sampleData:rawData;var data=Array.isArray(effectiveRawData)?effectiveRawData:[];var headerMapper=function(){var cleaned=_extends({},rawHeaderMapper);if("id"in cleaned){delete cleaned.id}if(data.length>0){var dataKeys=Object.keys(data[0]||{});return Object.fromEntries(Object.entries(cleaned).filter(function(_ref10){var key=_ref10[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref12){var _ref11=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref11.sortColumn,sortDirection=_ref11.sortDirection;return sortColumn&&sortDirection?(_ref12={},_ref12[sortColumn]=sortDirection,_ref12):{}}();var _useState13=useState(0),viewportWidth=_useState13[0],setViewportWidth=_useState13[1];var _useState14=useState(250),scrollAreaHeight=_useState14[0],setScrollAreaHeight=_useState14[1];var calculateTableHeight=function calculateTableHeight(tableWidth,rowCount){if(viewportWidth>0){var _gjsModel$collection;var widthRatio=tableWidth/viewportWidth;var baseTableHeight=250;var targetScrollAreaHeight=baseTableHeight;if(widthRatio>=0.8){var headerHeight=48;var rowHeight=40;var calculatedHeight=headerHeight+rowCount*rowHeight;targetScrollAreaHeight=Math.min(calculatedHeight,baseTableHeight)}var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection=gjsModel.collection)==null?void 0:_gjsModel$collection.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(tableElement){var headerElement=tableElement.querySelector("[data-slot=\"card-header\"]");if(headerElement&&headerElement.offsetHeight>0){var actualHeaderHeight=headerElement.offsetHeight;var standardHeaderHeight=58;var heightDifference=actualHeaderHeight-standardHeaderHeight;if(heightDifference>0){targetScrollAreaHeight=targetScrollAreaHeight-heightDifference}}}setScrollAreaHeight(targetScrollAreaHeight)}};useEffect(function(){var updateViewportWidth=function updateViewportWidth(){var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;var iframeDocument=iframeWindow==null?void 0:iframeWindow.document;if(iframeDocument){var dashboardRoot=iframeDocument.getElementById("dashboard-root");var effectiveViewportWidth=(dashboardRoot==null?void 0:dashboardRoot.clientWidth)||iframeDocument.documentElement.clientWidth;setViewportWidth(effectiveViewportWidth)}};updateViewportWidth();window.addEventListener("resize",updateViewportWidth);var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;if(iframeWindow){iframeWindow.addEventListener("resize",updateViewportWidth)}return function(){window.removeEventListener("resize",updateViewportWidth);if(iframeWindow){iframeWindow.removeEventListener("resize",updateViewportWidth)}}},[]);useEffect(function(){var updateTableWidthAndApplyCSS=function updateTableWidthAndApplyCSS(){var _gjsModel$collection2;var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection2=gjsModel.collection)==null?void 0:_gjsModel$collection2.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(!tableElement&&window.parent!==window){tableElement=window.parent.document.querySelector("[data-table-id=\""+tableId+"\"]")}if(!tableElement){return}var tableActualWidth=tableElement.getBoundingClientRect().width;if(tableActualWidth>0){calculateTableHeight(tableActualWidth,Array.isArray(data)?data.length:0)}};var timeoutId=setTimeout(updateTableWidthAndApplyCSS,150);window.addEventListener("resize",updateTableWidthAndApplyCSS);return function(){clearTimeout(timeoutId);window.removeEventListener("resize",updateTableWidthAndApplyCSS)}},[allData,gjsModel,viewportWidth,data,calculateTableHeight]);useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var parsedData=function(){if(typeof data==="object"&&data!==null&&!Array.isArray(data)&&data.name==="__peak_placeholder"){return[]}if(!Array.isArray(data)){return[]}return data.map(function(datum){var newData=_extends({},datum);delete newData.id;return newData})}();function onRowAction(_x,_x2){return _onRowAction.apply(this,arguments)}function _onRowAction(){_onRowAction=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(rowIndex,actionId){var id;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:id=gjsModel.get("id");_context.next=3;return performInteraction({id:actionId,interactionType:"tableButton",payload:{row:data[rowIndex],tableId:id},affectedComponents:[]});case 3:case"end":return _context.stop()}},_callee)}));return _onRowAction.apply(this,arguments)}function onPageChange(_x3,_x4){return _onPageChange.apply(this,arguments)}function _onPageChange(){_onPageChange=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(pageNumber,pageSize){var _gjsModel$get2;var id,_ref13,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:id=gjsModel.get("id");_ref13=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref13.sortColumn,sortDirection=_ref13.sortDirection;_context2.next=4;return performInteraction({id:id,interactionType:"pagination",payload:_extends({pageNumber:pageNumber,pageSize:pageSize},sortColumn&&sortDirection&&{sortColumn:sortColumn,sortDirection:sortDirection}),affectedComponents:getAffectedComponentsWithLoader([id],true)});case 4:case"end":return _context2.stop()}},_callee2)}));return _onPageChange.apply(this,arguments)}function handleSort(_x5,_x6){return _handleSort.apply(this,arguments)}function _handleSort(){_handleSort=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(column,direction){var currentProps,id;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:currentProps=gjsModel.get("componentProps");id=gjsModel.get("id");gjsModel.set("componentProps",_extends({},currentProps,{sortColumn:direction?column:null,sortDirection:direction}));_context3.next=5;return performInteraction({id:id,interactionType:"tableSort",payload:{sortColumn:direction?column:null,sortDirection:direction,tableId:id},affectedComponents:getAffectedComponentsWithLoader([id],true)});case 5:case"end":return _context3.stop()}},_callee3)}));return _handleSort.apply(this,arguments)}return/*#__PURE__*/_jsxs(Card,{ref:cardRef,className:"shadow border relative flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-1 flex flex-col overflow-hidden",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing?renderNoDataFallback():/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:attributes.interactionApiInProgress||attributes.loading,onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,otherProps:rest,height:scrollAreaHeight})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",tableActions:actions,firstRowData:Array.isArray(data)&&data.length>0?data[0]:{},isVisible:isEditable,componentProps:allData})]})}export function renderTab(props){var tabsWidth=157;var safeTabs=Array.isArray(props.tabs)?props.tabs:[];var showFallback=safeTabs.length===0;if(safeTabs.length>4){tabsWidth=157}var defaultValue=props.defaultValue||(safeTabs.length>0?safeTabs[0]:undefined);return/*#__PURE__*/_jsxs(Tabs,{defaultValue:defaultValue,children:[/*#__PURE__*/_jsx("div",{className:"text-center mb-4",children:/*#__PURE__*/_jsx(TabsList,{className:"bg-[#F9F9FE] border border-[#D4D5DE] p-1 rounded-lg h-auto",children:safeTabs.length>0?safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsTrigger,{value:tab,className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},children:tab},tab)}):/*#__PURE__*/_jsx(TabsTrigger,{value:"no-data",className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},disabled:true,children:"No tabs"})})}),showFallback?/*#__PURE__*/_jsx(TabsContent,{value:defaultValue||"no-data",className:"tabs-content","data-fallback":"true",children:renderNoDataFallback()}):safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsContent,{value:tab,className:"tabs-content"},tab)})]})}export function renderMarkdown(props){var _attributes$isEditabl4;var gjsModel=props.gjsModel,_props$isTemplateView5=props.isTemplateView,isTemplateView=_props$isTemplateView5===void 0?false:_props$isTemplateView5,rest=_objectWithoutPropertiesLoose(props,_excluded5);// Memoize filtered props to avoid re-filtering on every render
|
|
14
13
|
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState15=useState(initialData),allData=_useState15[0],setAllData=_useState15[1];var _useState16=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState16[0],setAttributes=_useState16[1];var isEditable=(_attributes$isEditabl4=attributes.isEditable)!=null?_attributes$isEditabl4:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var _useState17=useState(false),isEditing=_useState17[0],setIsEditing=_useState17[1];var _useState18=useState(false),isEditingHeading=_useState18[0],setIsEditingHeading=_useState18[1];var editRef=useRef(null);var headingEditRef=useRef(null);var startEditing=function startEditing(){setIsEditing(true);setTimeout(function(){setupEditor()},0)};var startEditingHeading=function startEditingHeading(){setIsEditingHeading(true);setTimeout(function(){setupHeadingEditor()},0)};var setupEditor=function setupEditor(){if(!editRef.current){return}var editor=editRef.current;editor.innerHTML="";var effectiveText=isTemplateView&&allData.sampleData!==undefined?allData.sampleData:allData.summaryText;editor.textContent=effectiveText;editor.focus()};var setupHeadingEditor=function setupHeadingEditor(){if(!headingEditRef.current){return}var editor=headingEditRef.current;editor.innerHTML="";editor.textContent=allData.summaryHeading||"Insights";editor.focus()};// Save changes and exit editing mode
|
|
15
14
|
var saveChanges=function saveChanges(){if(!editRef.current){return}var content=editRef.current.innerText||"";setAllData(function(prev){return _extends({},prev,{summaryText:content})});setIsEditing(false);editRef.current.innerHTML=""};var saveHeadingChanges=function saveHeadingChanges(){if(!headingEditRef.current){return}var content=headingEditRef.current.innerText||"Insights";setAllData(function(prev){return _extends({},prev,{summaryHeading:content})});setIsEditingHeading(false);headingEditRef.current.innerHTML=""};var markdownStyles={ul:{props:{className:"list-disc"}},h1:{props:{className:"text-4xl font-bold leading-[4rem]"}},h2:{props:{className:"text-3xl font-bold leading-[3rem]"}},h3:{props:{className:"text-2xl font-bold leading-[2rem]"}},h4:{props:{className:"text-xl font-bold leading-[2.5rem]"}},h5:{props:{className:"text-lg font-bold leading-[2.5rem]"}},h6:{props:{className:"text-base font-bold leading-[2rem]"}}};var summaryText=allData.summaryText,summaryHeading=allData.summaryHeading,sampleData=allData.sampleData;var rawSummaryText=isTemplateView&&sampleData!==undefined?sampleData:summaryText;var effectiveSummaryText=typeof rawSummaryText==="string"?rawSummaryText:"";var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=attributes.loading&&!hasError&&!hasMissing||attributes.interactionApiInProgress;if(isLoading){return/*#__PURE__*/_jsx(MarkdownLoader,{})}if(hasError||hasMissing){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:summaryHeading||"Insights"}),/*#__PURE__*/_jsxs("div",{className:"w-full py-8 flex flex-col items-center justify-center px-6 text-center",style:{minHeight:"180px"},children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-12 h-12 text-gray-400 mb-2"}),/*#__PURE__*/_jsx("h3",{className:"text-lg font-medium text-gray-900",children:"No data available"}),/*#__PURE__*/_jsx("p",{className:"mt-2 text-sm text-gray-500 max-w-md",children:"Check your filters or try a different time range."})]}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}if(!isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:summaryHeading||"Insights"}),/*#__PURE__*/_jsx("div",{"data-slot":"summaryText",children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:effectiveSummaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em] relative"},rest,{children:[isEditingHeading?/*#__PURE__*/_jsx("div",{ref:headingEditRef,contentEditable:true,onBlur:saveHeadingChanges,"data-slot":"summaryHeading",className:"text-xl font-semibold text-left",suppressContentEditableWarning:true}):/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",onClick:startEditingHeading,"data-slot":"summaryHeading",children:allData.summaryHeading||"Insights"}),isEditing?/*#__PURE__*/_jsx("div",{ref:editRef,contentEditable:true,onBlur:saveChanges,"data-slot":"summaryText",className:"p-2 min-h-[100px] whitespace-pre-wrap",suppressContentEditableWarning:true,style:{whiteSpace:"pre-wrap",wordWrap:"break-word"}}):/*#__PURE__*/_jsx("div",{onClick:startEditing,"data-slot":"summaryText",style:{whiteSpace:"pre-wrap",wordWrap:"break-word"},children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:effectiveSummaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}export function renderButton(props){var _attributes$isEditabl5;var gjsModel=props.gjsModel,_props$performInterac4=props.performInteraction,performInteraction=_props$performInterac4===void 0?function(){}:_props$performInterac4;var _useState19=useState(_extends({},props)),allData=_useState19[0],setAllData=_useState19[1];var _useState20=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState20[0],setAttributes=_useState20[1];var isEditable=(_attributes$isEditabl5=attributes.isEditable)!=null?_attributes$isEditabl5:false;useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(_extends({},gjsModel.get("componentProps")))})},[]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var text=allData.text,className=allData.className,payload=allData.payload,_allData$variant=allData.variant,variant=_allData$variant===void 0?"default":_allData$variant,_allData$size=allData.size,size=_allData$size===void 0?"sm":_allData$size,affectedComponents=allData.affectedComponents,tooltipContent=allData.tooltipContent;function interact(){var id=gjsModel.get("id");performInteraction({id:id,interactionType:"button",affectedComponents:getAffectedComponentsWithLoader([id].concat(affectedComponents),true),payload:payload})}return/*#__PURE__*/_jsx(TooltipButton,{className:className,isEditable:isEditable,interact:interact,attributes:attributes,variant:variant,size:size,text:text,tooltipContent:tooltipContent})}var renderActionCardWithWrapper=function renderActionCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"ActionCard"}),children:renderActionCard(props)})};var renderButtonWithWrapper=function renderButtonWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Button"}),children:renderButton(props)})};var renderCardWithWrapper=function renderCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Card"}),children:renderCard(props)})};var renderChartWithWrapper=function renderChartWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Chart"}),children:renderChart(props)})};var renderFilterWithWrapper=function renderFilterWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Filter"}),children:renderFilter(props)})};var renderMarkdownWithWrapper=function renderMarkdownWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Markdown"}),children:renderMarkdown(props)})};var renderSearchWithWrapper=function renderSearchWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Search"}),children:renderSearch(props)})};var renderTableWithWrapper=function renderTableWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Table"}),children:renderTable(props)})};var renderTabWithWrapper=function renderTabWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Tabs"}),children:renderTab(props)})};function renderActions(props){var actions=props.actions,_props$isEditable=props.isEditable,isEditable=_props$isEditable===void 0?false:_props$isEditable,gjsModel=props.gjsModel;if(actions===null){return/*#__PURE__*/_jsx("div",{})}if(!Array.isArray(actions)||actions.length===0){return/*#__PURE__*/_jsx("div",{className:"bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none relative",children:/*#__PURE__*/_jsx(CardLoader,{})})}return/*#__PURE__*/_jsx("div",{className:"dashboard-cards flex flex-wrap gap-4",children:actions.map(function(action,index){var icon=action.icon,title=action.title,description=action.description;return/*#__PURE__*/_jsx("div",{className:"flex-1 min-w-[200px]",children:renderActionCard({icon:icon,headerContent:title,bodyContent:description,isEditable:isEditable,gjsModel:gjsModel})},index)})})}var renderActionsWithWrapper=function renderActionsWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Actions"}),children:renderActions(props)})};export function getRenderers(){return{ActionCard:renderActionCardWithWrapper,Actions:renderActionsWithWrapper,Button:renderButtonWithWrapper,Card:renderCardWithWrapper,Chart:renderChartWithWrapper,Filter:renderFilterWithWrapper,Markdown:renderMarkdownWithWrapper,Search:renderSearchWithWrapper,Table:renderTableWithWrapper,Tabs:renderTabWithWrapper}}
|
|
16
15
|
//# sourceMappingURL=render-components.js.map
|