@peak-ai/canvas 1.6.7 → 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 });\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,mBAAmB,CAExC,OAASC,eAAe,KAAQ,aAAa,CAC7C,OAASC,W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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,KAA6B,UAAU,CACtD,MAAO,kCAAkC,CACzC,MAAO,C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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.7",
5
+ "version": "1.6.9-rc.1",
6
6
  "description": "",
7
7
  "dependencies": {
8
8
  "@emotion/react": "^11.11.4",
@@ -28,6 +28,7 @@ export type DataTableProps = {
28
28
  onPageChange?: (pageNumber: number, pageSize: number) => void;
29
29
  onSort?: (column: string, direction: SortDirection) => void;
30
30
  sortConfig?: Record<string, SortDirection>;
31
+ sortable?: boolean;
31
32
  otherProps?: Record<string, any>;
32
33
  height?: string | number;
33
34
  decimalPrecision?: number;
@@ -40,5 +41,5 @@ export type DataTableProps = {
40
41
  title?: string;
41
42
  onDownload?: (limit: number) => Promise<void>;
42
43
  };
43
- export declare function DataTable({ data, headerMapper, className, actions, isEditable, pagination, isLoading, onRowAction, onPageChange, onSort, sortConfig, otherProps, height, decimalPrecision, columnWithChipClass, chipStylesMapping, navigateToPage, isBulkSelectionEnabled, selectedIndices, setSelectedIndices, title, onDownload, }: DataTableProps): import("react/jsx-runtime").JSX.Element;
44
+ export declare function DataTable({ data, headerMapper, className, actions, isEditable, pagination, isLoading, onRowAction, onPageChange, onSort, sortConfig, sortable: sortableGlobal, otherProps, height, decimalPrecision, columnWithChipClass, chipStylesMapping, navigateToPage, isBulkSelectionEnabled, selectedIndices, setSelectedIndices, title, onDownload, }: DataTableProps): import("react/jsx-runtime").JSX.Element;
44
45
  export {};
@@ -7,10 +7,10 @@ if(value===null||value===undefined){return""}var str=String(value);return str.tr
7
7
  * Generates a stable hash based on unique value sets per column.
8
8
  * This hash is order-independent - it only changes when the set of unique values changes,
9
9
  * not when rows are reordered (e.g., during sorting).
10
- */function getUniqueValuesHash(data,columnWithChipClass){if(!Array.isArray(data)||data.length===0){return""}var availableKeys=Object.keys(data[0]||{});var hashParts={};Object.keys(columnWithChipClass).forEach(function(columnKey){if(!availableKeys.includes(columnKey)){return}var chipMode=getChipMode(columnWithChipClass,columnKey);if(chipMode==="useRandom"){var uniqueNormalizedValues=new Set;data.forEach(function(row){var value=row[columnKey];var normalizedKey=normalizeValue(value);if(normalizedKey){uniqueNormalizedValues.add(normalizedKey)}});var sortedUniqueValues=Array.from(uniqueNormalizedValues).sort();hashParts[columnKey]=sortedUniqueValues}});return JSON.stringify(hashParts)}export function DataTable(_ref){var _ref2,_pagination$values$pa,_pagination$values,_ref3,_pagination$values$pa2,_pagination$values2,_pagination$totalCoun,_pagination$totalCoun2;var _ref$data=_ref.data,data=_ref$data===void 0?[]:_ref$data,_ref$headerMapper=_ref.headerMapper,headerMapper=_ref$headerMapper===void 0?{}:_ref$headerMapper,_ref$className=_ref.className,className=_ref$className===void 0?"":_ref$className,_ref$actions=_ref.actions,actions=_ref$actions===void 0?[]:_ref$actions,_ref$isEditable=_ref.isEditable,isEditable=_ref$isEditable===void 0?false:_ref$isEditable,pagination=_ref.pagination,_ref$isLoading=_ref.isLoading,isLoading=_ref$isLoading===void 0?false:_ref$isLoading,onRowAction=_ref.onRowAction,onPageChange=_ref.onPageChange,onSort=_ref.onSort,sortConfig=_ref.sortConfig,_ref$otherProps=_ref.otherProps,otherProps=_ref$otherProps===void 0?{}:_ref$otherProps,height=_ref.height,_ref$decimalPrecision=_ref.decimalPrecision,decimalPrecision=_ref$decimalPrecision===void 0?2:_ref$decimalPrecision,_ref$columnWithChipCl=_ref.columnWithChipClass,columnWithChipClass=_ref$columnWithChipCl===void 0?{}:_ref$columnWithChipCl,_ref$chipStylesMappin=_ref.chipStylesMapping,chipStylesMapping=_ref$chipStylesMappin===void 0?{}:_ref$chipStylesMappin,navigateToPage=_ref.navigateToPage,_ref$isBulkSelectionE=_ref.isBulkSelectionEnabled,isBulkSelectionEnabled=_ref$isBulkSelectionE===void 0?false:_ref$isBulkSelectionE,_ref$selectedIndices=_ref.selectedIndices,selectedIndices=_ref$selectedIndices===void 0?[]:_ref$selectedIndices,setSelectedIndices=_ref.setSelectedIndices,title=_ref.title,onDownload=_ref.onDownload;if(!data||data.length===0){return/*#__PURE__*/_jsx(Fragment,{children:/*#__PURE__*/_jsx("div",{className:"flex flex-col overflow-hidden",children:/*#__PURE__*/_jsx("div",{"data-slot":"table-container",className:"aspect-auto w-full",style:{height:"auto",minHeight:"180px"},children:isLoading?/*#__PURE__*/_jsx(TableLoader,{}):renderNoDataFallback()})})})}var _useState=useState(null),activeSortColumn=_useState[0],setActiveSortColumn=_useState[1];var _useState2=useState({}),sortDirections=_useState2[0],setSortDirections=_useState2[1];var _useState3=useState(null),activeRowIndex=_useState3[0],setActiveRowIndex=_useState3[1];var _useState4=useState(null),activeAction=_useState4[0],setActiveAction=_useState4[1];var _useState5=useState(false),isFormSubmitting=_useState5[0],setIsFormSubmitting=_useState5[1];var _useState6=useState(null),loadingActionKey=_useState6[0],setLoadingActionKey=_useState6[1];var _useState7=useState(Number((_ref2=(_pagination$values$pa=pagination==null||(_pagination$values=pagination.values)==null?void 0:_pagination$values.pageNumber)!=null?_pagination$values$pa:pagination==null?void 0:pagination.initialPage)!=null?_ref2:1)),pageNumber=_useState7[0],setPageNumber=_useState7[1];var _useState8=useState(Number((_ref3=(_pagination$values$pa2=pagination==null||(_pagination$values2=pagination.values)==null?void 0:_pagination$values2.pageSize)!=null?_pagination$values$pa2:pagination==null?void 0:pagination.initialPageSize)!=null?_ref3:10)),pageSize=_useState8[0],setPageSize=_useState8[1];var _useState9=useState(Math.ceil(((pagination==null?void 0:pagination.totalCount)||0)/pageSize)||1),totalPages=_useState9[0],setTotalPages=_useState9[1];var _useState10=useState({}),chipColorMap=_useState10[0],setChipColorMap=_useState10[1];var _useState11=useState(null),openDropdownIndex=_useState11[0],setOpenDropdownIndex=_useState11[1];var prevDataHashRef=useRef("");useEffect(function(){var _ref4,_pagination$values$pa3,_pagination$values3,_ref5,_pagination$values$pa4,_pagination$values4;setPageNumber(Number((_ref4=(_pagination$values$pa3=pagination==null||(_pagination$values3=pagination.values)==null?void 0:_pagination$values3.pageNumber)!=null?_pagination$values$pa3:pagination==null?void 0:pagination.initialPage)!=null?_ref4:1));setPageSize(Number((_ref5=(_pagination$values$pa4=pagination==null||(_pagination$values4=pagination.values)==null?void 0:_pagination$values4.pageSize)!=null?_pagination$values$pa4:pagination==null?void 0:pagination.initialPageSize)!=null?_ref5:25))},[pagination]);useEffect(function(){setTotalPages(Math.ceil(((pagination==null?void 0:pagination.totalCount)||0)/pageSize)||1)},[pagination==null?void 0:pagination.totalCount,pageSize]);useEffect(function(){if(sortConfig){setSortDirections(sortConfig);var first=Object.keys(sortConfig)[0];if(first){setActiveSortColumn(first)}}},[sortConfig]);useEffect(function(){if(sortConfig!=null&&sortConfig.sortColumn||sortConfig!=null&&sortConfig.sortDirection){sortConfig.sortColumn=null;sortConfig.sortDirection=null}setActiveSortColumn(null);setSortDirections({})},[]);var computedColorMap=useMemo(function(){if(!Array.isArray(data)||data.length===0){return{}}// Get available column keys from first row
10
+ */function getUniqueValuesHash(data,columnWithChipClass){if(!Array.isArray(data)||data.length===0){return""}var availableKeys=Object.keys(data[0]||{});var hashParts={};Object.keys(columnWithChipClass).forEach(function(columnKey){if(!availableKeys.includes(columnKey)){return}var chipMode=getChipMode(columnWithChipClass,columnKey);if(chipMode==="useRandom"){var uniqueNormalizedValues=new Set;data.forEach(function(row){var value=row[columnKey];var normalizedKey=normalizeValue(value);if(normalizedKey){uniqueNormalizedValues.add(normalizedKey)}});var sortedUniqueValues=Array.from(uniqueNormalizedValues).sort();hashParts[columnKey]=sortedUniqueValues}});return JSON.stringify(hashParts)}export function DataTable(_ref){var _ref2,_pagination$values$pa,_pagination$values,_ref3,_pagination$values$pa2,_pagination$values2,_pagination$totalCoun,_pagination$totalCoun2;var _ref$data=_ref.data,data=_ref$data===void 0?[]:_ref$data,_ref$headerMapper=_ref.headerMapper,headerMapper=_ref$headerMapper===void 0?{}:_ref$headerMapper,_ref$className=_ref.className,className=_ref$className===void 0?"":_ref$className,_ref$actions=_ref.actions,actions=_ref$actions===void 0?[]:_ref$actions,_ref$isEditable=_ref.isEditable,isEditable=_ref$isEditable===void 0?false:_ref$isEditable,pagination=_ref.pagination,_ref$isLoading=_ref.isLoading,isLoading=_ref$isLoading===void 0?false:_ref$isLoading,onRowAction=_ref.onRowAction,onPageChange=_ref.onPageChange,onSort=_ref.onSort,sortConfig=_ref.sortConfig,_ref$sortable=_ref.sortable,sortableGlobal=_ref$sortable===void 0?true:_ref$sortable,_ref$otherProps=_ref.otherProps,otherProps=_ref$otherProps===void 0?{}:_ref$otherProps,height=_ref.height,_ref$decimalPrecision=_ref.decimalPrecision,decimalPrecision=_ref$decimalPrecision===void 0?2:_ref$decimalPrecision,_ref$columnWithChipCl=_ref.columnWithChipClass,columnWithChipClass=_ref$columnWithChipCl===void 0?{}:_ref$columnWithChipCl,_ref$chipStylesMappin=_ref.chipStylesMapping,chipStylesMapping=_ref$chipStylesMappin===void 0?{}:_ref$chipStylesMappin,navigateToPage=_ref.navigateToPage,_ref$isBulkSelectionE=_ref.isBulkSelectionEnabled,isBulkSelectionEnabled=_ref$isBulkSelectionE===void 0?false:_ref$isBulkSelectionE,_ref$selectedIndices=_ref.selectedIndices,selectedIndices=_ref$selectedIndices===void 0?[]:_ref$selectedIndices,setSelectedIndices=_ref.setSelectedIndices,title=_ref.title,onDownload=_ref.onDownload;if(!data||data.length===0){return/*#__PURE__*/_jsx(Fragment,{children:/*#__PURE__*/_jsx("div",{className:"flex flex-col overflow-hidden",children:/*#__PURE__*/_jsx("div",{"data-slot":"table-container",className:"aspect-auto w-full",style:{height:"auto",minHeight:"180px"},children:isLoading?/*#__PURE__*/_jsx(TableLoader,{}):renderNoDataFallback()})})})}var _useState=useState(null),activeSortColumn=_useState[0],setActiveSortColumn=_useState[1];var _useState2=useState({}),sortDirections=_useState2[0],setSortDirections=_useState2[1];var _useState3=useState(null),activeRowIndex=_useState3[0],setActiveRowIndex=_useState3[1];var _useState4=useState(null),activeAction=_useState4[0],setActiveAction=_useState4[1];var _useState5=useState(false),isFormSubmitting=_useState5[0],setIsFormSubmitting=_useState5[1];var _useState6=useState(null),loadingActionKey=_useState6[0],setLoadingActionKey=_useState6[1];var _useState7=useState(Number((_ref2=(_pagination$values$pa=pagination==null||(_pagination$values=pagination.values)==null?void 0:_pagination$values.pageNumber)!=null?_pagination$values$pa:pagination==null?void 0:pagination.initialPage)!=null?_ref2:1)),pageNumber=_useState7[0],setPageNumber=_useState7[1];var _useState8=useState(Number((_ref3=(_pagination$values$pa2=pagination==null||(_pagination$values2=pagination.values)==null?void 0:_pagination$values2.pageSize)!=null?_pagination$values$pa2:pagination==null?void 0:pagination.initialPageSize)!=null?_ref3:10)),pageSize=_useState8[0],setPageSize=_useState8[1];var _useState9=useState(Math.ceil(((pagination==null?void 0:pagination.totalCount)||0)/pageSize)||1),totalPages=_useState9[0],setTotalPages=_useState9[1];var _useState10=useState({}),chipColorMap=_useState10[0],setChipColorMap=_useState10[1];var _useState11=useState(null),openDropdownIndex=_useState11[0],setOpenDropdownIndex=_useState11[1];var prevDataHashRef=useRef("");useEffect(function(){var _ref4,_pagination$values$pa3,_pagination$values3,_ref5,_pagination$values$pa4,_pagination$values4;setPageNumber(Number((_ref4=(_pagination$values$pa3=pagination==null||(_pagination$values3=pagination.values)==null?void 0:_pagination$values3.pageNumber)!=null?_pagination$values$pa3:pagination==null?void 0:pagination.initialPage)!=null?_ref4:1));setPageSize(Number((_ref5=(_pagination$values$pa4=pagination==null||(_pagination$values4=pagination.values)==null?void 0:_pagination$values4.pageSize)!=null?_pagination$values$pa4:pagination==null?void 0:pagination.initialPageSize)!=null?_ref5:25))},[pagination]);useEffect(function(){setTotalPages(Math.ceil(((pagination==null?void 0:pagination.totalCount)||0)/pageSize)||1)},[pagination==null?void 0:pagination.totalCount,pageSize]);useEffect(function(){if(sortConfig){setSortDirections(sortConfig);var first=Object.keys(sortConfig)[0];if(first){setActiveSortColumn(first)}}},[sortConfig]);useEffect(function(){if(sortConfig!=null&&sortConfig.sortColumn||sortConfig!=null&&sortConfig.sortDirection){sortConfig.sortColumn=null;sortConfig.sortDirection=null}setActiveSortColumn(null);setSortDirections({})},[]);var computedColorMap=useMemo(function(){if(!Array.isArray(data)||data.length===0){return{}}// Get available column keys from first row
11
11
  var availableKeys=Object.keys(data[0]||{});var newColorMap={};// Process each column that uses random chips
12
12
  Object.keys(columnWithChipClass).forEach(function(columnKey){// Validate column key exists in data
13
13
  if(!availableKeys.includes(columnKey)){return}var chipMode=getChipMode(columnWithChipClass,columnKey);if(chipMode==="useRandom"){if(!newColorMap[columnKey]){newColorMap[columnKey]={}}var uniqueNormalizedValues=new Set;data.forEach(function(row){var value=row[columnKey];var normalizedKey=normalizeValue(value);if(normalizedKey){uniqueNormalizedValues.add(normalizedKey)}});var sortedUniqueValues=Array.from(uniqueNormalizedValues).sort();sortedUniqueValues.forEach(function(normalizedKey,index){if(!newColorMap[columnKey][normalizedKey]){var colorIndex=index%RANDOM_CHIP_COLOR_PALETTE.length;newColorMap[columnKey][normalizedKey]=RANDOM_CHIP_COLOR_PALETTE[colorIndex]}})}});return newColorMap},[data,columnWithChipClass]);useEffect(function(){var uniqueValuesHash=getUniqueValuesHash(data,columnWithChipClass);// Only update if the set of unique values actually changed
14
14
  if(uniqueValuesHash!==prevDataHashRef.current){prevDataHashRef.current=uniqueValuesHash;setChipColorMap(function(prevMap){var merged=_extends({},prevMap);Object.keys(computedColorMap).forEach(function(columnKey){merged[columnKey]=_extends({},computedColorMap[columnKey],merged[columnKey])});return merged})}},[computedColorMap,data,columnWithChipClass]);useEffect(function(){setChipColorMap(function(prevMap){var cleaned=_extends({},prevMap);var hasChanges=false;Object.keys(cleaned).forEach(function(columnKey){var chipMode=getChipMode(columnWithChipClass,columnKey);if(!chipMode){delete cleaned[columnKey];hasChanges=true}});return hasChanges?cleaned:prevMap})},[columnWithChipClass]);var _useButtonForm=useButtonForm({formMapper:activeAction==null?void 0:activeAction.action.formMapper,formTitle:activeAction==null?void 0:activeAction.action.formTitle,formDescription:activeAction==null?void 0:activeAction.action.formDescription,formButtonText:activeAction==null?void 0:activeAction.action.formButtonText,isSubmitting:isFormSubmitting||isLoading,onClose:function onClose(){setActiveRowIndex(null);setActiveAction(null)},onSubmit:function(){var _onSubmit=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(formData){return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(!(activeRowIndex!==null&&activeAction)){_context.next=10;break}setIsFormSubmitting(true);_context.prev=2;_context.next=5;return onRowAction==null?void 0:onRowAction(activeRowIndex,activeAction.id,formData);case 5:_context.prev=5;setIsFormSubmitting(false);return _context.finish(5);case 8:setActiveAction(null);setActiveRowIndex(null);case 10:case"end":return _context.stop()}},_callee,null,[[2,,5,8]])}));function onSubmit(_x){return _onSubmit.apply(this,arguments)}return onSubmit}()}),FormDialog=_useButtonForm.FormDialog,openForm=_useButtonForm.openForm;function handleButtonClick(rowIndex,action){if(action.action.action==="navigateToPage"&&action.action.targetPageId){var rowContext=resolveRowContext(action.action.rowContext,data[rowIndex]);navigateToPage==null||navigateToPage(action.action.targetPageId,rowContext);return}if(action.action.type==="navigation"){var onClick=action.action.onClick;if((onClick==null?void 0:onClick.action)==="navigateToPage"&&onClick.targetPageId){var _rowContext=resolveRowContext(action.action.rowContext,data[rowIndex]);navigateToPage==null||navigateToPage(onClick.targetPageId,_rowContext);return}}if(action.action.formMapper&&Object.keys(action.action.formMapper).length>0){setActiveRowIndex(rowIndex);setActiveAction(action)}else{onRowAction==null||onRowAction(rowIndex,action.id)}}useEffect(function(){if(activeAction!=null&&activeAction.action.formMapper&&Object.keys(activeAction.action.formMapper).length>0){openForm()}},[activeAction]);var originalKeys=Object.keys(data[0]||{}).filter(function(key){return key in headerMapper});var headers=originalKeys.map(function(key){return headerMapper[key]});if(actions.length>0){headers.push("")}var rows=data.map(function(datum){return originalKeys.map(function(key){return datum[key]})});function handlePageChange(_x2,_x3){return _handlePageChange.apply(this,arguments)}function _handlePageChange(){_handlePageChange=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(newPage,newSize){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:if(newPage===void 0){newPage=pageNumber}if(newSize===void 0){newSize=pageSize}setPageNumber(newPage);setPageSize(newSize);onPageChange==null||onPageChange(newPage,newSize);case 5:case"end":return _context3.stop()}},_callee3)}));return _handlePageChange.apply(this,arguments)}function handleSortClick(column,direction){setActiveSortColumn(direction?column:null);setSortDirections(function(prev){var _extends2;return _extends({},prev,(_extends2={},_extends2[column]=direction,_extends2))});onSort==null||onSort(column,direction)}function handleCheckboxClick(rowIndex){if(setSelectedIndices){if(selectedIndices.includes(rowIndex)){setSelectedIndices(selectedIndices.filter(function(idx){return idx!==rowIndex}))}else{setSelectedIndices([].concat(selectedIndices,[rowIndex]))}}}function ActionsDropdown(_ref6){var rowIndex=_ref6.rowIndex,rowActions=_ref6.rowActions;var isOpen=openDropdownIndex===rowIndex;var totalRows=rows.length;var isNearBottom=rowIndex>=totalRows-3;function handleActionClick(_x4){return _handleActionClick.apply(this,arguments)}function _handleActionClick(){_handleActionClick=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(action){var rowContext,onClick,_rowContext2,actionKey;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:if(!(action.action.action==="navigateToPage"&&action.action.targetPageId)){_context2.next=5;break}rowContext=resolveRowContext(action.action.rowContext,data[rowIndex]);navigateToPage==null||navigateToPage(action.action.targetPageId,rowContext);setOpenDropdownIndex(null);return _context2.abrupt("return");case 5:if(!(action.action.type==="navigation")){_context2.next=12;break}onClick=action.action.onClick;if(!((onClick==null?void 0:onClick.action)==="navigateToPage"&&onClick.targetPageId)){_context2.next=12;break}_rowContext2=resolveRowContext(action.action.rowContext,data[rowIndex]);navigateToPage==null||navigateToPage(onClick.targetPageId,_rowContext2);setOpenDropdownIndex(null);return _context2.abrupt("return");case 12:// Handle form-based and API actions
15
- actionKey=rowIndex+"-"+action.id;if(!(action.action.formMapper&&Object.keys(action.action.formMapper).length>0)){_context2.next=19;break}setActiveRowIndex(rowIndex);setActiveAction(action);setOpenDropdownIndex(null);_context2.next=27;break;case 19:_context2.prev=19;setLoadingActionKey(actionKey);_context2.next=23;return onRowAction==null?void 0:onRowAction(rowIndex,action.id);case 23:_context2.prev=23;setLoadingActionKey(null);setOpenDropdownIndex(null);return _context2.finish(23);case 27:case"end":return _context2.stop()}},_callee2,null,[[19,,23,27]])}));return _handleActionClick.apply(this,arguments)}function toggleDropdown(){setOpenDropdownIndex(isOpen?null:rowIndex)}function handleBackdropClick(){if(!loadingActionKey){setOpenDropdownIndex(null)}}return/*#__PURE__*/_jsxs(_Fragment,{children:[isOpen&&/*#__PURE__*/_jsx("div",{className:"fixed inset-0 z-40",onClick:handleBackdropClick,style:{background:"transparent",cursor:"default"}}),/*#__PURE__*/_jsxs("div",{className:"relative",children:[/*#__PURE__*/_jsx(Button,{variant:"ghost",size:"icon",onClick:function onClick(e){e.stopPropagation();toggleDropdown()},disabled:isLoading,className:"h-8 w-8 relative z-50","data-dropdown-button":"true",children:/*#__PURE__*/_jsx(MoreVertical,{className:"h-4 w-4"})}),isOpen&&/*#__PURE__*/_jsx("div",{className:cn("absolute right-full mr-2 w-48 rounded-md shadow-lg bg-white ring-gray-400 ring-opacity-5 z-50",isNearBottom?"bottom-0":"top-0"),children:/*#__PURE__*/_jsx("div",{className:"py-1",role:"menu",children:rowActions.map(function(action){var actionKey=rowIndex+"-"+action.id;var isActionLoading=loadingActionKey===actionKey;return/*#__PURE__*/_jsxs("button",{onClick:function onClick(){return handleActionClick(action)},className:"block w-full text-left px-4 py-2 text-sm hover:bg-accent transition-colors font-semibold disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 focus:outline-none focus:bg-accent",disabled:isLoading||isActionLoading,role:"menuitem",children:[isActionLoading&&/*#__PURE__*/_jsx(Loader2,{className:"h-3 w-3 animate-spin"}),action.text]},action.id)})})})]})]})}function renderActions(rowIndex,rowActions){if(!actions.length){return null}return/*#__PURE__*/_jsx(TableCell,{className:"sticky right-0 bg-white overflow-visible",children:/*#__PURE__*/_jsx(ActionsDropdown,{rowIndex:rowIndex,rowActions:rowActions})})}var defaultClasses="aspect-auto w-full";var mergedClasses=className?cn(defaultClasses,className):defaultClasses;function getRandomColorForValue(columnKey,value){var _chipColorMap$columnK;var normalizedKey=normalizeValue(value);if((_chipColorMap$columnK=chipColorMap[columnKey])!=null&&_chipColorMap$columnK[normalizedKey]){return chipColorMap[columnKey][normalizedKey]}return"bg-gray-50 text-gray-900 shadow-sm"}function renderChip(columnKey,value){var chipMode=getChipMode(columnWithChipClass,columnKey);var formattedValue=formatValue(value,decimalPrecision);if(!chipMode){return/*#__PURE__*/_jsx(_Fragment,{children:formattedValue})}var chipClassName="";if(chipMode==="useMap"){var _chipStylesMapping$co;var valueStr=String(value);chipClassName=(_chipStylesMapping$co=chipStylesMapping[columnKey])==null?void 0:_chipStylesMapping$co[valueStr];if(!chipClassName){var valueLower=valueStr.toLowerCase().trim();chipClassName=SEMANTIC_CHIP_STYLES_MAP[valueLower]}if(!chipClassName){chipClassName="bg-gray-50 text-gray-900 shadow-sm"}}else if(chipMode==="useRandom"){chipClassName=getRandomColorForValue(columnKey,value)}return/*#__PURE__*/_jsx("span",{className:cn("inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ring-gray-500/10",chipClassName),children:formattedValue})}function renderTableComponent(){if(isLoading||!data||data.length===0){return/*#__PURE__*/_jsx(TableLoader,{})}return/*#__PURE__*/_jsxs(Table,_extends({},otherProps,{className:"caption-bottom text-sm relative "+mergedClasses,"data-slot":"table",children:[/*#__PURE__*/_jsx(TableHeader,{"data-slot":"table-header",className:"sticky top-0 z-2",children:/*#__PURE__*/_jsxs(TableRow,{children:[isBulkSelectionEnabled&&/*#__PURE__*/_jsx(TableCell,{className:"p-2 w-10",children:/*#__PURE__*/_jsx(Checkbox,{checked:(selectedIndices==null?void 0:selectedIndices.length)===data.length,onCheckedChange:function onCheckedChange(){if(setSelectedIndices){if((selectedIndices==null?void 0:selectedIndices.length)===data.length){setSelectedIndices([])}else{setSelectedIndices(data.map(function(_,idx){return idx}))}}}})}),headers.map(function(head,idx){var isActionColumn=actions.length>0&&idx===headers.length-1;var originalKey=originalKeys[idx];if(isActionColumn){return/*#__PURE__*/_jsx(TableHead,{"data-slot":"table-header-"+idx,contentEditable:isEditable,className:"sticky right-0 bg-slate-100",children:head},idx)}return/*#__PURE__*/_jsx(TableHeadSortable,{"data-slot":"table-header-"+idx,sortDirection:sortDirections[originalKey]||"asc",isActive:activeSortColumn===originalKey,onSort:function onSort(direction){return handleSortClick(originalKey,direction)},sortable:!isLoading,isEditable:isEditable,children:head},idx)})]})}),/*#__PURE__*/_jsx(TableBody,{"data-slot":"table-body",children:rows.map(function(row,rIdx){return/*#__PURE__*/_jsxs(TableRow,{"data-slot":"row-"+rIdx,className:"hover:bg-muted/50 border-b transition-colors",children:[isBulkSelectionEnabled&&/*#__PURE__*/_jsx(TableCell,{className:"p-2 align-middle",children:/*#__PURE__*/_jsx(Checkbox,{checked:selectedIndices==null?void 0:selectedIndices.includes(rIdx),onCheckedChange:function onCheckedChange(){return handleCheckboxClick(rIdx)}})}),row.map(function(cell,cIdx){var columnKey=originalKeys[cIdx];var chipMode=columnKey?getChipMode(columnWithChipClass,columnKey):undefined;var shouldRenderChip=!!chipMode;return/*#__PURE__*/_jsx(TableCell,{"data-slot":"cell-"+rIdx+"-"+cIdx,className:"p-2 align-middle whitespace-nowrap",contentEditable:false,children:shouldRenderChip?renderChip(columnKey,cell):formatValue(cell,decimalPrecision)},cIdx)}),renderActions(rIdx,actions)]},rIdx)})})]}))}return/*#__PURE__*/_jsxs(Fragment,{children:[/*#__PURE__*/_jsx("div",{className:"flex flex-col h-full overflow-hidden",children:/*#__PURE__*/_jsxs(ScrollArea,_extends({"data-slot":"table-container",className:mergedClasses},height!==undefined&&{style:{height:height}},{children:[renderTableComponent(),/*#__PURE__*/_jsx(ScrollBar,{orientation:"horizontal"})]}))}),(((_pagination$totalCoun=pagination==null?void 0:pagination.totalCount)!=null?_pagination$totalCoun:0)>0||title&&!isEditable&&onDownload)&&/*#__PURE__*/_jsxs("div",{className:"flex-shrink-0 flex items-center justify-between mt-2 w-full overflow-x-auto border-t pt-2",children:[/*#__PURE__*/_jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:pagination&&pagination.totalCount>0&&/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsx("label",{htmlFor:"page-size-select",className:"text-sm whitespace-nowrap",children:"Rows per page:"}),/*#__PURE__*/_jsx("select",{id:"page-size-select",value:pageSize,onChange:function onChange(e){return handlePageChange(1,Number(e.target.value))},className:"border rounded px-2 py-1 text-sm cursor-pointer",disabled:isLoading,children:(pagination.pageSizeOptions||[10,20,50,100]).map(function(size){return/*#__PURE__*/_jsx("option",{value:size,children:size},size)})})]})}),/*#__PURE__*/_jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[title&&!isEditable&&onDownload&&/*#__PURE__*/_jsx(DownloadButton,{component:"table",title:title,onDownload:onDownload,dataCount:(_pagination$totalCoun2=pagination==null?void 0:pagination.totalCount)!=null?_pagination$totalCoun2:data.length}),pagination&&pagination.totalCount>0&&/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap ml-1.5",children:[(pageNumber-1)*pageSize+1,"\u2013",Math.min(pageNumber*pageSize,pagination.totalCount)," of ",pagination.totalCount]}),/*#__PURE__*/_jsx(Pagination,{children:/*#__PURE__*/_jsx(PaginationContent,{className:"gap-0.2 flex-shrink-0",children:renderPaginationArrows(pageNumber,totalPages,isLoading,handlePageChange)})})]})]})]}),FormDialog]})}
15
+ actionKey=rowIndex+"-"+action.id;if(!(action.action.formMapper&&Object.keys(action.action.formMapper).length>0)){_context2.next=19;break}setActiveRowIndex(rowIndex);setActiveAction(action);setOpenDropdownIndex(null);_context2.next=27;break;case 19:_context2.prev=19;setLoadingActionKey(actionKey);_context2.next=23;return onRowAction==null?void 0:onRowAction(rowIndex,action.id);case 23:_context2.prev=23;setLoadingActionKey(null);setOpenDropdownIndex(null);return _context2.finish(23);case 27:case"end":return _context2.stop()}},_callee2,null,[[19,,23,27]])}));return _handleActionClick.apply(this,arguments)}function toggleDropdown(){setOpenDropdownIndex(isOpen?null:rowIndex)}function handleBackdropClick(){if(!loadingActionKey){setOpenDropdownIndex(null)}}return/*#__PURE__*/_jsxs(_Fragment,{children:[isOpen&&/*#__PURE__*/_jsx("div",{className:"fixed inset-0 z-40",onClick:handleBackdropClick,style:{background:"transparent",cursor:"default"}}),/*#__PURE__*/_jsxs("div",{className:"relative",children:[/*#__PURE__*/_jsx(Button,{variant:"ghost",size:"icon",onClick:function onClick(e){e.stopPropagation();toggleDropdown()},disabled:isLoading,className:"h-8 w-8 relative z-50","data-dropdown-button":"true",children:/*#__PURE__*/_jsx(MoreVertical,{className:"h-4 w-4"})}),isOpen&&/*#__PURE__*/_jsx("div",{className:cn("absolute right-full mr-2 w-48 rounded-md shadow-lg bg-white ring-gray-400 ring-opacity-5 z-50",isNearBottom?"bottom-0":"top-0"),children:/*#__PURE__*/_jsx("div",{className:"py-1",role:"menu",children:rowActions.map(function(action){var actionKey=rowIndex+"-"+action.id;var isActionLoading=loadingActionKey===actionKey;return/*#__PURE__*/_jsxs("button",{onClick:function onClick(){return handleActionClick(action)},className:"block w-full text-left px-4 py-2 text-sm hover:bg-accent transition-colors font-semibold disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 focus:outline-none focus:bg-accent",disabled:isLoading||isActionLoading,role:"menuitem",children:[isActionLoading&&/*#__PURE__*/_jsx(Loader2,{className:"h-3 w-3 animate-spin"}),action.text]},action.id)})})})]})]})}function renderActions(rowIndex,rowActions){if(!actions.length){return null}return/*#__PURE__*/_jsx(TableCell,{className:"sticky right-0 bg-white overflow-visible",children:/*#__PURE__*/_jsx(ActionsDropdown,{rowIndex:rowIndex,rowActions:rowActions})})}var defaultClasses="aspect-auto w-full";var mergedClasses=className?cn(defaultClasses,className):defaultClasses;function getRandomColorForValue(columnKey,value){var _chipColorMap$columnK;var normalizedKey=normalizeValue(value);if((_chipColorMap$columnK=chipColorMap[columnKey])!=null&&_chipColorMap$columnK[normalizedKey]){return chipColorMap[columnKey][normalizedKey]}return"bg-gray-50 text-gray-900 shadow-sm"}function renderChip(columnKey,value){var chipMode=getChipMode(columnWithChipClass,columnKey);var formattedValue=formatValue(value,decimalPrecision);if(!chipMode){return/*#__PURE__*/_jsx(_Fragment,{children:formattedValue})}var chipClassName="";if(chipMode==="useMap"){var _chipStylesMapping$co;var valueStr=String(value);chipClassName=(_chipStylesMapping$co=chipStylesMapping[columnKey])==null?void 0:_chipStylesMapping$co[valueStr];if(!chipClassName){var valueLower=valueStr.toLowerCase().trim();chipClassName=SEMANTIC_CHIP_STYLES_MAP[valueLower]}if(!chipClassName){chipClassName="bg-gray-50 text-gray-900 shadow-sm"}}else if(chipMode==="useRandom"){chipClassName=getRandomColorForValue(columnKey,value)}return/*#__PURE__*/_jsx("span",{className:cn("inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ring-gray-500/10",chipClassName),children:formattedValue})}function renderTableComponent(){if(isLoading||!data||data.length===0){return/*#__PURE__*/_jsx(TableLoader,{})}return/*#__PURE__*/_jsxs(Table,_extends({},otherProps,{className:"caption-bottom text-sm relative "+mergedClasses,"data-slot":"table",children:[/*#__PURE__*/_jsx(TableHeader,{"data-slot":"table-header",className:"sticky top-0 z-2",children:/*#__PURE__*/_jsxs(TableRow,{children:[isBulkSelectionEnabled&&/*#__PURE__*/_jsx(TableCell,{className:"p-2 w-10",children:/*#__PURE__*/_jsx(Checkbox,{checked:(selectedIndices==null?void 0:selectedIndices.length)===data.length,onCheckedChange:function onCheckedChange(){if(setSelectedIndices){if((selectedIndices==null?void 0:selectedIndices.length)===data.length){setSelectedIndices([])}else{setSelectedIndices(data.map(function(_,idx){return idx}))}}}})}),headers.map(function(head,idx){var isActionColumn=actions.length>0&&idx===headers.length-1;var originalKey=originalKeys[idx];if(isActionColumn){return/*#__PURE__*/_jsx(TableHead,{"data-slot":"table-header-"+idx,contentEditable:isEditable,className:"sticky right-0 bg-slate-100",children:head},idx)}return/*#__PURE__*/_jsx(TableHeadSortable,{"data-slot":"table-header-"+idx,sortDirection:sortDirections[originalKey]||"asc",isActive:activeSortColumn===originalKey,onSort:function onSort(direction){return handleSortClick(originalKey,direction)},sortable:sortableGlobal&&!isLoading,isEditable:isEditable,children:head},idx)})]})}),/*#__PURE__*/_jsx(TableBody,{"data-slot":"table-body",children:rows.map(function(row,rIdx){return/*#__PURE__*/_jsxs(TableRow,{"data-slot":"row-"+rIdx,className:"hover:bg-muted/50 border-b transition-colors",children:[isBulkSelectionEnabled&&/*#__PURE__*/_jsx(TableCell,{className:"p-2 align-middle",children:/*#__PURE__*/_jsx(Checkbox,{checked:selectedIndices==null?void 0:selectedIndices.includes(rIdx),onCheckedChange:function onCheckedChange(){return handleCheckboxClick(rIdx)}})}),row.map(function(cell,cIdx){var columnKey=originalKeys[cIdx];var chipMode=columnKey?getChipMode(columnWithChipClass,columnKey):undefined;var shouldRenderChip=!!chipMode;return/*#__PURE__*/_jsx(TableCell,{"data-slot":"cell-"+rIdx+"-"+cIdx,className:"p-2 align-middle whitespace-nowrap",contentEditable:false,children:shouldRenderChip?renderChip(columnKey,cell):formatValue(cell,decimalPrecision)},cIdx)}),renderActions(rIdx,actions)]},rIdx)})})]}))}return/*#__PURE__*/_jsxs(Fragment,{children:[/*#__PURE__*/_jsx("div",{className:"flex flex-col h-full overflow-hidden",children:/*#__PURE__*/_jsxs(ScrollArea,_extends({"data-slot":"table-container",className:mergedClasses},height!==undefined&&{style:{height:height}},{children:[renderTableComponent(),/*#__PURE__*/_jsx(ScrollBar,{orientation:"horizontal"})]}))}),(((_pagination$totalCoun=pagination==null?void 0:pagination.totalCount)!=null?_pagination$totalCoun:0)>0||title&&!isEditable&&onDownload)&&/*#__PURE__*/_jsxs("div",{className:"flex-shrink-0 flex items-center justify-between mt-2 w-full overflow-x-auto border-t pt-2",children:[/*#__PURE__*/_jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:pagination&&pagination.totalCount>0&&/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsx("label",{htmlFor:"page-size-select",className:"text-sm whitespace-nowrap",children:"Rows per page:"}),/*#__PURE__*/_jsx("select",{id:"page-size-select",value:pageSize,onChange:function onChange(e){return handlePageChange(1,Number(e.target.value))},className:"border rounded px-2 py-1 text-sm cursor-pointer",disabled:isLoading,children:(pagination.pageSizeOptions||[10,20,50,100]).map(function(size){return/*#__PURE__*/_jsx("option",{value:size,children:size},size)})})]})}),/*#__PURE__*/_jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[title&&!isEditable&&onDownload&&/*#__PURE__*/_jsx(DownloadButton,{component:"table",title:title,onDownload:onDownload,dataCount:(_pagination$totalCoun2=pagination==null?void 0:pagination.totalCount)!=null?_pagination$totalCoun2:data.length}),pagination&&pagination.totalCount>0&&/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap ml-1.5",children:[(pageNumber-1)*pageSize+1,"\u2013",Math.min(pageNumber*pageSize,pagination.totalCount)," of ",pagination.totalCount]}),/*#__PURE__*/_jsx(Pagination,{children:/*#__PURE__*/_jsx(PaginationContent,{className:"gap-0.2 flex-shrink-0",children:renderPaginationArrows(pageNumber,totalPages,isLoading,handlePageChange)})})]})]})]}),FormDialog]})}
16
16
  //# sourceMappingURL=data-table.js.map