@peak-ai/canvas 1.5.2 → 1.6.0-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GrapesjsCanvas.d.ts +4 -3
- package/GrapesjsCanvas.js +16 -7
- package/GrapesjsCanvas.js.map +1 -1
- package/components/PageNavigator.d.ts +10 -0
- package/components/PageNavigator.js +2 -0
- package/components/PageNavigator.js.map +1 -0
- package/contexts/PageContext.d.ts +22 -0
- package/contexts/PageContext.js +3 -0
- package/contexts/PageContext.js.map +1 -0
- package/helpers/merge-json.d.ts +1 -3
- package/helpers/merge-json.js +1 -1
- package/helpers/merge-json.js.map +1 -1
- package/helpers/page-utils.d.ts +14 -0
- package/helpers/page-utils.js +4 -0
- package/helpers/page-utils.js.map +1 -0
- package/index.d.ts +3 -0
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/plugins/grapejs-plugin.d.ts +1 -1
- package/plugins/grapejs-plugin.js +4 -3
- package/plugins/grapejs-plugin.js.map +1 -1
- package/plugins/helpers/render-components.js +2 -1
- package/plugins/helpers/render-components.js.map +1 -1
- package/shadcn/components/ui/date-filter.d.ts +1 -1
- package/shadcn/components/ui/date-filter.js +2 -2
- package/shadcn/components/ui/date-filter.js.map +1 -1
- package/types/page.d.js +2 -0
- package/types/page.d.js.map +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"page-utils.js","names":["mergeStyles","globalStyles","pageStyles","length","merged","concat","selectorMap","Map","forEach","styleObj","index","key","selectors","sort","join","set","pageStyleObj","existingIndex","get","undefined","_extends","style","push","getCurrentPage","pages","currentPageId","find","p","id","extractPageMetadata","page","dataQueries","order","name","validateMultiPageJson","json","errors","valid","Array","isArray","frames","console","warn","normalizeMultiPageJson","normalizedPages","map"],"sources":["../../src/helpers/page-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Page, PageStyle } from '../types/page';\n\nexport function mergeStyles(globalStyles: PageStyle[], pageStyles: PageStyle[] = []): PageStyle[] {\n if (!pageStyles || pageStyles.length === 0) {\n return globalStyles;\n }\n\n const merged = [...globalStyles];\n const selectorMap = new Map<string, number>();\n\n globalStyles.forEach((styleObj, index) => {\n const key = styleObj.selectors.sort().join(',');\n\n selectorMap.set(key, index);\n });\n\n pageStyles.forEach((pageStyleObj) => {\n const key = pageStyleObj.selectors.sort().join(',');\n const existingIndex = selectorMap.get(key);\n\n if (existingIndex !== undefined) {\n merged[existingIndex] = {\n ...merged[existingIndex],\n style: {\n ...merged[existingIndex].style,\n ...pageStyleObj.style,\n },\n };\n } else {\n merged.push(pageStyleObj);\n }\n });\n\n return merged;\n}\n\nexport function getCurrentPage(pages: Page[], currentPageId?: string): Page | null {\n if (!pages || pages.length === 0) {\n return null;\n }\n\n if (!currentPageId) {\n return pages[0];\n }\n\n return pages.find((p) => p.id === currentPageId) || pages[0];\n}\n\nexport function extractPageMetadata(page: Page): {\n dataQueries?: string[];\n id: string;\n name: string;\n order: number;\n} {\n return {\n dataQueries: page.dataQueries,\n id: page.id || `page-${page.order || 1}`,\n name: page.name || `Page ${page.order || 1}`,\n order: page.order || 1,\n };\n}\n\nexport function validateMultiPageJson(json: any): { errors: string[]; valid: boolean } {\n const errors: string[] = [];\n\n if (!json) {\n errors.push('JSON is null or undefined');\n\n return { errors, valid: false };\n }\n\n if (!Array.isArray(json.pages)) {\n errors.push('JSON must have a \"pages\" array');\n\n return { errors, valid: false };\n }\n\n if (json.pages.length === 0) {\n errors.push('JSON must have at least one page');\n\n return { errors, valid: false };\n }\n\n json.pages.forEach((page: any, index: number) => {\n if (!page.frames || !Array.isArray(page.frames) || page.frames.length === 0) {\n errors.push(`Page at index ${index} must have at least one frame`);\n }\n\n if (!page.id) {\n // eslint-disable-next-line no-console\n console.warn(`Page at index ${index} is missing an \"id\" field`);\n }\n\n if (!page.name) {\n // eslint-disable-next-line no-console\n console.warn(`Page at index ${index} is missing a \"name\" field`);\n }\n });\n\n return { errors, valid: errors.length === 0 };\n}\n\nexport function normalizeMultiPageJson(json: any): any {\n if (!json || !json.pages || !Array.isArray(json.pages)) {\n return json;\n }\n\n const normalizedPages = json.pages.map((page: any, index: number) => ({\n ...page,\n id: page.id || `page-${index + 1}`,\n name: page.name || `Page ${index + 1}`,\n order: page.order !== undefined ? page.order : index + 1,\n }));\n\n return {\n ...json,\n pages: normalizedPages,\n };\n}\n"],"mappings":"qDAAA,uDAGA,MAAO,SAAS,CAAAA,WAAWA,CAACC,YAAyB,CAAEC,UAAuB,CAAoB,IAA3CA,UAAuB,WAAvBA,UAAuB,CAAG,EAAE,CACjF,GAAI,CAACA,UAAU,EAAIA,UAAU,CAACC,MAAM,GAAK,CAAC,CAAE,CAC1C,MAAO,CAAAF,YACT,CAEA,GAAM,CAAAG,MAAM,IAAAC,MAAA,CAAOJ,YAAY,CAAC,CAChC,GAAM,CAAAK,WAAW,CAAG,GAAI,CAAAC,GAAqB,CAE7CN,YAAY,CAACO,OAAO,CAAC,SAACC,QAAQ,CAAEC,KAAK,CAAK,CACxC,GAAM,CAAAC,GAAG,CAAGF,QAAQ,CAACG,SAAS,CAACC,IAAI,CAAC,CAAC,CAACC,IAAI,CAAC,GAAG,CAAC,CAE/CR,WAAW,CAACS,GAAG,CAACJ,GAAG,CAAED,KAAK,CAC5B,CAAC,CAAC,CAEFR,UAAU,CAACM,OAAO,CAAC,SAACQ,YAAY,CAAK,CACnC,GAAM,CAAAL,GAAG,CAAGK,YAAY,CAACJ,SAAS,CAACC,IAAI,CAAC,CAAC,CAACC,IAAI,CAAC,GAAG,CAAC,CACnD,GAAM,CAAAG,aAAa,CAAGX,WAAW,CAACY,GAAG,CAACP,GAAG,CAAC,CAE1C,GAAIM,aAAa,GAAKE,SAAS,CAAE,CAC/Bf,MAAM,CAACa,aAAa,CAAC,CAAAG,QAAA,IAChBhB,MAAM,CAACa,aAAa,CAAC,EACxBI,KAAK,CAAAD,QAAA,IACAhB,MAAM,CAACa,aA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ClCuB,IAAI,CAAEH,IAAI,CAACG,IAAI,WAAYvB,KAAK,CAAG,CAAC,CAAE,CACtCsB,KAAK,CAAEF,IAAI,CAACE,KAAK,GAAKb,SAAS,CAAGW,IAAI,CAACE,KAAK,CAAGtB,KAAK,CAAG,CAAC,GACxD,CAAC,CAEH,OAAAU,QAAA,IACKe,IAAI,EACPX,KAAK,CAAEoB,eAAe,EAE1B","ignoreList":[]}
|
package/index.d.ts
CHANGED
|
@@ -7,3 +7,6 @@ export { AiAvatarIcon } from './shadcn/components/icons/AiAvatarIcon';
|
|
|
7
7
|
export { CustomModal } from './plugins/helpers/custom-modal';
|
|
8
8
|
export { QueryDetailsModal } from './plugins/helpers/query-details-modal';
|
|
9
9
|
export { QueryLoadingModal } from './plugins/helpers/query-loading-modal';
|
|
10
|
+
export { PageProvider, usePageContext, useRequiredPageContext, useCurrentPage, usePageNavigation, } from './contexts/PageContext';
|
|
11
|
+
export { mergeStyles, getCurrentPage, extractPageMetadata, validateMultiPageJson, normalizeMultiPageJson, } from './helpers/page-utils';
|
|
12
|
+
export type { PageMetadata, PageStyle, NavigateToPageAction, Page, PageContext, PageAwareProps, MultiPageUIJson, } from './types/page';
|
package/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{default as GrapejsCanvas}from"./GrapesjsCanvas";export*from"./index.styles";export{getUpdatedUiJson}from"./helpers/merge-json";export{DataTable}from"./plugins/helpers/data-table";export{StyledInfoButton}from"./plugins/helpers/styled-info-button";export{AiAvatarIcon}from"./shadcn/components/icons/AiAvatarIcon";export{CustomModal}from"./plugins/helpers/custom-modal";export{QueryDetailsModal}from"./plugins/helpers/query-details-modal";export{QueryLoadingModal}from"./plugins/helpers/query-loading-modal";
|
|
1
|
+
export{default as GrapejsCanvas}from"./GrapesjsCanvas";export*from"./index.styles";export{getUpdatedUiJson}from"./helpers/merge-json";export{DataTable}from"./plugins/helpers/data-table";export{StyledInfoButton}from"./plugins/helpers/styled-info-button";export{AiAvatarIcon}from"./shadcn/components/icons/AiAvatarIcon";export{CustomModal}from"./plugins/helpers/custom-modal";export{QueryDetailsModal}from"./plugins/helpers/query-details-modal";export{QueryLoadingModal}from"./plugins/helpers/query-loading-modal";export{PageProvider,usePageContext,useRequiredPageContext,useCurrentPage,usePageNavigation}from"./contexts/PageContext";export{mergeStyles,getCurrentPage,extractPageMetadata,validateMultiPageJson,normalizeMultiPageJson}from"./helpers/page-utils";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["default","GrapejsCanvas","getUpdatedUiJson","DataTable","StyledInfoButton","AiAvatarIcon","CustomModal","QueryDetailsModal","QueryLoadingModal"],"sources":["../src/index.ts"],"sourcesContent":["export { default as GrapejsCanvas } from './GrapesjsCanvas';\nexport * from './index.styles';\nexport { getUpdatedUiJson } from './helpers/merge-json';\nexport { DataTable } from './plugins/helpers/data-table';\nexport { StyledInfoButton } from './plugins/helpers/styled-info-button';\nexport { AiAvatarIcon } from './shadcn/components/icons/AiAvatarIcon';\nexport { CustomModal } from './plugins/helpers/custom-modal';\nexport { QueryDetailsModal } from './plugins/helpers/query-details-modal';\nexport { QueryLoadingModal } from './plugins/helpers/query-loading-modal';\n"],"mappings":"AAAA,OAASA,OAAO,GAAI,CAAAC,aAAa,KAAQ,kBAAkB,CAC3D,WAAc,gBAAgB,CAC9B,OAASC,gBAAgB,KAAQ,sBAAsB,CACvD,OAASC,SAAS,KAAQ,8BAA8B,CACxD,OAASC,gBAAgB,KAAQ,sCAAsC,CACvE,OAASC,YAAY,KAAQ,wCAAwC,CACrE,OAASC,WAAW,KAAQ,gCAAgC,CAC5D,OAASC,iBAAiB,KAAQ,uCAAuC,CACzE,OAASC,iBAAiB,KAAQ,uCAAuC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["default","GrapejsCanvas","getUpdatedUiJson","DataTable","StyledInfoButton","AiAvatarIcon","CustomModal","QueryDetailsModal","QueryLoadingModal","PageProvider","usePageContext","useRequiredPageContext","useCurrentPage","usePageNavigation","mergeStyles","getCurrentPage","extractPageMetadata","validateMultiPageJson","normalizeMultiPageJson"],"sources":["../src/index.ts"],"sourcesContent":["export { default as GrapejsCanvas } from './GrapesjsCanvas';\nexport * from './index.styles';\nexport { getUpdatedUiJson } from './helpers/merge-json';\nexport { DataTable } from './plugins/helpers/data-table';\nexport { StyledInfoButton } from './plugins/helpers/styled-info-button';\nexport { AiAvatarIcon } from './shadcn/components/icons/AiAvatarIcon';\nexport { CustomModal } from './plugins/helpers/custom-modal';\nexport { QueryDetailsModal } from './plugins/helpers/query-details-modal';\nexport { QueryLoadingModal } from './plugins/helpers/query-loading-modal';\nexport {\n PageProvider,\n usePageContext,\n useRequiredPageContext,\n useCurrentPage,\n usePageNavigation,\n} from './contexts/PageContext';\nexport {\n mergeStyles,\n getCurrentPage,\n extractPageMetadata,\n validateMultiPageJson,\n normalizeMultiPageJson,\n} from './helpers/page-utils';\nexport type {\n PageMetadata,\n PageStyle,\n NavigateToPageAction,\n Page,\n PageContext,\n PageAwareProps,\n MultiPageUIJson,\n} from './types/page';\n"],"mappings":"AAAA,OAASA,OAAO,GAAI,CAAAC,aAAa,KAAQ,kBAAkB,CAC3D,WAAc,gBAAgB,CAC9B,OAASC,gBAAgB,KAAQ,sBAAsB,CACvD,OAASC,SAAS,KAAQ,8BAA8B,CACxD,OAASC,gBAAgB,KAAQ,sCAAsC,CACvE,OAASC,YAAY,KAAQ,wCAAwC,CACrE,OAASC,WAAW,KAAQ,gCAAgC,CAC5D,OAASC,iBAAiB,KAAQ,uCAAuC,CACzE,OAASC,iBAAiB,KAAQ,uCAAuC,CACzE,OACEC,YAAY,CACZC,cAAc,CACdC,sBAAsB,CACtBC,cAAc,CACdC,iBAAiB,KACZ,wBAAwB,CAC/B,OACEC,WAAW,CACXC,cAAc,CACdC,mBAAmB,CACnBC,qBAAqB,CACrBC,sBAAsB,KACjB,sBAAsB","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { Editor, Component } from 'grapesjs';
|
|
2
|
-
export declare function createGrapesjsShadcnGenericPlugin(mode: 'editor' | 'preview', performInteraction: (payload: Record<string, any>) => void, renderedComponents: Record<string, Component> | undefined, setHasChanged: (hasChanged: boolean) => void, isTemplateView?: boolean, isStreaming?: boolean): (editor: Editor) => void;
|
|
2
|
+
export declare function createGrapesjsShadcnGenericPlugin(mode: 'editor' | 'preview', performInteraction: (payload: Record<string, any>) => void, renderedComponents: Record<string, Component> | undefined, setHasChanged: (hasChanged: boolean) => void, isTemplateView?: boolean, isStreaming?: boolean, navigateToPage?: (pageId: string) => void): (editor: Editor) => void;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import _extends from"@babel/runtime/helpers/extends";/* eslint-disable import/no-named-as-default-member *//* eslint-disable func-names *//* eslint-disable @typescript-eslint/no-explicit-any */import ReactDOM from"react-dom";import{getRenderers}from"./helpers/render-components";import{QueryCacheProvider}from"./helpers/query-cache-context";import{jsx as _jsx}from"react/jsx-runtime";export function createGrapesjsShadcnGenericPlugin(mode,performInteraction,renderedComponents,setHasChanged,isTemplateView,isStreaming){if(renderedComponents===void 0){renderedComponents={}}if(isTemplateView===void 0){isTemplateView=false}if(isStreaming===void 0){isStreaming=false}return function grapesjsShadcnGenericPlugin(editor){editor.DomComponents.addType("shadcn-generic",{model:{defaults:{tagName:"div",droppable:false,componentName:"Card",componentProps:{},traits:[]}},view:{events:{"input [data-slot]":"handleSlotInput"},handleSlotInput:function handleSlotInput(e){var target=e.target;var slot=target.dataset.slot;var text=target.innerText;var props=this.model.get("componentProps")||{};if(!slot){return}if(slot.startsWith("table-header-")){var _props$data;var idx=parseInt(slot.split("-")[2],10);var dataKeys=Object.keys(((_props$data=props.data)==null?void 0:_props$data[0])||{});if(!props.headerMapper){props.headerMapper={}}var key=dataKeys[idx];if(key){props.headerMapper[key]=text}}else{props[slot]=text}this.model.set("componentProps",_extends({},props));if(!["search-input"].includes(slot)){setHasChanged(true)}},render:function render(){var _this=this;var compName=this.model.get("componentName");var compProps=this.model.get("componentProps");if(typeof compProps==="string"){try{compProps=JSON.parse(compProps)}catch(err){// eslint-disable-next-line no-console
|
|
2
|
-
console.error("Invalid JSON in componentProps",err);compProps={}}}compProps.performInteraction=performInteraction;compProps.isTemplateView=isTemplateView;compProps.isEditable=mode==="editor"&&!isStreaming;compProps.onChange=function(data){_this.model.set("componentProps",_extends({},_this.model.get("componentProps"),data))};var renderers=getRenderers();var Renderer=renderers[compName];if(Renderer){if(compName==="Tabs"){this._cleanupTabsSetup();ReactDOM.render(/*#__PURE__*/_jsx(QueryCacheProvider,{maxCacheSize:100,maxCacheAge:5*60*1000,children:/*#__PURE__*/_jsx(Renderer,_extends({},compProps,{gjsModel:this.model}))}),this.el);var children=this.model.components();if(children.length===0){return this}var tabAttributes=this.model.get("attributes")||{};var hasTabsError=tabAttributes.error||compProps.error;var hasTabsMissing=tabAttributes.isMissing||compProps.isMissing;var injectChildren=function injectChildren(){var tabsContent=_this.el.querySelectorAll(".tabs-content");var isFallback=Array.from(tabsContent).some(function(el){return el.dataset.fallback==="true"});if(isFallback||tabsContent.length===0){return false}children.each(function(childModel){_this.stopListening(childModel,"change:attributes")});children.each(function(childModel,i){var container=tabsContent[i];if(!container){return}var childView=_this.createView(childModel);if(childView){container.innerHTML="";childView.render();container.appendChild(childView.el);_this.listenTo(childModel,"change:attributes",function(){var childAttributes=childModel.get("attributes")||{};var childProps=childModel.get("componentProps")||{};var hasError=hasTabsError||childAttributes.error||childProps.error;var hasMissing=hasTabsMissing||childAttributes.isMissing||childProps.isMissing;if(hasError||hasMissing){childModel.set("attributes",_extends({},childAttributes,{loading:false,error:hasError,isMissing:hasMissing,inheritedFromParent:!!(hasTabsError||hasTabsMissing)}),{silent:false})}})}});return true};if(injectChildren()){return this}this._tabsTimeoutId=setTimeout(function(){if(injectChildren()){return}// eslint-disable-next-line no-console
|
|
3
|
-
console.warn("Could not inject tabs content after delay")},100)}else{ReactDOM.render(/*#__PURE__*/_jsx(QueryCacheProvider,{maxCacheSize:100,maxCacheAge:5*60*1000,children:/*#__PURE__*/_jsx(Renderer,_extends({},compProps,{gjsModel:this.model}))}),this.el)}}else{this.el.innerHTML="<div>Unsupported component: "+compName+"</div>"}renderedComponents[this.model.get("id")]=this.model
|
|
1
|
+
import _extends from"@babel/runtime/helpers/extends";/* eslint-disable import/no-named-as-default-member *//* eslint-disable func-names *//* eslint-disable @typescript-eslint/no-explicit-any */import ReactDOM from"react-dom";import{getRenderers}from"./helpers/render-components";import{QueryCacheProvider}from"./helpers/query-cache-context";import{jsx as _jsx}from"react/jsx-runtime";export function createGrapesjsShadcnGenericPlugin(mode,performInteraction,renderedComponents,setHasChanged,isTemplateView,isStreaming,navigateToPage){if(renderedComponents===void 0){renderedComponents={}}if(isTemplateView===void 0){isTemplateView=false}if(isStreaming===void 0){isStreaming=false}return function grapesjsShadcnGenericPlugin(editor){editor.DomComponents.addType("shadcn-generic",{model:{defaults:{tagName:"div",droppable:false,componentName:"Card",componentProps:{},traits:[]}},view:{events:{"input [data-slot]":"handleSlotInput"},handleSlotInput:function handleSlotInput(e){var target=e.target;var slot=target.dataset.slot;var text=target.innerText;var props=this.model.get("componentProps")||{};if(!slot){return}if(slot.startsWith("table-header-")){var _props$data;var idx=parseInt(slot.split("-")[2],10);var dataKeys=Object.keys(((_props$data=props.data)==null?void 0:_props$data[0])||{});if(!props.headerMapper){props.headerMapper={}}var key=dataKeys[idx];if(key){props.headerMapper[key]=text}}else{props[slot]=text}this.model.set("componentProps",_extends({},props));if(!["search-input"].includes(slot)){setHasChanged(true)}},render:function render(){var _this=this;var compName=this.model.get("componentName");var compProps=this.model.get("componentProps");if(typeof compProps==="string"){try{compProps=JSON.parse(compProps)}catch(err){// eslint-disable-next-line no-console
|
|
2
|
+
console.error("Invalid JSON in componentProps",err);compProps={}}}compProps.performInteraction=performInteraction;compProps.navigateToPage=navigateToPage;compProps.isTemplateView=isTemplateView;compProps.isEditable=mode==="editor"&&!isStreaming;compProps.onChange=function(data){_this.model.set("componentProps",_extends({},_this.model.get("componentProps"),data))};var renderers=getRenderers();var Renderer=renderers[compName];if(Renderer){if(compName==="Tabs"){this._cleanupTabsSetup();ReactDOM.render(/*#__PURE__*/_jsx(QueryCacheProvider,{maxCacheSize:100,maxCacheAge:5*60*1000,children:/*#__PURE__*/_jsx(Renderer,_extends({},compProps,{gjsModel:this.model}))}),this.el);var children=this.model.components();if(children.length===0){return this}var tabAttributes=this.model.get("attributes")||{};var hasTabsError=tabAttributes.error||compProps.error;var hasTabsMissing=tabAttributes.isMissing||compProps.isMissing;var injectChildren=function injectChildren(){var tabsContent=_this.el.querySelectorAll(".tabs-content");var isFallback=Array.from(tabsContent).some(function(el){return el.dataset.fallback==="true"});if(isFallback||tabsContent.length===0){return false}children.each(function(childModel){_this.stopListening(childModel,"change:attributes")});children.each(function(childModel,i){var container=tabsContent[i];if(!container){return}var childView=_this.createView(childModel);if(childView){container.innerHTML="";childView.render();container.appendChild(childView.el);_this.listenTo(childModel,"change:attributes",function(){var childAttributes=childModel.get("attributes")||{};var childProps=childModel.get("componentProps")||{};var hasError=hasTabsError||childAttributes.error||childProps.error;var hasMissing=hasTabsMissing||childAttributes.isMissing||childProps.isMissing;if(hasError||hasMissing){childModel.set("attributes",_extends({},childAttributes,{loading:false,error:hasError,isMissing:hasMissing,inheritedFromParent:!!(hasTabsError||hasTabsMissing)}),{silent:false})}})}});return true};if(injectChildren()){return this}this._tabsTimeoutId=setTimeout(function(){if(injectChildren()){return}// eslint-disable-next-line no-console
|
|
3
|
+
console.warn("Could not inject tabs content after delay")},100)}else{ReactDOM.render(/*#__PURE__*/_jsx(QueryCacheProvider,{maxCacheSize:100,maxCacheAge:5*60*1000,children:/*#__PURE__*/_jsx(Renderer,_extends({},compProps,{gjsModel:this.model}))}),this.el)}}else{this.el.innerHTML="<div>Unsupported component: "+compName+"</div>"}renderedComponents[this.model.get("id")]=this.model;// eslint-disable-next-line no-console
|
|
4
|
+
console.log("[GrapesJS Plugin] Component registered: "+this.model.get("id")+" ("+compName+")");return this},_cleanupTabsSetup:function _cleanupTabsSetup(){if(this._tabsTimeoutId){clearTimeout(this._tabsTimeoutId);this._tabsTimeoutId=null}},createView:function createView(model){var _this$em$get$getType;var ComponentView=(_this$em$get$getType=this.em.get("DomComponents").getType(model.get("type")))==null?void 0:_this$em$get$getType.view;if(!ComponentView){// eslint-disable-next-line no-console
|
|
4
5
|
console.warn("No view found for component type:",model.get("type"));return null}var view=new ComponentView({model:model,config:this.config,componentTypes:this.componentTypes});return view},remove:function remove(){this.stopListening();this._cleanupTabsSetup();// eslint-disable-next-line import/no-named-as-default-member
|
|
5
6
|
ReactDOM.unmountComponentAtNode(this.el);return this}}})}}
|
|
6
7
|
//# sourceMappingURL=grapejs-plugin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grapejs-plugin.js","names":["ReactDOM","getRenderers","QueryCacheProvider","jsx","_jsx","createGrapesjsShadcnGenericPlugin","mode","performInteraction","renderedComponents","setHasChanged","isTemplateView","isStreaming","grapesjsShadcnGenericPlugin","editor","DomComponents","addType","model","defaults","tagName","droppable","componentName","componentProps","traits","view","events","handleSlotInput","e","target","slot","dataset","text","innerText","props","get","startsWith","_props$data","idx","parseInt","split","dataKeys","Object","keys","data","headerMapper","key","set","_extends","includes","render","_this","compName","compProps","JSON","parse","err","console","error","isEditable","onChange","renderers","Renderer","_cleanupTabsSetup","maxCacheSize","maxCacheAge","children","gjsModel","el","components","length","tabAttributes","hasTabsError","hasTabsMissing","isMissing","injectChildren","tabsContent","querySelectorAll","isFallback","Array","from","some","fallback","each","childModel","stopListening","i","container","childView","createView","innerHTML","appendChild","listenTo","childAttributes","childProps","hasError","hasMissing","loading","inheritedFromParent","silent","_tabsTimeoutId","setTimeout","warn","clearTimeout","_this$em$get$getType","ComponentView","em","getType","config","componentTypes","remove","unmountComponentAtNode"],"sources":["../../src/plugins/grapejs-plugin.tsx"],"sourcesContent":["/* eslint-disable import/no-named-as-default-member */\n/* eslint-disable func-names */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport ReactDOM from 'react-dom';\nimport { Editor, Component } from 'grapesjs';\nimport { getRenderers } from './helpers/render-components';\nimport { QueryCacheProvider } from './helpers/query-cache-context';\n\nexport function createGrapesjsShadcnGenericPlugin(\n mode: 'editor' | 'preview',\n performInteraction: (payload: Record<string, any>) => void,\n renderedComponents: Record<string, Component> = {},\n setHasChanged: (hasChanged: boolean) => void,\n isTemplateView = false,\n isStreaming = false,\n) {\n return function grapesjsShadcnGenericPlugin(editor: Editor): void {\n editor.DomComponents.addType('shadcn-generic', {\n model: {\n defaults: {\n tagName: 'div',\n droppable: false,\n componentName: 'Card',\n componentProps: {},\n traits: [],\n },\n },\n view: {\n events: {\n 'input [data-slot]': 'handleSlotInput',\n } as any,\n handleSlotInput(e: Event) {\n const target = e.target as HTMLElement;\n const slot = target.dataset.slot;\n const text = target.innerText;\n\n const props = this.model.get('componentProps') || {};\n\n if (!slot) {\n return;\n }\n\n if (slot.startsWith('table-header-')) {\n const idx = parseInt(slot.split('-')[2], 10);\n const dataKeys = Object.keys(props.data?.[0] || {});\n\n if (!props.headerMapper) {\n props.headerMapper = {};\n }\n\n const key = dataKeys[idx];\n\n if (key) {\n props.headerMapper[key] = text;\n }\n } else {\n props[slot] = text;\n }\n\n this.model.set('componentProps', {\n ...props,\n });\n\n if (!['search-input'].includes(slot)) {\n setHasChanged(true);\n }\n },\n render: function () {\n const compName: string = this.model.get('componentName');\n let compProps: any = this.model.get('componentProps');\n\n if (typeof compProps === 'string') {\n try {\n compProps = JSON.parse(compProps);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Invalid JSON in componentProps', err);\n compProps = {};\n }\n }\n\n compProps.performInteraction = performInteraction;\n compProps.isTemplateView = isTemplateView;\n compProps.isEditable = mode === 'editor' && !isStreaming;\n\n compProps.onChange = (data: Record<string, any>) => {\n this.model.set('componentProps', {\n ...this.model.get('componentProps'),\n ...data,\n });\n };\n\n const renderers = getRenderers();\n const Renderer = renderers[compName];\n\n if (Renderer) {\n if (compName === 'Tabs') {\n this._cleanupTabsSetup();\n\n ReactDOM.render(\n <QueryCacheProvider maxCacheSize={100} maxCacheAge={5 * 60 * 1000}>\n <Renderer {...compProps} gjsModel={this.model} />\n </QueryCacheProvider>,\n this.el,\n );\n\n const children = this.model.components();\n\n if (children.length === 0) {\n return this;\n }\n\n const tabAttributes = this.model.get('attributes') || {};\n const hasTabsError = tabAttributes.error || compProps.error;\n const hasTabsMissing = tabAttributes.isMissing || compProps.isMissing;\n\n const injectChildren = () => {\n const tabsContent = this.el.querySelectorAll('.tabs-content');\n const isFallback = Array.from(tabsContent).some(\n (el: Element) => (el as HTMLElement).dataset.fallback === 'true',\n );\n\n if (isFallback || tabsContent.length === 0) {\n return false;\n }\n\n children.each((childModel: any) => {\n this.stopListening(childModel, 'change:attributes');\n });\n\n children.each((childModel: any, i: number) => {\n const container = tabsContent[i];\n\n if (!container) {\n return;\n }\n\n const childView = this.createView(childModel);\n\n if (childView) {\n container.innerHTML = '';\n childView.render();\n container.appendChild(childView.el);\n\n this.listenTo(childModel, 'change:attributes', () => {\n const childAttributes = childModel.get('attributes') || {};\n const childProps = childModel.get('componentProps') || {};\n const hasError = hasTabsError || childAttributes.error || childProps.error;\n const hasMissing =\n hasTabsMissing || childAttributes.isMissing || childProps.isMissing;\n\n if (hasError || hasMissing) {\n childModel.set(\n 'attributes',\n {\n ...childAttributes,\n loading: false,\n error: hasError,\n isMissing: hasMissing,\n inheritedFromParent: !!(hasTabsError || hasTabsMissing),\n },\n { silent: false },\n );\n }\n });\n }\n });\n\n return true;\n };\n\n if (injectChildren()) {\n return this;\n }\n\n this._tabsTimeoutId = setTimeout(() => {\n if (injectChildren()) {\n return;\n }\n\n // eslint-disable-next-line no-console\n console.warn('Could not inject tabs content after delay');\n }, 100);\n } else {\n ReactDOM.render(\n <QueryCacheProvider maxCacheSize={100} maxCacheAge={5 * 60 * 1000}>\n <Renderer {...compProps} gjsModel={this.model} />\n </QueryCacheProvider>,\n this.el,\n );\n }\n } else {\n this.el.innerHTML = `<div>Unsupported component: ${compName}</div>`;\n }\n\n renderedComponents[this.model.get('id')] = this.model;\n\n return this;\n },\n _cleanupTabsSetup: function () {\n if (this._tabsTimeoutId) {\n clearTimeout(this._tabsTimeoutId);\n this._tabsTimeoutId = null;\n }\n },\n createView(model: any) {\n const ComponentView = this.em.get('DomComponents').getType(model.get('type'))?.view;\n\n if (!ComponentView) {\n // eslint-disable-next-line no-console\n console.warn('No view found for component type:', model.get('type'));\n\n return null;\n }\n\n const view = new ComponentView({\n model,\n config: this.config,\n componentTypes: this.componentTypes,\n });\n\n return view;\n },\n remove: function () {\n this.stopListening();\n\n this._cleanupTabsSetup();\n\n // eslint-disable-next-line import/no-named-as-default-member\n ReactDOM.unmountComponentAtNode(this.el);\n\n return this;\n },\n },\n });\n };\n}\n"],"mappings":"qDAAA,sDACA,+BACA,uDACA,MAAO,CAAAA,QAAQ,KAAM,WAAW,CAEhC,OAASC,YAAY,KAAQ,6BAA6B,CAC1D,OAASC,kBAAkB,KAAQ,+BAA+B,CAAC,OAAAC,GAAA,IAAAC,IAAA,yBAEnE,MAAO,SAAS,CAAAC,iCAAiCA,CAC/CC,IAA0B,CAC1BC,kBAA0D,CAC1DC,kBAA6C,CAC7CC,aAA4C,CAC5CC,cAAc,CACdC,WAAW,CACX,IAJAH,kBAA6C,WAA7CA,kBAA6C,CAAG,CAAC,CAAC,IAElDE,cAAc,WAAdA,cAAc,CAAG,KAAK,IACtBC,WAAW,WAAXA,WAAW,CAAG,KAAK,CAEnB,MAAO,SAAS,CAAAC,2BAA2BA,CAACC,MAAc,CAAQ,CAChEA,MAAM,CAACC,aAAa,CAACC,OAAO,CAAC,gBAAgB,CAAE,CAC7CC,KAAK,CAAE,CACLC,QAAQ,CAAE,CACRC,OAAO,CAAE,KAAK,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AG,CAAC,MAAM,CAAC,CAAC,CAEpE,MAAO,KACT,CAEA,GAAM,CAAAV,IAAI,CAAG,GAAI,CAAAgF,aAAa,CAAC,CAC7BvF,KAAK,CAALA,KAAK,CACL0F,MAAM,CAAE,IAAI,CAACA,MAAM,CACnBC,cAAc,CAAE,IAAI,CAACA,cACvB,CAAC,CAAC,CAEF,MAAO,CAAApF,IACT,CAAC,CACDqF,MAAM,CAAE,QAAR,CAAAA,MAAMA,CAAA,CAAc,CAClB,IAAI,CAACzB,aAAa,CAAC,CAAC,CAEpB,IAAI,CAACtB,iBAAiB,CAAC,CAAC,CAExB;AACA7D,QAAQ,CAAC6G,sBAAsB,CAAC,IAAI,CAAC3C,EAAE,CAAC,CAExC,MAAO,KACT,CACF,CACF,CAAC,CACH,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"grapejs-plugin.js","names":["ReactDOM","getRenderers","QueryCacheProvider","jsx","_jsx","createGrapesjsShadcnGenericPlugin","mode","performInteraction","renderedComponents","setHasChanged","isTemplateView","isStreaming","navigateToPage","grapesjsShadcnGenericPlugin","editor","DomComponents","addType","model","defaults","tagName","droppable","componentName","componentProps","traits","view","events","handleSlotInput","e","target","slot","dataset","text","innerText","props","get","startsWith","_props$data","idx","parseInt","split","dataKeys","Object","keys","data","headerMapper","key","set","_extends","includes","render","_this","compName","compProps","JSON","parse","err","console","error","isEditable","onChange","renderers","Renderer","_cleanupTabsSetup","maxCacheSize","maxCacheAge","children","gjsModel","el","components","length","tabAttributes","hasTabsError","hasTabsMissing","isMissing","injectChildren","tabsContent","querySelectorAll","isFallback","Array","from","some","fallback","each","childModel","stopListening","i","container","childView","createView","innerHTML","appendChild","listenTo","childAttributes","childProps","hasError","hasMissing","loading","inheritedFromParent","silent","_tabsTimeoutId","setTimeout","warn","log","clearTimeout","_this$em$get$getType","ComponentView","em","getType","config","componentTypes","remove","unmountComponentAtNode"],"sources":["../../src/plugins/grapejs-plugin.tsx"],"sourcesContent":["/* eslint-disable import/no-named-as-default-member */\n/* eslint-disable func-names */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport ReactDOM from 'react-dom';\nimport { Editor, Component } from 'grapesjs';\nimport { getRenderers } from './helpers/render-components';\nimport { QueryCacheProvider } from './helpers/query-cache-context';\n\nexport function createGrapesjsShadcnGenericPlugin(\n mode: 'editor' | 'preview',\n performInteraction: (payload: Record<string, any>) => void,\n renderedComponents: Record<string, Component> = {},\n setHasChanged: (hasChanged: boolean) => void,\n isTemplateView = false,\n isStreaming = false,\n navigateToPage?: (pageId: string) => void,\n) {\n return function grapesjsShadcnGenericPlugin(editor: Editor): void {\n editor.DomComponents.addType('shadcn-generic', {\n model: {\n defaults: {\n tagName: 'div',\n droppable: false,\n componentName: 'Card',\n componentProps: {},\n traits: [],\n },\n },\n view: {\n events: {\n 'input [data-slot]': 'handleSlotInput',\n } as any,\n handleSlotInput(e: Event) {\n const target = e.target as HTMLElement;\n const slot = target.dataset.slot;\n const text = target.innerText;\n\n const props = this.model.get('componentProps') || {};\n\n if (!slot) {\n return;\n }\n\n if (slot.startsWith('table-header-')) {\n const idx = parseInt(slot.split('-')[2], 10);\n const dataKeys = Object.keys(props.data?.[0] || {});\n\n if (!props.headerMapper) {\n props.headerMapper = {};\n }\n\n const key = dataKeys[idx];\n\n if (key) {\n props.headerMapper[key] = text;\n }\n } else {\n props[slot] = text;\n }\n\n this.model.set('componentProps', {\n ...props,\n });\n\n if (!['search-input'].includes(slot)) {\n setHasChanged(true);\n }\n },\n render: function () {\n const compName: string = this.model.get('componentName');\n let compProps: any = this.model.get('componentProps');\n\n if (typeof compProps === 'string') {\n try {\n compProps = JSON.parse(compProps);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Invalid JSON in componentProps', err);\n compProps = {};\n }\n }\n\n compProps.performInteraction = performInteraction;\n compProps.navigateToPage = navigateToPage;\n compProps.isTemplateView = isTemplateView;\n compProps.isEditable = mode === 'editor' && !isStreaming;\n\n compProps.onChange = (data: Record<string, any>) => {\n this.model.set('componentProps', {\n ...this.model.get('componentProps'),\n ...data,\n });\n };\n\n const renderers = getRenderers();\n const Renderer = renderers[compName];\n\n if (Renderer) {\n if (compName === 'Tabs') {\n this._cleanupTabsSetup();\n\n ReactDOM.render(\n <QueryCacheProvider maxCacheSize={100} maxCacheAge={5 * 60 * 1000}>\n <Renderer {...compProps} gjsModel={this.model} />\n </QueryCacheProvider>,\n this.el,\n );\n\n const children = this.model.components();\n\n if (children.length === 0) {\n return this;\n }\n\n const tabAttributes = this.model.get('attributes') || {};\n const hasTabsError = tabAttributes.error || compProps.error;\n const hasTabsMissing = tabAttributes.isMissing || compProps.isMissing;\n\n const injectChildren = () => {\n const tabsContent = this.el.querySelectorAll('.tabs-content');\n const isFallback = Array.from(tabsContent).some(\n (el: Element) => (el as HTMLElement).dataset.fallback === 'true',\n );\n\n if (isFallback || tabsContent.length === 0) {\n return false;\n }\n\n children.each((childModel: any) => {\n this.stopListening(childModel, 'change:attributes');\n });\n\n children.each((childModel: any, i: number) => {\n const container = tabsContent[i];\n\n if (!container) {\n return;\n }\n\n const childView = this.createView(childModel);\n\n if (childView) {\n container.innerHTML = '';\n childView.render();\n container.appendChild(childView.el);\n\n this.listenTo(childModel, 'change:attributes', () => {\n const childAttributes = childModel.get('attributes') || {};\n const childProps = childModel.get('componentProps') || {};\n const hasError = hasTabsError || childAttributes.error || childProps.error;\n const hasMissing =\n hasTabsMissing || childAttributes.isMissing || childProps.isMissing;\n\n if (hasError || hasMissing) {\n childModel.set(\n 'attributes',\n {\n ...childAttributes,\n loading: false,\n error: hasError,\n isMissing: hasMissing,\n inheritedFromParent: !!(hasTabsError || hasTabsMissing),\n },\n { silent: false },\n );\n }\n });\n }\n });\n\n return true;\n };\n\n if (injectChildren()) {\n return this;\n }\n\n this._tabsTimeoutId = setTimeout(() => {\n if (injectChildren()) {\n return;\n }\n\n // eslint-disable-next-line no-console\n console.warn('Could not inject tabs content after delay');\n }, 100);\n } else {\n ReactDOM.render(\n <QueryCacheProvider maxCacheSize={100} maxCacheAge={5 * 60 * 1000}>\n <Renderer {...compProps} gjsModel={this.model} />\n </QueryCacheProvider>,\n this.el,\n );\n }\n } else {\n this.el.innerHTML = `<div>Unsupported component: ${compName}</div>`;\n }\n\n renderedComponents[this.model.get('id')] = this.model;\n \n // eslint-disable-next-line no-console\n console.log(`[GrapesJS Plugin] Component registered: ${this.model.get('id')} (${compName})`);\n\n return this;\n },\n _cleanupTabsSetup: function () {\n if (this._tabsTimeoutId) {\n clearTimeout(this._tabsTimeoutId);\n this._tabsTimeoutId = null;\n }\n },\n createView(model: any) {\n const ComponentView = this.em.get('DomComponents').getType(model.get('type'))?.view;\n\n if (!ComponentView) {\n // eslint-disable-next-line no-console\n console.warn('No view found for component type:', model.get('type'));\n\n return null;\n }\n\n const view = new ComponentView({\n model,\n config: this.config,\n componentTypes: this.componentTypes,\n });\n\n return view;\n },\n remove: function () {\n this.stopListening();\n\n this._cleanupTabsSetup();\n\n // eslint-disable-next-line import/no-named-as-default-member\n ReactDOM.unmountComponentAtNode(this.el);\n\n return this;\n },\n },\n });\n };\n}\n"],"mappings":"qDAAA,sDACA,+BACA,uDACA,MAAO,CAAAA,QAAQ,KAAM,WAAW,CAEhC,OAASC,YAAY,KAAQ,6BAA6B,CAC1D,OAASC,kBAAkB,KAAQ,+BAA+B,CAAC,OAAAC,GAAA,IAAAC,IAAA,yBAEnE,MAAO,SAAS,CAAAC,iCAAiCA,CAC/CC,IAA0B,CAC1BC,kBAA0D,CAC1DC,kBAA6C,CAC7CC,aAA4C,CAC5CC,cAAc,CACdC,WAAW,CACXC,cAAyC,CACzC,IALAJ,kBAA6C,WAA7CA,kBAA6C,CAAG,CAAC,CAAC,IAElDE,cAAc,WAAdA,cAAc,CAAG,KAAK,IACtBC,WAAW,WAAXA,WAAW,CAAG,KAAK,CAGnB,MAAO,SAAS,CAAAE,2BAA2BA,CAACC,MAAc,CAAQ,CAChEA,MAAM,CAACC,aAAa,CAACC,OAAO,CAAC,gB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EAAE,CAACxE,GAAG,CAAC,eAAe,CAAC,CAACyE,OAAO,CAAC1F,KAAK,CAACiB,GAAG,CAAC,MAAM,CAAC,CAAC,eAAvDsE,oBAAA,CAAyDhF,IAAI,CAEnF,GAAI,CAACiF,aAAa,CAAE,CAClB;AACAjD,OAAO,CAAC6C,IAAI,CAAC,mCAAmC,CAAEpF,KAAK,CAACiB,GAAG,CAAC,MAAM,CAAC,CAAC,CAEpE,MAAO,KACT,CAEA,GAAM,CAAAV,IAAI,CAAG,GAAI,CAAAiF,aAAa,CAAC,CAC7BxF,KAAK,CAALA,KAAK,CACL2F,MAAM,CAAE,IAAI,CAACA,MAAM,CACnBC,cAAc,CAAE,IAAI,CAACA,cACvB,CAAC,CAAC,CAEF,MAAO,CAAArF,IACT,CAAC,CACDsF,MAAM,CAAE,QAAR,CAAAA,MAAMA,CAAA,CAAc,CAClB,IAAI,CAAC1B,aAAa,CAAC,CAAC,CAEpB,IAAI,CAACtB,iBAAiB,CAAC,CAAC,CAExB;AACA9D,QAAQ,CAAC+G,sBAAsB,CAAC,IAAI,CAAC5C,EAAE,CAAC,CAExC,MAAO,KACT,CACF,CACF,CAAC,CACH,CACF","ignoreList":[]}
|
|
@@ -12,5 +12,6 @@ var initialData=useMemo(function(){return filterPlaceholders(props)},[]);var _us
|
|
|
12
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,decimalPrecision=allData.decimalPrecision,columnWithChipClass=allData.columnWithChipClass,chipStylesMapping=allData.chipStylesMapping;var effectiveRawData=isTemplateView&&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,decimalPrecision:decimalPrecision,columnWithChipClass:columnWithChipClass,chipStylesMapping:chipStylesMapping})}),/*#__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);useEffect(function(){if(props.gjsModel){var componentId=props.gjsModel.get("id");var childrenCount=props.gjsModel.components().length;if(safeTabs.length>0&&childrenCount===0){// eslint-disable-next-line no-console
|
|
13
13
|
console.warn("Tab component "+componentId+" has "+safeTabs.length+" tabs but no child components. This may indicate lost tab content.")}}},[safeTabs.length,props.gjsModel]);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$isTemplateView5=props.isTemplateView,isTemplateView=_props$isTemplateView5===void 0?false:_props$isTemplateView5,rest=_objectWithoutPropertiesLoose(props,_excluded5);// Memoize filtered props to avoid re-filtering on every render
|
|
14
14
|
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=isTemplateView&&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
|
|
15
|
-
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 rawSummaryText=isTemplateView&&sampleData!==undefined?sampleData:summaryText;var effectiveSummaryText=typeof rawSummaryText==="string"?rawSummaryText:"";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(){
|
|
15
|
+
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 rawSummaryText=isTemplateView&&sampleData!==undefined?sampleData:summaryText;var effectiveSummaryText=typeof rawSummaryText==="string"?rawSummaryText:"";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,navigateToPage=props.navigateToPage;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,onClick=allData.onClick;function interact(){if(onClick&&onClick.action==="navigateToPage"){if(navigateToPage){navigateToPage(onClick.targetPageId)}else{// eslint-disable-next-line no-console
|
|
16
|
+
console.warn("Page navigation requested but no navigation handler available")}return}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}}
|
|
16
17
|
//# sourceMappingURL=render-components.js.map
|