@peak-ai/canvas 1.4.19-rc.9 → 1.4.20-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/constants/index.js +1 -1
- package/constants/index.js.map +1 -1
- package/package.json +2 -2
- package/plugins/grapejs-plugin.js +2 -1
- package/plugins/grapejs-plugin.js.map +1 -1
- package/plugins/helpers/query-details-modal.d.ts +1 -8
- package/plugins/helpers/query-details-modal.js +3 -3
- package/plugins/helpers/query-details-modal.js.map +1 -1
- package/plugins/helpers/render-components.js +6 -5
- package/plugins/helpers/render-components.js.map +1 -1
- package/plugins/helpers/styled-info-button.js +1 -3
- package/plugins/helpers/styled-info-button.js.map +1 -1
- package/shadcn/components/ui/error-wrapper.d.ts +1 -1
- package/shadcn/components/ui/error-wrapper.js +1 -1
- package/shadcn/components/ui/error-wrapper.js.map +1 -1
- package/plugins/helpers/query-heading-formatter.d.ts +0 -1
- package/plugins/helpers/query-heading-formatter.js +0 -5
- package/plugins/helpers/query-heading-formatter.js.map +0 -1
package/constants/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export var TypesToRegister=[{tagName:"div",type:"div"},{tagName:"h1",type:"heading"},{tagName:"p",type:"text"},{tagName:"div",type:"container"},{tagName:"div",type:"grid"},{tagName:"table",type:"table"},{tagName:"thead",type:"thead"},{tagName:"tbody",type:"tbody"},{tagName:"tr",type:"tr"},{tagName:"th",type:"th"},{tagName:"td",type:"td"},{tagName:"button",type:"button"},{tagName:"section",type:"section"},{tagName:"
|
|
1
|
+
export var TypesToRegister=[{tagName:"div",type:"div"},{tagName:"h1",type:"heading"},{tagName:"p",type:"text"},{tagName:"div",type:"container"},{tagName:"div",type:"grid"},{tagName:"table",type:"table"},{tagName:"thead",type:"thead"},{tagName:"tbody",type:"tbody"},{tagName:"tr",type:"tr"},{tagName:"th",type:"th"},{tagName:"td",type:"td"},{tagName:"button",type:"button"},{tagName:"section",type:"section"},{tagName:"a",type:"link"},{tagName:"form",type:"form"},{tagName:"input",type:"input"},{tagName:"textarea",type:"textarea"},{tagName:"select",type:"select"},{tagName:"ul",type:"ul"},{tagName:"ol",type:"ol"},{tagName:"li",type:"li"},{tagName:"header",type:"header"},{tagName:"footer",type:"footer"}];
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/constants/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["TypesToRegister","tagName","type"],"sources":["../../src/constants/index.ts"],"sourcesContent":["export const TypesToRegister = [\n { tagName: 'div', type: 'div' },\n { tagName: 'h1', type: 'heading' },\n { tagName: 'p', type: 'text' },\n { tagName: 'div', type: 'container' },\n { tagName: 'div', type: 'grid' },\n { tagName: 'table', type: 'table' },\n { tagName: 'thead', type: 'thead' },\n { tagName: 'tbody', type: 'tbody' },\n { tagName: 'tr', type: 'tr' },\n { tagName: 'th', type: 'th' },\n { tagName: 'td', type: 'td' },\n { tagName: 'button', type: 'button' },\n { tagName: 'section', type: 'section' },\n { tagName: '
|
|
1
|
+
{"version":3,"file":"index.js","names":["TypesToRegister","tagName","type"],"sources":["../../src/constants/index.ts"],"sourcesContent":["export const TypesToRegister = [\n { tagName: 'div', type: 'div' },\n { tagName: 'h1', type: 'heading' },\n { tagName: 'p', type: 'text' },\n { tagName: 'div', type: 'container' },\n { tagName: 'div', type: 'grid' },\n { tagName: 'table', type: 'table' },\n { tagName: 'thead', type: 'thead' },\n { tagName: 'tbody', type: 'tbody' },\n { tagName: 'tr', type: 'tr' },\n { tagName: 'th', type: 'th' },\n { tagName: 'td', type: 'td' },\n { tagName: 'button', type: 'button' },\n { tagName: 'section', type: 'section' },\n { tagName: 'a', type: 'link' },\n { tagName: 'form', type: 'form' },\n { tagName: 'input', type: 'input' },\n { tagName: 'textarea', type: 'textarea' },\n { tagName: 'select', type: 'select' },\n { tagName: 'ul', type: 'ul' },\n { tagName: 'ol', type: 'ol' },\n { tagName: 'li', type: 'li' },\n { tagName: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AE,IAAI,CAAEC,IAAI,CAAE,IAAK,CAAC,CAC7B,CAAED,OAAO,CAAE,IAAI,CAAEC,IAAI,CAAE,IAAK,CAAC,CAC7B,CAAED,OAAO,CAAE,IAAI,CAAEC,IAAI,CAAE,IAAK,CAAC,CAC7B,CAAED,OAAO,CAAE,QAAQ,CAAEC,IAAI,CAAE,QAAS,CAAC,CACrC,CAAED,OAAO,CAAE,QAAQ,CAAEC,IAAI,CAAE,QAAS,CAAC,CACtC","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.20-rc.1",
|
|
6
6
|
"description": "",
|
|
7
7
|
"dependencies": {
|
|
8
8
|
"@emotion/react": "^11.11.4",
|
|
@@ -59,4 +59,4 @@
|
|
|
59
59
|
"types": "index.d.ts",
|
|
60
60
|
"module": "index.js",
|
|
61
61
|
"sideEffects": false
|
|
62
|
-
}
|
|
62
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import _extends from"@babel/runtime/helpers/extends";/* eslint-disable import/no-named-as-default-member *//* eslint-disable func-names *//* eslint-disable @typescript-eslint/no-explicit-any */import ReactDOM from"react-dom";import{getRenderers}from"./helpers/render-components";import{jsx as _jsx}from"react/jsx-runtime";export function createGrapesjsShadcnGenericPlugin(mode,performInteraction,renderedComponents,setHasChanged){if(renderedComponents===void 0){renderedComponents={}}return function grapesjsShadcnGenericPlugin(editor){editor.DomComponents.addType("shadcn-generic",{model:{defaults:{tagName:"div",droppable:false,componentName:"Card",componentProps:{},traits:[]}},view:{events:{"input [data-slot]":"handleSlotInput"},handleSlotInput:function handleSlotInput(e){var target=e.target;var slot=target.dataset.slot;var text=target.innerText;var props=this.model.get("componentProps")||{};if(!slot){return}if(slot.startsWith("table-header-")){var _props$data;var idx=parseInt(slot.split("-")[2],10);var dataKeys=Object.keys(((_props$data=props.data)==null?void 0:_props$data[0])||{});if(!props.headerMapper){props.headerMapper={}}var key=dataKeys[idx];if(key){props.headerMapper[key]=text}}else{props[slot]=text}this.model.set("componentProps",_extends({},props));if(!["search-input"].includes(slot)){setHasChanged(true)}},render:function render(){var _this=this;var compName=this.model.get("componentName");var compProps=this.model.get("componentProps");if(typeof compProps==="string"){try{compProps=JSON.parse(compProps)}catch(err){// eslint-disable-next-line no-console
|
|
2
2
|
console.error("Invalid JSON in componentProps",err);compProps={}}}compProps.isEditable=mode==="editor";compProps.performInteraction=performInteraction;compProps.onChange=function(data){_this.model.set("componentProps",_extends({},_this.model.get("componentProps"),data))};var renderers=getRenderers();var Renderer=renderers[compName];if(Renderer){if(compName==="Tabs"){ReactDOM.render(/*#__PURE__*/_jsx(Renderer,_extends({},compProps,{gjsModel:this.model})),this.el);var children=this.model.components();var tabsContent=this.el.querySelectorAll(".tabs-content");var tabAttributes=this.model.get("attributes")||{};var hasTabsError=tabAttributes.error||compProps.error;var hasTabsMissing=tabAttributes.isMissing||compProps.isMissing;var isFallback=Array.from(tabsContent).some(function(el){return el.dataset.fallback==="true"});if(!isFallback&&tabsContent.length>0){// Helper function to sync child attributes
|
|
3
|
-
|
|
3
|
+
// eslint-disable-next-line no-inner-declarations
|
|
4
|
+
var syncChildAttributes=function syncChildAttributes(childModel){var childAttributes=childModel.get("attributes")||{};var childProps=childModel.get("componentProps")||{};var hasError=hasTabsError||childAttributes.error||childProps.error;var hasMissing=hasTabsMissing||childAttributes.isMissing||childProps.isMissing;if(hasError||hasMissing){var newAttributes=_extends({},childAttributes,{loading:false,error:hasError,isMissing:hasMissing,inheritedFromParent:!!(hasTabsError||hasTabsMissing)});childModel.set("attributes",newAttributes,{silent:false})}};children.each(function(childModel,i){var childView=_this.createView(childModel);if(childView&&tabsContent[i]){childView.render();tabsContent[i].appendChild(childView.el);setTimeout(function(){syncChildAttributes(childModel)},100);childModel.on("change:attributes",function(){syncChildAttributes(childModel)})}})}}else{ReactDOM.render(/*#__PURE__*/_jsx(Renderer,_extends({},compProps,{gjsModel:this.model})),this.el)}}else{this.el.innerHTML="<div>Unsupported component: "+compName+"</div>"}renderedComponents[this.model.get("id")]=this.model;return this},createView:function createView(model){var _this$em$get$getType;var ComponentView=(_this$em$get$getType=this.em.get("DomComponents").getType(model.get("type")))==null?void 0:_this$em$get$getType.view;if(!ComponentView){// eslint-disable-next-line no-console
|
|
4
5
|
console.warn("No view found for component type:",model.get("type"));return null}var view=new ComponentView({model:model,config:this.config,componentTypes:this.componentTypes});return view},remove:function remove(){// eslint-disable-next-line import/no-named-as-default-member
|
|
5
6
|
ReactDOM.unmountComponentAtNode(this.el);return this}}})}}
|
|
6
7
|
//# sourceMappingURL=grapejs-plugin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grapejs-plugin.js","names":["ReactDOM","getRenderers","jsx","_jsx","createGrapesjsShadcnGenericPlugin","mode","performInteraction","renderedComponents","setHasChanged","grapesjsShadcnGenericPlugin","editor","DomComponents","addType","model","defaults","tagName","droppable","componentName","componentProps","traits","view","events","handleSlotInput","e","target","slot","dataset","text","innerText","props","get","startsWith","_props$data","idx","parseInt","split","dataKeys","Object","keys","data","headerMapper","key","set","_extends","includes","render","_this","compName","compProps","JSON","parse","err","console","error","isEditable","onChange","renderers","Renderer","gjsModel","el","children","components","tabsContent","querySelectorAll","tabAttributes","hasTabsError","hasTabsMissing","isMissing","isFallback","Array","from","some","fallback","length","syncChildAttributes","childModel","childAttributes","childProps","hasError","hasMissing","newAttributes","loading","inheritedFromParent","silent","each","i","childView","createView","appendChild","setTimeout","on","innerHTML","_this$em$get$getType","ComponentView","em","getType","warn","config","componentTypes","remove","unmountComponentAtNode"],"sources":["../../src/plugins/grapejs-plugin.tsx"],"sourcesContent":["/* eslint-disable import/no-named-as-default-member */\n/* eslint-disable func-names */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport ReactDOM from 'react-dom';\nimport { Editor, Component } from 'grapesjs';\nimport { getRenderers } from './helpers/render-components';\n\nexport function createGrapesjsShadcnGenericPlugin(\n mode: 'editor' | 'preview',\n performInteraction: (payload: Record<string, any>) => void,\n renderedComponents: Record<string, Component> = {},\n setHasChanged: (hasChanged: boolean) => void,\n) {\n return function grapesjsShadcnGenericPlugin(editor: Editor): void {\n editor.DomComponents.addType('shadcn-generic', {\n model: {\n defaults: {\n tagName: 'div',\n droppable: false,\n componentName: 'Card',\n componentProps: {},\n traits: [],\n },\n },\n view: {\n events: {\n 'input [data-slot]': 'handleSlotInput',\n } as any,\n handleSlotInput(e: Event) {\n const target = e.target as HTMLElement;\n const slot = target.dataset.slot;\n const text = target.innerText;\n\n const props = this.model.get('componentProps') || {};\n\n if (!slot) {\n return;\n }\n\n if (slot.startsWith('table-header-')) {\n const idx = parseInt(slot.split('-')[2], 10);\n const dataKeys = Object.keys(props.data?.[0] || {});\n\n if (!props.headerMapper) {\n props.headerMapper = {};\n }\n\n const key = dataKeys[idx];\n\n if (key) {\n props.headerMapper[key] = text;\n }\n } else {\n props[slot] = text;\n }\n\n this.model.set('componentProps', {\n ...props,\n });\n\n if (!['search-input'].includes(slot)) {\n setHasChanged(true);\n }\n },\n render: function () {\n const compName: string = this.model.get('componentName');\n let compProps: any = this.model.get('componentProps');\n\n if (typeof compProps === 'string') {\n try {\n compProps = JSON.parse(compProps);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Invalid JSON in componentProps', err);\n compProps = {};\n }\n }\n\n compProps.isEditable = mode === 'editor';\n compProps.performInteraction = performInteraction;\n\n compProps.onChange = (data: Record<string, any>) => {\n this.model.set('componentProps', {\n ...this.model.get('componentProps'),\n ...data,\n });\n };\n\n const renderers = getRenderers();\n const Renderer = renderers[compName];\n\n if (Renderer) {\n if (compName === 'Tabs') {\n ReactDOM.render(<Renderer {...compProps} gjsModel={this.model} />, this.el);\n\n const children = this.model.components();\n const tabsContent = this.el.querySelectorAll('.tabs-content');\n\n const tabAttributes = this.model.get('attributes') || {};\n const hasTabsError = tabAttributes.error || compProps.error;\n const hasTabsMissing = tabAttributes.isMissing || compProps.isMissing;\n const isFallback = Array.from(tabsContent).some((el: Element) => (el as HTMLElement).dataset.fallback === 'true');\n\n\n if (!isFallback && tabsContent.length > 0) {\n // Helper function to sync child attributes\n const syncChildAttributes = (childModel: any) => {\n const childAttributes = childModel.get('attributes') || {};\n const childProps = childModel.get('componentProps') || {};\n\n const hasError = hasTabsError || childAttributes.error || childProps.error;\n const hasMissing = hasTabsMissing || childAttributes.isMissing || childProps.isMissing;\n\n if (hasError || hasMissing) {\n const newAttributes = {\n ...childAttributes,\n loading: false,\n error: hasError,\n isMissing: hasMissing,\n inheritedFromParent: !!(hasTabsError || hasTabsMissing),\n };\n\n childModel.set('attributes', newAttributes, { silent: false });\n }\n };\n\n children.each((childModel, i) => {\n const childView = this.createView(childModel);\n\n if (childView && tabsContent[i]) {\n const childAttributes = childModel.get('attributes') || {};\n const childProps = childModel.get('componentProps') || {};\n childView.render();\n tabsContent[i].appendChild(childView.el);\n\n setTimeout(() => {\n syncChildAttributes(childModel);\n }, 100);\n\n childModel.on('change:attributes', () => {\n syncChildAttributes(childModel);\n });\n }\n });\n }\n } else {\n ReactDOM.render(<Renderer {...compProps} gjsModel={this.model} />, this.el);\n }\n } else {\n this.el.innerHTML = `<div>Unsupported component: ${compName}</div>`;\n }\n\n renderedComponents[this.model.get('id')] = this.model;\n\n return this;\n },\n createView(model: any) {\n const ComponentView = this.em.get('DomComponents').getType(model.get('type'))?.view;\n\n if (!ComponentView) {\n // eslint-disable-next-line no-console\n console.warn('No view found for component type:', model.get('type'));\n\n return null;\n }\n\n const view = new ComponentView({\n model,\n config: this.config,\n componentTypes: this.componentTypes,\n });\n\n return view;\n },\n remove: function () {\n // eslint-disable-next-line import/no-named-as-default-member\n ReactDOM.unmountComponentAtNode(this.el);\n\n return this;\n },\n },\n });\n };\n}\n"],"mappings":"qDAAA,sDACA,+BACA,uDACA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AMA,CAAA,CAAc,CAClB;AACAnG,QAAQ,CAACoG,sBAAsB,CAAC,IAAI,CAACzC,EAAE,CAAC,CAExC,MAAO,KACT,CACF,CACF,CAAC,CACH,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"grapejs-plugin.js","names":["ReactDOM","getRenderers","jsx","_jsx","createGrapesjsShadcnGenericPlugin","mode","performInteraction","renderedComponents","setHasChanged","grapesjsShadcnGenericPlugin","editor","DomComponents","addType","model","defaults","tagName","droppable","componentName","componentProps","traits","view","events","handleSlotInput","e","target","slot","dataset","text","innerText","props","get","startsWith","_props$data","idx","parseInt","split","dataKeys","Object","keys","data","headerMapper","key","set","_extends","includes","render","_this","compName","compProps","JSON","parse","err","console","error","isEditable","onChange","renderers","Renderer","gjsModel","el","children","components","tabsContent","querySelectorAll","tabAttributes","hasTabsError","hasTabsMissing","isMissing","isFallback","Array","from","some","fallback","length","syncChildAttributes","childModel","childAttributes","childProps","hasError","hasMissing","newAttributes","loading","inheritedFromParent","silent","each","i","childView","createView","appendChild","setTimeout","on","innerHTML","_this$em$get$getType","ComponentView","em","getType","warn","config","componentTypes","remove","unmountComponentAtNode"],"sources":["../../src/plugins/grapejs-plugin.tsx"],"sourcesContent":["/* eslint-disable import/no-named-as-default-member */\n/* eslint-disable func-names */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport ReactDOM from 'react-dom';\nimport { Editor, Component } from 'grapesjs';\nimport { getRenderers } from './helpers/render-components';\n\nexport function createGrapesjsShadcnGenericPlugin(\n mode: 'editor' | 'preview',\n performInteraction: (payload: Record<string, any>) => void,\n renderedComponents: Record<string, Component> = {},\n setHasChanged: (hasChanged: boolean) => void,\n) {\n return function grapesjsShadcnGenericPlugin(editor: Editor): void {\n editor.DomComponents.addType('shadcn-generic', {\n model: {\n defaults: {\n tagName: 'div',\n droppable: false,\n componentName: 'Card',\n componentProps: {},\n traits: [],\n },\n },\n view: {\n events: {\n 'input [data-slot]': 'handleSlotInput',\n } as any,\n handleSlotInput(e: Event) {\n const target = e.target as HTMLElement;\n const slot = target.dataset.slot;\n const text = target.innerText;\n\n const props = this.model.get('componentProps') || {};\n\n if (!slot) {\n return;\n }\n\n if (slot.startsWith('table-header-')) {\n const idx = parseInt(slot.split('-')[2], 10);\n const dataKeys = Object.keys(props.data?.[0] || {});\n\n if (!props.headerMapper) {\n props.headerMapper = {};\n }\n\n const key = dataKeys[idx];\n\n if (key) {\n props.headerMapper[key] = text;\n }\n } else {\n props[slot] = text;\n }\n\n this.model.set('componentProps', {\n ...props,\n });\n\n if (!['search-input'].includes(slot)) {\n setHasChanged(true);\n }\n },\n render: function () {\n const compName: string = this.model.get('componentName');\n let compProps: any = this.model.get('componentProps');\n\n if (typeof compProps === 'string') {\n try {\n compProps = JSON.parse(compProps);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Invalid JSON in componentProps', err);\n compProps = {};\n }\n }\n\n compProps.isEditable = mode === 'editor';\n compProps.performInteraction = performInteraction;\n\n compProps.onChange = (data: Record<string, any>) => {\n this.model.set('componentProps', {\n ...this.model.get('componentProps'),\n ...data,\n });\n };\n\n const renderers = getRenderers();\n const Renderer = renderers[compName];\n\n if (Renderer) {\n if (compName === 'Tabs') {\n ReactDOM.render(<Renderer {...compProps} gjsModel={this.model} />, this.el);\n\n const children = this.model.components();\n const tabsContent = this.el.querySelectorAll('.tabs-content');\n\n const tabAttributes = this.model.get('attributes') || {};\n const hasTabsError = tabAttributes.error || compProps.error;\n const hasTabsMissing = tabAttributes.isMissing || compProps.isMissing;\n const isFallback = Array.from(tabsContent).some(\n (el: Element) => (el as HTMLElement).dataset.fallback === 'true',\n );\n\n if (!isFallback && tabsContent.length > 0) {\n // Helper function to sync child attributes\n // eslint-disable-next-line no-inner-declarations\n function syncChildAttributes(childModel: any) {\n const childAttributes = childModel.get('attributes') || {};\n const childProps = childModel.get('componentProps') || {};\n\n const hasError = hasTabsError || childAttributes.error || childProps.error;\n const hasMissing =\n hasTabsMissing || childAttributes.isMissing || childProps.isMissing;\n\n if (hasError || hasMissing) {\n const newAttributes = {\n ...childAttributes,\n loading: false,\n error: hasError,\n isMissing: hasMissing,\n inheritedFromParent: !!(hasTabsError || hasTabsMissing),\n };\n\n childModel.set('attributes', newAttributes, { silent: false });\n }\n }\n\n children.each((childModel, i) => {\n const childView = this.createView(childModel);\n\n if (childView && tabsContent[i]) {\n childView.render();\n tabsContent[i].appendChild(childView.el);\n\n setTimeout(() => {\n syncChildAttributes(childModel);\n }, 100);\n\n childModel.on('change:attributes', () => {\n syncChildAttributes(childModel);\n });\n }\n });\n }\n } else {\n ReactDOM.render(<Renderer {...compProps} gjsModel={this.model} />, this.el);\n }\n } else {\n this.el.innerHTML = `<div>Unsupported component: ${compName}</div>`;\n }\n\n renderedComponents[this.model.get('id')] = this.model;\n\n return this;\n },\n createView(model: any) {\n const ComponentView = this.em.get('DomComponents').getType(model.get('type'))?.view;\n\n if (!ComponentView) {\n // eslint-disable-next-line no-console\n console.warn('No view found for component type:', model.get('type'));\n\n return null;\n }\n\n const view = new ComponentView({\n model,\n config: this.config,\n componentTypes: this.componentTypes,\n });\n\n return view;\n },\n remove: function () {\n // eslint-disable-next-line import/no-named-as-default-member\n ReactDOM.unmountComponentAtNode(this.el);\n\n return this;\n },\n },\n });\n };\n}\n"],"mappings":"qDAAA,sDACA,+BACA,uDACA,MAAO,CAAAA,QAAQ,KAAM,WAAW,CAEhC,OAASC,YAAY,KAAQ,6BAA6B,CAAC,OAAAC,GAAA,IAAAC,IAAA,yBAE3D,MAAO,SAAS,CAAAC,iCAAiCA,CAC/CC,IAA0B,CAC1BC,kBAA0D,CAC1DC,kBAA6C,CAC7CC,aAA4C,CAC5C,IAFAD,kBAA6C,WAA7CA,kBAA6C,CAAG,CAAC,CAAC,CAGlD,MAAO,SAAS,CAAAE,2BAA2BA,CAACC,MAAc,CAAQ,CAChEA,MAAM,CAACC,aAAa,CAACC,OAAO,CAAC,gBAAgB,CAAE,CAC7CC,KAAK,CAAE,CACLC,Q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C,CACD0E,UAAU,SAAV,CAAAA,UAAUA,CAAC1E,KAAU,CAAE,KAAA+E,oBAAA,CACrB,GAAM,CAAAC,aAAa,EAAAD,oBAAA,CAAG,IAAI,CAACE,EAAE,CAAChE,GAAG,CAAC,eAAe,CAAC,CAACiE,OAAO,CAAClF,KAAK,CAACiB,GAAG,CAAC,MAAM,CAAC,CAAC,eAAvD8D,oBAAA,CAAyDxE,IAAI,CAEnF,GAAI,CAACyE,aAAa,CAAE,CAClB;AACAzC,OAAO,CAAC4C,IAAI,CAAC,mCAAmC,CAAEnF,KAAK,CAACiB,GAAG,CAAC,MAAM,CAAC,CAAC,CAEpE,MAAO,KACT,CAEA,GAAM,CAAAV,IAAI,CAAG,GAAI,CAAAyE,aAAa,CAAC,CAC7BhF,KAAK,CAALA,KAAK,CACLoF,MAAM,CAAE,IAAI,CAACA,MAAM,CACnBC,cAAc,CAAE,IAAI,CAACA,cACvB,CAAC,CAAC,CAEF,MAAO,CAAA9E,IACT,CAAC,CACD+E,MAAM,CAAE,QAAR,CAAAA,MAAMA,CAAA,CAAc,CAClB;AACAnG,QAAQ,CAACoG,sBAAsB,CAAC,IAAI,CAACzC,EAAE,CAAC,CAExC,MAAO,KACT,CACF,CACF,CAAC,CACH,CACF","ignoreList":[]}
|
|
@@ -4,21 +4,14 @@ type QueryDetailsModalProps = {
|
|
|
4
4
|
isLoading: boolean;
|
|
5
5
|
error: string;
|
|
6
6
|
sqlQuery: string | string[];
|
|
7
|
-
queryHeadings?: string[];
|
|
8
7
|
tableButtonExplanations?: Array<{
|
|
9
8
|
action: string;
|
|
10
9
|
explanation: string;
|
|
11
10
|
operationName?: string;
|
|
12
|
-
operationSummary?: string;
|
|
13
|
-
operationDescription?: string;
|
|
14
11
|
buttonClassName?: string;
|
|
15
12
|
buttonStyle?: Record<string, unknown>;
|
|
16
|
-
formFields?: Record<string, unknown>;
|
|
17
|
-
jsonBody?: unknown;
|
|
18
|
-
filesArg?: Record<string, unknown>;
|
|
19
|
-
hasPayload?: boolean;
|
|
20
13
|
}>;
|
|
21
14
|
onRetry: () => void;
|
|
22
15
|
};
|
|
23
|
-
export declare function QueryDetailsModal({ isOpen, onClose, isLoading, error, sqlQuery,
|
|
16
|
+
export declare function QueryDetailsModal({ isOpen, onClose, isLoading, error, sqlQuery, tableButtonExplanations, onRetry }: QueryDetailsModalProps): import("react/jsx-runtime").JSX.Element;
|
|
24
17
|
export default QueryDetailsModal;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import _extends from"@babel/runtime/helpers/extends";import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _regeneratorRuntime from"@babel/runtime/regenerator";import React,{useState,useEffect}from"react";import{CustomModal}from"./custom-modal";import{Copy,Check,ChevronDown}from"lucide-react";import{
|
|
2
|
-
useEffect(function(){if(!isOpen){setExpandedButtons({})}},[isOpen]);function copyToClipboard(_x,_x2){return _copyToClipboard.apply(this,arguments)}function _copyToClipboard(){_copyToClipboard=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(queryToCopy,copyId){var textToCopy,id;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:textToCopy=queryToCopy;if(!textToCopy){if(Array.isArray(sqlQuery)){textToCopy=sqlQuery.filter(function(q){return q&&typeof q==="string"}).join("\n\n-- Next Query --\n\n")}else if(typeof sqlQuery==="string"){textToCopy=sqlQuery}else{textToCopy=""}}if(textToCopy){_context.next=4;break}return _context.abrupt("return");case 4:id=copyId||"main";_context.prev=5;_context.next=8;return navigator.clipboard.writeText(textToCopy);case 8:setCopied(function(prev){var _extends3;return _extends({},prev,(_extends3={},_extends3[id]=true,_extends3))});setTimeout(function(){return setCopied(function(prev){var _extends4;return _extends({},prev,(_extends4={},_extends4[id]=false,_extends4))})},2000);_context.next=14;break;case 12:_context.prev=12;_context.t0=_context["catch"](5);case 14:case"end":return _context.stop()}},_callee,null,[[5,12]])}));return _copyToClipboard.apply(this,arguments)}function toggleButtonExpansion(buttonIndex){setExpandedButtons(function(prev){var _extends2;return _extends({},prev,(_extends2={},_extends2[buttonIndex]=!prev[buttonIndex],_extends2))})}function renderTableButtonExplanations(){if(!tableButtonExplanations||tableButtonExplanations.length===0){return null}
|
|
3
|
-
if(Array.isArray(sqlQuery)){return/*#__PURE__*/_jsxs("div",{className:"p-6 space-y-4",children:[sqlQuery.filter(function(query){return query&&typeof query==="string"&&query.trim()}).map(function(query,index){
|
|
1
|
+
import _extends from"@babel/runtime/helpers/extends";import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _regeneratorRuntime from"@babel/runtime/regenerator";import React,{useState,useEffect}from"react";import{CustomModal}from"./custom-modal";import{Copy,Check,ChevronDown}from"lucide-react";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";export function QueryDetailsModal(_ref){var isOpen=_ref.isOpen,onClose=_ref.onClose,isLoading=_ref.isLoading,error=_ref.error,sqlQuery=_ref.sqlQuery,_ref$tableButtonExpla=_ref.tableButtonExplanations,tableButtonExplanations=_ref$tableButtonExpla===void 0?[]:_ref$tableButtonExpla,onRetry=_ref.onRetry;var _useState=useState({}),copied=_useState[0],setCopied=_useState[1];var _useState2=useState({}),expandedButtons=_useState2[0],setExpandedButtons=_useState2[1];// Reset expanded state when modal closes
|
|
2
|
+
useEffect(function(){if(!isOpen){setExpandedButtons({})}},[isOpen]);function copyToClipboard(_x,_x2){return _copyToClipboard.apply(this,arguments)}function _copyToClipboard(){_copyToClipboard=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(queryToCopy,copyId){var textToCopy,id;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:textToCopy=queryToCopy;if(!textToCopy){if(Array.isArray(sqlQuery)){textToCopy=sqlQuery.filter(function(q){return q&&typeof q==="string"}).join("\n\n-- Next Query --\n\n")}else if(typeof sqlQuery==="string"){textToCopy=sqlQuery}else{textToCopy=""}}if(textToCopy){_context.next=4;break}return _context.abrupt("return");case 4:id=copyId||"main";_context.prev=5;_context.next=8;return navigator.clipboard.writeText(textToCopy);case 8:setCopied(function(prev){var _extends3;return _extends({},prev,(_extends3={},_extends3[id]=true,_extends3))});setTimeout(function(){return setCopied(function(prev){var _extends4;return _extends({},prev,(_extends4={},_extends4[id]=false,_extends4))})},2000);_context.next=14;break;case 12:_context.prev=12;_context.t0=_context["catch"](5);case 14:case"end":return _context.stop()}},_callee,null,[[5,12]])}));return _copyToClipboard.apply(this,arguments)}function toggleButtonExpansion(buttonIndex){setExpandedButtons(function(prev){var _extends2;return _extends({},prev,(_extends2={},_extends2[buttonIndex]=!prev[buttonIndex],_extends2))})}function renderTableButtonExplanations(){if(!tableButtonExplanations||tableButtonExplanations.length===0){return null}return/*#__PURE__*/_jsx("div",{className:"mb-6",children:tableButtonExplanations.map(function(button,index){var _button$buttonStyle,_button$buttonStyle2,_button$buttonStyle3;return/*#__PURE__*/_jsxs("div",{className:"mb-3 border border-gray-200 rounded-lg",children:[/*#__PURE__*/_jsxs("div",{className:"w-full px-4 py-3 flex items-center justify-between rounded-lg",children:[/*#__PURE__*/_jsx("span",{className:"font-medium text-xs text-gray-500",children:"What does this button do?"}),/*#__PURE__*/_jsxs("div",{className:"flex items-center",children:[/*#__PURE__*/_jsx("button",{onClick:function onClick(){return toggleButtonExpansion(index)},className:button.buttonClassName||"flex items-center px-3 py-1.5 rounded text-xs font-medium",style:_extends({backgroundColor:((_button$buttonStyle=button.buttonStyle)==null?void 0:_button$buttonStyle.backgroundColor)||"#f3f4f6",color:((_button$buttonStyle2=button.buttonStyle)==null?void 0:_button$buttonStyle2.color)||"#374151",border:((_button$buttonStyle3=button.buttonStyle)==null?void 0:_button$buttonStyle3.border)||"1px solid #d1d5db"},button.buttonStyle||{}),children:button.action}),/*#__PURE__*/_jsx(ChevronDown,{className:"ml-2 w-4 h-4 text-gray-500 transition-transform cursor-pointer "+(expandedButtons[index]?"rotate-180":""),onClick:function onClick(){return toggleButtonExpansion(index)}})]})]}),expandedButtons[index]&&/*#__PURE__*/_jsx("div",{className:"px-4 pb-3 border-t border-gray-200",children:/*#__PURE__*/_jsxs("p",{className:"text-xs text-gray-700 mt-2",children:["This button will make a request to ",/*#__PURE__*/_jsx("span",{className:"font-semibold",children:button.explanation})]})})]},index)})})}function renderModalContent(){if(isLoading){return/*#__PURE__*/_jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[/*#__PURE__*/_jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600 mb-4"}),/*#__PURE__*/_jsx("span",{className:"text-xs text-gray-600",children:"Fetching query details from semantic layer..."}),/*#__PURE__*/_jsx("span",{className:"text-xs text-gray-400 mt-2",children:"This may take a few moments"})]})}if(error){return/*#__PURE__*/_jsxs("div",{className:"text-red-600 p-4 bg-red-50 rounded-lg border border-red-200 m-6",children:[/*#__PURE__*/_jsx("p",{className:"font-medium mb-2 text-xs",children:"Unable to fetch query details"}),/*#__PURE__*/_jsx("p",{className:"text-xs mb-3",children:error}),/*#__PURE__*/_jsx("button",{onClick:onRetry,className:"px-4 py-2 bg-red-100 hover:bg-red-200 rounded text-xs font-medium transition-colors",type:"button",children:"Retry"})]})}if(!sqlQuery||Array.isArray(sqlQuery)&&sqlQuery.length===0){return/*#__PURE__*/_jsx("div",{className:"text-gray-600 p-6",children:/*#__PURE__*/_jsx("p",{className:"text-xs",children:"No query details available"})})}// Handle multiple queries
|
|
3
|
+
if(Array.isArray(sqlQuery)){return/*#__PURE__*/_jsxs("div",{className:"p-6 space-y-4",children:[sqlQuery.filter(function(query){return query&&typeof query==="string"&&query.trim()}).map(function(query,index){return/*#__PURE__*/_jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[/*#__PURE__*/_jsxs("div",{className:"flex justify-between items-start mb-3",children:[/*#__PURE__*/_jsx("h3",{className:"font-semibold text-xs text-gray-500 m-0",children:"Query details"}),/*#__PURE__*/_jsx("button",{onClick:function onClick(){return copyToClipboard(query,"query-"+index)},className:"flex items-center gap-2 px-2 py-1 text-xs bg-gray-50 border border-gray-300 rounded hover:bg-gray-100 transition-colors",type:"button",children:copied["query-"+index]?/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsx(Check,{className:"w-3 h-3 text-green-600"}),/*#__PURE__*/_jsx("span",{className:"text-green-600",children:"Copied!"})]}):/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsx(Copy,{className:"w-3 h-3 text-gray-600"}),/*#__PURE__*/_jsx("span",{className:"text-gray-600",children:"Copy"})]})})]}),/*#__PURE__*/_jsx("pre",{className:"whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0",children:query})]},index)}),renderTableButtonExplanations()]})}return/*#__PURE__*/_jsxs("div",{className:"p-6 space-y-4",children:[/*#__PURE__*/_jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[/*#__PURE__*/_jsxs("div",{className:"flex justify-between items-start mb-3",children:[/*#__PURE__*/_jsx("h3",{className:"font-semibold text-xs text-gray-500 m-0",children:"Query details"}),/*#__PURE__*/_jsx("button",{onClick:function onClick(){return copyToClipboard(undefined,"single")},className:"flex items-center gap-2 px-2 py-1 text-xs bg-gray-50 border border-gray-300 rounded hover:bg-gray-100 transition-colors",type:"button",children:copied.single?/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsx(Check,{className:"w-3 h-3 text-green-600"}),/*#__PURE__*/_jsx("span",{className:"text-green-600",children:"Copied!"})]}):/*#__PURE__*/_jsxs(_Fragment,{children:[/*#__PURE__*/_jsx(Copy,{className:"w-3 h-3 text-gray-600"}),/*#__PURE__*/_jsx("span",{className:"text-gray-600",children:"Copy"})]})})]}),/*#__PURE__*/_jsx("pre",{className:"whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0",children:sqlQuery})]}),renderTableButtonExplanations()]})}return/*#__PURE__*/_jsx(CustomModal,{isOpen:isOpen,onClose:onClose,title:"How was this metric calculated?",children:renderModalContent()})}export default QueryDetailsModal;
|
|
4
4
|
//# sourceMappingURL=query-details-modal.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-details-modal.js","names":["React","useState","useEffect","CustomModal","Copy","Check","ChevronDown","formatQueryHeading","jsx","_jsx","jsxs","_jsxs","Fragment","_Fragment","QueryDetailsModal","_ref","isOpen","onClose","isLoading","error","sqlQuery","_ref$queryHeadings","queryHeadings","_ref$tableButtonExpla","tableButtonExplanations","onRetry","_useState","copied","setCopied","_useState2","expandedButtons","setExpandedButtons","copyToClipboard","_x","_x2","_copyToClipboard","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","queryToCopy","copyId","textToCopy","id","wrap","_callee$","_context","prev","next","Array","isArray","filter","q","join","abrupt","navigator","clipboard","writeText","_extends3","_extends","setTimeout","_extends4","t0","stop","toggleButtonExpansion","buttonIndex","_extends2","renderTableButtonExplanations","length","hasValidJsonBody","jsonBody","undefined","className","children","map","button","index","_button$buttonStyle","_button$buttonStyle2","_button$buttonStyle3","onClick","buttonClassName","style","backgroundColor","buttonStyle","color","border","action","operationDescription","operationSummary","explanation","type","hasPayload","formFields","Object","keys","JSON","stringify","filesArg","renderModalContent","query","trim","rawHeading","heading","single","title"],"sources":["../../../src/plugins/helpers/query-details-modal.tsx"],"sourcesContent":["import React, { useState, useEffect } from 'react';\nimport { CustomModal } from './custom-modal';\nimport { Copy, Check, ChevronDown } from 'lucide-react';\nimport { formatQueryHeading } from './query-heading-formatter';\n\ntype QueryDetailsModalProps = {\n isOpen: boolean;\n onClose: () => void;\n isLoading: boolean;\n error: string;\n sqlQuery: string | string[];\n queryHeadings?: string[];\n tableButtonExplanations?: Array<{\n action: string, \n explanation: string, \n operationName?: string, \n operationSummary?: string,\n operationDescription?: string,\n buttonClassName?: string, \n buttonStyle?: Record<string, unknown>,\n formFields?: Record<string, unknown>;\n jsonBody?: unknown;\n filesArg?: Record<string, unknown>;\n hasPayload?: boolean;\n }>;\n onRetry: () => void;\n};\n\nexport function QueryDetailsModal({\n isOpen,\n onClose,\n isLoading,\n error,\n sqlQuery,\n queryHeadings = [],\n tableButtonExplanations = [],\n onRetry\n}: QueryDetailsModalProps) {\n const [copied, setCopied] = useState<{ [key: string]: boolean }>({});\n const [expandedButtons, setExpandedButtons] = useState<{ [key: string]: boolean }>({});\n\n // Reset expanded state when modal closes\n useEffect(() => {\n if (!isOpen) {\n setExpandedButtons({});\n }\n }, [isOpen]);\n\n async function copyToClipboard(queryToCopy?: string, copyId?: string) {\n let textToCopy = queryToCopy;\n \n if (!textToCopy) {\n if (Array.isArray(sqlQuery)) {\n textToCopy = sqlQuery.filter(q => q && typeof q === 'string').join('\\n\\n-- Next Query --\\n\\n');\n } else if (typeof sqlQuery === 'string') {\n textToCopy = sqlQuery;\n } else {\n textToCopy = '';\n }\n }\n \n if (!textToCopy) {\n return;\n }\n \n const id = copyId || 'main';\n \n try {\n await navigator.clipboard.writeText(textToCopy);\n setCopied(prev => ({ ...prev, [id]: true }));\n setTimeout(() => setCopied(prev => ({ ...prev, [id]: false })), 2000);\n } catch (err) {\n // Silently fail if clipboard API is not available\n }\n }\n\n function toggleButtonExpansion(buttonIndex: number) {\n setExpandedButtons(prev => ({\n ...prev,\n [buttonIndex]: !prev[buttonIndex]\n }));\n }\n\n function renderTableButtonExplanations() {\n if (!tableButtonExplanations || tableButtonExplanations.length === 0) {\n return null;\n }\n\n const hasValidJsonBody = (jsonBody: unknown): boolean => {\n return jsonBody !== null && jsonBody !== undefined && jsonBody !== '';\n };\n\n return (\n <div className=\"mb-6\">\n {tableButtonExplanations.map((button, index) => (\n <div key={index} className=\"mb-3 border border-gray-200 rounded-lg\">\n <div className=\"w-full px-4 py-3 flex items-center justify-between rounded-lg\">\n <div className=\"flex items-center\">\n <button\n onClick={() => toggleButtonExpansion(index)}\n className={button.buttonClassName || \"flex items-center px-3 py-1.5 rounded text-xs font-medium\"}\n style={{\n backgroundColor: (button.buttonStyle?.backgroundColor as string) || '#f3f4f6',\n color: (button.buttonStyle?.color as string) || '#374151',\n border: (button.buttonStyle?.border as string) || '1px solid #d1d5db',\n ...(button.buttonStyle as React.CSSProperties || {})\n }}\n >\n {button.action}\n </button>\n <div className=\"ml-3 flex flex-col\">\n <span className=\"text-xs text-gray-500 font-medium\">\n {button.operationDescription || button.operationSummary || button.explanation}\n </span>\n </div>\n </div>\n <ChevronDown \n className={`w-4 h-4 text-gray-500 transition-transform cursor-pointer ${\n expandedButtons[index] ? 'rotate-180' : ''\n }`}\n onClick={() => toggleButtonExpansion(index)}\n />\n </div>\n \n {expandedButtons[index] && (\n <div className=\"px-4 pb-3 border-t border-gray-200\">\n <div className=\"mt-2 space-y-3\">\n <div className=\"bg-gray-50 rounded-lg p-3\">\n <div className=\"flex justify-between items-start mb-2\">\n <span className=\"text-xs font-medium text-gray-600\">URL</span>\n <button\n onClick={() => copyToClipboard(button.explanation, `url-${index}`)}\n className=\"flex items-center gap-1 px-2 py-1 text-xs bg-gray-100 border border-gray-300 rounded hover:bg-gray-200 transition-colors\"\n type=\"button\"\n >\n {copied[`url-${index}`] ? (\n <>\n <Check className=\"w-3 h-3 text-green-600\" />\n <span className=\"text-green-600\">Copied!</span>\n </>\n ) : (\n <>\n <Copy className=\"w-3 h-3 text-gray-600\" />\n <span className=\"text-gray-600\">Copy</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"text-xs text-gray-700 font-mono bg-white p-2 rounded border\">\n {button.explanation}\n </pre>\n </div>\n \n {button.hasPayload && (\n <div className=\"space-y-3\">\n {button.formFields && Object.keys(button.formFields).length > 0 && (\n <div className=\"bg-gray-50 rounded-lg p-3\">\n <div className=\"flex justify-between items-start mb-2\">\n <span className=\"text-xs font-medium text-gray-600\">Form Fields</span>\n <button\n onClick={() => copyToClipboard(JSON.stringify(button.formFields, null, 2), `form-fields-${index}`)}\n className=\"flex items-center gap-1 px-2 py-1 text-xs bg-gray-100 border border-gray-300 rounded hover:bg-gray-200 transition-colors\"\n type=\"button\"\n >\n {copied[`form-fields-${index}`] ? (\n <>\n <Check className=\"w-3 h-3 text-green-600\" />\n <span className=\"text-green-600\">Copied!</span>\n </>\n ) : (\n <>\n <Copy className=\"w-3 h-3 text-gray-600\" />\n <span className=\"text-gray-600\">Copy</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"text-xs text-gray-700 font-mono bg-white p-2 rounded border\">\n {JSON.stringify(button.formFields, null, 2)}\n </pre>\n </div>\n )}\n \n {hasValidJsonBody(button.jsonBody) && (\n <div className=\"bg-gray-50 rounded-lg p-3\">\n <div className=\"flex justify-between items-start mb-2\">\n <span className=\"text-xs font-medium text-gray-600\">JSON Body</span>\n <button\n onClick={() => copyToClipboard(JSON.stringify(button.jsonBody, null, 2), `json-body-${index}`)}\n className=\"flex items-center gap-1 px-2 py-1 text-xs bg-gray-100 border border-gray-300 rounded hover:bg-gray-200 transition-colors\"\n type=\"button\"\n >\n {copied[`json-body-${index}`] ? (\n <>\n <Check className=\"w-3 h-3 text-green-600\" />\n <span className=\"text-green-600\">Copied!</span>\n </>\n ) : (\n <>\n <Copy className=\"w-3 h-3 text-gray-600\" />\n <span className=\"text-gray-600\">Copy</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"text-xs text-gray-700 font-mono bg-white p-2 rounded border\">\n {JSON.stringify(button.jsonBody, null, 2)}\n </pre>\n </div>\n )}\n \n {button.filesArg && Object.keys(button.filesArg).length > 0 && (\n <div className=\"bg-gray-50 rounded-lg p-3\">\n <div className=\"flex justify-between items-start mb-2\">\n <span className=\"text-xs font-medium text-gray-600\">Files</span>\n <button\n onClick={() => copyToClipboard(JSON.stringify(button.filesArg, null, 2), `files-${index}`)}\n className=\"flex items-center gap-1 px-2 py-1 text-xs bg-gray-100 border border-gray-300 rounded hover:bg-gray-200 transition-colors\"\n type=\"button\"\n >\n {copied[`files-${index}`] ? (\n <>\n <Check className=\"w-3 h-3 text-green-600\" />\n <span className=\"text-green-600\">Copied!</span>\n </>\n ) : (\n <>\n <Copy className=\"w-3 h-3 text-gray-600\" />\n <span className=\"text-gray-600\">Copy</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"text-xs text-gray-700 font-mono bg-white p-2 rounded border\">\n {JSON.stringify(button.filesArg, null, 2)}\n </pre>\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n )}\n </div>\n ))}\n </div>\n );\n }\n\n function renderModalContent() {\n if (isLoading) {\n return (\n <div className=\"flex flex-col items-center justify-center py-12\">\n <div className=\"animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600 mb-4\"></div>\n <span className=\"text-xs text-gray-600\">Fetching query details from semantic layer...</span>\n <span className=\"text-xs text-gray-400 mt-2\">This may take a few moments</span>\n </div>\n );\n }\n\n if (error) {\n return (\n <div className=\"text-red-600 p-4 bg-red-50 rounded-lg border border-red-200 m-6\">\n <p className=\"font-medium mb-2 text-xs\">Unable to fetch query details</p>\n <p className=\"text-xs mb-3\">{error}</p>\n <button \n onClick={onRetry}\n className=\"px-4 py-2 bg-red-100 hover:bg-red-200 rounded text-xs font-medium transition-colors\"\n type=\"button\"\n >\n Retry\n </button>\n </div>\n );\n }\n\n if (!sqlQuery || (Array.isArray(sqlQuery) && sqlQuery.length === 0)) {\n return (\n <div className=\"text-gray-600 p-6\">\n <p className=\"text-xs\">No query details available</p>\n </div>\n );\n }\n\n // Handle multiple queries\n if (Array.isArray(sqlQuery)) {\n return (\n <div className=\"p-6 space-y-4\">\n {sqlQuery\n .filter(query => query && typeof query === 'string' && query.trim())\n .map((query, index) => {\n\n const rawHeading = queryHeadings[index] || `Query ${index + 1}`;\n const heading = formatQueryHeading(rawHeading);\n\n return (\n <div \n key={index} \n className=\"bg-white border border-gray-200 rounded-lg p-4\"\n >\n <div className=\"flex justify-between items-start mb-3\">\n <h3 className=\"font-semibold text-xs text-gray-500 m-0\">\n {heading}\n </h3>\n <button\n onClick={() => copyToClipboard(query, `query-${index}`)}\n className=\"flex items-center gap-2 px-2 py-1 text-xs bg-gray-50 border border-gray-300 rounded hover:bg-gray-100 transition-colors\"\n type=\"button\"\n >\n {copied[`query-${index}`] ? (\n <>\n <Check className=\"w-3 h-3 text-green-600\" />\n <span className=\"text-green-600\">Copied!</span>\n </>\n ) : (\n <>\n <Copy className=\"w-3 h-3 text-gray-600\" />\n <span className=\"text-gray-600\">Copy</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0\">\n {query}\n </pre>\n </div>\n );\n })}\n {renderTableButtonExplanations()}\n </div>\n );\n }\n\n return (\n <div className=\"p-6 space-y-4\">\n <div className=\"bg-white border border-gray-200 rounded-lg p-4\">\n <div className=\"flex justify-between items-start mb-3\">\n <h3 className=\"font-semibold text-xs text-gray-500 m-0\">\n {formatQueryHeading(queryHeadings[0] || \"Query details\")}\n </h3>\n <button\n onClick={() => copyToClipboard(undefined, 'single')}\n className=\"flex items-center gap-2 px-2 py-1 text-xs bg-gray-50 border border-gray-300 rounded hover:bg-gray-100 transition-colors\"\n type=\"button\"\n >\n {copied.single ? (\n <>\n <Check className=\"w-3 h-3 text-green-600\" />\n <span className=\"text-green-600\">Copied!</span>\n </>\n ) : (\n <>\n <Copy className=\"w-3 h-3 text-gray-600\" />\n <span className=\"text-gray-600\">Copy</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0\">\n {sqlQuery}\n </pre>\n </div>\n {renderTableButtonExplanations()}\n </div>\n );\n }\n\n return (\n <CustomModal\n isOpen={isOpen}\n onClose={onClose}\n title=\"How was this metric calculated?\"\n >\n {renderModalContent()}\n </CustomModal>\n );\n}\n\nexport default QueryDetailsModal;\n"],"mappings":"wLAAA,MAAO,CAAAA,KAAK,EAAIC,QAAQ,CAAEC,SAAS,KAAQ,OAAO,CAClD,OAASC,WAAW,KAAQ,gBAAgB,CAC5C,OAASC,IAAI,CAAEC,KAAK,CAAEC,WAAW,KAAQ,cAAc,CACvD,OAASC,kBAAkB,KA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AAC,gBAAgB,CAAAC,QAAA,CAAC,SAAO,CAAM,CAAC,EAC/C,CAAC,cAEHhE,KAAA,CAAAE,SAAA,EAAA8D,QAAA,eACElE,IAAA,CAACL,IAAI,EAACsE,SAAS,CAAC,uBAAuB,CAAE,CAAC,cAC1CjE,IAAA,SAAMiE,SAAS,CAAC,eAAe,CAAAC,QAAA,CAAC,MAAI,CAAM,CAAC,EAC3C,CACH,CACK,CAAC,EACN,CAAC,cACNlE,IAAA,QAAKiE,SAAS,CAAC,mEAAmE,CAAAC,QAAA,CAC/EvD,QAAQ,CACN,CAAC,EACH,CAAC,CACLiD,6BAA6B,CAAC,CAAC,EAC7B,CAEX,CAEA,mBACE5D,IAAA,CAACN,WAAW,EACVa,MAAM,CAAEA,MAAO,CACfC,OAAO,CAAEA,OAAQ,CACjB0F,KAAK,CAAC,iCAAiC,CAAAhC,QAAA,CAEtC0B,kBAAkB,CAAC,CAAC,CACV,CAEjB,CAEA,cAAe,CAAAvF,iBAAiB","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"query-details-modal.js","names":["React","useState","useEffect","CustomModal","Copy","Check","ChevronDown","jsx","_jsx","jsxs","_jsxs","Fragment","_Fragment","QueryDetailsModal","_ref","isOpen","onClose","isLoading","error","sqlQuery","_ref$tableButtonExpla","tableButtonExplanations","onRetry","_useState","copied","setCopied","_useState2","expandedButtons","setExpandedButtons","copyToClipboard","_x","_x2","_copyToClipboard","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","queryToCopy","copyId","textToCopy","id","wrap","_callee$","_context","prev","next","Array","isArray","filter","q","join","abrupt","navigator","clipboard","writeText","_extends3","_extends","setTimeout","_extends4","t0","stop","toggleButtonExpansion","buttonIndex","_extends2","renderTableButtonExplanations","length","className","children","map","button","index","_button$buttonStyle","_button$buttonStyle2","_button$buttonStyle3","onClick","buttonClassName","style","backgroundColor","buttonStyle","color","border","action","explanation","renderModalContent","type","query","trim","undefined","single","title"],"sources":["../../../src/plugins/helpers/query-details-modal.tsx"],"sourcesContent":["import React, { useState, useEffect } from 'react';\nimport { CustomModal } from './custom-modal';\nimport { Copy, Check, ChevronDown } from 'lucide-react';\n\ntype QueryDetailsModalProps = {\n isOpen: boolean;\n onClose: () => void;\n isLoading: boolean;\n error: string;\n sqlQuery: string | string[];\n tableButtonExplanations?: Array<{action: string, explanation: string, operationName?: string, buttonClassName?: string, buttonStyle?: Record<string, unknown>}>;\n onRetry: () => void;\n};\n\nexport function QueryDetailsModal({\n isOpen,\n onClose,\n isLoading,\n error,\n sqlQuery,\n tableButtonExplanations = [],\n onRetry\n}: QueryDetailsModalProps) {\n const [copied, setCopied] = useState<{ [key: string]: boolean }>({});\n const [expandedButtons, setExpandedButtons] = useState<{ [key: string]: boolean }>({});\n\n // Reset expanded state when modal closes\n useEffect(() => {\n if (!isOpen) {\n setExpandedButtons({});\n }\n }, [isOpen]);\n\n async function copyToClipboard(queryToCopy?: string, copyId?: string) {\n let textToCopy = queryToCopy;\n \n if (!textToCopy) {\n if (Array.isArray(sqlQuery)) {\n textToCopy = sqlQuery.filter(q => q && typeof q === 'string').join('\\n\\n-- Next Query --\\n\\n');\n } else if (typeof sqlQuery === 'string') {\n textToCopy = sqlQuery;\n } else {\n textToCopy = '';\n }\n }\n \n if (!textToCopy) {\n return;\n }\n \n const id = copyId || 'main';\n \n try {\n await navigator.clipboard.writeText(textToCopy);\n setCopied(prev => ({ ...prev, [id]: true }));\n setTimeout(() => setCopied(prev => ({ ...prev, [id]: false })), 2000);\n } catch (err) {\n // Silently fail if clipboard API is not available\n }\n }\n\n function toggleButtonExpansion(buttonIndex: number) {\n setExpandedButtons(prev => ({\n ...prev,\n [buttonIndex]: !prev[buttonIndex]\n }));\n }\n\n function renderTableButtonExplanations() {\n if (!tableButtonExplanations || tableButtonExplanations.length === 0) {\n return null;\n }\n\n return (\n <div className=\"mb-6\">\n {tableButtonExplanations.map((button, index) => (\n <div key={index} className=\"mb-3 border border-gray-200 rounded-lg\">\n <div className=\"w-full px-4 py-3 flex items-center justify-between rounded-lg\">\n <span className=\"font-medium text-xs text-gray-500\">\n What does this button do?\n </span>\n <div className=\"flex items-center\">\n <button\n onClick={() => toggleButtonExpansion(index)}\n className={button.buttonClassName || \"flex items-center px-3 py-1.5 rounded text-xs font-medium\"}\n style={{\n backgroundColor: (button.buttonStyle?.backgroundColor as string) || '#f3f4f6',\n color: (button.buttonStyle?.color as string) || '#374151',\n border: (button.buttonStyle?.border as string) || '1px solid #d1d5db',\n ...(button.buttonStyle as React.CSSProperties || {})\n }}\n >\n {button.action}\n </button>\n <ChevronDown \n className={`ml-2 w-4 h-4 text-gray-500 transition-transform cursor-pointer ${\n expandedButtons[index] ? 'rotate-180' : ''\n }`}\n onClick={() => toggleButtonExpansion(index)}\n />\n </div>\n </div>\n \n {expandedButtons[index] && (\n <div className=\"px-4 pb-3 border-t border-gray-200\">\n <p className=\"text-xs text-gray-700 mt-2\">\n This button will make a request to <span className=\"font-semibold\">{button.explanation}</span> \n </p>\n </div>\n )}\n </div>\n ))}\n </div>\n );\n }\n\n function renderModalContent() {\n if (isLoading) {\n return (\n <div className=\"flex flex-col items-center justify-center py-12\">\n <div className=\"animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600 mb-4\"></div>\n <span className=\"text-xs text-gray-600\">Fetching query details from semantic layer...</span>\n <span className=\"text-xs text-gray-400 mt-2\">This may take a few moments</span>\n </div>\n );\n }\n\n if (error) {\n return (\n <div className=\"text-red-600 p-4 bg-red-50 rounded-lg border border-red-200 m-6\">\n <p className=\"font-medium mb-2 text-xs\">Unable to fetch query details</p>\n <p className=\"text-xs mb-3\">{error}</p>\n <button \n onClick={onRetry}\n className=\"px-4 py-2 bg-red-100 hover:bg-red-200 rounded text-xs font-medium transition-colors\"\n type=\"button\"\n >\n Retry\n </button>\n </div>\n );\n }\n\n if (!sqlQuery || (Array.isArray(sqlQuery) && sqlQuery.length === 0)) {\n return (\n <div className=\"text-gray-600 p-6\">\n <p className=\"text-xs\">No query details available</p>\n </div>\n );\n }\n\n // Handle multiple queries\n if (Array.isArray(sqlQuery)) {\n return (\n <div className=\"p-6 space-y-4\">\n {sqlQuery\n .filter(query => query && typeof query === 'string' && query.trim())\n .map((query, index) => (\n <div \n key={index} \n className=\"bg-white border border-gray-200 rounded-lg p-4\"\n >\n <div className=\"flex justify-between items-start mb-3\">\n <h3 className=\"font-semibold text-xs text-gray-500 m-0\">\n Query details\n </h3>\n <button\n onClick={() => copyToClipboard(query, `query-${index}`)}\n className=\"flex items-center gap-2 px-2 py-1 text-xs bg-gray-50 border border-gray-300 rounded hover:bg-gray-100 transition-colors\"\n type=\"button\"\n >\n {copied[`query-${index}`] ? (\n <>\n <Check className=\"w-3 h-3 text-green-600\" />\n <span className=\"text-green-600\">Copied!</span>\n </>\n ) : (\n <>\n <Copy className=\"w-3 h-3 text-gray-600\" />\n <span className=\"text-gray-600\">Copy</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0\">\n {query}\n </pre>\n </div>\n ))}\n {renderTableButtonExplanations()}\n </div>\n );\n }\n\n return (\n <div className=\"p-6 space-y-4\">\n <div className=\"bg-white border border-gray-200 rounded-lg p-4\">\n <div className=\"flex justify-between items-start mb-3\">\n <h3 className=\"font-semibold text-xs text-gray-500 m-0\">\n Query details\n </h3>\n <button\n onClick={() => copyToClipboard(undefined, 'single')}\n className=\"flex items-center gap-2 px-2 py-1 text-xs bg-gray-50 border border-gray-300 rounded hover:bg-gray-100 transition-colors\"\n type=\"button\"\n >\n {copied.single ? (\n <>\n <Check className=\"w-3 h-3 text-green-600\" />\n <span className=\"text-green-600\">Copied!</span>\n </>\n ) : (\n <>\n <Copy className=\"w-3 h-3 text-gray-600\" />\n <span className=\"text-gray-600\">Copy</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0\">\n {sqlQuery}\n </pre>\n </div>\n {renderTableButtonExplanations()}\n </div>\n );\n }\n\n return (\n <CustomModal\n isOpen={isOpen}\n onClose={onClose}\n title=\"How was this metric calculated?\"\n >\n {renderModalContent()}\n </CustomModal>\n );\n}\n\nexport default QueryDetailsModal;\n"],"mappings":"wLAAA,MAAO,CAAAA,KAAK,EAAIC,QAAQ,CAAEC,SAAS,KAAQ,OAAO,CAClD,OAASC,WAAW,KAAQ,gBAAgB,CAC5C,OAASC,IAAI,CAAEC,KAAK,CAAEC,WAAW,KAAQ,cAAc,CAAC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,CAAAC,QAAA,IAAAC,SAAA,yBAYxD,MAAO,SAAS,CAAAC,iBAAiBA,CAAAC,IAAA,CAQN,IAPzB,CAAAC,MAAM,CAAAD,IAAA,CAANC,MAAM,CACNC,OAAO,CAAAF,IAAA,CAAPE,OAAO,CACPC,SAAS,CAAAH,IAAA,CAATG,SAAS,CACTC,KAAK,CAAAJ,IAAA,CAALI,KAAK,CACLC,QAAQ,CAAAL,IAAA,CAARK,QAAQ,CAAAC,qBAAA,CAAAN,IAAA,CACRO,uBAAuB,CAAvBA,uBAAuB,CAAAD,qBAAA,UAAG,EAAE,CAAAA,qBAAA,CAC5BE,OAAO,CAAAR,IAAA,CAAPQ,OAAO,CAEP,IAAAC,SAAA,CAA4BtB,QAAQ,CAA6B,CAAC,CAAC,CAAC,CAA7DuB,MAAM,CAAAD,SAAA,IAAEE,SAAS,CAAAF,SAAA,IACxB,IAAAG,UAAA,CAA8CzB,QAAQ,CAA6B,CAAC,CAAC,CAAC,CAA/E0B,eAAe,CAAAD,UAAA,IAAEE,kBAAkB,CAAAF,UAAA,IAE1C;AACAxB,SAAS,CAAC,UAAM,CACd,GAAI,CAACa,MAAM,CAAE,CACXa,kBAAkB,CAAC,CAAC,CAAC,CACvB,CACF,CAAC,CAAE,CAACb,MAAM,CAAC,CAAC,CAAC,QAEE,CAAAc,eAAeA,CAAAC,EAAA,CAAAC,GAAA,SAAAC,gBAAA,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Q,CAAAjB,QAAA,CAEZ7C,MAAM,CAACkE,MAAM,cACZhF,KAAA,CAAAE,SAAA,EAAAyD,QAAA,eACE7D,IAAA,CAACH,KAAK,EAAC+D,SAAS,CAAC,wBAAwB,CAAE,CAAC,cAC5C5D,IAAA,SAAM4D,SAAS,CAAC,gBAAgB,CAAAC,QAAA,CAAC,SAAO,CAAM,CAAC,EAC/C,CAAC,cAEH3D,KAAA,CAAAE,SAAA,EAAAyD,QAAA,eACE7D,IAAA,CAACJ,IAAI,EAACgE,SAAS,CAAC,uBAAuB,CAAE,CAAC,cAC1C5D,IAAA,SAAM4D,SAAS,CAAC,eAAe,CAAAC,QAAA,CAAC,MAAI,CAAM,CAAC,EAC3C,CACH,CACK,CAAC,EACN,CAAC,cACN7D,IAAA,QAAK4D,SAAS,CAAC,mEAAmE,CAAAC,QAAA,CAC/ElD,QAAQ,CACN,CAAC,EACH,CAAC,CACL+C,6BAA6B,CAAC,CAAC,EAC7B,CAEX,CAEA,mBACE1D,IAAA,CAACL,WAAW,EACVY,MAAM,CAAEA,MAAO,CACfC,OAAO,CAAEA,OAAQ,CACjB2E,KAAK,CAAC,iCAAiC,CAAAtB,QAAA,CAEtCgB,kBAAkB,CAAC,CAAC,CACV,CAEjB,CAEA,cAAe,CAAAxE,iBAAiB","ignoreList":[]}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _extends from"@babel/runtime/helpers/extends";import _objectWithoutPropertiesLoose from"@babel/runtime/helpers/objectWithoutPropertiesLoose";var _excluded=["
|
|
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","performInteraction"],_excluded3=["isEditable","gjsModel","performInteraction"],_excluded4=["isEditable","gjsModel","performInteraction"],_excluded5=["isEditable","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{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,ResponsiveContainer,XAxis,YAxis}from"recharts/lib";// @ts-ignore
|
|
2
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
|
-
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={
|
|
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 _props$isEditable=props.isEditable,isEditable=_props$isEditable===void 0?false:_props$isEditable,gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded);var _useState=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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"))),attributes=_useState2[0],setAttributes=_useState2[1];useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(function(prevData){return _extends({},prevData,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+" 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 _props$isEditable2=props.isEditable,isEditable=_props$isEditable2===void 0?false:_props$isEditable2,gjsModel=props.gjsModel,_props$performInterac=props.performInteraction,performInteraction=_props$performInterac===void 0?function(){return Promise.resolve({})}:_props$performInterac,rest=_objectWithoutPropertiesLoose(props,_excluded2);var _useState3=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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 safeHeaderContent=typeof headerContent==="string"?headerContent:headerContent?JSON.stringify(headerContent):"";var safeHeaderDescription=typeof headerDescription==="string"?headerDescription:headerDescription?JSON.stringify(headerDescription):"";var safeBodyContent=typeof bodyContent==="string"?bodyContent:bodyContent?JSON.stringify(bodyContent):"";var safeFooterContent=typeof footerContent==="string"?footerContent:footerContent?JSON.stringify(footerContent):"";var safeContentMetadata=typeof contentMetadata==="string"?contentMetadata:contentMetadata?JSON.stringify(contentMetadata):"";var _useState4=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState4[0],setAttributes=_useState4[1];useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(function(prevData){return _extends({},prevData,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(){var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=(attributes.interactionApiInProgress||attributes.loading)&&!hasError&&!hasMissing;if(isLoading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}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})]})})}),hasError||hasMissing||!safeBodyContent?/*#__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}),safeContentMetadata&&/*#__PURE__*/_jsx("div",{className:mergedContentMetadataClassName,style:{color:"#2A44D4"},children:safeContentMetadata})]}),/*#__PURE__*/_jsxs(CardFooter,{"data-slot":"footerContent",contentEditable:isEditable,className:cn(mergedFooterClassName),children:[footerIcon&&typeof footerIcon==="string"&&/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIcon}),safeFooterContent||""]})]})}return/*#__PURE__*/_jsxs(Card,_extends({},rest,{className:mergedCardClassName+" relative",children:[getCardContent(),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable})]}))}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(_ref){var name=_ref.name,percent=_ref.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,{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(_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||[];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(_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:[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(_ref4){var name=_ref4.name,percent=_ref4.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]})}}export function renderChart(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(){return Promise.resolve({})}:_props$performInterac2,rest=_objectWithoutPropertiesLoose(props,_excluded3);var _useState5=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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(){var handlePropsChange=function handlePropsChange(){var newProps=gjsModel.get("componentProps");setAllData(function(prevData){return _extends({},prevData,newProps)})};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)}};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 safeChartData=Array.isArray(chartData)?chartData:[];var colors=getNColors(safeChartData.length);for(var i=0;i<safeChartData.length;i++){var data=safeChartData[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 width=undefined;var totalDataPoints=0;// Helper function to get responsive config
|
|
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
|
|
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({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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"))),attributes=_useState2[0],setAttributes=_useState2[1];useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(function(prevData){return _extends({},prevData,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+" 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$error,_attributes$isMissing;var _props$isEditable=props.isEditable,isEditable=_props$isEditable===void 0?false:_props$isEditable,gjsModel=props.gjsModel,_props$performInterac=props.performInteraction,performInteraction=_props$performInterac===void 0?function(){return Promise.resolve({})}:_props$performInterac,rest=_objectWithoutPropertiesLoose(props,_excluded2);var _useState3=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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,dataClassName=allData.className,dataError=allData.error,dataIsMissing=allData.isMissing;function toSafeText(value){if(value===null){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(_extends({},gjsModel.get("attributes"))),attributes=_useState4[0],setAttributes=_useState4[1];useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(function(prevData){return _extends({},prevData,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=safeFooterContent?"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):"";// eslint-disable-next-line no-console
|
|
7
|
+
console.log({footerIcon:footerIcon,footerIconText:footerIconText,safeBodyContent:safeBodyContent,safeHeaderContent:safeHeaderContent,safeFooterContent:safeFooterContent,isLoading:isLoading,hasError:hasError,hasMissing:hasMissing});function getCardContent(){if(isLoading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}var showEmpty=hasError||hasMissing||!safeBodyContent;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:cn(mergedFooterClassName),children:[(footerIconText||"").trim()&&/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIconText}),safeFooterContent||""]})]})}return/*#__PURE__*/_jsxs(Card,_extends({},rest,{className:mergedCardClassName+" relative",children:[getCardContent(),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable})]}))}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(_ref){var name=_ref.name,percent=_ref.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,{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(_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||[];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(_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:[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(_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,_props$performInterac2=props.performInteraction,performInteraction=_props$performInterac2===void 0?function(){return Promise.resolve({})}:_props$performInterac2,rest=_objectWithoutPropertiesLoose(props,_excluded3);var _useState5=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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(){var handlePropsChange=function handlePropsChange(){var newProps=gjsModel.get("componentProps");setAllData(function(prevData){return _extends({},prevData,newProps)})};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)}};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 safeChartData=Array.isArray(chartData)?chartData:[];var colors=getNColors(safeChartData.length);for(var i=0;i<safeChartData.length;i++){var data=safeChartData[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 width=undefined;var totalDataPoints=0;// Helper function to get responsive config
|
|
7
8
|
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||[];var _safeChartData=Array.isArray(chartData)?chartData:[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];totalDataPoints=_safeChartData.length*Math.max(1,safeDataKeys.length);if(totalDataPoints>15){width=totalDataPoints*20+safeDataKeys.length*8*_safeChartData.length+_safeChartData.length*15;config.chartUi={barCategoryGap:"10%",width:width}}else{config.chartUi={}}}else if(chartType==="line"){config.dataKeys=config.dataKeys||[];var _safeChartData2=Array.isArray(chartData)?chartData:[];totalDataPoints=_safeChartData2.length;if(totalDataPoints>15){width=Math.max(800,totalDataPoints*20);config.chartUi={width:width}}else{config.chartUi={}}}var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=(attributes.interactionApiInProgress||attributes.loading)&&!hasError&&!hasMissing;var chartUi=isLoading?/*#__PURE__*/_jsx(ChartLoader,{}):hasError||hasMissing||!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 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",contentEditable:false,className:"px-6",children:chartUi}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable})]})}export function renderTable(props){var _props$isEditable4=props.isEditable,isEditable=_props$isEditable4===void 0?false:_props$isEditable4,gjsModel=props.gjsModel,_props$performInterac3=props.performInteraction,performInteraction=_props$performInterac3===void 0?function(){}:_props$performInterac3,rest=_objectWithoutPropertiesLoose(props,_excluded4);var _useState8=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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$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,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(){gjsModel.on("change:componentProps",function(){setAllData(function(prevData){return _extends({},prevData,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 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,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})]})}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 _props$isEditable5=props.isEditable,isEditable=_props$isEditable5===void 0?false:_props$isEditable5,gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded5);var _useState12=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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(function(prevData){return _extends({},prevData,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]"}}};var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=attributes.loading&&!hasError&&!hasMissing;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:"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})]}))}if(!allData.isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},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})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em] relative"},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})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable})]}))}export function renderButton(props){var _props$
|
|
9
|
+
return _extends({},config,{chartUi:{}})}return config};if(chartType==="bar"){config.dataKeys=config.dataKeys||[];var _safeChartData=Array.isArray(chartData)?chartData:[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];totalDataPoints=_safeChartData.length*Math.max(1,safeDataKeys.length);if(totalDataPoints>15){width=totalDataPoints*20+safeDataKeys.length*8*_safeChartData.length+_safeChartData.length*15;config.chartUi={barCategoryGap:"10%",width:width}}else{config.chartUi={}}}else if(chartType==="line"){config.dataKeys=config.dataKeys||[];var _safeChartData2=Array.isArray(chartData)?chartData:[];totalDataPoints=_safeChartData2.length;if(totalDataPoints>15){width=Math.max(800,totalDataPoints*20);config.chartUi={width:width}}else{config.chartUi={}}}var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=(attributes.interactionApiInProgress||attributes.loading)&&!hasError&&!hasMissing;var chartUi=isLoading?/*#__PURE__*/_jsx(ChartLoader,{}):hasError||hasMissing||!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 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",contentEditable:false,className:"px-6",children:chartUi}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable})]})}export function renderTable(props){var _props$isEditable3=props.isEditable,isEditable=_props$isEditable3===void 0?false:_props$isEditable3,gjsModel=props.gjsModel,_props$performInterac3=props.performInteraction,performInteraction=_props$performInterac3===void 0?function(){}:_props$performInterac3,rest=_objectWithoutPropertiesLoose(props,_excluded4);var _useState8=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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$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,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(){gjsModel.on("change:componentProps",function(){setAllData(function(prevData){return _extends({},prevData,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 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,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})]})}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 _props$isEditable4=props.isEditable,isEditable=_props$isEditable4===void 0?false:_props$isEditable4,gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded5);var _useState12=useState(_extends({},filterPlaceholders(gjsModel.get("componentProps")),filterPlaceholders(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(function(prevData){return _extends({},prevData,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
|
|
10
|
+
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]"}}};var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=attributes.loading&&!hasError&&!hasMissing;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:"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})]}))}if(!allData.isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},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})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em] relative"},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})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable})]}))}export function renderButton(props){var _props$isEditable5=props.isEditable,isEditable=_props$isEditable5===void 0?false:_props$isEditable5,gjsModel=props.gjsModel,_props$performInterac4=props.performInteraction,performInteraction=_props$performInterac4===void 0?function(){}:_props$performInterac4;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:_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)})};export function getRenderers(){return{ActionCard:renderActionCardWithWrapper,Button:renderButtonWithWrapper,Card:renderCardWithWrapper,Chart:renderChartWithWrapper,Filter:renderFilterWithWrapper,Markdown:renderMarkdownWithWrapper,Search:renderSearchWithWrapper,Table:renderTableWithWrapper,Tabs:renderTabWithWrapper}}
|
|
10
11
|
//# sourceMappingURL=render-components.js.map
|