@peak-ai/canvas 1.6.8 → 1.6.9-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/GrapesjsCanvas.js CHANGED
@@ -2,10 +2,10 @@ import _extends from"@babel/runtime/helpers/extends";import _asyncToGenerator fr
2
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{extractPageMetadata,getCurrentPage,mergeStyles,normalizeMultiPageJson}from"./helpers/page-utils";import{createGrapesjsShadcnGenericPlugin}from"./plugins/grapejs-plugin";import{StyledEditor}from"./index.styles";import{PageProvider,usePageContext}from"./contexts/PageContext";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 _callee6(editor){var _editor$Pages,wrapper,pages;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1)switch(_context6.prev=_context6.next){case 0:_context6.prev=0;wrapper=editor.getWrapper();if(wrapper){_context6.next=4;break}return _context6.abrupt("return",null);case 4:pages=((_editor$Pages=editor.Pages)==null||_editor$Pages.getAll==null?void 0:_editor$Pages.getAll())||[];if(!(pages.length===0)){_context6.next=7;break}return _context6.abrupt("return",null);case 7:_context6.next=9;return editor.store();case 9:return _context6.abrupt("return",_context6.sent);case 12:_context6.prev=12;_context6.t0=_context6["catch"](0);// eslint-disable-next-line no-console
3
3
  console.warn("Error during store operation:",_context6.t0);return _context6.abrupt("return",null);case 16:case"end":return _context6.stop()}},_callee6,null,[[0,12]])}));return _safeStoreEditor.apply(this,arguments)}function setComponentProperties(editor,isPreview,isStreaming){if(!editor){return}function setPropertiesRecursively(comp){if(!comp){return}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 resetStreamingComponent(comp){var attrs=comp.get("attributes")||{};var props=comp.get("componentProps")||{};var cleanedProps=_extends({},props);delete cleanedProps.bodyContent;delete cleanedProps.data;delete cleanedProps.rows;delete cleanedProps.series;delete cleanedProps.pagination;delete cleanedProps.error;delete cleanedProps.isMissing;comp.set({attributes:_extends({},attrs,{loading:true,error:undefined,isMissing:undefined}),componentProps:cleanedProps})}function GrapejsCanvasInternal(_ref2){var _pages$;var json=_ref2.json,_ref2$mode=_ref2.mode,mode=_ref2$mode===void 0?"preview":_ref2$mode,setEditor=_ref2.setEditor,performInteraction=_ref2.performInteraction,downloadTable=_ref2.downloadTable,_ref2$newDataNotifier=_ref2.newDataNotifier,newDataNotifier=_ref2$newDataNotifier===void 0?function(){// no op
4
4
  }:_ref2$newDataNotifier,_ref2$setHasChanged=_ref2.setHasChanged,setHasChanged=_ref2$setHasChanged===void 0?function(){// no op
5
- }:_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,externalCurrentPageId=_ref2.currentPageId,externalOnPageChange=_ref2.onPageChange,onRequestPageData=_ref2.onRequestPageData;var pageContext=usePageContext();var normalizedJson=normalizeMultiPageJson(json);var pages=normalizedJson.pages.map(extractPageMetadata);var effectiveCurrentPageId=externalCurrentPageId||(pageContext==null?void 0:pageContext.currentPageId)||((_pages$=pages[0])==null?void 0:_pages$.id)||"";var editorRef=useRef(null);var editorInstance=useRef(null);var renderedComponents=useRef({});var pageDataCache=useRef({});var currentPageIdRef=useRef(effectiveCurrentPageId);var isStreamingRef=useRef(isStreaming!=null?isStreaming:false);var modeRef=useRef(mode);var isSystemUpdateRef=useRef(false);var lastJsonRef=useRef("");var isEditorAliveRef=useRef(false);var onRequestPageDataRef=useRef(onRequestPageData);var rowNavigationContextRef=useRef(null);var _useState=useState(false),isTransitioning=_useState[0],setIsTransitioning=_useState[1];useEffect(function(){currentPageIdRef.current=effectiveCurrentPageId},[effectiveCurrentPageId]);useEffect(function(){isStreamingRef.current=isStreaming!=null?isStreaming:false},[isStreaming!=null?isStreaming:false]);useEffect(function(){modeRef.current=mode},[mode]);useEffect(function(){onRequestPageDataRef.current=onRequestPageData},[onRequestPageData]);function notificationHandler(props){if(!props){return true}var compId=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[compId];if(!model){var pageId=currentPageIdRef.current;if(pageId){if(!pageDataCache.current[pageId]){pageDataCache.current[pageId]={}}pageDataCache.current[pageId][compId]={newProps:newProps,newAttributes:newAttributes,timestamp:Date.now()}}return false}// Filter out complex placeholder objects by setting them to null
5
+ }:_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,externalCurrentPageId=_ref2.currentPageId,externalOnPageChange=_ref2.onPageChange,onRequestPageData=_ref2.onRequestPageData;var pageContext=usePageContext();var normalizedJson=normalizeMultiPageJson(json);var pages=normalizedJson.pages.map(extractPageMetadata);var effectiveCurrentPageId=externalCurrentPageId||(pageContext==null?void 0:pageContext.currentPageId)||((_pages$=pages[0])==null?void 0:_pages$.id)||"";var editorRef=useRef(null);var editorInstance=useRef(null);var renderedComponents=useRef({});var pageDataCache=useRef({});var currentPageIdRef=useRef(effectiveCurrentPageId);var isStreamingRef=useRef(isStreaming!=null?isStreaming:false);var modeRef=useRef(mode);var isSystemUpdateRef=useRef(false);var lastJsonRef=useRef("");var isEditorAliveRef=useRef(false);var onRequestPageDataRef=useRef(onRequestPageData);var rowNavigationContextRef=useRef(null);var _useState=useState(false),isTransitioning=_useState[0],setIsTransitioning=_useState[1];useEffect(function(){currentPageIdRef.current=effectiveCurrentPageId},[effectiveCurrentPageId]);useEffect(function(){isStreamingRef.current=isStreaming!=null?isStreaming:false},[isStreaming!=null?isStreaming:false]);useEffect(function(){modeRef.current=mode},[mode]);useEffect(function(){onRequestPageDataRef.current=onRequestPageData},[onRequestPageData]);function notificationHandler(props){var _model$get;if(!props){return true}var compId=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[compId];if(!model){var pageId=currentPageIdRef.current;if(pageId){if(!pageDataCache.current[pageId]){pageDataCache.current[pageId]={}}pageDataCache.current[pageId][compId]={newProps:newProps,newAttributes:newAttributes,timestamp:Date.now()}}return false}// Filter out complex placeholder objects by setting them to null
6
6
  // This ensures placeholder values are properly cleared and don't cause stale data issues
7
7
  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
8
- 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));var currentAttrs=model.get("attributes")||{};var hasRealValue=(parsedNewProps==null?void 0:parsedNewProps.bodyContent)!==undefined&&(parsedNewProps==null?void 0:parsedNewProps.bodyContent)!==null||(parsedNewProps==null?void 0:parsedNewProps.data)!==undefined&&(parsedNewProps==null?void 0:parsedNewProps.data)!==null||(parsedNewProps==null?void 0:parsedNewProps.rows)!==undefined&&(parsedNewProps==null?void 0:parsedNewProps.rows)!==null||(parsedNewProps==null?void 0:parsedNewProps.series)!==undefined&&(parsedNewProps==null?void 0:parsedNewProps.series)!==null;var shouldStopLoading=hasRealValue||(newAttributes==null?void 0:newAttributes.error)||(parsedNewProps==null?void 0:parsedNewProps.isMissing);model.set("attributes",_extends({},currentAttrs,newAttributes,shouldStopLoading?{loading:false}:{}));if(model.view){model.view.render()}return true}useEffect(function(){newDataNotifier(notificationHandler)},[]);function handleNavigateToPage(targetPageId,rowContext){rowNavigationContextRef.current=rowContext!=null?rowContext:null;if(externalOnPageChange){externalOnPageChange(targetPageId,rowContext)}if(pageContext){pageContext.navigateToPage(targetPageId,rowContext)}}function downloadTableWrapper(_x2){return _downloadTableWrapper.apply(this,arguments)}function _downloadTableWrapper(){_downloadTableWrapper=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(data){var updatedJson;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:if(downloadTable){_context4.next=2;break}return _context4.abrupt("return");case 2:updatedJson=null;if(!editorInstance.current){_context4.next=7;break}_context4.next=6;return safeStoreEditor(editorInstance.current);case 6:updatedJson=_context4.sent;case 7:_context4.next=9;return downloadTable(_extends({},data,{json:updatedJson}));case 9:case"end":return _context4.stop()}},_callee4)}));return _downloadTableWrapper.apply(this,arguments)}function performInteractionWrapper(_x3){return _performInteractionWrapper.apply(this,arguments)}function _performInteractionWrapper(){_performInteractionWrapper=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(payload){var updatedJson,apiResponse,componentUpdates;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:updatedJson=null;if(!editorInstance.current){_context5.next=5;break}_context5.next=4;return safeStoreEditor(editorInstance.current);case 4:updatedJson=_context5.sent;case 5:setInteracting(renderedComponents.current,payload.affectedComponents,true);_context5.prev=6;_context5.next=9;return performInteraction(_extends({},payload,{json:updatedJson}));case 9:apiResponse=_context5.sent;componentUpdates=apiResponse||{};Object.entries(componentUpdates).forEach(function(_ref8){var key=_ref8[0],value=_ref8[1];var model=renderedComponents.current[key];if(model){model.set("attributes",_extends({},model.get("attributes"),{error:undefined}));model.set("componentProps",_extends({},model.get("componentProps"),value,{error:undefined,isMissing:undefined}))}});return _context5.abrupt("return",componentUpdates);case 15:_context5.prev=15;_context5.t0=_context5["catch"](6);payload.affectedComponents.forEach(function(componentId){var model=renderedComponents.current[componentId];if(model){var errorMessage=_context5.t0 instanceof Error?_context5.t0.message:"Something went wrong. Please try again.";model.set("attributes",_extends({},model.get("attributes"),{error:errorMessage}));model.set("componentProps",_extends({},model.get("componentProps"),{error:errorMessage,isMissing:undefined}))}});throw _context5.t0;case 19:_context5.prev=19;setInteracting(renderedComponents.current,payload.affectedComponents,false);return _context5.finish(19);case 22:case"end":return _context5.stop()}},_callee5,null,[[6,15,19,22]])}));return _performInteractionWrapper.apply(this,arguments)}useEffect(function(){if(!editorRef.current){return function(){// no op
8
+ 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,{headerMapper:((_model$get=model.get("componentProps"))==null?void 0:_model$get.headerMapper)||parsedNewProps.headerMapper}));var currentAttrs=model.get("attributes")||{};var hasRealValue=(parsedNewProps==null?void 0:parsedNewProps.bodyContent)!==undefined&&(parsedNewProps==null?void 0:parsedNewProps.bodyContent)!==null||(parsedNewProps==null?void 0:parsedNewProps.data)!==undefined&&(parsedNewProps==null?void 0:parsedNewProps.data)!==null||(parsedNewProps==null?void 0:parsedNewProps.rows)!==undefined&&(parsedNewProps==null?void 0:parsedNewProps.rows)!==null||(parsedNewProps==null?void 0:parsedNewProps.series)!==undefined&&(parsedNewProps==null?void 0:parsedNewProps.series)!==null;var shouldStopLoading=hasRealValue||(newAttributes==null?void 0:newAttributes.error)||(parsedNewProps==null?void 0:parsedNewProps.isMissing);model.set("attributes",_extends({},currentAttrs,newAttributes,shouldStopLoading?{loading:false}:{}));if(model.view){model.view.render()}return true}useEffect(function(){newDataNotifier(notificationHandler)},[]);function handleNavigateToPage(targetPageId,rowContext){rowNavigationContextRef.current=rowContext!=null?rowContext:null;if(externalOnPageChange){externalOnPageChange(targetPageId,rowContext)}if(pageContext){pageContext.navigateToPage(targetPageId,rowContext)}}function downloadTableWrapper(_x2){return _downloadTableWrapper.apply(this,arguments)}function _downloadTableWrapper(){_downloadTableWrapper=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(data){var updatedJson;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:if(downloadTable){_context4.next=2;break}return _context4.abrupt("return");case 2:updatedJson=null;if(!editorInstance.current){_context4.next=7;break}_context4.next=6;return safeStoreEditor(editorInstance.current);case 6:updatedJson=_context4.sent;case 7:_context4.next=9;return downloadTable(_extends({},data,{json:updatedJson}));case 9:case"end":return _context4.stop()}},_callee4)}));return _downloadTableWrapper.apply(this,arguments)}function performInteractionWrapper(_x3){return _performInteractionWrapper.apply(this,arguments)}function _performInteractionWrapper(){_performInteractionWrapper=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(payload){var updatedJson,apiResponse,componentUpdates;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:updatedJson=null;if(!editorInstance.current){_context5.next=5;break}_context5.next=4;return safeStoreEditor(editorInstance.current);case 4:updatedJson=_context5.sent;case 5:setInteracting(renderedComponents.current,payload.affectedComponents,true);_context5.prev=6;_context5.next=9;return performInteraction(_extends({},payload,{json:updatedJson}));case 9:apiResponse=_context5.sent;componentUpdates=apiResponse||{};Object.entries(componentUpdates).forEach(function(_ref8){var key=_ref8[0],value=_ref8[1];var model=renderedComponents.current[key];if(model){model.set("attributes",_extends({},model.get("attributes"),{error:undefined}));model.set("componentProps",_extends({},model.get("componentProps"),value,{error:undefined,isMissing:undefined}))}});return _context5.abrupt("return",componentUpdates);case 15:_context5.prev=15;_context5.t0=_context5["catch"](6);payload.affectedComponents.forEach(function(componentId){var model=renderedComponents.current[componentId];if(model){var errorMessage=_context5.t0 instanceof Error?_context5.t0.message:"Something went wrong. Please try again.";model.set("attributes",_extends({},model.get("attributes"),{error:errorMessage}));model.set("componentProps",_extends({},model.get("componentProps"),{error:errorMessage,isMissing:undefined}))}});throw _context5.t0;case 19:_context5.prev=19;setInteracting(renderedComponents.current,payload.affectedComponents,false);return _context5.finish(19);case 22:case"end":return _context5.stop()}},_callee5,null,[[6,15,19,22]])}));return _performInteractionWrapper.apply(this,arguments)}useEffect(function(){if(!editorRef.current){return function(){// no op
9
9
  }}if(editorInstance.current){editorInstance.current.destroy();editorInstance.current=null;isEditorAliveRef.current=false}var currentMode=modeRef.current;var editor=grapesjs.init({container:editorRef.current,height:"100%",plugins:[tailwind,createGrapesjsShadcnGenericPlugin(modeRef,performInteractionWrapper,renderedComponents.current,setHasChanged,isTemplateView,isStreamingRef,handleNavigateToPage,downloadTableWrapper)],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
10
10
  // So, adding them from here!
11
11
  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;if(json&&((_json$pages=json.pages)==null?void 0:_json$pages.length)>0){var _currentPage$frames,_editorInstance$curre3;if(!isEditorAliveRef.current||!editorInstance.current){return}var pageNormalizedJson=normalizeMultiPageJson(json);var currentPage=getCurrentPage(pageNormalizedJson.pages,effectiveCurrentPageId);if(!currentPage||!((_currentPage$frames=currentPage.frames)!=null&&_currentPage$frames.length)){return}isSystemUpdateRef.current=true;var raw=currentPage.frames[0].component;var processed=expandActions(raw);try{var _editorInstance$curre;(_editorInstance$curre=editorInstance.current)==null||_editorInstance$curre.setComponents(processed);setTimeout(function(){if(editorInstance.current&&isEditorAliveRef.current){var _editorInstance$curre2;var domComponents=(_editorInstance$curre2=editorInstance.current)==null?void 0:_editorInstance$curre2.DomComponents;if(domComponents){var _domComponents$getWra;var allComponents=domComponents==null||(_domComponents$getWra=domComponents.getWrapper())==null?void 0:_domComponents$getWra.findType("shadcn-generic");allComponents==null||allComponents.forEach(function(comp){if(comp.get("componentName")==="Tabs"){var _comp$view;(_comp$view=comp.view)==null||_comp$view.render()}})}}},100)}catch(error){// eslint-disable-next-line no-console
@@ -1 +1 @@
1
- {"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","useState","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","extractPageMetadata","getCurrentPage","mergeStyles","normalizeMultiPageJson","createGrapesjsShadcnGenericPlugin","StyledEditor","PageProvider","usePageContext","jsx","_jsx","jsxs","_jsxs","isEditorCanvasReady","editor","canvas","Canvas","canvasDoc","getDocument","canvasBody","body","_unused","safeStoreEditor","_x","_safeStoreEditor","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee6","_editor$Pages","wrapper","pages","wrap","_callee6$","_context6","prev","next","getWrapper","abrupt","Pages","getAll","length","store","sent","t0","console","warn","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","resetStreamingComponent","attrs","props","cleanedProps","data","rows","series","pagination","error","isMissing","loading","GrapejsCanvasInternal","_ref2","_pages$","json","_ref2$mode","mode","setEditor","performInteraction","downloadTable","_ref2$newDataNotifier","newDataNotifier","_ref2$setHasChanged","setHasChanged","_ref2$isModeChangeFro","isModeChangeFromToggle","_ref2$isTemplateView","isTemplateView","externalCurrentPageId","currentPageId","externalOnPageChange","onPageChange","onRequestPageData","pageContext","normalizedJson","effectiveCurrentPageId","editorRef","editorInstance","pageDataCache","currentPageIdRef","isStreamingRef","modeRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","onRequestPageDataRef","rowNavigationContextRef","_useState","isTransitioning","setIsTransitioning","current","notificationHandler","compId","_props$newProps","newProps","_props$newAttributes","newAttributes","pageId","timestamp","Date","now","filteredProps","keys","key","name","parsedNewProps","isActionsComponent","hasValidActionsData","_model$components$at","isAlreadyExpanded","at","currentAttrs","hasRealValue","shouldStopLoading","view","render","handleNavigateToPage","targetPageId","rowContext","navigateToPage","downloadTableWrapper","_x2","_downloadTableWrapper","_callee4","updatedJson","_callee4$","_context4","performInteractionWrapper","_x3","_performInteractionWrapper","_callee5","payload","apiResponse","componentUpdates","_callee5$","_context5","affectedComponents","_ref8","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","cleanup","_json$pages","_currentPage$frames","_editorInstance$curre3","pageNormalizedJson","currentPage","frames","raw","processed","_editorInstance$curre","setComponents","_editorInstance$curre2","domComponents","_domComponents$getWra","allComponents","findType","_comp$view","globalStyles","styles","pageStyles","mergedStyles","cssText","setStyle","_rowNavigationContext","isMultiPage","Boolean","cachedData","_ref5","updatedAttributes","cacheCheckInterval","setInterval","appliedAny","_ref6","clearInterval","_callee3","_callee3$","_context3","shadcnComponents","currentIsStreaming","prevIsStreaming","Fragment","children","ref","opacity","transition","GrapejsCanvas","_pages$2","existingContext","initialPageId"],"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 {\n extractPageMetadata,\n getCurrentPage,\n mergeStyles,\n normalizeMultiPageJson,\n} from './helpers/page-utils';\nimport { createGrapesjsShadcnGenericPlugin } from './plugins/grapejs-plugin';\nimport { StyledEditor } from './index.styles';\nimport type { PageAwareProps } from './types/page';\nimport { PageProvider, usePageContext } from './contexts/PageContext';\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 downloadTable?: (data: {\n tableId: string;\n title: string;\n limit: number;\n json: any;\n headerMapper?: Record<string, string>;\n }) => Promise<void>;\n newDataNotifier: (notifHandler: NotificationHandler) => void;\n setHasChanged: (hasChanged: boolean) => void;\n isStreaming: boolean;\n isModeChangeFromToggle?: boolean;\n isTemplateView?: boolean;\n} & PageAwareProps;\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 // eslint-disable-next-line no-console\n console.warn('Error during store operation:', error);\n\n return null;\n }\n}\n\nfunction setComponentProperties(editor: Editor, isPreview: boolean, isStreaming: boolean): void {\n if (!editor) {\n return;\n }\n\n function setPropertiesRecursively(comp: Component) {\n if (!comp) {\n return;\n }\n\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 resetStreamingComponent(comp: Component): void {\n const attrs = comp.get('attributes') || {};\n const props = comp.get('componentProps') || {};\n\n const cleanedProps = { ...props };\n\n delete cleanedProps.bodyContent;\n delete cleanedProps.data;\n delete cleanedProps.rows;\n delete cleanedProps.series;\n delete cleanedProps.pagination;\n delete cleanedProps.error;\n delete cleanedProps.isMissing;\n\n comp.set({\n attributes: {\n ...attrs,\n loading: true,\n error: undefined,\n isMissing: undefined,\n },\n componentProps: cleanedProps,\n });\n}\n\nfunction GrapejsCanvasInternal({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n downloadTable,\n newDataNotifier = () => {\n // no op\n },\n setHasChanged = () => {\n // no op\n },\n isStreaming,\n isModeChangeFromToggle = false,\n isTemplateView = false,\n currentPageId: externalCurrentPageId,\n onPageChange: externalOnPageChange, // eslint-disable-line @typescript-eslint/no-unused-vars\n onRequestPageData,\n}: GrapesjsCanvasProps) {\n const pageContext = usePageContext();\n\n const normalizedJson = normalizeMultiPageJson(json);\n const pages = normalizedJson.pages.map(extractPageMetadata);\n const effectiveCurrentPageId =\n externalCurrentPageId || pageContext?.currentPageId || pages[0]?.id || '';\n\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<Editor | null>(null);\n const renderedComponents = useRef<Record<string, Component>>({});\n const pageDataCache = useRef<Record<string, Record<string, any>>>({});\n const currentPageIdRef = useRef<string>(effectiveCurrentPageId);\n const isStreamingRef = useRef(isStreaming ?? false);\n const modeRef = useRef(mode);\n const isSystemUpdateRef = useRef(false);\n const lastJsonRef = useRef<string>('');\n const isEditorAliveRef = useRef(false);\n const onRequestPageDataRef = useRef(onRequestPageData);\n const rowNavigationContextRef = useRef<Record<string, any> | null>(null);\n const [isTransitioning, setIsTransitioning] = useState(false);\n\n useEffect(() => {\n currentPageIdRef.current = effectiveCurrentPageId;\n }, [effectiveCurrentPageId]);\n\n useEffect(() => {\n isStreamingRef.current = isStreaming ?? false;\n }, [isStreaming ?? false]);\n\n useEffect(() => {\n modeRef.current = mode;\n }, [mode]);\n\n useEffect(() => {\n onRequestPageDataRef.current = onRequestPageData;\n }, [onRequestPageData]);\n\n function notificationHandler(\n props: Parameters<NotificationHandler>[0],\n ): ReturnType<NotificationHandler> {\n if (!props) {\n return true;\n }\n\n const { componentId: compId, newProps = {}, newAttributes = {} } = props;\n\n const model = renderedComponents.current[compId];\n\n if (!model) {\n const pageId = currentPageIdRef.current;\n\n if (pageId) {\n if (!pageDataCache.current[pageId]) {\n pageDataCache.current[pageId] = {};\n }\n\n pageDataCache.current[pageId][compId] = {\n newProps,\n newAttributes,\n timestamp: Date.now(),\n };\n }\n\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 // headerMapper: model.get('componentProps')?.headerMapper || parsedNewProps.headerMapper,\n });\n\n const currentAttrs = model.get('attributes') || {};\n\n const hasRealValue =\n (parsedNewProps?.bodyContent !== undefined && parsedNewProps?.bodyContent !== null) ||\n (parsedNewProps?.data !== undefined && parsedNewProps?.data !== null) ||\n (parsedNewProps?.rows !== undefined && parsedNewProps?.rows !== null) ||\n (parsedNewProps?.series !== undefined && parsedNewProps?.series !== null);\n\n const shouldStopLoading = hasRealValue || newAttributes?.error || parsedNewProps?.isMissing;\n\n model.set('attributes', {\n ...currentAttrs,\n ...newAttributes,\n ...(shouldStopLoading ? { loading: false } : {}),\n });\n\n if (model.view) {\n model.view.render();\n }\n\n return true;\n }\n\n useEffect(() => {\n newDataNotifier(notificationHandler);\n }, []);\n\n function handleNavigateToPage(targetPageId: string, rowContext?: Record<string, any>) {\n rowNavigationContextRef.current = rowContext ?? null;\n\n if (externalOnPageChange) {\n externalOnPageChange(targetPageId, rowContext);\n }\n\n if (pageContext) {\n pageContext.navigateToPage(targetPageId, rowContext);\n }\n }\n\n async function downloadTableWrapper(data: {\n tableId: string;\n title: string;\n limit: number;\n headerMapper?: Record<string, string>;\n }) {\n if (!downloadTable) {\n return;\n }\n\n let updatedJson = null;\n\n if (editorInstance.current) {\n updatedJson = await safeStoreEditor(editorInstance.current);\n }\n\n await downloadTable({ ...data, json: updatedJson });\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 = modeRef.current;\n\n const editor = grapesjs.init({\n container: editorRef.current,\n height: '100%',\n plugins: [\n tailwind,\n createGrapesjsShadcnGenericPlugin(\n modeRef,\n performInteractionWrapper,\n renderedComponents.current,\n setHasChanged,\n isTemplateView,\n isStreamingRef,\n handleNavigateToPage,\n downloadTableWrapper,\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) {\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n const pageNormalizedJson = normalizeMultiPageJson(json);\n\n const currentPage = getCurrentPage(pageNormalizedJson.pages, effectiveCurrentPageId);\n\n if (!currentPage || !currentPage.frames?.length) {\n return;\n }\n\n isSystemUpdateRef.current = true;\n const raw = currentPage.frames[0].component;\n const processed = expandActions(raw);\n\n try {\n editorInstance.current?.setComponents(processed);\n\n setTimeout(() => {\n if (editorInstance.current && isEditorAliveRef.current) {\n const domComponents = editorInstance.current?.DomComponents;\n\n if (domComponents) {\n const allComponents = domComponents?.getWrapper()?.findType('shadcn-generic');\n allComponents?.forEach((comp: any) => {\n if (comp.get('componentName') === 'Tabs') {\n comp.view?.render();\n }\n });\n }\n }\n }, 100);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error during component restoration:', error);\n }\n\n const globalStyles = pageNormalizedJson.styles || [];\n const pageStyles = currentPage.styles || [];\n const mergedStyles = mergeStyles(globalStyles, pageStyles);\n const cssText = convertStyles(mergedStyles);\n editorInstance.current?.setStyle(cssText);\n\n if (onRequestPageDataRef.current) {\n const isMultiPage = Boolean(pageNormalizedJson.isMultiPage);\n const pageId = isMultiPage ? currentPage.id : '';\n const rowContext = rowNavigationContextRef.current ?? undefined;\n\n onRequestPageDataRef.current(pageId, [], rowContext);\n rowNavigationContextRef.current = null;\n }\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(() => {\n if (currentPage && pageDataCache.current[currentPage.id]) {\n const cachedData = pageDataCache.current[currentPage.id];\n\n Object.entries(cachedData).forEach(([componentId, data]) => {\n const model = renderedComponents.current[componentId];\n\n if (model && data) {\n if (data.newProps) {\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...data.newProps,\n });\n }\n\n const updatedAttributes = {\n ...model.get('attributes'),\n ...(data.newAttributes || {}),\n };\n\n model.set('attributes', updatedAttributes);\n\n if (model.view) {\n model.view.render();\n }\n }\n });\n\n delete pageDataCache.current[currentPage.id];\n }\n }, 150);\n\n const cacheCheckInterval = setInterval(() => {\n if (!currentPage || !pageDataCache.current[currentPage.id]) {\n return;\n }\n\n const cachedData = pageDataCache.current[currentPage.id];\n let appliedAny = false;\n\n Object.entries(cachedData).forEach(([componentId, data]) => {\n const model = renderedComponents.current[componentId];\n\n if (model && data) {\n if (data.newProps) {\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...data.newProps,\n });\n }\n\n const updatedAttributes = {\n ...model.get('attributes'),\n ...(data.newAttributes || {}),\n };\n\n model.set('attributes', updatedAttributes);\n\n if (model.view) {\n model.view.render();\n }\n\n appliedAny = true;\n }\n });\n\n if (appliedAny) {\n Object.keys(cachedData).forEach((componentId) => {\n if (renderedComponents.current[componentId]) {\n delete cachedData[componentId];\n }\n });\n\n if (Object.keys(cachedData).length === 0) {\n delete pageDataCache.current[currentPage.id];\n }\n }\n }, 100);\n\n setTimeout(() => {\n clearInterval(cacheCheckInterval);\n }, 5000);\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, effectiveCurrentPageId]);\n\n useEffect(() => {\n const editor = editorInstance.current;\n\n if (!editor || !isEditorAliveRef.current) {\n return;\n }\n\n if (isModeChangeFromToggle) {\n setIsTransitioning(true);\n }\n\n setComponentProperties(\n editorInstance.current as Editor,\n mode === 'preview',\n isStreaming ?? false,\n );\n\n const wrapper = editor.getWrapper();\n const shadcnComponents = wrapper?.find('[data-gjs-type=\"shadcn-generic\"]') || [];\n\n shadcnComponents.forEach((comp: Component) => {\n if (comp.view && typeof comp.view.render === 'function') {\n comp.view.render();\n }\n });\n\n if (isModeChangeFromToggle) {\n requestAnimationFrame(() => {\n setIsTransitioning(false);\n });\n }\n }, [mode, isStreaming ?? false]);\n\n useEffect(() => {\n const editor = editorInstance.current;\n const currentIsStreaming = isStreaming ?? false;\n const prevIsStreaming = isStreamingRef.current;\n\n if (editor && isEditorAliveRef.current && currentIsStreaming && !prevIsStreaming) {\n const wrapper = editor.getWrapper();\n const shadcnComponents = wrapper?.findType('shadcn-generic') || [];\n\n shadcnComponents.forEach((comp: Component) => {\n resetStreamingComponent(comp);\n });\n }\n\n isStreamingRef.current = currentIsStreaming;\n }, [isStreaming]);\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\nfunction GrapejsCanvas(props: GrapesjsCanvasProps) {\n const existingContext = usePageContext();\n\n if (existingContext) {\n return <GrapejsCanvasInternal {...props} />;\n }\n\n const normalizedJson = normalizeMultiPageJson(props.json);\n const pages = normalizedJson.pages.map(extractPageMetadata);\n const initialPageId = props.currentPageId || pages[0]?.id || '';\n\n return (\n <PageProvider pages={pages} initialPageId={initialPageId} onPageChange={props.onPageChange}>\n <GrapejsCanvasInternal {...props} />\n </PageProvider>\n );\n}\n\nexport default GrapejsCanvas;\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,mBAAm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B,CAAE,KAAAkM,QAAA,CACjD,GAAM,CAAAC,eAAe,CAAGzT,cAAc,CAAC,CAAC,CAExC,GAAIyT,eAAe,CAAE,CACnB,mBAAOvT,IAAA,CAAC6H,qBAAqB,CAAAnE,QAAA,IAAK0D,KAAK,CAAG,CAC5C,CAEA,GAAM,CAAAgC,cAAc,CAAG1J,sBAAsB,CAAC0H,KAAK,CAACY,IAAI,CAAC,CACzD,GAAM,CAAAzG,KAAK,CAAG6H,cAAc,CAAC7H,KAAK,CAAC+C,GAAG,CAAC/E,mBAAmB,CAAC,CAC3D,GAAM,CAAAiU,aAAa,CAAGpM,KAAK,CAAC2B,aAAa,IAAAuK,QAAA,CAAI/R,KAAK,CAAC,CAAC,CAAC,eAAR+R,QAAA,CAAUjN,EAAE,GAAI,EAAE,CAE/D,mBACErG,IAAA,CAACH,YAAY,EAAC0B,KAAK,CAAEA,KAAM,CAACiS,aAAa,CAAEA,aAAc,CAACvK,YAAY,CAAE7B,KAAK,CAAC6B,YAAa,CAAAgK,QAAA,cACzFjT,IAAA,CAAC6H,qBAAqB,CAAAnE,QAAA,IAAK0D,KAAK,CAAG,CAAC,CACxB,CAElB,CAEA,cAAe,CAAAiM,aAAa","ignoreList":[]}
1
+ {"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","useState","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","extractPageMetadata","getCurrentPage","mergeStyles","normalizeMultiPageJson","createGrapesjsShadcnGenericPlugin","StyledEditor","PageProvider","usePageContext","jsx","_jsx","jsxs","_jsxs","isEditorCanvasReady","editor","canvas","Canvas","canvasDoc","getDocument","canvasBody","body","_unused","safeStoreEditor","_x","_safeStoreEditor","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee6","_editor$Pages","wrapper","pages","wrap","_callee6$","_context6","prev","next","getWrapper","abrupt","Pages","getAll","length","store","sent","t0","console","warn","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","resetStreamingComponent","attrs","props","cleanedProps","data","rows","series","pagination","error","isMissing","loading","GrapejsCanvasInternal","_ref2","_pages$","json","_ref2$mode","mode","setEditor","performInteraction","downloadTable","_ref2$newDataNotifier","newDataNotifier","_ref2$setHasChanged","setHasChanged","_ref2$isModeChangeFro","isModeChangeFromToggle","_ref2$isTemplateView","isTemplateView","externalCurrentPageId","currentPageId","externalOnPageChange","onPageChange","onRequestPageData","pageContext","normalizedJson","effectiveCurrentPageId","editorRef","editorInstance","pageDataCache","currentPageIdRef","isStreamingRef","modeRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","onRequestPageDataRef","rowNavigationContextRef","_useState","isTransitioning","setIsTransitioning","current","notificationHandler","_model$get","compId","_props$newProps","newProps","_props$newAttributes","newAttributes","pageId","timestamp","Date","now","filteredProps","keys","key","name","parsedNewProps","isActionsComponent","hasValidActionsData","_model$components$at","isAlreadyExpanded","at","headerMapper","currentAttrs","hasRealValue","shouldStopLoading","view","render","handleNavigateToPage","targetPageId","rowContext","navigateToPage","downloadTableWrapper","_x2","_downloadTableWrapper","_callee4","updatedJson","_callee4$","_context4","performInteractionWrapper","_x3","_performInteractionWrapper","_callee5","payload","apiResponse","componentUpdates","_callee5$","_context5","affectedComponents","_ref8","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","cleanup","_json$pages","_currentPage$frames","_editorInstance$curre3","pageNormalizedJson","currentPage","frames","raw","processed","_editorInstance$curre","setComponents","_editorInstance$curre2","domComponents","_domComponents$getWra","allComponents","findType","_comp$view","globalStyles","styles","pageStyles","mergedStyles","cssText","setStyle","_rowNavigationContext","isMultiPage","Boolean","cachedData","_ref5","updatedAttributes","cacheCheckInterval","setInterval","appliedAny","_ref6","clearInterval","_callee3","_callee3$","_context3","shadcnComponents","currentIsStreaming","prevIsStreaming","Fragment","children","ref","opacity","transition","GrapejsCanvas","_pages$2","existingContext","initialPageId"],"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 {\n extractPageMetadata,\n getCurrentPage,\n mergeStyles,\n normalizeMultiPageJson,\n} from './helpers/page-utils';\nimport { createGrapesjsShadcnGenericPlugin } from './plugins/grapejs-plugin';\nimport { StyledEditor } from './index.styles';\nimport type { PageAwareProps } from './types/page';\nimport { PageProvider, usePageContext } from './contexts/PageContext';\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 downloadTable?: (data: {\n tableId: string;\n title: string;\n limit: number;\n json: any;\n headerMapper?: Record<string, string>;\n }) => Promise<void>;\n newDataNotifier: (notifHandler: NotificationHandler) => void;\n setHasChanged: (hasChanged: boolean) => void;\n isStreaming: boolean;\n isModeChangeFromToggle?: boolean;\n isTemplateView?: boolean;\n} & PageAwareProps;\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 // eslint-disable-next-line no-console\n console.warn('Error during store operation:', error);\n\n return null;\n }\n}\n\nfunction setComponentProperties(editor: Editor, isPreview: boolean, isStreaming: boolean): void {\n if (!editor) {\n return;\n }\n\n function setPropertiesRecursively(comp: Component) {\n if (!comp) {\n return;\n }\n\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 resetStreamingComponent(comp: Component): void {\n const attrs = comp.get('attributes') || {};\n const props = comp.get('componentProps') || {};\n\n const cleanedProps = { ...props };\n\n delete cleanedProps.bodyContent;\n delete cleanedProps.data;\n delete cleanedProps.rows;\n delete cleanedProps.series;\n delete cleanedProps.pagination;\n delete cleanedProps.error;\n delete cleanedProps.isMissing;\n\n comp.set({\n attributes: {\n ...attrs,\n loading: true,\n error: undefined,\n isMissing: undefined,\n },\n componentProps: cleanedProps,\n });\n}\n\nfunction GrapejsCanvasInternal({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n downloadTable,\n newDataNotifier = () => {\n // no op\n },\n setHasChanged = () => {\n // no op\n },\n isStreaming,\n isModeChangeFromToggle = false,\n isTemplateView = false,\n currentPageId: externalCurrentPageId,\n onPageChange: externalOnPageChange, // eslint-disable-line @typescript-eslint/no-unused-vars\n onRequestPageData,\n}: GrapesjsCanvasProps) {\n const pageContext = usePageContext();\n\n const normalizedJson = normalizeMultiPageJson(json);\n const pages = normalizedJson.pages.map(extractPageMetadata);\n const effectiveCurrentPageId =\n externalCurrentPageId || pageContext?.currentPageId || pages[0]?.id || '';\n\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<Editor | null>(null);\n const renderedComponents = useRef<Record<string, Component>>({});\n const pageDataCache = useRef<Record<string, Record<string, any>>>({});\n const currentPageIdRef = useRef<string>(effectiveCurrentPageId);\n const isStreamingRef = useRef(isStreaming ?? false);\n const modeRef = useRef(mode);\n const isSystemUpdateRef = useRef(false);\n const lastJsonRef = useRef<string>('');\n const isEditorAliveRef = useRef(false);\n const onRequestPageDataRef = useRef(onRequestPageData);\n const rowNavigationContextRef = useRef<Record<string, any> | null>(null);\n const [isTransitioning, setIsTransitioning] = useState(false);\n\n useEffect(() => {\n currentPageIdRef.current = effectiveCurrentPageId;\n }, [effectiveCurrentPageId]);\n\n useEffect(() => {\n isStreamingRef.current = isStreaming ?? false;\n }, [isStreaming ?? false]);\n\n useEffect(() => {\n modeRef.current = mode;\n }, [mode]);\n\n useEffect(() => {\n onRequestPageDataRef.current = onRequestPageData;\n }, [onRequestPageData]);\n\n function notificationHandler(\n props: Parameters<NotificationHandler>[0],\n ): ReturnType<NotificationHandler> {\n if (!props) {\n return true;\n }\n\n const { componentId: compId, newProps = {}, newAttributes = {} } = props;\n\n const model = renderedComponents.current[compId];\n\n if (!model) {\n const pageId = currentPageIdRef.current;\n\n if (pageId) {\n if (!pageDataCache.current[pageId]) {\n pageDataCache.current[pageId] = {};\n }\n\n pageDataCache.current[pageId][compId] = {\n newProps,\n newAttributes,\n timestamp: Date.now(),\n };\n }\n\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 headerMapper: model.get('componentProps')?.headerMapper || parsedNewProps.headerMapper,\n });\n\n const currentAttrs = model.get('attributes') || {};\n\n const hasRealValue =\n (parsedNewProps?.bodyContent !== undefined && parsedNewProps?.bodyContent !== null) ||\n (parsedNewProps?.data !== undefined && parsedNewProps?.data !== null) ||\n (parsedNewProps?.rows !== undefined && parsedNewProps?.rows !== null) ||\n (parsedNewProps?.series !== undefined && parsedNewProps?.series !== null);\n\n const shouldStopLoading = hasRealValue || newAttributes?.error || parsedNewProps?.isMissing;\n\n model.set('attributes', {\n ...currentAttrs,\n ...newAttributes,\n ...(shouldStopLoading ? { loading: false } : {}),\n });\n\n if (model.view) {\n model.view.render();\n }\n\n return true;\n }\n\n useEffect(() => {\n newDataNotifier(notificationHandler);\n }, []);\n\n function handleNavigateToPage(targetPageId: string, rowContext?: Record<string, any>) {\n rowNavigationContextRef.current = rowContext ?? null;\n\n if (externalOnPageChange) {\n externalOnPageChange(targetPageId, rowContext);\n }\n\n if (pageContext) {\n pageContext.navigateToPage(targetPageId, rowContext);\n }\n }\n\n async function downloadTableWrapper(data: {\n tableId: string;\n title: string;\n limit: number;\n headerMapper?: Record<string, string>;\n }) {\n if (!downloadTable) {\n return;\n }\n\n let updatedJson = null;\n\n if (editorInstance.current) {\n updatedJson = await safeStoreEditor(editorInstance.current);\n }\n\n await downloadTable({ ...data, json: updatedJson });\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 = modeRef.current;\n\n const editor = grapesjs.init({\n container: editorRef.current,\n height: '100%',\n plugins: [\n tailwind,\n createGrapesjsShadcnGenericPlugin(\n modeRef,\n performInteractionWrapper,\n renderedComponents.current,\n setHasChanged,\n isTemplateView,\n isStreamingRef,\n handleNavigateToPage,\n downloadTableWrapper,\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) {\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n const pageNormalizedJson = normalizeMultiPageJson(json);\n\n const currentPage = getCurrentPage(pageNormalizedJson.pages, effectiveCurrentPageId);\n\n if (!currentPage || !currentPage.frames?.length) {\n return;\n }\n\n isSystemUpdateRef.current = true;\n const raw = currentPage.frames[0].component;\n const processed = expandActions(raw);\n\n try {\n editorInstance.current?.setComponents(processed);\n\n setTimeout(() => {\n if (editorInstance.current && isEditorAliveRef.current) {\n const domComponents = editorInstance.current?.DomComponents;\n\n if (domComponents) {\n const allComponents = domComponents?.getWrapper()?.findType('shadcn-generic');\n allComponents?.forEach((comp: any) => {\n if (comp.get('componentName') === 'Tabs') {\n comp.view?.render();\n }\n });\n }\n }\n }, 100);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error during component restoration:', error);\n }\n\n const globalStyles = pageNormalizedJson.styles || [];\n const pageStyles = currentPage.styles || [];\n const mergedStyles = mergeStyles(globalStyles, pageStyles);\n const cssText = convertStyles(mergedStyles);\n editorInstance.current?.setStyle(cssText);\n\n if (onRequestPageDataRef.current) {\n const isMultiPage = Boolean(pageNormalizedJson.isMultiPage);\n const pageId = isMultiPage ? currentPage.id : '';\n const rowContext = rowNavigationContextRef.current ?? undefined;\n\n onRequestPageDataRef.current(pageId, [], rowContext);\n rowNavigationContextRef.current = null;\n }\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(() => {\n if (currentPage && pageDataCache.current[currentPage.id]) {\n const cachedData = pageDataCache.current[currentPage.id];\n\n Object.entries(cachedData).forEach(([componentId, data]) => {\n const model = renderedComponents.current[componentId];\n\n if (model && data) {\n if (data.newProps) {\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...data.newProps,\n });\n }\n\n const updatedAttributes = {\n ...model.get('attributes'),\n ...(data.newAttributes || {}),\n };\n\n model.set('attributes', updatedAttributes);\n\n if (model.view) {\n model.view.render();\n }\n }\n });\n\n delete pageDataCache.current[currentPage.id];\n }\n }, 150);\n\n const cacheCheckInterval = setInterval(() => {\n if (!currentPage || !pageDataCache.current[currentPage.id]) {\n return;\n }\n\n const cachedData = pageDataCache.current[currentPage.id];\n let appliedAny = false;\n\n Object.entries(cachedData).forEach(([componentId, data]) => {\n const model = renderedComponents.current[componentId];\n\n if (model && data) {\n if (data.newProps) {\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...data.newProps,\n });\n }\n\n const updatedAttributes = {\n ...model.get('attributes'),\n ...(data.newAttributes || {}),\n };\n\n model.set('attributes', updatedAttributes);\n\n if (model.view) {\n model.view.render();\n }\n\n appliedAny = true;\n }\n });\n\n if (appliedAny) {\n Object.keys(cachedData).forEach((componentId) => {\n if (renderedComponents.current[componentId]) {\n delete cachedData[componentId];\n }\n });\n\n if (Object.keys(cachedData).length === 0) {\n delete pageDataCache.current[currentPage.id];\n }\n }\n }, 100);\n\n setTimeout(() => {\n clearInterval(cacheCheckInterval);\n }, 5000);\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, effectiveCurrentPageId]);\n\n useEffect(() => {\n const editor = editorInstance.current;\n\n if (!editor || !isEditorAliveRef.current) {\n return;\n }\n\n if (isModeChangeFromToggle) {\n setIsTransitioning(true);\n }\n\n setComponentProperties(\n editorInstance.current as Editor,\n mode === 'preview',\n isStreaming ?? false,\n );\n\n const wrapper = editor.getWrapper();\n const shadcnComponents = wrapper?.find('[data-gjs-type=\"shadcn-generic\"]') || [];\n\n shadcnComponents.forEach((comp: Component) => {\n if (comp.view && typeof comp.view.render === 'function') {\n comp.view.render();\n }\n });\n\n if (isModeChangeFromToggle) {\n requestAnimationFrame(() => {\n setIsTransitioning(false);\n });\n }\n }, [mode, isStreaming ?? false]);\n\n useEffect(() => {\n const editor = editorInstance.current;\n const currentIsStreaming = isStreaming ?? false;\n const prevIsStreaming = isStreamingRef.current;\n\n if (editor && isEditorAliveRef.current && currentIsStreaming && !prevIsStreaming) {\n const wrapper = editor.getWrapper();\n const shadcnComponents = wrapper?.findType('shadcn-generic') || [];\n\n shadcnComponents.forEach((comp: Component) => {\n resetStreamingComponent(comp);\n });\n }\n\n isStreamingRef.current = currentIsStreaming;\n }, [isStreaming]);\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\nfunction GrapejsCanvas(props: GrapesjsCanvasProps) {\n const existingContext = usePageContext();\n\n if (existingContext) {\n return <GrapejsCanvasInternal {...props} />;\n }\n\n const normalizedJson = normalizeMultiPageJson(props.json);\n const pages = normalizedJson.pages.map(extractPageMetadata);\n const initialPageId = props.currentPageId || pages[0]?.id || '';\n\n return (\n <PageProvider pages={pages} initialPageId={initialPageId} onPageChange={props.onPageChange}>\n <GrapejsCanvasInternal {...props} />\n </PageProvider>\n );\n}\n\nexport default GrapejsCanvas;\n"],"mappings":"wLAAA,uDACA,MAAO,CAAAA,KAAK,EAAIC,SAAS,CAAEC,MAAM,CAAEC,QAAQ,KAAQ,OAAO,CAC1D;AACA,MAAO,CAAAC,QAAQ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A,CAACJ,YAAY,GAAE,CAAC,cAChBI,IAAA,QACEoT,GAAG,CAAE9J,SAAU,CACfjD,EAAE,CAAC,iBAAiB,CACpBtB,KAAK,CAAE,CACLsO,OAAO,CAAEnJ,eAAe,CAAG,CAAC,CAAG,CAAC,CAChCoJ,UAAU,CAAE,2BACd,CAAE,CACH,CAAC,EACY,CAEpB,CAEA,QAAS,CAAAC,aAAaA,CAACnM,KAA0B,CAAE,KAAAoM,QAAA,CACjD,GAAM,CAAAC,eAAe,CAAG3T,cAAc,CAAC,CAAC,CAExC,GAAI2T,eAAe,CAAE,CACnB,mBAAOzT,IAAA,CAAC6H,qBAAqB,CAAAnE,QAAA,IAAK0D,KAAK,CAAG,CAC5C,CAEA,GAAM,CAAAgC,cAAc,CAAG1J,sBAAsB,CAAC0H,KAAK,CAACY,IAAI,CAAC,CACzD,GAAM,CAAAzG,KAAK,CAAG6H,cAAc,CAAC7H,KAAK,CAAC+C,GAAG,CAAC/E,mBAAmB,CAAC,CAC3D,GAAM,CAAAmU,aAAa,CAAGtM,KAAK,CAAC2B,aAAa,IAAAyK,QAAA,CAAIjS,KAAK,CAAC,CAAC,CAAC,eAARiS,QAAA,CAAUnN,EAAE,GAAI,EAAE,CAE/D,mBACErG,IAAA,CAACH,YAAY,EAAC0B,KAAK,CAAEA,KAAM,CAACmS,aAAa,CAAEA,aAAc,CAACzK,YAAY,CAAE7B,KAAK,CAAC6B,YAAa,CAAAkK,QAAA,cACzFnT,IAAA,CAAC6H,qBAAqB,CAAAnE,QAAA,IAAK0D,KAAK,CAAG,CAAC,CACxB,CAElB,CAEA,cAAe,CAAAmM,aAAa","ignoreList":[]}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@peak-ai/canvas",
3
3
  "author": "squad-builder-experience",
4
4
  "license": "UNLICENSED",
5
- "version": "1.6.8",
5
+ "version": "1.6.9-rc.1",
6
6
  "description": "",
7
7
  "dependencies": {
8
8
  "@emotion/react": "^11.11.4",
@@ -9,7 +9,7 @@ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _us
9
9
  var actualChartWidth=Math.max(innerWidth,xScale.range()[1]||0);var bounds={minY:BEESWARM_CONFIG.RADIUS,maxY:innerHeight-BEESWARM_CONFIG.RADIUS,minX:0,maxX:actualChartWidth};var nodes=data.map(function(d){var initialY=yScaleWithPadding(d.value);var clampedY=Math.max(bounds.minY,Math.min(bounds.maxY,initialY));var groupCenterX=(xScale(d.group)||0)+(xScale.bandwidth()||0)/2;var bandwidth=xScale.bandwidth()||0;var maxSpread=bandwidth*BEESWARM_CONFIG.SPREAD_FACTOR;var randomOffset=(Math.random()-0.5)*maxSpread*BEESWARM_CONFIG.RANDOM_FACTOR;return _extends({},d,{groupCenterX:groupCenterX,x:groupCenterX+randomOffset,y:clampedY,radius:BEESWARM_CONFIG.RADIUS,maxSpread:maxSpread})});var simulation=null;try{simulation=forceSimulation(nodes).force("x",forceX(function(d){return d.groupCenterX}).strength(0.15)).force("y",forceY(function(d){var targetY=yScaleWithPadding(d.value);return Math.max(bounds.minY,Math.min(bounds.maxY,targetY))}).strength(1)).force("collide",forceCollide().radius(function(d){return d.radius+BEESWARM_CONFIG.COLLISION_PADDING}).strength(0.9).iterations(3));if(simulation&&typeof simulation.stop==="function"){simulation.stop()}}catch(error){setSimulatedNodes([].concat(nodes));return}var constrainNode=function constrainNode(node,isFinal){if(isFinal===void 0){isFinal=false}var correctY=yScaleWithPadding(node.value);node.y=Math.max(bounds.minY,Math.min(bounds.maxY,correctY));node.vy=0;var nodeMinX=node.groupCenterX-node.maxSpread;var nodeMaxX=node.groupCenterX+node.maxSpread;var constrainedMinX=Math.max(bounds.minX,nodeMinX);var constrainedMaxX=Math.min(bounds.maxX,nodeMaxX);if(isFinal){if(node.x<constrainedMinX){node.x=constrainedMinX}else if(node.x>constrainedMaxX){node.x=constrainedMaxX}}else{var overflowMargin=node.maxSpread*0.1;if(node.x<constrainedMinX-overflowMargin){node.x=constrainedMinX-overflowMargin;node.vx*=0.7}else if(node.x>constrainedMaxX+overflowMargin){node.x=constrainedMaxX+overflowMargin;node.vx*=0.7}}};if(simulation&&typeof simulation.tick==="function"){for(var i=0;i<BEESWARM_CONFIG.SIMULATION_ITERATIONS;i++){try{simulation.tick();nodes.forEach(function(node){return constrainNode(node,false)})}catch(error){break}}}// Final constraint pass
10
10
  nodes.forEach(function(node){constrainNode(node,true);node.vx=0});setSimulatedNodes([].concat(nodes))},[scales,data]);if(simulatedNodes.length===0||dimensions.width===0||!scales){return/*#__PURE__*/_jsx("div",{ref:containerRef,style:{width:"100%",height:"250px"}})}var margin={top:20,right:20,bottom:60,left:60};var xScale=scales.xScale,yScale=scales.yScale,innerWidth=scales.innerWidth,innerHeight=scales.innerHeight;var handleMouseOver=function handleMouseOver(event,node){if(containerRef.current){var containerRect=containerRef.current.getBoundingClientRect();var x=event.clientX-containerRect.left+10;var y=event.clientY-containerRect.top-10;showTooltip({tooltipLeft:x,tooltipTop:y,tooltipData:node})}};var actualChartWidth=Math.max(innerWidth,xScale.range()[1]||0);var actualSvgWidth=actualChartWidth+margin.left+margin.right;return/*#__PURE__*/_jsxs("div",{ref:containerRef,style:{width:"100%",height:"250px",position:"relative"},children:[/*#__PURE__*/_jsx("svg",{ref:svgRef,width:Math.max(dimensions.width,actualSvgWidth),height:dimensions.height,onMouseLeave:hideTooltip,children:/*#__PURE__*/_jsxs(Group,{left:margin.left,top:margin.top,children:[/*#__PURE__*/_jsx(GridRows,{scale:yScale,width:actualChartWidth,strokeDasharray:"3,3",stroke:"#e0e0e0",strokeOpacity:0.5}),/*#__PURE__*/_jsx(AxisLeft,{scale:yScale,tickStroke:"#666",stroke:"#666",tickLabelProps:function tickLabelProps(){return{fill:"#666",fontSize:12,textAnchor:"end",dy:"0.33em"}}}),/*#__PURE__*/_jsx(AxisBottom,{top:innerHeight,scale:xScale,tickStroke:"#666",stroke:"#666",tickLabelProps:function tickLabelProps(){return{fill:"#666",fontSize:12,textAnchor:"middle"}}}),simulatedNodes.map(function(node,i){return/*#__PURE__*/_jsx(Circle,{cx:node.x||0,cy:node.y||0,r:node.radius,fill:color,opacity:0.8,stroke:color,strokeWidth:1,onMouseOver:function onMouseOver(e){return handleMouseOver(e,node)},style:{cursor:"pointer"}},i)})]})}),tooltipOpen&&tooltipData&&tooltipLeft!==null&&tooltipLeft!==undefined&&tooltipTop!==null&&tooltipTop!==undefined&&/*#__PURE__*/_jsx(TooltipWithBounds,{left:tooltipLeft,top:tooltipTop,style:_extends({},defaultStyles,{backgroundColor:"white",border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px 12px",boxShadow:"0 2px 8px rgba(0,0,0,0.15)",fontSize:"12px",position:"absolute",zIndex:1000,pointerEvents:"none"}),children:/*#__PURE__*/_jsxs("div",{children:[/*#__PURE__*/_jsxs("div",{style:{marginBottom:"4px",fontWeight:600},children:[groupBy,": ",tooltipData.group]}),/*#__PURE__*/_jsxs("div",{children:[valueKey,": ",formatValue(tooltipData.value,decimalPrecision)]})]})})]})}function renderChartComponent(chartType,data,config,decimalPrecision){if(decimalPrecision===void 0){decimalPrecision=2}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,decimalPrecision:decimalPrecision})}),/*#__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+": "+formatValue(percent*100,decimalPrecision)+"%"}: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",decimalPrecision:decimalPrecision})})]}))}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",decimalPrecision:decimalPrecision})}),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,{decimalPrecision:decimalPrecision})}),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",decimalPrecision:decimalPrecision})}),/*#__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,decimalPrecision:decimalPrecision})}default:return/*#__PURE__*/_jsxs(PieChart,{children:[safeData.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true,decimalPrecision:decimalPrecision})}),/*#__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+": "+formatValue(percent*100,decimalPrecision)+"%"}: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)}},[]);useEffect(function(){},[containerRef.current]);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,decimalPrecision=allData.decimalPrecision;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;var renderChartData=effectiveChartData;if(chartType==="pie"){var safeChartData=Array.isArray(effectiveChartData)?effectiveChartData:[];var colors=getNColors(safeChartData.length);renderChartData=safeChartData.map(function(data,i){return _extends({},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 hasSampleData=isTemplateView&&sampleData!==undefined;var isLoading=!hasSampleData&&(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,renderChartData,config,decimalPrecision!=null?decimalPrecision:2)}))});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,{"data-slot":"bodyContent",className:"px-6",style:{minHeight:"250px"},children:/*#__PURE__*/_jsx("div",{ref:containerRef,children:chartUi})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData}),!isEditable&&/*#__PURE__*/_jsx("div",{className:"absolute bottom-2 right-2 flex items-center gap-1 z-10",children:/*#__PURE__*/_jsx(DownloadButton,{component:"chart",containerRef:containerRef,title:title,subtitle:subTitle,onDownloadCSV:(effectiveChartData==null?void 0:effectiveChartData.length)>0?/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var keys,headers,rows,csv,blob,url,anchor;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:keys=Object.keys(effectiveChartData[0]);headers=keys.map(function(key){var _config$key;return((_config$key=config[key])==null?void 0:_config$key.label)||key});rows=effectiveChartData.map(function(row){return keys.map(function(key){var val=row[key];var str=val===null||val===undefined?"":String(val);return str.includes(",")?"\""+str+"\"":str}).join(",")});csv=[headers.join(",")].concat(rows).join("\n");blob=new Blob([csv],{type:"text/csv"});url=URL.createObjectURL(blob);anchor=document.createElement("a");anchor.href=url;anchor.download=(title||"chart")+".csv";anchor.click();URL.revokeObjectURL(url);case 11:case"end":return _context.stop()}},_callee)})):undefined})})]})}function handleBulkAction(actionId,tableId,selectedValues,performInteraction,setSelectedIndices){return/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.next=2;return performInteraction({id:actionId,interactionType:"tableBulkButton",payload:{rows:selectedValues,tableId:tableId},affectedComponents:getAffectedComponentsWithLoader([tableId],true)});case 2:setSelectedIndices([]);case 3:case"end":return _context2.stop()}},_callee2)}))}function BulkActionButton(_ref12){var action=_ref12.action,isEditable=_ref12.isEditable,attributes=_ref12.attributes,selectedValues=_ref12.selectedValues,tableId=_ref12.tableId,performInteraction=_ref12.performInteraction,setSelectedIndices=_ref12.setSelectedIndices;var _useState11=useState(false),isLoading=_useState11[0],setIsLoading=_useState11[1];var _ref13=action.action||{},formMapper=_ref13.formMapper,formButtonText=_ref13.formButtonText;var _useButtonForm=useButtonForm({formMapper:formMapper,isSubmitting:isLoading,formButtonText:formButtonText,onSubmit:function(){var _onSubmit=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(formData){var result;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:setIsLoading(true);_context3.prev=1;_context3.next=4;return performInteraction({id:action.id,interactionType:"tableBulkButton",payload:{rows:selectedValues,tableId:tableId,formData:formData},affectedComponents:getAffectedComponentsWithLoader([tableId],true)});case 4:result=_context3.sent;if(!(result&&result.errors)){_context3.next=7;break}throw{detail:result.errorMsg};case 7:setSelectedIndices([]);case 8:_context3.prev=8;setIsLoading(false);return _context3.finish(8);case 11:case"end":return _context3.stop()}},_callee3,null,[[1,,8,11]])}));function onSubmit(_x){return _onSubmit.apply(this,arguments)}return onSubmit}()}),openForm=_useButtonForm.openForm,FormDialog=_useButtonForm.FormDialog;var handleClick=/*#__PURE__*/function(){var _ref14=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:if(openForm()){_context4.next=8;break}setIsLoading(true);_context4.prev=2;_context4.next=5;return handleBulkAction(action.id,tableId,selectedValues,performInteraction,setSelectedIndices)();case 5:_context4.prev=5;setIsLoading(false);return _context4.finish(5);case 8:case"end":return _context4.stop()}},_callee4,null,[[2,,5,8]])}));return function handleClick(){return _ref14.apply(this,arguments)}}();return/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsx(TooltipButton,{className:action["class"],isEditable:isEditable,attributes:{interactionApiInProgress:isLoading,disabled:attributes.disabled},variant:action.variant,size:action.size,text:action.text,tooltipContent:action.tooltipContent,interact:handleClick,isDisabled:selectedValues.length===0},action.id),FormDialog]})}export function renderTable(props){var _attributes$isEditabl3;var gjsModel=props.gjsModel,_props$performInterac3=props.performInteraction,performInteraction=_props$performInterac3===void 0?function(){}:_props$performInterac3,navigateToPage=props.navigateToPage,downloadTable=props.downloadTable,_props$isTemplateView4=props.isTemplateView,isTemplateView=_props$isTemplateView4===void 0?false:_props$isTemplateView4,rest=_objectWithoutPropertiesLoose(props,_excluded4);// Memoize filtered props to avoid re-filtering on every render
12
- var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState12=useState(initialData),allData=_useState12[0],setAllData=_useState12[1];var _useState13=useState([]),selectedIndices=_useState13[0],setSelectedIndices=_useState13[1];var cardRef=useRef(null);var _useState14=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState14[0],setAttributes=_useState14[1];var isEditable=(_attributes$isEditabl3=attributes.isEditable)!=null?_attributes$isEditabl3:false;var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$title2=allData.title,title=_allData$title2===void 0?"Title":_allData$title2,_allData$subTitle2=allData.subTitle,subTitle=_allData$subTitle2===void 0?"Subtitle":_allData$subTitle2,_allData$actions=allData.actions,actions=_allData$actions===void 0?[]:_allData$actions,_allData$bulkSelector=allData.bulkSelectorActions,bulkSelectorActions=_allData$bulkSelector===void 0?[]:_allData$bulkSelector,pagination=allData.pagination,sampleData=allData.sampleData,decimalPrecision=allData.decimalPrecision,columnWithChipClass=allData.columnWithChipClass,chipStylesMapping=allData.chipStylesMapping,sortableFromProps=allData.sortable;var effectiveRawData=isTemplateView&&sampleData!==undefined?sampleData:rawData;var data=Array.isArray(effectiveRawData)?effectiveRawData:[];var isBulkSelectionEnabled=Array.isArray(bulkSelectorActions)&&bulkSelectorActions.length>0;var headerMapper=function(){var cleaned=_extends({},rawHeaderMapper);if("id"in cleaned){delete cleaned.id}if(data.length>0){var dataKeys=Object.keys(data[0]||{});return Object.fromEntries(Object.entries(cleaned).filter(function(_ref15){var key=_ref15[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref17){var _ref16=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref16.sortColumn,sortDirection=_ref16.sortDirection;return sortColumn&&sortDirection?(_ref17={},_ref17[sortColumn]=sortDirection,_ref17):{}}();var _useState15=useState(250),scrollAreaHeight=_useState15[0],setScrollAreaHeight=_useState15[1];var calculateTableHeight=function calculateTableHeight(rowCount){var baseTableHeight=250;var headerHeight=48;var rowHeight=40;var calculatedHeight=headerHeight+rowCount*rowHeight;setScrollAreaHeight(Math.min(calculatedHeight,baseTableHeight))};useEffect(function(){calculateTableHeight(Array.isArray(data)?data.length:0)},[data]);useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var parsedData=function(){if(typeof data==="object"&&data!==null&&!Array.isArray(data)&&data.name==="__peak_placeholder"){return[]}if(!Array.isArray(data)){return[]}return data.map(function(datum){var newData=_extends({},datum);delete newData.id;return newData})}();var selectedValues=useMemo(function(){return selectedIndices.map(function(idx){return data==null?void 0:data[idx]}).filter(Boolean)},[selectedIndices,data]);function onRowAction(_x2,_x3,_x4){return _onRowAction.apply(this,arguments)}function _onRowAction(){_onRowAction=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(rowIndex,actionId,formData){var id,result;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:id=gjsModel.get("id");_context5.next=3;return performInteraction({id:actionId,interactionType:"tableButton",payload:_extends({row:data[rowIndex],tableId:id},formData&&{formData:formData}),affectedComponents:[]});case 3:result=_context5.sent;if(!(result&&result.errors)){_context5.next=6;break}throw{detail:result.errorMsg};case 6:case"end":return _context5.stop()}},_callee5)}));return _onRowAction.apply(this,arguments)}function onPageChange(_x5,_x6){return _onPageChange.apply(this,arguments)}function _onPageChange(){_onPageChange=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(pageNumber,pageSize){var _gjsModel$get2;var id,_ref18,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1)switch(_context6.prev=_context6.next){case 0:id=gjsModel.get("id");_ref18=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref18.sortColumn,sortDirection=_ref18.sortDirection;_context6.next=4;return performInteraction({id:id,interactionType:"pagination",payload:_extends({pageNumber:pageNumber,pageSize:pageSize},sortColumn&&sortDirection&&{sortColumn:sortColumn,sortDirection:sortDirection}),affectedComponents:getAffectedComponentsWithLoader([id],true)});case 4:setSelectedIndices([]);case 5:case"end":return _context6.stop()}},_callee6)}));return _onPageChange.apply(this,arguments)}function handleSort(_x7,_x8){return _handleSort.apply(this,arguments)}function _handleSort(){_handleSort=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(column,direction){var currentProps,id;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1)switch(_context7.prev=_context7.next){case 0:currentProps=gjsModel.get("componentProps");id=gjsModel.get("id");gjsModel.set("componentProps",_extends({},currentProps,{sortColumn:direction?column:null,sortDirection:direction}));_context7.next=5;return performInteraction({id:id,interactionType:"tableSort",payload:{sortColumn:direction?column:null,sortDirection:direction,tableId:id},affectedComponents:getAffectedComponentsWithLoader([id],true)});case 5:setSelectedIndices([]);case 6:case"end":return _context7.stop()}},_callee7)}));return _handleSort.apply(this,arguments)}return/*#__PURE__*/_jsxs(Card,{ref:cardRef,className:"shadow border relative flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsxs("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})]}),isBulkSelectionEnabled&&/*#__PURE__*/_jsx("div",{className:cn("flex gap-2",isEditable&&"pr-8"),children:bulkSelectorActions.map(function(action){return/*#__PURE__*/_jsx(BulkActionButton,{action:action,isEditable:isEditable,attributes:attributes,selectedValues:selectedValues,tableId:gjsModel.get("id"),performInteraction:performInteraction,setSelectedIndices:setSelectedIndices},action.id)})})]})}),/*#__PURE__*/_jsx(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-1 flex flex-col overflow-hidden",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing?renderNoDataFallback():/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:!(isTemplateView&&sampleData!==undefined)&&(attributes.interactionApiInProgress||attributes.loading),onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,sortable:sortableFromProps!==false,otherProps:rest,height:scrollAreaHeight,decimalPrecision:decimalPrecision,columnWithChipClass:columnWithChipClass,chipStylesMapping:chipStylesMapping,navigateToPage:navigateToPage,isBulkSelectionEnabled:isBulkSelectionEnabled,selectedIndices:selectedIndices,setSelectedIndices:setSelectedIndices,title:title,onDownload:downloadTable?function(limit){return downloadTable({tableId:gjsModel.get("id"),title:title,limit:limit,headerMapper:headerMapper})}:undefined})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",tableActions:actions,firstRowData:Array.isArray(data)&&data.length>0?data[0]:{},isVisible:isEditable,componentProps:allData})]})}export function renderTab(props){var tabsWidth=157;var safeTabs=Array.isArray(props.tabs)?props.tabs:[];var showFallback=safeTabs.length===0;if(safeTabs.length>4){tabsWidth=157}var defaultValue=props.defaultValue||(safeTabs.length>0?safeTabs[0]:undefined);useEffect(function(){if(props.gjsModel){var componentId=props.gjsModel.get("id");var childrenCount=props.gjsModel.components().length;if(safeTabs.length>0&&childrenCount===0){// eslint-disable-next-line no-console
12
+ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState12=useState(initialData),allData=_useState12[0],setAllData=_useState12[1];var _useState13=useState([]),selectedIndices=_useState13[0],setSelectedIndices=_useState13[1];var cardRef=useRef(null);var _useState14=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState14[0],setAttributes=_useState14[1];var isEditable=(_attributes$isEditabl3=attributes.isEditable)!=null?_attributes$isEditabl3:false;var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$title2=allData.title,title=_allData$title2===void 0?"Title":_allData$title2,_allData$subTitle2=allData.subTitle,subTitle=_allData$subTitle2===void 0?"Subtitle":_allData$subTitle2,_allData$actions=allData.actions,actions=_allData$actions===void 0?[]:_allData$actions,_allData$bulkSelector=allData.bulkSelectorActions,bulkSelectorActions=_allData$bulkSelector===void 0?[]:_allData$bulkSelector,pagination=allData.pagination,sampleData=allData.sampleData,decimalPrecision=allData.decimalPrecision,columnWithChipClass=allData.columnWithChipClass,chipStylesMapping=allData.chipStylesMapping,sortableFromProps=allData.sortable;var effectiveRawData=isTemplateView&&sampleData!==undefined?sampleData:rawData;var data=Array.isArray(effectiveRawData)?effectiveRawData:[];var isBulkSelectionEnabled=Array.isArray(bulkSelectorActions)&&bulkSelectorActions.length>0;var headerMapper=function(){var cleaned=_extends({},rawHeaderMapper);if("id"in cleaned){delete cleaned.id}if(data.length>0){var dataKeys=Object.keys(data[0]||{});return Object.fromEntries(Object.entries(cleaned).filter(function(_ref15){var key=_ref15[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref17){var _ref16=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref16.sortColumn,sortDirection=_ref16.sortDirection;return sortColumn&&sortDirection?(_ref17={},_ref17[sortColumn]=sortDirection,_ref17):{}}();var _useState15=useState(250),scrollAreaHeight=_useState15[0],setScrollAreaHeight=_useState15[1];var calculateTableHeight=function calculateTableHeight(rowCount){var baseTableHeight=250;var headerHeight=48;var rowHeight=40;var calculatedHeight=headerHeight+rowCount*rowHeight;var total=pagination==null?void 0:pagination.totalCount;var height=Math.min(calculatedHeight,1100);if(total){height=Math.min(calculatedHeight,baseTableHeight)}setScrollAreaHeight(height)};useEffect(function(){calculateTableHeight(Array.isArray(data)?data.length:0)},[data]);useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var parsedData=function(){if(typeof data==="object"&&data!==null&&!Array.isArray(data)&&data.name==="__peak_placeholder"){return[]}if(!Array.isArray(data)){return[]}return data.map(function(datum){var newData=_extends({},datum);delete newData.id;return newData})}();var selectedValues=useMemo(function(){return selectedIndices.map(function(idx){return data==null?void 0:data[idx]}).filter(Boolean)},[selectedIndices,data]);function onRowAction(_x2,_x3,_x4){return _onRowAction.apply(this,arguments)}function _onRowAction(){_onRowAction=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(rowIndex,actionId,formData){var id,result;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:id=gjsModel.get("id");_context5.next=3;return performInteraction({id:actionId,interactionType:"tableButton",payload:_extends({row:data[rowIndex],tableId:id},formData&&{formData:formData}),affectedComponents:[]});case 3:result=_context5.sent;if(!(result&&result.errors)){_context5.next=6;break}throw{detail:result.errorMsg};case 6:case"end":return _context5.stop()}},_callee5)}));return _onRowAction.apply(this,arguments)}function onPageChange(_x5,_x6){return _onPageChange.apply(this,arguments)}function _onPageChange(){_onPageChange=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(pageNumber,pageSize){var _gjsModel$get2;var id,_ref18,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1)switch(_context6.prev=_context6.next){case 0:id=gjsModel.get("id");_ref18=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref18.sortColumn,sortDirection=_ref18.sortDirection;_context6.next=4;return performInteraction({id:id,interactionType:"pagination",payload:_extends({pageNumber:pageNumber,pageSize:pageSize},sortColumn&&sortDirection&&{sortColumn:sortColumn,sortDirection:sortDirection}),affectedComponents:getAffectedComponentsWithLoader([id],true)});case 4:setSelectedIndices([]);case 5:case"end":return _context6.stop()}},_callee6)}));return _onPageChange.apply(this,arguments)}function handleSort(_x7,_x8){return _handleSort.apply(this,arguments)}function _handleSort(){_handleSort=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(column,direction){var currentProps,id;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1)switch(_context7.prev=_context7.next){case 0:currentProps=gjsModel.get("componentProps");id=gjsModel.get("id");gjsModel.set("componentProps",_extends({},currentProps,{sortColumn:direction?column:null,sortDirection:direction}));_context7.next=5;return performInteraction({id:id,interactionType:"tableSort",payload:{sortColumn:direction?column:null,sortDirection:direction,tableId:id},affectedComponents:getAffectedComponentsWithLoader([id],true)});case 5:setSelectedIndices([]);case 6:case"end":return _context7.stop()}},_callee7)}));return _handleSort.apply(this,arguments)}return/*#__PURE__*/_jsxs(Card,{ref:cardRef,className:"shadow border relative flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsxs("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})]}),isBulkSelectionEnabled&&/*#__PURE__*/_jsx("div",{className:cn("flex gap-2",isEditable&&"pr-8"),children:bulkSelectorActions.map(function(action){return/*#__PURE__*/_jsx(BulkActionButton,{action:action,isEditable:isEditable,attributes:attributes,selectedValues:selectedValues,tableId:gjsModel.get("id"),performInteraction:performInteraction,setSelectedIndices:setSelectedIndices},action.id)})})]})}),/*#__PURE__*/_jsx(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-1 flex flex-col overflow-hidden",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing?renderNoDataFallback():/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:!(isTemplateView&&sampleData!==undefined)&&(attributes.interactionApiInProgress||attributes.loading),onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,sortable:sortableFromProps!==false,otherProps:rest,height:scrollAreaHeight,decimalPrecision:decimalPrecision,columnWithChipClass:columnWithChipClass,chipStylesMapping:chipStylesMapping,navigateToPage:navigateToPage,isBulkSelectionEnabled:isBulkSelectionEnabled,selectedIndices:selectedIndices,setSelectedIndices:setSelectedIndices,title:title,onDownload:downloadTable?function(limit){return downloadTable({tableId:gjsModel.get("id"),title:title,limit:limit,headerMapper:headerMapper})}:undefined})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",tableActions:actions,firstRowData:Array.isArray(data)&&data.length>0?data[0]:{},isVisible:isEditable,componentProps:allData})]})}export function renderTab(props){var tabsWidth=157;var safeTabs=Array.isArray(props.tabs)?props.tabs:[];var showFallback=safeTabs.length===0;if(safeTabs.length>4){tabsWidth=157}var defaultValue=props.defaultValue||(safeTabs.length>0?safeTabs[0]:undefined);useEffect(function(){if(props.gjsModel){var componentId=props.gjsModel.get("id");var childrenCount=props.gjsModel.components().length;if(safeTabs.length>0&&childrenCount===0){// eslint-disable-next-line no-console
13
13
  console.warn("Tab component "+componentId+" has "+safeTabs.length+" tabs but no child components. This may indicate lost tab content.")}}},[safeTabs.length,props.gjsModel]);return/*#__PURE__*/_jsxs(Tabs,{defaultValue:defaultValue,children:[/*#__PURE__*/_jsx("div",{className:"text-center mb-4",children:/*#__PURE__*/_jsx(TabsList,{className:"bg-[#F9F9FE] border border-[#D4D5DE] p-1 rounded-lg h-auto",children:safeTabs.length>0?safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsTrigger,{value:tab,className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},children:tab},tab)}):/*#__PURE__*/_jsx(TabsTrigger,{value:"no-data",className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},disabled:true,children:"No tabs"})})}),showFallback?/*#__PURE__*/_jsx(TabsContent,{value:defaultValue||"no-data",className:"tabs-content","data-fallback":"true",children:renderNoDataFallback()}):safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsContent,{value:tab,className:"tabs-content"},tab)})]})}export function renderMarkdown(props){var _attributes$isEditabl4;var gjsModel=props.gjsModel,_props$isTemplateView5=props.isTemplateView,isTemplateView=_props$isTemplateView5===void 0?false:_props$isTemplateView5,rest=_objectWithoutPropertiesLoose(props,_excluded5);// Memoize filtered props to avoid re-filtering on every render
14
14
  var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState16=useState(initialData),allData=_useState16[0],setAllData=_useState16[1];var _useState17=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState17[0],setAttributes=_useState17[1];var isEditable=(_attributes$isEditabl4=attributes.isEditable)!=null?_attributes$isEditabl4:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var _useState18=useState(false),isEditing=_useState18[0],setIsEditing=_useState18[1];var _useState19=useState(false),isEditingHeading=_useState19[0],setIsEditingHeading=_useState19[1];var editRef=useRef(null);var headingEditRef=useRef(null);var startEditing=function startEditing(){setIsEditing(true);setTimeout(function(){setupEditor()},0)};var startEditingHeading=function startEditingHeading(){setIsEditingHeading(true);setTimeout(function(){setupHeadingEditor()},0)};var setupEditor=function setupEditor(){if(!editRef.current){return}var editor=editRef.current;editor.innerHTML="";var effectiveText=isTemplateView&&allData.sampleData!==undefined?allData.sampleData:allData.summaryText;editor.textContent=effectiveText;editor.focus()};var setupHeadingEditor=function setupHeadingEditor(){if(!headingEditRef.current){return}var editor=headingEditRef.current;editor.innerHTML="";editor.textContent=allData.summaryHeading||"Insights";editor.focus()};// Save changes and exit editing mode
15
15
  var saveChanges=function saveChanges(){if(!editRef.current){return}var content=editRef.current.innerText||"";setAllData(function(prev){return _extends({},prev,{summaryText:content})});setIsEditing(false);editRef.current.innerHTML=""};var saveHeadingChanges=function saveHeadingChanges(){if(!headingEditRef.current){return}var content=headingEditRef.current.innerText||"Insights";setAllData(function(prev){return _extends({},prev,{summaryHeading:content})});setIsEditingHeading(false);headingEditRef.current.innerHTML=""};var markdownStyles={ul:{props:{className:"list-disc"}},h1:{props:{className:"text-4xl font-bold leading-[4rem]"}},h2:{props:{className:"text-3xl font-bold leading-[3rem]"}},h3:{props:{className:"text-2xl font-bold leading-[2rem]"}},h4:{props:{className:"text-xl font-bold leading-[2.5rem]"}},h5:{props:{className:"text-lg font-bold leading-[2.5rem]"}},h6:{props:{className:"text-base font-bold leading-[2rem]"}}};var summaryText=allData.summaryText,summaryHeading=allData.summaryHeading,sampleData=allData.sampleData;var rawSummaryText=isTemplateView&&sampleData!==undefined?sampleData:summaryText;var effectiveSummaryText=typeof rawSummaryText==="string"?rawSummaryText:"";var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var hasSampleData=isTemplateView&&allData.sampleData!==undefined;var isLoading=!hasSampleData&&(attributes.loading&&!hasError&&!hasMissing||attributes.interactionApiInProgress);if(isLoading){return/*#__PURE__*/_jsx(MarkdownLoader,{})}if(hasError||hasMissing){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:summaryHeading||"Insights"}),/*#__PURE__*/_jsxs("div",{className:"w-full py-8 flex flex-col items-center justify-center px-6 text-center",style:{minHeight:"180px"},children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-12 h-12 text-gray-400 mb-2"}),/*#__PURE__*/_jsx("h3",{className:"text-lg font-medium text-gray-900",children:"No data available"}),/*#__PURE__*/_jsx("p",{className:"mt-2 text-sm text-gray-500 max-w-md",children:"Check your filters or try a different time range."})]}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}if(!isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:summaryHeading||"Insights"}),/*#__PURE__*/_jsx("div",{"data-slot":"summaryText",children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:effectiveSummaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em] relative"},rest,{children:[isEditingHeading?/*#__PURE__*/_jsx("div",{ref:headingEditRef,contentEditable:true,onBlur:saveHeadingChanges,"data-slot":"summaryHeading",className:"text-xl font-semibold text-left",suppressContentEditableWarning:true}):/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",onClick:startEditingHeading,"data-slot":"summaryHeading",children:allData.summaryHeading||"Insights"}),isEditing?/*#__PURE__*/_jsx("div",{ref:editRef,contentEditable:true,onBlur:saveChanges,"data-slot":"summaryText",className:"p-2 min-h-[100px] whitespace-pre-wrap",suppressContentEditableWarning:true,style:{whiteSpace:"pre-wrap",wordWrap:"break-word"}}):/*#__PURE__*/_jsx("div",{onClick:startEditing,"data-slot":"summaryText",style:{whiteSpace:"pre-wrap",wordWrap:"break-word"},children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:effectiveSummaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}export function renderButton(props){var _attributes$isEditabl5;var gjsModel=props.gjsModel,_props$performInterac4=props.performInteraction,performInteraction=_props$performInterac4===void 0?function(){}:_props$performInterac4,navigateToPage=props.navigateToPage;var _useState20=useState(_extends({},props)),allData=_useState20[0],setAllData=_useState20[1];var _useState21=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState21[0],setAttributes=_useState21[1];var isEditable=(_attributes$isEditabl5=attributes.isEditable)!=null?_attributes$isEditabl5:false;useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(_extends({},gjsModel.get("componentProps")))})},[]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var text=allData.text,className=allData.className,payload=allData.payload,_allData$variant=allData.variant,variant=_allData$variant===void 0?"default":_allData$variant,_allData$size=allData.size,size=_allData$size===void 0?"sm":_allData$size,affectedComponents=allData.affectedComponents,tooltipContent=allData.tooltipContent,onClick=allData.onClick,action=allData.action;var _ref19=action||{},formMapper=_ref19.formMapper,formButtonText=_ref19.formButtonText;var _useButtonForm2=useButtonForm({formMapper:formMapper,isSubmitting:attributes.interactionApiInProgress||false,onSubmit:function(){var _onSubmit2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(formData){var id,result;return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1)switch(_context8.prev=_context8.next){case 0:id=gjsModel.get("id");_context8.next=3;return performInteraction({id:id,interactionType:"button",affectedComponents:getAffectedComponentsWithLoader([id].concat(affectedComponents),true),payload:_extends({},payload,{formData:formData})});case 3:result=_context8.sent;if(!(result&&result.errors)){_context8.next=6;break}throw{detail:result.errorMsg};case 6:case"end":return _context8.stop()}},_callee8)}));function onSubmit(_x9){return _onSubmit2.apply(this,arguments)}return onSubmit}(),formButtonText:formButtonText}),openForm=_useButtonForm2.openForm,FormDialog=_useButtonForm2.FormDialog;function interact(){if(openForm()){return}if(onClick&&onClick.action==="navigateToPage"){if(navigateToPage){navigateToPage(onClick.targetPageId)}return}var id=gjsModel.get("id");performInteraction({id:id,interactionType:"button",affectedComponents:getAffectedComponentsWithLoader([id].concat(affectedComponents),true),payload:payload})}return/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsx(TooltipButton,{className:className,isEditable:isEditable,interact:interact,attributes:attributes,variant:variant,size:size,text:text,tooltipContent:tooltipContent}),FormDialog]})}var renderActionCardWithWrapper=function renderActionCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"ActionCard"}),children:renderActionCard(props)})};var renderButtonWithWrapper=function renderButtonWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Button"}),children:renderButton(props)})};var renderCardWithWrapper=function renderCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Card"}),children:renderCard(props)})};var renderChartWithWrapper=function renderChartWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Chart"}),children:renderChart(props)})};var renderFilterWithWrapper=function renderFilterWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Filter"}),children:renderFilter(props)})};var renderUnifiedFilterWithWrapper=function renderUnifiedFilterWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"UnifiedFilter"}),children:renderUnifiedFilter(props)})};var renderMarkdownWithWrapper=function renderMarkdownWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Markdown"}),children:renderMarkdown(props)})};var renderSearchWithWrapper=function renderSearchWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Search"}),children:renderSearch(props)})};var renderTableWithWrapper=function renderTableWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Table"}),children:renderTable(props)})};var renderTabWithWrapper=function renderTabWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Tabs"}),children:renderTab(props)})};function renderActions(props){var actions=props.actions,_props$isEditable=props.isEditable,isEditable=_props$isEditable===void 0?false:_props$isEditable,gjsModel=props.gjsModel;if(actions===null){return/*#__PURE__*/_jsx("div",{})}if(!Array.isArray(actions)||actions.length===0){return/*#__PURE__*/_jsx("div",{className:"bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none relative",children:/*#__PURE__*/_jsx(CardLoader,{})})}return/*#__PURE__*/_jsx("div",{className:"dashboard-cards flex flex-wrap gap-4",children:actions.map(function(action,index){var icon=action.icon,title=action.title,description=action.description;return/*#__PURE__*/_jsx("div",{className:"flex-1 min-w-[200px]",children:renderActionCard({icon:icon,headerContent:title,bodyContent:description,isEditable:isEditable,gjsModel:gjsModel})},index)})})}var renderActionsWithWrapper=function renderActionsWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Actions"}),children:renderActions(props)})};export function getRenderers(){return{ActionCard:renderActionCardWithWrapper,Actions:renderActionsWithWrapper,Button:renderButtonWithWrapper,Card:renderCardWithWrapper,Chart:renderChartWithWrapper,Filter:renderFilterWithWrapper,Markdown:renderMarkdownWithWrapper,Search:renderSearchWithWrapper,Table:renderTableWithWrapper,Tabs:renderTabWithWrapper,UnifiedFilter:renderUnifiedFilterWithWrapper}}