@peak-ai/canvas 1.4.49 → 1.4.50
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 +6 -6
- package/GrapesjsCanvas.js.map +1 -1
- package/package.json +1 -1
- package/plugins/grapejs-plugin.d.ts +1 -1
- package/plugins/grapejs-plugin.js +2 -2
- package/plugins/grapejs-plugin.js.map +1 -1
- package/plugins/helpers/render-components.js +1 -1
- package/plugins/helpers/render-components.js.map +1 -1
package/GrapesjsCanvas.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import
|
|
2
|
-
import grapesjs from"grapesjs";import"grapesjs/dist/css/grapes.min.css";import tailwind from"grapesjs-tailwind";import{TypesToRegister}from"./constants";import{toKebabCase}from"./helpers";import{tailwindCompiledCss}from"./helpers/css";import{datePickerCss}from"./helpers/date-picker";import{createGrapesjsShadcnGenericPlugin}from"./plugins/grapejs-plugin";import{StyledEditor}from"./index.styles";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";function setComponentProperties(editor,isPreview){function setPropertiesRecursively(comp){comp.set({editable
|
|
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;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
|
|
3
3
|
}:_ref2$newDataNotifier,_ref2$setHasChanged=_ref2.setHasChanged,setHasChanged=_ref2$setHasChanged===void 0?function(){// no op
|
|
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
|
|
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
|
|
5
5
|
// This ensures placeholder values are properly cleared and don't cause stale data issues
|
|
6
6
|
var filteredProps=_extends({},newProps);Object.keys(filteredProps).forEach(function(key){var value=filteredProps[key];if(value&&typeof value==="object"&&value.name==="__peak_placeholder"){filteredProps[key]=null}});var parsedNewProps=_extends({},filteredProps);if(filteredProps.pagination){parsedNewProps.pagination=_extends({},model.get("componentProps").pagination||{},filteredProps.pagination)}// Handle Actions component: expand into ActionCards when data arrives via streaming
|
|
7
|
-
var isActionsComponent=model.get("componentName")==="Actions";var hasValidActionsData=parsedNewProps.actions&&parsedNewProps.actions!==null&&Array.isArray(parsedNewProps.actions)&&parsedNewProps.actions.length>0;if(isActionsComponent&&hasValidActionsData){var _model$components$at;var isAlreadyExpanded=model.components().length>0&&((_model$components$at=model.components().at(0))==null?void 0:_model$components$at.get("componentName"))==="ActionCard";if(!isAlreadyExpanded){expandActionsComponent(model,parsedNewProps.actions);return true}}model.set("componentProps",_extends({},model.get("componentProps"),parsedNewProps));model.set("attributes",_extends({},model.get("attributes"),newAttributes));return true}useEffect(function(){newDataNotifier(notificationHandler)},[]);function performInteractionWrapper(
|
|
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)],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.
|
|
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
|
|
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
|
|
9
9
|
// So, adding them from here!
|
|
10
|
-
editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var canvasDoc,canvasHead,style,fullCss;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:canvasDoc=editor.Canvas.getDocument();canvasHead=canvasDoc.head;if(!canvasHead.querySelector("[data-grapesjs-styles]")){style=canvasDoc.createElement("style");fullCss="\n "+tailwindCompiledCss+"\n "+datePickerCss+"\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");style.setAttribute("data-grapesjs-styles","true");canvasHead.appendChild(style)}isSystemUpdateRef.current=true;_context.
|
|
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;
|
|
11
11
|
//# sourceMappingURL=GrapesjsCanvas.js.map
|
package/GrapesjsCanvas.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","createGrapesjsShadcnGenericPlugin","StyledEditor","jsx","_jsx","jsxs","_jsxs","setComponentProperties","editor","isPreview","setPropertiesRecursively","comp","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","_extends","get","isEditable","attributes","command","components","forEach","runCommand","stopCommand","wrapper","getWrapper","find","convertStyles","stylesArray","map","block","selectors","Array","isArray","join","declarations","Object","entries","style","_ref","prop","value","createActionCardConfig","action","icon","title","description","type","componentName","componentProps","headerContent","bodyContent","expandActions","node","_node$componentProps","actions","length","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","isStreaming","_ref2$isModeChangeFro","isModeChangeFromToggle","_ref2$isTemplateView","isTemplateView","editorRef","editorInstance","isStreamingRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","_React$useState","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","_x","_performInteractionWrapper","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee4","payload","_editorInstance$curre3","updatedJson","apiResponse","componentUpdates","wrap","_callee4$","_context4","prev","next","store","sent","affectedComponents","_ref6","error","isMissing","abrupt","t0","errorMessage","Error","message","finish","stop","destroy","currentMode","init","container","height","plugins","storageManager","richTextEditor","canvas","customBadgeLabel","tagName","injectionAttempts","injectStylesEarly","_editor$Canvas","iframeDoc","Canvas","getDocument","head","querySelector","createElement","fullCss","innerHTML","setAttribute","appendChild","requestAnimationFrame","checkDirty","_checkDirty","_callee2","stored","newJson","_callee2$","_context2","JSON","stringify","debouncedCheckDirty","timeout","clearTimeout","setTimeout","evt","on","includes","_callee","canvasDoc","canvasHead","_callee$","_context","t1","call","_ref4","DomComponents","getType","addType","defaults","view","cleanup","_json$pages","_json$pages$0$frames","pages","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 } 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 setComponentProperties(editor: Editor, isPreview: boolean) {\n function setPropertiesRecursively(comp: Component) {\n comp.set({\n editable: !isPreview,\n draggable: !isPreview,\n droppable: !isPreview && comp.getName() !== 'Shadcn-generic',\n selectable: !isPreview,\n hoverable: !isPreview,\n highlightable: !isPreview,\n copyable: false,\n resizable: false,\n removable: !isPreview,\n badgable: false,\n });\n\n comp.set('attributes', {\n ...(comp.get('attributes') || {}),\n isEditable: !isPreview,\n });\n\n if (!isPreview) {\n comp.set('toolbar', [\n { attributes: { class: 'fa fa-arrows' }, command: 'tlb-move' },\n { attributes: { class: 'fa fa-trash' }, command: 'tlb-delete' },\n ]);\n }\n\n comp.components().forEach(setPropertiesRecursively);\n }\n\n if (isPreview) {\n editor.runCommand('core:preview');\n } else {\n editor.stopCommand('core:preview');\n }\n\n const wrapper = editor.getWrapper();\n wrapper?.find('*').forEach(setPropertiesRecursively);\n}\n\nfunction convertStyles(stylesArray: any[]): string {\n return stylesArray\n .map((block) => {\n const selectors = Array.isArray(block.selectors)\n ? block.selectors.join(', ')\n : block.selectors;\n const declarations = Object.entries(block.style)\n .map(([prop, value]) => `${toKebabCase(prop)}: ${value};`)\n .join(' ');\n\n return `${selectors} { ${declarations} }`;\n })\n .join('\\n');\n}\n\nfunction createActionCardConfig(action: any): any {\n const { icon, title, description } = action;\n\n return {\n type: 'shadcn-generic',\n componentName: 'ActionCard',\n badgable: false,\n copyable: false,\n removable: true,\n draggable: true,\n componentProps: {\n icon,\n headerContent: title,\n bodyContent: description,\n },\n };\n}\n\nfunction expandActions(node: any): any {\n if (node.type === 'shadcn-generic' && node.componentName === 'Actions') {\n const actions = node.componentProps?.actions;\n\n if (Array.isArray(actions) && actions.length > 0) {\n return {\n ...node,\n type: 'div',\n classes: ['dashboard-cards', ...(node.classes || [])],\n componentName: undefined,\n componentProps: undefined,\n components: actions.map((action: any, i: number) => ({\n ...createActionCardConfig(action),\n id: `${node.id}--action-card-${i}`,\n })),\n };\n }\n\n return node;\n }\n\n if (Array.isArray(node.components)) {\n return {\n ...node,\n components: node.components.map(expandActions),\n };\n }\n\n return node;\n}\n\nfunction setInteracting(\n renderedComponents: Record<string, Component>,\n components: { componentId: string; showLoader: boolean }[],\n inProgress: boolean,\n) {\n components.forEach((component) => {\n const { componentId, showLoader } = component;\n\n if (!showLoader) {\n return;\n }\n\n const gjsModel = renderedComponents[componentId];\n\n if (gjsModel) {\n gjsModel.set('attributes', {\n ...gjsModel.get('attributes'),\n interactionApiInProgress: inProgress,\n });\n }\n });\n}\n\nfunction expandActionsComponent(model: Component, actions: any[]): void {\n model.components('');\n\n actions.forEach((action: any) => {\n model.append(createActionCardConfig(action));\n });\n\n model.set('type', 'div');\n model.addClass('dashboard-cards');\n model.set('componentName', undefined);\n model.set('componentProps', {});\n}\n\nfunction GrapesjsCanvas({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n newDataNotifier = () => {\n // no op\n },\n setHasChanged = () => {\n // no op\n },\n isStreaming,\n 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] = React.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) {\n expandActionsComponent(model, parsedNewProps.actions);\n\n return true;\n }\n }\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...parsedNewProps,\n });\n\n model.set('attributes', {\n ...model.get('attributes'),\n ...newAttributes,\n });\n\n return true;\n }\n\n useEffect(() => {\n newDataNotifier(notificationHandler);\n }, []);\n\n async function performInteractionWrapper(payload: Record<string, any>) {\n const updatedJson = await editorInstance.current?.store();\n setInteracting(renderedComponents.current, payload.affectedComponents, true);\n\n try {\n const apiResponse = await performInteraction({\n ...payload,\n json: updatedJson,\n });\n\n const componentUpdates = apiResponse || {};\n\n Object.entries(componentUpdates).forEach(([key, value]) => {\n const model = renderedComponents.current[key];\n\n if (model) {\n model.set('attributes', {\n ...model.get('attributes'),\n error: undefined,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...value,\n error: undefined,\n isMissing: undefined,\n });\n }\n });\n\n return componentUpdates;\n } catch (error) {\n payload.affectedComponents.forEach((componentId: string) => {\n const model = renderedComponents.current[componentId];\n\n if (model) {\n const errorMessage =\n error instanceof Error ? error.message : 'Something went wrong. Please try again.';\n\n model.set('attributes', {\n ...model.get('attributes'),\n error: errorMessage,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n error: errorMessage,\n isMissing: undefined,\n });\n }\n });\n\n throw error;\n } finally {\n setInteracting(renderedComponents.current, payload.affectedComponents, false);\n }\n }\n\n useEffect(() => {\n if (!editorRef.current) {\n return () => {\n // no op\n };\n }\n\n if (editorInstance.current) {\n editorInstance.current.destroy();\n editorInstance.current = null;\n isEditorAliveRef.current = false;\n }\n\n const currentMode = mode;\n\n const editor = grapesjs.init({\n container: editorRef.current,\n height: '100%',\n plugins: [\n tailwind,\n createGrapesjsShadcnGenericPlugin(\n currentMode,\n performInteractionWrapper,\n renderedComponents.current,\n setHasChanged,\n isTemplateView,\n ),\n ],\n storageManager: { type: 'none' },\n richTextEditor: {\n actions: ['bold', 'italic', 'underline', 'strikethrough'],\n },\n canvas: {\n customBadgeLabel: (component) => {\n const tagName = component.get('tagName');\n\n return tagName === 'body' ? '' : tagName || '';\n },\n },\n });\n\n isEditorAliveRef.current = true;\n\n let injectionAttempts = 0;\n\n function injectStylesEarly() {\n const iframeDoc = editor.Canvas?.getDocument?.();\n\n if (iframeDoc && iframeDoc.head) {\n if (!iframeDoc.head.querySelector('[data-grapesjs-styles]')) {\n const style = iframeDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n iframeDoc.head.appendChild(style);\n }\n } else if (injectionAttempts < 50) {\n injectionAttempts += 1;\n requestAnimationFrame(injectStylesEarly);\n }\n }\n\n requestAnimationFrame(injectStylesEarly);\n\n async function checkDirty() {\n if (isStreamingRef.current || isSystemUpdateRef.current) {\n return;\n }\n\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n let stored = null;\n\n try {\n stored = await editorInstance.current.store();\n } catch (err) {\n return;\n }\n\n if (!stored) {\n return;\n }\n\n const newJson = JSON.stringify(stored);\n\n if (newJson !== lastJsonRef.current) {\n setHasChanged(true);\n lastJsonRef.current = newJson;\n }\n }\n\n const debouncedCheckDirty = (() => {\n let timeout: NodeJS.Timeout | null = null;\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(checkDirty, 200);\n };\n })();\n\n [\n 'component:add',\n 'component:remove',\n 'component:update:content',\n 'style:update',\n 'component:drag:end',\n 'rte:change',\n ].forEach((evt) => {\n editor.on(evt, debouncedCheckDirty);\n });\n\n editor.on('component:update', (model, prop) => {\n if (['attributes', 'componentProps', 'content'].includes(prop)) {\n debouncedCheckDirty();\n }\n });\n\n // Tailwind CSS rules aren't fully added to our component\n // So, adding them from here!\n editor.on('load', async () => {\n const canvasDoc = editor.Canvas.getDocument();\n const canvasHead = canvasDoc.head;\n\n if (!canvasHead.querySelector('[data-grapesjs-styles]')) {\n const style = canvasDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n canvasHead.appendChild(style);\n }\n\n isSystemUpdateRef.current = true;\n lastJsonRef.current = JSON.stringify(await editor.store());\n isSystemUpdateRef.current = false;\n });\n\n editorInstance.current = editor;\n\n if (setEditor) {\n setEditor(editor);\n }\n\n TypesToRegister.forEach(({ type, tagName }) => {\n if (!editor.DomComponents.getType(type)) {\n editor.DomComponents.addType(type, {\n model: {\n defaults: { tagName },\n },\n view: {},\n });\n }\n });\n\n 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 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 setTimeout(async () => {\n if (editorInstance.current) {\n lastJsonRef.current = JSON.stringify(await editorInstance.current.store());\n isSystemUpdateRef.current = false;\n }\n }, 100);\n }\n }, [json]);\n\n useEffect(() => {\n if (mode && editorInstance.current) {\n isSystemUpdateRef.current = true;\n\n if(isModeChangeFromToggle){\n setIsTransitioning(true);\n }\n\n setTimeout(() => {\n setComponentProperties(editorInstance.current as Editor, mode === 'preview');\n\n setTimeout(() => {\n isSystemUpdateRef.current = false;\n setIsTransitioning(false);\n }, 50);\n }, 0);\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,KAAQ,OAAO,CAChD;AACA,MAAO,CAAAC,QAAQ,KAA6B,UAAU,CACtD,MAAO,kCAAkC,CACzC,MAAO,CAAAC,QAAQ,KAAM,mBAAmB,CAExC,OAASC,eAAe,KAAQ,aAAa,CAC7C,OAASC,WAAW,KAAQ,WAAW,CACvC,OAASC,mBAAmB,KAAQ,eAAe,CACnD,OAASC,aAAa,KAAQ,uBAAuB,CACrD,OAASC,iCAAiC,KAAQ,0BAA0B,CAC5E,OAASC,YAAY,KAAQ,gBAAgB,CAAC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAoB9C,QAAS,CAAAC,sBAAsBA,CAACC,MAAc,CAAEC,SAAkB,CAAE,CAClE,QAAS,CAAAC,wBAAwBA,CAACC,IAAe,CAAE,CACjDA,IAAI,CAACC,GAAG,CAAC,CACPC,QAAQ,CAAE,CAACJ,SAAS,CACpBK,SAAS,CAAE,CAACL,SAAS,CACrBM,SAAS,CAAE,CAACN,SAAS,EAAIE,IAAI,CAACK,OAAO,CAAC,CAAC,GAAK,gBAAgB,CAC5DC,UAAU,CAAE,CAACR,SAAS,CACtBS,SAAS,CAAE,CAACT,SAAS,CACrBU,aAAa,CAAE,CAACV,SAAS,CACzBW,QAAQ,CAAE,KAAK,CACfC,SAAS,CAAE,KAAK,CAChBC,SAAS,CAAE,CAACb,SAAS,CACrBc,QAAQ,CAAE,KACZ,CAAC,CAAC,CAEFZ,IAAI,CAACC,GAAG,CAAC,YAAY,CAAAY,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ACS,OAAO,CAAYtB,IAAI,GAAK,SAAS,CAAC,CAE5E6G,UAAU,CAAC,UAAM,CACf9F,iBAAiB,CAACO,OAAO,CAAG,KAAK,CACjCD,kBAAkB,CAAC,KAAK,CAC1B,CAAC,CAAE,EAAE,CACP,CAAC,CAAE,CAAC,CACN,CACF,CAAC,CAAE,CAACrB,IAAI,CAAES,sBAAsB,CAAC,CAAC,CAElC,mBACE1F,KAAA,CAACd,KAAK,CAAC6O,QAAQ,EAAAC,QAAA,eACblO,IAAA,CAACF,YAAY,GAAE,CAAC,cAChBE,IAAA,QACEmO,GAAG,CAAEpI,SAAU,CACf7B,EAAE,CAAC,iBAAiB,CACpBvB,KAAK,CAAE,CACLyL,OAAO,CAAE7H,eAAe,CAAG,CAAC,CAAG,CAAC,CAChC8H,UAAU,CAAE,2BACd,CAAE,CACH,CAAC,EACY,CAEpB,CAEA,cAAe,CAAAtJ,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,CAAA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9H,SAAS,CAAC,UAAM,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,2 +1,2 @@
|
|
|
1
1
|
import { Editor, Component } from 'grapesjs';
|
|
2
|
-
export declare function createGrapesjsShadcnGenericPlugin(mode: 'editor' | 'preview', performInteraction: (payload: Record<string, any>) => void, renderedComponents: Record<string, Component> | undefined, setHasChanged: (hasChanged: boolean) => void, isTemplateView?: boolean): (editor: Editor) => void;
|
|
2
|
+
export declare function createGrapesjsShadcnGenericPlugin(mode: 'editor' | 'preview', performInteraction: (payload: Record<string, any>) => void, renderedComponents: Record<string, Component> | undefined, setHasChanged: (hasChanged: boolean) => void, isTemplateView?: boolean, isStreaming?: boolean): (editor: Editor) => void;
|
|
@@ -1,5 +1,5 @@
|
|
|
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){if(renderedComponents===void 0){renderedComponents={}}if(isTemplateView===void 0){isTemplateView=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.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
|
|
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"){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
3
|
// eslint-disable-next-line no-inner-declarations
|
|
4
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
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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grapejs-plugin.js","names":["ReactDOM","getRenderers","QueryCacheProvider","jsx","_jsx","createGrapesjsShadcnGenericPlugin","mode","performInteraction","renderedComponents","setHasChanged","isTemplateView","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","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: boolean = 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\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,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O,CAAA/E,IACT,CAAC,CACDgF,MAAM,CAAE,QAAR,CAAAA,MAAMA,CAAA,CAAc,CAClB;AACAtG,QAAQ,CAACuG,sBAAsB,CAAC,IAAI,CAACxC,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,KAA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AAG,GAAI,CAAA2E,aAAa,CAAC,CAC7BlF,KAAK,CAALA,KAAK,CACLsF,MAAM,CAAE,IAAI,CAACA,MAAM,CACnBC,cAAc,CAAE,IAAI,CAACA,cACvB,CAAC,CAAC,CAEF,MAAO,CAAAhF,IACT,CAAC,CACDiF,MAAM,CAAE,QAAR,CAAAA,MAAMA,CAAA,CAAc,CAClB;AACAxG,QAAQ,CAACyG,sBAAsB,CAAC,IAAI,CAACxC,EAAE,CAAC,CAExC,MAAO,KACT,CACF,CACF,CAAC,CACH,CACF","ignoreList":[]}
|
|
@@ -5,7 +5,7 @@ import*as domutil from"recharts/lib/util/DOMUtils";import{Group}from"@visx/group
|
|
|
5
5
|
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";domutil.getOffset=function(el){var html=el.ownerDocument.documentElement;var box={top:0,left:0};if(typeof el.getBoundingClientRect!=="undefined"){box=el.getBoundingClientRect()}var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;return{top:box.top+iframeWindow.pageYOffset-html.clientTop,left:box.left+iframeWindow.pageXOffset-html.clientLeft}};var BEESWARM_CONFIG={RADIUS:4,SPREAD_FACTOR:0.45,RANDOM_FACTOR:2,SIMULATION_ITERATIONS:300,COLLISION_PADDING:3};var baseColors=[[theme.colors.Blue_100,theme.colors.Blue_30],[theme.colors.Purpley_100,theme.colors.Purpley_30],[theme.colors.Light_Bluish_Green,"#06601b"],[theme.colors.Wild_Strawberry,"#4d001c"]];var iconMap={TrendingUp:/*#__PURE__*/_jsx(TrendingUp,{}),TrendingDown:/*#__PURE__*/_jsx(TrendingDown,{}),ShoppingCart:/*#__PURE__*/_jsx(ShoppingCart,{}),Equalizer:/*#__PURE__*/_jsx(ChartBarBig,{}),Style:/*#__PURE__*/_jsx(Tag,{}),Place:/*#__PURE__*/_jsx(MapPin,{})};function getIconFromString(iconString){if(!iconString){return null}if(iconMap[iconString]){return iconMap[iconString]}var lowerIconString=iconString.toLowerCase();var matchingKey=Object.keys(iconMap).find(function(key){return key.toLowerCase()===lowerIconString});if(matchingKey){return iconMap[matchingKey]}return null}function getNColors(n){var colors=[];var safeBaseColors=Array.isArray(baseColors)?baseColors:[];for(var _iterator=_createForOfIteratorHelperLoose(safeBaseColors),_step;!(_step=_iterator()).done;){var baseColor=_step.value;// eslint-disable-next-line import/no-named-as-default-member
|
|
6
6
|
colors.push(chroma.scale(baseColor).mode("lab").colors(n))}function getOneColor(existing){var color=null;do{var base=colors[Math.floor(Math.random()*colors.length)];var selectedColorIndex=Math.floor(Math.random()*base.length);color=base[selectedColorIndex]}while(existing.includes(color));return color}var selectedColors=[];for(var i=0;i<n;i++){selectedColors.push(getOneColor(selectedColors))}return selectedColors}/* TODO: Loader remains */export function renderActionCard(props){var gjsModel=props.gjsModel,_props$isTemplateView=props.isTemplateView,isTemplateView=_props$isTemplateView===void 0?false:_props$isTemplateView,rest=_objectWithoutPropertiesLoose(props,_excluded);// Memoize filtered props to avoid re-filtering on every render
|
|
7
7
|
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState=useState(initialData),allData=_useState[0],setAllData=_useState[1];var _allData$headerConten=allData.headerContent,headerContent=_allData$headerConten===void 0?"Default action card title":_allData$headerConten,icon=allData.icon,_allData$bodyContent=allData.bodyContent,bodyContent=_allData$bodyContent===void 0?"Default body content. Click to edit.":_allData$bodyContent,sampleData=allData.sampleData;var effectiveBodyContent=isTemplateView&&sampleData!==undefined?sampleData:bodyContent;var _useState2=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState2[0],setAttributes=_useState2[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(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var defaultClasses="text-black p-4 rounded-lg shadow border flex flex-col h-full";return/*#__PURE__*/_jsx(Card,_extends({className:defaultClasses+" relative",style:{backgroundColor:"#f9f9fe"},isEditable:false,contentEditable:false},rest,{children:/*#__PURE__*/_jsx(CardContent,{className:"p-0",isEditable:false,contentEditable:false,children:/*#__PURE__*/_jsx("div",{className:"px-4 py-3",children:/*#__PURE__*/_jsxs("div",{className:"flex items-start flex-col",children:[/*#__PURE__*/_jsxs("div",{className:"flex items-center justify-between w-full",children:[/*#__PURE__*/_jsx("div",{className:"text-xl font-semibold",children:headerContent}),/*#__PURE__*/_jsx("div",{className:"text-5xl ml-2 flex items-center","aria-hidden":"true",children:getIconFromString(icon)})]}),/*#__PURE__*/_jsx("div",{className:"w-full mt-1",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing||!effectiveBodyContent?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsx("div",{className:"text-base leading-relaxed",children:effectiveBodyContent})})]})})})}))}export function renderCard(props){var _attributes$isEditabl,_attributes$error,_attributes$isMissing;var gjsModel=props.gjsModel,_props$performInterac=props.performInteraction,performInteraction=_props$performInterac===void 0?function(){return Promise.resolve({})}:_props$performInterac,_props$isTemplateView2=props.isTemplateView,isTemplateView=_props$isTemplateView2===void 0?false:_props$isTemplateView2,rest=_objectWithoutPropertiesLoose(props,_excluded2);// Memoize filtered props to avoid re-filtering on every render
|
|
8
|
-
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState3=useState(initialData),allData=_useState3[0],setAllData=_useState3[1];var headerContent=allData.headerContent,headerDescription=allData.headerDescription,bodyContent=allData.bodyContent,footerContent=allData.footerContent,footerClass=allData.footerClass,footerIcon=allData.footerIcon,contentMetadata=allData.contentMetadata,contentMetadataClass=allData.contentMetadataClass,dataClassName=allData.className,dataError=allData.error,dataIsMissing=allData.isMissing,sampleData=allData.sampleData;function toSafeText(value){if(value===null||value===undefined){return""}return typeof value==="string"?value:JSON.stringify(value)}var safeHeaderContent=toSafeText(headerContent);var safeHeaderDescription=toSafeText(headerDescription);var effectiveBodyContent=isTemplateView&&sampleData!==undefined?sampleData.bodyContent:bodyContent;var safeBodyContent=toSafeText(effectiveBodyContent);var effectiveFooterContent=isTemplateView&&sampleData!==undefined?sampleData.footerContent:footerContent;var safeFooterContent=toSafeText(effectiveFooterContent);var safeContentMetadata=toSafeText(contentMetadata);var _useState4=useState((safeFooterContent==null?void 0:safeFooterContent.length)>0),footerHasContent=_useState4[0],setFooterHasContent=_useState4[1];var _useState5=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState5[0],setAttributes=_useState5[1];var isEditable=(_attributes$isEditabl=attributes.isEditable)!=null?_attributes$isEditabl: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(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);useEffect(function(){setFooterHasContent((safeFooterContent==null?void 0:safeFooterContent.length)>0)},[safeFooterContent]);var defaultClasses="bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none";var defaultFooterClasses=footerHasContent?"text-sm bg-pink-50 text-pink-900 shadow-sm":"text-sm";var defaultContentMetadataClasses="text-xs";var mergedCardClassName=dataClassName?cn(defaultClasses,dataClassName):defaultClasses;var effectiveFooterClass=isTemplateView&&sampleData!==undefined?sampleData.footerClass:footerClass;var mergedFooterClassName=effectiveFooterClass?cn(defaultFooterClasses,effectiveFooterClass):defaultFooterClasses;var mergedContentMetadataClassName=contentMetadataClass?cn(defaultContentMetadataClasses,contentMetadataClass):defaultContentMetadataClasses;var hasError=Boolean((_attributes$error=attributes==null?void 0:attributes.error)!=null?_attributes$error:dataError);var hasMissing=Boolean((_attributes$isMissing=attributes==null?void 0:attributes.isMissing)!=null?_attributes$isMissing:dataIsMissing);var isLoading=Boolean(((attributes==null?void 0:attributes.interactionApiInProgress)||(attributes==null?void 0:attributes.loading))&&!hasError&&!hasMissing);var footerIconText=typeof footerIcon==="string"?footerIcon:footerIcon&&typeof footerIcon==="object"&&"icon"in footerIcon?String(footerIcon.icon):"";function getCardContent(){if(isLoading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}var showEmpty=hasError||hasMissing||!safeBodyContent;function handleFooterInput(event){var target=event.target;var content=target.textContent||"";var hasContent=content.trim().length>0;setFooterHasContent(hasContent);if(!hasContent){var currentProps=gjsModel.get("componentProps");gjsModel.set("componentProps",_extends({},currentProps,{footerContent:null,footerIcon:null,footerClass:null,isEmptied:true}))}}return/*#__PURE__*/_jsxs(React.Fragment,{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":"headerContent",contentEditable:isEditable,className:"text-lg",children:safeHeaderContent}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"headerDescription",contentEditable:isEditable,className:"text-sm",children:safeHeaderDescription})]})})}),showEmpty?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsxs(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-grow",children:[/*#__PURE__*/_jsx("div",{className:"text-3xl font-semibold truncate",children:safeBodyContent}),safeContentMetadata&&/*#__PURE__*/_jsx("div",{className:mergedContentMetadataClassName,style:{color:"#2A44D4"},children:safeContentMetadata})]}),/*#__PURE__*/_jsxs(CardFooter,{"data-slot":"footerContent",contentEditable:isEditable,className:mergedFooterClassName,onInput:handleFooterInput,children:[(footerIconText||"").trim()?/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIconText}):null,safeFooterContent||""]})]})}return/*#__PURE__*/_jsxs(Card,_extends({},rest,{isEditable:false,className:mergedCardClassName+" relative",children:[getCardContent(),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}function transformDataForScatter(data,xAxis,yAxis,dataKeys){if(!data||data.length===0){return[]}var scatterData=data.filter(function(item){return item[xAxis]!==null&&item[xAxis]!==undefined&&item[yAxis]!==null&&item[yAxis]!==undefined}).map(function(item){var _result;var result=(_result={},_result[xAxis]=Number(item[xAxis]),_result[yAxis]=Number(item[yAxis]),_result);if(dataKeys&&dataKeys.length>0){dataKeys.forEach(function(_ref){var key=_ref.key;if(item[key]!==null&&item[key]!==undefined){result[key]=Number(item[key])}})}return result});return scatterData}function binDataForHistogram(data,valueKey,bins){if(bins===void 0){bins=10}if(!data||data.length===0){return[]}var values=data.map(function(item){return Number(item[valueKey])}).filter(function(val){return!isNaN(val)});if(values.length===0){return[]}var min=Math.min.apply(Math,values);var max=Math.max.apply(Math,values);var binWidth=(max-min)/bins;var binsArray=new Array(bins).fill(0);var binLabels=[];for(var i=0;i<bins;i++){var binStart=min+i*binWidth;var binEnd=binStart+binWidth;binLabels.push(binStart.toFixed(1)+"-"+binEnd.toFixed(1))}values.forEach(function(value){var binIndex=Math.floor((value-min)/binWidth);if(binIndex>=bins){binIndex=bins-1}if(binIndex<0){binIndex=0}binsArray[binIndex]+=1});return binLabels.map(function(label,index){return{bin:label,frequency:binsArray[index]}})}function transformDataForBeeswarm(data,groupBy,valueKey){if(!data||data.length===0){return{nodes:[],groups:[]}}var grouped={};data.forEach(function(item){if(item[groupBy]!==null&&item[groupBy]!==undefined&&item[valueKey]!==null&&item[valueKey]!==undefined){var group=String(item[groupBy]);var value=Number(item[valueKey]);if(!isNaN(value)){if(!grouped[group]){grouped[group]=[]}grouped[group].push(value)}}});var groups=Object.keys(grouped).sort();var nodes=[];groups.forEach(function(group,groupIndex){var values=grouped[group];values.forEach(function(value){nodes.push({group:group,groupIndex:groupIndex,value:value,x:groupIndex,y:value,radius:4})})});return{nodes:nodes,groups:groups}}function BeeswarmChart(_ref2){var data=_ref2.data,groups=_ref2.groups,color=_ref2.color,groupBy=_ref2.groupBy,valueKey=_ref2.valueKey;var containerRef=useRef(null);var svgRef=useRef(null);var _useState6=useState({width:800,height:250}),dimensions=_useState6[0],setDimensions=_useState6[1];var _useState7=useState([]),simulatedNodes=_useState7[0],setSimulatedNodes=_useState7[1];var _useTooltip=useTooltip(),tooltipData=_useTooltip.tooltipData,tooltipLeft=_useTooltip.tooltipLeft,tooltipTop=_useTooltip.tooltipTop,tooltipOpen=_useTooltip.tooltipOpen,showTooltip=_useTooltip.showTooltip,hideTooltip=_useTooltip.hideTooltip;useEffect(function(){var updateDimensions=function updateDimensions(){if(containerRef.current){setDimensions({width:containerRef.current.offsetWidth||800,height:250})}};updateDimensions();var resizeObserver=new ResizeObserver(function(entries){for(var _iterator2=_createForOfIteratorHelperLoose(entries),_step2;!(_step2=_iterator2()).done;){var entry=_step2.value;setDimensions({width:entry.contentRect.width||800,height:250})}});if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateDimensions);return function(){resizeObserver.disconnect();window.removeEventListener("resize",updateDimensions)}},[]);var createXScale=useCallback(function(innerWidth,groupDomain){var minBandwidth=60;var totalMinWidth=groupDomain.length*minBandwidth;var paddingRatio=0.3;var xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});if(totalMinWidth>innerWidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}else{xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});var currentBandwidth=xScale.bandwidth();if(currentBandwidth<minBandwidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}}return xScale},[]);var scales=useMemo(function(){if(data.length===0||dimensions.width===0){return null}var margin={top:20,right:20,bottom:60,left:60};var innerWidth=dimensions.width-margin.left-margin.right;var innerHeight=dimensions.height-margin.top-margin.bottom;var values=data.map(function(d){return d.value});var minValue=Math.min.apply(Math,values);var maxValue=Math.max.apply(Math,values);var xScale=createXScale(innerWidth,groups);var yScale=scaleLinear({domain:[minValue,maxValue],range:[innerHeight,0]});return{xScale:xScale,yScale:yScale,minValue:minValue,maxValue:maxValue,innerWidth:innerWidth,innerHeight:innerHeight}},[data,groups,dimensions,createXScale]);useEffect(function(){if(!scales){return}var xScale=scales.xScale,yScale=scales.yScale,minValue=scales.minValue,maxValue=scales.maxValue,innerWidth=scales.innerWidth,innerHeight=scales.innerHeight;var valueRange=maxValue-minValue;var padding=valueRange*0.1;var yScaleWithPadding=scaleLinear({domain:[minValue-padding,maxValue+padding],range:[innerHeight,0]});// Use the actual chart width from xScale range, not just innerWidth
|
|
8
|
+
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState3=useState(initialData),allData=_useState3[0],setAllData=_useState3[1];var headerContent=allData.headerContent,headerDescription=allData.headerDescription,bodyContent=allData.bodyContent,footerContent=allData.footerContent,footerClass=allData.footerClass,footerIcon=allData.footerIcon,contentMetadata=allData.contentMetadata,contentMetadataClass=allData.contentMetadataClass,dataClassName=allData.className,dataError=allData.error,dataIsMissing=allData.isMissing,sampleData=allData.sampleData;function toSafeText(value){if(value===null||value===undefined){return""}return typeof value==="string"?value:JSON.stringify(value)}var safeHeaderContent=toSafeText(headerContent);var safeHeaderDescription=toSafeText(headerDescription);var effectiveBodyContent=isTemplateView&&sampleData!==undefined?sampleData.bodyContent:bodyContent;var safeBodyContent=toSafeText(effectiveBodyContent);var effectiveFooterContent=isTemplateView&&sampleData!==undefined?sampleData.footerContent:footerContent;var safeFooterContent=toSafeText(effectiveFooterContent);var safeContentMetadata=toSafeText(contentMetadata);var _useState4=useState((safeFooterContent==null?void 0:safeFooterContent.length)>0),footerHasContent=_useState4[0],setFooterHasContent=_useState4[1];var _useState5=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState5[0],setAttributes=_useState5[1];var isEditable=(_attributes$isEditabl=attributes.isEditable)!=null?_attributes$isEditabl: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(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);useEffect(function(){setFooterHasContent((safeFooterContent==null?void 0:safeFooterContent.length)>0)},[safeFooterContent]);var defaultClasses="bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none";var defaultFooterClasses=footerHasContent?"text-sm bg-pink-50 text-pink-900 shadow-sm":"text-sm";var defaultContentMetadataClasses="text-xs";var mergedCardClassName=dataClassName?cn(defaultClasses,dataClassName):defaultClasses;var effectiveFooterClass=isTemplateView&&sampleData!==undefined?sampleData.footerClass:footerClass;var mergedFooterClassName=effectiveFooterClass?cn(defaultFooterClasses,effectiveFooterClass):defaultFooterClasses;var mergedContentMetadataClassName=contentMetadataClass?cn(defaultContentMetadataClasses,contentMetadataClass):defaultContentMetadataClasses;var hasError=Boolean((_attributes$error=attributes==null?void 0:attributes.error)!=null?_attributes$error:dataError);var hasMissing=Boolean((_attributes$isMissing=attributes==null?void 0:attributes.isMissing)!=null?_attributes$isMissing:dataIsMissing);var isLoading=Boolean(((attributes==null?void 0:attributes.interactionApiInProgress)||(attributes==null?void 0:attributes.loading))&&!hasError&&!hasMissing);var footerIconText=typeof footerIcon==="string"?footerIcon:footerIcon&&typeof footerIcon==="object"&&"icon"in footerIcon?String(footerIcon.icon):"";function getCardContent(){if(isLoading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}var showEmpty=hasError||hasMissing||!safeBodyContent;function handleFooterInput(event){var target=event.target;var content=target.textContent||"";var hasContent=content.trim().length>0;setFooterHasContent(hasContent);if(!hasContent){var currentProps=gjsModel.get("componentProps");gjsModel.set("componentProps",_extends({},currentProps,{footerContent:null,footerIcon:null,footerClass:null,isEmptied:true}))}}return/*#__PURE__*/_jsxs(React.Fragment,{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":"headerContent",contentEditable:isEditable,className:"text-lg",children:safeHeaderContent}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"headerDescription",contentEditable:isEditable,className:"text-sm",children:safeHeaderDescription})]})})}),showEmpty?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsxs(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-grow",children:[/*#__PURE__*/_jsx("div",{className:"text-3xl font-semibold truncate",children:safeBodyContent}),safeContentMetadata&&/*#__PURE__*/_jsx("div",{className:mergedContentMetadataClassName,style:{color:"#2A44D4"},children:safeContentMetadata})]}),/*#__PURE__*/_jsxs(CardFooter,{"data-slot":"footerContent",contentEditable:isEditable,className:mergedFooterClassName,onInput:handleFooterInput,children:[(footerIconText||"").trim()?/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIconText}):null,safeFooterContent||""]})]})}return/*#__PURE__*/_jsxs(Card,_extends({},rest,{isEditable:false,className:mergedCardClassName+" relative",children:[getCardContent(),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}function transformDataForScatter(data,xAxis,yAxis,dataKeys){if(!data||data.length===0){return[]}var scatterData=data.filter(function(item){return item[xAxis]!==null&&item[xAxis]!==undefined&&item[yAxis]!==null&&item[yAxis]!==undefined}).map(function(item){var _result;var result=(_result={},_result[xAxis]=Number(item[xAxis]),_result[yAxis]=Number(item[yAxis]),_result);if(dataKeys&&dataKeys.length>0){dataKeys.forEach(function(_ref){var key=_ref.key;if(item[key]!==null&&item[key]!==undefined){result[key]=Number(item[key])}})}return result});return scatterData}function binDataForHistogram(data,valueKey,bins){if(bins===void 0){bins=10}if(!data||data.length===0){return[]}var values=data.map(function(item){return Number(item[valueKey])}).filter(function(val){return!isNaN(val)});if(values.length===0){return[]}var min=Math.min.apply(Math,values);var max=Math.max.apply(Math,values);var binWidth=(max-min)/bins;var binsArray=new Array(bins).fill(0);var binLabels=[];for(var i=0;i<bins;i++){var binStart=min+i*binWidth;var binEnd=binStart+binWidth;binLabels.push(binStart.toFixed(1)+"-"+binEnd.toFixed(1))}values.forEach(function(value){var binIndex=Math.floor((value-min)/binWidth);if(binIndex>=bins){binIndex=bins-1}if(binIndex<0){binIndex=0}binsArray[binIndex]+=1});return binLabels.map(function(label,index){return{bin:label,frequency:binsArray[index]}})}function transformDataForBeeswarm(data,groupBy,valueKey){if(!data||data.length===0){return{nodes:[],groups:[]}}var grouped={};data.forEach(function(item){if(item[groupBy]!==null&&item[groupBy]!==undefined&&item[valueKey]!==null&&item[valueKey]!==undefined){var group=String(item[groupBy]);var value=Number(item[valueKey]);if(!isNaN(value)){if(!grouped[group]){grouped[group]=[]}grouped[group].push(value)}}});var groups=Object.keys(grouped).sort();var nodes=[];groups.forEach(function(group,groupIndex){var values=grouped[group];values.forEach(function(value){nodes.push({group:group,groupIndex:groupIndex,value:value,x:groupIndex,y:value,radius:4})})});return{nodes:nodes,groups:groups}}function BeeswarmChart(_ref2){var data=_ref2.data,groups=_ref2.groups,color=_ref2.color,groupBy=_ref2.groupBy,valueKey=_ref2.valueKey;var containerRef=useRef(null);var svgRef=useRef(null);var _useState6=useState({width:800,height:250}),dimensions=_useState6[0],setDimensions=_useState6[1];var _useState7=useState([]),simulatedNodes=_useState7[0],setSimulatedNodes=_useState7[1];var _useTooltip=useTooltip(),tooltipData=_useTooltip.tooltipData,tooltipLeft=_useTooltip.tooltipLeft,tooltipTop=_useTooltip.tooltipTop,tooltipOpen=_useTooltip.tooltipOpen,showTooltip=_useTooltip.showTooltip,hideTooltip=_useTooltip.hideTooltip;useEffect(function(){var updateDimensions=function updateDimensions(){if(containerRef.current){setDimensions({width:containerRef.current.offsetWidth||800,height:250})}};updateDimensions();var resizeObserver=new ResizeObserver(function(entries){for(var _iterator2=_createForOfIteratorHelperLoose(entries),_step2;!(_step2=_iterator2()).done;){var entry=_step2.value;setDimensions({width:entry.contentRect.width||800,height:250})}});if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateDimensions);return function(){resizeObserver.disconnect();window.removeEventListener("resize",updateDimensions)}},[]);var createXScale=useCallback(function(innerWidth,groupDomain){var minBandwidth=60;var totalMinWidth=groupDomain.length*minBandwidth;var paddingRatio=0.3;var xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});if(totalMinWidth>innerWidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}else{xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});var currentBandwidth=xScale.bandwidth();if(currentBandwidth<minBandwidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}}return xScale},[]);var scales=useMemo(function(){if(data.length===0||dimensions.width===0){return null}var margin={top:20,right:20,bottom:60,left:60};var innerWidth=dimensions.width-margin.left-margin.right;var innerHeight=dimensions.height-margin.top-margin.bottom;var values=data.map(function(d){return d.value});var minValue=Math.min.apply(Math,values);var maxValue=Math.max.apply(Math,values);var xScale=createXScale(innerWidth,groups);var yScale=scaleLinear({domain:[minValue,maxValue],range:[innerHeight,0]});return{xScale:xScale,yScale:yScale,minValue:minValue,maxValue:maxValue,innerWidth:innerWidth,innerHeight:innerHeight}},[data,groups,dimensions,createXScale]);useEffect(function(){if(!scales){return}var xScale=scales.xScale,minValue=scales.minValue,maxValue=scales.maxValue,innerWidth=scales.innerWidth,innerHeight=scales.innerHeight;var valueRange=maxValue-minValue;var padding=valueRange*0.1;var yScaleWithPadding=scaleLinear({domain:[minValue-padding,maxValue+padding],range:[innerHeight,0]});// Use the actual chart width from xScale range, not just innerWidth
|
|
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
|