dp-widgets-framework 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.esm.js +1373 -104
  2. package/dist/index.js +1373 -104
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2020,7 +2020,7 @@ const borderRadiusMap$2 = {
2020
2020
  large: "0.5rem",
2021
2021
  "extra-large": "0.75rem",
2022
2022
  };
2023
- const getStyleValues$5 = (styles = {}) => {
2023
+ const getStyleValues$a = (styles = {}) => {
2024
2024
  return {
2025
2025
  backgroundColor: styles.backgroundColor || "transparent",
2026
2026
  borderRadius: borderRadiusMap$2[styles.borderRadius || "rounded"],
@@ -2033,7 +2033,7 @@ const getStyleValues$5 = (styles = {}) => {
2033
2033
  };
2034
2034
  function HeaderWidget({ widget }) {
2035
2035
  var _a, _b;
2036
- const styles = getStyleValues$5((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2036
+ const styles = getStyleValues$a((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2037
2037
  const content = ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
2038
2038
  return (jsxRuntimeExports.jsx("div", { className: "w-full", style: styles, children: jsxRuntimeExports.jsxs("div", { className: cn("flex items-center justify-between"), children: [jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [content.showLogo && content.logoUrl && (jsxRuntimeExports.jsx("img", { src: content.logoUrl, alt: "Logo", className: "h-8 w-auto" })), jsxRuntimeExports.jsx("h1", { className: cn("font-semibold", content.titleSize || "text-xl"), children: content.title || "Header" })] }), content.showRightContent && (jsxRuntimeExports.jsx("div", { className: "flex items-center gap-4", children: content.rightContent }))] }) }));
2039
2039
  }
@@ -2044,7 +2044,7 @@ const borderRadiusMap$1 = {
2044
2044
  large: "0.5rem",
2045
2045
  "extra-large": "0.75rem",
2046
2046
  };
2047
- const getStyleValues$4 = (styles = {}) => {
2047
+ const getStyleValues$9 = (styles = {}) => {
2048
2048
  return {
2049
2049
  backgroundColor: styles.backgroundColor || "transparent",
2050
2050
  borderRadius: borderRadiusMap$1[styles.borderRadius || "rounded"],
@@ -2057,7 +2057,7 @@ const getStyleValues$4 = (styles = {}) => {
2057
2057
  };
2058
2058
  function FooterWidget({ widget }) {
2059
2059
  var _a, _b;
2060
- const styles = getStyleValues$4((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2060
+ const styles = getStyleValues$9((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2061
2061
  const content = ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
2062
2062
  return (jsxRuntimeExports.jsx("footer", { className: "w-full", style: styles, children: jsxRuntimeExports.jsxs("div", { className: cn("flex items-center", content.layout === "centered" ? "justify-center" : "justify-between"), children: [jsxRuntimeExports.jsx("div", { className: "text-sm", children: content.leftContent || "© 2024 Your Company" }), content.showCenterContent && (jsxRuntimeExports.jsx("div", { className: "text-sm", children: content.centerContent })), content.showRightContent && (jsxRuntimeExports.jsx("div", { className: "flex items-center gap-4 text-sm", children: content.rightContent }))] }) }));
2063
2063
  }
@@ -2068,7 +2068,7 @@ const borderRadiusMap = {
2068
2068
  large: "0.5rem",
2069
2069
  "extra-large": "0.75rem",
2070
2070
  };
2071
- const getStyleValues$3 = (styles = {}) => {
2071
+ const getStyleValues$8 = (styles = {}) => {
2072
2072
  const borderRadius = (styles.borderRadius || "rounded");
2073
2073
  return {
2074
2074
  backgroundColor: styles.backgroundColor || "transparent",
@@ -2083,12 +2083,12 @@ const getStyleValues$3 = (styles = {}) => {
2083
2083
  };
2084
2084
  function TextWidget({ widget }) {
2085
2085
  var _a, _b;
2086
- const styles = getStyleValues$3((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2086
+ const styles = getStyleValues$8((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2087
2087
  const content = ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
2088
2088
  return (jsxRuntimeExports.jsx("div", { className: "w-full", style: styles, children: jsxRuntimeExports.jsx("div", { className: cn("prose max-w-none", content.blockType === "heading-1" && "text-[24px] font-bold", content.blockType === "heading-2" && "text-[22px] font-bold", content.blockType === "heading-3" && "text-[18px] font-bold", content.blockType === "paragraph" && "text-base"), dangerouslySetInnerHTML: { __html: content.displayText || "Text content" } }) }));
2089
2089
  }
2090
2090
 
2091
- const getStyleValues$2 = (styles = {}) => {
2091
+ const getStyleValues$7 = (styles = {}) => {
2092
2092
  return {
2093
2093
  borderColor: styles.color || "#e5e7eb",
2094
2094
  borderStyle: styles.style || "solid",
@@ -2098,7 +2098,7 @@ const getStyleValues$2 = (styles = {}) => {
2098
2098
  };
2099
2099
  function DividerWidget({ widget }) {
2100
2100
  var _a, _b;
2101
- const styles = getStyleValues$2((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2101
+ const styles = getStyleValues$7((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2102
2102
  const content = ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
2103
2103
  return (jsxRuntimeExports.jsxs("div", { className: "w-full", style: { margin: styles.margin }, children: [jsxRuntimeExports.jsx("hr", { className: cn("w-full", content.variant === "dashed" && "border-dashed", content.variant === "dotted" && "border-dotted"), style: {
2104
2104
  borderColor: styles.borderColor,
@@ -17707,7 +17707,6 @@ function DataGrid({ title, data, className }) {
17707
17707
  // Format the value with commas if it's a number or numeric string
17708
17708
  let valueStr;
17709
17709
  valueStr = formatWithCommas(value);
17710
- console.log('value==>', valueStr, unit);
17711
17710
  // If no unit or unit length > 3, return value only
17712
17711
  if (!unit || unit.length > 3) {
17713
17712
  return valueStr;
@@ -38437,10 +38436,10 @@ function SummaryWidget({ title, data, metadata, className }) {
38437
38436
  }, children: title }) })), jsxRuntimeExports.jsx("div", { className: "flex-1 overflow-auto space-y-4", children: jsxRuntimeExports.jsx("div", { className: "prose prose-sm max-w-none", children: jsxRuntimeExports.jsx(Markdown, { className: "text-gray-800", children: data.content }) }) })] }));
38438
38437
  }
38439
38438
 
38440
- const CHART_REFRESH_TIMEOUT = 3000;
38441
- const DEFAULT_COLORS = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
38439
+ const CHART_REFRESH_TIMEOUT$4 = 3000;
38440
+ const DEFAULT_COLORS$3 = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
38442
38441
  const LINE_COLORS = ["#243D84", "#69238B", "#4A959F", "#D0A677", "#B31E47", "#396431"];
38443
- const clearChat = async (widgetBackendUrl, widgetId) => {
38442
+ const clearChat$4 = async (widgetBackendUrl, widgetId) => {
38444
38443
  if (!widgetBackendUrl || !widgetId)
38445
38444
  return;
38446
38445
  console.log('clearChat called for widgetId:', widgetId);
@@ -38462,8 +38461,8 @@ const clearChat = async (widgetBackendUrl, widgetId) => {
38462
38461
  console.error('Failed to clear chat:', error);
38463
38462
  }
38464
38463
  };
38465
- const createLoadingComponent = (message = "Loading chart data...") => (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full", children: jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
38466
- const createInitialChartState = (agentType, widgetIds, datasetId) => {
38464
+ const createLoadingComponent$4 = (message = "Loading chart data...") => (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full", children: jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
38465
+ const createInitialChartState$4 = (agentType, widgetIds, datasetId) => {
38467
38466
  const baseState = { dataset_id: datasetId || "home_generation_dataset" };
38468
38467
  switch (agentType) {
38469
38468
  case "Pie Chart Agent":
@@ -38490,6 +38489,8 @@ const createInitialChartState = (agentType, widgetIds, datasetId) => {
38490
38489
  title: "",
38491
38490
  type: "series_bar",
38492
38491
  chart_type: "financial",
38492
+ x_axis_title: "",
38493
+ y_axis_title: "",
38493
38494
  orientation: "vertical",
38494
38495
  units: "",
38495
38496
  data: { labels: [], series: [], total: 0, average: 0 },
@@ -38518,7 +38519,7 @@ const createInitialChartState = (agentType, widgetIds, datasetId) => {
38518
38519
  return Object.assign({ widget_ids: widgetIds }, baseState);
38519
38520
  }
38520
38521
  };
38521
- const loadAgentState = async (widgetBackendUrl, threadId, agentName) => {
38522
+ const loadAgentState$4 = async (widgetBackendUrl, threadId, agentName) => {
38522
38523
  try {
38523
38524
  const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
38524
38525
  method: 'POST',
@@ -38547,7 +38548,7 @@ const loadAgentState = async (widgetBackendUrl, threadId, agentName) => {
38547
38548
  return null;
38548
38549
  }
38549
38550
  };
38550
- const parseAndUpdateChartState = (apiResponse, setChartState) => {
38551
+ const parseAndUpdateChartState$4 = (apiResponse, setChartState) => {
38551
38552
  var _a, _b;
38552
38553
  try {
38553
38554
  if ((_b = (_a = apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.data) === null || _a === void 0 ? void 0 : _a.loadAgentState) === null || _b === void 0 ? void 0 : _b.state) {
@@ -38590,7 +38591,7 @@ const parseAndUpdateChartState = (apiResponse, setChartState) => {
38590
38591
  console.error('Failed to parse and update chart state:', error);
38591
38592
  }
38592
38593
  };
38593
- const getStyleValues$1 = (styles = {}) => {
38594
+ const getStyleValues$6 = (styles = {}) => {
38594
38595
  const borderRadiusMap = {
38595
38596
  none: "0px",
38596
38597
  rounded: "0.375rem",
@@ -38624,7 +38625,7 @@ function BarChartComponent({ orientation, barChartState, styles, appendMessage,
38624
38625
  const isEmpty = labels.length === 0 || values.length === 0;
38625
38626
  const handleRefresh = async () => {
38626
38627
  if (query && widgetBackendUrl && widgetId) {
38627
- await clearChat(widgetBackendUrl, widgetId);
38628
+ await clearChat$4(widgetBackendUrl, widgetId);
38628
38629
  appendMessage(new TextMessage({
38629
38630
  content: `${query} and render data on a bar chart`,
38630
38631
  role: Role.User,
@@ -38648,10 +38649,10 @@ function BarChartComponent({ orientation, barChartState, styles, appendMessage,
38648
38649
  }
38649
38650
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38650
38651
  const finalColors = React.useMemo(() => {
38651
- return shuffleColors(DEFAULT_COLORS, labels === null || labels === void 0 ? void 0 : labels.length);
38652
+ return shuffleColors(DEFAULT_COLORS$3, labels === null || labels === void 0 ? void 0 : labels.length);
38652
38653
  }, [labels.length]);
38653
38654
  if (isEmpty) {
38654
- return createLoadingComponent();
38655
+ return createLoadingComponent$4();
38655
38656
  }
38656
38657
  const transformedData = {
38657
38658
  labels: labels,
@@ -38665,7 +38666,7 @@ function BarChartComponent({ orientation, barChartState, styles, appendMessage,
38665
38666
  };
38666
38667
  return (jsxRuntimeExports.jsx(BarChart, { orientation: orientation, title: chartTitle, data: transformedData, units: units, content: content }));
38667
38668
  }
38668
- function SeriesBarChartComponent({ orientation, seriesBarChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content }) {
38669
+ function SeriesBarChartComponent$2({ orientation, seriesBarChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content }) {
38669
38670
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
38670
38671
  const hasCalledRef = React.useRef(false);
38671
38672
  const labels = ((_b = (_a = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.labels) || ((_e = (_d = (_c = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.state) === null || _c === void 0 ? void 0 : _c.series_bar_chart_data) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.labels) || [];
@@ -38677,7 +38678,7 @@ function SeriesBarChartComponent({ orientation, seriesBarChartState, styles, app
38677
38678
  const isEmpty = labels.length === 0 || series.length === 0;
38678
38679
  const handleRefresh = async () => {
38679
38680
  if (query) {
38680
- await clearChat(widgetBackendUrl, widgetId);
38681
+ await clearChat$4(widgetBackendUrl, widgetId);
38681
38682
  // Send trigger event to clear chart state
38682
38683
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38683
38684
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38703,10 +38704,10 @@ function SeriesBarChartComponent({ orientation, seriesBarChartState, styles, app
38703
38704
  }
38704
38705
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38705
38706
  const finalColors = React.useMemo(() => {
38706
- return shuffleColors(DEFAULT_COLORS, series === null || series === void 0 ? void 0 : series.length);
38707
+ return shuffleColors(DEFAULT_COLORS$3, series === null || series === void 0 ? void 0 : series.length);
38707
38708
  }, [series.length]);
38708
38709
  if (isEmpty) {
38709
- return createLoadingComponent();
38710
+ return createLoadingComponent$4();
38710
38711
  }
38711
38712
  const transformedData = {
38712
38713
  labels: labels,
@@ -38730,7 +38731,7 @@ function SeriesLineChartComponent({ orientation, seriesLineChartState, styles, a
38730
38731
  const isEmpty = labels.length === 0 || series.length === 0;
38731
38732
  const handleRefresh = async () => {
38732
38733
  if (query) {
38733
- await clearChat(widgetBackendUrl, widgetId);
38734
+ await clearChat$4(widgetBackendUrl, widgetId);
38734
38735
  // Send trigger event to clear chart state
38735
38736
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38736
38737
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38756,10 +38757,10 @@ function SeriesLineChartComponent({ orientation, seriesLineChartState, styles, a
38756
38757
  }
38757
38758
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38758
38759
  const finalColors = React.useMemo(() => {
38759
- return shuffleColors([...LINE_COLORS, ...DEFAULT_COLORS], series === null || series === void 0 ? void 0 : series.length);
38760
+ return shuffleColors([...LINE_COLORS, ...DEFAULT_COLORS$3], series === null || series === void 0 ? void 0 : series.length);
38760
38761
  }, [series.length]);
38761
38762
  if (isEmpty) {
38762
- return createLoadingComponent();
38763
+ return createLoadingComponent$4();
38763
38764
  }
38764
38765
  const transformedData = {
38765
38766
  labels: labels,
@@ -38778,7 +38779,7 @@ function SeriesLineChartComponent({ orientation, seriesLineChartState, styles, a
38778
38779
  };
38779
38780
  return (jsxRuntimeExports.jsx(SeriesLineChart, { orientation: orientation, title: chartTitle, data: transformedData, units: units, content: content, x_axis_title: x_axis_title, y_axis_title: y_axis_title }));
38780
38781
  }
38781
- function PieChartComponent({ pieChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content }) {
38782
+ function PieChartComponent$1({ pieChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content }) {
38782
38783
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
38783
38784
  const hasCalledRef = React.useRef(false);
38784
38785
  const labels = ((_b = (_a = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.labels) || ((_e = (_d = (_c = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.state) === null || _c === void 0 ? void 0 : _c.pie_chart_data) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.labels) || [];
@@ -38789,7 +38790,7 @@ function PieChartComponent({ pieChartState, styles, appendMessage, query, isFirs
38789
38790
  const isEmpty = labels.length === 0 || values.length === 0;
38790
38791
  const handleRefresh = async () => {
38791
38792
  if (query) {
38792
- await clearChat(widgetBackendUrl, widgetId);
38793
+ await clearChat$4(widgetBackendUrl, widgetId);
38793
38794
  // Send trigger event to clear chart state
38794
38795
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38795
38796
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38815,10 +38816,10 @@ function PieChartComponent({ pieChartState, styles, appendMessage, query, isFirs
38815
38816
  }
38816
38817
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38817
38818
  const backgroundColors = React.useMemo(() => {
38818
- return shuffleColors(DEFAULT_COLORS, labels.length);
38819
+ return shuffleColors(DEFAULT_COLORS$3, labels.length);
38819
38820
  }, [labels.length]);
38820
38821
  if (isEmpty) {
38821
- return createLoadingComponent();
38822
+ return createLoadingComponent$4();
38822
38823
  }
38823
38824
  const colors = ((_y = (_x = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _x === void 0 ? void 0 : _x.data) === null || _y === void 0 ? void 0 : _y.colors) || ((_1 = (_0 = (_z = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.state) === null || _z === void 0 ? void 0 : _z.pie_chart_data) === null || _0 === void 0 ? void 0 : _0.data) === null || _1 === void 0 ? void 0 : _1.colors) || labels.map((_, index) => backgroundColors[index % backgroundColors.length]);
38824
38825
  const transformedData = {
@@ -38845,7 +38846,7 @@ function LineChartComponent({ lineChartState, styles, appendMessage, query, isFi
38845
38846
  const isEmpty = labels.length === 0 || values.length === 0;
38846
38847
  const handleRefresh = async () => {
38847
38848
  if (query && widgetBackendUrl && widgetId) {
38848
- await clearChat(widgetBackendUrl, widgetId);
38849
+ await clearChat$4(widgetBackendUrl, widgetId);
38849
38850
  appendMessage(new TextMessage({
38850
38851
  content: `${query} and render data on a bar chart`,
38851
38852
  role: Role.User,
@@ -38871,7 +38872,7 @@ function LineChartComponent({ lineChartState, styles, appendMessage, query, isFi
38871
38872
  return LINE_COLORS[Math.floor(Math.random() * LINE_COLORS.length)];
38872
38873
  }, [labels.length]);
38873
38874
  if (isEmpty) {
38874
- return createLoadingComponent();
38875
+ return createLoadingComponent$4();
38875
38876
  }
38876
38877
  const transformedData = {
38877
38878
  labels: labels,
@@ -38891,7 +38892,7 @@ function LineChartComponent({ lineChartState, styles, appendMessage, query, isFi
38891
38892
  };
38892
38893
  return (jsxRuntimeExports.jsx(LineChart, { title: chartTitle, data: transformedData, units: units, content: content }));
38893
38894
  }
38894
- function DataGridComponent({ dataGridState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout }) {
38895
+ function DataGridComponent$1({ dataGridState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout }) {
38895
38896
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
38896
38897
  const hasCalledRef = React.useRef(false);
38897
38898
  const columns = ((_b = (_a = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.headers) || ((_e = (_d = (_c = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.state) === null || _c === void 0 ? void 0 : _c.matrix_grid_data) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.headers) || [];
@@ -38901,7 +38902,7 @@ function DataGridComponent({ dataGridState, styles, appendMessage, query, isFirs
38901
38902
  const isEmpty = columns.length === 0 || rows.length === 0;
38902
38903
  const handleRefresh = async () => {
38903
38904
  if (query) {
38904
- await clearChat(widgetBackendUrl, widgetId);
38905
+ await clearChat$4(widgetBackendUrl, widgetId);
38905
38906
  // Send trigger event to clear chart state
38906
38907
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38907
38908
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38927,7 +38928,7 @@ function DataGridComponent({ dataGridState, styles, appendMessage, query, isFirs
38927
38928
  }
38928
38929
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38929
38930
  if (isEmpty) {
38930
- return createLoadingComponent("Loading table data...");
38931
+ return createLoadingComponent$4("Loading table data...");
38931
38932
  }
38932
38933
  const transformedData = {
38933
38934
  columns: columns,
@@ -38948,7 +38949,7 @@ function SummaryComponent({ summaryState, styles, appendMessage, query, isFirstL
38948
38949
  const isEmpty = !content || content.trim() === "";
38949
38950
  const handleRefresh = async () => {
38950
38951
  if (query) {
38951
- await clearChat(widgetBackendUrl, widgetId);
38952
+ await clearChat$4(widgetBackendUrl, widgetId);
38952
38953
  // Send trigger event to clear chart state
38953
38954
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38954
38955
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38961,7 +38962,7 @@ function SummaryComponent({ summaryState, styles, appendMessage, query, isFirstL
38961
38962
  React.useEffect(() => {
38962
38963
  if (isEmpty && query && isFirstLoad && !(summaryState === null || summaryState === void 0 ? void 0 : summaryState.agent_message) && !hasCalledRef.current) {
38963
38964
  hasCalledRef.current = true;
38964
- setChartState((prevState) => (Object.assign(Object.assign({}, prevState), { widget_ids: widget_ids })));
38965
+ setChartState(Object.assign(Object.assign({}, summaryState), { widget_ids: widget_ids }));
38965
38966
  setTimeout(() => {
38966
38967
  handleRefresh();
38967
38968
  }, 500);
@@ -38977,12 +38978,12 @@ function SummaryComponent({ summaryState, styles, appendMessage, query, isFirstL
38977
38978
  }
38978
38979
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38979
38980
  if (isEmpty) {
38980
- return createLoadingComponent("Loading summary...");
38981
+ return createLoadingComponent$4("Loading summary...");
38981
38982
  }
38982
38983
  return (jsxRuntimeExports.jsx(SummaryWidget, { title: title, data: data, metadata: metadata, className: "" }));
38983
38984
  }
38984
- function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds, widgetBackendUrl, datasetId }) {
38985
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32;
38985
+ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds, widgetBackendUrl, datasetId, widgetData, }) {
38986
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29;
38986
38987
  const agentType = (_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentType;
38987
38988
  const orientation = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.orientation;
38988
38989
  const isFirstLoad = (_c = widget.config) === null || _c === void 0 ? void 0 : _c.isFirstLoad;
@@ -38997,7 +38998,7 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
38997
38998
  }, [widget.id, setThreadId]);
38998
38999
  const { state: chartState, setState: setChartState } = reactCore.useCoAgent({
38999
39000
  name: (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName,
39000
- initialState: createInitialChartState(agentType || '', widgetIds, datasetId),
39001
+ initialState: createInitialChartState$4(agentType || '', widgetIds, datasetId),
39001
39002
  });
39002
39003
  // Function to handle timeout and call loadAgentState API
39003
39004
  const handleLoadingTimeout = React.useCallback(async () => {
@@ -39016,9 +39017,9 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39016
39017
  // Increment the API call counter
39017
39018
  setApiCallCount(prev => prev + 1);
39018
39019
  const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
39019
- const apiResponse = await loadAgentState(widgetBackendUrl, widget.id, agentName);
39020
+ const apiResponse = await loadAgentState$4(widgetBackendUrl, widget.id, agentName);
39020
39021
  if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
39021
- parseAndUpdateChartState(apiResponse, setChartState);
39022
+ parseAndUpdateChartState$4(apiResponse, setChartState);
39022
39023
  }
39023
39024
  }, [widgetBackendUrl, widget.id, isTimeoutTriggered, setChartState, (_f = widget.config) === null || _f === void 0 ? void 0 : _f.agentName, chartState, apiCallCount, hasTimeoutError]);
39024
39025
  // Function to start timeout
@@ -39029,7 +39030,7 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39029
39030
  setIsTimeoutTriggered(false);
39030
39031
  timeoutRef.current = setTimeout(() => {
39031
39032
  handleLoadingTimeout();
39032
- }, CHART_REFRESH_TIMEOUT);
39033
+ }, CHART_REFRESH_TIMEOUT$4);
39033
39034
  }, [handleLoadingTimeout]);
39034
39035
  // Function to clear timeout
39035
39036
  const clearLoadingTimeout = React.useCallback(() => {
@@ -39038,29 +39039,6 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39038
39039
  timeoutRef.current = null;
39039
39040
  }
39040
39041
  }, []);
39041
- // Function to clear chat and reset chart state
39042
- React.useCallback(async (widgetId) => {
39043
- if (!widgetBackendUrl)
39044
- return;
39045
- try {
39046
- await fetch(`${widgetBackendUrl}/api/clear-chat`, {
39047
- method: 'POST',
39048
- headers: {
39049
- 'Content-Type': 'application/json',
39050
- },
39051
- body: JSON.stringify({
39052
- session_id: widgetId,
39053
- delete_state: true
39054
- }),
39055
- });
39056
- setChartState(createInitialChartState(agentType || '', widgetIds, datasetId));
39057
- setApiCallCount(0);
39058
- setHasTimeoutError(false);
39059
- }
39060
- catch (error) {
39061
- console.error('Failed to clear chat and state:', error);
39062
- }
39063
- }, [widgetBackendUrl, setChartState, agentType, widgetIds]);
39064
39042
  // Clean up timeout on unmount
39065
39043
  React.useEffect(() => {
39066
39044
  return () => {
@@ -39109,7 +39087,7 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39109
39087
  messageContent = `${query} and render the data on a summary widget`;
39110
39088
  }
39111
39089
  console.log('triggering to datasetId==>', datasetId);
39112
- setChartState(createInitialChartState(agentType || '', widgetIds, datasetId));
39090
+ setChartState(createInitialChartState$4(agentType || '', widgetIds, datasetId));
39113
39091
  appendMessage(new TextMessage({
39114
39092
  content: messageContent,
39115
39093
  role: Role.User,
@@ -39119,7 +39097,7 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39119
39097
  const handleClearChartState = (event) => {
39120
39098
  const { widgetId } = event.detail;
39121
39099
  if (widgetId === widget.id) {
39122
- setChartState(createInitialChartState(agentType || '', widgetIds, datasetId));
39100
+ setChartState(createInitialChartState$4(agentType || '', widgetIds, datasetId));
39123
39101
  setApiCallCount(0);
39124
39102
  setHasTimeoutError(false);
39125
39103
  }
@@ -39139,16 +39117,11 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39139
39117
  (agentType === "Pie Chart Agent" && (!((_2 = (_1 = (_0 = chartState.pie_chart_data) === null || _0 === void 0 ? void 0 : _0.data) === null || _1 === void 0 ? void 0 : _1.labels) === null || _2 === void 0 ? void 0 : _2.length) || !((_5 = (_4 = (_3 = chartState.pie_chart_data) === null || _3 === void 0 ? void 0 : _3.data) === null || _4 === void 0 ? void 0 : _4.values) === null || _5 === void 0 ? void 0 : _5.length))) ||
39140
39118
  (agentType === "Line Chart Agent" && (!((_8 = (_7 = (_6 = chartState.bar_chart_data) === null || _6 === void 0 ? void 0 : _6.data) === null || _7 === void 0 ? void 0 : _7.labels) === null || _8 === void 0 ? void 0 : _8.length) || !((_11 = (_10 = (_9 = chartState.bar_chart_data) === null || _9 === void 0 ? void 0 : _9.data) === null || _10 === void 0 ? void 0 : _10.values) === null || _11 === void 0 ? void 0 : _11.length))) ||
39141
39119
  (agentType === "Data Grid Agent" && (!((_14 = (_13 = (_12 = chartState.matrix_grid_data) === null || _12 === void 0 ? void 0 : _12.data) === null || _13 === void 0 ? void 0 : _13.headers) === null || _14 === void 0 ? void 0 : _14.length) || !((_17 = (_16 = (_15 = chartState.matrix_grid_data) === null || _15 === void 0 ? void 0 : _15.data) === null || _16 === void 0 ? void 0 : _16.rows) === null || _17 === void 0 ? void 0 : _17.length))) ||
39142
- (agentType === "Summary Agent" && (!((_19 = (_18 = chartState.summary_data) === null || _18 === void 0 ? void 0 : _18.data) === null || _19 === void 0 ? void 0 : _19.content) || ((_22 = (_21 = (_20 = chartState.summary_data) === null || _20 === void 0 ? void 0 : _20.data) === null || _21 === void 0 ? void 0 : _21.content) === null || _22 === void 0 ? void 0 : _22.trim()) === ""))) ? (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full p-4", children: jsxRuntimeExports.jsx("div", { className: "text-center max-w-md", children: jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700", children: chartState.agent_message }) }) })) : agentType === "Bar Chart Agent" ? (jsxRuntimeExports.jsx(BarChartComponent, { barChartState: chartState, styles: styles, orientation: orientation, content: content, appendMessage: appendMessage, query: (_23 = widget.config) === null || _23 === void 0 ? void 0 : _23.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Series Bar Chart Agent" ? (jsxRuntimeExports.jsx(SeriesBarChartComponent, { seriesBarChartState: chartState, styles: styles, orientation: orientation, content: content, appendMessage: appendMessage, query: (_24 = widget.config) === null || _24 === void 0 ? void 0 : _24.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Series Line Chart Agent" ? (jsxRuntimeExports.jsx(SeriesLineChartComponent, { seriesLineChartState: chartState, styles: styles, orientation: orientation, content: content, appendMessage: appendMessage, query: (_25 = widget.config) === null || _25 === void 0 ? void 0 : _25.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Pie Chart Agent" ? (jsxRuntimeExports.jsx(PieChartComponent, { pieChartState: chartState, styles: styles, appendMessage: appendMessage, content: content, query: (_26 = widget.config) === null || _26 === void 0 ? void 0 : _26.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Line Chart Agent" ? (jsxRuntimeExports.jsx(LineChartComponent, { lineChartState: chartState, styles: styles, appendMessage: appendMessage, content: content, query: (_27 = widget.config) === null || _27 === void 0 ? void 0 : _27.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Data Grid Agent" ? (jsxRuntimeExports.jsx(DataGridComponent, { dataGridState: chartState, styles: styles, appendMessage: appendMessage, query: (_28 = widget.config) === null || _28 === void 0 ? void 0 : _28.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Summary Agent" ? (jsxRuntimeExports.jsx(SummaryComponent, { summaryState: chartState, styles: styles, appendMessage: appendMessage, query: (_29 = widget.config) === null || _29 === void 0 ? void 0 : _29.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, widget_ids: widgetIds, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout, setChartState: setChartState })) : (jsxRuntimeExports.jsx(reactUi.CopilotChat, { className: "h-full text-xs [&_.copilot-chat-message]:text-xs [&_.copilot-chat-input]:text-xs", labels: {
39143
- title: ((_30 = widget.config) === null || _30 === void 0 ? void 0 : _30.copilotTitle) || widget.title,
39144
- initial: ((_31 = widget.config) === null || _31 === void 0 ? void 0 : _31.copilotInitialMessage) || ((_32 = widget.config) === null || _32 === void 0 ? void 0 : _32.placeholder) || "How can I help you today?"
39145
- }, onSubmitMessage: () => {
39146
- setChartState(prevState => (Object.assign(Object.assign({}, prevState), { widget_ids: widgetIds, dataset_id: datasetId })));
39147
- } })) })] }));
39120
+ (agentType === "Summary Agent" && (!((_19 = (_18 = chartState.summary_data) === null || _18 === void 0 ? void 0 : _18.data) === null || _19 === void 0 ? void 0 : _19.content) || ((_22 = (_21 = (_20 = chartState.summary_data) === null || _20 === void 0 ? void 0 : _20.data) === null || _21 === void 0 ? void 0 : _21.content) === null || _22 === void 0 ? void 0 : _22.trim()) === ""))) ? (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full p-4", children: jsxRuntimeExports.jsx("div", { className: "text-center max-w-md", children: jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700", children: chartState.agent_message }) }) })) : agentType === "Bar Chart Agent" ? (jsxRuntimeExports.jsx(BarChartComponent, { barChartState: chartState, styles: styles, orientation: orientation, content: content, appendMessage: appendMessage, query: (_23 = widget.config) === null || _23 === void 0 ? void 0 : _23.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Series Bar Chart Agent" ? (jsxRuntimeExports.jsx(SeriesBarChartComponent$2, { seriesBarChartState: chartState, styles: styles, orientation: orientation, content: content, appendMessage: appendMessage, query: (_24 = widget.config) === null || _24 === void 0 ? void 0 : _24.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Series Line Chart Agent" ? (jsxRuntimeExports.jsx(SeriesLineChartComponent, { seriesLineChartState: chartState, styles: styles, orientation: orientation, content: content, appendMessage: appendMessage, query: (_25 = widget.config) === null || _25 === void 0 ? void 0 : _25.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Pie Chart Agent" ? (jsxRuntimeExports.jsx(PieChartComponent$1, { pieChartState: chartState, styles: styles, appendMessage: appendMessage, content: content, query: (_26 = widget.config) === null || _26 === void 0 ? void 0 : _26.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Line Chart Agent" ? (jsxRuntimeExports.jsx(LineChartComponent, { lineChartState: chartState, styles: styles, appendMessage: appendMessage, content: content, query: (_27 = widget.config) === null || _27 === void 0 ? void 0 : _27.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Data Grid Agent" ? (jsxRuntimeExports.jsx(DataGridComponent$1, { dataGridState: chartState, styles: styles, appendMessage: appendMessage, query: (_28 = widget.config) === null || _28 === void 0 ? void 0 : _28.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout })) : agentType === "Summary Agent" ? (jsxRuntimeExports.jsx(SummaryComponent, { summaryState: chartState, styles: styles, appendMessage: appendMessage, query: (_29 = widget.config) === null || _29 === void 0 ? void 0 : _29.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, widget_ids: widgetIds, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout, setChartState: setChartState })) : null })] }));
39148
39121
  }
39149
- function AgentWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, }) {
39122
+ function AgentWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
39150
39123
  var _a, _b;
39151
- const styles = getStyleValues$1((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39124
+ const styles = getStyleValues$6((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39152
39125
  // Construct the runtime URL using the configurable backend URL
39153
39126
  const getRuntimeUrl = () => {
39154
39127
  var _a;
@@ -39159,7 +39132,7 @@ function AgentWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady
39159
39132
  return (jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: jsxRuntimeExports.jsx(reactCore.CopilotKit, { runtimeUrl: getRuntimeUrl(), showDevConsole: false, agent: ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.agentName) || "widget_assistant", children: jsxRuntimeExports.jsx(CopilotKitAgent, { widget: widget, showHeader: showHeader, styles: styles, onResetReady: onResetReady, widgetIds: widgetIds, widgetBackendUrl: widgetBackendUrl, datasetId: datasetId }) }) }));
39160
39133
  }
39161
39134
 
39162
- const getStyleValues = (styles = {}) => {
39135
+ const getStyleValues$5 = (styles = {}) => {
39163
39136
  (styles.borderRadius || "rounded");
39164
39137
  return {
39165
39138
  // backgroundColor: styles.backgroundColor || "10px",
@@ -39167,37 +39140,1333 @@ const getStyleValues = (styles = {}) => {
39167
39140
  };
39168
39141
  function SpacerWidget({ widget }) {
39169
39142
  var _a, _b;
39170
- const styles = getStyleValues((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39143
+ const styles = getStyleValues$5((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39171
39144
  ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
39172
39145
  return (jsxRuntimeExports.jsx("div", { className: "w-full", style: styles }));
39173
39146
  }
39174
39147
 
39175
- function WidgetRenderer({ widget, isTemplate = false, onConfigUpdate, widgetBackendUrl, onResetReady, widgetIds, datasetId, }) {
39176
- const handleConfigUpdate = (config) => {
39177
- if (onConfigUpdate) {
39178
- onConfigUpdate(widget.id, config);
39148
+ const getStyleValues$4 = (styles = {}) => {
39149
+ const borderRadiusMap = {
39150
+ none: "0px",
39151
+ rounded: "0.375rem",
39152
+ large: "0.5rem",
39153
+ "extra-large": "0.75rem",
39154
+ };
39155
+ const paddingMap = {
39156
+ small: "0.5rem",
39157
+ medium: "1rem",
39158
+ large: "1.5rem",
39159
+ "extra-large": "2rem",
39160
+ };
39161
+ const alignment = styles.alignment || "left";
39162
+ return {
39163
+ backgroundColor: styles.backgroundColor || "#ffffff",
39164
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
39165
+ padding: paddingMap[styles.padding || "medium"],
39166
+ color: styles.textColor || "#000000",
39167
+ fontSize: styles.fontSize || "14px",
39168
+ textAlign: alignment,
39169
+ };
39170
+ };
39171
+ function CopilotKitChatbot({ widget, showHeader, styles, onResetReady, widgetIds, datasetId, }) {
39172
+ var _a, _b, _c, _d;
39173
+ const { threadId, setThreadId } = reactCore.useCopilotContext();
39174
+ React.useEffect(() => {
39175
+ setThreadId(widget.id);
39176
+ }, [widget.id, setThreadId]);
39177
+ const { state: chatbotState, setState: setChatbotState } = reactCore.useCoAgent({
39178
+ name: ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "widget_assistant",
39179
+ initialState: {
39180
+ widget_ids: widgetIds,
39181
+ dataset_id: datasetId
39182
+ },
39183
+ });
39184
+ const { reset } = reactCore.useCopilotChat();
39185
+ // Register the reset function with the parent component
39186
+ React.useEffect(() => {
39187
+ if (onResetReady && reset && widget.id) {
39188
+ console.log('on reset ready=>');
39189
+ const wrappedReset = () => {
39190
+ reset();
39191
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
39192
+ };
39193
+ onResetReady(widget.id, wrappedReset);
39179
39194
  }
39195
+ }, [reset, widget.id, onResetReady]);
39196
+ // Listen for clearChartState events for this widget
39197
+ React.useEffect(() => {
39198
+ const handleClearChartState = (event) => {
39199
+ const { widgetId } = event.detail;
39200
+ if (widgetId === widget.id) {
39201
+ setChatbotState({
39202
+ widget_ids: widgetIds,
39203
+ dataset_id: datasetId
39204
+ });
39205
+ }
39206
+ };
39207
+ window.addEventListener('clearChartState', handleClearChartState);
39208
+ return () => {
39209
+ window.removeEventListener('clearChartState', handleClearChartState);
39210
+ };
39211
+ }, [widget.id, widgetIds, datasetId, setChatbotState]);
39212
+ return (jsxRuntimeExports.jsxs("div", { className: cn("flex flex-col h-full"), children: [showHeader && (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between pb-2 border-b", children: jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.Bot, { className: "h-4 w-4" }), jsxRuntimeExports.jsx("h3", { className: "text-sm font-medium", children: widget.title })] }) })), jsxRuntimeExports.jsx("div", { className: "flex-1 h-full", children: jsxRuntimeExports.jsx(reactUi.CopilotChat, { className: "h-full text-xs [&_.copilot-chat-message]:text-xs [&_.copilot-chat-input]:text-xs", labels: {
39213
+ title: ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.copilotTitle) || widget.title,
39214
+ initial: ((_c = widget.config) === null || _c === void 0 ? void 0 : _c.copilotInitialMessage) || ((_d = widget.config) === null || _d === void 0 ? void 0 : _d.placeholder) || "How can I help you today?"
39215
+ }, onSubmitMessage: () => {
39216
+ setChatbotState(prevState => (Object.assign(Object.assign({}, prevState), { widget_ids: widgetIds, dataset_id: datasetId })));
39217
+ } }) })] }));
39218
+ }
39219
+ function ChatbotWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, }) {
39220
+ var _a, _b;
39221
+ const styles = getStyleValues$4((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39222
+ // Construct the runtime URL using the configurable backend URL
39223
+ const getRuntimeUrl = () => {
39224
+ var _a;
39225
+ const baseUrl = widgetBackendUrl || '';
39226
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
39227
+ return `${baseUrl}/api/copilot/${agentName}`;
39180
39228
  };
39181
- getWidgetStyles(widget);
39182
- const renderWidget = () => {
39183
- switch (widget.type) {
39184
- // Search-related widget cases removed
39185
- // Available widgets
39186
- case "header":
39187
- return jsxRuntimeExports.jsx(HeaderWidget, { widget: widget, showHeader: false });
39188
- case "footer":
39189
- return jsxRuntimeExports.jsx(FooterWidget, { widget: widget, showHeader: false });
39190
- case "text":
39191
- return jsxRuntimeExports.jsx(TextWidget, { widget: widget, showHeader: false });
39192
- case "spacer":
39193
- return jsxRuntimeExports.jsx(SpacerWidget, { widget: widget, showHeader: false });
39194
- case "divider":
39195
- return jsxRuntimeExports.jsx(DividerWidget, { widget: widget, showHeader: false });
39196
- case "facet":
39197
- return (jsxRuntimeExports.jsx(FacetWidget, { widget: widget, showHeader: false, onConfigUpdate: handleConfigUpdate }));
39198
- case "agent":
39199
- case "chatbot":
39200
- return jsxRuntimeExports.jsx(AgentWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId });
39229
+ return (jsxRuntimeExports.jsx(reactCore.CopilotKit, { runtimeUrl: getRuntimeUrl(), showDevConsole: false, agent: ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.agentName) || "widget_assistant", children: jsxRuntimeExports.jsx(CopilotKitChatbot, { widget: widget, showHeader: showHeader, styles: styles, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId }) }));
39230
+ }
39231
+
39232
+ const CHART_REFRESH_TIMEOUT$3 = 3000;
39233
+ const DEFAULT_COLORS$2 = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
39234
+ const clearChat$3 = async (widgetBackendUrl, widgetId) => {
39235
+ if (!widgetBackendUrl || !widgetId)
39236
+ return;
39237
+ console.log('clearChat called for widgetId:', widgetId);
39238
+ try {
39239
+ await fetch(`${widgetBackendUrl}/api/clear-chat`, {
39240
+ method: 'POST',
39241
+ headers: {
39242
+ 'Content-Type': 'application/json',
39243
+ },
39244
+ body: JSON.stringify({
39245
+ session_id: widgetId,
39246
+ delete_state: true
39247
+ }),
39248
+ });
39249
+ console.log('Dispatching clearChartState event from clearChat for widgetId:', widgetId);
39250
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39251
+ }
39252
+ catch (error) {
39253
+ console.error('Failed to clear chat:', error);
39254
+ }
39255
+ };
39256
+ const createLoadingComponent$3 = (message = "Loading chart data...") => (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full", children: jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
39257
+ const createInitialChartState$3 = (datasetId, pieChartState) => {
39258
+ return {
39259
+ pie_chart_data: {
39260
+ title: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.title) || "",
39261
+ type: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.type) || "pie",
39262
+ chart_type: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.chart_type) || "financial",
39263
+ data: { labels: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.data.labels) || [], values: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.data.values) || [], percentages: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.data.percentages) || [], total: pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.data.total },
39264
+ metadata: { categories: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.metadata.categories) || 0, largest_category: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.metadata.largest_category) || "", largest_value: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.metadata.largest_value) || 0, largest_percentage: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.metadata.largest_percentage) || 0 }
39265
+ },
39266
+ dataset_id: datasetId || "home_generation_dataset"
39267
+ };
39268
+ };
39269
+ const loadAgentState$3 = async (widgetBackendUrl, threadId, agentName) => {
39270
+ try {
39271
+ const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
39272
+ method: 'POST',
39273
+ headers: {
39274
+ 'Content-Type': 'application/json',
39275
+ },
39276
+ body: JSON.stringify({
39277
+ "operationName": "loadAgentState",
39278
+ "query": "query loadAgentState($data: LoadAgentStateInput!) {\n loadAgentState(data: $data) {\n threadId\n threadExists\n state\n messages\n __typename\n }\n}",
39279
+ "variables": {
39280
+ "data": {
39281
+ "agentName": agentName,
39282
+ "threadId": threadId
39283
+ }
39284
+ }
39285
+ }),
39286
+ });
39287
+ if (!response.ok) {
39288
+ throw new Error(`HTTP error! status: ${response.status}`);
39289
+ }
39290
+ const result = await response.json();
39291
+ return result;
39292
+ }
39293
+ catch (error) {
39294
+ console.error('Failed to load agent state:', error);
39295
+ return null;
39296
+ }
39297
+ };
39298
+ const parseAndUpdateChartState$3 = (apiResponse, setChartState) => {
39299
+ var _a, _b;
39300
+ try {
39301
+ if ((_b = (_a = apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.data) === null || _a === void 0 ? void 0 : _a.loadAgentState) === null || _b === void 0 ? void 0 : _b.state) {
39302
+ const stateString = apiResponse.data.loadAgentState.state;
39303
+ const parsedState = JSON.parse(stateString);
39304
+ if (parsedState.state) {
39305
+ const chartData = parsedState.state;
39306
+ setChartState((prevState) => {
39307
+ const newChartState = Object.assign({}, prevState);
39308
+ if (chartData.pie_chart_data) {
39309
+ newChartState.pie_chart_data = chartData.pie_chart_data;
39310
+ }
39311
+ if (chartData.agent_message) {
39312
+ newChartState.agent_message = chartData.agent_message;
39313
+ }
39314
+ return newChartState;
39315
+ });
39316
+ }
39317
+ }
39318
+ }
39319
+ catch (error) {
39320
+ console.error('Failed to parse and update chart state:', error);
39321
+ }
39322
+ };
39323
+ const getStyleValues$3 = (styles = {}) => {
39324
+ const borderRadiusMap = {
39325
+ none: "0px",
39326
+ rounded: "0.375rem",
39327
+ large: "0.5rem",
39328
+ "extra-large": "0.75rem",
39329
+ };
39330
+ const paddingMap = {
39331
+ small: "0.5rem",
39332
+ medium: "1rem",
39333
+ large: "1.5rem",
39334
+ "extra-large": "2rem",
39335
+ };
39336
+ const alignment = styles.alignment || "left";
39337
+ return {
39338
+ backgroundColor: styles.backgroundColor || "#ffffff",
39339
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
39340
+ padding: paddingMap[styles.padding || "medium"],
39341
+ color: styles.textColor || "#000000",
39342
+ fontSize: styles.fontSize || "14px",
39343
+ textAlign: alignment,
39344
+ };
39345
+ };
39346
+ function PieChartComponent({ pieChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content, hasWidgetData }) {
39347
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
39348
+ const hasCalledRef = React.useRef(false);
39349
+ const labels = ((_b = (_a = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.labels) || [];
39350
+ const values = ((_d = (_c = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.values) || [];
39351
+ ((_f = (_e = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _e === void 0 ? void 0 : _e.data) === null || _f === void 0 ? void 0 : _f.percentages) || [];
39352
+ const chartTitle = ((_g = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _g === void 0 ? void 0 : _g.title) || "";
39353
+ const units = ((_h = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _h === void 0 ? void 0 : _h.units) || "";
39354
+ const isEmpty = labels.length === 0 || values.length === 0;
39355
+ const handleRefresh = async () => {
39356
+ if (query) {
39357
+ await clearChat$3(widgetBackendUrl, widgetId);
39358
+ console.log('Dispatching clearChartState event for widgetId:', widgetId);
39359
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39360
+ appendMessage(new TextMessage({
39361
+ content: `${query} and render data on pie chart`,
39362
+ role: Role.User,
39363
+ }));
39364
+ }
39365
+ };
39366
+ React.useEffect(() => {
39367
+ if (isEmpty && query && isFirstLoad && !(pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.agent_message) && !hasCalledRef.current) {
39368
+ hasCalledRef.current = true;
39369
+ handleRefresh();
39370
+ }
39371
+ }, [isEmpty, query, isFirstLoad, pieChartState]);
39372
+ React.useEffect(() => {
39373
+ console.log('PieChartComponent useEffect - isEmpty:', isEmpty, 'hasMessage:', !!(pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.agent_message), 'hasWidgetData:', hasWidgetData, 'isFirstLoad:', isFirstLoad);
39374
+ if (isEmpty && startLoadingTimeout && !(pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.agent_message)) {
39375
+ console.log('Starting loading timeout from PieChartComponent useEffect');
39376
+ startLoadingTimeout();
39377
+ }
39378
+ else if (!isEmpty && clearLoadingTimeout) {
39379
+ clearLoadingTimeout();
39380
+ }
39381
+ }, [isEmpty, startLoadingTimeout, clearLoadingTimeout, pieChartState]);
39382
+ const backgroundColors = React.useMemo(() => {
39383
+ return shuffleColors(DEFAULT_COLORS$2, labels.length);
39384
+ }, [labels.length]);
39385
+ if (isEmpty) {
39386
+ return createLoadingComponent$3();
39387
+ }
39388
+ const colors = ((_k = (_j = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _j === void 0 ? void 0 : _j.data) === null || _k === void 0 ? void 0 : _k.colors) || labels.map((_, index) => backgroundColors[index % backgroundColors.length]);
39389
+ const transformedData = {
39390
+ labels: labels,
39391
+ datasets: [
39392
+ {
39393
+ label: chartTitle || "Data",
39394
+ data: values,
39395
+ backgroundColor: colors,
39396
+ borderWidth: 0,
39397
+ },
39398
+ ],
39399
+ };
39400
+ return (jsxRuntimeExports.jsx(PieChart, { title: chartTitle, data: transformedData, units: units, content: content }));
39401
+ }
39402
+ function CopilotKitPieChart({ widget, showHeader, styles, onResetReady, widgetBackendUrl, datasetId, widgetData, }) {
39403
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
39404
+ const isFirstLoad = (_a = widget.config) === null || _a === void 0 ? void 0 : _a.isFirstLoad;
39405
+ const content = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.content;
39406
+ const widget_data = (_c = widget.widget_data) === null || _c === void 0 ? void 0 : _c.pie_chart_data;
39407
+ console.log('widget_data===>', widget_data);
39408
+ const { threadId, setThreadId } = reactCore.useCopilotContext();
39409
+ const timeoutRef = React.useRef(null);
39410
+ const [apiCallCount, setApiCallCount] = React.useState(0);
39411
+ const [hasTimeoutError, setHasTimeoutError] = React.useState(false);
39412
+ React.useEffect(() => {
39413
+ setThreadId(widget.id);
39414
+ }, [widget.id, setThreadId]);
39415
+ const { state: agentState, setState: setAgentState } = reactCore.useCoAgent({
39416
+ name: (_d = widget.config) === null || _d === void 0 ? void 0 : _d.agentName,
39417
+ initialState: createInitialChartState$3(datasetId, widget_data),
39418
+ });
39419
+ const [chartState, setChartState] = React.useState(createInitialChartState$3(datasetId, widget_data));
39420
+ const handleLoadingTimeout = React.useCallback(async () => {
39421
+ var _a;
39422
+ if (!widgetBackendUrl || !widget.id || (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) || hasTimeoutError) {
39423
+ console.log('Skipping API call - conditions not met');
39424
+ return;
39425
+ }
39426
+ console.log('Loading timeout triggered for widget:', widget.id, 'API call count:', apiCallCount);
39427
+ if (apiCallCount >= 30) {
39428
+ console.log('API call limit reached for widget:', widget.id);
39429
+ setHasTimeoutError(true);
39430
+ setChartState(prevState => (Object.assign(Object.assign({}, prevState), { agent_message: "Timeout: Unable to load data after multiple attempts. Please try refreshing the widget." })));
39431
+ return;
39432
+ }
39433
+ setApiCallCount(prev => prev + 1);
39434
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
39435
+ console.log('Calling loadAgentState API for widget:', widget.id);
39436
+ const apiResponse = await loadAgentState$3(widgetBackendUrl, widget.id, agentName);
39437
+ console.log('API response received:', apiResponse);
39438
+ if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
39439
+ parseAndUpdateChartState$3(apiResponse, setChartState);
39440
+ }
39441
+ }, [widgetBackendUrl, widget.id, setChartState, (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName, chartState, apiCallCount, hasTimeoutError]);
39442
+ const startLoadingTimeout = React.useCallback(() => {
39443
+ if (timeoutRef.current) {
39444
+ clearTimeout(timeoutRef.current);
39445
+ }
39446
+ console.log('Scheduling next API call in 3 seconds');
39447
+ timeoutRef.current = setTimeout(() => {
39448
+ handleLoadingTimeout();
39449
+ }, CHART_REFRESH_TIMEOUT$3);
39450
+ }, [handleLoadingTimeout]);
39451
+ const clearLoadingTimeout = React.useCallback(() => {
39452
+ if (timeoutRef.current) {
39453
+ clearTimeout(timeoutRef.current);
39454
+ timeoutRef.current = null;
39455
+ }
39456
+ }, []);
39457
+ React.useEffect(() => {
39458
+ return () => {
39459
+ if (timeoutRef.current) {
39460
+ clearTimeout(timeoutRef.current);
39461
+ }
39462
+ };
39463
+ }, []);
39464
+ const { appendMessage, reset } = reactCore.useCopilotChat();
39465
+ React.useEffect(() => {
39466
+ if (onResetReady && reset && widget.id) {
39467
+ const wrappedReset = () => {
39468
+ reset();
39469
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
39470
+ };
39471
+ onResetReady(widget.id, wrappedReset);
39472
+ }
39473
+ }, [reset, widget.id, onResetReady]);
39474
+ React.useEffect(() => {
39475
+ const handleTriggerAgent = (event) => {
39476
+ const { widgetId, query, agentType: eventAgentType, datasetId } = event.detail;
39477
+ reset();
39478
+ if (widgetId === widget.id) {
39479
+ let messageContent = `${query} and render data on pie chart`;
39480
+ console.log('triggering to datasetId==>', datasetId);
39481
+ setChartState(createInitialChartState$3(datasetId));
39482
+ setAgentState(createInitialChartState$3(datasetId));
39483
+ setApiCallCount(0);
39484
+ setHasTimeoutError(false);
39485
+ appendMessage(new TextMessage({
39486
+ content: messageContent,
39487
+ role: Role.User,
39488
+ }));
39489
+ // Start polling for chart data
39490
+ startLoadingTimeout();
39491
+ }
39492
+ };
39493
+ const handleClearChartState = (event) => {
39494
+ const { widgetId } = event.detail;
39495
+ if (widgetId === widget.id) {
39496
+ setChartState(createInitialChartState$3(datasetId));
39497
+ setAgentState(createInitialChartState$3(datasetId));
39498
+ setApiCallCount(0);
39499
+ setHasTimeoutError(false);
39500
+ }
39501
+ };
39502
+ window.addEventListener('triggerAgent', handleTriggerAgent);
39503
+ window.addEventListener('clearChartState', handleClearChartState);
39504
+ return () => {
39505
+ window.removeEventListener('triggerAgent', handleTriggerAgent);
39506
+ window.removeEventListener('clearChartState', handleClearChartState);
39507
+ };
39508
+ }, [widget.id, appendMessage, setChartState, startLoadingTimeout]);
39509
+ return (jsxRuntimeExports.jsxs("div", { className: cn("flex flex-col h-full"), children: [showHeader && (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between pb-2 border-b", children: jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.Bot, { className: "h-4 w-4" }), jsxRuntimeExports.jsx("h3", { className: "text-sm font-medium", children: widget.title })] }) })), jsxRuntimeExports.jsx("div", { className: "flex-1 h-full", children: (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) &&
39510
+ (!((_h = (_g = (_f = chartState.pie_chart_data) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.labels) === null || _h === void 0 ? void 0 : _h.length) || !((_l = (_k = (_j = chartState.pie_chart_data) === null || _j === void 0 ? void 0 : _j.data) === null || _k === void 0 ? void 0 : _k.values) === null || _l === void 0 ? void 0 : _l.length))
39511
+ ? (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full p-4", children: jsxRuntimeExports.jsx("div", { className: "text-center max-w-md", children: jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700", children: chartState.agent_message }) }) })) : (jsxRuntimeExports.jsx(PieChartComponent, { pieChartState: chartState, styles: styles, appendMessage: appendMessage, content: content, query: (_m = widget.config) === null || _m === void 0 ? void 0 : _m.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout, hasWidgetData: !!(((_p = (_o = widget_data === null || widget_data === void 0 ? void 0 : widget_data.data) === null || _o === void 0 ? void 0 : _o.labels) === null || _p === void 0 ? void 0 : _p.length) && ((_r = (_q = widget_data === null || widget_data === void 0 ? void 0 : widget_data.data) === null || _q === void 0 ? void 0 : _q.values) === null || _r === void 0 ? void 0 : _r.length)) })) })] }));
39512
+ }
39513
+ function PieChartWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
39514
+ var _a, _b;
39515
+ const styles = getStyleValues$3((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39516
+ const getRuntimeUrl = () => {
39517
+ var _a;
39518
+ const baseUrl = widgetBackendUrl || '';
39519
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
39520
+ return `${baseUrl}/api/copilot/${agentName}`;
39521
+ };
39522
+ return (jsxRuntimeExports.jsx(reactCore.CopilotKit, { runtimeUrl: getRuntimeUrl(), showDevConsole: false, agent: ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.agentName) || "widget_assistant", children: jsxRuntimeExports.jsx(CopilotKitPieChart, { widget: widget, showHeader: showHeader, styles: styles, onResetReady: onResetReady, widgetBackendUrl: widgetBackendUrl, datasetId: datasetId }) }));
39523
+ }
39524
+
39525
+ const CHART_REFRESH_TIMEOUT$2 = 3000;
39526
+ const DEFAULT_COLORS$1 = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
39527
+ const clearChat$2 = async (widgetBackendUrl, widgetId) => {
39528
+ if (!widgetBackendUrl || !widgetId)
39529
+ return;
39530
+ console.log('clearChat called for widgetId:', widgetId);
39531
+ try {
39532
+ await fetch(`${widgetBackendUrl}/api/clear-chat`, {
39533
+ method: 'POST',
39534
+ headers: {
39535
+ 'Content-Type': 'application/json',
39536
+ },
39537
+ body: JSON.stringify({
39538
+ session_id: widgetId,
39539
+ delete_state: true
39540
+ }),
39541
+ });
39542
+ console.log('Dispatching clearChartState event from clearChat for widgetId:', widgetId);
39543
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39544
+ }
39545
+ catch (error) {
39546
+ console.error('Failed to clear chat:', error);
39547
+ }
39548
+ };
39549
+ const createLoadingComponent$2 = (message = "Loading chart data...") => (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full", children: jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
39550
+ const createInitialChartState$2 = (datasetId, seriesBarChartState) => {
39551
+ return {
39552
+ series_bar_chart_data: {
39553
+ title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.title) || "",
39554
+ type: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.type) || "series_bar",
39555
+ chart_type: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.chart_type) || "financial",
39556
+ x_axis_title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.x_axis_title) || "",
39557
+ y_axis_title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.y_axis_title) || "",
39558
+ orientation: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.orientation) || "vertical",
39559
+ units: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.units) || "",
39560
+ data: {
39561
+ labels: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.labels) || [],
39562
+ series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.series) || [],
39563
+ total: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.total) || 0,
39564
+ average: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.average) || 0
39565
+ },
39566
+ metadata: {
39567
+ categories: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.categories) || 0,
39568
+ series_count: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_count) || 0,
39569
+ highest_category: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_category) || "",
39570
+ highest_value: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_value) || 0,
39571
+ highest_series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_series) || "",
39572
+ lowest_category: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_category) || "",
39573
+ lowest_value: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_value) || 0,
39574
+ lowest_series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_series) || "",
39575
+ range: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.range) || 0,
39576
+ series_totals: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_totals) || {},
39577
+ series_averages: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_averages) || {}
39578
+ }
39579
+ },
39580
+ dataset_id: datasetId || "home_generation_dataset"
39581
+ };
39582
+ };
39583
+ const loadAgentState$2 = async (widgetBackendUrl, threadId, agentName) => {
39584
+ try {
39585
+ const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
39586
+ method: 'POST',
39587
+ headers: {
39588
+ 'Content-Type': 'application/json',
39589
+ },
39590
+ body: JSON.stringify({
39591
+ "operationName": "loadAgentState",
39592
+ "query": "query loadAgentState($data: LoadAgentStateInput!) {\n loadAgentState(data: $data) {\n threadId\n threadExists\n state\n messages\n __typename\n }\n}",
39593
+ "variables": {
39594
+ "data": {
39595
+ "agentName": agentName,
39596
+ "threadId": threadId
39597
+ }
39598
+ }
39599
+ }),
39600
+ });
39601
+ if (!response.ok) {
39602
+ throw new Error(`HTTP error! status: ${response.status}`);
39603
+ }
39604
+ const result = await response.json();
39605
+ return result;
39606
+ }
39607
+ catch (error) {
39608
+ console.error('Failed to load agent state:', error);
39609
+ return null;
39610
+ }
39611
+ };
39612
+ const parseAndUpdateChartState$2 = (apiResponse, setChartState) => {
39613
+ var _a, _b;
39614
+ try {
39615
+ if ((_b = (_a = apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.data) === null || _a === void 0 ? void 0 : _a.loadAgentState) === null || _b === void 0 ? void 0 : _b.state) {
39616
+ const stateString = apiResponse.data.loadAgentState.state;
39617
+ const parsedState = JSON.parse(stateString);
39618
+ if (parsedState.state) {
39619
+ const chartData = parsedState.state;
39620
+ setChartState((prevState) => {
39621
+ const newChartState = Object.assign({}, prevState);
39622
+ if (chartData.series_bar_chart_data) {
39623
+ newChartState.series_bar_chart_data = chartData.series_bar_chart_data;
39624
+ }
39625
+ if (chartData.agent_message) {
39626
+ newChartState.agent_message = chartData.agent_message;
39627
+ }
39628
+ return newChartState;
39629
+ });
39630
+ }
39631
+ }
39632
+ }
39633
+ catch (error) {
39634
+ console.error('Failed to parse and update chart state:', error);
39635
+ }
39636
+ };
39637
+ const getStyleValues$2 = (styles = {}) => {
39638
+ const borderRadiusMap = {
39639
+ none: "0px",
39640
+ rounded: "0.375rem",
39641
+ large: "0.5rem",
39642
+ "extra-large": "0.75rem",
39643
+ };
39644
+ const paddingMap = {
39645
+ small: "0.5rem",
39646
+ medium: "1rem",
39647
+ large: "1.5rem",
39648
+ "extra-large": "2rem",
39649
+ };
39650
+ const alignment = styles.alignment || "left";
39651
+ return {
39652
+ backgroundColor: styles.backgroundColor || "#ffffff",
39653
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
39654
+ padding: paddingMap[styles.padding || "medium"],
39655
+ color: styles.textColor || "#000000",
39656
+ fontSize: styles.fontSize || "14px",
39657
+ textAlign: alignment,
39658
+ };
39659
+ };
39660
+ function SeriesBarChartComponent$1({ orientation, seriesBarChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content, hasWidgetData }) {
39661
+ var _a, _b, _c, _d, _e, _f, _g, _h;
39662
+ const hasCalledRef = React.useRef(false);
39663
+ const labels = ((_b = (_a = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.labels) || [];
39664
+ const series = ((_d = (_c = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.series) || [];
39665
+ const chartTitle = ((_e = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _e === void 0 ? void 0 : _e.title) || "";
39666
+ const units = ((_f = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _f === void 0 ? void 0 : _f.units) || "";
39667
+ const x_axis_title = ((_g = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _g === void 0 ? void 0 : _g.x_axis_title) || "";
39668
+ const y_axis_title = ((_h = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _h === void 0 ? void 0 : _h.y_axis_title) || "";
39669
+ const isEmpty = labels.length === 0 || series.length === 0;
39670
+ const handleRefresh = async () => {
39671
+ if (query) {
39672
+ await clearChat$2(widgetBackendUrl, widgetId);
39673
+ console.log('Dispatching clearChartState event for widgetId:', widgetId);
39674
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39675
+ appendMessage(new TextMessage({
39676
+ content: `${query} and render data on a series bar chart`,
39677
+ role: Role.User,
39678
+ }));
39679
+ }
39680
+ };
39681
+ React.useEffect(() => {
39682
+ if (isEmpty && query && isFirstLoad && !(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message) && !hasCalledRef.current) {
39683
+ hasCalledRef.current = true;
39684
+ handleRefresh();
39685
+ }
39686
+ }, [isEmpty, query, isFirstLoad, seriesBarChartState]);
39687
+ React.useEffect(() => {
39688
+ console.log('SeriesBarChartComponent useEffect - isEmpty:', isEmpty, 'hasMessage:', !!(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message), 'hasWidgetData:', hasWidgetData, 'isFirstLoad:', isFirstLoad);
39689
+ if (isEmpty && startLoadingTimeout && !(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message)) {
39690
+ console.log('Starting loading timeout from SeriesBarChartComponent useEffect');
39691
+ startLoadingTimeout();
39692
+ }
39693
+ else if (!isEmpty && clearLoadingTimeout) {
39694
+ clearLoadingTimeout();
39695
+ }
39696
+ }, [isEmpty, startLoadingTimeout, clearLoadingTimeout, seriesBarChartState]);
39697
+ const finalColors = React.useMemo(() => {
39698
+ return shuffleColors(DEFAULT_COLORS$1, series.length);
39699
+ }, [series.length]);
39700
+ if (isEmpty) {
39701
+ return createLoadingComponent$2();
39702
+ }
39703
+ const transformedData = {
39704
+ labels: labels,
39705
+ datasets: series.map((seriesItem, index) => ({
39706
+ label: seriesItem.name,
39707
+ data: seriesItem.values,
39708
+ backgroundColor: (seriesItem === null || seriesItem === void 0 ? void 0 : seriesItem.colors) || (seriesItem === null || seriesItem === void 0 ? void 0 : seriesItem.color) || finalColors[index % finalColors.length],
39709
+ })),
39710
+ };
39711
+ return (jsxRuntimeExports.jsx(SeriesChart, { orientation: orientation, title: chartTitle, data: transformedData, units: units, content: content, x_axis_title: x_axis_title, y_axis_title: y_axis_title }));
39712
+ }
39713
+ function CopilotKitSeriesBarChart$1({ widget, showHeader, styles, onResetReady, widgetBackendUrl, datasetId, widgetData, }) {
39714
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
39715
+ const orientation = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.orientation) || "vertical";
39716
+ const isFirstLoad = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.isFirstLoad;
39717
+ const content = (_c = widget.config) === null || _c === void 0 ? void 0 : _c.content;
39718
+ const widget_data = (_d = widget.widget_data) === null || _d === void 0 ? void 0 : _d.series_bar_chart_data;
39719
+ console.log('widget_data===>', widget_data);
39720
+ const { threadId, setThreadId } = reactCore.useCopilotContext();
39721
+ const timeoutRef = React.useRef(null);
39722
+ const [apiCallCount, setApiCallCount] = React.useState(0);
39723
+ const [hasTimeoutError, setHasTimeoutError] = React.useState(false);
39724
+ React.useEffect(() => {
39725
+ setThreadId(widget.id);
39726
+ }, [widget.id, setThreadId]);
39727
+ const { state: agentState, setState: setAgentState } = reactCore.useCoAgent({
39728
+ name: (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName,
39729
+ initialState: createInitialChartState$2(datasetId, widget_data),
39730
+ });
39731
+ const [chartState, setChartState] = React.useState(createInitialChartState$2(datasetId, widget_data));
39732
+ const handleLoadingTimeout = React.useCallback(async () => {
39733
+ var _a;
39734
+ if (!widgetBackendUrl || !widget.id || (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) || hasTimeoutError) {
39735
+ console.log('Skipping API call - conditions not met');
39736
+ return;
39737
+ }
39738
+ console.log('Loading timeout triggered for widget:', widget.id, 'API call count:', apiCallCount);
39739
+ if (apiCallCount >= 30) {
39740
+ console.log('API call limit reached for widget:', widget.id);
39741
+ setHasTimeoutError(true);
39742
+ setChartState(prevState => (Object.assign(Object.assign({}, prevState), { agent_message: "Timeout: Unable to load data after multiple attempts. Please try refreshing the widget." })));
39743
+ return;
39744
+ }
39745
+ setApiCallCount(prev => prev + 1);
39746
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
39747
+ console.log('Calling loadAgentState API for widget:', widget.id);
39748
+ const apiResponse = await loadAgentState$2(widgetBackendUrl, widget.id, agentName);
39749
+ console.log('API response received:', apiResponse);
39750
+ if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
39751
+ parseAndUpdateChartState$2(apiResponse, setChartState);
39752
+ }
39753
+ }, [widgetBackendUrl, widget.id, setChartState, (_f = widget.config) === null || _f === void 0 ? void 0 : _f.agentName, chartState, apiCallCount, hasTimeoutError]);
39754
+ const startLoadingTimeout = React.useCallback(() => {
39755
+ if (timeoutRef.current) {
39756
+ clearTimeout(timeoutRef.current);
39757
+ }
39758
+ console.log('Scheduling next API call in 3 seconds');
39759
+ timeoutRef.current = setTimeout(() => {
39760
+ handleLoadingTimeout();
39761
+ }, CHART_REFRESH_TIMEOUT$2);
39762
+ }, [handleLoadingTimeout]);
39763
+ const clearLoadingTimeout = React.useCallback(() => {
39764
+ if (timeoutRef.current) {
39765
+ clearTimeout(timeoutRef.current);
39766
+ timeoutRef.current = null;
39767
+ }
39768
+ }, []);
39769
+ React.useEffect(() => {
39770
+ return () => {
39771
+ if (timeoutRef.current) {
39772
+ clearTimeout(timeoutRef.current);
39773
+ }
39774
+ };
39775
+ }, []);
39776
+ const { appendMessage, reset } = reactCore.useCopilotChat();
39777
+ React.useEffect(() => {
39778
+ if (onResetReady && reset && widget.id) {
39779
+ const wrappedReset = () => {
39780
+ reset();
39781
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
39782
+ };
39783
+ onResetReady(widget.id, wrappedReset);
39784
+ }
39785
+ }, [reset, widget.id, onResetReady]);
39786
+ React.useEffect(() => {
39787
+ const handleTriggerAgent = (event) => {
39788
+ const { widgetId, query, agentType: eventAgentType, datasetId } = event.detail;
39789
+ if (widgetId === widget.id) {
39790
+ let messageContent = `${query} and render data on a series bar chart`;
39791
+ reset();
39792
+ console.log('triggering to datasetId==>', datasetId);
39793
+ setChartState(createInitialChartState$2(datasetId));
39794
+ setAgentState(createInitialChartState$2(datasetId));
39795
+ setApiCallCount(0);
39796
+ setHasTimeoutError(false);
39797
+ appendMessage(new TextMessage({
39798
+ content: messageContent,
39799
+ role: Role.User,
39800
+ }));
39801
+ // Start polling for chart data
39802
+ startLoadingTimeout();
39803
+ }
39804
+ };
39805
+ const handleClearChartState = (event) => {
39806
+ const { widgetId } = event.detail;
39807
+ if (widgetId === widget.id) {
39808
+ setChartState(createInitialChartState$2(datasetId));
39809
+ setAgentState(createInitialChartState$2(datasetId));
39810
+ setApiCallCount(0);
39811
+ setHasTimeoutError(false);
39812
+ }
39813
+ };
39814
+ window.addEventListener('triggerAgent', handleTriggerAgent);
39815
+ window.addEventListener('clearChartState', handleClearChartState);
39816
+ return () => {
39817
+ window.removeEventListener('triggerAgent', handleTriggerAgent);
39818
+ window.removeEventListener('clearChartState', handleClearChartState);
39819
+ };
39820
+ }, [widget.id, appendMessage, setChartState, startLoadingTimeout]);
39821
+ return (jsxRuntimeExports.jsxs("div", { className: cn("flex flex-col h-full"), children: [showHeader && (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between pb-2 border-b", children: jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.Bot, { className: "h-4 w-4" }), jsxRuntimeExports.jsx("h3", { className: "text-sm font-medium", children: widget.title })] }) })), jsxRuntimeExports.jsx("div", { className: "flex-1 h-full", children: (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) &&
39822
+ (!((_j = (_h = (_g = chartState.series_bar_chart_data) === null || _g === void 0 ? void 0 : _g.data) === null || _h === void 0 ? void 0 : _h.labels) === null || _j === void 0 ? void 0 : _j.length) || !((_m = (_l = (_k = chartState.series_bar_chart_data) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.series) === null || _m === void 0 ? void 0 : _m.length))
39823
+ ? (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full p-4", children: jsxRuntimeExports.jsx("div", { className: "text-center max-w-md", children: jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700", children: chartState.agent_message }) }) })) : (jsxRuntimeExports.jsx(SeriesBarChartComponent$1, { orientation: orientation, seriesBarChartState: chartState, styles: styles, appendMessage: appendMessage, content: content, query: (_o = widget.config) === null || _o === void 0 ? void 0 : _o.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout, hasWidgetData: !!(((_q = (_p = widget_data === null || widget_data === void 0 ? void 0 : widget_data.data) === null || _p === void 0 ? void 0 : _p.labels) === null || _q === void 0 ? void 0 : _q.length) && ((_s = (_r = widget_data === null || widget_data === void 0 ? void 0 : widget_data.data) === null || _r === void 0 ? void 0 : _r.series) === null || _s === void 0 ? void 0 : _s.length)) })) })] }));
39824
+ }
39825
+ function SeriesBarChartWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
39826
+ var _a, _b;
39827
+ const styles = getStyleValues$2((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39828
+ const getRuntimeUrl = () => {
39829
+ var _a;
39830
+ const baseUrl = widgetBackendUrl || '';
39831
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
39832
+ return `${baseUrl}/api/copilot/${agentName}`;
39833
+ };
39834
+ return (jsxRuntimeExports.jsx(reactCore.CopilotKit, { runtimeUrl: getRuntimeUrl(), showDevConsole: false, agent: ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.agentName) || "widget_assistant", children: jsxRuntimeExports.jsx(CopilotKitSeriesBarChart$1, { widget: widget, showHeader: showHeader, styles: styles, onResetReady: onResetReady, widgetBackendUrl: widgetBackendUrl, datasetId: datasetId }) }));
39835
+ }
39836
+
39837
+ const CHART_REFRESH_TIMEOUT$1 = 3000;
39838
+ const DEFAULT_COLORS = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
39839
+ const clearChat$1 = async (widgetBackendUrl, widgetId) => {
39840
+ if (!widgetBackendUrl || !widgetId)
39841
+ return;
39842
+ console.log('clearChat called for widgetId:', widgetId);
39843
+ try {
39844
+ await fetch(`${widgetBackendUrl}/api/clear-chat`, {
39845
+ method: 'POST',
39846
+ headers: {
39847
+ 'Content-Type': 'application/json',
39848
+ },
39849
+ body: JSON.stringify({
39850
+ session_id: widgetId,
39851
+ delete_state: true
39852
+ }),
39853
+ });
39854
+ console.log('Dispatching clearChartState event from clearChat for widgetId:', widgetId);
39855
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39856
+ }
39857
+ catch (error) {
39858
+ console.error('Failed to clear chat:', error);
39859
+ }
39860
+ };
39861
+ const createLoadingComponent$1 = (message = "Loading chart data...") => (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full", children: jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
39862
+ const createInitialChartState$1 = (datasetId, seriesBarChartState) => {
39863
+ return {
39864
+ series_bar_chart_data: {
39865
+ title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.title) || "",
39866
+ type: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.type) || "series_bar",
39867
+ chart_type: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.chart_type) || "financial",
39868
+ x_axis_title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.x_axis_title) || "",
39869
+ y_axis_title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.y_axis_title) || "",
39870
+ orientation: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.orientation) || "vertical",
39871
+ units: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.units) || "",
39872
+ data: {
39873
+ labels: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.labels) || [],
39874
+ series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.series) || [],
39875
+ total: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.total) || 0,
39876
+ average: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.average) || 0
39877
+ },
39878
+ metadata: {
39879
+ categories: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.categories) || 0,
39880
+ series_count: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_count) || 0,
39881
+ highest_category: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_category) || "",
39882
+ highest_value: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_value) || 0,
39883
+ highest_series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_series) || "",
39884
+ lowest_category: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_category) || "",
39885
+ lowest_value: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_value) || 0,
39886
+ lowest_series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_series) || "",
39887
+ range: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.range) || 0,
39888
+ series_totals: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_totals) || {},
39889
+ series_averages: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_averages) || {}
39890
+ }
39891
+ },
39892
+ dataset_id: datasetId || "home_generation_dataset"
39893
+ };
39894
+ };
39895
+ const loadAgentState$1 = async (widgetBackendUrl, threadId, agentName) => {
39896
+ try {
39897
+ const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
39898
+ method: 'POST',
39899
+ headers: {
39900
+ 'Content-Type': 'application/json',
39901
+ },
39902
+ body: JSON.stringify({
39903
+ "operationName": "loadAgentState",
39904
+ "query": "query loadAgentState($data: LoadAgentStateInput!) {\n loadAgentState(data: $data) {\n threadId\n threadExists\n state\n messages\n __typename\n }\n}",
39905
+ "variables": {
39906
+ "data": {
39907
+ "agentName": agentName,
39908
+ "threadId": threadId
39909
+ }
39910
+ }
39911
+ }),
39912
+ });
39913
+ if (!response.ok) {
39914
+ throw new Error(`HTTP error! status: ${response.status}`);
39915
+ }
39916
+ const result = await response.json();
39917
+ return result;
39918
+ }
39919
+ catch (error) {
39920
+ console.error('Failed to load agent state:', error);
39921
+ return null;
39922
+ }
39923
+ };
39924
+ const parseAndUpdateChartState$1 = (apiResponse, setChartState) => {
39925
+ var _a, _b;
39926
+ try {
39927
+ if ((_b = (_a = apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.data) === null || _a === void 0 ? void 0 : _a.loadAgentState) === null || _b === void 0 ? void 0 : _b.state) {
39928
+ const stateString = apiResponse.data.loadAgentState.state;
39929
+ const parsedState = JSON.parse(stateString);
39930
+ if (parsedState.state) {
39931
+ const chartData = parsedState.state;
39932
+ setChartState((prevState) => {
39933
+ const newChartState = Object.assign({}, prevState);
39934
+ if (chartData.series_bar_chart_data) {
39935
+ newChartState.series_bar_chart_data = chartData.series_bar_chart_data;
39936
+ }
39937
+ if (chartData.agent_message) {
39938
+ newChartState.agent_message = chartData.agent_message;
39939
+ }
39940
+ return newChartState;
39941
+ });
39942
+ }
39943
+ }
39944
+ }
39945
+ catch (error) {
39946
+ console.error('Failed to parse and update chart state:', error);
39947
+ }
39948
+ };
39949
+ const getStyleValues$1 = (styles = {}) => {
39950
+ const borderRadiusMap = {
39951
+ none: "0px",
39952
+ rounded: "0.375rem",
39953
+ large: "0.5rem",
39954
+ "extra-large": "0.75rem",
39955
+ };
39956
+ const paddingMap = {
39957
+ small: "0.5rem",
39958
+ medium: "1rem",
39959
+ large: "1.5rem",
39960
+ "extra-large": "2rem",
39961
+ };
39962
+ const alignment = styles.alignment || "left";
39963
+ return {
39964
+ backgroundColor: styles.backgroundColor || "#ffffff",
39965
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
39966
+ padding: paddingMap[styles.padding || "medium"],
39967
+ color: styles.textColor || "#000000",
39968
+ fontSize: styles.fontSize || "14px",
39969
+ textAlign: alignment,
39970
+ };
39971
+ };
39972
+ function SeriesBarChartComponent({ orientation, seriesBarChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content, hasWidgetData }) {
39973
+ var _a, _b, _c, _d, _e, _f, _g, _h;
39974
+ const hasCalledRef = React.useRef(false);
39975
+ const labels = ((_b = (_a = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.labels) || [];
39976
+ const series = ((_d = (_c = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.series) || [];
39977
+ const chartTitle = ((_e = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _e === void 0 ? void 0 : _e.title) || "";
39978
+ const units = ((_f = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _f === void 0 ? void 0 : _f.units) || "";
39979
+ const x_axis_title = ((_g = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _g === void 0 ? void 0 : _g.x_axis_title) || "";
39980
+ const y_axis_title = ((_h = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _h === void 0 ? void 0 : _h.y_axis_title) || "";
39981
+ const isEmpty = labels.length === 0 || series.length === 0;
39982
+ const handleRefresh = async () => {
39983
+ if (query) {
39984
+ await clearChat$1(widgetBackendUrl, widgetId);
39985
+ console.log('Dispatching clearChartState event for widgetId:', widgetId);
39986
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39987
+ appendMessage(new TextMessage({
39988
+ content: `${query} and render data on a series bar chart`,
39989
+ role: Role.User,
39990
+ }));
39991
+ }
39992
+ };
39993
+ React.useEffect(() => {
39994
+ if (isEmpty && query && isFirstLoad && !(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message) && !hasCalledRef.current) {
39995
+ hasCalledRef.current = true;
39996
+ handleRefresh();
39997
+ }
39998
+ }, [isEmpty, query, isFirstLoad, seriesBarChartState]);
39999
+ React.useEffect(() => {
40000
+ console.log('SeriesBarChartComponent useEffect - isEmpty:', isEmpty, 'hasMessage:', !!(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message), 'hasWidgetData:', hasWidgetData, 'isFirstLoad:', isFirstLoad);
40001
+ if (isEmpty && startLoadingTimeout && !(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message)) {
40002
+ console.log('Starting loading timeout from SeriesBarChartComponent useEffect');
40003
+ startLoadingTimeout();
40004
+ }
40005
+ else if (!isEmpty && clearLoadingTimeout) {
40006
+ clearLoadingTimeout();
40007
+ }
40008
+ }, [isEmpty, startLoadingTimeout, clearLoadingTimeout, seriesBarChartState]);
40009
+ const finalColors = React.useMemo(() => {
40010
+ return shuffleColors(DEFAULT_COLORS, series.length);
40011
+ }, [series.length]);
40012
+ if (isEmpty) {
40013
+ return createLoadingComponent$1();
40014
+ }
40015
+ const transformedData = {
40016
+ labels: labels,
40017
+ datasets: series.map((seriesItem, index) => ({
40018
+ label: seriesItem.name,
40019
+ data: seriesItem.values,
40020
+ backgroundColor: (seriesItem === null || seriesItem === void 0 ? void 0 : seriesItem.colors) || (seriesItem === null || seriesItem === void 0 ? void 0 : seriesItem.color) || finalColors[index % finalColors.length],
40021
+ })),
40022
+ };
40023
+ return (jsxRuntimeExports.jsx(SeriesLineChart, { orientation: orientation, title: chartTitle, data: transformedData, units: units, content: content, x_axis_title: x_axis_title, y_axis_title: y_axis_title }));
40024
+ }
40025
+ function CopilotKitSeriesBarChart({ widget, showHeader, styles, onResetReady, widgetBackendUrl, datasetId, widgetData, }) {
40026
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
40027
+ const orientation = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.orientation) || "vertical";
40028
+ const isFirstLoad = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.isFirstLoad;
40029
+ const content = (_c = widget.config) === null || _c === void 0 ? void 0 : _c.content;
40030
+ const widget_data = (_d = widget.widget_data) === null || _d === void 0 ? void 0 : _d.series_bar_chart_data;
40031
+ console.log('widget_data===>', widget_data);
40032
+ const { threadId, setThreadId } = reactCore.useCopilotContext();
40033
+ const timeoutRef = React.useRef(null);
40034
+ const [apiCallCount, setApiCallCount] = React.useState(0);
40035
+ const [hasTimeoutError, setHasTimeoutError] = React.useState(false);
40036
+ React.useEffect(() => {
40037
+ setThreadId(widget.id);
40038
+ }, [widget.id, setThreadId]);
40039
+ const { state: agentState, setState: setAgentState } = reactCore.useCoAgent({
40040
+ name: (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName,
40041
+ initialState: createInitialChartState$1(datasetId, widget_data),
40042
+ });
40043
+ const [chartState, setChartState] = React.useState(createInitialChartState$1(datasetId, widget_data));
40044
+ const handleLoadingTimeout = React.useCallback(async () => {
40045
+ var _a;
40046
+ if (!widgetBackendUrl || !widget.id || (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) || hasTimeoutError) {
40047
+ console.log('Skipping API call - conditions not met');
40048
+ return;
40049
+ }
40050
+ console.log('Loading timeout triggered for widget:', widget.id, 'API call count:', apiCallCount);
40051
+ if (apiCallCount >= 30) {
40052
+ console.log('API call limit reached for widget:', widget.id);
40053
+ setHasTimeoutError(true);
40054
+ setChartState(prevState => (Object.assign(Object.assign({}, prevState), { agent_message: "Timeout: Unable to load data after multiple attempts. Please try refreshing the widget." })));
40055
+ return;
40056
+ }
40057
+ setApiCallCount(prev => prev + 1);
40058
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
40059
+ console.log('Calling loadAgentState API for widget:', widget.id);
40060
+ const apiResponse = await loadAgentState$1(widgetBackendUrl, widget.id, agentName);
40061
+ console.log('API response received:', apiResponse);
40062
+ if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
40063
+ parseAndUpdateChartState$1(apiResponse, setChartState);
40064
+ }
40065
+ }, [widgetBackendUrl, widget.id, setChartState, (_f = widget.config) === null || _f === void 0 ? void 0 : _f.agentName, chartState, apiCallCount, hasTimeoutError]);
40066
+ const startLoadingTimeout = React.useCallback(() => {
40067
+ if (timeoutRef.current) {
40068
+ clearTimeout(timeoutRef.current);
40069
+ }
40070
+ console.log('Scheduling next API call in 3 seconds');
40071
+ timeoutRef.current = setTimeout(() => {
40072
+ handleLoadingTimeout();
40073
+ }, CHART_REFRESH_TIMEOUT$1);
40074
+ }, [handleLoadingTimeout]);
40075
+ const clearLoadingTimeout = React.useCallback(() => {
40076
+ if (timeoutRef.current) {
40077
+ clearTimeout(timeoutRef.current);
40078
+ timeoutRef.current = null;
40079
+ }
40080
+ }, []);
40081
+ React.useEffect(() => {
40082
+ return () => {
40083
+ if (timeoutRef.current) {
40084
+ clearTimeout(timeoutRef.current);
40085
+ }
40086
+ };
40087
+ }, []);
40088
+ const { appendMessage, reset } = reactCore.useCopilotChat();
40089
+ React.useEffect(() => {
40090
+ if (onResetReady && reset && widget.id) {
40091
+ const wrappedReset = () => {
40092
+ reset();
40093
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
40094
+ };
40095
+ onResetReady(widget.id, wrappedReset);
40096
+ }
40097
+ }, [reset, widget.id, onResetReady]);
40098
+ React.useEffect(() => {
40099
+ const handleTriggerAgent = (event) => {
40100
+ const { widgetId, query, agentType: eventAgentType, datasetId } = event.detail;
40101
+ if (widgetId === widget.id) {
40102
+ let messageContent = `${query} and render data on a series bar chart`;
40103
+ reset();
40104
+ console.log('triggering to datasetId==>', datasetId);
40105
+ setChartState(createInitialChartState$1(datasetId));
40106
+ setAgentState(createInitialChartState$1(datasetId));
40107
+ setApiCallCount(0);
40108
+ setHasTimeoutError(false);
40109
+ appendMessage(new TextMessage({
40110
+ content: messageContent,
40111
+ role: Role.User,
40112
+ }));
40113
+ // Start polling for chart data
40114
+ startLoadingTimeout();
40115
+ }
40116
+ };
40117
+ const handleClearChartState = (event) => {
40118
+ const { widgetId } = event.detail;
40119
+ if (widgetId === widget.id) {
40120
+ setChartState(createInitialChartState$1(datasetId));
40121
+ setAgentState(createInitialChartState$1(datasetId));
40122
+ setApiCallCount(0);
40123
+ setHasTimeoutError(false);
40124
+ }
40125
+ };
40126
+ window.addEventListener('triggerAgent', handleTriggerAgent);
40127
+ window.addEventListener('clearChartState', handleClearChartState);
40128
+ return () => {
40129
+ window.removeEventListener('triggerAgent', handleTriggerAgent);
40130
+ window.removeEventListener('clearChartState', handleClearChartState);
40131
+ };
40132
+ }, [widget.id, appendMessage, setChartState, startLoadingTimeout]);
40133
+ return (jsxRuntimeExports.jsxs("div", { className: cn("flex flex-col h-full"), children: [showHeader && (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between pb-2 border-b", children: jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.Bot, { className: "h-4 w-4" }), jsxRuntimeExports.jsx("h3", { className: "text-sm font-medium", children: widget.title })] }) })), jsxRuntimeExports.jsx("div", { className: "flex-1 h-full", children: (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) &&
40134
+ (!((_j = (_h = (_g = chartState.series_bar_chart_data) === null || _g === void 0 ? void 0 : _g.data) === null || _h === void 0 ? void 0 : _h.labels) === null || _j === void 0 ? void 0 : _j.length) || !((_m = (_l = (_k = chartState.series_bar_chart_data) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.series) === null || _m === void 0 ? void 0 : _m.length))
40135
+ ? (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full p-4", children: jsxRuntimeExports.jsx("div", { className: "text-center max-w-md", children: jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700", children: chartState.agent_message }) }) })) : (jsxRuntimeExports.jsx(SeriesBarChartComponent, { orientation: orientation, seriesBarChartState: chartState, styles: styles, appendMessage: appendMessage, content: content, query: (_o = widget.config) === null || _o === void 0 ? void 0 : _o.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout, hasWidgetData: !!(((_q = (_p = widget_data === null || widget_data === void 0 ? void 0 : widget_data.data) === null || _p === void 0 ? void 0 : _p.labels) === null || _q === void 0 ? void 0 : _q.length) && ((_s = (_r = widget_data === null || widget_data === void 0 ? void 0 : widget_data.data) === null || _r === void 0 ? void 0 : _r.series) === null || _s === void 0 ? void 0 : _s.length)) })) })] }));
40136
+ }
40137
+ function SeriesLineChartWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
40138
+ var _a, _b;
40139
+ const styles = getStyleValues$1((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
40140
+ const getRuntimeUrl = () => {
40141
+ var _a;
40142
+ const baseUrl = widgetBackendUrl || '';
40143
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
40144
+ return `${baseUrl}/api/copilot/${agentName}`;
40145
+ };
40146
+ return (jsxRuntimeExports.jsx(reactCore.CopilotKit, { runtimeUrl: getRuntimeUrl(), showDevConsole: false, agent: ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.agentName) || "widget_assistant", children: jsxRuntimeExports.jsx(CopilotKitSeriesBarChart, { widget: widget, showHeader: showHeader, styles: styles, onResetReady: onResetReady, widgetBackendUrl: widgetBackendUrl, datasetId: datasetId }) }));
40147
+ }
40148
+
40149
+ const CHART_REFRESH_TIMEOUT = 3000;
40150
+ const clearChat = async (widgetBackendUrl, widgetId) => {
40151
+ if (!widgetBackendUrl || !widgetId)
40152
+ return;
40153
+ console.log('clearChat called for widgetId:', widgetId);
40154
+ try {
40155
+ await fetch(`${widgetBackendUrl}/api/clear-chat`, {
40156
+ method: 'POST',
40157
+ headers: {
40158
+ 'Content-Type': 'application/json',
40159
+ },
40160
+ body: JSON.stringify({
40161
+ session_id: widgetId,
40162
+ delete_state: true
40163
+ }),
40164
+ });
40165
+ console.log('Dispatching clearChartState event from clearChat for widgetId:', widgetId);
40166
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
40167
+ }
40168
+ catch (error) {
40169
+ console.error('Failed to clear chat:', error);
40170
+ }
40171
+ };
40172
+ const createLoadingComponent = (message = "Loading table data...") => (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full", children: jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
40173
+ const createInitialChartState = (datasetId, dataGridState) => {
40174
+ return {
40175
+ matrix_grid_data: {
40176
+ title: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.title) || "",
40177
+ type: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.type) || "data_grid",
40178
+ grid_type: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.grid_type) || "",
40179
+ grouped: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.grouped) || false,
40180
+ data: {
40181
+ headers: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.headers) || [],
40182
+ units: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.units) || [],
40183
+ rows: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.rows) || [],
40184
+ row_count: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.row_count) || 0,
40185
+ column_count: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.column_count) || 0
40186
+ },
40187
+ metadata: {
40188
+ total_rows: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.metadata.total_rows) || 0,
40189
+ total_columns: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.metadata.total_columns) || 0,
40190
+ numeric_columns: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.metadata.numeric_columns) || []
40191
+ }
40192
+ },
40193
+ dataset_id: datasetId || "home_generation_dataset"
40194
+ };
40195
+ };
40196
+ const loadAgentState = async (widgetBackendUrl, threadId, agentName) => {
40197
+ try {
40198
+ const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
40199
+ method: 'POST',
40200
+ headers: {
40201
+ 'Content-Type': 'application/json',
40202
+ },
40203
+ body: JSON.stringify({
40204
+ "operationName": "loadAgentState",
40205
+ "query": "query loadAgentState($data: LoadAgentStateInput!) {\n loadAgentState(data: $data) {\n threadId\n threadExists\n state\n messages\n __typename\n }\n}",
40206
+ "variables": {
40207
+ "data": {
40208
+ "agentName": agentName,
40209
+ "threadId": threadId
40210
+ }
40211
+ }
40212
+ }),
40213
+ });
40214
+ if (!response.ok) {
40215
+ throw new Error(`HTTP error! status: ${response.status}`);
40216
+ }
40217
+ const result = await response.json();
40218
+ return result;
40219
+ }
40220
+ catch (error) {
40221
+ console.error('Failed to load agent state:', error);
40222
+ return null;
40223
+ }
40224
+ };
40225
+ const parseAndUpdateChartState = (apiResponse, setChartState) => {
40226
+ var _a, _b;
40227
+ try {
40228
+ if ((_b = (_a = apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.data) === null || _a === void 0 ? void 0 : _a.loadAgentState) === null || _b === void 0 ? void 0 : _b.state) {
40229
+ const stateString = apiResponse.data.loadAgentState.state;
40230
+ const parsedState = JSON.parse(stateString);
40231
+ if (parsedState.state) {
40232
+ const chartData = parsedState.state;
40233
+ setChartState((prevState) => {
40234
+ const newChartState = Object.assign({}, prevState);
40235
+ if (chartData.matrix_grid_data) {
40236
+ newChartState.matrix_grid_data = chartData.matrix_grid_data;
40237
+ }
40238
+ if (chartData.agent_message) {
40239
+ newChartState.agent_message = chartData.agent_message;
40240
+ }
40241
+ return newChartState;
40242
+ });
40243
+ }
40244
+ }
40245
+ }
40246
+ catch (error) {
40247
+ console.error('Failed to parse and update chart state:', error);
40248
+ }
40249
+ };
40250
+ const getStyleValues = (styles = {}) => {
40251
+ const borderRadiusMap = {
40252
+ none: "0px",
40253
+ rounded: "0.375rem",
40254
+ large: "0.5rem",
40255
+ "extra-large": "0.75rem",
40256
+ };
40257
+ const paddingMap = {
40258
+ small: "0.5rem",
40259
+ medium: "1rem",
40260
+ large: "1.5rem",
40261
+ "extra-large": "2rem",
40262
+ };
40263
+ const alignment = styles.alignment || "left";
40264
+ return {
40265
+ backgroundColor: styles.backgroundColor || "#ffffff",
40266
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
40267
+ padding: paddingMap[styles.padding || "medium"],
40268
+ color: styles.textColor || "#000000",
40269
+ fontSize: styles.fontSize || "14px",
40270
+ textAlign: alignment,
40271
+ };
40272
+ };
40273
+ function DataGridComponent({ dataGridState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content, hasWidgetData }) {
40274
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
40275
+ const hasCalledRef = React.useRef(false);
40276
+ const columns = ((_b = (_a = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.headers) || [];
40277
+ const rows = ((_d = (_c = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.rows) || [];
40278
+ const gridTitle = ((_e = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _e === void 0 ? void 0 : _e.title) || "";
40279
+ const units = ((_g = (_f = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.units) || [];
40280
+ const isEmpty = columns.length === 0 || rows.length === 0;
40281
+ const handleRefresh = async () => {
40282
+ if (query) {
40283
+ await clearChat(widgetBackendUrl, widgetId);
40284
+ console.log('Dispatching clearChartState event for widgetId:', widgetId);
40285
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
40286
+ appendMessage(new TextMessage({
40287
+ content: `${query} and render data in a data grid table`,
40288
+ role: Role.User,
40289
+ }));
40290
+ }
40291
+ };
40292
+ React.useEffect(() => {
40293
+ if (isEmpty && query && isFirstLoad && !(dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.agent_message) && !hasCalledRef.current) {
40294
+ hasCalledRef.current = true;
40295
+ handleRefresh();
40296
+ }
40297
+ }, [isEmpty, query, isFirstLoad, dataGridState]);
40298
+ React.useEffect(() => {
40299
+ console.log('DataGridComponent useEffect - isEmpty:', isEmpty, 'hasMessage:', !!(dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.agent_message), 'hasWidgetData:', hasWidgetData, 'isFirstLoad:', isFirstLoad);
40300
+ if (isEmpty && startLoadingTimeout && !(dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.agent_message)) {
40301
+ console.log('Starting loading timeout from DataGridComponent useEffect');
40302
+ startLoadingTimeout();
40303
+ }
40304
+ else if (!isEmpty && clearLoadingTimeout) {
40305
+ clearLoadingTimeout();
40306
+ }
40307
+ }, [isEmpty, startLoadingTimeout, clearLoadingTimeout, dataGridState]);
40308
+ if (isEmpty) {
40309
+ return createLoadingComponent();
40310
+ }
40311
+ const transformedData = {
40312
+ columns: columns,
40313
+ units: units,
40314
+ rows: rows,
40315
+ grouped: ((_h = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _h === void 0 ? void 0 : _h.grouped) || false,
40316
+ grouping: (_j = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _j === void 0 ? void 0 : _j.grouping
40317
+ };
40318
+ return (jsxRuntimeExports.jsx(DataGrid, { title: gridTitle, data: transformedData, className: "" }));
40319
+ }
40320
+ function CopilotKitDataGrid({ widget, showHeader, styles, onResetReady, widgetBackendUrl, datasetId, widgetData, }) {
40321
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
40322
+ const isFirstLoad = (_a = widget.config) === null || _a === void 0 ? void 0 : _a.isFirstLoad;
40323
+ const content = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.content;
40324
+ const widget_data = (_c = widget.widget_data) === null || _c === void 0 ? void 0 : _c.matrix_grid_data;
40325
+ console.log('widget_data===>', widget_data);
40326
+ const { threadId, setThreadId } = reactCore.useCopilotContext();
40327
+ const timeoutRef = React.useRef(null);
40328
+ const [apiCallCount, setApiCallCount] = React.useState(0);
40329
+ const [hasTimeoutError, setHasTimeoutError] = React.useState(false);
40330
+ React.useEffect(() => {
40331
+ setThreadId(widget.id);
40332
+ }, [widget.id, setThreadId]);
40333
+ const { state: agentState, setState: setAgentState } = reactCore.useCoAgent({
40334
+ name: (_d = widget.config) === null || _d === void 0 ? void 0 : _d.agentName,
40335
+ initialState: createInitialChartState(datasetId, widget_data),
40336
+ });
40337
+ const [chartState, setChartState] = React.useState(createInitialChartState(datasetId, widget_data));
40338
+ const handleLoadingTimeout = React.useCallback(async () => {
40339
+ var _a;
40340
+ if (!widgetBackendUrl || !widget.id || (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) || hasTimeoutError) {
40341
+ console.log('Skipping API call - conditions not met');
40342
+ return;
40343
+ }
40344
+ console.log('Loading timeout triggered for widget:', widget.id, 'API call count:', apiCallCount);
40345
+ if (apiCallCount >= 30) {
40346
+ console.log('API call limit reached for widget:', widget.id);
40347
+ setHasTimeoutError(true);
40348
+ setChartState(prevState => (Object.assign(Object.assign({}, prevState), { agent_message: "Timeout: Unable to load data after multiple attempts. Please try refreshing the widget." })));
40349
+ return;
40350
+ }
40351
+ setApiCallCount(prev => prev + 1);
40352
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
40353
+ console.log('Calling loadAgentState API for widget:', widget.id);
40354
+ const apiResponse = await loadAgentState(widgetBackendUrl, widget.id, agentName);
40355
+ console.log('API response received:', apiResponse);
40356
+ if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
40357
+ parseAndUpdateChartState(apiResponse, setChartState);
40358
+ }
40359
+ }, [widgetBackendUrl, widget.id, setChartState, (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName, chartState, apiCallCount, hasTimeoutError]);
40360
+ const startLoadingTimeout = React.useCallback(() => {
40361
+ if (timeoutRef.current) {
40362
+ clearTimeout(timeoutRef.current);
40363
+ }
40364
+ console.log('Scheduling next API call in 3 seconds');
40365
+ timeoutRef.current = setTimeout(() => {
40366
+ handleLoadingTimeout();
40367
+ }, CHART_REFRESH_TIMEOUT);
40368
+ }, [handleLoadingTimeout]);
40369
+ const clearLoadingTimeout = React.useCallback(() => {
40370
+ if (timeoutRef.current) {
40371
+ clearTimeout(timeoutRef.current);
40372
+ timeoutRef.current = null;
40373
+ }
40374
+ }, []);
40375
+ React.useEffect(() => {
40376
+ return () => {
40377
+ if (timeoutRef.current) {
40378
+ clearTimeout(timeoutRef.current);
40379
+ }
40380
+ };
40381
+ }, []);
40382
+ const { appendMessage, reset } = reactCore.useCopilotChat();
40383
+ React.useEffect(() => {
40384
+ if (onResetReady && reset && widget.id) {
40385
+ const wrappedReset = () => {
40386
+ reset();
40387
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
40388
+ };
40389
+ onResetReady(widget.id, wrappedReset);
40390
+ }
40391
+ }, [reset, widget.id, onResetReady]);
40392
+ React.useEffect(() => {
40393
+ const handleTriggerAgent = (event) => {
40394
+ const { widgetId, query, agentType: eventAgentType, datasetId } = event.detail;
40395
+ reset();
40396
+ if (widgetId === widget.id) {
40397
+ let messageContent = `${query} and render data in a data grid table`;
40398
+ console.log('triggering to datasetId==>', datasetId);
40399
+ setChartState(createInitialChartState(datasetId));
40400
+ setAgentState(createInitialChartState(datasetId));
40401
+ setApiCallCount(0);
40402
+ setHasTimeoutError(false);
40403
+ appendMessage(new TextMessage({
40404
+ content: messageContent,
40405
+ role: Role.User,
40406
+ }));
40407
+ // Start polling for chart data
40408
+ startLoadingTimeout();
40409
+ }
40410
+ };
40411
+ const handleClearChartState = (event) => {
40412
+ const { widgetId } = event.detail;
40413
+ if (widgetId === widget.id) {
40414
+ setChartState(createInitialChartState(datasetId));
40415
+ setAgentState(createInitialChartState(datasetId));
40416
+ setApiCallCount(0);
40417
+ setHasTimeoutError(false);
40418
+ }
40419
+ };
40420
+ window.addEventListener('triggerAgent', handleTriggerAgent);
40421
+ window.addEventListener('clearChartState', handleClearChartState);
40422
+ return () => {
40423
+ window.removeEventListener('triggerAgent', handleTriggerAgent);
40424
+ window.removeEventListener('clearChartState', handleClearChartState);
40425
+ };
40426
+ }, [widget.id, appendMessage, setChartState, startLoadingTimeout]);
40427
+ return (jsxRuntimeExports.jsxs("div", { className: cn("flex flex-col h-full"), children: [showHeader && (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between pb-2 border-b", children: jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [jsxRuntimeExports.jsx(lucideReact.Bot, { className: "h-4 w-4" }), jsxRuntimeExports.jsx("h3", { className: "text-sm font-medium", children: widget.title })] }) })), jsxRuntimeExports.jsx("div", { className: "flex-1 h-full", children: (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) &&
40428
+ (!((_h = (_g = (_f = chartState.matrix_grid_data) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.headers) === null || _h === void 0 ? void 0 : _h.length) || !((_l = (_k = (_j = chartState.matrix_grid_data) === null || _j === void 0 ? void 0 : _j.data) === null || _k === void 0 ? void 0 : _k.rows) === null || _l === void 0 ? void 0 : _l.length))
40429
+ ? (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full p-4", children: jsxRuntimeExports.jsx("div", { className: "text-center max-w-md", children: jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700", children: chartState.agent_message }) }) })) : (jsxRuntimeExports.jsx(DataGridComponent, { dataGridState: chartState, styles: styles, appendMessage: appendMessage, content: content, query: (_m = widget.config) === null || _m === void 0 ? void 0 : _m.query, isFirstLoad: isFirstLoad, widgetBackendUrl: widgetBackendUrl, widgetId: widget.id, startLoadingTimeout: startLoadingTimeout, clearLoadingTimeout: clearLoadingTimeout, hasWidgetData: !!(((_p = (_o = widget_data === null || widget_data === void 0 ? void 0 : widget_data.data) === null || _o === void 0 ? void 0 : _o.headers) === null || _p === void 0 ? void 0 : _p.length) && ((_r = (_q = widget_data === null || widget_data === void 0 ? void 0 : widget_data.data) === null || _q === void 0 ? void 0 : _q.rows) === null || _r === void 0 ? void 0 : _r.length)) })) })] }));
40430
+ }
40431
+ function DatagridWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
40432
+ var _a, _b;
40433
+ const styles = getStyleValues((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
40434
+ const getRuntimeUrl = () => {
40435
+ var _a;
40436
+ const baseUrl = widgetBackendUrl || '';
40437
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
40438
+ return `${baseUrl}/api/copilot/${agentName}`;
40439
+ };
40440
+ return (jsxRuntimeExports.jsx(reactCore.CopilotKit, { runtimeUrl: getRuntimeUrl(), showDevConsole: false, agent: ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.agentName) || "widget_assistant", children: jsxRuntimeExports.jsx(CopilotKitDataGrid, { widget: widget, showHeader: showHeader, styles: styles, onResetReady: onResetReady, widgetBackendUrl: widgetBackendUrl, datasetId: datasetId }) }));
40441
+ }
40442
+
40443
+ function WidgetRenderer({ widget, isTemplate = false, onConfigUpdate, widgetBackendUrl, onResetReady, widgetIds, datasetId, }) {
40444
+ const handleConfigUpdate = (config) => {
40445
+ if (onConfigUpdate) {
40446
+ onConfigUpdate(widget.id, config);
40447
+ }
40448
+ };
40449
+ getWidgetStyles(widget);
40450
+ const renderWidget = () => {
40451
+ switch (widget.type) {
40452
+ // Search-related widget cases removed
40453
+ // Available widgets
40454
+ case "header":
40455
+ return jsxRuntimeExports.jsx(HeaderWidget, { widget: widget, showHeader: false });
40456
+ case "footer":
40457
+ return jsxRuntimeExports.jsx(FooterWidget, { widget: widget, showHeader: false });
40458
+ case "text":
40459
+ return jsxRuntimeExports.jsx(TextWidget, { widget: widget, showHeader: false });
40460
+ case "spacer":
40461
+ return jsxRuntimeExports.jsx(SpacerWidget, { widget: widget, showHeader: false });
40462
+ case "divider":
40463
+ return jsxRuntimeExports.jsx(DividerWidget, { widget: widget, showHeader: false });
40464
+ case "facet":
40465
+ return (jsxRuntimeExports.jsx(FacetWidget, { widget: widget, showHeader: false, onConfigUpdate: handleConfigUpdate }));
40466
+ case "chatbot":
40467
+ return jsxRuntimeExports.jsx(ChatbotWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId });
40468
+ case "agent":
40469
+ return widget.config.agentType === "Pie Chart Agent" ? (jsxRuntimeExports.jsx(PieChartWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId })) : widget.config.agentType === "Series Bar Chart Agent" ? (jsxRuntimeExports.jsx(SeriesBarChartWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId })) : widget.config.agentType === "Series Line Chart Agent" ? (jsxRuntimeExports.jsx(SeriesLineChartWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId })) : widget.config.agentType === "Data Grid Agent" ? (jsxRuntimeExports.jsx(DatagridWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId })) : (jsxRuntimeExports.jsx(AgentWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId }));
39201
40470
  default:
39202
40471
  return (jsxRuntimeExports.jsxs("div", { className: "text-muted-foreground", children: ["Unknown widget type: ", widget.type] }));
39203
40472
  }