@peak-ai/canvas 1.4.38-rc.8 → 1.4.39
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.d.ts +2 -1
- package/GrapesjsCanvas.js +2 -2
- package/GrapesjsCanvas.js.map +1 -1
- package/package.json +2 -2
- package/plugins/helpers/render-components.js +6 -7
- package/plugins/helpers/render-components.js.map +1 -1
- package/shadcn/components/ui/chart.js +2 -2
- package/shadcn/components/ui/chart.js.map +1 -1
package/GrapesjsCanvas.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ type GrapesjsCanvasProps = {
|
|
|
13
13
|
newDataNotifier: (notifHandler: NotificationHandler) => void;
|
|
14
14
|
setHasChanged: (hasChanged: boolean) => void;
|
|
15
15
|
isStreaming: boolean;
|
|
16
|
+
isModeChangeFromToggle?: boolean;
|
|
16
17
|
};
|
|
17
|
-
declare function GrapesjsCanvas({ json, mode, setEditor, performInteraction, newDataNotifier, setHasChanged, isStreaming, }: GrapesjsCanvasProps): import("react/jsx-runtime").JSX.Element;
|
|
18
|
+
declare function GrapesjsCanvas({ json, mode, setEditor, performInteraction, newDataNotifier, setHasChanged, isStreaming, isModeChangeFromToggle, }: GrapesjsCanvasProps): import("react/jsx-runtime").JSX.Element;
|
|
18
19
|
export default GrapesjsCanvas;
|
package/GrapesjsCanvas.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _extends from"@babel/runtime/helpers/extends";import _regeneratorRuntime from"@babel/runtime/regenerator";/* eslint-disable @typescript-eslint/no-explicit-any */import React,{useEffect,useRef}from"react";// eslint-disable-next-line import/no-named-as-default
|
|
2
2
|
import grapesjs from"grapesjs";import"grapesjs/dist/css/grapes.min.css";import tailwind from"grapesjs-tailwind";import{TypesToRegister}from"./constants";import{toKebabCase}from"./helpers";import{tailwindCompiledCss}from"./helpers/css";import{datePickerCss}from"./helpers/date-picker";import{createGrapesjsShadcnGenericPlugin}from"./plugins/grapejs-plugin";import{StyledEditor}from"./index.styles";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";function setComponentProperties(editor,isPreview){function setPropertiesRecursively(comp){comp.set({editable:!isPreview,draggable:!isPreview,droppable:!isPreview&&comp.getName()!=="Shadcn-generic",selectable:!isPreview,hoverable:!isPreview,highlightable:!isPreview,copyable:false,resizable:false,removable:!isPreview,badgable:false});comp.set("attributes",_extends({},comp.get("attributes")||{},{isEditable:!isPreview}));if(!isPreview){comp.set("toolbar",[{attributes:{"class":"fa fa-arrows"},command:"tlb-move"},{attributes:{"class":"fa fa-trash"},command:"tlb-delete"}])}comp.components().forEach(setPropertiesRecursively)}if(isPreview){editor.runCommand("core:preview")}else{editor.stopCommand("core:preview")}var wrapper=editor.getWrapper();wrapper==null||wrapper.find("*").forEach(setPropertiesRecursively)}function convertStyles(stylesArray){return stylesArray.map(function(block){var selectors=Array.isArray(block.selectors)?block.selectors.join(", "):block.selectors;var declarations=Object.entries(block.style).map(function(_ref){var prop=_ref[0],value=_ref[1];return toKebabCase(prop)+": "+value+";"}).join(" ");return selectors+" { "+declarations+" }"}).join("\n")}function createActionCardConfig(action){var icon=action.icon,title=action.title,description=action.description;return{type:"shadcn-generic",componentName:"ActionCard",badgable:false,copyable:false,removable:true,draggable:true,componentProps:{icon:icon,headerContent:title,bodyContent:description}}}function expandActions(node){if(node.type==="shadcn-generic"&&node.componentName==="Actions"){var _node$componentProps;var actions=(_node$componentProps=node.componentProps)==null?void 0:_node$componentProps.actions;if(Array.isArray(actions)&&actions.length>0){return _extends({},node,{type:"div",classes:["dashboard-cards"].concat(node.classes||[]),componentName:undefined,componentProps:undefined,components:actions.map(function(action,i){return _extends({},createActionCardConfig(action),{id:node.id+"--action-card-"+i})})})}return node}if(Array.isArray(node.components)){return _extends({},node,{components:node.components.map(expandActions)})}return node}function setInteracting(renderedComponents,components,inProgress){components.forEach(function(component){var componentId=component.componentId,showLoader=component.showLoader;if(!showLoader){return}var gjsModel=renderedComponents[componentId];if(gjsModel){gjsModel.set("attributes",_extends({},gjsModel.get("attributes"),{interactionApiInProgress:inProgress}))}})}function expandActionsComponent(model,actions){model.components("");actions.forEach(function(action){model.append(createActionCardConfig(action))});model.set("type","div");model.addClass("dashboard-cards");model.set("componentName",undefined);model.set("componentProps",{})}function GrapesjsCanvas(_ref2){var json=_ref2.json,_ref2$mode=_ref2.mode,mode=_ref2$mode===void 0?"preview":_ref2$mode,setEditor=_ref2.setEditor,performInteraction=_ref2.performInteraction,_ref2$newDataNotifier=_ref2.newDataNotifier,newDataNotifier=_ref2$newDataNotifier===void 0?function(){// no op
|
|
3
3
|
}:_ref2$newDataNotifier,_ref2$setHasChanged=_ref2.setHasChanged,setHasChanged=_ref2$setHasChanged===void 0?function(){// no op
|
|
4
|
-
}:_ref2$setHasChanged,isStreaming=_ref2.isStreaming;var editorRef=useRef(null);var editorInstance=useRef(null);var renderedComponents=useRef({});var isStreamingRef=useRef(isStreaming);var isSystemUpdateRef=useRef(false);var lastJsonRef=useRef("");var isEditorAliveRef=useRef(false);useEffect(function(){isStreamingRef.current=isStreaming},[isStreaming]);function notificationHandler(props){if(!props){return true}var componentId=props.componentId,_props$newProps=props.newProps,newProps=_props$newProps===void 0?{}:_props$newProps,_props$newAttributes=props.newAttributes,newAttributes=_props$newAttributes===void 0?{}:_props$newAttributes;var model=renderedComponents.current[componentId];if(!model){return false}// Filter out complex placeholder objects by setting them to null
|
|
4
|
+
}:_ref2$setHasChanged,isStreaming=_ref2.isStreaming,_ref2$isModeChangeFro=_ref2.isModeChangeFromToggle,isModeChangeFromToggle=_ref2$isModeChangeFro===void 0?false:_ref2$isModeChangeFro;var editorRef=useRef(null);var editorInstance=useRef(null);var renderedComponents=useRef({});var isStreamingRef=useRef(isStreaming);var isSystemUpdateRef=useRef(false);var lastJsonRef=useRef("");var isEditorAliveRef=useRef(false);var _React$useState=React.useState(false),isTransitioning=_React$useState[0],setIsTransitioning=_React$useState[1];useEffect(function(){isStreamingRef.current=isStreaming},[isStreaming]);function notificationHandler(props){if(!props){return true}var componentId=props.componentId,_props$newProps=props.newProps,newProps=_props$newProps===void 0?{}:_props$newProps,_props$newAttributes=props.newAttributes,newAttributes=_props$newAttributes===void 0?{}:_props$newAttributes;var model=renderedComponents.current[componentId];if(!model){return false}// Filter out complex placeholder objects by setting them to null
|
|
5
5
|
// This ensures placeholder values are properly cleared and don't cause stale data issues
|
|
6
6
|
var filteredProps=_extends({},newProps);Object.keys(filteredProps).forEach(function(key){var value=filteredProps[key];if(value&&typeof value==="object"&&value.name==="__peak_placeholder"){filteredProps[key]=null}});var parsedNewProps=_extends({},filteredProps);if(filteredProps.pagination){parsedNewProps.pagination=_extends({},model.get("componentProps").pagination||{},filteredProps.pagination)}// Handle Actions component: expand into ActionCards when data arrives via streaming
|
|
7
7
|
var isActionsComponent=model.get("componentName")==="Actions";var hasValidActionsData=parsedNewProps.actions&&parsedNewProps.actions!==null&&Array.isArray(parsedNewProps.actions)&&parsedNewProps.actions.length>0;if(isActionsComponent&&hasValidActionsData){var _model$components$at;var isAlreadyExpanded=model.components().length>0&&((_model$components$at=model.components().at(0))==null?void 0:_model$components$at.get("componentName"))==="ActionCard";if(!isAlreadyExpanded){expandActionsComponent(model,parsedNewProps.actions);return true}}model.set("componentProps",_extends({},model.get("componentProps"),parsedNewProps));model.set("attributes",_extends({},model.get("attributes"),newAttributes));return true}useEffect(function(){newDataNotifier(notificationHandler)},[]);function performInteractionWrapper(_x){return _performInteractionWrapper.apply(this,arguments)}function _performInteractionWrapper(){_performInteractionWrapper=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(payload){var _editorInstance$curre3;var updatedJson,apiResponse,componentUpdates;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=2;return(_editorInstance$curre3=editorInstance.current)==null?void 0:_editorInstance$curre3.store();case 2:updatedJson=_context4.sent;setInteracting(renderedComponents.current,payload.affectedComponents,true);_context4.prev=4;_context4.next=7;return performInteraction(_extends({},payload,{json:updatedJson}));case 7:apiResponse=_context4.sent;componentUpdates=apiResponse||{};Object.entries(componentUpdates).forEach(function(_ref6){var key=_ref6[0],value=_ref6[1];var model=renderedComponents.current[key];if(model){model.set("attributes",_extends({},model.get("attributes"),{error:undefined}));model.set("componentProps",_extends({},model.get("componentProps"),value,{error:undefined,isMissing:undefined}))}});return _context4.abrupt("return",componentUpdates);case 13:_context4.prev=13;_context4.t0=_context4["catch"](4);payload.affectedComponents.forEach(function(componentId){var model=renderedComponents.current[componentId];if(model){var errorMessage=_context4.t0 instanceof Error?_context4.t0.message:"Something went wrong. Please try again.";model.set("attributes",_extends({},model.get("attributes"),{error:errorMessage}));model.set("componentProps",_extends({},model.get("componentProps"),{error:errorMessage,isMissing:undefined}))}});throw _context4.t0;case 17:_context4.prev=17;setInteracting(renderedComponents.current,payload.affectedComponents,false);return _context4.finish(17);case 20:case"end":return _context4.stop()}},_callee4,null,[[4,13,17,20]])}));return _performInteractionWrapper.apply(this,arguments)}useEffect(function(){if(!editorRef.current){return function(){// no op
|
|
8
8
|
}}if(editorInstance.current){editorInstance.current.destroy();editorInstance.current=null;isEditorAliveRef.current=false}var currentMode=mode;var editor=grapesjs.init({container:editorRef.current,height:"100%",plugins:[tailwind,createGrapesjsShadcnGenericPlugin(currentMode,performInteractionWrapper,renderedComponents.current,setHasChanged)],storageManager:{type:"none"},richTextEditor:{actions:["bold","italic","underline","strikethrough"]},canvas:{customBadgeLabel:function customBadgeLabel(component){var tagName=component.get("tagName");return tagName==="body"?"":tagName||""}}});isEditorAliveRef.current=true;var injectionAttempts=0;function injectStylesEarly(){var _editor$Canvas;var iframeDoc=(_editor$Canvas=editor.Canvas)==null||_editor$Canvas.getDocument==null?void 0:_editor$Canvas.getDocument();if(iframeDoc&&iframeDoc.head){if(!iframeDoc.head.querySelector("[data-grapesjs-styles]")){var style=iframeDoc.createElement("style");var fullCss="\n "+tailwindCompiledCss+"\n "+datePickerCss+"\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");style.setAttribute("data-grapesjs-styles","true");iframeDoc.head.appendChild(style)}}else if(injectionAttempts<50){injectionAttempts+=1;requestAnimationFrame(injectStylesEarly)}}requestAnimationFrame(injectStylesEarly);function checkDirty(){return _checkDirty.apply(this,arguments)}function _checkDirty(){_checkDirty=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _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.prev=5;_context2.next=8;return editorInstance.current.store();case 8:stored=_context2.sent;_context2.next=14;break;case 11:_context2.prev=11;_context2.t0=_context2["catch"](5);return _context2.abrupt("return");case 14:if(stored){_context2.next=16;break}return _context2.abrupt("return");case 16:newJson=JSON.stringify(stored);if(newJson!==lastJsonRef.current){setHasChanged(true);lastJsonRef.current=newJson}case 18:case"end":return _context2.stop()}},_callee2,null,[[5,11]])}));return _checkDirty.apply(this,arguments)}var debouncedCheckDirty=function(){var timeout=null;return function(){if(timeout){clearTimeout(timeout)}timeout=setTimeout(checkDirty,200)}}();["component:add","component:remove","component:update:content","style:update","component:drag:end","rte:change"].forEach(function(evt){editor.on(evt,debouncedCheckDirty)});editor.on("component:update",function(model,prop){if(["attributes","componentProps","content"].includes(prop)){debouncedCheckDirty()}});// Tailwind CSS rules aren't fully added to our component
|
|
9
9
|
// So, adding them from here!
|
|
10
|
-
editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var canvasDoc,canvasHead,style,fullCss;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:canvasDoc=editor.Canvas.getDocument();canvasHead=canvasDoc.head;if(!canvasHead.querySelector("[data-grapesjs-styles]")){style=canvasDoc.createElement("style");fullCss="\n "+tailwindCompiledCss+"\n "+datePickerCss+"\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");style.setAttribute("data-grapesjs-styles","true");canvasHead.appendChild(style)}isSystemUpdateRef.current=true;_context.t0=JSON;_context.next=7;return editor.store();case 7:_context.t1=_context.sent;lastJsonRef.current=_context.t0.stringify.call(_context.t0,_context.t1);isSystemUpdateRef.current=false;case 10:case"end":return _context.stop()}},_callee)})));editorInstance.current=editor;if(setEditor){setEditor(editor)}TypesToRegister.forEach(function(_ref4){var type=_ref4.type,tagName=_ref4.tagName;if(!editor.DomComponents.getType(type)){editor.DomComponents.addType(type,{model:{defaults:{tagName:tagName}},view:{}})}});return function cleanup(){editor.destroy();isEditorAliveRef.current=false}},[]);useEffect(function(){var _json$pages,_json$pages$0$frames;if(json&&((_json$pages=json.pages)==null?void 0:_json$pages.length)>0&&((_json$pages$0$frames=json.pages[0].frames)==null?void 0:_json$pages$0$frames.length)>0){var _editorInstance$curre,_editorInstance$curre2;isSystemUpdateRef.current=true;var raw=json.pages[0].frames[0].component;var processed=expandActions(raw);(_editorInstance$curre=editorInstance.current)==null||_editorInstance$curre.setComponents(processed);var cssText=convertStyles(json.styles||[]);(_editorInstance$curre2=editorInstance.current)==null||_editorInstance$curre2.setStyle(cssText);setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:if(!editorInstance.current){_context3.next=7;break}_context3.t0=JSON;_context3.next=4;return editorInstance.current.store();case 4:_context3.t1=_context3.sent;lastJsonRef.current=_context3.t0.stringify.call(_context3.t0,_context3.t1);isSystemUpdateRef.current=false;case 7:case"end":return _context3.stop()}},_callee3)})),100)}},[json]);useEffect(function(){if(mode&&editorInstance.current){isSystemUpdateRef.current=true;setTimeout(function(){setComponentProperties(editorInstance.current,mode==="preview");setTimeout(function(){isSystemUpdateRef.current=false},50)},0)}},[mode]);return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(StyledEditor,{}),/*#__PURE__*/_jsx("div",{ref:editorRef,id:"grapesjs-editor"})]})}export default GrapesjsCanvas;
|
|
10
|
+
editor.on("load",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var canvasDoc,canvasHead,style,fullCss;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:canvasDoc=editor.Canvas.getDocument();canvasHead=canvasDoc.head;if(!canvasHead.querySelector("[data-grapesjs-styles]")){style=canvasDoc.createElement("style");fullCss="\n "+tailwindCompiledCss+"\n "+datePickerCss+"\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");style.setAttribute("data-grapesjs-styles","true");canvasHead.appendChild(style)}isSystemUpdateRef.current=true;_context.t0=JSON;_context.next=7;return editor.store();case 7:_context.t1=_context.sent;lastJsonRef.current=_context.t0.stringify.call(_context.t0,_context.t1);isSystemUpdateRef.current=false;case 10:case"end":return _context.stop()}},_callee)})));editorInstance.current=editor;if(setEditor){setEditor(editor)}TypesToRegister.forEach(function(_ref4){var type=_ref4.type,tagName=_ref4.tagName;if(!editor.DomComponents.getType(type)){editor.DomComponents.addType(type,{model:{defaults:{tagName:tagName}},view:{}})}});return function cleanup(){editor.destroy();isEditorAliveRef.current=false}},[]);useEffect(function(){var _json$pages,_json$pages$0$frames;if(json&&((_json$pages=json.pages)==null?void 0:_json$pages.length)>0&&((_json$pages$0$frames=json.pages[0].frames)==null?void 0:_json$pages$0$frames.length)>0){var _editorInstance$curre,_editorInstance$curre2;isSystemUpdateRef.current=true;var raw=json.pages[0].frames[0].component;var processed=expandActions(raw);(_editorInstance$curre=editorInstance.current)==null||_editorInstance$curre.setComponents(processed);var cssText=convertStyles(json.styles||[]);(_editorInstance$curre2=editorInstance.current)==null||_editorInstance$curre2.setStyle(cssText);setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:if(!editorInstance.current){_context3.next=7;break}_context3.t0=JSON;_context3.next=4;return editorInstance.current.store();case 4:_context3.t1=_context3.sent;lastJsonRef.current=_context3.t0.stringify.call(_context3.t0,_context3.t1);isSystemUpdateRef.current=false;case 7:case"end":return _context3.stop()}},_callee3)})),100)}},[json]);useEffect(function(){if(mode&&editorInstance.current){isSystemUpdateRef.current=true;if(isModeChangeFromToggle){setIsTransitioning(true)}setTimeout(function(){setComponentProperties(editorInstance.current,mode==="preview");setTimeout(function(){isSystemUpdateRef.current=false;setIsTransitioning(false)},50)},0)}},[mode,isModeChangeFromToggle]);return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(StyledEditor,{}),/*#__PURE__*/_jsx("div",{ref:editorRef,id:"grapesjs-editor",style:{opacity:isTransitioning?0:1,transition:"opacity 0.15s ease-in-out"}})]})}export default GrapesjsCanvas;
|
|
11
11
|
//# sourceMappingURL=GrapesjsCanvas.js.map
|
package/GrapesjsCanvas.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","createGrapesjsShadcnGenericPlugin","StyledEditor","jsx","_jsx","jsxs","_jsxs","setComponentProperties","editor","isPreview","setPropertiesRecursively","comp","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","_extends","get","isEditable","attributes","command","components","forEach","runCommand","stopCommand","wrapper","getWrapper","find","convertStyles","stylesArray","map","block","selectors","Array","isArray","join","declarations","Object","entries","style","_ref","prop","value","createActionCardConfig","action","icon","title","description","type","componentName","componentProps","headerContent","bodyContent","expandActions","node","_node$componentProps","actions","length","classes","concat","undefined","i","id","setInteracting","renderedComponents","inProgress","component","componentId","showLoader","gjsModel","interactionApiInProgress","expandActionsComponent","model","append","addClass","GrapesjsCanvas","_ref2","json","_ref2$mode","mode","setEditor","performInteraction","_ref2$newDataNotifier","newDataNotifier","_ref2$setHasChanged","setHasChanged","isStreaming","editorRef","editorInstance","isStreamingRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","current","notificationHandler","props","_props$newProps","newProps","_props$newAttributes","newAttributes","filteredProps","keys","key","name","parsedNewProps","pagination","isActionsComponent","hasValidActionsData","_model$components$at","isAlreadyExpanded","at","performInteractionWrapper","_x","_performInteractionWrapper","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee4","payload","_editorInstance$curre3","updatedJson","apiResponse","componentUpdates","wrap","_callee4$","_context4","prev","next","store","sent","affectedComponents","_ref6","error","isMissing","abrupt","t0","errorMessage","Error","message","finish","stop","destroy","currentMode","init","container","height","plugins","storageManager","richTextEditor","canvas","customBadgeLabel","tagName","injectionAttempts","injectStylesEarly","_editor$Canvas","iframeDoc","Canvas","getDocument","head","querySelector","createElement","fullCss","innerHTML","setAttribute","appendChild","requestAnimationFrame","checkDirty","_checkDirty","_callee2","stored","newJson","_callee2$","_context2","JSON","stringify","debouncedCheckDirty","timeout","clearTimeout","setTimeout","evt","on","includes","_callee","canvasDoc","canvasHead","_callee$","_context","t1","call","_ref4","DomComponents","getType","addType","defaults","view","cleanup","_json$pages","_json$pages$0$frames","pages","frames","_editorInstance$curre","_editorInstance$curre2","raw","processed","setComponents","cssText","styles","setStyle","_callee3","_callee3$","_context3","Fragment","children","ref"],"sources":["../src/GrapesjsCanvas.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { useEffect, useRef } from 'react';\n// eslint-disable-next-line import/no-named-as-default\nimport grapesjs, { Component, Editor } from 'grapesjs';\nimport 'grapesjs/dist/css/grapes.min.css';\nimport tailwind from 'grapesjs-tailwind';\n\nimport { TypesToRegister } from './constants';\nimport { toKebabCase } from './helpers';\nimport { tailwindCompiledCss } from './helpers/css';\nimport { datePickerCss } from './helpers/date-picker';\nimport { createGrapesjsShadcnGenericPlugin } from './plugins/grapejs-plugin';\nimport { StyledEditor } from './index.styles';\n\ntype NotificationHandler = (newData: {\n componentId: string;\n newProps: Record<string, any>;\n newAttributes: Record<string, any>;\n}) => boolean;\n\ntype GrapesjsCanvasProps = {\n json: any;\n mode?: 'editor' | 'preview';\n setEditor: (editor: Editor) => void;\n performInteraction: (payload: Record<string, any>) => Promise<Record<string, any> | undefined>;\n newDataNotifier: (notifHandler: NotificationHandler) => void;\n setHasChanged: (hasChanged: boolean) => void;\n isStreaming: boolean;\n};\n\nfunction setComponentProperties(editor: Editor, isPreview: boolean) {\n function setPropertiesRecursively(comp: Component) {\n comp.set({\n editable: !isPreview,\n draggable: !isPreview,\n droppable: !isPreview && comp.getName() !== 'Shadcn-generic',\n selectable: !isPreview,\n hoverable: !isPreview,\n highlightable: !isPreview,\n copyable: false,\n resizable: false,\n removable: !isPreview,\n badgable: false,\n });\n\n comp.set('attributes', {\n ...(comp.get('attributes') || {}),\n isEditable: !isPreview,\n });\n\n if (!isPreview) {\n comp.set('toolbar', [\n { attributes: { class: 'fa fa-arrows' }, command: 'tlb-move' },\n { attributes: { class: 'fa fa-trash' }, command: 'tlb-delete' },\n ]);\n }\n\n comp.components().forEach(setPropertiesRecursively);\n }\n\n if (isPreview) {\n editor.runCommand('core:preview');\n } else {\n editor.stopCommand('core:preview');\n }\n\n const wrapper = editor.getWrapper();\n wrapper?.find('*').forEach(setPropertiesRecursively);\n}\n\nfunction convertStyles(stylesArray: any[]): string {\n return stylesArray\n .map((block) => {\n const selectors = Array.isArray(block.selectors)\n ? block.selectors.join(', ')\n : block.selectors;\n const declarations = Object.entries(block.style)\n .map(([prop, value]) => `${toKebabCase(prop)}: ${value};`)\n .join(' ');\n\n return `${selectors} { ${declarations} }`;\n })\n .join('\\n');\n}\n\nfunction createActionCardConfig(action: any): any {\n const { icon, title, description } = action;\n\n return {\n type: 'shadcn-generic',\n componentName: 'ActionCard',\n badgable: false,\n copyable: false,\n removable: true,\n draggable: true,\n componentProps: {\n icon,\n headerContent: title,\n bodyContent: description,\n },\n };\n}\n\nfunction expandActions(node: any): any {\n if (node.type === 'shadcn-generic' && node.componentName === 'Actions') {\n const actions = node.componentProps?.actions;\n\n if (Array.isArray(actions) && actions.length > 0) {\n return {\n ...node,\n type: 'div',\n classes: ['dashboard-cards', ...(node.classes || [])],\n componentName: undefined,\n componentProps: undefined,\n components: actions.map((action: any, i: number) => ({\n ...createActionCardConfig(action),\n id: `${node.id}--action-card-${i}`,\n })),\n };\n }\n\n return node;\n }\n\n if (Array.isArray(node.components)) {\n return {\n ...node,\n components: node.components.map(expandActions),\n };\n }\n\n return node;\n}\n\nfunction setInteracting(\n renderedComponents: Record<string, Component>,\n components: { componentId: string; showLoader: boolean }[],\n inProgress: boolean,\n) {\n components.forEach((component) => {\n const { componentId, showLoader } = component;\n\n if (!showLoader) {\n return;\n }\n\n const gjsModel = renderedComponents[componentId];\n\n if (gjsModel) {\n gjsModel.set('attributes', {\n ...gjsModel.get('attributes'),\n interactionApiInProgress: inProgress,\n });\n }\n });\n}\n\nfunction expandActionsComponent(model: Component, actions: any[]): void {\n model.components('');\n\n actions.forEach((action: any) => {\n model.append(createActionCardConfig(action));\n });\n\n model.set('type', 'div');\n model.addClass('dashboard-cards');\n model.set('componentName', undefined);\n model.set('componentProps', {});\n}\n\nfunction GrapesjsCanvas({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n newDataNotifier = () => {\n // no op\n },\n setHasChanged = () => {\n // no op\n },\n isStreaming,\n}: GrapesjsCanvasProps) {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<Editor | null>(null);\n const renderedComponents = useRef<Record<string, Component>>({});\n const isStreamingRef = useRef(isStreaming);\n const isSystemUpdateRef = useRef(false);\n const lastJsonRef = useRef<string>('');\n const isEditorAliveRef = useRef(false);\n\n useEffect(() => {\n isStreamingRef.current = isStreaming;\n }, [isStreaming]);\n\n function notificationHandler(\n props: Parameters<NotificationHandler>[0],\n ): ReturnType<NotificationHandler> {\n if (!props) {\n return true;\n }\n\n const { componentId, newProps = {}, newAttributes = {} } = props;\n\n const model = renderedComponents.current[componentId];\n\n if (!model) {\n return false;\n }\n\n // Filter out complex placeholder objects by setting them to null\n // This ensures placeholder values are properly cleared and don't cause stale data issues\n const filteredProps = { ...newProps };\n\n Object.keys(filteredProps).forEach((key) => {\n const value = filteredProps[key];\n\n if (value && typeof value === 'object' && value.name === '__peak_placeholder') {\n filteredProps[key] = null;\n }\n });\n\n const parsedNewProps = {\n ...filteredProps,\n };\n\n if (filteredProps.pagination) {\n parsedNewProps.pagination = {\n ...(model.get('componentProps').pagination || {}),\n ...filteredProps.pagination,\n };\n }\n\n // Handle Actions component: expand into ActionCards when data arrives via streaming\n const isActionsComponent = model.get('componentName') === 'Actions';\n const hasValidActionsData =\n parsedNewProps.actions &&\n parsedNewProps.actions !== null &&\n Array.isArray(parsedNewProps.actions) &&\n parsedNewProps.actions.length > 0;\n\n if (isActionsComponent && hasValidActionsData) {\n const isAlreadyExpanded =\n model.components().length > 0 &&\n model.components().at(0)?.get('componentName') === 'ActionCard';\n\n if (!isAlreadyExpanded) {\n expandActionsComponent(model, parsedNewProps.actions);\n\n return true;\n }\n }\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...parsedNewProps,\n });\n\n model.set('attributes', {\n ...model.get('attributes'),\n ...newAttributes,\n });\n\n return true;\n }\n\n useEffect(() => {\n newDataNotifier(notificationHandler);\n }, []);\n\n async function performInteractionWrapper(payload: Record<string, any>) {\n const updatedJson = await editorInstance.current?.store();\n setInteracting(renderedComponents.current, payload.affectedComponents, true);\n\n try {\n const apiResponse = await performInteraction({\n ...payload,\n json: updatedJson,\n });\n\n const componentUpdates = apiResponse || {};\n\n Object.entries(componentUpdates).forEach(([key, value]) => {\n const model = renderedComponents.current[key];\n\n if (model) {\n model.set('attributes', {\n ...model.get('attributes'),\n error: undefined,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...value,\n error: undefined,\n isMissing: undefined,\n });\n }\n });\n\n return componentUpdates;\n } catch (error) {\n payload.affectedComponents.forEach((componentId: string) => {\n const model = renderedComponents.current[componentId];\n\n if (model) {\n const errorMessage =\n error instanceof Error ? error.message : 'Something went wrong. Please try again.';\n\n model.set('attributes', {\n ...model.get('attributes'),\n error: errorMessage,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n error: errorMessage,\n isMissing: undefined,\n });\n }\n });\n\n throw error;\n } finally {\n setInteracting(renderedComponents.current, payload.affectedComponents, false);\n }\n }\n\n useEffect(() => {\n if (!editorRef.current) {\n return () => {\n // no op\n };\n }\n\n if (editorInstance.current) {\n editorInstance.current.destroy();\n editorInstance.current = null;\n isEditorAliveRef.current = false;\n }\n\n const currentMode = mode;\n\n const editor = grapesjs.init({\n container: editorRef.current,\n height: '100%',\n plugins: [\n tailwind,\n createGrapesjsShadcnGenericPlugin(\n currentMode,\n performInteractionWrapper,\n renderedComponents.current,\n setHasChanged,\n ),\n ],\n storageManager: { type: 'none' },\n richTextEditor: {\n actions: ['bold', 'italic', 'underline', 'strikethrough'],\n },\n canvas: {\n customBadgeLabel: (component) => {\n const tagName = component.get('tagName');\n\n return tagName === 'body' ? '' : tagName || '';\n },\n },\n });\n\n isEditorAliveRef.current = true;\n\n let injectionAttempts = 0;\n\n function injectStylesEarly() {\n const iframeDoc = editor.Canvas?.getDocument?.();\n\n if (iframeDoc && iframeDoc.head) {\n if (!iframeDoc.head.querySelector('[data-grapesjs-styles]')) {\n const style = iframeDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n iframeDoc.head.appendChild(style);\n }\n } else if (injectionAttempts < 50) {\n injectionAttempts += 1;\n requestAnimationFrame(injectStylesEarly);\n }\n }\n\n requestAnimationFrame(injectStylesEarly);\n\n async function checkDirty() {\n if (isStreamingRef.current || isSystemUpdateRef.current) {\n return;\n }\n\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n let stored = null;\n\n try {\n stored = await editorInstance.current.store();\n } catch (err) {\n return;\n }\n\n if (!stored) {\n return;\n }\n\n const newJson = JSON.stringify(stored);\n\n if (newJson !== lastJsonRef.current) {\n setHasChanged(true);\n lastJsonRef.current = newJson;\n }\n }\n\n const debouncedCheckDirty = (() => {\n let timeout: NodeJS.Timeout | null = null;\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(checkDirty, 200);\n };\n })();\n\n [\n 'component:add',\n 'component:remove',\n 'component:update:content',\n 'style:update',\n 'component:drag:end',\n 'rte:change',\n ].forEach((evt) => {\n editor.on(evt, debouncedCheckDirty);\n });\n\n editor.on('component:update', (model, prop) => {\n if (['attributes', 'componentProps', 'content'].includes(prop)) {\n debouncedCheckDirty();\n }\n });\n\n // Tailwind CSS rules aren't fully added to our component\n // So, adding them from here!\n editor.on('load', async () => {\n const canvasDoc = editor.Canvas.getDocument();\n const canvasHead = canvasDoc.head;\n\n if (!canvasHead.querySelector('[data-grapesjs-styles]')) {\n const style = canvasDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n canvasHead.appendChild(style);\n }\n\n isSystemUpdateRef.current = true;\n lastJsonRef.current = JSON.stringify(await editor.store());\n isSystemUpdateRef.current = false;\n });\n\n editorInstance.current = editor;\n\n if (setEditor) {\n setEditor(editor);\n }\n\n TypesToRegister.forEach(({ type, tagName }) => {\n if (!editor.DomComponents.getType(type)) {\n editor.DomComponents.addType(type, {\n model: {\n defaults: { tagName },\n },\n view: {},\n });\n }\n });\n\n return function cleanup() {\n editor.destroy();\n isEditorAliveRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (json && json.pages?.length > 0 && json.pages[0].frames?.length > 0) {\n isSystemUpdateRef.current = true;\n const raw = json.pages[0].frames[0].component;\n const processed = expandActions(raw);\n editorInstance.current?.setComponents(processed);\n\n const cssText = convertStyles(json.styles || []);\n editorInstance.current?.setStyle(cssText);\n\n setTimeout(async () => {\n if (editorInstance.current) {\n lastJsonRef.current = JSON.stringify(await editorInstance.current.store());\n isSystemUpdateRef.current = false;\n }\n }, 100);\n }\n }, [json]);\n\n useEffect(() => {\n if (mode && editorInstance.current) {\n isSystemUpdateRef.current = true;\n\n setTimeout(() => {\n setComponentProperties(editorInstance.current as Editor, mode === 'preview');\n\n setTimeout(() => {\n isSystemUpdateRef.current = false;\n }, 50);\n }, 0);\n }\n }, [mode]);\n\n return (\n <React.Fragment>\n <StyledEditor />\n <div ref={editorRef} id=\"grapesjs-editor\" />\n </React.Fragment>\n );\n}\n\nexport default GrapesjsCanvas;\n"],"mappings":"wLAAA,uDACA,MAAO,CAAAA,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AAzC,cAAc,CAACK,OAAO,CAACqC,KAAK,CAAC,CAAC,QAAAkF,SAAA,CAAAvB,EAAA,CAAAuB,SAAA,CAAAjF,IAAA,CAAzExC,WAAW,CAACE,OAAO,CAAAuH,SAAA,CAAA3E,EAAA,CAAQuC,SAAS,CAAAc,IAAA,CAAAsB,SAAA,CAAA3E,EAAA,CAAA2E,SAAA,CAAAvB,EAAA,EACpCnG,iBAAiB,CAACG,OAAO,CAAG,KAAK,CAAC,wBAAAuH,SAAA,CAAAtE,IAAA,KAAAoE,QAAA,EAErC,GAAE,GAAG,CACR,CACF,CAAC,CAAE,CAACrI,IAAI,CAAC,CAAC,CAEV5F,SAAS,CAAC,UAAM,CACd,GAAI8F,IAAI,EAAIS,cAAc,CAACK,OAAO,CAAE,CAClCH,iBAAiB,CAACG,OAAO,CAAG,IAAI,CAEhCuF,UAAU,CAAC,UAAM,CACfrL,sBAAsB,CAACyF,cAAc,CAACK,OAAO,CAAYd,IAAI,GAAK,SAAS,CAAC,CAE5EqG,UAAU,CAAC,UAAM,CACf1F,iBAAiB,CAACG,OAAO,CAAG,KAC9B,CAAC,CAAE,EAAE,CACP,CAAC,CAAE,CAAC,CACN,CACF,CAAC,CAAE,CAACd,IAAI,CAAC,CAAC,CAEV,mBACEjF,KAAA,CAACd,KAAK,CAACqO,QAAQ,EAAAC,QAAA,eACb1N,IAAA,CAACF,YAAY,GAAE,CAAC,cAChBE,IAAA,QAAK2N,GAAG,CAAEhI,SAAU,CAACzB,EAAE,CAAC,iBAAiB,CAAE,CAAC,EAC9B,CAEpB,CAEA,cAAe,CAAAa,cAAc","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","grapesjs","tailwind","TypesToRegister","toKebabCase","tailwindCompiledCss","datePickerCss","createGrapesjsShadcnGenericPlugin","StyledEditor","jsx","_jsx","jsxs","_jsxs","setComponentProperties","editor","isPreview","setPropertiesRecursively","comp","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","_extends","get","isEditable","attributes","command","components","forEach","runCommand","stopCommand","wrapper","getWrapper","find","convertStyles","stylesArray","map","block","selectors","Array","isArray","join","declarations","Object","entries","style","_ref","prop","value","createActionCardConfig","action","icon","title","description","type","componentName","componentProps","headerContent","bodyContent","expandActions","node","_node$componentProps","actions","length","classes","concat","undefined","i","id","setInteracting","renderedComponents","inProgress","component","componentId","showLoader","gjsModel","interactionApiInProgress","expandActionsComponent","model","append","addClass","GrapesjsCanvas","_ref2","json","_ref2$mode","mode","setEditor","performInteraction","_ref2$newDataNotifier","newDataNotifier","_ref2$setHasChanged","setHasChanged","isStreaming","_ref2$isModeChangeFro","isModeChangeFromToggle","editorRef","editorInstance","isStreamingRef","isSystemUpdateRef","lastJsonRef","isEditorAliveRef","_React$useState","useState","isTransitioning","setIsTransitioning","current","notificationHandler","props","_props$newProps","newProps","_props$newAttributes","newAttributes","filteredProps","keys","key","name","parsedNewProps","pagination","isActionsComponent","hasValidActionsData","_model$components$at","isAlreadyExpanded","at","performInteractionWrapper","_x","_performInteractionWrapper","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee4","payload","_editorInstance$curre3","updatedJson","apiResponse","componentUpdates","wrap","_callee4$","_context4","prev","next","store","sent","affectedComponents","_ref6","error","isMissing","abrupt","t0","errorMessage","Error","message","finish","stop","destroy","currentMode","init","container","height","plugins","storageManager","richTextEditor","canvas","customBadgeLabel","tagName","injectionAttempts","injectStylesEarly","_editor$Canvas","iframeDoc","Canvas","getDocument","head","querySelector","createElement","fullCss","innerHTML","setAttribute","appendChild","requestAnimationFrame","checkDirty","_checkDirty","_callee2","stored","newJson","_callee2$","_context2","JSON","stringify","debouncedCheckDirty","timeout","clearTimeout","setTimeout","evt","on","includes","_callee","canvasDoc","canvasHead","_callee$","_context","t1","call","_ref4","DomComponents","getType","addType","defaults","view","cleanup","_json$pages","_json$pages$0$frames","pages","frames","_editorInstance$curre","_editorInstance$curre2","raw","processed","setComponents","cssText","styles","setStyle","_callee3","_callee3$","_context3","Fragment","children","ref","opacity","transition"],"sources":["../src/GrapesjsCanvas.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { useEffect, useRef } from 'react';\n// eslint-disable-next-line import/no-named-as-default\nimport grapesjs, { Component, Editor } from 'grapesjs';\nimport 'grapesjs/dist/css/grapes.min.css';\nimport tailwind from 'grapesjs-tailwind';\n\nimport { TypesToRegister } from './constants';\nimport { toKebabCase } from './helpers';\nimport { tailwindCompiledCss } from './helpers/css';\nimport { datePickerCss } from './helpers/date-picker';\nimport { createGrapesjsShadcnGenericPlugin } from './plugins/grapejs-plugin';\nimport { StyledEditor } from './index.styles';\n\ntype NotificationHandler = (newData: {\n componentId: string;\n newProps: Record<string, any>;\n newAttributes: Record<string, any>;\n}) => boolean;\n\ntype GrapesjsCanvasProps = {\n json: any;\n mode?: 'editor' | 'preview';\n setEditor: (editor: Editor) => void;\n performInteraction: (payload: Record<string, any>) => Promise<Record<string, any> | undefined>;\n newDataNotifier: (notifHandler: NotificationHandler) => void;\n setHasChanged: (hasChanged: boolean) => void;\n isStreaming: boolean;\n isModeChangeFromToggle?: boolean;\n};\n\nfunction setComponentProperties(editor: Editor, isPreview: boolean) {\n function setPropertiesRecursively(comp: Component) {\n comp.set({\n editable: !isPreview,\n draggable: !isPreview,\n droppable: !isPreview && comp.getName() !== 'Shadcn-generic',\n selectable: !isPreview,\n hoverable: !isPreview,\n highlightable: !isPreview,\n copyable: false,\n resizable: false,\n removable: !isPreview,\n badgable: false,\n });\n\n comp.set('attributes', {\n ...(comp.get('attributes') || {}),\n isEditable: !isPreview,\n });\n\n if (!isPreview) {\n comp.set('toolbar', [\n { attributes: { class: 'fa fa-arrows' }, command: 'tlb-move' },\n { attributes: { class: 'fa fa-trash' }, command: 'tlb-delete' },\n ]);\n }\n\n comp.components().forEach(setPropertiesRecursively);\n }\n\n if (isPreview) {\n editor.runCommand('core:preview');\n } else {\n editor.stopCommand('core:preview');\n }\n\n const wrapper = editor.getWrapper();\n wrapper?.find('*').forEach(setPropertiesRecursively);\n}\n\nfunction convertStyles(stylesArray: any[]): string {\n return stylesArray\n .map((block) => {\n const selectors = Array.isArray(block.selectors)\n ? block.selectors.join(', ')\n : block.selectors;\n const declarations = Object.entries(block.style)\n .map(([prop, value]) => `${toKebabCase(prop)}: ${value};`)\n .join(' ');\n\n return `${selectors} { ${declarations} }`;\n })\n .join('\\n');\n}\n\nfunction createActionCardConfig(action: any): any {\n const { icon, title, description } = action;\n\n return {\n type: 'shadcn-generic',\n componentName: 'ActionCard',\n badgable: false,\n copyable: false,\n removable: true,\n draggable: true,\n componentProps: {\n icon,\n headerContent: title,\n bodyContent: description,\n },\n };\n}\n\nfunction expandActions(node: any): any {\n if (node.type === 'shadcn-generic' && node.componentName === 'Actions') {\n const actions = node.componentProps?.actions;\n\n if (Array.isArray(actions) && actions.length > 0) {\n return {\n ...node,\n type: 'div',\n classes: ['dashboard-cards', ...(node.classes || [])],\n componentName: undefined,\n componentProps: undefined,\n components: actions.map((action: any, i: number) => ({\n ...createActionCardConfig(action),\n id: `${node.id}--action-card-${i}`,\n })),\n };\n }\n\n return node;\n }\n\n if (Array.isArray(node.components)) {\n return {\n ...node,\n components: node.components.map(expandActions),\n };\n }\n\n return node;\n}\n\nfunction setInteracting(\n renderedComponents: Record<string, Component>,\n components: { componentId: string; showLoader: boolean }[],\n inProgress: boolean,\n) {\n components.forEach((component) => {\n const { componentId, showLoader } = component;\n\n if (!showLoader) {\n return;\n }\n\n const gjsModel = renderedComponents[componentId];\n\n if (gjsModel) {\n gjsModel.set('attributes', {\n ...gjsModel.get('attributes'),\n interactionApiInProgress: inProgress,\n });\n }\n });\n}\n\nfunction expandActionsComponent(model: Component, actions: any[]): void {\n model.components('');\n\n actions.forEach((action: any) => {\n model.append(createActionCardConfig(action));\n });\n\n model.set('type', 'div');\n model.addClass('dashboard-cards');\n model.set('componentName', undefined);\n model.set('componentProps', {});\n}\n\nfunction GrapesjsCanvas({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n newDataNotifier = () => {\n // no op\n },\n setHasChanged = () => {\n // no op\n },\n isStreaming,\n isModeChangeFromToggle = false,\n}: GrapesjsCanvasProps) {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<Editor | null>(null);\n const renderedComponents = useRef<Record<string, Component>>({});\n const isStreamingRef = useRef(isStreaming);\n const isSystemUpdateRef = useRef(false);\n const lastJsonRef = useRef<string>('');\n const isEditorAliveRef = useRef(false);\n const [isTransitioning, setIsTransitioning] = React.useState(false);\n\n useEffect(() => {\n isStreamingRef.current = isStreaming;\n }, [isStreaming]);\n\n function notificationHandler(\n props: Parameters<NotificationHandler>[0],\n ): ReturnType<NotificationHandler> {\n if (!props) {\n return true;\n }\n\n const { componentId, newProps = {}, newAttributes = {} } = props;\n\n const model = renderedComponents.current[componentId];\n\n if (!model) {\n return false;\n }\n\n // Filter out complex placeholder objects by setting them to null\n // This ensures placeholder values are properly cleared and don't cause stale data issues\n const filteredProps = { ...newProps };\n\n Object.keys(filteredProps).forEach((key) => {\n const value = filteredProps[key];\n\n if (value && typeof value === 'object' && value.name === '__peak_placeholder') {\n filteredProps[key] = null;\n }\n });\n\n const parsedNewProps = {\n ...filteredProps,\n };\n\n if (filteredProps.pagination) {\n parsedNewProps.pagination = {\n ...(model.get('componentProps').pagination || {}),\n ...filteredProps.pagination,\n };\n }\n\n // Handle Actions component: expand into ActionCards when data arrives via streaming\n const isActionsComponent = model.get('componentName') === 'Actions';\n const hasValidActionsData =\n parsedNewProps.actions &&\n parsedNewProps.actions !== null &&\n Array.isArray(parsedNewProps.actions) &&\n parsedNewProps.actions.length > 0;\n\n if (isActionsComponent && hasValidActionsData) {\n const isAlreadyExpanded =\n model.components().length > 0 &&\n model.components().at(0)?.get('componentName') === 'ActionCard';\n\n if (!isAlreadyExpanded) {\n expandActionsComponent(model, parsedNewProps.actions);\n\n return true;\n }\n }\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...parsedNewProps,\n });\n\n model.set('attributes', {\n ...model.get('attributes'),\n ...newAttributes,\n });\n\n return true;\n }\n\n useEffect(() => {\n newDataNotifier(notificationHandler);\n }, []);\n\n async function performInteractionWrapper(payload: Record<string, any>) {\n const updatedJson = await editorInstance.current?.store();\n setInteracting(renderedComponents.current, payload.affectedComponents, true);\n\n try {\n const apiResponse = await performInteraction({\n ...payload,\n json: updatedJson,\n });\n\n const componentUpdates = apiResponse || {};\n\n Object.entries(componentUpdates).forEach(([key, value]) => {\n const model = renderedComponents.current[key];\n\n if (model) {\n model.set('attributes', {\n ...model.get('attributes'),\n error: undefined,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...value,\n error: undefined,\n isMissing: undefined,\n });\n }\n });\n\n return componentUpdates;\n } catch (error) {\n payload.affectedComponents.forEach((componentId: string) => {\n const model = renderedComponents.current[componentId];\n\n if (model) {\n const errorMessage =\n error instanceof Error ? error.message : 'Something went wrong. Please try again.';\n\n model.set('attributes', {\n ...model.get('attributes'),\n error: errorMessage,\n });\n\n model.set('componentProps', {\n ...model.get('componentProps'),\n error: errorMessage,\n isMissing: undefined,\n });\n }\n });\n\n throw error;\n } finally {\n setInteracting(renderedComponents.current, payload.affectedComponents, false);\n }\n }\n\n useEffect(() => {\n if (!editorRef.current) {\n return () => {\n // no op\n };\n }\n\n if (editorInstance.current) {\n editorInstance.current.destroy();\n editorInstance.current = null;\n isEditorAliveRef.current = false;\n }\n\n const currentMode = mode;\n\n const editor = grapesjs.init({\n container: editorRef.current,\n height: '100%',\n plugins: [\n tailwind,\n createGrapesjsShadcnGenericPlugin(\n currentMode,\n performInteractionWrapper,\n renderedComponents.current,\n setHasChanged,\n ),\n ],\n storageManager: { type: 'none' },\n richTextEditor: {\n actions: ['bold', 'italic', 'underline', 'strikethrough'],\n },\n canvas: {\n customBadgeLabel: (component) => {\n const tagName = component.get('tagName');\n\n return tagName === 'body' ? '' : tagName || '';\n },\n },\n });\n\n isEditorAliveRef.current = true;\n\n let injectionAttempts = 0;\n\n function injectStylesEarly() {\n const iframeDoc = editor.Canvas?.getDocument?.();\n\n if (iframeDoc && iframeDoc.head) {\n if (!iframeDoc.head.querySelector('[data-grapesjs-styles]')) {\n const style = iframeDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n iframeDoc.head.appendChild(style);\n }\n } else if (injectionAttempts < 50) {\n injectionAttempts += 1;\n requestAnimationFrame(injectStylesEarly);\n }\n }\n\n requestAnimationFrame(injectStylesEarly);\n\n async function checkDirty() {\n if (isStreamingRef.current || isSystemUpdateRef.current) {\n return;\n }\n\n if (!isEditorAliveRef.current || !editorInstance.current) {\n return;\n }\n\n let stored = null;\n\n try {\n stored = await editorInstance.current.store();\n } catch (err) {\n return;\n }\n\n if (!stored) {\n return;\n }\n\n const newJson = JSON.stringify(stored);\n\n if (newJson !== lastJsonRef.current) {\n setHasChanged(true);\n lastJsonRef.current = newJson;\n }\n }\n\n const debouncedCheckDirty = (() => {\n let timeout: NodeJS.Timeout | null = null;\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(checkDirty, 200);\n };\n })();\n\n [\n 'component:add',\n 'component:remove',\n 'component:update:content',\n 'style:update',\n 'component:drag:end',\n 'rte:change',\n ].forEach((evt) => {\n editor.on(evt, debouncedCheckDirty);\n });\n\n editor.on('component:update', (model, prop) => {\n if (['attributes', 'componentProps', 'content'].includes(prop)) {\n debouncedCheckDirty();\n }\n });\n\n // Tailwind CSS rules aren't fully added to our component\n // So, adding them from here!\n editor.on('load', async () => {\n const canvasDoc = editor.Canvas.getDocument();\n const canvasHead = canvasDoc.head;\n\n if (!canvasHead.querySelector('[data-grapesjs-styles]')) {\n const style = canvasDoc.createElement('style');\n const fullCss = `\n ${tailwindCompiledCss}\n ${datePickerCss}\n ::-webkit-scrollbar {\n width: 0px;\n height: 0px;\n }\n html, body {\n overflow: auto !important;\n -ms-overflow-style: none; /* IE and Edge */\n scrollbar-width: none; /* Firefox */\n }\n `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n style.setAttribute('data-grapesjs-styles', 'true');\n canvasHead.appendChild(style);\n }\n\n isSystemUpdateRef.current = true;\n lastJsonRef.current = JSON.stringify(await editor.store());\n isSystemUpdateRef.current = false;\n });\n\n editorInstance.current = editor;\n\n if (setEditor) {\n setEditor(editor);\n }\n\n TypesToRegister.forEach(({ type, tagName }) => {\n if (!editor.DomComponents.getType(type)) {\n editor.DomComponents.addType(type, {\n model: {\n defaults: { tagName },\n },\n view: {},\n });\n }\n });\n\n return function cleanup() {\n editor.destroy();\n isEditorAliveRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (json && json.pages?.length > 0 && json.pages[0].frames?.length > 0) {\n isSystemUpdateRef.current = true;\n const raw = json.pages[0].frames[0].component;\n const processed = expandActions(raw);\n editorInstance.current?.setComponents(processed);\n\n const cssText = convertStyles(json.styles || []);\n editorInstance.current?.setStyle(cssText);\n\n setTimeout(async () => {\n if (editorInstance.current) {\n lastJsonRef.current = JSON.stringify(await editorInstance.current.store());\n isSystemUpdateRef.current = false;\n }\n }, 100);\n }\n }, [json]);\n\n useEffect(() => {\n if (mode && editorInstance.current) {\n isSystemUpdateRef.current = true;\n\n if(isModeChangeFromToggle){\n setIsTransitioning(true);\n }\n\n setTimeout(() => {\n setComponentProperties(editorInstance.current as Editor, mode === 'preview');\n\n setTimeout(() => {\n isSystemUpdateRef.current = false;\n setIsTransitioning(false);\n }, 50);\n }, 0);\n }\n }, [mode, isModeChangeFromToggle]);\n\n return (\n <React.Fragment>\n <StyledEditor />\n <div \n ref={editorRef} \n id=\"grapesjs-editor\" \n style={{\n opacity: isTransitioning ? 0 : 1,\n transition: 'opacity 0.15s ease-in-out',\n }}\n />\n </React.Fragment>\n );\n}\n\nexport default GrapesjsCanvas;\n"],"mappings":"wLAAA,uDACA,MAAO,CAAAA,KAAK,EAAIC,SAAS,CAAEC,MAAM,KAAQ,OAAO,CAChD;AACA,MAAO,CAAAC,QAAQ,KAA6B,UAAU,CACtD,MAAO,kCAAkC,CACzC,MAAO,CAAAC,QAAQ,KAAM,mBAAmB,CAExC,OAASC,eAAe,KAAQ,aAAa,CAC7C,OAASC,WAAW,KAAQ,WAAW,CACvC,OAASC,mBAAmB,KAAQ,eAAe,CACnD,OAASC,aAAa,KAAQ,uBAAuB,CACrD,OAASC,iCAAiC,KAAQ,0BAA0B,CAC5E,OAASC,YAAY,KAAQ,gBAAgB,CAAC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAmB9C,QAAS,CAAAC,sBAAsBA,CAACC,MAAc,CAAEC,SAAkB,CAAE,CAClE,QAAS,CAAAC,wBAAwBA,CAACC,IAAe,CAAE,CACjDA,IAAI,CAACC,GAAG,CAAC,CACPC,QAAQ,CAAE,CAACJ,SAAS,CACpBK,SAAS,CAAE,CAACL,SAAS,CACrBM,SAAS,CAAE,CAACN,SAAS,EAAIE,IAAI,CAACK,OAAO,CAAC,CAAC,GAAK,gBAAgB,CAC5DC,UAAU,CAAE,CAACR,SAAS,CACtBS,SAAS,CAAE,CAACT,SAAS,CACrBU,aAAa,CAAE,CAACV,SAAS,CACzBW,QAAQ,CAAE,KAAK,CACfC,SAAS,CAAE,KAAK,CAChBC,SAAS,CAAE,CAACb,SAAS,CACrBc,QAAQ,CAAE,KACZ,CAAC,CAAC,CAEFZ,IAAI,CAACC,GAAG,CAAC,YAAY,CAAAY,QAAA,IACfb,IAAI,CAACc,GAAG,CAAC,YAAY,CAAC,EAAI,CAAC,CAAC,EAChCC,UAAU,CAAE,CAACjB,SAAS,EACvB,CAAC,CAEF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CAAES,sBAAsB,CAAC,CAAC,CAElC,mBACE1F,KAAA,CAACd,KAAK,CAAC2O,QAAQ,EAAAC,QAAA,eACbhO,IAAA,CAACF,YAAY,GAAE,CAAC,cAChBE,IAAA,QACEiO,GAAG,CAAEpI,SAAU,CACf3B,EAAE,CAAC,iBAAiB,CACpBvB,KAAK,CAAE,CACLuL,OAAO,CAAE7H,eAAe,CAAG,CAAC,CAAG,CAAC,CAChC8H,UAAU,CAAE,2BACd,CAAE,CACH,CAAC,EACY,CAEpB,CAEA,cAAe,CAAApJ,cAAc","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@peak-ai/canvas",
|
|
3
3
|
"author": "squad-builder-experience",
|
|
4
4
|
"license": "UNLICENSED",
|
|
5
|
-
"version": "1.4.
|
|
5
|
+
"version": "1.4.39",
|
|
6
6
|
"description": "",
|
|
7
7
|
"dependencies": {
|
|
8
8
|
"@emotion/react": "^11.11.4",
|
|
@@ -68,4 +68,4 @@
|
|
|
68
68
|
"types": "index.d.ts",
|
|
69
69
|
"module": "index.js",
|
|
70
70
|
"sideEffects": false
|
|
71
|
-
}
|
|
71
|
+
}
|
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _extends from"@babel/runtime/helpers/extends";import _objectWithoutPropertiesLoose from"@babel/runtime/helpers/objectWithoutPropertiesLoose";var _excluded=["gjsModel"],_excluded2=["gjsModel","performInteraction"],_excluded3=["gjsModel","performInteraction"],_excluded4=["gjsModel","performInteraction"],_excluded5=["gjsModel"];import _regeneratorRuntime from"@babel/runtime/regenerator";function _createForOfIteratorHelperLoose(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}/* eslint-disable no-nested-ternary *//* eslint-disable @typescript-eslint/ban-ts-comment *//* eslint-disable func-style *//* eslint-disable @typescript-eslint/no-empty-function *//* eslint-disable func-names *//* eslint-disable @typescript-eslint/no-explicit-any */import chroma from"chroma-js";import React,{useEffect,useState,useMemo,useRef}from"react";import{renderNoDataFallback}from"./extra";import{CircleAlert,TrendingDown,TrendingUp,ShoppingCart,ChartBarBig,Tag,MapPin}from"lucide-react";import{StyledInfoButton}from"./styled-info-button";import{filterPlaceholders}from"../../helpers/filter-placeholder";import{theme}from"@peak-ai/ais-components/theme";import Markdown from"markdown-to-jsx";import{Bar,BarChart,CartesianGrid,Legend,Line,LineChart,Pie,PieChart,Scatter,ScatterChart,XAxis,YAxis,Cell}from"recharts/lib";// @ts-ignore
|
|
1
|
+
import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _extends from"@babel/runtime/helpers/extends";import _objectWithoutPropertiesLoose from"@babel/runtime/helpers/objectWithoutPropertiesLoose";var _excluded=["gjsModel"],_excluded2=["gjsModel","performInteraction"],_excluded3=["gjsModel","performInteraction"],_excluded4=["gjsModel","performInteraction"],_excluded5=["gjsModel"];import _regeneratorRuntime from"@babel/runtime/regenerator";function _createForOfIteratorHelperLoose(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}/* eslint-disable no-nested-ternary *//* eslint-disable @typescript-eslint/ban-ts-comment *//* eslint-disable func-style *//* eslint-disable @typescript-eslint/no-empty-function *//* eslint-disable func-names *//* eslint-disable @typescript-eslint/no-explicit-any */import chroma from"chroma-js";import React,{useEffect,useState,useMemo,useCallback,useRef}from"react";import{renderNoDataFallback}from"./extra";import{CircleAlert,TrendingDown,TrendingUp,ShoppingCart,ChartBarBig,Tag,MapPin}from"lucide-react";import{StyledInfoButton}from"./styled-info-button";import{filterPlaceholders}from"../../helpers/filter-placeholder";import{theme}from"@peak-ai/ais-components/theme";import Markdown from"markdown-to-jsx";import{Bar,BarChart,CartesianGrid,Legend,Line,LineChart,Pie,PieChart,Scatter,ScatterChart,XAxis,YAxis,Cell}from"recharts/lib";// @ts-ignore
|
|
2
2
|
import*as domutil from"recharts/lib/util/DOMUtils";import{Group}from"@visx/group";import{scaleBand,scaleLinear}from"@visx/scale";import{AxisBottom,AxisLeft}from"@visx/axis";import{GridRows}from"@visx/grid";import{Circle}from"@visx/shape";import{useTooltip,TooltipWithBounds,defaultStyles}from"@visx/tooltip";import{forceSimulation,forceX,forceY,forceCollide}from"d3-force";import{TooltipButton}from"../../shadcn/components/ui/button";import{Card,CardContent,CardDescription,CardFooter,CardHeader,CardTitle}from"../../shadcn/components/ui/card";import{ChartContainer,ChartTooltip,ChartTooltipContent}from"../../shadcn/components/ui/chart";import{renderFilter}from"../../shadcn/components/ui/filter";import{renderSearch}from"../../shadcn/components/ui/search";import{CardLoader,ChartLoader,MarkdownLoader}from"../../shadcn/components/ui/skeleton";import{Tabs,TabsContent,TabsList,TabsTrigger}from"../../shadcn/components/ui/tabs";import{cn}from"../../shadcn/utils";import{getAffectedComponentsWithLoader}from"../../helpers";import{DataTable}from"./data-table";import{ComponentWrapper}from"../../shadcn/components/ui/error-wrapper";// Monkey-patching the getOffset function to use iframe's window instead of global one
|
|
3
3
|
// REMEMBER TO UDPATE THIS WHEN recharts IS UPGRADED
|
|
4
4
|
// @ts-ignore
|
|
5
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";domutil.getOffset=function(el){var html=el.ownerDocument.documentElement;var box={top:0,left:0};if(typeof el.getBoundingClientRect!=="undefined"){box=el.getBoundingClientRect()}var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;return{top:box.top+iframeWindow.pageYOffset-html.clientTop,left:box.left+iframeWindow.pageXOffset-html.clientLeft}};var baseColors=[[theme.colors.Blue_100,theme.colors.Blue_30],[theme.colors.Purpley_100,theme.colors.Purpley_30],[theme.colors.Light_Bluish_Green,"#06601b"],[theme.colors.Wild_Strawberry,"#4d001c"]];var iconMap={TrendingUp:/*#__PURE__*/_jsx(TrendingUp,{}),TrendingDown:/*#__PURE__*/_jsx(TrendingDown,{}),ShoppingCart:/*#__PURE__*/_jsx(ShoppingCart,{}),Equalizer:/*#__PURE__*/_jsx(ChartBarBig,{}),Style:/*#__PURE__*/_jsx(Tag,{}),Place:/*#__PURE__*/_jsx(MapPin,{})};function getIconFromString(iconString){if(!iconString){return null}if(iconMap[iconString]){return iconMap[iconString]}var lowerIconString=iconString.toLowerCase();var matchingKey=Object.keys(iconMap).find(function(key){return key.toLowerCase()===lowerIconString});if(matchingKey){return iconMap[matchingKey]}return null}function getNColors(n){var colors=[];var safeBaseColors=Array.isArray(baseColors)?baseColors:[];for(var _iterator=_createForOfIteratorHelperLoose(safeBaseColors),_step;!(_step=_iterator()).done;){var baseColor=_step.value;// eslint-disable-next-line import/no-named-as-default-member
|
|
5
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";domutil.getOffset=function(el){var html=el.ownerDocument.documentElement;var box={top:0,left:0};if(typeof el.getBoundingClientRect!=="undefined"){box=el.getBoundingClientRect()}var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;return{top:box.top+iframeWindow.pageYOffset-html.clientTop,left:box.left+iframeWindow.pageXOffset-html.clientLeft}};var BEESWARM_CONFIG={RADIUS:4,SPREAD_FACTOR:0.45,RANDOM_FACTOR:2,SIMULATION_ITERATIONS:300,COLLISION_PADDING:3};var baseColors=[[theme.colors.Blue_100,theme.colors.Blue_30],[theme.colors.Purpley_100,theme.colors.Purpley_30],[theme.colors.Light_Bluish_Green,"#06601b"],[theme.colors.Wild_Strawberry,"#4d001c"]];var iconMap={TrendingUp:/*#__PURE__*/_jsx(TrendingUp,{}),TrendingDown:/*#__PURE__*/_jsx(TrendingDown,{}),ShoppingCart:/*#__PURE__*/_jsx(ShoppingCart,{}),Equalizer:/*#__PURE__*/_jsx(ChartBarBig,{}),Style:/*#__PURE__*/_jsx(Tag,{}),Place:/*#__PURE__*/_jsx(MapPin,{})};function getIconFromString(iconString){if(!iconString){return null}if(iconMap[iconString]){return iconMap[iconString]}var lowerIconString=iconString.toLowerCase();var matchingKey=Object.keys(iconMap).find(function(key){return key.toLowerCase()===lowerIconString});if(matchingKey){return iconMap[matchingKey]}return null}function getNColors(n){var colors=[];var safeBaseColors=Array.isArray(baseColors)?baseColors:[];for(var _iterator=_createForOfIteratorHelperLoose(safeBaseColors),_step;!(_step=_iterator()).done;){var baseColor=_step.value;// eslint-disable-next-line import/no-named-as-default-member
|
|
6
6
|
colors.push(chroma.scale(baseColor).mode("lab").colors(n))}function getOneColor(existing){var color=null;do{var base=colors[Math.floor(Math.random()*colors.length)];var selectedColorIndex=Math.floor(Math.random()*base.length);color=base[selectedColorIndex]}while(existing.includes(color));return color}var selectedColors=[];for(var i=0;i<n;i++){selectedColors.push(getOneColor(selectedColors))}return selectedColors}/* TODO: Loader remains */export function renderActionCard(props){var gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded);// Memoize filtered props to avoid re-filtering on every render
|
|
7
7
|
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState=useState(initialData),allData=_useState[0],setAllData=_useState[1];var _allData$headerConten=allData.headerContent,headerContent=_allData$headerConten===void 0?"Default action card title":_allData$headerConten,icon=allData.icon,_allData$bodyContent=allData.bodyContent,bodyContent=_allData$bodyContent===void 0?"Default body content. Click to edit.":_allData$bodyContent;var _useState2=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState2[0],setAttributes=_useState2[1];useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var defaultClasses="text-black p-4 rounded-lg shadow border flex flex-col h-full";return/*#__PURE__*/_jsx(Card,_extends({className:defaultClasses+" relative",style:{backgroundColor:"#f9f9fe"},isEditable:false,contentEditable:false},rest,{children:/*#__PURE__*/_jsx(CardContent,{className:"p-0",isEditable:false,contentEditable:false,children:/*#__PURE__*/_jsx("div",{className:"px-4 py-3",children:/*#__PURE__*/_jsxs("div",{className:"flex items-start flex-col",children:[/*#__PURE__*/_jsxs("div",{className:"flex items-center justify-between w-full",children:[/*#__PURE__*/_jsx("div",{className:"text-xl font-semibold",children:headerContent}),/*#__PURE__*/_jsx("div",{className:"text-5xl ml-2 flex items-center","aria-hidden":"true",children:getIconFromString(icon)})]}),/*#__PURE__*/_jsx("div",{className:"w-full mt-1",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing||!bodyContent?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsx("div",{className:"text-base leading-relaxed",children:bodyContent})})]})})})}))}export function renderCard(props){var _attributes$isEditabl,_attributes$error,_attributes$isMissing;var gjsModel=props.gjsModel,_props$performInterac=props.performInteraction,performInteraction=_props$performInterac===void 0?function(){return Promise.resolve({})}:_props$performInterac,rest=_objectWithoutPropertiesLoose(props,_excluded2);// Memoize filtered props to avoid re-filtering on every render
|
|
8
|
-
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState3=useState(initialData),allData=_useState3[0],setAllData=_useState3[1];var headerContent=allData.headerContent,headerDescription=allData.headerDescription,bodyContent=allData.bodyContent,footerContent=allData.footerContent,footerClass=allData.footerClass,footerIcon=allData.footerIcon,contentMetadata=allData.contentMetadata,contentMetadataClass=allData.contentMetadataClass,dataClassName=allData.className,dataError=allData.error,dataIsMissing=allData.isMissing;function toSafeText(value){if(value===null||value===undefined){return""}return typeof value==="string"?value:JSON.stringify(value)}var safeHeaderContent=toSafeText(headerContent);var safeHeaderDescription=toSafeText(headerDescription);var safeBodyContent=toSafeText(bodyContent);var safeFooterContent=toSafeText(footerContent);var safeContentMetadata=toSafeText(contentMetadata);var _useState4=useState((safeFooterContent==null?void 0:safeFooterContent.length)>0),footerHasContent=_useState4[0],setFooterHasContent=_useState4[1];var _useState5=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState5[0],setAttributes=_useState5[1];var isEditable=(_attributes$isEditabl=attributes.isEditable)!=null?_attributes$isEditabl:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);useEffect(function(){setFooterHasContent((safeFooterContent==null?void 0:safeFooterContent.length)>0)},[safeFooterContent]);var defaultClasses="bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none";var defaultFooterClasses=footerHasContent?"text-sm bg-pink-50 text-pink-900 shadow-sm":"text-sm";var defaultContentMetadataClasses="text-xs";var mergedCardClassName=dataClassName?cn(defaultClasses,dataClassName):defaultClasses;var mergedFooterClassName=footerClass?cn(defaultFooterClasses,footerClass):defaultFooterClasses;var mergedContentMetadataClassName=contentMetadataClass?cn(defaultContentMetadataClasses,contentMetadataClass):defaultContentMetadataClasses;var hasError=Boolean((_attributes$error=attributes==null?void 0:attributes.error)!=null?_attributes$error:dataError);var hasMissing=Boolean((_attributes$isMissing=attributes==null?void 0:attributes.isMissing)!=null?_attributes$isMissing:dataIsMissing);var isLoading=Boolean(((attributes==null?void 0:attributes.interactionApiInProgress)||(attributes==null?void 0:attributes.loading))&&!hasError&&!hasMissing);var footerIconText=typeof footerIcon==="string"?footerIcon:footerIcon&&typeof footerIcon==="object"&&"icon"in footerIcon?String(footerIcon.icon):"";function getCardContent(){if(isLoading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}var showEmpty=hasError||hasMissing||!safeBodyContent;function handleFooterInput(event){var target=event.target;var content=target.textContent||"";var hasContent=content.trim().length>0;setFooterHasContent(hasContent);if(!hasContent){var currentProps=gjsModel.get("componentProps");gjsModel.set("componentProps",_extends({},currentProps,{footerContent:null,footerIcon:null,footerClass:null,isEmptied:true}))}}return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"headerContent",contentEditable:isEditable,className:"text-lg",children:safeHeaderContent}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"headerDescription",contentEditable:isEditable,className:"text-sm",children:safeHeaderDescription})]})})}),showEmpty?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsxs(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-grow",children:[/*#__PURE__*/_jsx("div",{className:"text-3xl font-semibold truncate",children:safeBodyContent}),safeContentMetadata&&/*#__PURE__*/_jsx("div",{className:mergedContentMetadataClassName,style:{color:"#2A44D4"},children:safeContentMetadata})]}),/*#__PURE__*/_jsxs(CardFooter,{"data-slot":"footerContent",contentEditable:isEditable,className:mergedFooterClassName,onInput:handleFooterInput,children:[(footerIconText||"").trim()?/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIconText}):null,safeFooterContent||""]})]})}return/*#__PURE__*/_jsxs(Card,_extends({},rest,{isEditable:false,className:mergedCardClassName+" relative",children:[getCardContent(),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}function transformDataForScatter(data,xAxis,yAxis,dataKeys){if(!data||data.length===0){return[]}var scatterData=data.filter(function(item){return item[xAxis]!==null&&item[xAxis]!==undefined&&item[yAxis]!==null&&item[yAxis]!==undefined}).map(function(item){var _result;var result=(_result={},_result[xAxis]=Number(item[xAxis]),_result[yAxis]=Number(item[yAxis]),_result);if(dataKeys&&dataKeys.length>0){dataKeys.forEach(function(_ref){var key=_ref.key;if(item[key]!==null&&item[key]!==undefined){result[key]=Number(item[key])}})}return result});return scatterData}function binDataForHistogram(data,valueKey,bins){if(bins===void 0){bins=10}if(!data||data.length===0){return[]}var values=data.map(function(item){return Number(item[valueKey])}).filter(function(val){return!isNaN(val)});if(values.length===0){return[]}var min=Math.min.apply(Math,values);var max=Math.max.apply(Math,values);var binWidth=(max-min)/bins;var binsArray=new Array(bins).fill(0);var binLabels=[];for(var i=0;i<bins;i++){var binStart=min+i*binWidth;var binEnd=binStart+binWidth;binLabels.push(binStart.toFixed(1)+"-"+binEnd.toFixed(1))}values.forEach(function(value){var binIndex=Math.floor((value-min)/binWidth);if(binIndex>=bins){binIndex=bins-1}if(binIndex<0){binIndex=0}binsArray[binIndex]+=1});return binLabels.map(function(label,index){return{bin:label,frequency:binsArray[index]}})}function transformDataForBeeswarm(data,groupBy,valueKey){if(!data||data.length===0){return{nodes:[],groups:[]}}var grouped={};data.forEach(function(item){if(item[groupBy]!==null&&item[groupBy]!==undefined&&item[valueKey]!==null&&item[valueKey]!==undefined){var group=String(item[groupBy]);var value=Number(item[valueKey]);if(!isNaN(value)){if(!grouped[group]){grouped[group]=[]}grouped[group].push(value)}}});var groups=Object.keys(grouped).sort();var nodes=[];groups.forEach(function(group,groupIndex){var values=grouped[group];values.forEach(function(value){nodes.push({group:group,groupIndex:groupIndex,value:value,x:groupIndex,y:value,radius:4})})});return{nodes:nodes,groups:groups}}function BeeswarmChart(_ref2){var data=_ref2.data,groups=_ref2.groups,color=_ref2.color,groupBy=_ref2.groupBy,valueKey=_ref2.valueKey;var containerRef=useRef(null);var svgRef=useRef(null);var _useState6=useState({width:800,height:250}),dimensions=_useState6[0],setDimensions=_useState6[1];var _useState7=useState([]),simulatedNodes=_useState7[0],setSimulatedNodes=_useState7[1];var _useTooltip=useTooltip(),tooltipData=_useTooltip.tooltipData,tooltipLeft=_useTooltip.tooltipLeft,tooltipTop=_useTooltip.tooltipTop,tooltipOpen=_useTooltip.tooltipOpen,showTooltip=_useTooltip.showTooltip,hideTooltip=_useTooltip.hideTooltip;useEffect(function(){var updateDimensions=function updateDimensions(){if(containerRef.current){setDimensions({width:containerRef.current.offsetWidth||800,height:250})}};updateDimensions();var resizeObserver=new ResizeObserver(function(entries){for(var _iterator2=_createForOfIteratorHelperLoose(entries),_step2;!(_step2=_iterator2()).done;){var entry=_step2.value;setDimensions({width:entry.contentRect.width||800,height:250})}});if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateDimensions);return function(){resizeObserver.disconnect();window.removeEventListener("resize",updateDimensions)}},[]);var createXScale=function createXScale(innerWidth,groupDomain){var minBandwidth=60;var totalMinWidth=groupDomain.length*minBandwidth;var paddingRatio=0.3;var xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});if(totalMinWidth>innerWidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}else{xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});var currentBandwidth=xScale.bandwidth();if(currentBandwidth<minBandwidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}}return xScale};useEffect(function(){if(data.length===0||dimensions.width===0){return}var margin={top:20,right:20,bottom:60,left:60};var innerWidth=dimensions.width-margin.left-margin.right;var innerHeight=dimensions.height-margin.top-margin.bottom;var values=data.map(function(d){return d.value});var minValue=Math.min.apply(Math,values);var maxValue=Math.max.apply(Math,values);var valueRange=maxValue-minValue;var padding=valueRange*0.1;// Use consistent xScale calculation
|
|
9
|
-
var
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState8=useState(initialData),allData=_useState8[0],setAllData=_useState8[1];var _useState9=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState9[0],setAttributes=_useState9[1];var isEditable=(_attributes$isEditabl2=attributes.isEditable)!=null?_attributes$isEditabl2:false;var containerRef=useRef(null);var _useState10=useState(0),containerWidth=_useState10[0],setContainerWidth=_useState10[1];useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){var newAttributes=gjsModel.get("attributes");setAttributes(_extends({},newAttributes))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);useEffect(function(){var updateContainerWidth=function updateContainerWidth(){if(containerRef.current){setContainerWidth(containerRef.current.offsetWidth||0)}};var resizeObserver=new ResizeObserver(function(entries){for(var _iterator3=_createForOfIteratorHelperLoose(entries),_step3;!(_step3=_iterator3()).done;){var entry=_step3.value;setContainerWidth(entry.contentRect.width||0)}});updateContainerWidth();var timeoutId=setTimeout(updateContainerWidth,50);if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateContainerWidth);return function(){clearTimeout(timeoutId);resizeObserver.disconnect();window.removeEventListener("resize",updateContainerWidth)}},[]);var _allData$config=allData.config,config=_allData$config===void 0?{}:_allData$config,_allData$chartType=allData.chartType,chartType=_allData$chartType===void 0?"pie":_allData$chartType,_allData$chartData=allData.chartData,chartData=_allData$chartData===void 0?[]:_allData$chartData,className=allData.className,_allData$title=allData.title,title=_allData$title===void 0?"Title":_allData$title,_allData$subTitle=allData.subTitle,subTitle=_allData$subTitle===void 0?"Subtitle":_allData$subTitle;var defaultClasses="aspect-auto h-[250px] w-full min-w-[200px] min-h-[200px]";var mergedClasses=className?cn(defaultClasses,className):defaultClasses;if(chartType==="pie"){var safeChartData=Array.isArray(chartData)?chartData:[];var colors=getNColors(safeChartData.length);safeChartData.forEach(function(data,i){if(!data.fill){data.fill=colors[i]}})}else if(!config.color){var safeBaseColors=Array.isArray(baseColors)?baseColors:[];if(safeBaseColors.length>0){config.color=safeBaseColors[Math.floor(Math.random()*safeBaseColors.length)]}}var totalDataPoints=0;if(chartType==="bar"||chartType==="line"||chartType==="scatter"||chartType==="histogram"||chartType==="beeswarm"){var _safeChartData=Array.isArray(chartData)?chartData:[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];if(chartType==="bar"){totalDataPoints=_safeChartData.length*Math.max(1,safeDataKeys.length)}else if(chartType==="line"){totalDataPoints=_safeChartData.length}else if(chartType==="scatter"||chartType==="histogram"||chartType==="beeswarm"){totalDataPoints=_safeChartData.length}}var getScrollableWidth=function getScrollableWidth(){if(chartType==="line"){return totalDataPoints*20}if(chartType==="bar"){return totalDataPoints*20+(Array.isArray(config.dataKeys)?config.dataKeys.length:0)*8*(Array.isArray(chartData)?chartData.length:0)+(Array.isArray(chartData)?chartData.length:0)*15}if(chartType==="scatter"||chartType==="histogram"||chartType==="beeswarm"){return 800}return 800};var scrollWidth=getScrollableWidth();var shouldScroll=(chartType==="bar"||chartType==="line"||chartType==="beeswarm"||chartType==="histogram")&&totalDataPoints>15&&scrollWidth>containerWidth;var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=(attributes.interactionApiInProgress||attributes.loading)&&!hasError&&!hasMissing;var ChartWrapper=function ChartWrapper(_ref9){var children=_ref9.children;if(shouldScroll){return/*#__PURE__*/_jsx("div",{className:"w-full h-[250px] overflow-x-auto",children:/*#__PURE__*/_jsx("div",{style:{minWidth:scrollWidth+"px",height:"250px"},children:children})})}return/*#__PURE__*/_jsx("div",{className:"w-full h-[250px]",children:children})};var isBeeswarmChart=chartType==="beeswarm";var chartUi=isLoading?/*#__PURE__*/_jsx(ChartLoader,{}):hasError||hasMissing||!chartData?renderNoDataFallback():isBeeswarmChart?/*#__PURE__*/_jsx(ChartWrapper,{children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:config,className:mergedClasses,children:renderChartComponent(chartType,chartData,config)}))}):/*#__PURE__*/_jsx(ChartWrapper,{children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:config,className:mergedClasses,children:renderChartComponent(chartType,chartData,config)}))});return/*#__PURE__*/_jsxs(Card,{className:"shadow border mt-2 mb-2 relative",children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{ref:containerRef,"data-slot":"bodyContent",className:"px-6",style:{minHeight:"250px"},children:chartUi}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]})}export function renderTable(props){var _attributes$isEditabl3;var gjsModel=props.gjsModel,_props$performInterac3=props.performInteraction,performInteraction=_props$performInterac3===void 0?function(){}:_props$performInterac3,rest=_objectWithoutPropertiesLoose(props,_excluded4);// Memoize filtered props to avoid re-filtering on every render
|
|
8
|
+
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState3=useState(initialData),allData=_useState3[0],setAllData=_useState3[1];var headerContent=allData.headerContent,headerDescription=allData.headerDescription,bodyContent=allData.bodyContent,footerContent=allData.footerContent,footerClass=allData.footerClass,footerIcon=allData.footerIcon,contentMetadata=allData.contentMetadata,contentMetadataClass=allData.contentMetadataClass,dataClassName=allData.className,dataError=allData.error,dataIsMissing=allData.isMissing;function toSafeText(value){if(value===null||value===undefined){return""}return typeof value==="string"?value:JSON.stringify(value)}var safeHeaderContent=toSafeText(headerContent);var safeHeaderDescription=toSafeText(headerDescription);var safeBodyContent=toSafeText(bodyContent);var safeFooterContent=toSafeText(footerContent);var safeContentMetadata=toSafeText(contentMetadata);var _useState4=useState((safeFooterContent==null?void 0:safeFooterContent.length)>0),footerHasContent=_useState4[0],setFooterHasContent=_useState4[1];var _useState5=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState5[0],setAttributes=_useState5[1];var isEditable=(_attributes$isEditabl=attributes.isEditable)!=null?_attributes$isEditabl:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);useEffect(function(){setFooterHasContent((safeFooterContent==null?void 0:safeFooterContent.length)>0)},[safeFooterContent]);var defaultClasses="bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none";var defaultFooterClasses=footerHasContent?"text-sm bg-pink-50 text-pink-900 shadow-sm":"text-sm";var defaultContentMetadataClasses="text-xs";var mergedCardClassName=dataClassName?cn(defaultClasses,dataClassName):defaultClasses;var mergedFooterClassName=footerClass?cn(defaultFooterClasses,footerClass):defaultFooterClasses;var mergedContentMetadataClassName=contentMetadataClass?cn(defaultContentMetadataClasses,contentMetadataClass):defaultContentMetadataClasses;var hasError=Boolean((_attributes$error=attributes==null?void 0:attributes.error)!=null?_attributes$error:dataError);var hasMissing=Boolean((_attributes$isMissing=attributes==null?void 0:attributes.isMissing)!=null?_attributes$isMissing:dataIsMissing);var isLoading=Boolean(((attributes==null?void 0:attributes.interactionApiInProgress)||(attributes==null?void 0:attributes.loading))&&!hasError&&!hasMissing);var footerIconText=typeof footerIcon==="string"?footerIcon:footerIcon&&typeof footerIcon==="object"&&"icon"in footerIcon?String(footerIcon.icon):"";function getCardContent(){if(isLoading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}var showEmpty=hasError||hasMissing||!safeBodyContent;function handleFooterInput(event){var target=event.target;var content=target.textContent||"";var hasContent=content.trim().length>0;setFooterHasContent(hasContent);if(!hasContent){var currentProps=gjsModel.get("componentProps");gjsModel.set("componentProps",_extends({},currentProps,{footerContent:null,footerIcon:null,footerClass:null,isEmptied:true}))}}return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"headerContent",contentEditable:isEditable,className:"text-lg",children:safeHeaderContent}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"headerDescription",contentEditable:isEditable,className:"text-sm",children:safeHeaderDescription})]})})}),showEmpty?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsxs(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-grow",children:[/*#__PURE__*/_jsx("div",{className:"text-3xl font-semibold truncate",children:safeBodyContent}),safeContentMetadata&&/*#__PURE__*/_jsx("div",{className:mergedContentMetadataClassName,style:{color:"#2A44D4"},children:safeContentMetadata})]}),/*#__PURE__*/_jsxs(CardFooter,{"data-slot":"footerContent",contentEditable:isEditable,className:mergedFooterClassName,onInput:handleFooterInput,children:[(footerIconText||"").trim()?/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIconText}):null,safeFooterContent||""]})]})}return/*#__PURE__*/_jsxs(Card,_extends({},rest,{isEditable:false,className:mergedCardClassName+" relative",children:[getCardContent(),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}function transformDataForScatter(data,xAxis,yAxis,dataKeys){if(!data||data.length===0){return[]}var scatterData=data.filter(function(item){return item[xAxis]!==null&&item[xAxis]!==undefined&&item[yAxis]!==null&&item[yAxis]!==undefined}).map(function(item){var _result;var result=(_result={},_result[xAxis]=Number(item[xAxis]),_result[yAxis]=Number(item[yAxis]),_result);if(dataKeys&&dataKeys.length>0){dataKeys.forEach(function(_ref){var key=_ref.key;if(item[key]!==null&&item[key]!==undefined){result[key]=Number(item[key])}})}return result});return scatterData}function binDataForHistogram(data,valueKey,bins){if(bins===void 0){bins=10}if(!data||data.length===0){return[]}var values=data.map(function(item){return Number(item[valueKey])}).filter(function(val){return!isNaN(val)});if(values.length===0){return[]}var min=Math.min.apply(Math,values);var max=Math.max.apply(Math,values);var binWidth=(max-min)/bins;var binsArray=new Array(bins).fill(0);var binLabels=[];for(var i=0;i<bins;i++){var binStart=min+i*binWidth;var binEnd=binStart+binWidth;binLabels.push(binStart.toFixed(1)+"-"+binEnd.toFixed(1))}values.forEach(function(value){var binIndex=Math.floor((value-min)/binWidth);if(binIndex>=bins){binIndex=bins-1}if(binIndex<0){binIndex=0}binsArray[binIndex]+=1});return binLabels.map(function(label,index){return{bin:label,frequency:binsArray[index]}})}function transformDataForBeeswarm(data,groupBy,valueKey){if(!data||data.length===0){return{nodes:[],groups:[]}}var grouped={};data.forEach(function(item){if(item[groupBy]!==null&&item[groupBy]!==undefined&&item[valueKey]!==null&&item[valueKey]!==undefined){var group=String(item[groupBy]);var value=Number(item[valueKey]);if(!isNaN(value)){if(!grouped[group]){grouped[group]=[]}grouped[group].push(value)}}});var groups=Object.keys(grouped).sort();var nodes=[];groups.forEach(function(group,groupIndex){var values=grouped[group];values.forEach(function(value){nodes.push({group:group,groupIndex:groupIndex,value:value,x:groupIndex,y:value,radius:4})})});return{nodes:nodes,groups:groups}}function BeeswarmChart(_ref2){var data=_ref2.data,groups=_ref2.groups,color=_ref2.color,groupBy=_ref2.groupBy,valueKey=_ref2.valueKey;var containerRef=useRef(null);var svgRef=useRef(null);var _useState6=useState({width:800,height:250}),dimensions=_useState6[0],setDimensions=_useState6[1];var _useState7=useState([]),simulatedNodes=_useState7[0],setSimulatedNodes=_useState7[1];var _useTooltip=useTooltip(),tooltipData=_useTooltip.tooltipData,tooltipLeft=_useTooltip.tooltipLeft,tooltipTop=_useTooltip.tooltipTop,tooltipOpen=_useTooltip.tooltipOpen,showTooltip=_useTooltip.showTooltip,hideTooltip=_useTooltip.hideTooltip;useEffect(function(){var updateDimensions=function updateDimensions(){if(containerRef.current){setDimensions({width:containerRef.current.offsetWidth||800,height:250})}};updateDimensions();var resizeObserver=new ResizeObserver(function(entries){for(var _iterator2=_createForOfIteratorHelperLoose(entries),_step2;!(_step2=_iterator2()).done;){var entry=_step2.value;setDimensions({width:entry.contentRect.width||800,height:250})}});if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateDimensions);return function(){resizeObserver.disconnect();window.removeEventListener("resize",updateDimensions)}},[]);var createXScale=useCallback(function(innerWidth,groupDomain){var minBandwidth=60;var totalMinWidth=groupDomain.length*minBandwidth;var paddingRatio=0.3;var xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});if(totalMinWidth>innerWidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}else{xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});var currentBandwidth=xScale.bandwidth();if(currentBandwidth<minBandwidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}}return xScale},[]);var scales=useMemo(function(){if(data.length===0||dimensions.width===0){return null}var margin={top:20,right:20,bottom:60,left:60};var innerWidth=dimensions.width-margin.left-margin.right;var innerHeight=dimensions.height-margin.top-margin.bottom;var values=data.map(function(d){return d.value});var minValue=Math.min.apply(Math,values);var maxValue=Math.max.apply(Math,values);var xScale=createXScale(innerWidth,groups);var yScale=scaleLinear({domain:[minValue,maxValue],range:[innerHeight,0]});return{xScale:xScale,yScale:yScale,minValue:minValue,maxValue:maxValue,innerWidth:innerWidth,innerHeight:innerHeight}},[data,groups,dimensions,createXScale]);useEffect(function(){if(!scales){return}var xScale=scales.xScale,yScale=scales.yScale,minValue=scales.minValue,maxValue=scales.maxValue,innerWidth=scales.innerWidth,innerHeight=scales.innerHeight;var valueRange=maxValue-minValue;var padding=valueRange*0.1;var yScaleWithPadding=scaleLinear({domain:[minValue-padding,maxValue+padding],range:[innerHeight,0]});// Use the actual chart width from xScale range, not just innerWidth
|
|
9
|
+
var actualChartWidth=Math.max(innerWidth,xScale.range()[1]||0);var bounds={minY:BEESWARM_CONFIG.RADIUS,maxY:innerHeight-BEESWARM_CONFIG.RADIUS,minX:0,maxX:actualChartWidth};var nodes=data.map(function(d){var initialY=yScaleWithPadding(d.value);var clampedY=Math.max(bounds.minY,Math.min(bounds.maxY,initialY));var groupCenterX=(xScale(d.group)||0)+(xScale.bandwidth()||0)/2;var bandwidth=xScale.bandwidth()||0;var maxSpread=bandwidth*BEESWARM_CONFIG.SPREAD_FACTOR;var randomOffset=(Math.random()-0.5)*maxSpread*BEESWARM_CONFIG.RANDOM_FACTOR;return _extends({},d,{groupCenterX:groupCenterX,x:groupCenterX+randomOffset,y:clampedY,radius:BEESWARM_CONFIG.RADIUS,maxSpread:maxSpread})});var simulation=null;try{simulation=forceSimulation(nodes).force("x",forceX(function(d){return d.groupCenterX}).strength(0.15)).force("y",forceY(function(d){var targetY=yScaleWithPadding(d.value);return Math.max(bounds.minY,Math.min(bounds.maxY,targetY))}).strength(1)).force("collide",forceCollide().radius(function(d){return d.radius+BEESWARM_CONFIG.COLLISION_PADDING}).strength(0.9).iterations(3));if(simulation&&typeof simulation.stop==="function"){simulation.stop()}}catch(error){setSimulatedNodes([].concat(nodes));return}var constrainNode=function constrainNode(node,isFinal){if(isFinal===void 0){isFinal=false}var correctY=yScaleWithPadding(node.value);node.y=Math.max(bounds.minY,Math.min(bounds.maxY,correctY));node.vy=0;var nodeMinX=node.groupCenterX-node.maxSpread;var nodeMaxX=node.groupCenterX+node.maxSpread;var constrainedMinX=Math.max(bounds.minX,nodeMinX);var constrainedMaxX=Math.min(bounds.maxX,nodeMaxX);if(isFinal){if(node.x<constrainedMinX){node.x=constrainedMinX}else if(node.x>constrainedMaxX){node.x=constrainedMaxX}}else{var overflowMargin=node.maxSpread*0.1;if(node.x<constrainedMinX-overflowMargin){node.x=constrainedMinX-overflowMargin;node.vx*=0.7}else if(node.x>constrainedMaxX+overflowMargin){node.x=constrainedMaxX+overflowMargin;node.vx*=0.7}}};if(simulation&&typeof simulation.tick==="function"){for(var i=0;i<BEESWARM_CONFIG.SIMULATION_ITERATIONS;i++){try{simulation.tick();nodes.forEach(function(node){return constrainNode(node,false)})}catch(error){break}}}// Final constraint pass
|
|
10
|
+
nodes.forEach(function(node){constrainNode(node,true);node.vx=0});setSimulatedNodes([].concat(nodes))},[scales,data]);if(simulatedNodes.length===0||dimensions.width===0||!scales){return/*#__PURE__*/_jsx("div",{ref:containerRef,style:{width:"100%",height:"250px"}})}var margin={top:20,right:20,bottom:60,left:60};var xScale=scales.xScale,yScale=scales.yScale,innerWidth=scales.innerWidth,innerHeight=scales.innerHeight;var handleMouseOver=function handleMouseOver(event,node){if(containerRef.current){var containerRect=containerRef.current.getBoundingClientRect();var x=event.clientX-containerRect.left+10;var y=event.clientY-containerRect.top-10;showTooltip({tooltipLeft:x,tooltipTop:y,tooltipData:node})}};var actualChartWidth=Math.max(innerWidth,xScale.range()[1]||0);var actualSvgWidth=actualChartWidth+margin.left+margin.right;return/*#__PURE__*/_jsxs("div",{ref:containerRef,style:{width:"100%",height:"250px",position:"relative"},children:[/*#__PURE__*/_jsx("svg",{ref:svgRef,width:Math.max(dimensions.width,actualSvgWidth),height:dimensions.height,onMouseLeave:hideTooltip,children:/*#__PURE__*/_jsxs(Group,{left:margin.left,top:margin.top,children:[/*#__PURE__*/_jsx(GridRows,{scale:yScale,width:actualChartWidth,strokeDasharray:"3,3",stroke:"#e0e0e0",strokeOpacity:0.5}),/*#__PURE__*/_jsx(AxisLeft,{scale:yScale,tickStroke:"#666",stroke:"#666",tickLabelProps:function tickLabelProps(){return{fill:"#666",fontSize:12,textAnchor:"end",dy:"0.33em"}}}),/*#__PURE__*/_jsx(AxisBottom,{top:innerHeight,scale:xScale,tickStroke:"#666",stroke:"#666",tickLabelProps:function tickLabelProps(){return{fill:"#666",fontSize:12,textAnchor:"middle"}}}),simulatedNodes.map(function(node,i){return/*#__PURE__*/_jsx(Circle,{cx:node.x||0,cy:node.y||0,r:node.radius,fill:color,opacity:0.8,stroke:color,strokeWidth:1,onMouseOver:function onMouseOver(e){return handleMouseOver(e,node)},style:{cursor:"pointer"}},i)})]})}),tooltipOpen&&tooltipData&&tooltipLeft!==null&&tooltipLeft!==undefined&&tooltipTop!==null&&tooltipTop!==undefined&&/*#__PURE__*/_jsx(TooltipWithBounds,{left:tooltipLeft,top:tooltipTop,style:_extends({},defaultStyles,{backgroundColor:"white",border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px 12px",boxShadow:"0 2px 8px rgba(0,0,0,0.15)",fontSize:"12px",position:"absolute",zIndex:1000,pointerEvents:"none"}),children:/*#__PURE__*/_jsxs("div",{children:[/*#__PURE__*/_jsxs("div",{style:{marginBottom:"4px",fontWeight:600},children:[groupBy,": ",tooltipData.group]}),/*#__PURE__*/_jsxs("div",{children:[valueKey,": ",tooltipData.value.toLocaleString()]})]})})]})}function renderChartComponent(chartType,data,config){var safeData=Array.isArray(data)?data:[];if(safeData.length===0){return renderNoDataFallback()}switch(chartType){case"pie":return/*#__PURE__*/_jsxs(PieChart,{children:[safeData.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true})}),/*#__PURE__*/_jsx(Pie,{data:safeData,dataKey:config.dataKey,nameKey:config.nameKey,innerRadius:60,strokeWidth:10,label:safeData.length<20?function(_ref3){var name=_ref3.name,percent=_ref3.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]});case"bar":{config.dataKeys=config.dataKeys||[];var barDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];return/*#__PURE__*/_jsxs(BarChart,_extends({data:safeData},config.chartUi,barDataKeys.length>1&&{barGap:0},{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:config.xAxis}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(Legend,{align:"left",wrapperStyle:{marginLeft:20}}),barDataKeys.map(function(_ref4){var key=_ref4.key,name=_ref4.name,color=_ref4.color;return/*#__PURE__*/_jsx(Bar,{dataKey:key,fill:color!=null?color:"#4caf50",name:name,radius:2},key)}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})})]}))}case"line":{config.dataKeys=config.dataKeys||[];var safeDataKeysLine=Array.isArray(config.dataKeys)?config.dataKeys:[];return/*#__PURE__*/_jsxs(LineChart,_extends({data:safeData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:config.xAxis}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})}),safeDataKeysLine.map(function(_ref5){var key=_ref5.key,name=_ref5.name,color=_ref5.color;return/*#__PURE__*/_jsx(Line,{type:"monotone",dataKey:key,stroke:color!=null?color:"#4caf50",name:name},key)}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"scatter":{config.dataKeys=config.dataKeys||[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];var scatterData=transformDataForScatter(safeData,config.xAxis,config.yAxis,safeDataKeys);if(scatterData.length===0){return renderNoDataFallback()}var colors=safeDataKeys.length>0?safeDataKeys.map(function(_ref6){var color=_ref6.color;return color!=null?color:"#2A44D4"}):["#2A44D4"];return/*#__PURE__*/_jsxs(ScatterChart,_extends({data:scatterData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{type:"number",dataKey:config.xAxis,name:config.xAxis||"X Axis",domain:["auto","auto"]}),/*#__PURE__*/_jsx(YAxis,{type:"number",dataKey:config.yAxis,name:config.yAxis||"Y Axis",domain:["auto","auto"]}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:{strokeDasharray:"3 3"},content:/*#__PURE__*/_jsx(ChartTooltipContent,{})}),safeDataKeys.length>0?safeDataKeys.map(function(_ref7,index){var key=_ref7.key,name=_ref7.name,color=_ref7.color;return/*#__PURE__*/_jsx(Scatter,{name:name||key,dataKey:key||config.yAxis,fill:color!=null?color:colors[index%colors.length]},key)}):/*#__PURE__*/_jsx(Scatter,{name:"Data",dataKey:config.yAxis,fill:colors[0]}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"histogram":{config.dataKeys=config.dataKeys||[];var _safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];var valueKey=_safeDataKeys.length>0?_safeDataKeys[0].key:config.xAxis;var bins=config.bins||10;var binnedData=binDataForHistogram(safeData,valueKey,bins);if(binnedData.length===0){return renderNoDataFallback()}var color=_safeDataKeys.length>0?_safeDataKeys[0].color:"#2A44D4";return/*#__PURE__*/_jsxs(BarChart,_extends({data:binnedData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:"bin",angle:-45,textAnchor:"end",height:80}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})}),/*#__PURE__*/_jsx(Bar,{dataKey:"frequency",fill:color,radius:2,children:binnedData.map(function(entry,index){return/*#__PURE__*/_jsx(Cell,{fill:color},"cell-"+index)})}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"beeswarm":{var _config$dataKeys$,_config$dataKeys$2;var groupBy=config.groupBy||config.xAxis;var _valueKey=config.valueKey||config.dataKeys&&((_config$dataKeys$=config.dataKeys[0])==null?void 0:_config$dataKeys$.key)||"value";var _transformDataForBees=transformDataForBeeswarm(safeData,groupBy,_valueKey),nodes=_transformDataForBees.nodes,groups=_transformDataForBees.groups;if(nodes.length===0||groups.length===0){return renderNoDataFallback()}var _color=config.dataKeys&&(_config$dataKeys$2=config.dataKeys[0])!=null&&_config$dataKeys$2.color?config.dataKeys[0].color:"#2A44D4";return/*#__PURE__*/_jsx(BeeswarmChart,{data:nodes,groups:groups,color:_color,groupBy:groupBy,valueKey:_valueKey})}default:return/*#__PURE__*/_jsxs(PieChart,{children:[safeData.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true})}),/*#__PURE__*/_jsx(Pie,{data:safeData,dataKey:config.dataKey,nameKey:config.nameKey,innerRadius:60,strokeWidth:10,label:safeData.length<20?function(_ref8){var name=_ref8.name,percent=_ref8.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]})}}export function renderChart(props){var _attributes$isEditabl2;var gjsModel=props.gjsModel,_props$performInterac2=props.performInteraction,performInteraction=_props$performInterac2===void 0?function(){return Promise.resolve({})}:_props$performInterac2,rest=_objectWithoutPropertiesLoose(props,_excluded3);// Memoize filtered props to avoid re-filtering on every render
|
|
11
|
+
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState8=useState(initialData),allData=_useState8[0],setAllData=_useState8[1];var _useState9=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState9[0],setAttributes=_useState9[1];var isEditable=(_attributes$isEditabl2=attributes.isEditable)!=null?_attributes$isEditabl2:false;var containerRef=useRef(null);var _useState10=useState(0),containerWidth=_useState10[0],setContainerWidth=_useState10[1];useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){var newAttributes=gjsModel.get("attributes");setAttributes(_extends({},newAttributes))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);useEffect(function(){var updateContainerWidth=function updateContainerWidth(){if(containerRef.current){setContainerWidth(containerRef.current.offsetWidth||0)}};var resizeObserver=new ResizeObserver(function(entries){for(var _iterator3=_createForOfIteratorHelperLoose(entries),_step3;!(_step3=_iterator3()).done;){var entry=_step3.value;setContainerWidth(entry.contentRect.width||0)}});updateContainerWidth();var timeoutId=setTimeout(updateContainerWidth,50);if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateContainerWidth);return function(){clearTimeout(timeoutId);resizeObserver.disconnect();window.removeEventListener("resize",updateContainerWidth)}},[]);var _allData$config=allData.config,config=_allData$config===void 0?{}:_allData$config,_allData$chartType=allData.chartType,chartType=_allData$chartType===void 0?"pie":_allData$chartType,_allData$chartData=allData.chartData,chartData=_allData$chartData===void 0?[]:_allData$chartData,className=allData.className,_allData$title=allData.title,title=_allData$title===void 0?"Title":_allData$title,_allData$subTitle=allData.subTitle,subTitle=_allData$subTitle===void 0?"Subtitle":_allData$subTitle;var defaultClasses="aspect-auto h-[250px] w-full min-w-[200px] min-h-[200px]";var mergedClasses=className?cn(defaultClasses,className):defaultClasses;if(chartType==="pie"){var safeChartData=Array.isArray(chartData)?chartData:[];var colors=getNColors(safeChartData.length);safeChartData.forEach(function(data,i){if(!data.fill){data.fill=colors[i]}})}else if(!config.color){var safeBaseColors=Array.isArray(baseColors)?baseColors:[];if(safeBaseColors.length>0){config.color=safeBaseColors[Math.floor(Math.random()*safeBaseColors.length)]}}var totalDataPoints=0;if(chartType==="bar"||chartType==="line"||chartType==="scatter"||chartType==="histogram"||chartType==="beeswarm"){var _safeChartData=Array.isArray(chartData)?chartData:[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];if(chartType==="bar"){totalDataPoints=_safeChartData.length*Math.max(1,safeDataKeys.length)}else{totalDataPoints=_safeChartData.length}}var getScrollableWidth=function getScrollableWidth(){if(chartType==="line"){return totalDataPoints*20}if(chartType==="bar"){return totalDataPoints*20+(Array.isArray(config.dataKeys)?config.dataKeys.length:0)*8*(Array.isArray(chartData)?chartData.length:0)+(Array.isArray(chartData)?chartData.length:0)*15}return 800};var scrollWidth=getScrollableWidth();var shouldScroll=(chartType==="bar"||chartType==="line"||chartType==="beeswarm"||chartType==="histogram"||chartType==="scatter")&&totalDataPoints>15&&scrollWidth>containerWidth;var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=(attributes.interactionApiInProgress||attributes.loading)&&!hasError&&!hasMissing;var ChartWrapper=function ChartWrapper(_ref9){var children=_ref9.children;if(shouldScroll){return/*#__PURE__*/_jsx("div",{className:"w-full h-[250px] overflow-x-auto",children:/*#__PURE__*/_jsx("div",{style:{minWidth:scrollWidth+"px",height:"250px"},children:children})})}return/*#__PURE__*/_jsx("div",{className:"w-full h-[250px]",children:children})};var chartUi=isLoading?/*#__PURE__*/_jsx(ChartLoader,{}):hasError||hasMissing||!chartData?renderNoDataFallback():/*#__PURE__*/_jsx(ChartWrapper,{children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:config,className:mergedClasses,children:renderChartComponent(chartType,chartData,config)}))});return/*#__PURE__*/_jsxs(Card,{className:"shadow border mt-2 mb-2 relative",children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{ref:containerRef,"data-slot":"bodyContent",className:"px-6",style:{minHeight:"250px"},children:chartUi}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]})}export function renderTable(props){var _attributes$isEditabl3;var gjsModel=props.gjsModel,_props$performInterac3=props.performInteraction,performInteraction=_props$performInterac3===void 0?function(){}:_props$performInterac3,rest=_objectWithoutPropertiesLoose(props,_excluded4);// Memoize filtered props to avoid re-filtering on every render
|
|
13
12
|
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState11=useState(initialData),allData=_useState11[0],setAllData=_useState11[1];var cardRef=useRef(null);var _useState12=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState12[0],setAttributes=_useState12[1];var isEditable=(_attributes$isEditabl3=attributes.isEditable)!=null?_attributes$isEditabl3:false;var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$title2=allData.title,title=_allData$title2===void 0?"Title":_allData$title2,_allData$subTitle2=allData.subTitle,subTitle=_allData$subTitle2===void 0?"Subtitle":_allData$subTitle2,_allData$actions=allData.actions,actions=_allData$actions===void 0?[]:_allData$actions,pagination=allData.pagination;var data=Array.isArray(rawData)?rawData:[];var headerMapper=function(){var cleaned=_extends({},rawHeaderMapper);if("id"in cleaned){delete cleaned.id}if(data.length>0){var dataKeys=Object.keys(data[0]||{});return Object.fromEntries(Object.entries(cleaned).filter(function(_ref10){var key=_ref10[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref12){var _ref11=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref11.sortColumn,sortDirection=_ref11.sortDirection;return sortColumn&&sortDirection?(_ref12={},_ref12[sortColumn]=sortDirection,_ref12):{}}();var _useState13=useState(0),viewportWidth=_useState13[0],setViewportWidth=_useState13[1];var _useState14=useState(250),scrollAreaHeight=_useState14[0],setScrollAreaHeight=_useState14[1];var calculateTableHeight=function calculateTableHeight(tableWidth,rowCount){if(viewportWidth>0){var _gjsModel$collection;var widthRatio=tableWidth/viewportWidth;var baseTableHeight=250;var targetScrollAreaHeight=baseTableHeight;if(widthRatio>=0.8){var headerHeight=48;var rowHeight=40;var calculatedHeight=headerHeight+rowCount*rowHeight;targetScrollAreaHeight=Math.min(calculatedHeight,baseTableHeight)}var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection=gjsModel.collection)==null?void 0:_gjsModel$collection.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(tableElement){var headerElement=tableElement.querySelector("[data-slot=\"card-header\"]");if(headerElement&&headerElement.offsetHeight>0){var actualHeaderHeight=headerElement.offsetHeight;var standardHeaderHeight=58;var heightDifference=actualHeaderHeight-standardHeaderHeight;if(heightDifference>0){targetScrollAreaHeight=targetScrollAreaHeight-heightDifference}}}setScrollAreaHeight(targetScrollAreaHeight)}};useEffect(function(){var updateViewportWidth=function updateViewportWidth(){var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;var iframeDocument=iframeWindow==null?void 0:iframeWindow.document;if(iframeDocument){var dashboardRoot=iframeDocument.getElementById("dashboard-root");var effectiveViewportWidth=(dashboardRoot==null?void 0:dashboardRoot.clientWidth)||iframeDocument.documentElement.clientWidth;setViewportWidth(effectiveViewportWidth)}};updateViewportWidth();window.addEventListener("resize",updateViewportWidth);var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;if(iframeWindow){iframeWindow.addEventListener("resize",updateViewportWidth)}return function(){window.removeEventListener("resize",updateViewportWidth);if(iframeWindow){iframeWindow.removeEventListener("resize",updateViewportWidth)}}},[]);useEffect(function(){var updateTableWidthAndApplyCSS=function updateTableWidthAndApplyCSS(){var _gjsModel$collection2;var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection2=gjsModel.collection)==null?void 0:_gjsModel$collection2.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(!tableElement&&window.parent!==window){tableElement=window.parent.document.querySelector("[data-table-id=\""+tableId+"\"]")}if(!tableElement){return}var tableActualWidth=tableElement.getBoundingClientRect().width;if(tableActualWidth>0){calculateTableHeight(tableActualWidth,Array.isArray(data)?data.length:0)}};var timeoutId=setTimeout(updateTableWidthAndApplyCSS,150);window.addEventListener("resize",updateTableWidthAndApplyCSS);return function(){clearTimeout(timeoutId);window.removeEventListener("resize",updateTableWidthAndApplyCSS)}},[allData,gjsModel,viewportWidth,data,calculateTableHeight]);useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var parsedData=function(){if(typeof data==="object"&&data!==null&&!Array.isArray(data)&&data.name==="__peak_placeholder"){return[]}if(!Array.isArray(data)){return[]}return data.map(function(datum){var newData=_extends({},datum);delete newData.id;return newData})}();function onRowAction(_x,_x2){return _onRowAction.apply(this,arguments)}function _onRowAction(){_onRowAction=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(rowIndex,actionId){var id;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:id=gjsModel.get("id");_context.next=3;return performInteraction({id:actionId,interactionType:"tableButton",payload:{row:data[rowIndex],tableId:id},affectedComponents:[]});case 3:case"end":return _context.stop()}},_callee)}));return _onRowAction.apply(this,arguments)}function onPageChange(_x3,_x4){return _onPageChange.apply(this,arguments)}function _onPageChange(){_onPageChange=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(pageNumber,pageSize){var _gjsModel$get2;var id,_ref13,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:id=gjsModel.get("id");_ref13=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref13.sortColumn,sortDirection=_ref13.sortDirection;_context2.next=4;return performInteraction({id:id,interactionType:"pagination",payload:_extends({pageNumber:pageNumber,pageSize:pageSize},sortColumn&&sortDirection&&{sortColumn:sortColumn,sortDirection:sortDirection}),affectedComponents:getAffectedComponentsWithLoader([id],true)});case 4:case"end":return _context2.stop()}},_callee2)}));return _onPageChange.apply(this,arguments)}function handleSort(_x5,_x6){return _handleSort.apply(this,arguments)}function _handleSort(){_handleSort=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(column,direction){var currentProps,id;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:currentProps=gjsModel.get("componentProps");id=gjsModel.get("id");gjsModel.set("componentProps",_extends({},currentProps,{sortColumn:direction?column:null,sortDirection:direction}));_context3.next=5;return performInteraction({id:id,interactionType:"tableSort",payload:{sortColumn:direction?column:null,sortDirection:direction,tableId:id},affectedComponents:getAffectedComponentsWithLoader([id],true)});case 5:case"end":return _context3.stop()}},_callee3)}));return _handleSort.apply(this,arguments)}return/*#__PURE__*/_jsxs(Card,{ref:cardRef,className:"shadow border relative flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-1 flex flex-col overflow-hidden",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing?renderNoDataFallback():/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:attributes.interactionApiInProgress||attributes.loading,onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,otherProps:rest,height:scrollAreaHeight})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",tableActions:actions,firstRowData:Array.isArray(data)&&data.length>0?data[0]:{},isVisible:isEditable,componentProps:allData})]})}export function renderTab(props){var tabsWidth=157;var safeTabs=Array.isArray(props.tabs)?props.tabs:[];var showFallback=safeTabs.length===0;if(safeTabs.length>4){tabsWidth=157}var defaultValue=props.defaultValue||(safeTabs.length>0?safeTabs[0]:undefined);return/*#__PURE__*/_jsxs(Tabs,{defaultValue:defaultValue,children:[/*#__PURE__*/_jsx("div",{className:"text-center mb-4",children:/*#__PURE__*/_jsx(TabsList,{className:"bg-[#F9F9FE] border border-[#D4D5DE] p-1 rounded-lg h-auto",children:safeTabs.length>0?safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsTrigger,{value:tab,className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},children:tab},tab)}):/*#__PURE__*/_jsx(TabsTrigger,{value:"no-data",className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},disabled:true,children:"No tabs"})})}),showFallback?/*#__PURE__*/_jsx(TabsContent,{value:defaultValue||"no-data",className:"tabs-content","data-fallback":"true",children:renderNoDataFallback()}):safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsContent,{value:tab,className:"tabs-content"},tab)})]})}export function renderMarkdown(props){var _attributes$isEditabl4;var gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded5);// Memoize filtered props to avoid re-filtering on every render
|
|
14
13
|
var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState15=useState(initialData),allData=_useState15[0],setAllData=_useState15[1];var _useState16=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState16[0],setAttributes=_useState16[1];var isEditable=(_attributes$isEditabl4=attributes.isEditable)!=null?_attributes$isEditabl4:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var _useState17=useState(false),isEditing=_useState17[0],setIsEditing=_useState17[1];var _useState18=useState(false),isEditingHeading=_useState18[0],setIsEditingHeading=_useState18[1];var editRef=useRef(null);var headingEditRef=useRef(null);var startEditing=function startEditing(){setIsEditing(true);setTimeout(function(){setupEditor()},0)};var startEditingHeading=function startEditingHeading(){setIsEditingHeading(true);setTimeout(function(){setupHeadingEditor()},0)};var setupEditor=function setupEditor(){if(!editRef.current){return}var editor=editRef.current;editor.innerHTML="";editor.textContent=allData.summaryText;editor.focus()};var setupHeadingEditor=function setupHeadingEditor(){if(!headingEditRef.current){return}var editor=headingEditRef.current;editor.innerHTML="";editor.textContent=allData.summaryHeading||"Insights";editor.focus()};// Save changes and exit editing mode
|
|
15
14
|
var saveChanges=function saveChanges(){if(!editRef.current){return}var content=editRef.current.innerText||"";setAllData(function(prev){return _extends({},prev,{summaryText:content})});setIsEditing(false);editRef.current.innerHTML=""};var saveHeadingChanges=function saveHeadingChanges(){if(!headingEditRef.current){return}var content=headingEditRef.current.innerText||"Insights";setAllData(function(prev){return _extends({},prev,{summaryHeading:content})});setIsEditingHeading(false);headingEditRef.current.innerHTML=""};var markdownStyles={ul:{props:{className:"list-disc"}},h1:{props:{className:"text-4xl font-bold leading-[4rem]"}},h2:{props:{className:"text-3xl font-bold leading-[3rem]"}},h3:{props:{className:"text-2xl font-bold leading-[2rem]"}},h4:{props:{className:"text-xl font-bold leading-[2.5rem]"}},h5:{props:{className:"text-lg font-bold leading-[2.5rem]"}},h6:{props:{className:"text-base font-bold leading-[2rem]"}}};var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=attributes.loading&&!hasError&&!hasMissing||attributes.interactionApiInProgress;if(isLoading){return/*#__PURE__*/_jsx(MarkdownLoader,{})}if(hasError||hasMissing){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:allData.summaryHeading||"Insights"}),/*#__PURE__*/_jsxs("div",{className:"w-full py-8 flex flex-col items-center justify-center px-6 text-center",style:{minHeight:"180px"},children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-12 h-12 text-gray-400 mb-2"}),/*#__PURE__*/_jsx("h3",{className:"text-lg font-medium text-gray-900",children:"No data available"}),/*#__PURE__*/_jsx("p",{className:"mt-2 text-sm text-gray-500 max-w-md",children:"Check your filters or try a different time range."})]}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}if(!isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:allData.summaryHeading||"Insights"}),/*#__PURE__*/_jsx("div",{"data-slot":"summaryText",children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:allData.summaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em] relative"},rest,{children:[isEditingHeading?/*#__PURE__*/_jsx("div",{ref:headingEditRef,contentEditable:true,onBlur:saveHeadingChanges,"data-slot":"summaryHeading",className:"text-xl font-semibold text-left",suppressContentEditableWarning:true}):/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",onClick:startEditingHeading,"data-slot":"summaryHeading",children:allData.summaryHeading||"Insights"}),isEditing?/*#__PURE__*/_jsx("div",{ref:editRef,contentEditable:true,onBlur:saveChanges,"data-slot":"summaryText",className:"p-2 min-h-[100px] whitespace-pre-wrap",suppressContentEditableWarning:true,style:{whiteSpace:"pre-wrap",wordWrap:"break-word"}}):/*#__PURE__*/_jsx("div",{onClick:startEditing,"data-slot":"summaryText",style:{whiteSpace:"pre-wrap",wordWrap:"break-word"},children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:allData.summaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}export function renderButton(props){var _attributes$isEditabl5;var gjsModel=props.gjsModel,_props$performInterac4=props.performInteraction,performInteraction=_props$performInterac4===void 0?function(){}:_props$performInterac4;var _useState19=useState(_extends({},props)),allData=_useState19[0],setAllData=_useState19[1];var _useState20=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState20[0],setAttributes=_useState20[1];var isEditable=(_attributes$isEditabl5=attributes.isEditable)!=null?_attributes$isEditabl5:false;useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(_extends({},gjsModel.get("componentProps")))})},[]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var text=allData.text,className=allData.className,payload=allData.payload,_allData$variant=allData.variant,variant=_allData$variant===void 0?"default":_allData$variant,_allData$size=allData.size,size=_allData$size===void 0?"sm":_allData$size,affectedComponents=allData.affectedComponents,tooltipContent=allData.tooltipContent;function interact(){var id=gjsModel.get("id");performInteraction({id:id,interactionType:"button",affectedComponents:getAffectedComponentsWithLoader([id].concat(affectedComponents),true),payload:payload})}return/*#__PURE__*/_jsx(TooltipButton,{className:className,isEditable:isEditable,interact:interact,attributes:attributes,variant:variant,size:size,text:text,tooltipContent:tooltipContent})}var renderActionCardWithWrapper=function renderActionCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"ActionCard"}),children:renderActionCard(props)})};var renderButtonWithWrapper=function renderButtonWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Button"}),children:renderButton(props)})};var renderCardWithWrapper=function renderCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Card"}),children:renderCard(props)})};var renderChartWithWrapper=function renderChartWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Chart"}),children:renderChart(props)})};var renderFilterWithWrapper=function renderFilterWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Filter"}),children:renderFilter(props)})};var renderMarkdownWithWrapper=function renderMarkdownWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Markdown"}),children:renderMarkdown(props)})};var renderSearchWithWrapper=function renderSearchWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Search"}),children:renderSearch(props)})};var renderTableWithWrapper=function renderTableWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Table"}),children:renderTable(props)})};var renderTabWithWrapper=function renderTabWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Tabs"}),children:renderTab(props)})};function renderActions(props){var actions=props.actions,_props$isEditable=props.isEditable,isEditable=_props$isEditable===void 0?false:_props$isEditable,gjsModel=props.gjsModel;if(actions===null){return/*#__PURE__*/_jsx("div",{})}if(!Array.isArray(actions)||actions.length===0){return/*#__PURE__*/_jsx("div",{className:"bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none relative",children:/*#__PURE__*/_jsx(CardLoader,{})})}return/*#__PURE__*/_jsx("div",{className:"dashboard-cards flex flex-wrap gap-4",children:actions.map(function(action,index){var icon=action.icon,title=action.title,description=action.description;return/*#__PURE__*/_jsx("div",{className:"flex-1 min-w-[200px]",children:renderActionCard({icon:icon,headerContent:title,bodyContent:description,isEditable:isEditable,gjsModel:gjsModel})},index)})})}var renderActionsWithWrapper=function renderActionsWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Actions"}),children:renderActions(props)})};export function getRenderers(){return{ActionCard:renderActionCardWithWrapper,Actions:renderActionsWithWrapper,Button:renderButtonWithWrapper,Card:renderCardWithWrapper,Chart:renderChartWithWrapper,Filter:renderFilterWithWrapper,Markdown:renderMarkdownWithWrapper,Search:renderSearchWithWrapper,Table:renderTableWithWrapper,Tabs:renderTabWithWrapper}}
|