@peak-ai/canvas 1.4.9 → 1.4.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GrapesjsCanvas.js +3 -3
- package/GrapesjsCanvas.js.map +1 -1
- package/package.json +1 -1
- package/plugins/helpers/render-components.js +3 -3
- package/plugins/helpers/render-components.js.map +1 -1
- package/shadcn/components/ui/component-wrapper.d.ts +26 -0
- package/shadcn/components/ui/component-wrapper.js +2 -0
- package/shadcn/components/ui/component-wrapper.js.map +1 -0
- package/shadcn/components/ui/date-filter.js +1 -1
- package/shadcn/components/ui/date-filter.js.map +1 -1
- package/shadcn/components/ui/error-container.js +1 -1
- package/shadcn/components/ui/error-container.js.map +1 -1
- package/shadcn/components/ui/error-wrapper.d.ts +7 -4
- package/shadcn/components/ui/error-wrapper.js +1 -1
- package/shadcn/components/ui/error-wrapper.js.map +1 -1
package/GrapesjsCanvas.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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
|
-
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{createGrapesjsShadcnGenericPlugin}from"./plugins/grapejs-plugin";import{StyledEditor}from"./index.styles";import{tailwindCompiledCss}from"./helpers/css";import{datePickerCss}from"./helpers/date-picker";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});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 expandActions(node){var _node$componentProps;if(node.type==="shadcn-generic"&&node.componentName==="Actions"&&Array.isArray((_node$componentProps=node.componentProps)==null?void 0:_node$componentProps.actions)){var actions=node.componentProps.actions;return _extends({},node,{type:"div",classes:["dashboard-cards"].concat(node.classes||[]),componentName:undefined,componentProps:undefined,components:actions.map(function(action,i){var icon=action.icon,title=action.title,description=action.description;return{id:node.id+"--action-card-"+i,type:"shadcn-generic",componentName:"ActionCard",badgable:false,copyable:false,componentProps:{icon:icon,headerContent:title,bodyContent:description}}})})}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 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(){
|
|
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{createGrapesjsShadcnGenericPlugin}from"./plugins/grapejs-plugin";import{StyledEditor}from"./index.styles";import{tailwindCompiledCss}from"./helpers/css";import{datePickerCss}from"./helpers/date-picker";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});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 expandActions(node){var _node$componentProps;if(node.type==="shadcn-generic"&&node.componentName==="Actions"&&Array.isArray((_node$componentProps=node.componentProps)==null?void 0:_node$componentProps.actions)){var actions=node.componentProps.actions;return _extends({},node,{type:"div",classes:["dashboard-cards"].concat(node.classes||[]),componentName:undefined,componentProps:undefined,components:actions.map(function(action,i){var icon=action.icon,title=action.title,description=action.description;return{id:node.id+"--action-card-"+i,type:"shadcn-generic",componentName:"ActionCard",badgable:false,copyable:false,componentProps:{icon:icon,headerContent:title,bodyContent:description}}})})}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 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(){// Default empty handler
|
|
3
|
+
}:_ref2$newDataNotifier;var editorRef=useRef(null);var editorInstance=useRef(null);var renderedComponents={};function notificationHandler(props){if(!props){return true}var componentId=props.componentId,newProps=props.newProps,newAttributes=props.newAttributes;var model=renderedComponents[componentId];if(!model){return false}var parsedNewProps=_extends({},newProps);if(newProps.pagination){parsedNewProps.pagination=_extends({},model.get("componentProps").pagination||{},newProps.pagination)}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 _callee(payload){var _editorInstance$curre;var updatedJson,result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=2;return(_editorInstance$curre=editorInstance.current)==null?void 0:_editorInstance$curre.store();case 2:updatedJson=_context.sent;setInteracting(renderedComponents,payload.affectedComponents,true);_context.prev=4;_context.next=7;return performInteraction(_extends({},payload,{json:updatedJson}));case 7:result=_context.sent;Object.entries(result||{}).forEach(function(_ref4){var key=_ref4[0],value=_ref4[1];var model=renderedComponents[key];if(model){model.set("componentProps",_extends({},model.get("componentProps"),value))}});return _context.abrupt("return",result);case 10:_context.prev=10;setInteracting(renderedComponents,payload.affectedComponents,false);return _context.finish(10);case 13:case"end":return _context.stop()}},_callee,null,[[4,,10,13]])}));return _performInteractionWrapper.apply(this,arguments)}useEffect(function(){var _json$pages,_json$pages$0$frames;if(!editorRef.current){return function cleanup(){// Cleanup if editorRef is not available
|
|
3
4
|
}}if(editorInstance.current){editorInstance.current.destroy();editorInstance.current=null}var currentMode=mode;var editor=grapesjs.init({container:editorRef.current,height:"100%",plugins:[tailwind,createGrapesjsShadcnGenericPlugin(currentMode,performInteractionWrapper,renderedComponents)],storageManager:{type:"none"},richTextEditor:{actions:["bold","italic","underline","strikethrough"]},canvas:{customBadgeLabel:function customBadgeLabel(component){var tagName=component.get("tagName");return tagName==="body"?"":tagName||""}}});// Tailwind CSS rules aren't fully added to our component
|
|
4
5
|
// So, adding them from here!
|
|
5
|
-
editor.on("load",function(){var canvasHead=editor.Canvas.getDocument().head;var style=document.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
|
|
6
|
-
},[json,mode]);return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(StyledEditor,{}),/*#__PURE__*/_jsx("div",{ref:editorRef,id:"grapesjs-editor"})]})}export default GrapesjsCanvas;
|
|
6
|
+
editor.on("load",function(){var canvasHead=editor.Canvas.getDocument().head;var style=document.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\n ";style.innerHTML=fullCss;style.setAttribute("type","text/css");canvasHead.appendChild(style)});editorInstance.current=editor;if(setEditor){setEditor(editor)}TypesToRegister.forEach(function(_ref3){var type=_ref3.type,tagName=_ref3.tagName;if(!editor.DomComponents.getType(type)){editor.DomComponents.addType(type,{model:{defaults:{tagName:tagName}},view:{}})}});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 raw=json.pages[0].frames[0].component;var processed=expandActions(raw);editor.setComponents(processed);var cssText=convertStyles(json.styles||[]);editor.setStyle(cssText)}editor.on("load",function(){setComponentProperties(editor,mode==="preview")});return function cleanup(){editor.destroy()}},[json,mode]);return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(StyledEditor,{}),/*#__PURE__*/_jsx("div",{ref:editorRef,id:"grapesjs-editor"})]})}export default GrapesjsCanvas;
|
|
7
7
|
//# 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","createGrapesjsShadcnGenericPlugin","StyledEditor","tailwindCompiledCss","datePickerCss","jsx","_jsx","jsxs","_jsxs","setComponentProperties","editor","isPreview","setPropertiesRecursively","comp","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","attributes","command","components","forEach","runCommand","stopCommand","wrapper","getWrapper","find","convertStyles","stylesArray","map","block","selectors","Array","isArray","join","declarations","Object","entries","style","_ref","prop","value","expandActions","node","_node$componentProps","type","componentName","componentProps","actions","_extends","classes","concat","undefined","action","i","icon","title","description","id","headerContent","bodyContent","setInteracting","renderedComponents","inProgress","component","componentId","showLoader","gjsModel","get","interactionApiInProgress","GrapesjsCanvas","_ref2","json","_ref2$mode","mode","setEditor","performInteraction","_ref2$newDataNotifier","newDataNotifier","editorRef","editorInstance","notificationHandler","props","newProps","newAttributes","model","parsedNewProps","pagination","performInteractionWrapper","_x","_performInteractionWrapper","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","payload","_editorInstance$curre","updatedJson","result","wrap","_callee$","_context","prev","next","current","store","sent","affectedComponents","_ref4","key","abrupt","finish","stop","_json$pages","_json$pages$0$frames","destroy","currentMode","init","container","height","plugins","storageManager","richTextEditor","canvas","customBadgeLabel","tagName","on","canvasHead","Canvas","getDocument","head","document","createElement","fullCss","innerHTML","setAttribute","appendChild","_ref3","DomComponents","getType","addType","defaults","view","pages","length","frames","raw","processed","setComponents","cssText","styles","setStyle","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';\nimport { TypesToRegister } from './constants';\nimport { toKebabCase } from './helpers';\nimport { createGrapesjsShadcnGenericPlugin } from './plugins/grapejs-plugin';\nimport { StyledEditor } from './index.styles';\nimport { tailwindCompiledCss } from './helpers/css';\nimport { datePickerCss } from './helpers/date-picker';\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};\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 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 expandActions(node: any): any {\n if (\n node.type === 'shadcn-generic' &&\n node.componentName === 'Actions' &&\n Array.isArray(node.componentProps?.actions)\n ) {\n const { actions } = node.componentProps;\n\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 const { icon, title, description } = action;\n\n return {\n id: `${node.id}--action-card-${i}`,\n type: 'shadcn-generic',\n componentName: 'ActionCard',\n badgable: false,\n copyable: false,\n componentProps: {\n icon,\n headerContent: title,\n bodyContent: description,\n },\n };\n }),\n };\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 GrapesjsCanvas({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n newDataNotifier = () => {},\n}: GrapesjsCanvasProps) {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<any>(null);\n const renderedComponents: Record<string, Component> = {};\n\n function notificationHandler(props: Parameters<NotificationHandler>[0]): ReturnType<NotificationHandler> {\n if (!props) {\n return true;\n }\n\n const {\n componentId,\n newProps,\n newAttributes,\n } = props;\n const model = renderedComponents[componentId];\n\n if (!model) {\n return false;\n }\n\n const parsedNewProps = {\n ...newProps,\n };\n\n if (newProps.pagination) {\n parsedNewProps.pagination = {\n ...(model.get('componentProps').pagination || {}),\n ...newProps.pagination,\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, payload.affectedComponents, true);\n\n try {\n const result = await performInteraction({\n ...payload,\n json: updatedJson,\n });\n\n Object.entries(result || {}).forEach(([key, value]) => {\n const model = renderedComponents[key];\n\n if (model) {\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...value,\n });\n }\n });\n\n return result;\n } finally {\n setInteracting(renderedComponents, payload.affectedComponents, false);\n }\n }\n\n useEffect(() => {\n if (!editorRef.current) {\n return () => {\n // Cleanup if editorRef is not available\n };\n }\n\n if (editorInstance.current) {\n editorInstance.current.destroy();\n editorInstance.current = null;\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,\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 // Tailwind CSS rules aren't fully added to our component\n // So, adding them from here!\n editor.on('load', () => {\n const canvasHead = editor.Canvas.getDocument().head;\n const style = document.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 `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n canvasHead.appendChild(style);\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 if (json && json.pages?.length > 0 && json.pages[0].frames?.length > 0) {\n const raw = json.pages[0].frames[0].component;\n const processed = expandActions(raw);\n editor.setComponents(processed);\n\n const cssText = convertStyles(json.styles || []);\n editor.setStyle(cssText);\n }\n\n editor.on('load', () => {\n setComponentProperties(editor, mode === 'preview');\n });\n\n return () => {\n editor.destroy();\n };\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n }, [json, 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,KAAK,EAAIC,SAAS,CAAEC,MAAM,KAAQ,OAAO,CAChD;AACA,MAAO,CAAAC,QAAQ,KAA6B,UAAU,CACtD,MAAO,kCAAkC,CACzC,MAAO,CAAAC,QAAQ,KAAM,mBAAmB,CACxC,OAASC,eAAe,KAAQ,aAAa,CAC7C,OAASC,WAAW,KAAQ,WAAW,CACvC,OAASC,iCAAiC,KAAQ,0BAA0B,CAC5E,OAASC,YAAY,KAAQ,gBAAgB,CAC7C,OAASC,mBAAmB,KAAQ,eAAe,CACnD,OAASC,aAAa,KAAQ,uBAAuB,CAAC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAgBtD,QAAS,CAAAC,sBAAsBA,CAAC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C7C,GAAM,CAAAqF,SAAS,CAAG3G,aAAa,CAAC0G,GAAG,CAAC,CACpClJ,MAAM,CAACoJ,aAAa,CAACD,SAAS,CAAC,CAE/B,GAAM,CAAAE,OAAO,CAAG5H,aAAa,CAAC6C,IAAI,CAACgF,MAAM,EAAI,EAAE,CAAC,CAChDtJ,MAAM,CAACuJ,QAAQ,CAACF,OAAO,CACzB,CAEArJ,MAAM,CAAC8H,EAAE,CAAC,MAAM,CAAE,UAAM,CACtB/H,sBAAsB,CAACC,MAAM,CAAEwE,IAAI,GAAK,SAAS,CACnD,CAAC,CAAC,CAEF,MAAO,WAAM,CACXxE,MAAM,CAACmH,OAAO,CAAC,CACjB,CAAC,CACD;AACF,CAAC,CAAE,CAAC7C,IAAI,CAAEE,IAAI,CAAC,CAAC,CAEhB,mBACE1E,KAAA,CAACd,KAAK,CAACwK,QAAQ,EAAAC,QAAA,eACb7J,IAAA,CAACJ,YAAY,GAAE,CAAC,cAChBI,IAAA,QAAK8J,GAAG,CAAE7E,SAAU,CAACrB,EAAE,CAAC,iBAAiB,CAAE,CAAC,EAC9B,CAEpB,CAEA,cAAe,CAAAY,cAAc","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"GrapesjsCanvas.js","names":["React","useEffect","useRef","grapesjs","tailwind","TypesToRegister","toKebabCase","createGrapesjsShadcnGenericPlugin","StyledEditor","tailwindCompiledCss","datePickerCss","jsx","_jsx","jsxs","_jsxs","setComponentProperties","editor","isPreview","setPropertiesRecursively","comp","set","editable","draggable","droppable","getName","selectable","hoverable","highlightable","copyable","resizable","removable","badgable","attributes","command","components","forEach","runCommand","stopCommand","wrapper","getWrapper","find","convertStyles","stylesArray","map","block","selectors","Array","isArray","join","declarations","Object","entries","style","_ref","prop","value","expandActions","node","_node$componentProps","type","componentName","componentProps","actions","_extends","classes","concat","undefined","action","i","icon","title","description","id","headerContent","bodyContent","setInteracting","renderedComponents","inProgress","component","componentId","showLoader","gjsModel","get","interactionApiInProgress","GrapesjsCanvas","_ref2","json","_ref2$mode","mode","setEditor","performInteraction","_ref2$newDataNotifier","newDataNotifier","editorRef","editorInstance","notificationHandler","props","newProps","newAttributes","model","parsedNewProps","pagination","performInteractionWrapper","_x","_performInteractionWrapper","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","payload","_editorInstance$curre","updatedJson","result","wrap","_callee$","_context","prev","next","current","store","sent","affectedComponents","_ref4","key","abrupt","finish","stop","_json$pages","_json$pages$0$frames","cleanup","destroy","currentMode","init","container","height","plugins","storageManager","richTextEditor","canvas","customBadgeLabel","tagName","on","canvasHead","Canvas","getDocument","head","document","createElement","fullCss","innerHTML","setAttribute","appendChild","_ref3","DomComponents","getType","addType","defaults","view","pages","length","frames","raw","processed","setComponents","cssText","styles","setStyle","Fragment","children","ref"],"sources":["../src/GrapesjsCanvas.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { useEffect, useRef, useState } from 'react';\n// eslint-disable-next-line import/no-named-as-default\nimport grapesjs, { Component, Editor } from 'grapesjs';\nimport 'grapesjs/dist/css/grapes.min.css';\nimport tailwind from 'grapesjs-tailwind';\nimport { TypesToRegister } from './constants';\nimport { toKebabCase } from './helpers';\nimport { createGrapesjsShadcnGenericPlugin } from './plugins/grapejs-plugin';\nimport { StyledEditor } from './index.styles';\nimport { tailwindCompiledCss } from './helpers/css';\nimport { datePickerCss } from './helpers/date-picker';\n\ntype NotificationHandler = (newData: {\n componentId: string;\n newProps: Record<string, any>;\n newAttributes: Record<string, any>;\n}) => boolean;\n\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};\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 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 expandActions(node: any): any {\n if (\n node.type === 'shadcn-generic' &&\n node.componentName === 'Actions' &&\n Array.isArray(node.componentProps?.actions)\n ) {\n const { actions } = node.componentProps;\n\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 const { icon, title, description } = action;\n\n return {\n id: `${node.id}--action-card-${i}`,\n type: 'shadcn-generic',\n componentName: 'ActionCard',\n badgable: false,\n copyable: false,\n componentProps: {\n icon,\n headerContent: title,\n bodyContent: description,\n },\n };\n }),\n };\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 GrapesjsCanvas({\n json,\n mode = 'preview',\n setEditor,\n performInteraction,\n newDataNotifier = () => {\n // Default empty handler\n },\n}: GrapesjsCanvasProps) {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<any>(null);\n const renderedComponents: Record<string, Component> = {};\n\n function notificationHandler(props: Parameters<NotificationHandler>[0]): ReturnType<NotificationHandler> {\n if (!props) {\n return true;\n }\n\n const {\n componentId,\n newProps,\n newAttributes,\n } = props;\n const model = renderedComponents[componentId];\n\n if (!model) {\n return false;\n }\n\n const parsedNewProps = {\n ...newProps,\n };\n\n if (newProps.pagination) {\n parsedNewProps.pagination = {\n ...(model.get('componentProps').pagination || {}),\n ...newProps.pagination,\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 return true;\n }\n\n\n\n useEffect(() => {\n newDataNotifier(notificationHandler);\n }, []);\n\n\n async function performInteractionWrapper(payload: Record<string, any>) {\n const updatedJson = await editorInstance.current?.store();\n setInteracting(renderedComponents, payload.affectedComponents, true);\n\n try {\n const result = await performInteraction({\n ...payload,\n json: updatedJson,\n });\n\n Object.entries(result || {}).forEach(([key, value]) => {\n const model = renderedComponents[key];\n\n if (model) {\n model.set('componentProps', {\n ...model.get('componentProps'),\n ...value,\n });\n }\n });\n\n return result;\n } finally {\n setInteracting(renderedComponents, payload.affectedComponents, false);\n }\n }\n\n\n useEffect(() => {\n if (!editorRef.current) {\n return function cleanup() {\n // Cleanup if editorRef is not available\n };\n }\n\n if (editorInstance.current) {\n editorInstance.current.destroy();\n editorInstance.current = null;\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,\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 // Tailwind CSS rules aren't fully added to our component\n // So, adding them from here!\n editor.on('load', () => {\n const canvasHead = editor.Canvas.getDocument().head;\n const style = document.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 `;\n style.innerHTML = fullCss;\n style.setAttribute('type', 'text/css');\n canvasHead.appendChild(style);\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 if (json && json.pages?.length > 0 && json.pages[0].frames?.length > 0) {\n const raw = json.pages[0].frames[0].component;\n const processed = expandActions(raw);\n editor.setComponents(processed);\n\n const cssText = convertStyles(json.styles || []);\n editor.setStyle(cssText);\n }\n\n editor.on('load', () => {\n setComponentProperties(editor, mode === 'preview');\n });\n\n return function cleanup() {\n editor.destroy();\n };\n }, [json, 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,KAAK,EAAIC,SAAS,CAAEC,MAAM,KAAkB,OAAO,CAC1D;AACA,MAAO,CAAAC,QAAQ,KAA6B,UAAU,CACtD,MAAO,kCAAkC,CACzC,MAAO,CAAAC,QAAQ,KAAM,mBAAmB,CACxC,OAASC,eAAe,KAAQ,aAAa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CAAC0E,KAAK,eAAV/B,WAAA,CAAYgC,MAAM,EAAG,CAAC,EAAI,EAAA/B,oBAAA,CAAA5C,IAAI,CAAC0E,KAAK,CAAC,CAAC,CAAC,CAACE,MAAM,eAApBhC,oBAAA,CAAsB+B,MAAM,EAAG,CAAC,CAAE,CACtE,GAAM,CAAAE,GAAG,CAAG7E,IAAI,CAAC0E,KAAK,CAAC,CAAC,CAAC,CAACE,MAAM,CAAC,CAAC,CAAC,CAACpF,SAAS,CAC7C,GAAM,CAAAsF,SAAS,CAAG5G,aAAa,CAAC2G,GAAG,CAAC,CACpCnJ,MAAM,CAACqJ,aAAa,CAACD,SAAS,CAAC,CAE/B,GAAM,CAAAE,OAAO,CAAG7H,aAAa,CAAC6C,IAAI,CAACiF,MAAM,EAAI,EAAE,CAAC,CAChDvJ,MAAM,CAACwJ,QAAQ,CAACF,OAAO,CACzB,CAEAtJ,MAAM,CAAC+H,EAAE,CAAC,MAAM,CAAE,UAAM,CACtBhI,sBAAsB,CAACC,MAAM,CAAEwE,IAAI,GAAK,SAAS,CACnD,CAAC,CAAC,CAEF,MAAO,SAAS,CAAA2C,OAAOA,CAAA,CAAG,CACxBnH,MAAM,CAACoH,OAAO,CAAC,CACjB,CACF,CAAC,CAAE,CAAC9C,IAAI,CAAEE,IAAI,CAAC,CAAC,CAEhB,mBACE1E,KAAA,CAACd,KAAK,CAACyK,QAAQ,EAAAC,QAAA,eACb9J,IAAA,CAACJ,YAAY,GAAE,CAAC,cAChBI,IAAA,QAAK+J,GAAG,CAAE9E,SAAU,CAACrB,EAAE,CAAC,iBAAiB,CAAE,CAAC,EAC9B,CAEpB,CAEA,cAAe,CAAAY,cAAc","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
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=["isEditable","gjsModel"],_excluded3=["isEditable","gjsModel"],_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,useRef}from"react";import{renderNoDataFallback}from"./extra";import{CircleAlert,TrendingDown,TrendingUp,ShoppingCart,ChartBarBig,Tag,MapPin}from"lucide-react";import{theme}from"@peak-ai/ais-components/theme";import Markdown from"markdown-to-jsx";import{Bar,BarChart,CartesianGrid,Legend,Line,LineChart,Pie,PieChart,ResponsiveContainer,XAxis,YAxis}from"recharts/lib";// @ts-ignore
|
|
2
|
-
import*as domutil from"recharts/lib/util/DOMUtils";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{ScrollArea,ScrollBar}from"../../shadcn/components/ui/scroll-area";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{
|
|
2
|
+
import*as domutil from"recharts/lib/util/DOMUtils";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{ScrollArea,ScrollBar}from"../../shadcn/components/ui/scroll-area";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
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=[];for(var _iterator=_createForOfIteratorHelperLoose(baseColors),_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);var _useState=useState(_extends({},props)),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"))),setAttributes=_useState2[1];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 defaultClasses="text-black p-4 rounded-lg shadow border flex flex-col h-full";return/*#__PURE__*/_jsx(Card,_extends({className:defaultClasses,style:{background:"linear-gradient(0deg, rgba(255, 255, 255, 0.4), rgba(255, 255, 255, 0.4)), linear-gradient(90.01deg, rgba(255, 255, 255, 0.4) -36.34%, rgba(42, 68, 212, 0.9) 218.89%)"},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:!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 _props$isEditable=props.isEditable,isEditable=_props$isEditable===void 0?false:_props$isEditable,gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded2);var _useState3=useState(_extends({},props)),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,className=allData.className;var _useState4=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState4[0],setAttributes=_useState4[1];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 defaultClasses="bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none";var defaultFooterClasses=footerContent?"text-sm bg-pink-50 text-pink-900 shadow-sm":"text-sm";var defaultContentMetadataClasses="text-xs";var mergedCardClassName=className?cn(defaultClasses,className):defaultClasses;var mergedFooterClassName=footerClass?cn(defaultFooterClasses,footerClass):defaultFooterClasses;var mergedContentMetadataClassName=contentMetadataClass?cn(defaultContentMetadataClasses,contentMetadataClass):defaultContentMetadataClasses;function getCardContent(){if(attributes.interactionApiInProgress||attributes.loading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsxs(CardHeader,{children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"headerContent",contentEditable:isEditable,className:"text-lg",children:headerContent}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"headerDescription",contentEditable:isEditable,className:"text-sm",children:headerDescription})]}),!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__*/_jsxs(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-grow",children:[/*#__PURE__*/_jsx("div",{className:"text-3xl font-semibold truncate",children:bodyContent}),contentMetadata&&/*#__PURE__*/_jsx("div",{className:mergedContentMetadataClassName,style:{color:"#2A44D4"},children:contentMetadata})]}),/*#__PURE__*/_jsxs(CardFooter,{"data-slot":"footerContent",contentEditable:isEditable,className:cn(mergedFooterClassName),children:[footerIcon&&/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIcon}),footerContent]})]})}return/*#__PURE__*/_jsx(Card,_extends({},rest,{className:mergedCardClassName,children:getCardContent()}))}function renderChartComponent(chartType,data,config){if(!data||data.length===0){return renderNoDataFallback()}switch(chartType){case"pie":return/*#__PURE__*/_jsxs(PieChart,{children:[data.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true})}),/*#__PURE__*/_jsx(Pie,{data:data,dataKey:config.dataKey,nameKey:config.nameKey,innerRadius:60,strokeWidth:10,label:data.length<20?function(_ref){var name=_ref.name,percent=_ref.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]});case"bar":config.dataKeys=config.dataKeys||[];return/*#__PURE__*/_jsxs(BarChart,_extends({data:data},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:config.xAxis}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(Legend,{align:"left",wrapperStyle:{marginLeft:20}}),config.dataKeys.map(function(_ref2){var key=_ref2.key,name=_ref2.name,color=_ref2.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||[];return/*#__PURE__*/_jsxs(LineChart,_extends({data:data},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"})}),config.dataKeys.map(function(_ref3){var key=_ref3.key,name=_ref3.name,color=_ref3.color;return/*#__PURE__*/_jsx(Line,{type:"monotone",dataKey:key,stroke:color!=null?color:"#4caf50",name:name},key)}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}));default:return/*#__PURE__*/_jsxs(PieChart,{children:[data.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true})}),/*#__PURE__*/_jsx(Pie,{data:data,dataKey:config.dataKey,nameKey:config.nameKey,innerRadius:60,strokeWidth:10,label:data.length<20?function(_ref4){var name=_ref4.name,percent=_ref4.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]})}}export function renderChart(props){var _props$isEditable2=props.isEditable,isEditable=_props$isEditable2===void 0?false:_props$isEditable2,gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded3);var _useState5=useState(_extends({},props)),allData=_useState5[0],setAllData=_useState5[1];var _useState6=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState6[0],setAttributes=_useState6[1];var containerRef=useRef(null);var _useState7=useState(0),containerWidth=_useState7[0],setContainerWidth=_useState7[1];useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(_extends({},gjsModel.get("componentProps")))})},[]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);useEffect(function(){var updateContainerWidth=function updateContainerWidth(){if(containerRef.current){setContainerWidth(containerRef.current.offsetWidth)}};updateContainerWidth();window.addEventListener("resize",updateContainerWidth);return function(){return 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";var mergedClasses=className?cn(defaultClasses,className):defaultClasses;if(chartType==="pie"){var colors=getNColors(chartData.length);for(var i=0;i<chartData.length;i++){var data=chartData[i];if(!data.fill){data.fill=colors[i]}}}else if(!config.color){config.color=baseColors[Math.floor(Math.random()*baseColors.length)]}var width=undefined;var totalDataPoints=0;// Helper function to get responsive config
|
|
7
7
|
var getResponsiveConfig=function getResponsiveConfig(){if(chartType==="bar"&&totalDataPoints>15&&containerWidth>0&&width&&width<=containerWidth){// If chart fits in container, use responsive behavior
|
|
8
|
-
return _extends({},config,{chartUi:{}})}return config};if(chartType==="bar"){config.dataKeys=config.dataKeys||[];totalDataPoints=chartData.length*Math.max(1,config.dataKeys.length);if(totalDataPoints>15){width=totalDataPoints*20+config.dataKeys.length*8*chartData.length+chartData.length*15;config.chartUi={barCategoryGap:"10%",width:width}}else{config.chartUi={}}}else if(chartType==="line"){config.dataKeys=config.dataKeys||[];totalDataPoints=chartData.length;if(totalDataPoints>15){width=Math.max(800,totalDataPoints*20);config.chartUi={width:width}}else{config.chartUi={}}}var chartUi=attributes.interactionApiInProgress||attributes.loading?/*#__PURE__*/_jsx(ChartLoader,{}):!chartData?renderNoDataFallback():/*#__PURE__*/_jsx(React.Fragment,{children:(chartType==="bar"||chartType==="line")&&totalDataPoints>15&&width&&(containerWidth===0||width>containerWidth)?/*#__PURE__*/_jsx("div",{className:"w-full h-[250px]",children:/*#__PURE__*/_jsxs(ScrollArea,{className:"w-full h-full",children:[/*#__PURE__*/_jsx("div",{style:{minWidth:width+"px",width:"max-content",height:"250px"},children:/*#__PURE__*/_jsx(ResponsiveContainer,{width:width,height:250,children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:config,className:mergedClasses,children:renderChartComponent(chartType,chartData,config)}))})}),/*#__PURE__*/_jsx(ScrollBar,{orientation:"horizontal"})]})}):/*#__PURE__*/_jsx(ResponsiveContainer,{width:"100%",height:250,children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:getResponsiveConfig(),className:mergedClasses,children:renderChartComponent(chartType,chartData,getResponsiveConfig())}))})});return/*#__PURE__*/_jsxs(Card,{className:"shadow border mt-2 mb-2",children:[/*#__PURE__*/_jsxs(CardHeader,{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",contentEditable:false,className:"px-6",children:chartUi})]})}export function renderTable(props){var gjsModel=props.gjsModel,_props$performInterac=props.performInteraction,performInteraction=_props$performInterac===void 0?function(){}:_props$performInterac,rest=_objectWithoutPropertiesLoose(props,_excluded4);var _useState8=useState(_extends({},props)),allData=_useState8[0],setAllData=_useState8[1];var cardRef=useRef(null);var _useState9=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState9[0],setAttributes=_useState9[1];var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$isEditable=allData.isEditable,isEditable=_allData$isEditable===void 0?false:_allData$isEditable,_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(_ref5){var key=_ref5[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref7){var _ref6=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref6.sortColumn,sortDirection=_ref6.sortDirection;return sortColumn&&sortDirection?(_ref7={},_ref7[sortColumn]=sortDirection,_ref7):{}}();var _useState0=useState(0),viewportWidth=_useState0[0],setViewportWidth=_useState0[1];var _useState1=useState(250),scrollAreaHeight=_useState1[0],setScrollAreaHeight=_useState1[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,data.length)}};var timeoutId=setTimeout(updateTableWidthAndApplyCSS,150);window.addEventListener("resize",updateTableWidthAndApplyCSS);return function(){clearTimeout(timeoutId);window.removeEventListener("resize",updateTableWidthAndApplyCSS)}},[allData,gjsModel,viewportWidth,data,calculateTableHeight]);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 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,_ref8,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:id=gjsModel.get("id");_ref8=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref8.sortColumn,sortDirection=_ref8.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 flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsxs(CardHeader,{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:/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:attributes.interactionApiInProgress,onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,otherProps:rest,height:scrollAreaHeight})})]})}export function renderTab(props){var tabsWidth=157;if(props.tabs.length>4){tabsWidth=157}return/*#__PURE__*/_jsxs(Tabs,{defaultValue:props.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:props.tabs.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)})})}),props.tabs.map(function(tab){return/*#__PURE__*/_jsx(TabsContent,{value:tab,className:"tabs-content"},tab)})]})}export function renderMarkdown(props){var gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded5);var _useState10=useState(_extends({},props)),allData=_useState10[0],setAllData=_useState10[1];var _useState11=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState11[0],setAttributes=_useState11[1];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 _useState12=useState(false),isEditing=_useState12[0],setIsEditing=_useState12[1];var editRef=useRef(null);var startEditing=function startEditing(){setIsEditing(true);setTimeout(function(){setupEditor()},0)};var setupEditor=function setupEditor(){if(!editRef.current){return}var editor=editRef.current;editor.innerHTML="";editor.textContent=allData.summaryText;editor.focus()};// Save changes and exit editing mode
|
|
9
|
-
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 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]"}}};if(attributes.loading){return/*#__PURE__*/_jsx(MarkdownLoader,{})}if(!allData.isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em]"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:"Insights"}),/*#__PURE__*/_jsx("div",{"data-slot":"summaryText",children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:allData.summaryText})})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em]"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:"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})})]}))}export function renderButton(props){var _props$isEditable3=props.isEditable,isEditable=_props$isEditable3===void 0?false:_props$isEditable3,gjsModel=props.gjsModel,_props$performInterac2=props.performInteraction,performInteraction=_props$performInterac2===void 0?function(){}:_props$performInterac2;var
|
|
8
|
+
return _extends({},config,{chartUi:{}})}return config};if(chartType==="bar"){config.dataKeys=config.dataKeys||[];totalDataPoints=chartData.length*Math.max(1,config.dataKeys.length);if(totalDataPoints>15){width=totalDataPoints*20+config.dataKeys.length*8*chartData.length+chartData.length*15;config.chartUi={barCategoryGap:"10%",width:width}}else{config.chartUi={}}}else if(chartType==="line"){config.dataKeys=config.dataKeys||[];totalDataPoints=chartData.length;if(totalDataPoints>15){width=Math.max(800,totalDataPoints*20);config.chartUi={width:width}}else{config.chartUi={}}}var chartUi=attributes.interactionApiInProgress||attributes.loading?/*#__PURE__*/_jsx(ChartLoader,{}):!chartData?renderNoDataFallback():/*#__PURE__*/_jsx(React.Fragment,{children:(chartType==="bar"||chartType==="line")&&totalDataPoints>15&&width&&(containerWidth===0||width>containerWidth)?/*#__PURE__*/_jsx("div",{className:"w-full h-[250px]",children:/*#__PURE__*/_jsxs(ScrollArea,{className:"w-full h-full",children:[/*#__PURE__*/_jsx("div",{style:{minWidth:width+"px",width:"max-content",height:"250px"},children:/*#__PURE__*/_jsx(ResponsiveContainer,{width:width,height:250,children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:config,className:mergedClasses,children:renderChartComponent(chartType,chartData,config)}))})}),/*#__PURE__*/_jsx(ScrollBar,{orientation:"horizontal"})]})}):/*#__PURE__*/_jsx(ResponsiveContainer,{width:"100%",height:250,children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:getResponsiveConfig(),className:mergedClasses,children:renderChartComponent(chartType,chartData,getResponsiveConfig())}))})});return/*#__PURE__*/_jsxs(Card,{className:"shadow border mt-2 mb-2",children:[/*#__PURE__*/_jsxs(CardHeader,{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",contentEditable:false,className:"px-6",children:chartUi})]})}export function renderTable(props){var gjsModel=props.gjsModel,_props$performInterac=props.performInteraction,performInteraction=_props$performInterac===void 0?function(){}:_props$performInterac,rest=_objectWithoutPropertiesLoose(props,_excluded4);var _useState8=useState(_extends({},props)),allData=_useState8[0],setAllData=_useState8[1];var cardRef=useRef(null);var _useState9=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState9[0],setAttributes=_useState9[1];var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$isEditable=allData.isEditable,isEditable=_allData$isEditable===void 0?false:_allData$isEditable,_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(_ref5){var key=_ref5[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref7){var _ref6=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref6.sortColumn,sortDirection=_ref6.sortDirection;return sortColumn&&sortDirection?(_ref7={},_ref7[sortColumn]=sortDirection,_ref7):{}}();var _useState10=useState(0),viewportWidth=_useState10[0],setViewportWidth=_useState10[1];var _useState11=useState(250),scrollAreaHeight=_useState11[0],setScrollAreaHeight=_useState11[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,data.length)}};var timeoutId=setTimeout(updateTableWidthAndApplyCSS,150);window.addEventListener("resize",updateTableWidthAndApplyCSS);return function(){clearTimeout(timeoutId);window.removeEventListener("resize",updateTableWidthAndApplyCSS)}},[allData,gjsModel,viewportWidth,data,calculateTableHeight]);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 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,_ref8,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:id=gjsModel.get("id");_ref8=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref8.sortColumn,sortDirection=_ref8.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 flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsxs(CardHeader,{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:/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:attributes.interactionApiInProgress,onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,otherProps:rest,height:scrollAreaHeight})})]})}export function renderTab(props){var tabsWidth=157;if(props.tabs.length>4){tabsWidth=157}return/*#__PURE__*/_jsxs(Tabs,{defaultValue:props.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:props.tabs.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)})})}),props.tabs.map(function(tab){return/*#__PURE__*/_jsx(TabsContent,{value:tab,className:"tabs-content"},tab)})]})}export function renderMarkdown(props){var gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded5);var _useState12=useState(_extends({},props)),allData=_useState12[0],setAllData=_useState12[1];var _useState13=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState13[0],setAttributes=_useState13[1];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 _useState14=useState(false),isEditing=_useState14[0],setIsEditing=_useState14[1];var editRef=useRef(null);var startEditing=function startEditing(){setIsEditing(true);setTimeout(function(){setupEditor()},0)};var setupEditor=function setupEditor(){if(!editRef.current){return}var editor=editRef.current;editor.innerHTML="";editor.textContent=allData.summaryText;editor.focus()};// Save changes and exit editing mode
|
|
9
|
+
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 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]"}}};if(attributes.loading){return/*#__PURE__*/_jsx(MarkdownLoader,{})}if(!allData.isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em]"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:"Insights"}),/*#__PURE__*/_jsx("div",{"data-slot":"summaryText",children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:allData.summaryText})})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em]"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:"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})})]}))}export function renderButton(props){var _props$isEditable3=props.isEditable,isEditable=_props$isEditable3===void 0?false:_props$isEditable3,gjsModel=props.gjsModel,_props$performInterac2=props.performInteraction,performInteraction=_props$performInterac2===void 0?function(){}:_props$performInterac2;var _useState15=useState(_extends({},props)),allData=_useState15[0],setAllData=_useState15[1];var _useState16=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState16[0],setAttributes=_useState16[1];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:props,children:renderActionCard(props)})};var renderButtonWithWrapper=function renderButtonWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:props,children:renderButton(props)})};var renderCardWithWrapper=function renderCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:props,children:renderCard(props)})};var renderChartWithWrapper=function renderChartWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:props,children:renderChart(props)})};var renderFilterWithWrapper=function renderFilterWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:props,children:renderFilter(props)})};var renderMarkdownWithWrapper=function renderMarkdownWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:props,children:renderMarkdown(props)})};var renderSearchWithWrapper=function renderSearchWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:props,children:renderSearch(props)})};var renderTableWithWrapper=function renderTableWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:props,children:renderTable(props)})};var renderTabWithWrapper=function renderTabWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:props,children:renderTab(props)})};export function getRenderers(){return{ActionCard:renderActionCardWithWrapper,Button:renderButtonWithWrapper,Card:renderCardWithWrapper,Chart:renderChartWithWrapper,Filter:renderFilterWithWrapper,Markdown:renderMarkdownWithWrapper,Search:renderSearchWithWrapper,Table:renderTableWithWrapper,Tabs:renderTabWithWrapper}}
|
|
10
10
|
//# sourceMappingURL=render-components.js.map
|