@peak-ai/canvas 1.4.38 → 1.4.39-rc.3

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.
@@ -1,4 +1,4 @@
1
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,ChevronUp}from"lucide-react";import{formatQueryHeading}from"./query-heading-formatter";import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";function CopyButton(_ref){var onClick=_ref.onClick,isCopied=_ref.isCopied,_ref$variant=_ref.variant,variant=_ref$variant===void 0?"default":_ref$variant;var baseClasses="flex items-center gap-1 px-2 py-1 text-xs border rounded transition-colors";var variantClasses=variant==="light"?"bg-gray-50 border-gray-300 hover:bg-gray-100":"bg-gray-100 border-gray-300 hover:bg-gray-200";return/*#__PURE__*/_jsx("button",{onClick:onClick,className:baseClasses+" "+variantClasses,type:"button",children:isCopied?/*#__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"})]})})}function ContentText(_ref2){var children=_ref2.children,_ref2$hasOverflowHand=_ref2.hasOverflowHandling,hasOverflowHandling=_ref2$hasOverflowHand===void 0?true:_ref2$hasOverflowHand;var overflowClasses=hasOverflowHandling?"overflow-hidden break-words":"";return/*#__PURE__*/_jsx("pre",{className:"whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0 "+overflowClasses,children:children})}function ContentBlock(_ref3){var title=_ref3.title,children=_ref3.children,copyContent=_ref3.copyContent,copyId=_ref3.copyId,copied=_ref3.copied,onCopy=_ref3.onCopy,_ref3$variant=_ref3.variant,variant=_ref3$variant===void 0?"bordered":_ref3$variant,_ref3$copyButtonVaria=_ref3.copyButtonVariant,copyButtonVariant=_ref3$copyButtonVaria===void 0?"default":_ref3$copyButtonVaria;var containerClasses=variant==="bordered"?"rounded-lg p-3":"bg-white border border-gray-200 rounded-lg p-4";var containerStyle=variant==="bordered"?{border:"1px solid #E9EAF5"}:{};var titleClasses=variant==="bordered"?"text-sm font-medium text-gray-600":"font-semibold text-sm text-gray-500 m-0";return/*#__PURE__*/_jsxs("div",{className:containerClasses,style:containerStyle,children:[/*#__PURE__*/_jsxs("div",{className:"flex justify-between items-start mb-2",children:[/*#__PURE__*/_jsx("span",{className:titleClasses,children:title}),copyContent&&/*#__PURE__*/_jsx(CopyButton,{onClick:function onClick(){return onCopy(copyContent,copyId)},isCopied:copied[copyId]||false,variant:copyButtonVariant})]}),children]})}export function QueryDetailsModal(_ref4){var isOpen=_ref4.isOpen,onClose=_ref4.onClose,isLoading=_ref4.isLoading,error=_ref4.error,sqlQuery=_ref4.sqlQuery,_ref4$queryHeadings=_ref4.queryHeadings,queryHeadings=_ref4$queryHeadings===void 0?[]:_ref4$queryHeadings,_ref4$tableButtonExpl=_ref4.tableButtonExplanations,tableButtonExplanations=_ref4$tableButtonExpl===void 0?[]:_ref4$tableButtonExpl,onRetry=_ref4.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,_t;return _regeneratorRuntime.wrap(function(_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=1;break}return _context.abrupt("return");case 1:id=copyId||"main";_context.prev=2;_context.next=3;return navigator.clipboard.writeText(textToCopy);case 3: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=5;break;case 4:_context.prev=4;_t=_context["catch"](2);case 5:case"end":return _context.stop()}},_callee,null,[[2,4]])}));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}function hasValidJsonBody(jsonBody){return jsonBody!==null&&jsonBody!==undefined&&jsonBody!==""}function hasValidFormFields(formFields){return formFields!==null&&formFields!==undefined&&Object.keys(formFields||{}).length>0}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__*/_jsxs("div",{className:"flex items-center",children:[/*#__PURE__*/_jsx("button",{onClick:function onClick(){return toggleButtonExpansion(index)},className:button.buttonClassName||"flex items-center justify-center px-3 rounded text-xs font-medium",style:_extends({height:"35px",width:"fit-content",minWidth:"fit-content",backgroundColor:(_button$buttonStyle=button.buttonStyle)==null?void 0:_button$buttonStyle.backgroundColor,color:(_button$buttonStyle2=button.buttonStyle)==null?void 0:_button$buttonStyle2.color,border:(_button$buttonStyle3=button.buttonStyle)==null?void 0:_button$buttonStyle3.border},button.buttonStyle||{},button.buttonStyle||{},{display:"flex",alignItems:"center",justifyContent:"center"}),children:button.action}),/*#__PURE__*/_jsx("div",{className:"ml-3 flex flex-col",children:button.operationSummary&&/*#__PURE__*/_jsx("span",{className:"text-xs text-gray-700 font-medium",children:button.operationSummary})})]}),expandedButtons[index]?/*#__PURE__*/_jsx(ChevronUp,{className:"w-4 h-4 text-gray-500 transition-transform cursor-pointer",onClick:function onClick(){return toggleButtonExpansion(index)}}):/*#__PURE__*/_jsx(ChevronDown,{className:"w-4 h-4 text-gray-500 transition-transform cursor-pointer",onClick:function onClick(){return toggleButtonExpansion(index)}})]}),expandedButtons[index]&&/*#__PURE__*/_jsx("div",{className:"px-4 pb-3 border-t border-gray-200",children:/*#__PURE__*/_jsxs("div",{className:"mt-2 space-y-3",children:[button.operationDescription&&/*#__PURE__*/_jsx(ContentBlock,{title:"Description",copyId:"description-"+index,copied:copied,onCopy:copyToClipboard,variant:"bordered",children:/*#__PURE__*/_jsx(ContentText,{children:button.operationDescription})}),(button.requestUrl||button.explanation)&&/*#__PURE__*/_jsx(ContentBlock,{title:"URL",copyContent:button.requestUrl||button.explanation,copyId:"url-"+index,copied:copied,onCopy:copyToClipboard,variant:"bordered",children:/*#__PURE__*/_jsx(ContentText,{children:button.requestUrl||button.explanation})}),(hasValidJsonBody(button.jsonBody)||hasValidFormFields(button.formFields))&&/*#__PURE__*/_jsx(ContentBlock,{title:"Payload",copyContent:JSON.stringify(hasValidJsonBody(button.jsonBody)?button.jsonBody:button.formFields,null,2),copyId:"payload-"+index,copied:copied,onCopy:copyToClipboard,variant:"bordered",children:/*#__PURE__*/_jsx(ContentText,{children:hasValidJsonBody(button.jsonBody)?JSON.stringify(button.jsonBody,null,2):JSON.stringify(button.formFields,null,2)})})]})})]},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
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}function hasValidJsonBody(jsonBody){return jsonBody!==null&&jsonBody!==undefined&&jsonBody!==""}function hasValidFormFields(formFields){return formFields!==null&&formFields!==undefined&&Object.keys(formFields||{}).length>0}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__*/_jsxs("div",{className:"flex items-center",children:[/*#__PURE__*/_jsx("button",{onClick:function onClick(){return toggleButtonExpansion(index)},className:button.buttonClassName||"flex items-center justify-center px-3 rounded text-xs font-medium",style:_extends({height:"35px",width:"fit-content",minWidth:"fit-content",backgroundColor:(_button$buttonStyle=button.buttonStyle)==null?void 0:_button$buttonStyle.backgroundColor,color:(_button$buttonStyle2=button.buttonStyle)==null?void 0:_button$buttonStyle2.color,border:(_button$buttonStyle3=button.buttonStyle)==null?void 0:_button$buttonStyle3.border},button.buttonStyle||{},button.buttonStyle||{},{display:"flex",alignItems:"center",justifyContent:"center"}),children:button.action}),/*#__PURE__*/_jsx("div",{className:"ml-3 flex flex-col",children:button.operationSummary&&/*#__PURE__*/_jsx("span",{className:"text-xs text-gray-700 font-medium",children:button.operationSummary})})]}),expandedButtons[index]?/*#__PURE__*/_jsx(ChevronUp,{className:"w-4 h-4 text-gray-500 transition-transform cursor-pointer",onClick:function onClick(){return toggleButtonExpansion(index)}}):/*#__PURE__*/_jsx(ChevronDown,{className:"w-4 h-4 text-gray-500 transition-transform cursor-pointer",onClick:function onClick(){return toggleButtonExpansion(index)}})]}),expandedButtons[index]&&/*#__PURE__*/_jsx("div",{className:"px-4 pb-3 border-t border-gray-200",children:/*#__PURE__*/_jsxs("div",{className:"mt-2 space-y-3",children:[button.operationDescription&&/*#__PURE__*/_jsx(ContentBlock,{title:"Description",copyId:"description-"+index,copied:copied,onCopy:copyToClipboard,variant:"bordered",children:/*#__PURE__*/_jsx(ContentText,{children:button.operationDescription})}),(button.requestUrl||button.explanation)&&/*#__PURE__*/_jsx(ContentBlock,{title:"URL",copyContent:button.requestUrl||button.explanation,copyId:"url-"+index,copied:copied,onCopy:copyToClipboard,variant:"bordered",children:/*#__PURE__*/_jsx(ContentText,{children:button.requestUrl||button.explanation})}),(hasValidJsonBody(button.jsonBody)||hasValidFormFields(button.formFields))&&/*#__PURE__*/_jsx(ContentBlock,{title:"Payload",copyContent:JSON.stringify(hasValidJsonBody(button.jsonBody)?button.jsonBody:button.formFields,null,2),copyId:"payload-"+index,copied:copied,onCopy:copyToClipboard,variant:"bordered",children:/*#__PURE__*/_jsx(ContentText,{children:hasValidJsonBody(button.jsonBody)?JSON.stringify(button.jsonBody,null,2):JSON.stringify(button.formFields,null,2)})})]})})]},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
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){var rawHeading=queryHeadings[index]||"Query "+(index+1);var heading=formatQueryHeading(rawHeading);return/*#__PURE__*/_jsx(ContentBlock,{title:heading,copyContent:query,copyId:"query-"+index,copied:copied,onCopy:copyToClipboard,variant:"default",copyButtonVariant:"light",children:/*#__PURE__*/_jsx(ContentText,{hasOverflowHandling:false,children:query})},index)}),renderTableButtonExplanations()]})}return/*#__PURE__*/_jsxs("div",{className:"p-6 space-y-4",children:[/*#__PURE__*/_jsx(ContentBlock,{title:formatQueryHeading(queryHeadings[0]||"Query details"),copyContent:typeof sqlQuery==="string"?sqlQuery:"",copyId:"single",copied:copied,onCopy:copyToClipboard,variant:"default",copyButtonVariant:"light",children:/*#__PURE__*/_jsx(ContentText,{hasOverflowHandling:false,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","ChevronUp","formatQueryHeading","jsx","_jsx","Fragment","_Fragment","jsxs","_jsxs","CopyButton","_ref","onClick","isCopied","_ref$variant","variant","baseClasses","variantClasses","className","type","children","ContentText","_ref2","_ref2$hasOverflowHand","hasOverflowHandling","overflowClasses","ContentBlock","_ref3","title","copyContent","copyId","copied","onCopy","_ref3$variant","_ref3$copyButtonVaria","copyButtonVariant","containerClasses","containerStyle","border","titleClasses","style","QueryDetailsModal","_ref4","isOpen","onClose","isLoading","error","sqlQuery","_ref4$queryHeadings","queryHeadings","_ref4$tableButtonExpl","tableButtonExplanations","onRetry","_useState","setCopied","_useState2","expandedButtons","setExpandedButtons","copyToClipboard","_x","_x2","_copyToClipboard","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","queryToCopy","textToCopy","id","_t","wrap","_context","prev","next","Array","isArray","filter","q","join","abrupt","navigator","clipboard","writeText","_extends3","_extends","setTimeout","_extends4","stop","toggleButtonExpansion","buttonIndex","_extends2","renderTableButtonExplanations","length","hasValidJsonBody","jsonBody","undefined","hasValidFormFields","formFields","Object","keys","map","button","index","_button$buttonStyle","_button$buttonStyle2","_button$buttonStyle3","buttonClassName","height","width","minWidth","backgroundColor","buttonStyle","color","display","alignItems","justifyContent","action","operationSummary","operationDescription","requestUrl","explanation","JSON","stringify","renderModalContent","query","trim","rawHeading","heading"],"sources":["../../../src/plugins/helpers/query-details-modal.tsx"],"sourcesContent":["import React, { useState, useEffect } from 'react';\nimport { CustomModal } from './custom-modal';\nimport { Copy, Check, ChevronDown, ChevronUp, X } from 'lucide-react';\nimport { formatQueryHeading } from './query-heading-formatter';\n\ntype CopyButtonProps = {\n onClick: () => void;\n isCopied: boolean;\n variant?: 'default' | 'light';\n};\n\nfunction CopyButton({ onClick, isCopied, variant = 'default' }: CopyButtonProps) {\n const baseClasses = \"flex items-center gap-1 px-2 py-1 text-xs border rounded transition-colors\";\n const variantClasses = variant === 'light' \n ? \"bg-gray-50 border-gray-300 hover:bg-gray-100\"\n : \"bg-gray-100 border-gray-300 hover:bg-gray-200\";\n\n return (\n <button\n onClick={onClick}\n className={`${baseClasses} ${variantClasses}`}\n type=\"button\"\n >\n {isCopied ? (\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 );\n}\n\ntype ContentTextProps = {\n children: React.ReactNode;\n hasOverflowHandling?: boolean;\n};\n\nfunction ContentText({ children, hasOverflowHandling = true }: ContentTextProps) {\n const overflowClasses = hasOverflowHandling ? \"overflow-hidden break-words\" : \"\";\n\n return (\n <pre className={`whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0 ${overflowClasses}`}>\n {children}\n </pre>\n );\n}\n\ntype ContentBlockProps = {\n title: string;\n children: React.ReactNode;\n copyContent?: string;\n copyId: string;\n copied: Record<string, boolean>;\n onCopy: (content: string, id: string) => void;\n variant?: 'default' | 'bordered';\n copyButtonVariant?: 'default' | 'light';\n};\n\nfunction ContentBlock({ \n title, \n children, \n copyContent, \n copyId, \n copied, \n onCopy,\n variant = 'bordered',\n copyButtonVariant = 'default'\n}: ContentBlockProps) {\n const containerClasses = variant === 'bordered' \n ? \"rounded-lg p-3\"\n : \"bg-white border border-gray-200 rounded-lg p-4\";\n \n const containerStyle = variant === 'bordered' \n ? { border: '1px solid #E9EAF5' }\n : {};\n\n const titleClasses = variant === 'bordered'\n ? \"text-sm font-medium text-gray-600\"\n : \"font-semibold text-sm text-gray-500 m-0\";\n\n return (\n <div className={containerClasses} style={containerStyle}>\n <div className=\"flex justify-between items-start mb-2\">\n <span className={titleClasses}>{title}</span>\n {copyContent && (\n <CopyButton\n onClick={() => onCopy(copyContent, copyId)}\n isCopied={copied[copyId] || false}\n variant={copyButtonVariant}\n />\n )}\n </div>\n {children}\n </div>\n );\n}\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 operationSummary?: string,\n operationDescription?: string,\n buttonClassName?: string, \n buttonStyle?: Record<string, unknown>,\n formFields?: Record<string, unknown>;\n jsonBody?: unknown;\n requestUrl?: string;\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 function hasValidJsonBody(jsonBody: unknown): boolean {\n return jsonBody !== null && jsonBody !== undefined && jsonBody !== '';\n }\n\n function hasValidFormFields(formFields: Record<string, unknown> | undefined): boolean {\n return formFields !== null && formFields !== undefined && Object.keys(formFields || {}).length > 0;\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 justify-center px-3 rounded text-xs font-medium\"}\n style={{\n height: '35px',\n width: 'fit-content',\n minWidth: 'fit-content',\n backgroundColor: (button.buttonStyle?.backgroundColor as string),\n color: (button.buttonStyle?.color as string),\n border: (button.buttonStyle?.border as string),\n ...(button.buttonStyle as React.CSSProperties || {})\n , ...button.buttonStyle as React.CSSProperties || {},\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center'\n }}\n >\n {button.action}\n </button>\n <div className=\"ml-3 flex flex-col\">\n {button.operationSummary && (\n <span className=\"text-xs text-gray-700 font-medium\">\n {button.operationSummary}\n </span>\n )}\n </div>\n </div>\n {expandedButtons[index] ? (\n <ChevronUp \n className=\"w-4 h-4 text-gray-500 transition-transform cursor-pointer\"\n onClick={() => toggleButtonExpansion(index)}\n />\n ) : (\n <ChevronDown \n className=\"w-4 h-4 text-gray-500 transition-transform cursor-pointer\"\n onClick={() => toggleButtonExpansion(index)}\n />\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 {/* Description Block */}\n {button.operationDescription && (\n <ContentBlock\n title=\"Description\"\n copyId={`description-${index}`}\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"bordered\"\n >\n <ContentText>\n {button.operationDescription}\n </ContentText>\n </ContentBlock>\n )}\n\n {(button.requestUrl || button.explanation) && (\n <ContentBlock\n title=\"URL\"\n copyContent={button.requestUrl || button.explanation}\n copyId={`url-${index}`}\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"bordered\"\n >\n <ContentText>\n {button.requestUrl || button.explanation}\n </ContentText>\n </ContentBlock>\n )}\n \n {(hasValidJsonBody(button.jsonBody) || hasValidFormFields(button.formFields)) && (\n <ContentBlock\n title=\"Payload\"\n copyContent={JSON.stringify(\n hasValidJsonBody(button.jsonBody) ? button.jsonBody : button.formFields, \n null, \n 2\n )}\n copyId={`payload-${index}`}\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"bordered\"\n >\n <ContentText>\n {hasValidJsonBody(button.jsonBody) \n ? JSON.stringify(button.jsonBody, null, 2)\n : JSON.stringify(button.formFields, null, 2)}\n </ContentText>\n </ContentBlock>\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 <ContentBlock\n key={index}\n title={heading}\n copyContent={query}\n copyId={`query-${index}`}\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"default\"\n copyButtonVariant=\"light\"\n >\n <ContentText hasOverflowHandling={false}>\n {query}\n </ContentText>\n </ContentBlock>\n );\n })}\n {renderTableButtonExplanations()}\n </div>\n );\n }\n\n return (\n <div className=\"p-6 space-y-4\">\n <ContentBlock\n title={formatQueryHeading(queryHeadings[0] || \"Query details\")}\n copyContent={typeof sqlQuery === 'string' ? sqlQuery : ''}\n copyId=\"single\"\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"default\"\n copyButtonVariant=\"light\"\n >\n <ContentText hasOverflowHandling={false}>\n {sqlQuery}\n </ContentText>\n </ContentBlock>\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,CAAEC,SAAS,KAAW,cAAc,CACrE,OAASC,kBAAkB,KAAQ,2BAA2B,CAAC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,QAAA,IAAAC,SAAA,CAAAC,IAAA,IAAAC,KAAA,yBAQ/D,QAAS,CAAAC,UAAUA,CAAAC,IAAA,CAA8D,IAA3D,CAAAC,OAAO,CAAAD,IAAA,CAAPC,OAAO,CAAEC,QAAQ,CAAAF,IAAA,CAARE,QAAQ,CAAAC,YAAA,CAAAH,IAAA,CAAEI,OAAO,CAAPA,OAAO,CAAAD,YAAA,UAAG,SAAS,CAAAA,YAAA,CAC1D,GAAM,CAAAE,WAAW,CAAG,4EAA4E,CAChG,GAAM,CAAAC,cAAc,CAAGF,OAAO,GAAK,OAAO,CACtC,8CAA8C,CAC9C,+CAA+C,CAEnD,mBACEV,IAAA,WACEO,OAAO,CAAEA,OAAQ,CACjBM,SAAS,CAAKF,WAAW,KAAIC,cAAiB,CAC9CE,IAAI,CAAC,QAAQ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AAApF,iBAAiB","ignoreList":[]}
1
+ {"version":3,"file":"query-details-modal.js","names":["React","useState","useEffect","CustomModal","Copy","Check","ChevronDown","ChevronUp","formatQueryHeading","jsx","_jsx","Fragment","_Fragment","jsxs","_jsxs","CopyButton","_ref","onClick","isCopied","_ref$variant","variant","baseClasses","variantClasses","className","type","children","ContentText","_ref2","_ref2$hasOverflowHand","hasOverflowHandling","overflowClasses","ContentBlock","_ref3","title","copyContent","copyId","copied","onCopy","_ref3$variant","_ref3$copyButtonVaria","copyButtonVariant","containerClasses","containerStyle","border","titleClasses","style","QueryDetailsModal","_ref4","isOpen","onClose","isLoading","error","sqlQuery","_ref4$queryHeadings","queryHeadings","_ref4$tableButtonExpl","tableButtonExplanations","onRetry","_useState","setCopied","_useState2","expandedButtons","setExpandedButtons","copyToClipboard","_x","_x2","_copyToClipboard","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","queryToCopy","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","hasValidFormFields","formFields","Object","keys","map","button","index","_button$buttonStyle","_button$buttonStyle2","_button$buttonStyle3","buttonClassName","height","width","minWidth","backgroundColor","buttonStyle","color","display","alignItems","justifyContent","action","operationSummary","operationDescription","requestUrl","explanation","JSON","stringify","renderModalContent","query","trim","rawHeading","heading"],"sources":["../../../src/plugins/helpers/query-details-modal.tsx"],"sourcesContent":["import React, { useState, useEffect } from 'react';\nimport { CustomModal } from './custom-modal';\nimport { Copy, Check, ChevronDown, ChevronUp, X } from 'lucide-react';\nimport { formatQueryHeading } from './query-heading-formatter';\n\ntype CopyButtonProps = {\n onClick: () => void;\n isCopied: boolean;\n variant?: 'default' | 'light';\n};\n\nfunction CopyButton({ onClick, isCopied, variant = 'default' }: CopyButtonProps) {\n const baseClasses = \"flex items-center gap-1 px-2 py-1 text-xs border rounded transition-colors\";\n const variantClasses = variant === 'light' \n ? \"bg-gray-50 border-gray-300 hover:bg-gray-100\"\n : \"bg-gray-100 border-gray-300 hover:bg-gray-200\";\n\n return (\n <button\n onClick={onClick}\n className={`${baseClasses} ${variantClasses}`}\n type=\"button\"\n >\n {isCopied ? (\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 );\n}\n\ntype ContentTextProps = {\n children: React.ReactNode;\n hasOverflowHandling?: boolean;\n};\n\nfunction ContentText({ children, hasOverflowHandling = true }: ContentTextProps) {\n const overflowClasses = hasOverflowHandling ? \"overflow-hidden break-words\" : \"\";\n\n return (\n <pre className={`whitespace-pre-wrap leading-relaxed text-xs text-gray-700 m-0 p-0 ${overflowClasses}`}>\n {children}\n </pre>\n );\n}\n\ntype ContentBlockProps = {\n title: string;\n children: React.ReactNode;\n copyContent?: string;\n copyId: string;\n copied: Record<string, boolean>;\n onCopy: (content: string, id: string) => void;\n variant?: 'default' | 'bordered';\n copyButtonVariant?: 'default' | 'light';\n};\n\nfunction ContentBlock({ \n title, \n children, \n copyContent, \n copyId, \n copied, \n onCopy,\n variant = 'bordered',\n copyButtonVariant = 'default'\n}: ContentBlockProps) {\n const containerClasses = variant === 'bordered' \n ? \"rounded-lg p-3\"\n : \"bg-white border border-gray-200 rounded-lg p-4\";\n \n const containerStyle = variant === 'bordered' \n ? { border: '1px solid #E9EAF5' }\n : {};\n\n const titleClasses = variant === 'bordered'\n ? \"text-sm font-medium text-gray-600\"\n : \"font-semibold text-sm text-gray-500 m-0\";\n\n return (\n <div className={containerClasses} style={containerStyle}>\n <div className=\"flex justify-between items-start mb-2\">\n <span className={titleClasses}>{title}</span>\n {copyContent && (\n <CopyButton\n onClick={() => onCopy(copyContent, copyId)}\n isCopied={copied[copyId] || false}\n variant={copyButtonVariant}\n />\n )}\n </div>\n {children}\n </div>\n );\n}\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 operationSummary?: string,\n operationDescription?: string,\n buttonClassName?: string, \n buttonStyle?: Record<string, unknown>,\n formFields?: Record<string, unknown>;\n jsonBody?: unknown;\n requestUrl?: string;\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 function hasValidJsonBody(jsonBody: unknown): boolean {\n return jsonBody !== null && jsonBody !== undefined && jsonBody !== '';\n }\n\n function hasValidFormFields(formFields: Record<string, unknown> | undefined): boolean {\n return formFields !== null && formFields !== undefined && Object.keys(formFields || {}).length > 0;\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 justify-center px-3 rounded text-xs font-medium\"}\n style={{\n height: '35px',\n width: 'fit-content',\n minWidth: 'fit-content',\n backgroundColor: (button.buttonStyle?.backgroundColor as string),\n color: (button.buttonStyle?.color as string),\n border: (button.buttonStyle?.border as string),\n ...(button.buttonStyle as React.CSSProperties || {})\n , ...button.buttonStyle as React.CSSProperties || {},\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center'\n }}\n >\n {button.action}\n </button>\n <div className=\"ml-3 flex flex-col\">\n {button.operationSummary && (\n <span className=\"text-xs text-gray-700 font-medium\">\n {button.operationSummary}\n </span>\n )}\n </div>\n </div>\n {expandedButtons[index] ? (\n <ChevronUp \n className=\"w-4 h-4 text-gray-500 transition-transform cursor-pointer\"\n onClick={() => toggleButtonExpansion(index)}\n />\n ) : (\n <ChevronDown \n className=\"w-4 h-4 text-gray-500 transition-transform cursor-pointer\"\n onClick={() => toggleButtonExpansion(index)}\n />\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 {/* Description Block */}\n {button.operationDescription && (\n <ContentBlock\n title=\"Description\"\n copyId={`description-${index}`}\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"bordered\"\n >\n <ContentText>\n {button.operationDescription}\n </ContentText>\n </ContentBlock>\n )}\n\n {(button.requestUrl || button.explanation) && (\n <ContentBlock\n title=\"URL\"\n copyContent={button.requestUrl || button.explanation}\n copyId={`url-${index}`}\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"bordered\"\n >\n <ContentText>\n {button.requestUrl || button.explanation}\n </ContentText>\n </ContentBlock>\n )}\n \n {(hasValidJsonBody(button.jsonBody) || hasValidFormFields(button.formFields)) && (\n <ContentBlock\n title=\"Payload\"\n copyContent={JSON.stringify(\n hasValidJsonBody(button.jsonBody) ? button.jsonBody : button.formFields, \n null, \n 2\n )}\n copyId={`payload-${index}`}\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"bordered\"\n >\n <ContentText>\n {hasValidJsonBody(button.jsonBody) \n ? JSON.stringify(button.jsonBody, null, 2)\n : JSON.stringify(button.formFields, null, 2)}\n </ContentText>\n </ContentBlock>\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 <ContentBlock\n key={index}\n title={heading}\n copyContent={query}\n copyId={`query-${index}`}\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"default\"\n copyButtonVariant=\"light\"\n >\n <ContentText hasOverflowHandling={false}>\n {query}\n </ContentText>\n </ContentBlock>\n );\n })}\n {renderTableButtonExplanations()}\n </div>\n );\n }\n\n return (\n <div className=\"p-6 space-y-4\">\n <ContentBlock\n title={formatQueryHeading(queryHeadings[0] || \"Query details\")}\n copyContent={typeof sqlQuery === 'string' ? sqlQuery : ''}\n copyId=\"single\"\n copied={copied}\n onCopy={copyToClipboard}\n variant=\"default\"\n copyButtonVariant=\"light\"\n >\n <ContentText hasOverflowHandling={false}>\n {sqlQuery}\n </ContentText>\n </ContentBlock>\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,CAAEC,SAAS,KAAW,cAAc,CACrE,OAASC,kBAAkB,KAAQ,2BAA2B,CAAC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,QAAA,IAAAC,SAAA,CAAAC,IAAA,IAAAC,KAAA,yBAQ/D,QAAS,CAAAC,UAAUA,CAAAC,IAAA,CAA8D,IAA3D,CAAAC,OAAO,CAAAD,IAAA,CAAPC,OAAO,CAAEC,QAAQ,CAAAF,IAAA,CAARE,QAAQ,CAAAC,YAAA,CAAAH,IAAA,CAAEI,OAAO,CAAPA,OAAO,CAAAD,YAAA,UAAG,SAAS,CAAAA,YAAA,CAC1D,GAAM,CAAAE,WAAW,CAA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AA6B,CAAC,CAAC,EAC7B,CAEX,CAEA,mBACEzF,IAAA,CAACP,WAAW,EACV6C,MAAM,CAAEA,MAAO,CACfC,OAAO,CAAEA,OAAQ,CACjBhB,KAAK,CAAC,iCAAiC,CAAAR,QAAA,CAEtC0G,kBAAkB,CAAC,CAAC,CACV,CAEjB,CAEA,cAAe,CAAArF,iBAAiB","ignoreList":[]}
@@ -1,13 +1,15 @@
1
- import _asyncToGenerator from"@babel/runtime/helpers/asyncToGenerator";import _extends from"@babel/runtime/helpers/extends";import _objectWithoutPropertiesLoose from"@babel/runtime/helpers/objectWithoutPropertiesLoose";var _excluded=["gjsModel"],_excluded2=["gjsModel","performInteraction"],_excluded3=["gjsModel","performInteraction"],_excluded4=["gjsModel","performInteraction"],_excluded5=["gjsModel"];import _regeneratorRuntime from"@babel/runtime/regenerator";function _createForOfIteratorHelperLoose(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}/* eslint-disable no-nested-ternary *//* eslint-disable @typescript-eslint/ban-ts-comment *//* eslint-disable func-style *//* eslint-disable @typescript-eslint/no-empty-function *//* eslint-disable func-names *//* eslint-disable @typescript-eslint/no-explicit-any */import chroma from"chroma-js";import React,{useEffect,useState,useMemo,useRef}from"react";import{renderNoDataFallback}from"./extra";import{CircleAlert,TrendingDown,TrendingUp,ShoppingCart,ChartBarBig,Tag,MapPin}from"lucide-react";import{StyledInfoButton}from"./styled-info-button";import{filterPlaceholders}from"../../helpers/filter-placeholder";import{theme}from"@peak-ai/ais-components/theme";import Markdown from"markdown-to-jsx";import{Bar,BarChart,CartesianGrid,Legend,Line,LineChart,Pie,PieChart,ResponsiveContainer,XAxis,YAxis}from"recharts/lib";// @ts-ignore
2
- import*as domutil from"recharts/lib/util/DOMUtils";import{TooltipButton}from"../../shadcn/components/ui/button";import{Card,CardContent,CardDescription,CardFooter,CardHeader,CardTitle}from"../../shadcn/components/ui/card";import{ChartContainer,ChartTooltip,ChartTooltipContent}from"../../shadcn/components/ui/chart";import{renderFilter}from"../../shadcn/components/ui/filter";import{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
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","isCreatingAssetFromTemplate"],_excluded2=["gjsModel","performInteraction","isCreatingAssetFromTemplate"],_excluded3=["gjsModel","performInteraction","isCreatingAssetFromTemplate"],_excluded4=["gjsModel","performInteraction","isCreatingAssetFromTemplate"],_excluded5=["gjsModel","isCreatingAssetFromTemplate"];import _regeneratorRuntime from"@babel/runtime/regenerator";function _createForOfIteratorHelperLoose(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}/* eslint-disable no-nested-ternary *//* eslint-disable @typescript-eslint/ban-ts-comment *//* eslint-disable func-style *//* eslint-disable @typescript-eslint/no-empty-function *//* eslint-disable func-names *//* eslint-disable @typescript-eslint/no-explicit-any */import chroma from"chroma-js";import React,{useEffect,useState,useMemo,useCallback,useRef}from"react";import{renderNoDataFallback}from"./extra";import{CircleAlert,TrendingDown,TrendingUp,ShoppingCart,ChartBarBig,Tag,MapPin}from"lucide-react";import{StyledInfoButton}from"./styled-info-button";import{filterPlaceholders}from"../../helpers/filter-placeholder";import{theme}from"@peak-ai/ais-components/theme";import Markdown from"markdown-to-jsx";import{Bar,BarChart,CartesianGrid,Legend,Line,LineChart,Pie,PieChart,Scatter,ScatterChart,XAxis,YAxis,Cell}from"recharts/lib";// @ts-ignore
2
+ import*as domutil from"recharts/lib/util/DOMUtils";import{Group}from"@visx/group";import{scaleBand,scaleLinear}from"@visx/scale";import{AxisBottom,AxisLeft}from"@visx/axis";import{GridRows}from"@visx/grid";import{Circle}from"@visx/shape";import{useTooltip,TooltipWithBounds,defaultStyles}from"@visx/tooltip";import{forceSimulation,forceX,forceY,forceCollide}from"d3-force";import{TooltipButton}from"../../shadcn/components/ui/button";import{Card,CardContent,CardDescription,CardFooter,CardHeader,CardTitle}from"../../shadcn/components/ui/card";import{ChartContainer,ChartTooltip,ChartTooltipContent}from"../../shadcn/components/ui/chart";import{renderFilter}from"../../shadcn/components/ui/filter";import{renderSearch}from"../../shadcn/components/ui/search";import{CardLoader,ChartLoader,MarkdownLoader}from"../../shadcn/components/ui/skeleton";import{Tabs,TabsContent,TabsList,TabsTrigger}from"../../shadcn/components/ui/tabs";import{cn}from"../../shadcn/utils";import{getAffectedComponentsWithLoader}from"../../helpers";import{DataTable}from"./data-table";import{ComponentWrapper}from"../../shadcn/components/ui/error-wrapper";// Monkey-patching the getOffset function to use iframe's window instead of global one
3
3
  // REMEMBER TO UDPATE THIS WHEN recharts IS UPGRADED
4
4
  // @ts-ignore
5
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";domutil.getOffset=function(el){var html=el.ownerDocument.documentElement;var box={top:0,left:0};if(typeof el.getBoundingClientRect!=="undefined"){box=el.getBoundingClientRect()}var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;return{top:box.top+iframeWindow.pageYOffset-html.clientTop,left:box.left+iframeWindow.pageXOffset-html.clientLeft}};var baseColors=[[theme.colors.Blue_100,theme.colors.Blue_30],[theme.colors.Purpley_100,theme.colors.Purpley_30],[theme.colors.Light_Bluish_Green,"#06601b"],[theme.colors.Wild_Strawberry,"#4d001c"]];var iconMap={TrendingUp:/*#__PURE__*/_jsx(TrendingUp,{}),TrendingDown:/*#__PURE__*/_jsx(TrendingDown,{}),ShoppingCart:/*#__PURE__*/_jsx(ShoppingCart,{}),Equalizer:/*#__PURE__*/_jsx(ChartBarBig,{}),Style:/*#__PURE__*/_jsx(Tag,{}),Place:/*#__PURE__*/_jsx(MapPin,{})};function getIconFromString(iconString){if(!iconString){return null}if(iconMap[iconString]){return iconMap[iconString]}var lowerIconString=iconString.toLowerCase();var matchingKey=Object.keys(iconMap).find(function(key){return key.toLowerCase()===lowerIconString});if(matchingKey){return iconMap[matchingKey]}return null}function getNColors(n){var colors=[];var safeBaseColors=Array.isArray(baseColors)?baseColors:[];for(var _iterator=_createForOfIteratorHelperLoose(safeBaseColors),_step;!(_step=_iterator()).done;){var baseColor=_step.value;// eslint-disable-next-line import/no-named-as-default-member
6
- colors.push(chroma.scale(baseColor).mode("lab").colors(n))}function getOneColor(existing){var color=null;do{var base=colors[Math.floor(Math.random()*colors.length)];var selectedColorIndex=Math.floor(Math.random()*base.length);color=base[selectedColorIndex]}while(existing.includes(color));return color}var selectedColors=[];for(var i=0;i<n;i++){selectedColors.push(getOneColor(selectedColors))}return selectedColors}/* TODO: Loader remains */export function renderActionCard(props){var gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded);// Memoize filtered props to avoid re-filtering on every render
7
- var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState=useState(initialData),allData=_useState[0],setAllData=_useState[1];var _allData$headerConten=allData.headerContent,headerContent=_allData$headerConten===void 0?"Default action card title":_allData$headerConten,icon=allData.icon,_allData$bodyContent=allData.bodyContent,bodyContent=_allData$bodyContent===void 0?"Default body content. Click to edit.":_allData$bodyContent;var _useState2=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState2[0],setAttributes=_useState2[1];useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var defaultClasses="text-black p-4 rounded-lg shadow border flex flex-col h-full";return/*#__PURE__*/_jsx(Card,_extends({className:defaultClasses+" relative",style:{backgroundColor:"#f9f9fe"},isEditable:false,contentEditable:false},rest,{children:/*#__PURE__*/_jsx(CardContent,{className:"p-0",isEditable:false,contentEditable:false,children:/*#__PURE__*/_jsx("div",{className:"px-4 py-3",children:/*#__PURE__*/_jsxs("div",{className:"flex items-start flex-col",children:[/*#__PURE__*/_jsxs("div",{className:"flex items-center justify-between w-full",children:[/*#__PURE__*/_jsx("div",{className:"text-xl font-semibold",children:headerContent}),/*#__PURE__*/_jsx("div",{className:"text-5xl ml-2 flex items-center","aria-hidden":"true",children:getIconFromString(icon)})]}),/*#__PURE__*/_jsx("div",{className:"w-full mt-1",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing||!bodyContent?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsx("div",{className:"text-base leading-relaxed",children:bodyContent})})]})})})}))}export function renderCard(props){var _attributes$isEditabl,_attributes$error,_attributes$isMissing;var gjsModel=props.gjsModel,_props$performInterac=props.performInteraction,performInteraction=_props$performInterac===void 0?function(){return Promise.resolve({})}:_props$performInterac,rest=_objectWithoutPropertiesLoose(props,_excluded2);// Memoize filtered props to avoid re-filtering on every render
8
- var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState3=useState(initialData),allData=_useState3[0],setAllData=_useState3[1];var headerContent=allData.headerContent,headerDescription=allData.headerDescription,bodyContent=allData.bodyContent,footerContent=allData.footerContent,footerClass=allData.footerClass,footerIcon=allData.footerIcon,contentMetadata=allData.contentMetadata,contentMetadataClass=allData.contentMetadataClass,dataClassName=allData.className,dataError=allData.error,dataIsMissing=allData.isMissing;function toSafeText(value){if(value===null||value===undefined){return""}return typeof value==="string"?value:JSON.stringify(value)}var safeHeaderContent=toSafeText(headerContent);var safeHeaderDescription=toSafeText(headerDescription);var safeBodyContent=toSafeText(bodyContent);var safeFooterContent=toSafeText(footerContent);var safeContentMetadata=toSafeText(contentMetadata);var _useState4=useState((safeFooterContent==null?void 0:safeFooterContent.length)>0),footerHasContent=_useState4[0],setFooterHasContent=_useState4[1];var _useState5=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState5[0],setAttributes=_useState5[1];var isEditable=(_attributes$isEditabl=attributes.isEditable)!=null?_attributes$isEditabl:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);useEffect(function(){setFooterHasContent((safeFooterContent==null?void 0:safeFooterContent.length)>0)},[safeFooterContent]);var defaultClasses="bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none";var defaultFooterClasses=footerHasContent?"text-sm bg-pink-50 text-pink-900 shadow-sm":"text-sm";var defaultContentMetadataClasses="text-xs";var mergedCardClassName=dataClassName?cn(defaultClasses,dataClassName):defaultClasses;var mergedFooterClassName=footerClass?cn(defaultFooterClasses,footerClass):defaultFooterClasses;var mergedContentMetadataClassName=contentMetadataClass?cn(defaultContentMetadataClasses,contentMetadataClass):defaultContentMetadataClasses;var hasError=Boolean((_attributes$error=attributes==null?void 0:attributes.error)!=null?_attributes$error:dataError);var hasMissing=Boolean((_attributes$isMissing=attributes==null?void 0:attributes.isMissing)!=null?_attributes$isMissing:dataIsMissing);var isLoading=Boolean(((attributes==null?void 0:attributes.interactionApiInProgress)||(attributes==null?void 0:attributes.loading))&&!hasError&&!hasMissing);var footerIconText=typeof footerIcon==="string"?footerIcon:footerIcon&&typeof footerIcon==="object"&&"icon"in footerIcon?String(footerIcon.icon):"";function getCardContent(){if(isLoading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}var showEmpty=hasError||hasMissing||!safeBodyContent;function handleFooterInput(event){var target=event.target;var content=target.textContent||"";var hasContent=content.trim().length>0;setFooterHasContent(hasContent);if(!hasContent){var currentProps=gjsModel.get("componentProps");gjsModel.set("componentProps",_extends({},currentProps,{footerContent:null,footerIcon:null,footerClass:null,isEmptied:true}))}}return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"headerContent",contentEditable:isEditable,className:"text-lg",children:safeHeaderContent}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"headerDescription",contentEditable:isEditable,className:"text-sm",children:safeHeaderDescription})]})})}),showEmpty?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsxs(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-grow",children:[/*#__PURE__*/_jsx("div",{className:"text-3xl font-semibold truncate",children:safeBodyContent}),safeContentMetadata&&/*#__PURE__*/_jsx("div",{className:mergedContentMetadataClassName,style:{color:"#2A44D4"},children:safeContentMetadata})]}),/*#__PURE__*/_jsxs(CardFooter,{"data-slot":"footerContent",contentEditable:isEditable,className:mergedFooterClassName,onInput:handleFooterInput,children:[(footerIconText||"").trim()?/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIconText}):null,safeFooterContent||""]})]})}return/*#__PURE__*/_jsxs(Card,_extends({},rest,{isEditable:false,className:mergedCardClassName+" relative",children:[getCardContent(),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}function 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,barDataKeys.length>1&&{barGap:0},{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:config.xAxis}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(Legend,{align:"left",wrapperStyle:{marginLeft:20}}),barDataKeys.map(function(_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 _attributes$isEditabl2;var gjsModel=props.gjsModel,_props$performInterac2=props.performInteraction,performInteraction=_props$performInterac2===void 0?function(){return Promise.resolve({})}:_props$performInterac2,rest=_objectWithoutPropertiesLoose(props,_excluded3);// Memoize filtered props to avoid re-filtering on every render
9
- var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState6=useState(initialData),allData=_useState6[0],setAllData=_useState6[1];var _useState7=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState7[0],setAttributes=_useState7[1];var isEditable=(_attributes$isEditabl2=attributes.isEditable)!=null?_attributes$isEditabl2:false;var containerRef=useRef(null);var _useState8=useState(0),containerWidth=_useState8[0],setContainerWidth=_useState8[1];useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){var newAttributes=gjsModel.get("attributes");setAttributes(_extends({},newAttributes))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);useEffect(function(){var updateContainerWidth=function updateContainerWidth(){if(containerRef.current){setContainerWidth(containerRef.current.offsetWidth||0)}};var resizeObserver=new ResizeObserver(function(entries){for(var _iterator2=_createForOfIteratorHelperLoose(entries),_step2;!(_step2=_iterator2()).done;){var entry=_step2.value;setContainerWidth(entry.contentRect.width||0)}});updateContainerWidth();var timeoutId=setTimeout(updateContainerWidth,50);if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateContainerWidth);return function(){clearTimeout(timeoutId);resizeObserver.disconnect();window.removeEventListener("resize",updateContainerWidth)}},[]);var _allData$config=allData.config,config=_allData$config===void 0?{}:_allData$config,_allData$chartType=allData.chartType,chartType=_allData$chartType===void 0?"pie":_allData$chartType,_allData$chartData=allData.chartData,chartData=_allData$chartData===void 0?[]:_allData$chartData,className=allData.className,_allData$title=allData.title,title=_allData$title===void 0?"Title":_allData$title,_allData$subTitle=allData.subTitle,subTitle=_allData$subTitle===void 0?"Subtitle":_allData$subTitle;var defaultClasses="aspect-auto h-[250px] w-full";var mergedClasses=className?cn(defaultClasses,className):defaultClasses;if(chartType==="pie"){var safeChartData=Array.isArray(chartData)?chartData:[];var colors=getNColors(safeChartData.length);safeChartData.forEach(function(data,i){if(!data.fill){data.fill=colors[i]}})}else if(!config.color){var safeBaseColors=Array.isArray(baseColors)?baseColors:[];if(safeBaseColors.length>0){config.color=safeBaseColors[Math.floor(Math.random()*safeBaseColors.length)]}}var totalDataPoints=0;if(chartType==="bar"||chartType==="line"){var _safeChartData=Array.isArray(chartData)?chartData:[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];totalDataPoints=chartType==="bar"?_safeChartData.length*Math.max(1,safeDataKeys.length):_safeChartData.length}var getScrollableWidth=function getScrollableWidth(){if(chartType==="line"){return totalDataPoints*20}if(chartType==="bar"){return totalDataPoints*20+(Array.isArray(config.dataKeys)?config.dataKeys.length:0)*8*(Array.isArray(chartData)?chartData.length:0)+(Array.isArray(chartData)?chartData.length:0)*15}return 800};var scrollWidth=getScrollableWidth();var shouldScroll=(chartType==="bar"||chartType==="line")&&totalDataPoints>15&&scrollWidth>containerWidth;var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=(attributes.interactionApiInProgress||attributes.loading)&&!hasError&&!hasMissing;var ChartWrapper=function ChartWrapper(_ref5){var children=_ref5.children;if(shouldScroll){return/*#__PURE__*/_jsx("div",{className:"w-full h-[250px] overflow-x-auto",children:/*#__PURE__*/_jsx("div",{style:{minWidth:scrollWidth+"px",height:"250px"},children:children})})}return/*#__PURE__*/_jsx("div",{className:"w-full h-[250px]",children:children})};var chartUi=isLoading?/*#__PURE__*/_jsx(ChartLoader,{}):hasError||hasMissing||!chartData?renderNoDataFallback():/*#__PURE__*/_jsx(ChartWrapper,{children:/*#__PURE__*/_jsx(ResponsiveContainer,{width:"100%",height:250,children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:config,className:mergedClasses,children:renderChartComponent(chartType,chartData,config)}))})});return/*#__PURE__*/_jsxs(Card,{className:"shadow border mt-2 mb-2 relative",children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{ref:containerRef,"data-slot":"bodyContent",className:"px-6",children:chartUi}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]})}export function renderTable(props){var _attributes$isEditabl3;var gjsModel=props.gjsModel,_props$performInterac3=props.performInteraction,performInteraction=_props$performInterac3===void 0?function(){}:_props$performInterac3,rest=_objectWithoutPropertiesLoose(props,_excluded4);// Memoize filtered props to avoid re-filtering on every render
10
- var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState9=useState(initialData),allData=_useState9[0],setAllData=_useState9[1];var cardRef=useRef(null);var _useState10=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState10[0],setAttributes=_useState10[1];var isEditable=(_attributes$isEditabl3=attributes.isEditable)!=null?_attributes$isEditabl3:false;var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$title2=allData.title,title=_allData$title2===void 0?"Title":_allData$title2,_allData$subTitle2=allData.subTitle,subTitle=_allData$subTitle2===void 0?"Subtitle":_allData$subTitle2,_allData$actions=allData.actions,actions=_allData$actions===void 0?[]:_allData$actions,pagination=allData.pagination;var data=Array.isArray(rawData)?rawData:[];var headerMapper=function(){var cleaned=_extends({},rawHeaderMapper);if("id"in cleaned){delete cleaned.id}if(data.length>0){var dataKeys=Object.keys(data[0]||{});return Object.fromEntries(Object.entries(cleaned).filter(function(_ref6){var key=_ref6[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref8){var _ref7=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref7.sortColumn,sortDirection=_ref7.sortDirection;return sortColumn&&sortDirection?(_ref8={},_ref8[sortColumn]=sortDirection,_ref8):{}}();var _useState11=useState(0),viewportWidth=_useState11[0],setViewportWidth=_useState11[1];var _useState12=useState(250),scrollAreaHeight=_useState12[0],setScrollAreaHeight=_useState12[1];var calculateTableHeight=function calculateTableHeight(tableWidth,rowCount){if(viewportWidth>0){var _gjsModel$collection;var widthRatio=tableWidth/viewportWidth;var baseTableHeight=250;var targetScrollAreaHeight=baseTableHeight;if(widthRatio>=0.8){var headerHeight=48;var rowHeight=40;var calculatedHeight=headerHeight+rowCount*rowHeight;targetScrollAreaHeight=Math.min(calculatedHeight,baseTableHeight)}var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection=gjsModel.collection)==null?void 0:_gjsModel$collection.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(tableElement){var headerElement=tableElement.querySelector("[data-slot=\"card-header\"]");if(headerElement&&headerElement.offsetHeight>0){var actualHeaderHeight=headerElement.offsetHeight;var standardHeaderHeight=58;var heightDifference=actualHeaderHeight-standardHeaderHeight;if(heightDifference>0){targetScrollAreaHeight=targetScrollAreaHeight-heightDifference}}}setScrollAreaHeight(targetScrollAreaHeight)}};useEffect(function(){var updateViewportWidth=function updateViewportWidth(){var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;var iframeDocument=iframeWindow==null?void 0:iframeWindow.document;if(iframeDocument){var dashboardRoot=iframeDocument.getElementById("dashboard-root");var effectiveViewportWidth=(dashboardRoot==null?void 0:dashboardRoot.clientWidth)||iframeDocument.documentElement.clientWidth;setViewportWidth(effectiveViewportWidth)}};updateViewportWidth();window.addEventListener("resize",updateViewportWidth);var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;if(iframeWindow){iframeWindow.addEventListener("resize",updateViewportWidth)}return function(){window.removeEventListener("resize",updateViewportWidth);if(iframeWindow){iframeWindow.removeEventListener("resize",updateViewportWidth)}}},[]);useEffect(function(){var updateTableWidthAndApplyCSS=function updateTableWidthAndApplyCSS(){var _gjsModel$collection2;var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection2=gjsModel.collection)==null?void 0:_gjsModel$collection2.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(!tableElement&&window.parent!==window){tableElement=window.parent.document.querySelector("[data-table-id=\""+tableId+"\"]")}if(!tableElement){return}var tableActualWidth=tableElement.getBoundingClientRect().width;if(tableActualWidth>0){calculateTableHeight(tableActualWidth,Array.isArray(data)?data.length:0)}};var timeoutId=setTimeout(updateTableWidthAndApplyCSS,150);window.addEventListener("resize",updateTableWidthAndApplyCSS);return function(){clearTimeout(timeoutId);window.removeEventListener("resize",updateTableWidthAndApplyCSS)}},[allData,gjsModel,viewportWidth,data,calculateTableHeight]);useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var parsedData=function(){if(typeof data==="object"&&data!==null&&!Array.isArray(data)&&data.name==="__peak_placeholder"){return[]}if(!Array.isArray(data)){return[]}return data.map(function(datum){var newData=_extends({},datum);delete newData.id;return newData})}();function onRowAction(_x,_x2){return _onRowAction.apply(this,arguments)}function _onRowAction(){_onRowAction=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(rowIndex,actionId){var id;return _regeneratorRuntime.wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:id=gjsModel.get("id");_context.next=1;return performInteraction({id:actionId,interactionType:"tableButton",payload:{row:data[rowIndex],tableId:id},affectedComponents:[]});case 1: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,_ref9,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:id=gjsModel.get("id");_ref9=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref9.sortColumn,sortDirection=_ref9.sortDirection;_context2.next=1;return performInteraction({id:id,interactionType:"pagination",payload:_extends({pageNumber:pageNumber,pageSize:pageSize},sortColumn&&sortDirection&&{sortColumn:sortColumn,sortDirection:sortDirection}),affectedComponents:getAffectedComponentsWithLoader([id],true)});case 1: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(_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=1;return performInteraction({id:id,interactionType:"tableSort",payload:{sortColumn:direction?column:null,sortDirection:direction,tableId:id},affectedComponents:getAffectedComponentsWithLoader([id],true)});case 1:case"end":return _context3.stop()}},_callee3)}));return _handleSort.apply(this,arguments)}return/*#__PURE__*/_jsxs(Card,{ref:cardRef,className:"shadow border relative flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-1 flex flex-col overflow-hidden",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing?renderNoDataFallback():/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:attributes.interactionApiInProgress||attributes.loading,onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,otherProps:rest,height:scrollAreaHeight})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",tableActions:actions,firstRowData:Array.isArray(data)&&data.length>0?data[0]:{},isVisible:isEditable,componentProps:allData})]})}export function renderTab(props){var tabsWidth=157;var safeTabs=Array.isArray(props.tabs)?props.tabs:[];var showFallback=safeTabs.length===0;if(safeTabs.length>4){tabsWidth=157}var defaultValue=props.defaultValue||(safeTabs.length>0?safeTabs[0]:undefined);return/*#__PURE__*/_jsxs(Tabs,{defaultValue:defaultValue,children:[/*#__PURE__*/_jsx("div",{className:"text-center mb-4",children:/*#__PURE__*/_jsx(TabsList,{className:"bg-[#F9F9FE] border border-[#D4D5DE] p-1 rounded-lg h-auto",children:safeTabs.length>0?safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsTrigger,{value:tab,className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},children:tab},tab)}):/*#__PURE__*/_jsx(TabsTrigger,{value:"no-data",className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},disabled:true,children:"No tabs"})})}),showFallback?/*#__PURE__*/_jsx(TabsContent,{value:defaultValue||"no-data",className:"tabs-content","data-fallback":"true",children:renderNoDataFallback()}):safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsContent,{value:tab,className:"tabs-content"},tab)})]})}export function renderMarkdown(props){var _attributes$isEditabl4;var gjsModel=props.gjsModel,rest=_objectWithoutPropertiesLoose(props,_excluded5);// Memoize filtered props to avoid re-filtering on every render
11
- var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState13=useState(initialData),allData=_useState13[0],setAllData=_useState13[1];var _useState14=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState14[0],setAttributes=_useState14[1];var isEditable=(_attributes$isEditabl4=attributes.isEditable)!=null?_attributes$isEditabl4:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var _useState15=useState(false),isEditing=_useState15[0],setIsEditing=_useState15[1];var _useState16=useState(false),isEditingHeading=_useState16[0],setIsEditingHeading=_useState16[1];var editRef=useRef(null);var headingEditRef=useRef(null);var startEditing=function startEditing(){setIsEditing(true);setTimeout(function(){setupEditor()},0)};var startEditingHeading=function startEditingHeading(){setIsEditingHeading(true);setTimeout(function(){setupHeadingEditor()},0)};var setupEditor=function setupEditor(){if(!editRef.current){return}var editor=editRef.current;editor.innerHTML="";editor.textContent=allData.summaryText;editor.focus()};var setupHeadingEditor=function setupHeadingEditor(){if(!headingEditRef.current){return}var editor=headingEditRef.current;editor.innerHTML="";editor.textContent=allData.summaryHeading||"Insights";editor.focus()};// Save changes and exit editing mode
12
- var saveChanges=function saveChanges(){if(!editRef.current){return}var content=editRef.current.innerText||"";setAllData(function(prev){return _extends({},prev,{summaryText:content})});setIsEditing(false);editRef.current.innerHTML=""};var saveHeadingChanges=function saveHeadingChanges(){if(!headingEditRef.current){return}var content=headingEditRef.current.innerText||"Insights";setAllData(function(prev){return _extends({},prev,{summaryHeading:content})});setIsEditingHeading(false);headingEditRef.current.innerHTML=""};var markdownStyles={ul:{props:{className:"list-disc"}},h1:{props:{className:"text-4xl font-bold leading-[4rem]"}},h2:{props:{className:"text-3xl font-bold leading-[3rem]"}},h3:{props:{className:"text-2xl font-bold leading-[2rem]"}},h4:{props:{className:"text-xl font-bold leading-[2.5rem]"}},h5:{props:{className:"text-lg font-bold leading-[2.5rem]"}},h6:{props:{className:"text-base font-bold leading-[2rem]"}}};var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=attributes.loading&&!hasError&&!hasMissing||attributes.interactionApiInProgress;if(isLoading){return/*#__PURE__*/_jsx(MarkdownLoader,{})}if(hasError||hasMissing){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:allData.summaryHeading||"Insights"}),/*#__PURE__*/_jsxs("div",{className:"w-full py-8 flex flex-col items-center justify-center px-6 text-center",style:{minHeight:"180px"},children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-12 h-12 text-gray-400 mb-2"}),/*#__PURE__*/_jsx("h3",{className:"text-lg font-medium text-gray-900",children:"No data available"}),/*#__PURE__*/_jsx("p",{className:"mt-2 text-sm text-gray-500 max-w-md",children:"Check your filters or try a different time range."})]}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}if(!isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:allData.summaryHeading||"Insights"}),/*#__PURE__*/_jsx("div",{"data-slot":"summaryText",children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:allData.summaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em] relative"},rest,{children:[isEditingHeading?/*#__PURE__*/_jsx("div",{ref:headingEditRef,contentEditable:true,onBlur:saveHeadingChanges,"data-slot":"summaryHeading",className:"text-xl font-semibold text-left",suppressContentEditableWarning:true}):/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",onClick:startEditingHeading,"data-slot":"summaryHeading",children:allData.summaryHeading||"Insights"}),isEditing?/*#__PURE__*/_jsx("div",{ref:editRef,contentEditable:true,onBlur:saveChanges,"data-slot":"summaryText",className:"p-2 min-h-[100px] whitespace-pre-wrap",suppressContentEditableWarning:true,style:{whiteSpace:"pre-wrap",wordWrap:"break-word"}}):/*#__PURE__*/_jsx("div",{onClick:startEditing,"data-slot":"summaryText",style:{whiteSpace:"pre-wrap",wordWrap:"break-word"},children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:allData.summaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}export function renderButton(props){var _attributes$isEditabl5;var gjsModel=props.gjsModel,_props$performInterac4=props.performInteraction,performInteraction=_props$performInterac4===void 0?function(){}:_props$performInterac4;var _useState17=useState(_extends({},props)),allData=_useState17[0],setAllData=_useState17[1];var _useState18=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState18[0],setAttributes=_useState18[1];var isEditable=(_attributes$isEditabl5=attributes.isEditable)!=null?_attributes$isEditabl5:false;useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(_extends({},gjsModel.get("componentProps")))})},[]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var text=allData.text,className=allData.className,payload=allData.payload,_allData$variant=allData.variant,variant=_allData$variant===void 0?"default":_allData$variant,_allData$size=allData.size,size=_allData$size===void 0?"sm":_allData$size,affectedComponents=allData.affectedComponents,tooltipContent=allData.tooltipContent;function interact(){var id=gjsModel.get("id");performInteraction({id:id,interactionType:"button",affectedComponents:getAffectedComponentsWithLoader([id].concat(affectedComponents),true),payload:payload})}return/*#__PURE__*/_jsx(TooltipButton,{className:className,isEditable:isEditable,interact:interact,attributes:attributes,variant:variant,size:size,text:text,tooltipContent:tooltipContent})}var renderActionCardWithWrapper=function renderActionCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"ActionCard"}),children:renderActionCard(props)})};var renderButtonWithWrapper=function renderButtonWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Button"}),children:renderButton(props)})};var renderCardWithWrapper=function renderCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Card"}),children:renderCard(props)})};var renderChartWithWrapper=function renderChartWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Chart"}),children:renderChart(props)})};var renderFilterWithWrapper=function renderFilterWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Filter"}),children:renderFilter(props)})};var renderMarkdownWithWrapper=function renderMarkdownWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Markdown"}),children:renderMarkdown(props)})};var renderSearchWithWrapper=function renderSearchWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Search"}),children:renderSearch(props)})};var renderTableWithWrapper=function renderTableWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Table"}),children:renderTable(props)})};var renderTabWithWrapper=function renderTabWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Tabs"}),children:renderTab(props)})};function renderActions(props){var actions=props.actions,_props$isEditable=props.isEditable,isEditable=_props$isEditable===void 0?false:_props$isEditable,gjsModel=props.gjsModel;if(actions===null){return/*#__PURE__*/_jsx("div",{})}if(!Array.isArray(actions)||actions.length===0){return/*#__PURE__*/_jsx("div",{className:"bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none relative",children:/*#__PURE__*/_jsx(CardLoader,{})})}return/*#__PURE__*/_jsx("div",{className:"dashboard-cards flex flex-wrap gap-4",children:actions.map(function(action,index){var icon=action.icon,title=action.title,description=action.description;return/*#__PURE__*/_jsx("div",{className:"flex-1 min-w-[200px]",children:renderActionCard({icon:icon,headerContent:title,bodyContent:description,isEditable:isEditable,gjsModel:gjsModel})},index)})})}var renderActionsWithWrapper=function renderActionsWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Actions"}),children:renderActions(props)})};export function getRenderers(){return{ActionCard:renderActionCardWithWrapper,Actions:renderActionsWithWrapper,Button:renderButtonWithWrapper,Card:renderCardWithWrapper,Chart:renderChartWithWrapper,Filter:renderFilterWithWrapper,Markdown:renderMarkdownWithWrapper,Search:renderSearchWithWrapper,Table:renderTableWithWrapper,Tabs:renderTabWithWrapper}}
5
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";domutil.getOffset=function(el){var html=el.ownerDocument.documentElement;var box={top:0,left:0};if(typeof el.getBoundingClientRect!=="undefined"){box=el.getBoundingClientRect()}var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;return{top:box.top+iframeWindow.pageYOffset-html.clientTop,left:box.left+iframeWindow.pageXOffset-html.clientLeft}};var BEESWARM_CONFIG={RADIUS:4,SPREAD_FACTOR:0.45,RANDOM_FACTOR:2,SIMULATION_ITERATIONS:300,COLLISION_PADDING:3};var baseColors=[[theme.colors.Blue_100,theme.colors.Blue_30],[theme.colors.Purpley_100,theme.colors.Purpley_30],[theme.colors.Light_Bluish_Green,"#06601b"],[theme.colors.Wild_Strawberry,"#4d001c"]];var iconMap={TrendingUp:/*#__PURE__*/_jsx(TrendingUp,{}),TrendingDown:/*#__PURE__*/_jsx(TrendingDown,{}),ShoppingCart:/*#__PURE__*/_jsx(ShoppingCart,{}),Equalizer:/*#__PURE__*/_jsx(ChartBarBig,{}),Style:/*#__PURE__*/_jsx(Tag,{}),Place:/*#__PURE__*/_jsx(MapPin,{})};function getIconFromString(iconString){if(!iconString){return null}if(iconMap[iconString]){return iconMap[iconString]}var lowerIconString=iconString.toLowerCase();var matchingKey=Object.keys(iconMap).find(function(key){return key.toLowerCase()===lowerIconString});if(matchingKey){return iconMap[matchingKey]}return null}function getNColors(n){var colors=[];var safeBaseColors=Array.isArray(baseColors)?baseColors:[];for(var _iterator=_createForOfIteratorHelperLoose(safeBaseColors),_step;!(_step=_iterator()).done;){var baseColor=_step.value;// eslint-disable-next-line import/no-named-as-default-member
6
+ 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,_props$isCreatingAsse=props.isCreatingAssetFromTemplate,isCreatingAssetFromTemplate=_props$isCreatingAsse===void 0?false:_props$isCreatingAsse,rest=_objectWithoutPropertiesLoose(props,_excluded);// Memoize filtered props to avoid re-filtering on every render
7
+ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState=useState(initialData),allData=_useState[0],setAllData=_useState[1];var _allData$headerConten=allData.headerContent,headerContent=_allData$headerConten===void 0?"Default action card title":_allData$headerConten,icon=allData.icon,_allData$bodyContent=allData.bodyContent,bodyContent=_allData$bodyContent===void 0?"Default body content. Click to edit.":_allData$bodyContent,sampleData=allData.sampleData;var effectiveBodyContent=isCreatingAssetFromTemplate&&sampleData!==undefined?sampleData:bodyContent;var _useState2=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState2[0],setAttributes=_useState2[1];useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var defaultClasses="text-black p-4 rounded-lg shadow border flex flex-col h-full";return/*#__PURE__*/_jsx(Card,_extends({className:defaultClasses+" relative",style:{backgroundColor:"#f9f9fe"},isEditable:false,contentEditable:false},rest,{children:/*#__PURE__*/_jsx(CardContent,{className:"p-0",isEditable:false,contentEditable:false,children:/*#__PURE__*/_jsx("div",{className:"px-4 py-3",children:/*#__PURE__*/_jsxs("div",{className:"flex items-start flex-col",children:[/*#__PURE__*/_jsxs("div",{className:"flex items-center justify-between w-full",children:[/*#__PURE__*/_jsx("div",{className:"text-xl font-semibold",children:headerContent}),/*#__PURE__*/_jsx("div",{className:"text-5xl ml-2 flex items-center","aria-hidden":"true",children:getIconFromString(icon)})]}),/*#__PURE__*/_jsx("div",{className:"w-full mt-1",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing||!effectiveBodyContent?/*#__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:effectiveBodyContent})})]})})})}))}export function renderCard(props){var _attributes$isEditabl,_attributes$error,_attributes$isMissing;var gjsModel=props.gjsModel,_props$performInterac=props.performInteraction,performInteraction=_props$performInterac===void 0?function(){return Promise.resolve({})}:_props$performInterac,_props$isCreatingAsse2=props.isCreatingAssetFromTemplate,isCreatingAssetFromTemplate=_props$isCreatingAsse2===void 0?false:_props$isCreatingAsse2,rest=_objectWithoutPropertiesLoose(props,_excluded2);// Memoize filtered props to avoid re-filtering on every render
8
+ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState3=useState(initialData),allData=_useState3[0],setAllData=_useState3[1];var headerContent=allData.headerContent,headerDescription=allData.headerDescription,bodyContent=allData.bodyContent,footerContent=allData.footerContent,footerClass=allData.footerClass,footerIcon=allData.footerIcon,contentMetadata=allData.contentMetadata,contentMetadataClass=allData.contentMetadataClass,dataClassName=allData.className,dataError=allData.error,dataIsMissing=allData.isMissing,sampleData=allData.sampleData;function toSafeText(value){if(value===null||value===undefined){return""}return typeof value==="string"?value:JSON.stringify(value)}var safeHeaderContent=toSafeText(headerContent);var safeHeaderDescription=toSafeText(headerDescription);var effectiveBodyContent=isCreatingAssetFromTemplate&&sampleData!==undefined?sampleData:bodyContent;var safeBodyContent=toSafeText(effectiveBodyContent);var safeFooterContent=toSafeText(footerContent);var safeContentMetadata=toSafeText(contentMetadata);var _useState4=useState((safeFooterContent==null?void 0:safeFooterContent.length)>0),footerHasContent=_useState4[0],setFooterHasContent=_useState4[1];var _useState5=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState5[0],setAttributes=_useState5[1];var isEditable=(_attributes$isEditabl=attributes.isEditable)!=null?_attributes$isEditabl:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);useEffect(function(){setFooterHasContent((safeFooterContent==null?void 0:safeFooterContent.length)>0)},[safeFooterContent]);var defaultClasses="bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none";var defaultFooterClasses=footerHasContent?"text-sm bg-pink-50 text-pink-900 shadow-sm":"text-sm";var defaultContentMetadataClasses="text-xs";var mergedCardClassName=dataClassName?cn(defaultClasses,dataClassName):defaultClasses;var mergedFooterClassName=footerClass?cn(defaultFooterClasses,footerClass):defaultFooterClasses;var mergedContentMetadataClassName=contentMetadataClass?cn(defaultContentMetadataClasses,contentMetadataClass):defaultContentMetadataClasses;var hasError=Boolean((_attributes$error=attributes==null?void 0:attributes.error)!=null?_attributes$error:dataError);var hasMissing=Boolean((_attributes$isMissing=attributes==null?void 0:attributes.isMissing)!=null?_attributes$isMissing:dataIsMissing);var isLoading=Boolean(((attributes==null?void 0:attributes.interactionApiInProgress)||(attributes==null?void 0:attributes.loading))&&!hasError&&!hasMissing);var footerIconText=typeof footerIcon==="string"?footerIcon:footerIcon&&typeof footerIcon==="object"&&"icon"in footerIcon?String(footerIcon.icon):"";function getCardContent(){if(isLoading){return/*#__PURE__*/_jsx(CardContent,{children:/*#__PURE__*/_jsx(CardLoader,{})})}var showEmpty=hasError||hasMissing||!safeBodyContent;function handleFooterInput(event){var target=event.target;var content=target.textContent||"";var hasContent=content.trim().length>0;setFooterHasContent(hasContent);if(!hasContent){var currentProps=gjsModel.get("componentProps");gjsModel.set("componentProps",_extends({},currentProps,{footerContent:null,footerIcon:null,footerClass:null,isEmptied:true}))}}return/*#__PURE__*/_jsxs(React.Fragment,{children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"headerContent",contentEditable:isEditable,className:"text-lg",children:safeHeaderContent}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"headerDescription",contentEditable:isEditable,className:"text-sm",children:safeHeaderDescription})]})})}),showEmpty?/*#__PURE__*/_jsxs("span",{className:"flex flex-row items-center px-3 py-2",children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-3 h-3 text-gray-400 mr-1"}),/*#__PURE__*/_jsx("p",{className:"text-sm text-gray-500 max-w-md text-center",children:"No data available for given filters"})]}):/*#__PURE__*/_jsxs(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-grow",children:[/*#__PURE__*/_jsx("div",{className:"text-3xl font-semibold truncate",children:safeBodyContent}),safeContentMetadata&&/*#__PURE__*/_jsx("div",{className:mergedContentMetadataClassName,style:{color:"#2A44D4"},children:safeContentMetadata})]}),/*#__PURE__*/_jsxs(CardFooter,{"data-slot":"footerContent",contentEditable:isEditable,className:mergedFooterClassName,onInput:handleFooterInput,children:[(footerIconText||"").trim()?/*#__PURE__*/_jsx("span",{className:"mr-2","aria-hidden":"true",children:footerIconText}):null,safeFooterContent||""]})]})}return/*#__PURE__*/_jsxs(Card,_extends({},rest,{isEditable:false,className:mergedCardClassName+" relative",children:[getCardContent(),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}function transformDataForScatter(data,xAxis,yAxis,dataKeys){if(!data||data.length===0){return[]}var scatterData=data.filter(function(item){return item[xAxis]!==null&&item[xAxis]!==undefined&&item[yAxis]!==null&&item[yAxis]!==undefined}).map(function(item){var _result;var result=(_result={},_result[xAxis]=Number(item[xAxis]),_result[yAxis]=Number(item[yAxis]),_result);if(dataKeys&&dataKeys.length>0){dataKeys.forEach(function(_ref){var key=_ref.key;if(item[key]!==null&&item[key]!==undefined){result[key]=Number(item[key])}})}return result});return scatterData}function binDataForHistogram(data,valueKey,bins){if(bins===void 0){bins=10}if(!data||data.length===0){return[]}var values=data.map(function(item){return Number(item[valueKey])}).filter(function(val){return!isNaN(val)});if(values.length===0){return[]}var min=Math.min.apply(Math,values);var max=Math.max.apply(Math,values);var binWidth=(max-min)/bins;var binsArray=new Array(bins).fill(0);var binLabels=[];for(var i=0;i<bins;i++){var binStart=min+i*binWidth;var binEnd=binStart+binWidth;binLabels.push(binStart.toFixed(1)+"-"+binEnd.toFixed(1))}values.forEach(function(value){var binIndex=Math.floor((value-min)/binWidth);if(binIndex>=bins){binIndex=bins-1}if(binIndex<0){binIndex=0}binsArray[binIndex]+=1});return binLabels.map(function(label,index){return{bin:label,frequency:binsArray[index]}})}function transformDataForBeeswarm(data,groupBy,valueKey){if(!data||data.length===0){return{nodes:[],groups:[]}}var grouped={};data.forEach(function(item){if(item[groupBy]!==null&&item[groupBy]!==undefined&&item[valueKey]!==null&&item[valueKey]!==undefined){var group=String(item[groupBy]);var value=Number(item[valueKey]);if(!isNaN(value)){if(!grouped[group]){grouped[group]=[]}grouped[group].push(value)}}});var groups=Object.keys(grouped).sort();var nodes=[];groups.forEach(function(group,groupIndex){var values=grouped[group];values.forEach(function(value){nodes.push({group:group,groupIndex:groupIndex,value:value,x:groupIndex,y:value,radius:4})})});return{nodes:nodes,groups:groups}}function BeeswarmChart(_ref2){var data=_ref2.data,groups=_ref2.groups,color=_ref2.color,groupBy=_ref2.groupBy,valueKey=_ref2.valueKey;var containerRef=useRef(null);var svgRef=useRef(null);var _useState6=useState({width:800,height:250}),dimensions=_useState6[0],setDimensions=_useState6[1];var _useState7=useState([]),simulatedNodes=_useState7[0],setSimulatedNodes=_useState7[1];var _useTooltip=useTooltip(),tooltipData=_useTooltip.tooltipData,tooltipLeft=_useTooltip.tooltipLeft,tooltipTop=_useTooltip.tooltipTop,tooltipOpen=_useTooltip.tooltipOpen,showTooltip=_useTooltip.showTooltip,hideTooltip=_useTooltip.hideTooltip;useEffect(function(){var updateDimensions=function updateDimensions(){if(containerRef.current){setDimensions({width:containerRef.current.offsetWidth||800,height:250})}};updateDimensions();var resizeObserver=new ResizeObserver(function(entries){for(var _iterator2=_createForOfIteratorHelperLoose(entries),_step2;!(_step2=_iterator2()).done;){var entry=_step2.value;setDimensions({width:entry.contentRect.width||800,height:250})}});if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateDimensions);return function(){resizeObserver.disconnect();window.removeEventListener("resize",updateDimensions)}},[]);var createXScale=useCallback(function(innerWidth,groupDomain){var minBandwidth=60;var totalMinWidth=groupDomain.length*minBandwidth;var paddingRatio=0.3;var xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});if(totalMinWidth>innerWidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}else{xScale=scaleBand({domain:groupDomain,range:[0,innerWidth],padding:paddingRatio});var currentBandwidth=xScale.bandwidth();if(currentBandwidth<minBandwidth){xScale=scaleBand({domain:groupDomain,range:[0,groupDomain.length*minBandwidth],padding:paddingRatio})}}return xScale},[]);var scales=useMemo(function(){if(data.length===0||dimensions.width===0){return null}var margin={top:20,right:20,bottom:60,left:60};var innerWidth=dimensions.width-margin.left-margin.right;var innerHeight=dimensions.height-margin.top-margin.bottom;var values=data.map(function(d){return d.value});var minValue=Math.min.apply(Math,values);var maxValue=Math.max.apply(Math,values);var xScale=createXScale(innerWidth,groups);var yScale=scaleLinear({domain:[minValue,maxValue],range:[innerHeight,0]});return{xScale:xScale,yScale:yScale,minValue:minValue,maxValue:maxValue,innerWidth:innerWidth,innerHeight:innerHeight}},[data,groups,dimensions,createXScale]);useEffect(function(){if(!scales){return}var xScale=scales.xScale,yScale=scales.yScale,minValue=scales.minValue,maxValue=scales.maxValue,innerWidth=scales.innerWidth,innerHeight=scales.innerHeight;var valueRange=maxValue-minValue;var padding=valueRange*0.1;var yScaleWithPadding=scaleLinear({domain:[minValue-padding,maxValue+padding],range:[innerHeight,0]});// Use the actual chart width from xScale range, not just innerWidth
9
+ var actualChartWidth=Math.max(innerWidth,xScale.range()[1]||0);var bounds={minY:BEESWARM_CONFIG.RADIUS,maxY:innerHeight-BEESWARM_CONFIG.RADIUS,minX:0,maxX:actualChartWidth};var nodes=data.map(function(d){var initialY=yScaleWithPadding(d.value);var clampedY=Math.max(bounds.minY,Math.min(bounds.maxY,initialY));var groupCenterX=(xScale(d.group)||0)+(xScale.bandwidth()||0)/2;var bandwidth=xScale.bandwidth()||0;var maxSpread=bandwidth*BEESWARM_CONFIG.SPREAD_FACTOR;var randomOffset=(Math.random()-0.5)*maxSpread*BEESWARM_CONFIG.RANDOM_FACTOR;return _extends({},d,{groupCenterX:groupCenterX,x:groupCenterX+randomOffset,y:clampedY,radius:BEESWARM_CONFIG.RADIUS,maxSpread:maxSpread})});var simulation=null;try{simulation=forceSimulation(nodes).force("x",forceX(function(d){return d.groupCenterX}).strength(0.15)).force("y",forceY(function(d){var targetY=yScaleWithPadding(d.value);return Math.max(bounds.minY,Math.min(bounds.maxY,targetY))}).strength(1)).force("collide",forceCollide().radius(function(d){return d.radius+BEESWARM_CONFIG.COLLISION_PADDING}).strength(0.9).iterations(3));if(simulation&&typeof simulation.stop==="function"){simulation.stop()}}catch(error){setSimulatedNodes([].concat(nodes));return}var constrainNode=function constrainNode(node,isFinal){if(isFinal===void 0){isFinal=false}var correctY=yScaleWithPadding(node.value);node.y=Math.max(bounds.minY,Math.min(bounds.maxY,correctY));node.vy=0;var nodeMinX=node.groupCenterX-node.maxSpread;var nodeMaxX=node.groupCenterX+node.maxSpread;var constrainedMinX=Math.max(bounds.minX,nodeMinX);var constrainedMaxX=Math.min(bounds.maxX,nodeMaxX);if(isFinal){if(node.x<constrainedMinX){node.x=constrainedMinX}else if(node.x>constrainedMaxX){node.x=constrainedMaxX}}else{var overflowMargin=node.maxSpread*0.1;if(node.x<constrainedMinX-overflowMargin){node.x=constrainedMinX-overflowMargin;node.vx*=0.7}else if(node.x>constrainedMaxX+overflowMargin){node.x=constrainedMaxX+overflowMargin;node.vx*=0.7}}};if(simulation&&typeof simulation.tick==="function"){for(var i=0;i<BEESWARM_CONFIG.SIMULATION_ITERATIONS;i++){try{simulation.tick();nodes.forEach(function(node){return constrainNode(node,false)})}catch(error){break}}}// Final constraint pass
10
+ nodes.forEach(function(node){constrainNode(node,true);node.vx=0});setSimulatedNodes([].concat(nodes))},[scales,data]);if(simulatedNodes.length===0||dimensions.width===0||!scales){return/*#__PURE__*/_jsx("div",{ref:containerRef,style:{width:"100%",height:"250px"}})}var margin={top:20,right:20,bottom:60,left:60};var xScale=scales.xScale,yScale=scales.yScale,innerWidth=scales.innerWidth,innerHeight=scales.innerHeight;var handleMouseOver=function handleMouseOver(event,node){if(containerRef.current){var containerRect=containerRef.current.getBoundingClientRect();var x=event.clientX-containerRect.left+10;var y=event.clientY-containerRect.top-10;showTooltip({tooltipLeft:x,tooltipTop:y,tooltipData:node})}};var actualChartWidth=Math.max(innerWidth,xScale.range()[1]||0);var actualSvgWidth=actualChartWidth+margin.left+margin.right;return/*#__PURE__*/_jsxs("div",{ref:containerRef,style:{width:"100%",height:"250px",position:"relative"},children:[/*#__PURE__*/_jsx("svg",{ref:svgRef,width:Math.max(dimensions.width,actualSvgWidth),height:dimensions.height,onMouseLeave:hideTooltip,children:/*#__PURE__*/_jsxs(Group,{left:margin.left,top:margin.top,children:[/*#__PURE__*/_jsx(GridRows,{scale:yScale,width:actualChartWidth,strokeDasharray:"3,3",stroke:"#e0e0e0",strokeOpacity:0.5}),/*#__PURE__*/_jsx(AxisLeft,{scale:yScale,tickStroke:"#666",stroke:"#666",tickLabelProps:function tickLabelProps(){return{fill:"#666",fontSize:12,textAnchor:"end",dy:"0.33em"}}}),/*#__PURE__*/_jsx(AxisBottom,{top:innerHeight,scale:xScale,tickStroke:"#666",stroke:"#666",tickLabelProps:function tickLabelProps(){return{fill:"#666",fontSize:12,textAnchor:"middle"}}}),simulatedNodes.map(function(node,i){return/*#__PURE__*/_jsx(Circle,{cx:node.x||0,cy:node.y||0,r:node.radius,fill:color,opacity:0.8,stroke:color,strokeWidth:1,onMouseOver:function onMouseOver(e){return handleMouseOver(e,node)},style:{cursor:"pointer"}},i)})]})}),tooltipOpen&&tooltipData&&tooltipLeft!==null&&tooltipLeft!==undefined&&tooltipTop!==null&&tooltipTop!==undefined&&/*#__PURE__*/_jsx(TooltipWithBounds,{left:tooltipLeft,top:tooltipTop,style:_extends({},defaultStyles,{backgroundColor:"white",border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px 12px",boxShadow:"0 2px 8px rgba(0,0,0,0.15)",fontSize:"12px",position:"absolute",zIndex:1000,pointerEvents:"none"}),children:/*#__PURE__*/_jsxs("div",{children:[/*#__PURE__*/_jsxs("div",{style:{marginBottom:"4px",fontWeight:600},children:[groupBy,": ",tooltipData.group]}),/*#__PURE__*/_jsxs("div",{children:[valueKey,": ",tooltipData.value.toLocaleString()]})]})})]})}function renderChartComponent(chartType,data,config){var safeData=Array.isArray(data)?data:[];if(safeData.length===0){return renderNoDataFallback()}switch(chartType){case"pie":return/*#__PURE__*/_jsxs(PieChart,{children:[safeData.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true})}),/*#__PURE__*/_jsx(Pie,{data:safeData,dataKey:config.dataKey,nameKey:config.nameKey,innerRadius:60,strokeWidth:10,label:safeData.length<20?function(_ref3){var name=_ref3.name,percent=_ref3.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]});case"bar":{config.dataKeys=config.dataKeys||[];var barDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];return/*#__PURE__*/_jsxs(BarChart,_extends({data:safeData},config.chartUi,barDataKeys.length>1&&{barGap:0},{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:config.xAxis}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(Legend,{align:"left",wrapperStyle:{marginLeft:20}}),barDataKeys.map(function(_ref4){var key=_ref4.key,name=_ref4.name,color=_ref4.color;return/*#__PURE__*/_jsx(Bar,{dataKey:key,fill:color!=null?color:"#4caf50",name:name,radius:2},key)}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})})]}))}case"line":{config.dataKeys=config.dataKeys||[];var safeDataKeysLine=Array.isArray(config.dataKeys)?config.dataKeys:[];return/*#__PURE__*/_jsxs(LineChart,_extends({data:safeData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:config.xAxis}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})}),safeDataKeysLine.map(function(_ref5){var key=_ref5.key,name=_ref5.name,color=_ref5.color;return/*#__PURE__*/_jsx(Line,{type:"monotone",dataKey:key,stroke:color!=null?color:"#4caf50",name:name},key)}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"scatter":{config.dataKeys=config.dataKeys||[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];var scatterData=transformDataForScatter(safeData,config.xAxis,config.yAxis,safeDataKeys);if(scatterData.length===0){return renderNoDataFallback()}var colors=safeDataKeys.length>0?safeDataKeys.map(function(_ref6){var color=_ref6.color;return color!=null?color:"#2A44D4"}):["#2A44D4"];return/*#__PURE__*/_jsxs(ScatterChart,_extends({data:scatterData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{type:"number",dataKey:config.xAxis,name:config.xAxis||"X Axis",domain:["auto","auto"]}),/*#__PURE__*/_jsx(YAxis,{type:"number",dataKey:config.yAxis,name:config.yAxis||"Y Axis",domain:["auto","auto"]}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:{strokeDasharray:"3 3"},content:/*#__PURE__*/_jsx(ChartTooltipContent,{})}),safeDataKeys.length>0?safeDataKeys.map(function(_ref7,index){var key=_ref7.key,name=_ref7.name,color=_ref7.color;return/*#__PURE__*/_jsx(Scatter,{name:name||key,dataKey:key||config.yAxis,fill:color!=null?color:colors[index%colors.length]},key)}):/*#__PURE__*/_jsx(Scatter,{name:"Data",dataKey:config.yAxis,fill:colors[0]}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"histogram":{config.dataKeys=config.dataKeys||[];var _safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];var valueKey=_safeDataKeys.length>0?_safeDataKeys[0].key:config.xAxis;var bins=config.bins||10;var binnedData=binDataForHistogram(safeData,valueKey,bins);if(binnedData.length===0){return renderNoDataFallback()}var color=_safeDataKeys.length>0?_safeDataKeys[0].color:"#2A44D4";return/*#__PURE__*/_jsxs(BarChart,_extends({data:binnedData},config.chartUi,{children:[/*#__PURE__*/_jsx(CartesianGrid,{vertical:false}),/*#__PURE__*/_jsx(XAxis,{dataKey:"bin",angle:-45,textAnchor:"end",height:80}),/*#__PURE__*/_jsx(YAxis,{}),/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{indicator:"dashed"})}),/*#__PURE__*/_jsx(Bar,{dataKey:"frequency",fill:color,radius:2,children:binnedData.map(function(entry,index){return/*#__PURE__*/_jsx(Cell,{fill:color},"cell-"+index)})}),/*#__PURE__*/_jsx(Legend,{align:"left"})]}))}case"beeswarm":{var _config$dataKeys$,_config$dataKeys$2;var groupBy=config.groupBy||config.xAxis;var _valueKey=config.valueKey||config.dataKeys&&((_config$dataKeys$=config.dataKeys[0])==null?void 0:_config$dataKeys$.key)||"value";var _transformDataForBees=transformDataForBeeswarm(safeData,groupBy,_valueKey),nodes=_transformDataForBees.nodes,groups=_transformDataForBees.groups;if(nodes.length===0||groups.length===0){return renderNoDataFallback()}var _color=config.dataKeys&&(_config$dataKeys$2=config.dataKeys[0])!=null&&_config$dataKeys$2.color?config.dataKeys[0].color:"#2A44D4";return/*#__PURE__*/_jsx(BeeswarmChart,{data:nodes,groups:groups,color:_color,groupBy:groupBy,valueKey:_valueKey})}default:return/*#__PURE__*/_jsxs(PieChart,{children:[safeData.length>=20&&/*#__PURE__*/_jsx(ChartTooltip,{cursor:false,content:/*#__PURE__*/_jsx(ChartTooltipContent,{hideLabel:true})}),/*#__PURE__*/_jsx(Pie,{data:safeData,dataKey:config.dataKey,nameKey:config.nameKey,innerRadius:60,strokeWidth:10,label:safeData.length<20?function(_ref8){var name=_ref8.name,percent=_ref8.percent;return name+": "+(percent*100).toFixed(0)+"%"}:undefined,labelLine:false})]})}}export function renderChart(props){var _attributes$isEditabl2;var gjsModel=props.gjsModel,_props$performInterac2=props.performInteraction,performInteraction=_props$performInterac2===void 0?function(){return Promise.resolve({})}:_props$performInterac2,_props$isCreatingAsse3=props.isCreatingAssetFromTemplate,isCreatingAssetFromTemplate=_props$isCreatingAsse3===void 0?false:_props$isCreatingAsse3,rest=_objectWithoutPropertiesLoose(props,_excluded3);// Memoize filtered props to avoid re-filtering on every render
11
+ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState8=useState(initialData),allData=_useState8[0],setAllData=_useState8[1];var _useState9=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState9[0],setAttributes=_useState9[1];var isEditable=(_attributes$isEditabl2=attributes.isEditable)!=null?_attributes$isEditabl2:false;var containerRef=useRef(null);var _useState10=useState(0),containerWidth=_useState10[0],setContainerWidth=_useState10[1];useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){var newAttributes=gjsModel.get("attributes");setAttributes(_extends({},newAttributes))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);useEffect(function(){var updateContainerWidth=function updateContainerWidth(){if(containerRef.current){setContainerWidth(containerRef.current.offsetWidth||0)}};var resizeObserver=new ResizeObserver(function(entries){for(var _iterator3=_createForOfIteratorHelperLoose(entries),_step3;!(_step3=_iterator3()).done;){var entry=_step3.value;setContainerWidth(entry.contentRect.width||0)}});updateContainerWidth();var timeoutId=setTimeout(updateContainerWidth,50);if(containerRef.current){resizeObserver.observe(containerRef.current)}window.addEventListener("resize",updateContainerWidth);return function(){clearTimeout(timeoutId);resizeObserver.disconnect();window.removeEventListener("resize",updateContainerWidth)}},[]);var _allData$config=allData.config,config=_allData$config===void 0?{}:_allData$config,_allData$chartType=allData.chartType,chartType=_allData$chartType===void 0?"pie":_allData$chartType,_allData$chartData=allData.chartData,chartData=_allData$chartData===void 0?[]:_allData$chartData,className=allData.className,_allData$title=allData.title,title=_allData$title===void 0?"Title":_allData$title,_allData$subTitle=allData.subTitle,subTitle=_allData$subTitle===void 0?"Subtitle":_allData$subTitle,sampleData=allData.sampleData;var effectiveChartData=isCreatingAssetFromTemplate&&sampleData!==undefined?sampleData:chartData;var defaultClasses="aspect-auto h-[250px] w-full min-w-[200px] min-h-[200px]";var mergedClasses=className?cn(defaultClasses,className):defaultClasses;if(chartType==="pie"){var safeChartData=Array.isArray(effectiveChartData)?effectiveChartData:[];var colors=getNColors(safeChartData.length);safeChartData.forEach(function(data,i){if(!data.fill){data.fill=colors[i]}})}else if(!config.color){var safeBaseColors=Array.isArray(baseColors)?baseColors:[];if(safeBaseColors.length>0){config.color=safeBaseColors[Math.floor(Math.random()*safeBaseColors.length)]}}var totalDataPoints=0;if(chartType==="bar"||chartType==="line"||chartType==="scatter"||chartType==="histogram"||chartType==="beeswarm"){var _safeChartData=Array.isArray(effectiveChartData)?effectiveChartData:[];var safeDataKeys=Array.isArray(config.dataKeys)?config.dataKeys:[];if(chartType==="bar"){totalDataPoints=_safeChartData.length*Math.max(1,safeDataKeys.length)}else{totalDataPoints=_safeChartData.length}}var getScrollableWidth=function getScrollableWidth(){if(chartType==="line"){return totalDataPoints*20}if(chartType==="bar"){return totalDataPoints*20+(Array.isArray(config.dataKeys)?config.dataKeys.length:0)*8*(Array.isArray(chartData)?chartData.length:0)+(Array.isArray(chartData)?chartData.length:0)*15}return 800};var scrollWidth=getScrollableWidth();var shouldScroll=(chartType==="bar"||chartType==="line"||chartType==="beeswarm"||chartType==="histogram"||chartType==="scatter")&&totalDataPoints>15&&scrollWidth>containerWidth;var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=(attributes.interactionApiInProgress||attributes.loading)&&!hasError&&!hasMissing;var ChartWrapper=function ChartWrapper(_ref9){var children=_ref9.children;if(shouldScroll){return/*#__PURE__*/_jsx("div",{className:"w-full h-[250px] overflow-x-auto",children:/*#__PURE__*/_jsx("div",{style:{minWidth:scrollWidth+"px",height:"250px"},children:children})})}return/*#__PURE__*/_jsx("div",{className:"w-full h-[250px]",children:children})};var chartUi=isLoading?/*#__PURE__*/_jsx(ChartLoader,{}):hasError||hasMissing||!effectiveChartData?renderNoDataFallback():/*#__PURE__*/_jsx(ChartWrapper,{children:/*#__PURE__*/_jsx(ChartContainer,_extends({},rest,{config:config,className:mergedClasses,children:renderChartComponent(chartType,effectiveChartData,config)}))});return/*#__PURE__*/_jsxs(Card,{className:"shadow border mt-2 mb-2 relative",children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{ref:containerRef,"data-slot":"bodyContent",className:"px-6",style:{minHeight:"250px"},children:chartUi}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]})}export function renderTable(props){var _attributes$isEditabl3;var gjsModel=props.gjsModel,_props$performInterac3=props.performInteraction,performInteraction=_props$performInterac3===void 0?function(){}:_props$performInterac3,_props$isCreatingAsse4=props.isCreatingAssetFromTemplate,isCreatingAssetFromTemplate=_props$isCreatingAsse4===void 0?false:_props$isCreatingAsse4,rest=_objectWithoutPropertiesLoose(props,_excluded4);// Memoize filtered props to avoid re-filtering on every render
12
+ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState11=useState(initialData),allData=_useState11[0],setAllData=_useState11[1];var cardRef=useRef(null);var _useState12=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState12[0],setAttributes=_useState12[1];var isEditable=(_attributes$isEditabl3=attributes.isEditable)!=null?_attributes$isEditabl3:false;var rawData=allData.data,_allData$headerMapper=allData.headerMapper,rawHeaderMapper=_allData$headerMapper===void 0?{}:_allData$headerMapper,className=allData.className,_allData$title2=allData.title,title=_allData$title2===void 0?"Title":_allData$title2,_allData$subTitle2=allData.subTitle,subTitle=_allData$subTitle2===void 0?"Subtitle":_allData$subTitle2,_allData$actions=allData.actions,actions=_allData$actions===void 0?[]:_allData$actions,pagination=allData.pagination,sampleData=allData.sampleData;var effectiveRawData=isCreatingAssetFromTemplate&&sampleData!==undefined?sampleData:rawData;var data=Array.isArray(effectiveRawData)?effectiveRawData:[];var headerMapper=function(){var cleaned=_extends({},rawHeaderMapper);if("id"in cleaned){delete cleaned.id}if(data.length>0){var dataKeys=Object.keys(data[0]||{});return Object.fromEntries(Object.entries(cleaned).filter(function(_ref10){var key=_ref10[0];return dataKeys.includes(key)}))}return cleaned}();var sortConfig=function(_gjsModel$get,_ref12){var _ref11=(_gjsModel$get=gjsModel.get("componentProps"))!=null?_gjsModel$get:{},sortColumn=_ref11.sortColumn,sortDirection=_ref11.sortDirection;return sortColumn&&sortDirection?(_ref12={},_ref12[sortColumn]=sortDirection,_ref12):{}}();var _useState13=useState(0),viewportWidth=_useState13[0],setViewportWidth=_useState13[1];var _useState14=useState(250),scrollAreaHeight=_useState14[0],setScrollAreaHeight=_useState14[1];var calculateTableHeight=function calculateTableHeight(tableWidth,rowCount){if(viewportWidth>0){var _gjsModel$collection;var widthRatio=tableWidth/viewportWidth;var baseTableHeight=250;var targetScrollAreaHeight=baseTableHeight;if(widthRatio>=0.8){var headerHeight=48;var rowHeight=40;var calculatedHeight=headerHeight+rowCount*rowHeight;targetScrollAreaHeight=Math.min(calculatedHeight,baseTableHeight)}var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection=gjsModel.collection)==null?void 0:_gjsModel$collection.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(tableElement){var headerElement=tableElement.querySelector("[data-slot=\"card-header\"]");if(headerElement&&headerElement.offsetHeight>0){var actualHeaderHeight=headerElement.offsetHeight;var standardHeaderHeight=58;var heightDifference=actualHeaderHeight-standardHeaderHeight;if(heightDifference>0){targetScrollAreaHeight=targetScrollAreaHeight-heightDifference}}}setScrollAreaHeight(targetScrollAreaHeight)}};useEffect(function(){var updateViewportWidth=function updateViewportWidth(){var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;var iframeDocument=iframeWindow==null?void 0:iframeWindow.document;if(iframeDocument){var dashboardRoot=iframeDocument.getElementById("dashboard-root");var effectiveViewportWidth=(dashboardRoot==null?void 0:dashboardRoot.clientWidth)||iframeDocument.documentElement.clientWidth;setViewportWidth(effectiveViewportWidth)}};updateViewportWidth();window.addEventListener("resize",updateViewportWidth);var iframe=document.querySelector(".gjs-frame");var iframeWindow=iframe==null?void 0:iframe.contentWindow;if(iframeWindow){iframeWindow.addEventListener("resize",updateViewportWidth)}return function(){window.removeEventListener("resize",updateViewportWidth);if(iframeWindow){iframeWindow.removeEventListener("resize",updateViewportWidth)}}},[]);useEffect(function(){var updateTableWidthAndApplyCSS=function updateTableWidthAndApplyCSS(){var _gjsModel$collection2;var tableId=gjsModel.get("id");var editor=gjsModel.em||((_gjsModel$collection2=gjsModel.collection)==null?void 0:_gjsModel$collection2.em);var canvasDocument=editor.Canvas.getDocument()||document;var tableElement=canvasDocument.querySelector("[data-table-id=\""+tableId+"\"]");if(!tableElement&&window.parent!==window){tableElement=window.parent.document.querySelector("[data-table-id=\""+tableId+"\"]")}if(!tableElement){return}var tableActualWidth=tableElement.getBoundingClientRect().width;if(tableActualWidth>0){calculateTableHeight(tableActualWidth,Array.isArray(data)?data.length:0)}};var timeoutId=setTimeout(updateTableWidthAndApplyCSS,150);window.addEventListener("resize",updateTableWidthAndApplyCSS);return function(){clearTimeout(timeoutId);window.removeEventListener("resize",updateTableWidthAndApplyCSS)}},[allData,gjsModel,viewportWidth,data,calculateTableHeight]);useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var parsedData=function(){if(typeof data==="object"&&data!==null&&!Array.isArray(data)&&data.name==="__peak_placeholder"){return[]}if(!Array.isArray(data)){return[]}return data.map(function(datum){var newData=_extends({},datum);delete newData.id;return newData})}();function onRowAction(_x,_x2){return _onRowAction.apply(this,arguments)}function _onRowAction(){_onRowAction=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(rowIndex,actionId){var id;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:id=gjsModel.get("id");_context.next=3;return performInteraction({id:actionId,interactionType:"tableButton",payload:{row:data[rowIndex],tableId:id},affectedComponents:[]});case 3:case"end":return _context.stop()}},_callee)}));return _onRowAction.apply(this,arguments)}function onPageChange(_x3,_x4){return _onPageChange.apply(this,arguments)}function _onPageChange(){_onPageChange=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(pageNumber,pageSize){var _gjsModel$get2;var id,_ref13,sortColumn,sortDirection;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:id=gjsModel.get("id");_ref13=(_gjsModel$get2=gjsModel.get("componentProps"))!=null?_gjsModel$get2:{},sortColumn=_ref13.sortColumn,sortDirection=_ref13.sortDirection;_context2.next=4;return performInteraction({id:id,interactionType:"pagination",payload:_extends({pageNumber:pageNumber,pageSize:pageSize},sortColumn&&sortDirection&&{sortColumn:sortColumn,sortDirection:sortDirection}),affectedComponents:getAffectedComponentsWithLoader([id],true)});case 4:case"end":return _context2.stop()}},_callee2)}));return _onPageChange.apply(this,arguments)}function handleSort(_x5,_x6){return _handleSort.apply(this,arguments)}function _handleSort(){_handleSort=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(column,direction){var currentProps,id;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:currentProps=gjsModel.get("componentProps");id=gjsModel.get("id");gjsModel.set("componentProps",_extends({},currentProps,{sortColumn:direction?column:null,sortDirection:direction}));_context3.next=5;return performInteraction({id:id,interactionType:"tableSort",payload:{sortColumn:direction?column:null,sortDirection:direction,tableId:id},affectedComponents:getAffectedComponentsWithLoader([id],true)});case 5:case"end":return _context3.stop()}},_callee3)}));return _handleSort.apply(this,arguments)}return/*#__PURE__*/_jsxs(Card,{ref:cardRef,className:"shadow border relative flex flex-col h-fit overflow-hidden","data-component-type":"table","data-table-id":gjsModel.get("id"),children:[/*#__PURE__*/_jsx(CardHeader,{children:/*#__PURE__*/_jsx("div",{className:"flex items-start justify-between",children:/*#__PURE__*/_jsxs("div",{className:"flex-1",children:[/*#__PURE__*/_jsx(CardTitle,{"data-slot":"title",contentEditable:isEditable,className:"text-2xl",children:title}),/*#__PURE__*/_jsx(CardDescription,{"data-slot":"subTitle",contentEditable:isEditable,className:"text-sm",children:subTitle})]})})}),/*#__PURE__*/_jsx(CardContent,{"data-slot":"bodyContent",contentEditable:false,className:"flex-1 flex flex-col overflow-hidden",children:attributes.error||allData.error||attributes.isMissing||allData.isMissing?renderNoDataFallback():/*#__PURE__*/_jsx(DataTable,{data:parsedData,headerMapper:headerMapper,className:className,isEditable:isEditable,actions:actions,pagination:pagination,isLoading:attributes.interactionApiInProgress||attributes.loading,onRowAction:onRowAction,onPageChange:onPageChange,onSort:handleSort,sortConfig:sortConfig,otherProps:rest,height:scrollAreaHeight})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:performInteraction,position:"top-right",tableActions:actions,firstRowData:Array.isArray(data)&&data.length>0?data[0]:{},isVisible:isEditable,componentProps:allData})]})}export function renderTab(props){var tabsWidth=157;var safeTabs=Array.isArray(props.tabs)?props.tabs:[];var showFallback=safeTabs.length===0;if(safeTabs.length>4){tabsWidth=157}var defaultValue=props.defaultValue||(safeTabs.length>0?safeTabs[0]:undefined);return/*#__PURE__*/_jsxs(Tabs,{defaultValue:defaultValue,children:[/*#__PURE__*/_jsx("div",{className:"text-center mb-4",children:/*#__PURE__*/_jsx(TabsList,{className:"bg-[#F9F9FE] border border-[#D4D5DE] p-1 rounded-lg h-auto",children:safeTabs.length>0?safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsTrigger,{value:tab,className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},children:tab},tab)}):/*#__PURE__*/_jsx(TabsTrigger,{value:"no-data",className:"\n w-["+tabsWidth+"px] h-[38px] gap-1 px-3 py-[11px]\n font-medium text-sm leading-4\n border-0 bg-[#F9F9FE] text-[#687387] rounded-none\n data-[state=active]:border data-[state=active]:border-solid data-[state=active]:border-[#2A44D4] data-[state=active]:bg-[#EAECFB] data-[state=active]:text-[#263DBF] data-[state=active]:shadow-none data-[state=active]:rounded-md\n transition-all duration-200\n ",style:{fontFamily:"Helvetica Neue",fontWeight:500,fontSize:"14px",lineHeight:"16px",letterSpacing:"0%"},disabled:true,children:"No tabs"})})}),showFallback?/*#__PURE__*/_jsx(TabsContent,{value:defaultValue||"no-data",className:"tabs-content","data-fallback":"true",children:renderNoDataFallback()}):safeTabs.map(function(tab){return/*#__PURE__*/_jsx(TabsContent,{value:tab,className:"tabs-content"},tab)})]})}export function renderMarkdown(props){var _attributes$isEditabl4;var gjsModel=props.gjsModel,_props$isCreatingAsse5=props.isCreatingAssetFromTemplate,isCreatingAssetFromTemplate=_props$isCreatingAsse5===void 0?false:_props$isCreatingAsse5,rest=_objectWithoutPropertiesLoose(props,_excluded5);// Memoize filtered props to avoid re-filtering on every render
13
+ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _useState15=useState(initialData),allData=_useState15[0],setAllData=_useState15[1];var _useState16=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState16[0],setAttributes=_useState16[1];var isEditable=(_attributes$isEditabl4=attributes.isEditable)!=null?_attributes$isEditabl4:false;useEffect(function(){var handlePropsChange=function handlePropsChange(){var newComponentProps=gjsModel.get("componentProps");var filteredProps=filterPlaceholders(newComponentProps);setAllData(function(prevData){return _extends({},prevData,filteredProps)})};gjsModel.on("change:componentProps",handlePropsChange);return function(){gjsModel.off("change:componentProps",handlePropsChange)}},[gjsModel]);useEffect(function(){var handleAttributesChange=function handleAttributesChange(){setAttributes(_extends({},gjsModel.get("attributes")))};gjsModel.on("change:attributes",handleAttributesChange);return function(){gjsModel.off("change:attributes",handleAttributesChange)}},[gjsModel]);var _useState17=useState(false),isEditing=_useState17[0],setIsEditing=_useState17[1];var _useState18=useState(false),isEditingHeading=_useState18[0],setIsEditingHeading=_useState18[1];var editRef=useRef(null);var headingEditRef=useRef(null);var startEditing=function startEditing(){setIsEditing(true);setTimeout(function(){setupEditor()},0)};var startEditingHeading=function startEditingHeading(){setIsEditingHeading(true);setTimeout(function(){setupHeadingEditor()},0)};var setupEditor=function setupEditor(){if(!editRef.current){return}var editor=editRef.current;editor.innerHTML="";var effectiveText=isCreatingAssetFromTemplate&&allData.sampleData!==undefined?allData.sampleData:allData.summaryText;editor.textContent=effectiveText;editor.focus()};var setupHeadingEditor=function setupHeadingEditor(){if(!headingEditRef.current){return}var editor=headingEditRef.current;editor.innerHTML="";editor.textContent=allData.summaryHeading||"Insights";editor.focus()};// Save changes and exit editing mode
14
+ var saveChanges=function saveChanges(){if(!editRef.current){return}var content=editRef.current.innerText||"";setAllData(function(prev){return _extends({},prev,{summaryText:content})});setIsEditing(false);editRef.current.innerHTML=""};var saveHeadingChanges=function saveHeadingChanges(){if(!headingEditRef.current){return}var content=headingEditRef.current.innerText||"Insights";setAllData(function(prev){return _extends({},prev,{summaryHeading:content})});setIsEditingHeading(false);headingEditRef.current.innerHTML=""};var markdownStyles={ul:{props:{className:"list-disc"}},h1:{props:{className:"text-4xl font-bold leading-[4rem]"}},h2:{props:{className:"text-3xl font-bold leading-[3rem]"}},h3:{props:{className:"text-2xl font-bold leading-[2rem]"}},h4:{props:{className:"text-xl font-bold leading-[2.5rem]"}},h5:{props:{className:"text-lg font-bold leading-[2.5rem]"}},h6:{props:{className:"text-base font-bold leading-[2rem]"}}};var summaryText=allData.summaryText,summaryHeading=allData.summaryHeading,sampleData=allData.sampleData;var effectiveSummaryText=isCreatingAssetFromTemplate&&sampleData!==undefined?sampleData:summaryText;var hasError=attributes.error||allData.error;var hasMissing=attributes.isMissing||allData.isMissing;var isLoading=attributes.loading&&!hasError&&!hasMissing||attributes.interactionApiInProgress;if(isLoading){return/*#__PURE__*/_jsx(MarkdownLoader,{})}if(hasError||hasMissing){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:summaryHeading||"Insights"}),/*#__PURE__*/_jsxs("div",{className:"w-full py-8 flex flex-col items-center justify-center px-6 text-center",style:{minHeight:"180px"},children:[/*#__PURE__*/_jsx(CircleAlert,{className:"w-12 h-12 text-gray-400 mb-2"}),/*#__PURE__*/_jsx("h3",{className:"text-lg font-medium text-gray-900",children:"No data available"}),/*#__PURE__*/_jsx("p",{className:"mt-2 text-sm text-gray-500 max-w-md",children:"Check your filters or try a different time range."})]}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}if(!isEditable){return/*#__PURE__*/_jsxs("div",_extends({className:"px-[1em] relative"},rest,{children:[/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",children:summaryHeading||"Insights"}),/*#__PURE__*/_jsx("div",{"data-slot":"summaryText",children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:effectiveSummaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}return/*#__PURE__*/_jsxs("div",_extends({className:"p-[1em] relative"},rest,{children:[isEditingHeading?/*#__PURE__*/_jsx("div",{ref:headingEditRef,contentEditable:true,onBlur:saveHeadingChanges,"data-slot":"summaryHeading",className:"text-xl font-semibold text-left",suppressContentEditableWarning:true}):/*#__PURE__*/_jsx("h3",{className:"text-xl font-semibold text-left",onClick:startEditingHeading,"data-slot":"summaryHeading",children:allData.summaryHeading||"Insights"}),isEditing?/*#__PURE__*/_jsx("div",{ref:editRef,contentEditable:true,onBlur:saveChanges,"data-slot":"summaryText",className:"p-2 min-h-[100px] whitespace-pre-wrap",suppressContentEditableWarning:true,style:{whiteSpace:"pre-wrap",wordWrap:"break-word"}}):/*#__PURE__*/_jsx("div",{onClick:startEditing,"data-slot":"summaryText",style:{whiteSpace:"pre-wrap",wordWrap:"break-word"},children:/*#__PURE__*/_jsx(Markdown,{options:{overrides:markdownStyles},children:effectiveSummaryText})}),/*#__PURE__*/_jsx(StyledInfoButton,{componentId:gjsModel.get("id"),performInteraction:props.performInteraction,position:"top-right",isVisible:isEditable,componentProps:allData})]}))}export function renderButton(props){var _attributes$isEditabl5;var gjsModel=props.gjsModel,_props$performInterac4=props.performInteraction,performInteraction=_props$performInterac4===void 0?function(){}:_props$performInterac4;var _useState19=useState(_extends({},props)),allData=_useState19[0],setAllData=_useState19[1];var _useState20=useState(_extends({},gjsModel.get("attributes"))),attributes=_useState20[0],setAttributes=_useState20[1];var isEditable=(_attributes$isEditabl5=attributes.isEditable)!=null?_attributes$isEditabl5:false;useEffect(function(){gjsModel.on("change:componentProps",function(){setAllData(_extends({},gjsModel.get("componentProps")))})},[]);useEffect(function(){gjsModel.on("change:attributes",function(){setAttributes(_extends({},gjsModel.get("attributes")))})},[]);var text=allData.text,className=allData.className,payload=allData.payload,_allData$variant=allData.variant,variant=_allData$variant===void 0?"default":_allData$variant,_allData$size=allData.size,size=_allData$size===void 0?"sm":_allData$size,affectedComponents=allData.affectedComponents,tooltipContent=allData.tooltipContent;function interact(){var id=gjsModel.get("id");performInteraction({id:id,interactionType:"button",affectedComponents:getAffectedComponentsWithLoader([id].concat(affectedComponents),true),payload:payload})}return/*#__PURE__*/_jsx(TooltipButton,{className:className,isEditable:isEditable,interact:interact,attributes:attributes,variant:variant,size:size,text:text,tooltipContent:tooltipContent})}var renderActionCardWithWrapper=function renderActionCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"ActionCard"}),children:renderActionCard(props)})};var renderButtonWithWrapper=function renderButtonWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Button"}),children:renderButton(props)})};var renderCardWithWrapper=function renderCardWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Card"}),children:renderCard(props)})};var renderChartWithWrapper=function renderChartWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Chart"}),children:renderChart(props)})};var renderFilterWithWrapper=function renderFilterWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Filter"}),children:renderFilter(props)})};var renderMarkdownWithWrapper=function renderMarkdownWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Markdown"}),children:renderMarkdown(props)})};var renderSearchWithWrapper=function renderSearchWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Search"}),children:renderSearch(props)})};var renderTableWithWrapper=function renderTableWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Table"}),children:renderTable(props)})};var renderTabWithWrapper=function renderTabWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Tabs"}),children:renderTab(props)})};function renderActions(props){var actions=props.actions,_props$isEditable=props.isEditable,isEditable=_props$isEditable===void 0?false:_props$isEditable,gjsModel=props.gjsModel;if(actions===null){return/*#__PURE__*/_jsx("div",{})}if(!Array.isArray(actions)||actions.length===0){return/*#__PURE__*/_jsx("div",{className:"bg-white text-black p-4 rounded-lg border flex flex-col h-full shadow-none relative",children:/*#__PURE__*/_jsx(CardLoader,{})})}return/*#__PURE__*/_jsx("div",{className:"dashboard-cards flex flex-wrap gap-4",children:actions.map(function(action,index){var icon=action.icon,title=action.title,description=action.description;return/*#__PURE__*/_jsx("div",{className:"flex-1 min-w-[200px]",children:renderActionCard({icon:icon,headerContent:title,bodyContent:description,isEditable:isEditable,gjsModel:gjsModel})},index)})})}var renderActionsWithWrapper=function renderActionsWithWrapper(props){return/*#__PURE__*/_jsx(ComponentWrapper,{componentProps:_extends({},props,{componentType:"Actions"}),children:renderActions(props)})};export function getRenderers(){return{ActionCard:renderActionCardWithWrapper,Actions:renderActionsWithWrapper,Button:renderButtonWithWrapper,Card:renderCardWithWrapper,Chart:renderChartWithWrapper,Filter:renderFilterWithWrapper,Markdown:renderMarkdownWithWrapper,Search:renderSearchWithWrapper,Table:renderTableWithWrapper,Tabs:renderTabWithWrapper}}
13
15
  //# sourceMappingURL=render-components.js.map