dp-widgets-framework 1.3.9 → 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 +1385 -110
  2. package/dist/index.js +1385 -110
  3. package/package.json +1 -1
package/dist/index.esm.js CHANGED
@@ -1993,7 +1993,7 @@ const borderRadiusMap$2 = {
1993
1993
  large: "0.5rem",
1994
1994
  "extra-large": "0.75rem",
1995
1995
  };
1996
- const getStyleValues$5 = (styles = {}) => {
1996
+ const getStyleValues$a = (styles = {}) => {
1997
1997
  return {
1998
1998
  backgroundColor: styles.backgroundColor || "transparent",
1999
1999
  borderRadius: borderRadiusMap$2[styles.borderRadius || "rounded"],
@@ -2006,7 +2006,7 @@ const getStyleValues$5 = (styles = {}) => {
2006
2006
  };
2007
2007
  function HeaderWidget({ widget }) {
2008
2008
  var _a, _b;
2009
- const styles = getStyleValues$5((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2009
+ const styles = getStyleValues$a((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2010
2010
  const content = ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
2011
2011
  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 }))] }) }));
2012
2012
  }
@@ -2017,7 +2017,7 @@ const borderRadiusMap$1 = {
2017
2017
  large: "0.5rem",
2018
2018
  "extra-large": "0.75rem",
2019
2019
  };
2020
- const getStyleValues$4 = (styles = {}) => {
2020
+ const getStyleValues$9 = (styles = {}) => {
2021
2021
  return {
2022
2022
  backgroundColor: styles.backgroundColor || "transparent",
2023
2023
  borderRadius: borderRadiusMap$1[styles.borderRadius || "rounded"],
@@ -2030,7 +2030,7 @@ const getStyleValues$4 = (styles = {}) => {
2030
2030
  };
2031
2031
  function FooterWidget({ widget }) {
2032
2032
  var _a, _b;
2033
- const styles = getStyleValues$4((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2033
+ const styles = getStyleValues$9((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2034
2034
  const content = ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
2035
2035
  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 }))] }) }));
2036
2036
  }
@@ -2041,7 +2041,7 @@ const borderRadiusMap = {
2041
2041
  large: "0.5rem",
2042
2042
  "extra-large": "0.75rem",
2043
2043
  };
2044
- const getStyleValues$3 = (styles = {}) => {
2044
+ const getStyleValues$8 = (styles = {}) => {
2045
2045
  const borderRadius = (styles.borderRadius || "rounded");
2046
2046
  return {
2047
2047
  backgroundColor: styles.backgroundColor || "transparent",
@@ -2056,12 +2056,12 @@ const getStyleValues$3 = (styles = {}) => {
2056
2056
  };
2057
2057
  function TextWidget({ widget }) {
2058
2058
  var _a, _b;
2059
- const styles = getStyleValues$3((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2059
+ const styles = getStyleValues$8((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2060
2060
  const content = ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
2061
2061
  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" } }) }));
2062
2062
  }
2063
2063
 
2064
- const getStyleValues$2 = (styles = {}) => {
2064
+ const getStyleValues$7 = (styles = {}) => {
2065
2065
  return {
2066
2066
  borderColor: styles.color || "#e5e7eb",
2067
2067
  borderStyle: styles.style || "solid",
@@ -2071,7 +2071,7 @@ const getStyleValues$2 = (styles = {}) => {
2071
2071
  };
2072
2072
  function DividerWidget({ widget }) {
2073
2073
  var _a, _b;
2074
- const styles = getStyleValues$2((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2074
+ const styles = getStyleValues$7((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
2075
2075
  const content = ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
2076
2076
  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: {
2077
2077
  borderColor: styles.borderColor,
@@ -17662,19 +17662,24 @@ function DataGrid({ title, data, className }) {
17662
17662
  }
17663
17663
  setExpandedGroups(newExpanded);
17664
17664
  };
17665
+ const formatWithCommas = (value) => {
17666
+ if (value == null || value === "")
17667
+ return "";
17668
+ let str = value.toString().trim();
17669
+ let num = Number(str);
17670
+ if (isNaN(num))
17671
+ return str;
17672
+ let [integer, decimal] = str.split(".");
17673
+ integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
17674
+ return decimal ? `${integer}.${decimal}` : integer;
17675
+ };
17665
17676
  const formatValueWithUnit = (value, columnIndex) => {
17666
17677
  if (value === null || value === undefined)
17667
17678
  return "—";
17668
17679
  const unit = units === null || units === void 0 ? void 0 : units[columnIndex];
17669
- console.log('value==>', value, unit);
17670
17680
  // Format the value with commas if it's a number or numeric string
17671
17681
  let valueStr;
17672
- if (typeof value === 'number') {
17673
- valueStr = value.toLocaleString();
17674
- }
17675
- else {
17676
- valueStr = String(value);
17677
- }
17682
+ valueStr = formatWithCommas(value);
17678
17683
  // If no unit or unit length > 3, return value only
17679
17684
  if (!unit || unit.length > 3) {
17680
17685
  return valueStr;
@@ -38404,10 +38409,10 @@ function SummaryWidget({ title, data, metadata, className }) {
38404
38409
  }, 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 }) }) })] }));
38405
38410
  }
38406
38411
 
38407
- const CHART_REFRESH_TIMEOUT = 3000;
38408
- const DEFAULT_COLORS = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
38412
+ const CHART_REFRESH_TIMEOUT$4 = 3000;
38413
+ const DEFAULT_COLORS$3 = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
38409
38414
  const LINE_COLORS = ["#243D84", "#69238B", "#4A959F", "#D0A677", "#B31E47", "#396431"];
38410
- const clearChat = async (widgetBackendUrl, widgetId) => {
38415
+ const clearChat$4 = async (widgetBackendUrl, widgetId) => {
38411
38416
  if (!widgetBackendUrl || !widgetId)
38412
38417
  return;
38413
38418
  console.log('clearChat called for widgetId:', widgetId);
@@ -38429,8 +38434,8 @@ const clearChat = async (widgetBackendUrl, widgetId) => {
38429
38434
  console.error('Failed to clear chat:', error);
38430
38435
  }
38431
38436
  };
38432
- 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(RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
38433
- const createInitialChartState = (agentType, widgetIds, datasetId) => {
38437
+ 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(RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
38438
+ const createInitialChartState$4 = (agentType, widgetIds, datasetId) => {
38434
38439
  const baseState = { dataset_id: datasetId || "home_generation_dataset" };
38435
38440
  switch (agentType) {
38436
38441
  case "Pie Chart Agent":
@@ -38457,6 +38462,8 @@ const createInitialChartState = (agentType, widgetIds, datasetId) => {
38457
38462
  title: "",
38458
38463
  type: "series_bar",
38459
38464
  chart_type: "financial",
38465
+ x_axis_title: "",
38466
+ y_axis_title: "",
38460
38467
  orientation: "vertical",
38461
38468
  units: "",
38462
38469
  data: { labels: [], series: [], total: 0, average: 0 },
@@ -38485,7 +38492,7 @@ const createInitialChartState = (agentType, widgetIds, datasetId) => {
38485
38492
  return Object.assign({ widget_ids: widgetIds }, baseState);
38486
38493
  }
38487
38494
  };
38488
- const loadAgentState = async (widgetBackendUrl, threadId, agentName) => {
38495
+ const loadAgentState$4 = async (widgetBackendUrl, threadId, agentName) => {
38489
38496
  try {
38490
38497
  const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
38491
38498
  method: 'POST',
@@ -38514,7 +38521,7 @@ const loadAgentState = async (widgetBackendUrl, threadId, agentName) => {
38514
38521
  return null;
38515
38522
  }
38516
38523
  };
38517
- const parseAndUpdateChartState = (apiResponse, setChartState) => {
38524
+ const parseAndUpdateChartState$4 = (apiResponse, setChartState) => {
38518
38525
  var _a, _b;
38519
38526
  try {
38520
38527
  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) {
@@ -38557,7 +38564,7 @@ const parseAndUpdateChartState = (apiResponse, setChartState) => {
38557
38564
  console.error('Failed to parse and update chart state:', error);
38558
38565
  }
38559
38566
  };
38560
- const getStyleValues$1 = (styles = {}) => {
38567
+ const getStyleValues$6 = (styles = {}) => {
38561
38568
  const borderRadiusMap = {
38562
38569
  none: "0px",
38563
38570
  rounded: "0.375rem",
@@ -38591,7 +38598,7 @@ function BarChartComponent({ orientation, barChartState, styles, appendMessage,
38591
38598
  const isEmpty = labels.length === 0 || values.length === 0;
38592
38599
  const handleRefresh = async () => {
38593
38600
  if (query && widgetBackendUrl && widgetId) {
38594
- await clearChat(widgetBackendUrl, widgetId);
38601
+ await clearChat$4(widgetBackendUrl, widgetId);
38595
38602
  appendMessage(new TextMessage({
38596
38603
  content: `${query} and render data on a bar chart`,
38597
38604
  role: Role.User,
@@ -38615,10 +38622,10 @@ function BarChartComponent({ orientation, barChartState, styles, appendMessage,
38615
38622
  }
38616
38623
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38617
38624
  const finalColors = useMemo(() => {
38618
- return shuffleColors(DEFAULT_COLORS, labels === null || labels === void 0 ? void 0 : labels.length);
38625
+ return shuffleColors(DEFAULT_COLORS$3, labels === null || labels === void 0 ? void 0 : labels.length);
38619
38626
  }, [labels.length]);
38620
38627
  if (isEmpty) {
38621
- return createLoadingComponent();
38628
+ return createLoadingComponent$4();
38622
38629
  }
38623
38630
  const transformedData = {
38624
38631
  labels: labels,
@@ -38632,7 +38639,7 @@ function BarChartComponent({ orientation, barChartState, styles, appendMessage,
38632
38639
  };
38633
38640
  return (jsxRuntimeExports.jsx(BarChart, { orientation: orientation, title: chartTitle, data: transformedData, units: units, content: content }));
38634
38641
  }
38635
- function SeriesBarChartComponent({ orientation, seriesBarChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content }) {
38642
+ function SeriesBarChartComponent$2({ orientation, seriesBarChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content }) {
38636
38643
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
38637
38644
  const hasCalledRef = useRef(false);
38638
38645
  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) || [];
@@ -38644,7 +38651,7 @@ function SeriesBarChartComponent({ orientation, seriesBarChartState, styles, app
38644
38651
  const isEmpty = labels.length === 0 || series.length === 0;
38645
38652
  const handleRefresh = async () => {
38646
38653
  if (query) {
38647
- await clearChat(widgetBackendUrl, widgetId);
38654
+ await clearChat$4(widgetBackendUrl, widgetId);
38648
38655
  // Send trigger event to clear chart state
38649
38656
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38650
38657
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38670,10 +38677,10 @@ function SeriesBarChartComponent({ orientation, seriesBarChartState, styles, app
38670
38677
  }
38671
38678
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38672
38679
  const finalColors = useMemo(() => {
38673
- return shuffleColors(DEFAULT_COLORS, series === null || series === void 0 ? void 0 : series.length);
38680
+ return shuffleColors(DEFAULT_COLORS$3, series === null || series === void 0 ? void 0 : series.length);
38674
38681
  }, [series.length]);
38675
38682
  if (isEmpty) {
38676
- return createLoadingComponent();
38683
+ return createLoadingComponent$4();
38677
38684
  }
38678
38685
  const transformedData = {
38679
38686
  labels: labels,
@@ -38697,7 +38704,7 @@ function SeriesLineChartComponent({ orientation, seriesLineChartState, styles, a
38697
38704
  const isEmpty = labels.length === 0 || series.length === 0;
38698
38705
  const handleRefresh = async () => {
38699
38706
  if (query) {
38700
- await clearChat(widgetBackendUrl, widgetId);
38707
+ await clearChat$4(widgetBackendUrl, widgetId);
38701
38708
  // Send trigger event to clear chart state
38702
38709
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38703
38710
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38723,10 +38730,10 @@ function SeriesLineChartComponent({ orientation, seriesLineChartState, styles, a
38723
38730
  }
38724
38731
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38725
38732
  const finalColors = useMemo(() => {
38726
- return shuffleColors([...LINE_COLORS, ...DEFAULT_COLORS], series === null || series === void 0 ? void 0 : series.length);
38733
+ return shuffleColors([...LINE_COLORS, ...DEFAULT_COLORS$3], series === null || series === void 0 ? void 0 : series.length);
38727
38734
  }, [series.length]);
38728
38735
  if (isEmpty) {
38729
- return createLoadingComponent();
38736
+ return createLoadingComponent$4();
38730
38737
  }
38731
38738
  const transformedData = {
38732
38739
  labels: labels,
@@ -38745,7 +38752,7 @@ function SeriesLineChartComponent({ orientation, seriesLineChartState, styles, a
38745
38752
  };
38746
38753
  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 }));
38747
38754
  }
38748
- function PieChartComponent({ pieChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content }) {
38755
+ function PieChartComponent$1({ pieChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content }) {
38749
38756
  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;
38750
38757
  const hasCalledRef = useRef(false);
38751
38758
  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) || [];
@@ -38756,7 +38763,7 @@ function PieChartComponent({ pieChartState, styles, appendMessage, query, isFirs
38756
38763
  const isEmpty = labels.length === 0 || values.length === 0;
38757
38764
  const handleRefresh = async () => {
38758
38765
  if (query) {
38759
- await clearChat(widgetBackendUrl, widgetId);
38766
+ await clearChat$4(widgetBackendUrl, widgetId);
38760
38767
  // Send trigger event to clear chart state
38761
38768
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38762
38769
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38782,10 +38789,10 @@ function PieChartComponent({ pieChartState, styles, appendMessage, query, isFirs
38782
38789
  }
38783
38790
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38784
38791
  const backgroundColors = useMemo(() => {
38785
- return shuffleColors(DEFAULT_COLORS, labels.length);
38792
+ return shuffleColors(DEFAULT_COLORS$3, labels.length);
38786
38793
  }, [labels.length]);
38787
38794
  if (isEmpty) {
38788
- return createLoadingComponent();
38795
+ return createLoadingComponent$4();
38789
38796
  }
38790
38797
  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]);
38791
38798
  const transformedData = {
@@ -38812,7 +38819,7 @@ function LineChartComponent({ lineChartState, styles, appendMessage, query, isFi
38812
38819
  const isEmpty = labels.length === 0 || values.length === 0;
38813
38820
  const handleRefresh = async () => {
38814
38821
  if (query && widgetBackendUrl && widgetId) {
38815
- await clearChat(widgetBackendUrl, widgetId);
38822
+ await clearChat$4(widgetBackendUrl, widgetId);
38816
38823
  appendMessage(new TextMessage({
38817
38824
  content: `${query} and render data on a bar chart`,
38818
38825
  role: Role.User,
@@ -38838,7 +38845,7 @@ function LineChartComponent({ lineChartState, styles, appendMessage, query, isFi
38838
38845
  return LINE_COLORS[Math.floor(Math.random() * LINE_COLORS.length)];
38839
38846
  }, [labels.length]);
38840
38847
  if (isEmpty) {
38841
- return createLoadingComponent();
38848
+ return createLoadingComponent$4();
38842
38849
  }
38843
38850
  const transformedData = {
38844
38851
  labels: labels,
@@ -38858,7 +38865,7 @@ function LineChartComponent({ lineChartState, styles, appendMessage, query, isFi
38858
38865
  };
38859
38866
  return (jsxRuntimeExports.jsx(LineChart, { title: chartTitle, data: transformedData, units: units, content: content }));
38860
38867
  }
38861
- function DataGridComponent({ dataGridState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout }) {
38868
+ function DataGridComponent$1({ dataGridState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout }) {
38862
38869
  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;
38863
38870
  const hasCalledRef = useRef(false);
38864
38871
  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) || [];
@@ -38868,7 +38875,7 @@ function DataGridComponent({ dataGridState, styles, appendMessage, query, isFirs
38868
38875
  const isEmpty = columns.length === 0 || rows.length === 0;
38869
38876
  const handleRefresh = async () => {
38870
38877
  if (query) {
38871
- await clearChat(widgetBackendUrl, widgetId);
38878
+ await clearChat$4(widgetBackendUrl, widgetId);
38872
38879
  // Send trigger event to clear chart state
38873
38880
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38874
38881
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38894,7 +38901,7 @@ function DataGridComponent({ dataGridState, styles, appendMessage, query, isFirs
38894
38901
  }
38895
38902
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38896
38903
  if (isEmpty) {
38897
- return createLoadingComponent("Loading table data...");
38904
+ return createLoadingComponent$4("Loading table data...");
38898
38905
  }
38899
38906
  const transformedData = {
38900
38907
  columns: columns,
@@ -38915,7 +38922,7 @@ function SummaryComponent({ summaryState, styles, appendMessage, query, isFirstL
38915
38922
  const isEmpty = !content || content.trim() === "";
38916
38923
  const handleRefresh = async () => {
38917
38924
  if (query) {
38918
- await clearChat(widgetBackendUrl, widgetId);
38925
+ await clearChat$4(widgetBackendUrl, widgetId);
38919
38926
  // Send trigger event to clear chart state
38920
38927
  console.log('Dispatching clearChartState event for widgetId:', widgetId);
38921
38928
  window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
@@ -38928,7 +38935,7 @@ function SummaryComponent({ summaryState, styles, appendMessage, query, isFirstL
38928
38935
  useEffect(() => {
38929
38936
  if (isEmpty && query && isFirstLoad && !(summaryState === null || summaryState === void 0 ? void 0 : summaryState.agent_message) && !hasCalledRef.current) {
38930
38937
  hasCalledRef.current = true;
38931
- setChartState((prevState) => (Object.assign(Object.assign({}, prevState), { widget_ids: widget_ids })));
38938
+ setChartState(Object.assign(Object.assign({}, summaryState), { widget_ids: widget_ids }));
38932
38939
  setTimeout(() => {
38933
38940
  handleRefresh();
38934
38941
  }, 500);
@@ -38944,12 +38951,12 @@ function SummaryComponent({ summaryState, styles, appendMessage, query, isFirstL
38944
38951
  }
38945
38952
  }, [isEmpty, startLoadingTimeout, clearLoadingTimeout]);
38946
38953
  if (isEmpty) {
38947
- return createLoadingComponent("Loading summary...");
38954
+ return createLoadingComponent$4("Loading summary...");
38948
38955
  }
38949
38956
  return (jsxRuntimeExports.jsx(SummaryWidget, { title: title, data: data, metadata: metadata, className: "" }));
38950
38957
  }
38951
- function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds, widgetBackendUrl, datasetId }) {
38952
- 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;
38958
+ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds, widgetBackendUrl, datasetId, widgetData, }) {
38959
+ 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;
38953
38960
  const agentType = (_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentType;
38954
38961
  const orientation = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.orientation;
38955
38962
  const isFirstLoad = (_c = widget.config) === null || _c === void 0 ? void 0 : _c.isFirstLoad;
@@ -38964,7 +38971,7 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
38964
38971
  }, [widget.id, setThreadId]);
38965
38972
  const { state: chartState, setState: setChartState } = useCoAgent({
38966
38973
  name: (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName,
38967
- initialState: createInitialChartState(agentType || '', widgetIds, datasetId),
38974
+ initialState: createInitialChartState$4(agentType || '', widgetIds, datasetId),
38968
38975
  });
38969
38976
  // Function to handle timeout and call loadAgentState API
38970
38977
  const handleLoadingTimeout = useCallback(async () => {
@@ -38983,9 +38990,9 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
38983
38990
  // Increment the API call counter
38984
38991
  setApiCallCount(prev => prev + 1);
38985
38992
  const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
38986
- const apiResponse = await loadAgentState(widgetBackendUrl, widget.id, agentName);
38993
+ const apiResponse = await loadAgentState$4(widgetBackendUrl, widget.id, agentName);
38987
38994
  if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
38988
- parseAndUpdateChartState(apiResponse, setChartState);
38995
+ parseAndUpdateChartState$4(apiResponse, setChartState);
38989
38996
  }
38990
38997
  }, [widgetBackendUrl, widget.id, isTimeoutTriggered, setChartState, (_f = widget.config) === null || _f === void 0 ? void 0 : _f.agentName, chartState, apiCallCount, hasTimeoutError]);
38991
38998
  // Function to start timeout
@@ -38996,7 +39003,7 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
38996
39003
  setIsTimeoutTriggered(false);
38997
39004
  timeoutRef.current = setTimeout(() => {
38998
39005
  handleLoadingTimeout();
38999
- }, CHART_REFRESH_TIMEOUT);
39006
+ }, CHART_REFRESH_TIMEOUT$4);
39000
39007
  }, [handleLoadingTimeout]);
39001
39008
  // Function to clear timeout
39002
39009
  const clearLoadingTimeout = useCallback(() => {
@@ -39005,29 +39012,6 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39005
39012
  timeoutRef.current = null;
39006
39013
  }
39007
39014
  }, []);
39008
- // Function to clear chat and reset chart state
39009
- useCallback(async (widgetId) => {
39010
- if (!widgetBackendUrl)
39011
- return;
39012
- try {
39013
- await fetch(`${widgetBackendUrl}/api/clear-chat`, {
39014
- method: 'POST',
39015
- headers: {
39016
- 'Content-Type': 'application/json',
39017
- },
39018
- body: JSON.stringify({
39019
- session_id: widgetId,
39020
- delete_state: true
39021
- }),
39022
- });
39023
- setChartState(createInitialChartState(agentType || '', widgetIds, datasetId));
39024
- setApiCallCount(0);
39025
- setHasTimeoutError(false);
39026
- }
39027
- catch (error) {
39028
- console.error('Failed to clear chat and state:', error);
39029
- }
39030
- }, [widgetBackendUrl, setChartState, agentType, widgetIds]);
39031
39015
  // Clean up timeout on unmount
39032
39016
  useEffect(() => {
39033
39017
  return () => {
@@ -39076,7 +39060,7 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39076
39060
  messageContent = `${query} and render the data on a summary widget`;
39077
39061
  }
39078
39062
  console.log('triggering to datasetId==>', datasetId);
39079
- setChartState(createInitialChartState(agentType || '', widgetIds, datasetId));
39063
+ setChartState(createInitialChartState$4(agentType || '', widgetIds, datasetId));
39080
39064
  appendMessage(new TextMessage({
39081
39065
  content: messageContent,
39082
39066
  role: Role.User,
@@ -39086,7 +39070,7 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39086
39070
  const handleClearChartState = (event) => {
39087
39071
  const { widgetId } = event.detail;
39088
39072
  if (widgetId === widget.id) {
39089
- setChartState(createInitialChartState(agentType || '', widgetIds, datasetId));
39073
+ setChartState(createInitialChartState$4(agentType || '', widgetIds, datasetId));
39090
39074
  setApiCallCount(0);
39091
39075
  setHasTimeoutError(false);
39092
39076
  }
@@ -39106,16 +39090,11 @@ function CopilotKitAgent({ widget, showHeader, styles, onResetReady, widgetIds,
39106
39090
  (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))) ||
39107
39091
  (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))) ||
39108
39092
  (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))) ||
39109
- (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(CopilotChat, { className: "h-full text-xs [&_.copilot-chat-message]:text-xs [&_.copilot-chat-input]:text-xs", labels: {
39110
- title: ((_30 = widget.config) === null || _30 === void 0 ? void 0 : _30.copilotTitle) || widget.title,
39111
- 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?"
39112
- }, onSubmitMessage: () => {
39113
- setChartState(prevState => (Object.assign(Object.assign({}, prevState), { widget_ids: widgetIds, dataset_id: datasetId })));
39114
- } })) })] }));
39093
+ (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 })] }));
39115
39094
  }
39116
- function AgentWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, }) {
39095
+ function AgentWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
39117
39096
  var _a, _b;
39118
- const styles = getStyleValues$1((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39097
+ const styles = getStyleValues$6((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39119
39098
  // Construct the runtime URL using the configurable backend URL
39120
39099
  const getRuntimeUrl = () => {
39121
39100
  var _a;
@@ -39126,7 +39105,7 @@ function AgentWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady
39126
39105
  return (jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: jsxRuntimeExports.jsx(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 }) }) }));
39127
39106
  }
39128
39107
 
39129
- const getStyleValues = (styles = {}) => {
39108
+ const getStyleValues$5 = (styles = {}) => {
39130
39109
  (styles.borderRadius || "rounded");
39131
39110
  return {
39132
39111
  // backgroundColor: styles.backgroundColor || "10px",
@@ -39134,37 +39113,1333 @@ const getStyleValues = (styles = {}) => {
39134
39113
  };
39135
39114
  function SpacerWidget({ widget }) {
39136
39115
  var _a, _b;
39137
- const styles = getStyleValues((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39116
+ const styles = getStyleValues$5((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39138
39117
  ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.content) || {};
39139
39118
  return (jsxRuntimeExports.jsx("div", { className: "w-full", style: styles }));
39140
39119
  }
39141
39120
 
39142
- function WidgetRenderer({ widget, isTemplate = false, onConfigUpdate, widgetBackendUrl, onResetReady, widgetIds, datasetId, }) {
39143
- const handleConfigUpdate = (config) => {
39144
- if (onConfigUpdate) {
39145
- onConfigUpdate(widget.id, config);
39121
+ const getStyleValues$4 = (styles = {}) => {
39122
+ const borderRadiusMap = {
39123
+ none: "0px",
39124
+ rounded: "0.375rem",
39125
+ large: "0.5rem",
39126
+ "extra-large": "0.75rem",
39127
+ };
39128
+ const paddingMap = {
39129
+ small: "0.5rem",
39130
+ medium: "1rem",
39131
+ large: "1.5rem",
39132
+ "extra-large": "2rem",
39133
+ };
39134
+ const alignment = styles.alignment || "left";
39135
+ return {
39136
+ backgroundColor: styles.backgroundColor || "#ffffff",
39137
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
39138
+ padding: paddingMap[styles.padding || "medium"],
39139
+ color: styles.textColor || "#000000",
39140
+ fontSize: styles.fontSize || "14px",
39141
+ textAlign: alignment,
39142
+ };
39143
+ };
39144
+ function CopilotKitChatbot({ widget, showHeader, styles, onResetReady, widgetIds, datasetId, }) {
39145
+ var _a, _b, _c, _d;
39146
+ const { threadId, setThreadId } = useCopilotContext();
39147
+ useEffect(() => {
39148
+ setThreadId(widget.id);
39149
+ }, [widget.id, setThreadId]);
39150
+ const { state: chatbotState, setState: setChatbotState } = useCoAgent({
39151
+ name: ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "widget_assistant",
39152
+ initialState: {
39153
+ widget_ids: widgetIds,
39154
+ dataset_id: datasetId
39155
+ },
39156
+ });
39157
+ const { reset } = useCopilotChat();
39158
+ // Register the reset function with the parent component
39159
+ useEffect(() => {
39160
+ if (onResetReady && reset && widget.id) {
39161
+ console.log('on reset ready=>');
39162
+ const wrappedReset = () => {
39163
+ reset();
39164
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
39165
+ };
39166
+ onResetReady(widget.id, wrappedReset);
39146
39167
  }
39168
+ }, [reset, widget.id, onResetReady]);
39169
+ // Listen for clearChartState events for this widget
39170
+ useEffect(() => {
39171
+ const handleClearChartState = (event) => {
39172
+ const { widgetId } = event.detail;
39173
+ if (widgetId === widget.id) {
39174
+ setChatbotState({
39175
+ widget_ids: widgetIds,
39176
+ dataset_id: datasetId
39177
+ });
39178
+ }
39179
+ };
39180
+ window.addEventListener('clearChartState', handleClearChartState);
39181
+ return () => {
39182
+ window.removeEventListener('clearChartState', handleClearChartState);
39183
+ };
39184
+ }, [widget.id, widgetIds, datasetId, setChatbotState]);
39185
+ 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(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(CopilotChat, { className: "h-full text-xs [&_.copilot-chat-message]:text-xs [&_.copilot-chat-input]:text-xs", labels: {
39186
+ title: ((_b = widget.config) === null || _b === void 0 ? void 0 : _b.copilotTitle) || widget.title,
39187
+ 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?"
39188
+ }, onSubmitMessage: () => {
39189
+ setChatbotState(prevState => (Object.assign(Object.assign({}, prevState), { widget_ids: widgetIds, dataset_id: datasetId })));
39190
+ } }) })] }));
39191
+ }
39192
+ function ChatbotWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, }) {
39193
+ var _a, _b;
39194
+ const styles = getStyleValues$4((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39195
+ // Construct the runtime URL using the configurable backend URL
39196
+ const getRuntimeUrl = () => {
39197
+ var _a;
39198
+ const baseUrl = widgetBackendUrl || '';
39199
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
39200
+ return `${baseUrl}/api/copilot/${agentName}`;
39147
39201
  };
39148
- getWidgetStyles(widget);
39149
- const renderWidget = () => {
39150
- switch (widget.type) {
39151
- // Search-related widget cases removed
39152
- // Available widgets
39153
- case "header":
39154
- return jsxRuntimeExports.jsx(HeaderWidget, { widget: widget, showHeader: false });
39155
- case "footer":
39156
- return jsxRuntimeExports.jsx(FooterWidget, { widget: widget, showHeader: false });
39157
- case "text":
39158
- return jsxRuntimeExports.jsx(TextWidget, { widget: widget, showHeader: false });
39159
- case "spacer":
39160
- return jsxRuntimeExports.jsx(SpacerWidget, { widget: widget, showHeader: false });
39161
- case "divider":
39162
- return jsxRuntimeExports.jsx(DividerWidget, { widget: widget, showHeader: false });
39163
- case "facet":
39164
- return (jsxRuntimeExports.jsx(FacetWidget, { widget: widget, showHeader: false, onConfigUpdate: handleConfigUpdate }));
39165
- case "agent":
39166
- case "chatbot":
39167
- return jsxRuntimeExports.jsx(AgentWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId });
39202
+ return (jsxRuntimeExports.jsx(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 }) }));
39203
+ }
39204
+
39205
+ const CHART_REFRESH_TIMEOUT$3 = 3000;
39206
+ const DEFAULT_COLORS$2 = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
39207
+ const clearChat$3 = async (widgetBackendUrl, widgetId) => {
39208
+ if (!widgetBackendUrl || !widgetId)
39209
+ return;
39210
+ console.log('clearChat called for widgetId:', widgetId);
39211
+ try {
39212
+ await fetch(`${widgetBackendUrl}/api/clear-chat`, {
39213
+ method: 'POST',
39214
+ headers: {
39215
+ 'Content-Type': 'application/json',
39216
+ },
39217
+ body: JSON.stringify({
39218
+ session_id: widgetId,
39219
+ delete_state: true
39220
+ }),
39221
+ });
39222
+ console.log('Dispatching clearChartState event from clearChat for widgetId:', widgetId);
39223
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39224
+ }
39225
+ catch (error) {
39226
+ console.error('Failed to clear chat:', error);
39227
+ }
39228
+ };
39229
+ 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(RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
39230
+ const createInitialChartState$3 = (datasetId, pieChartState) => {
39231
+ return {
39232
+ pie_chart_data: {
39233
+ title: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.title) || "",
39234
+ type: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.type) || "pie",
39235
+ chart_type: (pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.chart_type) || "financial",
39236
+ 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 },
39237
+ 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 }
39238
+ },
39239
+ dataset_id: datasetId || "home_generation_dataset"
39240
+ };
39241
+ };
39242
+ const loadAgentState$3 = async (widgetBackendUrl, threadId, agentName) => {
39243
+ try {
39244
+ const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
39245
+ method: 'POST',
39246
+ headers: {
39247
+ 'Content-Type': 'application/json',
39248
+ },
39249
+ body: JSON.stringify({
39250
+ "operationName": "loadAgentState",
39251
+ "query": "query loadAgentState($data: LoadAgentStateInput!) {\n loadAgentState(data: $data) {\n threadId\n threadExists\n state\n messages\n __typename\n }\n}",
39252
+ "variables": {
39253
+ "data": {
39254
+ "agentName": agentName,
39255
+ "threadId": threadId
39256
+ }
39257
+ }
39258
+ }),
39259
+ });
39260
+ if (!response.ok) {
39261
+ throw new Error(`HTTP error! status: ${response.status}`);
39262
+ }
39263
+ const result = await response.json();
39264
+ return result;
39265
+ }
39266
+ catch (error) {
39267
+ console.error('Failed to load agent state:', error);
39268
+ return null;
39269
+ }
39270
+ };
39271
+ const parseAndUpdateChartState$3 = (apiResponse, setChartState) => {
39272
+ var _a, _b;
39273
+ try {
39274
+ 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) {
39275
+ const stateString = apiResponse.data.loadAgentState.state;
39276
+ const parsedState = JSON.parse(stateString);
39277
+ if (parsedState.state) {
39278
+ const chartData = parsedState.state;
39279
+ setChartState((prevState) => {
39280
+ const newChartState = Object.assign({}, prevState);
39281
+ if (chartData.pie_chart_data) {
39282
+ newChartState.pie_chart_data = chartData.pie_chart_data;
39283
+ }
39284
+ if (chartData.agent_message) {
39285
+ newChartState.agent_message = chartData.agent_message;
39286
+ }
39287
+ return newChartState;
39288
+ });
39289
+ }
39290
+ }
39291
+ }
39292
+ catch (error) {
39293
+ console.error('Failed to parse and update chart state:', error);
39294
+ }
39295
+ };
39296
+ const getStyleValues$3 = (styles = {}) => {
39297
+ const borderRadiusMap = {
39298
+ none: "0px",
39299
+ rounded: "0.375rem",
39300
+ large: "0.5rem",
39301
+ "extra-large": "0.75rem",
39302
+ };
39303
+ const paddingMap = {
39304
+ small: "0.5rem",
39305
+ medium: "1rem",
39306
+ large: "1.5rem",
39307
+ "extra-large": "2rem",
39308
+ };
39309
+ const alignment = styles.alignment || "left";
39310
+ return {
39311
+ backgroundColor: styles.backgroundColor || "#ffffff",
39312
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
39313
+ padding: paddingMap[styles.padding || "medium"],
39314
+ color: styles.textColor || "#000000",
39315
+ fontSize: styles.fontSize || "14px",
39316
+ textAlign: alignment,
39317
+ };
39318
+ };
39319
+ function PieChartComponent({ pieChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content, hasWidgetData }) {
39320
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
39321
+ const hasCalledRef = useRef(false);
39322
+ 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) || [];
39323
+ 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) || [];
39324
+ ((_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) || [];
39325
+ const chartTitle = ((_g = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _g === void 0 ? void 0 : _g.title) || "";
39326
+ const units = ((_h = pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.pie_chart_data) === null || _h === void 0 ? void 0 : _h.units) || "";
39327
+ const isEmpty = labels.length === 0 || values.length === 0;
39328
+ const handleRefresh = async () => {
39329
+ if (query) {
39330
+ await clearChat$3(widgetBackendUrl, widgetId);
39331
+ console.log('Dispatching clearChartState event for widgetId:', widgetId);
39332
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39333
+ appendMessage(new TextMessage({
39334
+ content: `${query} and render data on pie chart`,
39335
+ role: Role.User,
39336
+ }));
39337
+ }
39338
+ };
39339
+ useEffect(() => {
39340
+ if (isEmpty && query && isFirstLoad && !(pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.agent_message) && !hasCalledRef.current) {
39341
+ hasCalledRef.current = true;
39342
+ handleRefresh();
39343
+ }
39344
+ }, [isEmpty, query, isFirstLoad, pieChartState]);
39345
+ useEffect(() => {
39346
+ console.log('PieChartComponent useEffect - isEmpty:', isEmpty, 'hasMessage:', !!(pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.agent_message), 'hasWidgetData:', hasWidgetData, 'isFirstLoad:', isFirstLoad);
39347
+ if (isEmpty && startLoadingTimeout && !(pieChartState === null || pieChartState === void 0 ? void 0 : pieChartState.agent_message)) {
39348
+ console.log('Starting loading timeout from PieChartComponent useEffect');
39349
+ startLoadingTimeout();
39350
+ }
39351
+ else if (!isEmpty && clearLoadingTimeout) {
39352
+ clearLoadingTimeout();
39353
+ }
39354
+ }, [isEmpty, startLoadingTimeout, clearLoadingTimeout, pieChartState]);
39355
+ const backgroundColors = useMemo(() => {
39356
+ return shuffleColors(DEFAULT_COLORS$2, labels.length);
39357
+ }, [labels.length]);
39358
+ if (isEmpty) {
39359
+ return createLoadingComponent$3();
39360
+ }
39361
+ 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]);
39362
+ const transformedData = {
39363
+ labels: labels,
39364
+ datasets: [
39365
+ {
39366
+ label: chartTitle || "Data",
39367
+ data: values,
39368
+ backgroundColor: colors,
39369
+ borderWidth: 0,
39370
+ },
39371
+ ],
39372
+ };
39373
+ return (jsxRuntimeExports.jsx(PieChart, { title: chartTitle, data: transformedData, units: units, content: content }));
39374
+ }
39375
+ function CopilotKitPieChart({ widget, showHeader, styles, onResetReady, widgetBackendUrl, datasetId, widgetData, }) {
39376
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
39377
+ const isFirstLoad = (_a = widget.config) === null || _a === void 0 ? void 0 : _a.isFirstLoad;
39378
+ const content = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.content;
39379
+ const widget_data = (_c = widget.widget_data) === null || _c === void 0 ? void 0 : _c.pie_chart_data;
39380
+ console.log('widget_data===>', widget_data);
39381
+ const { threadId, setThreadId } = useCopilotContext();
39382
+ const timeoutRef = useRef(null);
39383
+ const [apiCallCount, setApiCallCount] = useState(0);
39384
+ const [hasTimeoutError, setHasTimeoutError] = useState(false);
39385
+ useEffect(() => {
39386
+ setThreadId(widget.id);
39387
+ }, [widget.id, setThreadId]);
39388
+ const { state: agentState, setState: setAgentState } = useCoAgent({
39389
+ name: (_d = widget.config) === null || _d === void 0 ? void 0 : _d.agentName,
39390
+ initialState: createInitialChartState$3(datasetId, widget_data),
39391
+ });
39392
+ const [chartState, setChartState] = useState(createInitialChartState$3(datasetId, widget_data));
39393
+ const handleLoadingTimeout = useCallback(async () => {
39394
+ var _a;
39395
+ if (!widgetBackendUrl || !widget.id || (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) || hasTimeoutError) {
39396
+ console.log('Skipping API call - conditions not met');
39397
+ return;
39398
+ }
39399
+ console.log('Loading timeout triggered for widget:', widget.id, 'API call count:', apiCallCount);
39400
+ if (apiCallCount >= 30) {
39401
+ console.log('API call limit reached for widget:', widget.id);
39402
+ setHasTimeoutError(true);
39403
+ setChartState(prevState => (Object.assign(Object.assign({}, prevState), { agent_message: "Timeout: Unable to load data after multiple attempts. Please try refreshing the widget." })));
39404
+ return;
39405
+ }
39406
+ setApiCallCount(prev => prev + 1);
39407
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
39408
+ console.log('Calling loadAgentState API for widget:', widget.id);
39409
+ const apiResponse = await loadAgentState$3(widgetBackendUrl, widget.id, agentName);
39410
+ console.log('API response received:', apiResponse);
39411
+ if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
39412
+ parseAndUpdateChartState$3(apiResponse, setChartState);
39413
+ }
39414
+ }, [widgetBackendUrl, widget.id, setChartState, (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName, chartState, apiCallCount, hasTimeoutError]);
39415
+ const startLoadingTimeout = useCallback(() => {
39416
+ if (timeoutRef.current) {
39417
+ clearTimeout(timeoutRef.current);
39418
+ }
39419
+ console.log('Scheduling next API call in 3 seconds');
39420
+ timeoutRef.current = setTimeout(() => {
39421
+ handleLoadingTimeout();
39422
+ }, CHART_REFRESH_TIMEOUT$3);
39423
+ }, [handleLoadingTimeout]);
39424
+ const clearLoadingTimeout = useCallback(() => {
39425
+ if (timeoutRef.current) {
39426
+ clearTimeout(timeoutRef.current);
39427
+ timeoutRef.current = null;
39428
+ }
39429
+ }, []);
39430
+ useEffect(() => {
39431
+ return () => {
39432
+ if (timeoutRef.current) {
39433
+ clearTimeout(timeoutRef.current);
39434
+ }
39435
+ };
39436
+ }, []);
39437
+ const { appendMessage, reset } = useCopilotChat();
39438
+ useEffect(() => {
39439
+ if (onResetReady && reset && widget.id) {
39440
+ const wrappedReset = () => {
39441
+ reset();
39442
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
39443
+ };
39444
+ onResetReady(widget.id, wrappedReset);
39445
+ }
39446
+ }, [reset, widget.id, onResetReady]);
39447
+ useEffect(() => {
39448
+ const handleTriggerAgent = (event) => {
39449
+ const { widgetId, query, agentType: eventAgentType, datasetId } = event.detail;
39450
+ reset();
39451
+ if (widgetId === widget.id) {
39452
+ let messageContent = `${query} and render data on pie chart`;
39453
+ console.log('triggering to datasetId==>', datasetId);
39454
+ setChartState(createInitialChartState$3(datasetId));
39455
+ setAgentState(createInitialChartState$3(datasetId));
39456
+ setApiCallCount(0);
39457
+ setHasTimeoutError(false);
39458
+ appendMessage(new TextMessage({
39459
+ content: messageContent,
39460
+ role: Role.User,
39461
+ }));
39462
+ // Start polling for chart data
39463
+ startLoadingTimeout();
39464
+ }
39465
+ };
39466
+ const handleClearChartState = (event) => {
39467
+ const { widgetId } = event.detail;
39468
+ if (widgetId === widget.id) {
39469
+ setChartState(createInitialChartState$3(datasetId));
39470
+ setAgentState(createInitialChartState$3(datasetId));
39471
+ setApiCallCount(0);
39472
+ setHasTimeoutError(false);
39473
+ }
39474
+ };
39475
+ window.addEventListener('triggerAgent', handleTriggerAgent);
39476
+ window.addEventListener('clearChartState', handleClearChartState);
39477
+ return () => {
39478
+ window.removeEventListener('triggerAgent', handleTriggerAgent);
39479
+ window.removeEventListener('clearChartState', handleClearChartState);
39480
+ };
39481
+ }, [widget.id, appendMessage, setChartState, startLoadingTimeout]);
39482
+ 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(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) &&
39483
+ (!((_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))
39484
+ ? (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)) })) })] }));
39485
+ }
39486
+ function PieChartWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
39487
+ var _a, _b;
39488
+ const styles = getStyleValues$3((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39489
+ const getRuntimeUrl = () => {
39490
+ var _a;
39491
+ const baseUrl = widgetBackendUrl || '';
39492
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
39493
+ return `${baseUrl}/api/copilot/${agentName}`;
39494
+ };
39495
+ return (jsxRuntimeExports.jsx(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 }) }));
39496
+ }
39497
+
39498
+ const CHART_REFRESH_TIMEOUT$2 = 3000;
39499
+ const DEFAULT_COLORS$1 = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
39500
+ const clearChat$2 = async (widgetBackendUrl, widgetId) => {
39501
+ if (!widgetBackendUrl || !widgetId)
39502
+ return;
39503
+ console.log('clearChat called for widgetId:', widgetId);
39504
+ try {
39505
+ await fetch(`${widgetBackendUrl}/api/clear-chat`, {
39506
+ method: 'POST',
39507
+ headers: {
39508
+ 'Content-Type': 'application/json',
39509
+ },
39510
+ body: JSON.stringify({
39511
+ session_id: widgetId,
39512
+ delete_state: true
39513
+ }),
39514
+ });
39515
+ console.log('Dispatching clearChartState event from clearChat for widgetId:', widgetId);
39516
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39517
+ }
39518
+ catch (error) {
39519
+ console.error('Failed to clear chat:', error);
39520
+ }
39521
+ };
39522
+ 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(RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
39523
+ const createInitialChartState$2 = (datasetId, seriesBarChartState) => {
39524
+ return {
39525
+ series_bar_chart_data: {
39526
+ title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.title) || "",
39527
+ type: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.type) || "series_bar",
39528
+ chart_type: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.chart_type) || "financial",
39529
+ x_axis_title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.x_axis_title) || "",
39530
+ y_axis_title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.y_axis_title) || "",
39531
+ orientation: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.orientation) || "vertical",
39532
+ units: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.units) || "",
39533
+ data: {
39534
+ labels: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.labels) || [],
39535
+ series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.series) || [],
39536
+ total: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.total) || 0,
39537
+ average: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.average) || 0
39538
+ },
39539
+ metadata: {
39540
+ categories: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.categories) || 0,
39541
+ series_count: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_count) || 0,
39542
+ highest_category: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_category) || "",
39543
+ highest_value: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_value) || 0,
39544
+ highest_series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_series) || "",
39545
+ lowest_category: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_category) || "",
39546
+ lowest_value: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_value) || 0,
39547
+ lowest_series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_series) || "",
39548
+ range: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.range) || 0,
39549
+ series_totals: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_totals) || {},
39550
+ series_averages: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_averages) || {}
39551
+ }
39552
+ },
39553
+ dataset_id: datasetId || "home_generation_dataset"
39554
+ };
39555
+ };
39556
+ const loadAgentState$2 = async (widgetBackendUrl, threadId, agentName) => {
39557
+ try {
39558
+ const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
39559
+ method: 'POST',
39560
+ headers: {
39561
+ 'Content-Type': 'application/json',
39562
+ },
39563
+ body: JSON.stringify({
39564
+ "operationName": "loadAgentState",
39565
+ "query": "query loadAgentState($data: LoadAgentStateInput!) {\n loadAgentState(data: $data) {\n threadId\n threadExists\n state\n messages\n __typename\n }\n}",
39566
+ "variables": {
39567
+ "data": {
39568
+ "agentName": agentName,
39569
+ "threadId": threadId
39570
+ }
39571
+ }
39572
+ }),
39573
+ });
39574
+ if (!response.ok) {
39575
+ throw new Error(`HTTP error! status: ${response.status}`);
39576
+ }
39577
+ const result = await response.json();
39578
+ return result;
39579
+ }
39580
+ catch (error) {
39581
+ console.error('Failed to load agent state:', error);
39582
+ return null;
39583
+ }
39584
+ };
39585
+ const parseAndUpdateChartState$2 = (apiResponse, setChartState) => {
39586
+ var _a, _b;
39587
+ try {
39588
+ 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) {
39589
+ const stateString = apiResponse.data.loadAgentState.state;
39590
+ const parsedState = JSON.parse(stateString);
39591
+ if (parsedState.state) {
39592
+ const chartData = parsedState.state;
39593
+ setChartState((prevState) => {
39594
+ const newChartState = Object.assign({}, prevState);
39595
+ if (chartData.series_bar_chart_data) {
39596
+ newChartState.series_bar_chart_data = chartData.series_bar_chart_data;
39597
+ }
39598
+ if (chartData.agent_message) {
39599
+ newChartState.agent_message = chartData.agent_message;
39600
+ }
39601
+ return newChartState;
39602
+ });
39603
+ }
39604
+ }
39605
+ }
39606
+ catch (error) {
39607
+ console.error('Failed to parse and update chart state:', error);
39608
+ }
39609
+ };
39610
+ const getStyleValues$2 = (styles = {}) => {
39611
+ const borderRadiusMap = {
39612
+ none: "0px",
39613
+ rounded: "0.375rem",
39614
+ large: "0.5rem",
39615
+ "extra-large": "0.75rem",
39616
+ };
39617
+ const paddingMap = {
39618
+ small: "0.5rem",
39619
+ medium: "1rem",
39620
+ large: "1.5rem",
39621
+ "extra-large": "2rem",
39622
+ };
39623
+ const alignment = styles.alignment || "left";
39624
+ return {
39625
+ backgroundColor: styles.backgroundColor || "#ffffff",
39626
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
39627
+ padding: paddingMap[styles.padding || "medium"],
39628
+ color: styles.textColor || "#000000",
39629
+ fontSize: styles.fontSize || "14px",
39630
+ textAlign: alignment,
39631
+ };
39632
+ };
39633
+ function SeriesBarChartComponent$1({ orientation, seriesBarChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content, hasWidgetData }) {
39634
+ var _a, _b, _c, _d, _e, _f, _g, _h;
39635
+ const hasCalledRef = useRef(false);
39636
+ 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) || [];
39637
+ 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) || [];
39638
+ const chartTitle = ((_e = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _e === void 0 ? void 0 : _e.title) || "";
39639
+ const units = ((_f = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _f === void 0 ? void 0 : _f.units) || "";
39640
+ 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) || "";
39641
+ 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) || "";
39642
+ const isEmpty = labels.length === 0 || series.length === 0;
39643
+ const handleRefresh = async () => {
39644
+ if (query) {
39645
+ await clearChat$2(widgetBackendUrl, widgetId);
39646
+ console.log('Dispatching clearChartState event for widgetId:', widgetId);
39647
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39648
+ appendMessage(new TextMessage({
39649
+ content: `${query} and render data on a series bar chart`,
39650
+ role: Role.User,
39651
+ }));
39652
+ }
39653
+ };
39654
+ useEffect(() => {
39655
+ if (isEmpty && query && isFirstLoad && !(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message) && !hasCalledRef.current) {
39656
+ hasCalledRef.current = true;
39657
+ handleRefresh();
39658
+ }
39659
+ }, [isEmpty, query, isFirstLoad, seriesBarChartState]);
39660
+ useEffect(() => {
39661
+ console.log('SeriesBarChartComponent useEffect - isEmpty:', isEmpty, 'hasMessage:', !!(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message), 'hasWidgetData:', hasWidgetData, 'isFirstLoad:', isFirstLoad);
39662
+ if (isEmpty && startLoadingTimeout && !(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message)) {
39663
+ console.log('Starting loading timeout from SeriesBarChartComponent useEffect');
39664
+ startLoadingTimeout();
39665
+ }
39666
+ else if (!isEmpty && clearLoadingTimeout) {
39667
+ clearLoadingTimeout();
39668
+ }
39669
+ }, [isEmpty, startLoadingTimeout, clearLoadingTimeout, seriesBarChartState]);
39670
+ const finalColors = useMemo(() => {
39671
+ return shuffleColors(DEFAULT_COLORS$1, series.length);
39672
+ }, [series.length]);
39673
+ if (isEmpty) {
39674
+ return createLoadingComponent$2();
39675
+ }
39676
+ const transformedData = {
39677
+ labels: labels,
39678
+ datasets: series.map((seriesItem, index) => ({
39679
+ label: seriesItem.name,
39680
+ data: seriesItem.values,
39681
+ backgroundColor: (seriesItem === null || seriesItem === void 0 ? void 0 : seriesItem.colors) || (seriesItem === null || seriesItem === void 0 ? void 0 : seriesItem.color) || finalColors[index % finalColors.length],
39682
+ })),
39683
+ };
39684
+ 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 }));
39685
+ }
39686
+ function CopilotKitSeriesBarChart$1({ widget, showHeader, styles, onResetReady, widgetBackendUrl, datasetId, widgetData, }) {
39687
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
39688
+ const orientation = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.orientation) || "vertical";
39689
+ const isFirstLoad = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.isFirstLoad;
39690
+ const content = (_c = widget.config) === null || _c === void 0 ? void 0 : _c.content;
39691
+ const widget_data = (_d = widget.widget_data) === null || _d === void 0 ? void 0 : _d.series_bar_chart_data;
39692
+ console.log('widget_data===>', widget_data);
39693
+ const { threadId, setThreadId } = useCopilotContext();
39694
+ const timeoutRef = useRef(null);
39695
+ const [apiCallCount, setApiCallCount] = useState(0);
39696
+ const [hasTimeoutError, setHasTimeoutError] = useState(false);
39697
+ useEffect(() => {
39698
+ setThreadId(widget.id);
39699
+ }, [widget.id, setThreadId]);
39700
+ const { state: agentState, setState: setAgentState } = useCoAgent({
39701
+ name: (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName,
39702
+ initialState: createInitialChartState$2(datasetId, widget_data),
39703
+ });
39704
+ const [chartState, setChartState] = useState(createInitialChartState$2(datasetId, widget_data));
39705
+ const handleLoadingTimeout = useCallback(async () => {
39706
+ var _a;
39707
+ if (!widgetBackendUrl || !widget.id || (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) || hasTimeoutError) {
39708
+ console.log('Skipping API call - conditions not met');
39709
+ return;
39710
+ }
39711
+ console.log('Loading timeout triggered for widget:', widget.id, 'API call count:', apiCallCount);
39712
+ if (apiCallCount >= 30) {
39713
+ console.log('API call limit reached for widget:', widget.id);
39714
+ setHasTimeoutError(true);
39715
+ setChartState(prevState => (Object.assign(Object.assign({}, prevState), { agent_message: "Timeout: Unable to load data after multiple attempts. Please try refreshing the widget." })));
39716
+ return;
39717
+ }
39718
+ setApiCallCount(prev => prev + 1);
39719
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
39720
+ console.log('Calling loadAgentState API for widget:', widget.id);
39721
+ const apiResponse = await loadAgentState$2(widgetBackendUrl, widget.id, agentName);
39722
+ console.log('API response received:', apiResponse);
39723
+ if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
39724
+ parseAndUpdateChartState$2(apiResponse, setChartState);
39725
+ }
39726
+ }, [widgetBackendUrl, widget.id, setChartState, (_f = widget.config) === null || _f === void 0 ? void 0 : _f.agentName, chartState, apiCallCount, hasTimeoutError]);
39727
+ const startLoadingTimeout = useCallback(() => {
39728
+ if (timeoutRef.current) {
39729
+ clearTimeout(timeoutRef.current);
39730
+ }
39731
+ console.log('Scheduling next API call in 3 seconds');
39732
+ timeoutRef.current = setTimeout(() => {
39733
+ handleLoadingTimeout();
39734
+ }, CHART_REFRESH_TIMEOUT$2);
39735
+ }, [handleLoadingTimeout]);
39736
+ const clearLoadingTimeout = useCallback(() => {
39737
+ if (timeoutRef.current) {
39738
+ clearTimeout(timeoutRef.current);
39739
+ timeoutRef.current = null;
39740
+ }
39741
+ }, []);
39742
+ useEffect(() => {
39743
+ return () => {
39744
+ if (timeoutRef.current) {
39745
+ clearTimeout(timeoutRef.current);
39746
+ }
39747
+ };
39748
+ }, []);
39749
+ const { appendMessage, reset } = useCopilotChat();
39750
+ useEffect(() => {
39751
+ if (onResetReady && reset && widget.id) {
39752
+ const wrappedReset = () => {
39753
+ reset();
39754
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
39755
+ };
39756
+ onResetReady(widget.id, wrappedReset);
39757
+ }
39758
+ }, [reset, widget.id, onResetReady]);
39759
+ useEffect(() => {
39760
+ const handleTriggerAgent = (event) => {
39761
+ const { widgetId, query, agentType: eventAgentType, datasetId } = event.detail;
39762
+ if (widgetId === widget.id) {
39763
+ let messageContent = `${query} and render data on a series bar chart`;
39764
+ reset();
39765
+ console.log('triggering to datasetId==>', datasetId);
39766
+ setChartState(createInitialChartState$2(datasetId));
39767
+ setAgentState(createInitialChartState$2(datasetId));
39768
+ setApiCallCount(0);
39769
+ setHasTimeoutError(false);
39770
+ appendMessage(new TextMessage({
39771
+ content: messageContent,
39772
+ role: Role.User,
39773
+ }));
39774
+ // Start polling for chart data
39775
+ startLoadingTimeout();
39776
+ }
39777
+ };
39778
+ const handleClearChartState = (event) => {
39779
+ const { widgetId } = event.detail;
39780
+ if (widgetId === widget.id) {
39781
+ setChartState(createInitialChartState$2(datasetId));
39782
+ setAgentState(createInitialChartState$2(datasetId));
39783
+ setApiCallCount(0);
39784
+ setHasTimeoutError(false);
39785
+ }
39786
+ };
39787
+ window.addEventListener('triggerAgent', handleTriggerAgent);
39788
+ window.addEventListener('clearChartState', handleClearChartState);
39789
+ return () => {
39790
+ window.removeEventListener('triggerAgent', handleTriggerAgent);
39791
+ window.removeEventListener('clearChartState', handleClearChartState);
39792
+ };
39793
+ }, [widget.id, appendMessage, setChartState, startLoadingTimeout]);
39794
+ 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(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) &&
39795
+ (!((_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))
39796
+ ? (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)) })) })] }));
39797
+ }
39798
+ function SeriesBarChartWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
39799
+ var _a, _b;
39800
+ const styles = getStyleValues$2((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
39801
+ const getRuntimeUrl = () => {
39802
+ var _a;
39803
+ const baseUrl = widgetBackendUrl || '';
39804
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
39805
+ return `${baseUrl}/api/copilot/${agentName}`;
39806
+ };
39807
+ return (jsxRuntimeExports.jsx(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 }) }));
39808
+ }
39809
+
39810
+ const CHART_REFRESH_TIMEOUT$1 = 3000;
39811
+ const DEFAULT_COLORS = ["#E4DCB8", "#DAC46C", "#808080", "#582809", "#A3ADD0", "#398E6F", "#AF123D", "#8C99C4", "#5290AC", "#601B07", "#50649D", "#B4A8A0", "#6F2587"];
39812
+ const clearChat$1 = async (widgetBackendUrl, widgetId) => {
39813
+ if (!widgetBackendUrl || !widgetId)
39814
+ return;
39815
+ console.log('clearChat called for widgetId:', widgetId);
39816
+ try {
39817
+ await fetch(`${widgetBackendUrl}/api/clear-chat`, {
39818
+ method: 'POST',
39819
+ headers: {
39820
+ 'Content-Type': 'application/json',
39821
+ },
39822
+ body: JSON.stringify({
39823
+ session_id: widgetId,
39824
+ delete_state: true
39825
+ }),
39826
+ });
39827
+ console.log('Dispatching clearChartState event from clearChat for widgetId:', widgetId);
39828
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39829
+ }
39830
+ catch (error) {
39831
+ console.error('Failed to clear chat:', error);
39832
+ }
39833
+ };
39834
+ 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(RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
39835
+ const createInitialChartState$1 = (datasetId, seriesBarChartState) => {
39836
+ return {
39837
+ series_bar_chart_data: {
39838
+ title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.title) || "",
39839
+ type: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.type) || "series_bar",
39840
+ chart_type: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.chart_type) || "financial",
39841
+ x_axis_title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.x_axis_title) || "",
39842
+ y_axis_title: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.y_axis_title) || "",
39843
+ orientation: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.orientation) || "vertical",
39844
+ units: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.units) || "",
39845
+ data: {
39846
+ labels: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.labels) || [],
39847
+ series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.series) || [],
39848
+ total: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.total) || 0,
39849
+ average: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.data.average) || 0
39850
+ },
39851
+ metadata: {
39852
+ categories: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.categories) || 0,
39853
+ series_count: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_count) || 0,
39854
+ highest_category: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_category) || "",
39855
+ highest_value: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_value) || 0,
39856
+ highest_series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.highest_series) || "",
39857
+ lowest_category: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_category) || "",
39858
+ lowest_value: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_value) || 0,
39859
+ lowest_series: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.lowest_series) || "",
39860
+ range: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.range) || 0,
39861
+ series_totals: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_totals) || {},
39862
+ series_averages: (seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.metadata.series_averages) || {}
39863
+ }
39864
+ },
39865
+ dataset_id: datasetId || "home_generation_dataset"
39866
+ };
39867
+ };
39868
+ const loadAgentState$1 = async (widgetBackendUrl, threadId, agentName) => {
39869
+ try {
39870
+ const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
39871
+ method: 'POST',
39872
+ headers: {
39873
+ 'Content-Type': 'application/json',
39874
+ },
39875
+ body: JSON.stringify({
39876
+ "operationName": "loadAgentState",
39877
+ "query": "query loadAgentState($data: LoadAgentStateInput!) {\n loadAgentState(data: $data) {\n threadId\n threadExists\n state\n messages\n __typename\n }\n}",
39878
+ "variables": {
39879
+ "data": {
39880
+ "agentName": agentName,
39881
+ "threadId": threadId
39882
+ }
39883
+ }
39884
+ }),
39885
+ });
39886
+ if (!response.ok) {
39887
+ throw new Error(`HTTP error! status: ${response.status}`);
39888
+ }
39889
+ const result = await response.json();
39890
+ return result;
39891
+ }
39892
+ catch (error) {
39893
+ console.error('Failed to load agent state:', error);
39894
+ return null;
39895
+ }
39896
+ };
39897
+ const parseAndUpdateChartState$1 = (apiResponse, setChartState) => {
39898
+ var _a, _b;
39899
+ try {
39900
+ 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) {
39901
+ const stateString = apiResponse.data.loadAgentState.state;
39902
+ const parsedState = JSON.parse(stateString);
39903
+ if (parsedState.state) {
39904
+ const chartData = parsedState.state;
39905
+ setChartState((prevState) => {
39906
+ const newChartState = Object.assign({}, prevState);
39907
+ if (chartData.series_bar_chart_data) {
39908
+ newChartState.series_bar_chart_data = chartData.series_bar_chart_data;
39909
+ }
39910
+ if (chartData.agent_message) {
39911
+ newChartState.agent_message = chartData.agent_message;
39912
+ }
39913
+ return newChartState;
39914
+ });
39915
+ }
39916
+ }
39917
+ }
39918
+ catch (error) {
39919
+ console.error('Failed to parse and update chart state:', error);
39920
+ }
39921
+ };
39922
+ const getStyleValues$1 = (styles = {}) => {
39923
+ const borderRadiusMap = {
39924
+ none: "0px",
39925
+ rounded: "0.375rem",
39926
+ large: "0.5rem",
39927
+ "extra-large": "0.75rem",
39928
+ };
39929
+ const paddingMap = {
39930
+ small: "0.5rem",
39931
+ medium: "1rem",
39932
+ large: "1.5rem",
39933
+ "extra-large": "2rem",
39934
+ };
39935
+ const alignment = styles.alignment || "left";
39936
+ return {
39937
+ backgroundColor: styles.backgroundColor || "#ffffff",
39938
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
39939
+ padding: paddingMap[styles.padding || "medium"],
39940
+ color: styles.textColor || "#000000",
39941
+ fontSize: styles.fontSize || "14px",
39942
+ textAlign: alignment,
39943
+ };
39944
+ };
39945
+ function SeriesBarChartComponent({ orientation, seriesBarChartState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content, hasWidgetData }) {
39946
+ var _a, _b, _c, _d, _e, _f, _g, _h;
39947
+ const hasCalledRef = useRef(false);
39948
+ 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) || [];
39949
+ 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) || [];
39950
+ const chartTitle = ((_e = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _e === void 0 ? void 0 : _e.title) || "";
39951
+ const units = ((_f = seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.series_bar_chart_data) === null || _f === void 0 ? void 0 : _f.units) || "";
39952
+ 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) || "";
39953
+ 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) || "";
39954
+ const isEmpty = labels.length === 0 || series.length === 0;
39955
+ const handleRefresh = async () => {
39956
+ if (query) {
39957
+ await clearChat$1(widgetBackendUrl, widgetId);
39958
+ console.log('Dispatching clearChartState event for widgetId:', widgetId);
39959
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
39960
+ appendMessage(new TextMessage({
39961
+ content: `${query} and render data on a series bar chart`,
39962
+ role: Role.User,
39963
+ }));
39964
+ }
39965
+ };
39966
+ useEffect(() => {
39967
+ if (isEmpty && query && isFirstLoad && !(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message) && !hasCalledRef.current) {
39968
+ hasCalledRef.current = true;
39969
+ handleRefresh();
39970
+ }
39971
+ }, [isEmpty, query, isFirstLoad, seriesBarChartState]);
39972
+ useEffect(() => {
39973
+ console.log('SeriesBarChartComponent useEffect - isEmpty:', isEmpty, 'hasMessage:', !!(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message), 'hasWidgetData:', hasWidgetData, 'isFirstLoad:', isFirstLoad);
39974
+ if (isEmpty && startLoadingTimeout && !(seriesBarChartState === null || seriesBarChartState === void 0 ? void 0 : seriesBarChartState.agent_message)) {
39975
+ console.log('Starting loading timeout from SeriesBarChartComponent useEffect');
39976
+ startLoadingTimeout();
39977
+ }
39978
+ else if (!isEmpty && clearLoadingTimeout) {
39979
+ clearLoadingTimeout();
39980
+ }
39981
+ }, [isEmpty, startLoadingTimeout, clearLoadingTimeout, seriesBarChartState]);
39982
+ const finalColors = useMemo(() => {
39983
+ return shuffleColors(DEFAULT_COLORS, series.length);
39984
+ }, [series.length]);
39985
+ if (isEmpty) {
39986
+ return createLoadingComponent$1();
39987
+ }
39988
+ const transformedData = {
39989
+ labels: labels,
39990
+ datasets: series.map((seriesItem, index) => ({
39991
+ label: seriesItem.name,
39992
+ data: seriesItem.values,
39993
+ backgroundColor: (seriesItem === null || seriesItem === void 0 ? void 0 : seriesItem.colors) || (seriesItem === null || seriesItem === void 0 ? void 0 : seriesItem.color) || finalColors[index % finalColors.length],
39994
+ })),
39995
+ };
39996
+ 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 }));
39997
+ }
39998
+ function CopilotKitSeriesBarChart({ widget, showHeader, styles, onResetReady, widgetBackendUrl, datasetId, widgetData, }) {
39999
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
40000
+ const orientation = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.orientation) || "vertical";
40001
+ const isFirstLoad = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.isFirstLoad;
40002
+ const content = (_c = widget.config) === null || _c === void 0 ? void 0 : _c.content;
40003
+ const widget_data = (_d = widget.widget_data) === null || _d === void 0 ? void 0 : _d.series_bar_chart_data;
40004
+ console.log('widget_data===>', widget_data);
40005
+ const { threadId, setThreadId } = useCopilotContext();
40006
+ const timeoutRef = useRef(null);
40007
+ const [apiCallCount, setApiCallCount] = useState(0);
40008
+ const [hasTimeoutError, setHasTimeoutError] = useState(false);
40009
+ useEffect(() => {
40010
+ setThreadId(widget.id);
40011
+ }, [widget.id, setThreadId]);
40012
+ const { state: agentState, setState: setAgentState } = useCoAgent({
40013
+ name: (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName,
40014
+ initialState: createInitialChartState$1(datasetId, widget_data),
40015
+ });
40016
+ const [chartState, setChartState] = useState(createInitialChartState$1(datasetId, widget_data));
40017
+ const handleLoadingTimeout = useCallback(async () => {
40018
+ var _a;
40019
+ if (!widgetBackendUrl || !widget.id || (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) || hasTimeoutError) {
40020
+ console.log('Skipping API call - conditions not met');
40021
+ return;
40022
+ }
40023
+ console.log('Loading timeout triggered for widget:', widget.id, 'API call count:', apiCallCount);
40024
+ if (apiCallCount >= 30) {
40025
+ console.log('API call limit reached for widget:', widget.id);
40026
+ setHasTimeoutError(true);
40027
+ setChartState(prevState => (Object.assign(Object.assign({}, prevState), { agent_message: "Timeout: Unable to load data after multiple attempts. Please try refreshing the widget." })));
40028
+ return;
40029
+ }
40030
+ setApiCallCount(prev => prev + 1);
40031
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
40032
+ console.log('Calling loadAgentState API for widget:', widget.id);
40033
+ const apiResponse = await loadAgentState$1(widgetBackendUrl, widget.id, agentName);
40034
+ console.log('API response received:', apiResponse);
40035
+ if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
40036
+ parseAndUpdateChartState$1(apiResponse, setChartState);
40037
+ }
40038
+ }, [widgetBackendUrl, widget.id, setChartState, (_f = widget.config) === null || _f === void 0 ? void 0 : _f.agentName, chartState, apiCallCount, hasTimeoutError]);
40039
+ const startLoadingTimeout = useCallback(() => {
40040
+ if (timeoutRef.current) {
40041
+ clearTimeout(timeoutRef.current);
40042
+ }
40043
+ console.log('Scheduling next API call in 3 seconds');
40044
+ timeoutRef.current = setTimeout(() => {
40045
+ handleLoadingTimeout();
40046
+ }, CHART_REFRESH_TIMEOUT$1);
40047
+ }, [handleLoadingTimeout]);
40048
+ const clearLoadingTimeout = useCallback(() => {
40049
+ if (timeoutRef.current) {
40050
+ clearTimeout(timeoutRef.current);
40051
+ timeoutRef.current = null;
40052
+ }
40053
+ }, []);
40054
+ useEffect(() => {
40055
+ return () => {
40056
+ if (timeoutRef.current) {
40057
+ clearTimeout(timeoutRef.current);
40058
+ }
40059
+ };
40060
+ }, []);
40061
+ const { appendMessage, reset } = useCopilotChat();
40062
+ useEffect(() => {
40063
+ if (onResetReady && reset && widget.id) {
40064
+ const wrappedReset = () => {
40065
+ reset();
40066
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
40067
+ };
40068
+ onResetReady(widget.id, wrappedReset);
40069
+ }
40070
+ }, [reset, widget.id, onResetReady]);
40071
+ useEffect(() => {
40072
+ const handleTriggerAgent = (event) => {
40073
+ const { widgetId, query, agentType: eventAgentType, datasetId } = event.detail;
40074
+ if (widgetId === widget.id) {
40075
+ let messageContent = `${query} and render data on a series bar chart`;
40076
+ reset();
40077
+ console.log('triggering to datasetId==>', datasetId);
40078
+ setChartState(createInitialChartState$1(datasetId));
40079
+ setAgentState(createInitialChartState$1(datasetId));
40080
+ setApiCallCount(0);
40081
+ setHasTimeoutError(false);
40082
+ appendMessage(new TextMessage({
40083
+ content: messageContent,
40084
+ role: Role.User,
40085
+ }));
40086
+ // Start polling for chart data
40087
+ startLoadingTimeout();
40088
+ }
40089
+ };
40090
+ const handleClearChartState = (event) => {
40091
+ const { widgetId } = event.detail;
40092
+ if (widgetId === widget.id) {
40093
+ setChartState(createInitialChartState$1(datasetId));
40094
+ setAgentState(createInitialChartState$1(datasetId));
40095
+ setApiCallCount(0);
40096
+ setHasTimeoutError(false);
40097
+ }
40098
+ };
40099
+ window.addEventListener('triggerAgent', handleTriggerAgent);
40100
+ window.addEventListener('clearChartState', handleClearChartState);
40101
+ return () => {
40102
+ window.removeEventListener('triggerAgent', handleTriggerAgent);
40103
+ window.removeEventListener('clearChartState', handleClearChartState);
40104
+ };
40105
+ }, [widget.id, appendMessage, setChartState, startLoadingTimeout]);
40106
+ 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(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) &&
40107
+ (!((_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))
40108
+ ? (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)) })) })] }));
40109
+ }
40110
+ function SeriesLineChartWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
40111
+ var _a, _b;
40112
+ const styles = getStyleValues$1((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
40113
+ const getRuntimeUrl = () => {
40114
+ var _a;
40115
+ const baseUrl = widgetBackendUrl || '';
40116
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
40117
+ return `${baseUrl}/api/copilot/${agentName}`;
40118
+ };
40119
+ return (jsxRuntimeExports.jsx(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 }) }));
40120
+ }
40121
+
40122
+ const CHART_REFRESH_TIMEOUT = 3000;
40123
+ const clearChat = async (widgetBackendUrl, widgetId) => {
40124
+ if (!widgetBackendUrl || !widgetId)
40125
+ return;
40126
+ console.log('clearChat called for widgetId:', widgetId);
40127
+ try {
40128
+ await fetch(`${widgetBackendUrl}/api/clear-chat`, {
40129
+ method: 'POST',
40130
+ headers: {
40131
+ 'Content-Type': 'application/json',
40132
+ },
40133
+ body: JSON.stringify({
40134
+ session_id: widgetId,
40135
+ delete_state: true
40136
+ }),
40137
+ });
40138
+ console.log('Dispatching clearChartState event from clearChat for widgetId:', widgetId);
40139
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
40140
+ }
40141
+ catch (error) {
40142
+ console.error('Failed to clear chat:', error);
40143
+ }
40144
+ };
40145
+ 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(RefreshCw, { className: "h-6 w-6 animate-spin text-gray-800" }), jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: message })] }) }));
40146
+ const createInitialChartState = (datasetId, dataGridState) => {
40147
+ return {
40148
+ matrix_grid_data: {
40149
+ title: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.title) || "",
40150
+ type: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.type) || "data_grid",
40151
+ grid_type: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.grid_type) || "",
40152
+ grouped: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.grouped) || false,
40153
+ data: {
40154
+ headers: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.headers) || [],
40155
+ units: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.units) || [],
40156
+ rows: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.rows) || [],
40157
+ row_count: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.row_count) || 0,
40158
+ column_count: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.data.column_count) || 0
40159
+ },
40160
+ metadata: {
40161
+ total_rows: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.metadata.total_rows) || 0,
40162
+ total_columns: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.metadata.total_columns) || 0,
40163
+ numeric_columns: (dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.metadata.numeric_columns) || []
40164
+ }
40165
+ },
40166
+ dataset_id: datasetId || "home_generation_dataset"
40167
+ };
40168
+ };
40169
+ const loadAgentState = async (widgetBackendUrl, threadId, agentName) => {
40170
+ try {
40171
+ const response = await fetch(`${widgetBackendUrl}/api/copilot/${agentName}`, {
40172
+ method: 'POST',
40173
+ headers: {
40174
+ 'Content-Type': 'application/json',
40175
+ },
40176
+ body: JSON.stringify({
40177
+ "operationName": "loadAgentState",
40178
+ "query": "query loadAgentState($data: LoadAgentStateInput!) {\n loadAgentState(data: $data) {\n threadId\n threadExists\n state\n messages\n __typename\n }\n}",
40179
+ "variables": {
40180
+ "data": {
40181
+ "agentName": agentName,
40182
+ "threadId": threadId
40183
+ }
40184
+ }
40185
+ }),
40186
+ });
40187
+ if (!response.ok) {
40188
+ throw new Error(`HTTP error! status: ${response.status}`);
40189
+ }
40190
+ const result = await response.json();
40191
+ return result;
40192
+ }
40193
+ catch (error) {
40194
+ console.error('Failed to load agent state:', error);
40195
+ return null;
40196
+ }
40197
+ };
40198
+ const parseAndUpdateChartState = (apiResponse, setChartState) => {
40199
+ var _a, _b;
40200
+ try {
40201
+ 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) {
40202
+ const stateString = apiResponse.data.loadAgentState.state;
40203
+ const parsedState = JSON.parse(stateString);
40204
+ if (parsedState.state) {
40205
+ const chartData = parsedState.state;
40206
+ setChartState((prevState) => {
40207
+ const newChartState = Object.assign({}, prevState);
40208
+ if (chartData.matrix_grid_data) {
40209
+ newChartState.matrix_grid_data = chartData.matrix_grid_data;
40210
+ }
40211
+ if (chartData.agent_message) {
40212
+ newChartState.agent_message = chartData.agent_message;
40213
+ }
40214
+ return newChartState;
40215
+ });
40216
+ }
40217
+ }
40218
+ }
40219
+ catch (error) {
40220
+ console.error('Failed to parse and update chart state:', error);
40221
+ }
40222
+ };
40223
+ const getStyleValues = (styles = {}) => {
40224
+ const borderRadiusMap = {
40225
+ none: "0px",
40226
+ rounded: "0.375rem",
40227
+ large: "0.5rem",
40228
+ "extra-large": "0.75rem",
40229
+ };
40230
+ const paddingMap = {
40231
+ small: "0.5rem",
40232
+ medium: "1rem",
40233
+ large: "1.5rem",
40234
+ "extra-large": "2rem",
40235
+ };
40236
+ const alignment = styles.alignment || "left";
40237
+ return {
40238
+ backgroundColor: styles.backgroundColor || "#ffffff",
40239
+ borderRadius: borderRadiusMap[styles.borderRadius || "rounded"],
40240
+ padding: paddingMap[styles.padding || "medium"],
40241
+ color: styles.textColor || "#000000",
40242
+ fontSize: styles.fontSize || "14px",
40243
+ textAlign: alignment,
40244
+ };
40245
+ };
40246
+ function DataGridComponent({ dataGridState, styles, appendMessage, query, isFirstLoad, widgetBackendUrl, widgetId, startLoadingTimeout, clearLoadingTimeout, content, hasWidgetData }) {
40247
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
40248
+ const hasCalledRef = useRef(false);
40249
+ 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) || [];
40250
+ 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) || [];
40251
+ const gridTitle = ((_e = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _e === void 0 ? void 0 : _e.title) || "";
40252
+ 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) || [];
40253
+ const isEmpty = columns.length === 0 || rows.length === 0;
40254
+ const handleRefresh = async () => {
40255
+ if (query) {
40256
+ await clearChat(widgetBackendUrl, widgetId);
40257
+ console.log('Dispatching clearChartState event for widgetId:', widgetId);
40258
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId } }));
40259
+ appendMessage(new TextMessage({
40260
+ content: `${query} and render data in a data grid table`,
40261
+ role: Role.User,
40262
+ }));
40263
+ }
40264
+ };
40265
+ useEffect(() => {
40266
+ if (isEmpty && query && isFirstLoad && !(dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.agent_message) && !hasCalledRef.current) {
40267
+ hasCalledRef.current = true;
40268
+ handleRefresh();
40269
+ }
40270
+ }, [isEmpty, query, isFirstLoad, dataGridState]);
40271
+ useEffect(() => {
40272
+ console.log('DataGridComponent useEffect - isEmpty:', isEmpty, 'hasMessage:', !!(dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.agent_message), 'hasWidgetData:', hasWidgetData, 'isFirstLoad:', isFirstLoad);
40273
+ if (isEmpty && startLoadingTimeout && !(dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.agent_message)) {
40274
+ console.log('Starting loading timeout from DataGridComponent useEffect');
40275
+ startLoadingTimeout();
40276
+ }
40277
+ else if (!isEmpty && clearLoadingTimeout) {
40278
+ clearLoadingTimeout();
40279
+ }
40280
+ }, [isEmpty, startLoadingTimeout, clearLoadingTimeout, dataGridState]);
40281
+ if (isEmpty) {
40282
+ return createLoadingComponent();
40283
+ }
40284
+ const transformedData = {
40285
+ columns: columns,
40286
+ units: units,
40287
+ rows: rows,
40288
+ grouped: ((_h = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _h === void 0 ? void 0 : _h.grouped) || false,
40289
+ grouping: (_j = dataGridState === null || dataGridState === void 0 ? void 0 : dataGridState.matrix_grid_data) === null || _j === void 0 ? void 0 : _j.grouping
40290
+ };
40291
+ return (jsxRuntimeExports.jsx(DataGrid, { title: gridTitle, data: transformedData, className: "" }));
40292
+ }
40293
+ function CopilotKitDataGrid({ widget, showHeader, styles, onResetReady, widgetBackendUrl, datasetId, widgetData, }) {
40294
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
40295
+ const isFirstLoad = (_a = widget.config) === null || _a === void 0 ? void 0 : _a.isFirstLoad;
40296
+ const content = (_b = widget.config) === null || _b === void 0 ? void 0 : _b.content;
40297
+ const widget_data = (_c = widget.widget_data) === null || _c === void 0 ? void 0 : _c.matrix_grid_data;
40298
+ console.log('widget_data===>', widget_data);
40299
+ const { threadId, setThreadId } = useCopilotContext();
40300
+ const timeoutRef = useRef(null);
40301
+ const [apiCallCount, setApiCallCount] = useState(0);
40302
+ const [hasTimeoutError, setHasTimeoutError] = useState(false);
40303
+ useEffect(() => {
40304
+ setThreadId(widget.id);
40305
+ }, [widget.id, setThreadId]);
40306
+ const { state: agentState, setState: setAgentState } = useCoAgent({
40307
+ name: (_d = widget.config) === null || _d === void 0 ? void 0 : _d.agentName,
40308
+ initialState: createInitialChartState(datasetId, widget_data),
40309
+ });
40310
+ const [chartState, setChartState] = useState(createInitialChartState(datasetId, widget_data));
40311
+ const handleLoadingTimeout = useCallback(async () => {
40312
+ var _a;
40313
+ if (!widgetBackendUrl || !widget.id || (chartState === null || chartState === void 0 ? void 0 : chartState.agent_message) || hasTimeoutError) {
40314
+ console.log('Skipping API call - conditions not met');
40315
+ return;
40316
+ }
40317
+ console.log('Loading timeout triggered for widget:', widget.id, 'API call count:', apiCallCount);
40318
+ if (apiCallCount >= 30) {
40319
+ console.log('API call limit reached for widget:', widget.id);
40320
+ setHasTimeoutError(true);
40321
+ setChartState(prevState => (Object.assign(Object.assign({}, prevState), { agent_message: "Timeout: Unable to load data after multiple attempts. Please try refreshing the widget." })));
40322
+ return;
40323
+ }
40324
+ setApiCallCount(prev => prev + 1);
40325
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || "adk-construction-project-agent";
40326
+ console.log('Calling loadAgentState API for widget:', widget.id);
40327
+ const apiResponse = await loadAgentState(widgetBackendUrl, widget.id, agentName);
40328
+ console.log('API response received:', apiResponse);
40329
+ if (apiResponse && !(chartState === null || chartState === void 0 ? void 0 : chartState.agent_message)) {
40330
+ parseAndUpdateChartState(apiResponse, setChartState);
40331
+ }
40332
+ }, [widgetBackendUrl, widget.id, setChartState, (_e = widget.config) === null || _e === void 0 ? void 0 : _e.agentName, chartState, apiCallCount, hasTimeoutError]);
40333
+ const startLoadingTimeout = useCallback(() => {
40334
+ if (timeoutRef.current) {
40335
+ clearTimeout(timeoutRef.current);
40336
+ }
40337
+ console.log('Scheduling next API call in 3 seconds');
40338
+ timeoutRef.current = setTimeout(() => {
40339
+ handleLoadingTimeout();
40340
+ }, CHART_REFRESH_TIMEOUT);
40341
+ }, [handleLoadingTimeout]);
40342
+ const clearLoadingTimeout = useCallback(() => {
40343
+ if (timeoutRef.current) {
40344
+ clearTimeout(timeoutRef.current);
40345
+ timeoutRef.current = null;
40346
+ }
40347
+ }, []);
40348
+ useEffect(() => {
40349
+ return () => {
40350
+ if (timeoutRef.current) {
40351
+ clearTimeout(timeoutRef.current);
40352
+ }
40353
+ };
40354
+ }, []);
40355
+ const { appendMessage, reset } = useCopilotChat();
40356
+ useEffect(() => {
40357
+ if (onResetReady && reset && widget.id) {
40358
+ const wrappedReset = () => {
40359
+ reset();
40360
+ window.dispatchEvent(new CustomEvent('clearChartState', { detail: { widgetId: widget.id } }));
40361
+ };
40362
+ onResetReady(widget.id, wrappedReset);
40363
+ }
40364
+ }, [reset, widget.id, onResetReady]);
40365
+ useEffect(() => {
40366
+ const handleTriggerAgent = (event) => {
40367
+ const { widgetId, query, agentType: eventAgentType, datasetId } = event.detail;
40368
+ reset();
40369
+ if (widgetId === widget.id) {
40370
+ let messageContent = `${query} and render data in a data grid table`;
40371
+ console.log('triggering to datasetId==>', datasetId);
40372
+ setChartState(createInitialChartState(datasetId));
40373
+ setAgentState(createInitialChartState(datasetId));
40374
+ setApiCallCount(0);
40375
+ setHasTimeoutError(false);
40376
+ appendMessage(new TextMessage({
40377
+ content: messageContent,
40378
+ role: Role.User,
40379
+ }));
40380
+ // Start polling for chart data
40381
+ startLoadingTimeout();
40382
+ }
40383
+ };
40384
+ const handleClearChartState = (event) => {
40385
+ const { widgetId } = event.detail;
40386
+ if (widgetId === widget.id) {
40387
+ setChartState(createInitialChartState(datasetId));
40388
+ setAgentState(createInitialChartState(datasetId));
40389
+ setApiCallCount(0);
40390
+ setHasTimeoutError(false);
40391
+ }
40392
+ };
40393
+ window.addEventListener('triggerAgent', handleTriggerAgent);
40394
+ window.addEventListener('clearChartState', handleClearChartState);
40395
+ return () => {
40396
+ window.removeEventListener('triggerAgent', handleTriggerAgent);
40397
+ window.removeEventListener('clearChartState', handleClearChartState);
40398
+ };
40399
+ }, [widget.id, appendMessage, setChartState, startLoadingTimeout]);
40400
+ 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(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) &&
40401
+ (!((_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))
40402
+ ? (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)) })) })] }));
40403
+ }
40404
+ function DatagridWidget({ widget, showHeader = true, widgetBackendUrl, onResetReady, widgetIds, datasetId, widgetData, }) {
40405
+ var _a, _b;
40406
+ const styles = getStyleValues((_a = widget.config) === null || _a === void 0 ? void 0 : _a.styles);
40407
+ const getRuntimeUrl = () => {
40408
+ var _a;
40409
+ const baseUrl = widgetBackendUrl || '';
40410
+ const agentName = ((_a = widget.config) === null || _a === void 0 ? void 0 : _a.agentName) || 'default-agent';
40411
+ return `${baseUrl}/api/copilot/${agentName}`;
40412
+ };
40413
+ return (jsxRuntimeExports.jsx(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 }) }));
40414
+ }
40415
+
40416
+ function WidgetRenderer({ widget, isTemplate = false, onConfigUpdate, widgetBackendUrl, onResetReady, widgetIds, datasetId, }) {
40417
+ const handleConfigUpdate = (config) => {
40418
+ if (onConfigUpdate) {
40419
+ onConfigUpdate(widget.id, config);
40420
+ }
40421
+ };
40422
+ getWidgetStyles(widget);
40423
+ const renderWidget = () => {
40424
+ switch (widget.type) {
40425
+ // Search-related widget cases removed
40426
+ // Available widgets
40427
+ case "header":
40428
+ return jsxRuntimeExports.jsx(HeaderWidget, { widget: widget, showHeader: false });
40429
+ case "footer":
40430
+ return jsxRuntimeExports.jsx(FooterWidget, { widget: widget, showHeader: false });
40431
+ case "text":
40432
+ return jsxRuntimeExports.jsx(TextWidget, { widget: widget, showHeader: false });
40433
+ case "spacer":
40434
+ return jsxRuntimeExports.jsx(SpacerWidget, { widget: widget, showHeader: false });
40435
+ case "divider":
40436
+ return jsxRuntimeExports.jsx(DividerWidget, { widget: widget, showHeader: false });
40437
+ case "facet":
40438
+ return (jsxRuntimeExports.jsx(FacetWidget, { widget: widget, showHeader: false, onConfigUpdate: handleConfigUpdate }));
40439
+ case "chatbot":
40440
+ return jsxRuntimeExports.jsx(ChatbotWidget, { widget: widget, showHeader: false, widgetBackendUrl: widgetBackendUrl, onResetReady: onResetReady, widgetIds: widgetIds, datasetId: datasetId });
40441
+ case "agent":
40442
+ 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 }));
39168
40443
  default:
39169
40444
  return (jsxRuntimeExports.jsxs("div", { className: "text-muted-foreground", children: ["Unknown widget type: ", widget.type] }));
39170
40445
  }