@burdenoff/microfe-bigconsole 2026.1004.3 → 2026.1004.4

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 (150) hide show
  1. package/dist/bigconsole/BigConsoleRoutes.d.ts +1 -1
  2. package/dist/bigconsole/BigConsoleRoutes.d.ts.map +1 -1
  3. package/dist/bigconsole/BigConsoleRoutes.js +15 -1
  4. package/dist/bigconsole/BigConsoleRoutes.js.map +1 -1
  5. package/dist/bigconsole/components/DrilldownModal.d.ts.map +1 -1
  6. package/dist/bigconsole/components/DrilldownModal.js +54 -53
  7. package/dist/bigconsole/components/DrilldownModal.js.map +1 -1
  8. package/dist/bigconsole/components/builder/inspector/DataBindingSection.d.ts +3 -1
  9. package/dist/bigconsole/components/builder/inspector/DataBindingSection.d.ts.map +1 -1
  10. package/dist/bigconsole/components/builder/inspector/DataBindingSection.js +40 -39
  11. package/dist/bigconsole/components/builder/inspector/DataBindingSection.js.map +1 -1
  12. package/dist/bigconsole/components/dashboard/DashboardCanvas.d.ts.map +1 -1
  13. package/dist/bigconsole/components/dashboard/DashboardCanvas.js +184 -177
  14. package/dist/bigconsole/components/dashboard/DashboardCanvas.js.map +1 -1
  15. package/dist/bigconsole/components/dashboard/DashboardGrid.d.ts.map +1 -1
  16. package/dist/bigconsole/components/dashboard/DashboardGrid.js +40 -22
  17. package/dist/bigconsole/components/dashboard/DashboardGrid.js.map +1 -1
  18. package/dist/bigconsole/components/dashboard/ExportDashboardDialog.d.ts.map +1 -1
  19. package/dist/bigconsole/components/dashboard/ExportDashboardDialog.js +31 -25
  20. package/dist/bigconsole/components/dashboard/ExportDashboardDialog.js.map +1 -1
  21. package/dist/bigconsole/components/dashboard/GlobalFiltersBar/FilterEditor.d.ts +1 -1
  22. package/dist/bigconsole/components/dashboard/GlobalFiltersBar/FilterEditor.d.ts.map +1 -1
  23. package/dist/bigconsole/components/dashboard/GlobalFiltersBar/FilterEditor.js +115 -80
  24. package/dist/bigconsole/components/dashboard/GlobalFiltersBar/FilterEditor.js.map +1 -1
  25. package/dist/bigconsole/components/dashboard/GlobalFiltersBar/GlobalFiltersBar.d.ts.map +1 -1
  26. package/dist/bigconsole/components/dashboard/GlobalFiltersBar/GlobalFiltersBar.js +177 -146
  27. package/dist/bigconsole/components/dashboard/GlobalFiltersBar/GlobalFiltersBar.js.map +1 -1
  28. package/dist/bigconsole/components/dashboard/ShareDialog/ShareDialog.d.ts +1 -1
  29. package/dist/bigconsole/components/dashboard/ShareDialog/ShareDialog.d.ts.map +1 -1
  30. package/dist/bigconsole/components/dashboard/ShareDialog/ShareDialog.js +375 -325
  31. package/dist/bigconsole/components/dashboard/ShareDialog/ShareDialog.js.map +1 -1
  32. package/dist/bigconsole/components/datasink/CacheTTLSelector.d.ts.map +1 -1
  33. package/dist/bigconsole/components/datasink/CacheTTLSelector.js +7 -1
  34. package/dist/bigconsole/components/datasink/CacheTTLSelector.js.map +1 -1
  35. package/dist/bigconsole/components/parser/ParserSelector.d.ts +3 -1
  36. package/dist/bigconsole/components/parser/ParserSelector.d.ts.map +1 -1
  37. package/dist/bigconsole/components/parser/ParserSelector.js +94 -94
  38. package/dist/bigconsole/components/parser/ParserSelector.js.map +1 -1
  39. package/dist/bigconsole/components/pipeline/PipelineCard.d.ts.map +1 -1
  40. package/dist/bigconsole/components/pipeline/PipelineCard.js +111 -89
  41. package/dist/bigconsole/components/pipeline/PipelineCard.js.map +1 -1
  42. package/dist/bigconsole/components/pipeline/PipelineScopePicker.d.ts +8 -0
  43. package/dist/bigconsole/components/pipeline/PipelineScopePicker.d.ts.map +1 -0
  44. package/dist/bigconsole/components/pipeline/PipelineScopePicker.js +52 -0
  45. package/dist/bigconsole/components/pipeline/PipelineScopePicker.js.map +1 -0
  46. package/dist/bigconsole/components/widgets/PropertiesPanel.d.ts.map +1 -1
  47. package/dist/bigconsole/components/widgets/PropertiesPanel.js +257 -221
  48. package/dist/bigconsole/components/widgets/PropertiesPanel.js.map +1 -1
  49. package/dist/bigconsole/components/widgets/WidgetHeader.d.ts +1 -0
  50. package/dist/bigconsole/components/widgets/WidgetHeader.d.ts.map +1 -1
  51. package/dist/bigconsole/components/widgets/WidgetHeader.js +29 -29
  52. package/dist/bigconsole/components/widgets/WidgetHeader.js.map +1 -1
  53. package/dist/bigconsole/components/widgets/WidgetWrapper.d.ts +2 -0
  54. package/dist/bigconsole/components/widgets/WidgetWrapper.d.ts.map +1 -1
  55. package/dist/bigconsole/components/widgets/WidgetWrapper.js +247 -239
  56. package/dist/bigconsole/components/widgets/WidgetWrapper.js.map +1 -1
  57. package/dist/bigconsole/components/widgets/metric-card/MetricCardWidget.d.ts.map +1 -1
  58. package/dist/bigconsole/components/widgets/metric-card/MetricCardWidget.js +6 -4
  59. package/dist/bigconsole/components/widgets/metric-card/MetricCardWidget.js.map +1 -1
  60. package/dist/bigconsole/components/widgets/states/EmptyState.d.ts +1 -0
  61. package/dist/bigconsole/components/widgets/states/EmptyState.d.ts.map +1 -1
  62. package/dist/bigconsole/components/widgets/states/EmptyState.js +4 -4
  63. package/dist/bigconsole/components/widgets/states/EmptyState.js.map +1 -1
  64. package/dist/bigconsole/components/workflow/WorkflowDesignPreview.d.ts +7 -0
  65. package/dist/bigconsole/components/workflow/WorkflowDesignPreview.d.ts.map +1 -0
  66. package/dist/bigconsole/components/workflow/WorkflowDesignPreview.js +94 -0
  67. package/dist/bigconsole/components/workflow/WorkflowDesignPreview.js.map +1 -0
  68. package/dist/bigconsole/components/workflow/WorkflowSinkLinkForm.d.ts +7 -0
  69. package/dist/bigconsole/components/workflow/WorkflowSinkLinkForm.d.ts.map +1 -0
  70. package/dist/bigconsole/components/workflow/WorkflowSinkLinkForm.js +101 -0
  71. package/dist/bigconsole/components/workflow/WorkflowSinkLinkForm.js.map +1 -0
  72. package/dist/bigconsole/hooks/useBigConsoleSettings.d.ts +16 -0
  73. package/dist/bigconsole/hooks/useBigConsoleSettings.d.ts.map +1 -0
  74. package/dist/bigconsole/hooks/useBigConsoleSettings.js +57 -0
  75. package/dist/bigconsole/hooks/useBigConsoleSettings.js.map +1 -0
  76. package/dist/bigconsole/hooks/useDashboardOperations.d.ts.map +1 -1
  77. package/dist/bigconsole/hooks/useDashboardOperations.js +102 -79
  78. package/dist/bigconsole/hooks/useDashboardOperations.js.map +1 -1
  79. package/dist/bigconsole/hooks/useExportDashboard.d.ts +3 -1
  80. package/dist/bigconsole/hooks/useExportDashboard.d.ts.map +1 -1
  81. package/dist/bigconsole/hooks/useExportDashboard.js +23 -13
  82. package/dist/bigconsole/hooks/useExportDashboard.js.map +1 -1
  83. package/dist/bigconsole/hooks/useFilterUrlSync.d.ts +18 -0
  84. package/dist/bigconsole/hooks/useFilterUrlSync.d.ts.map +1 -1
  85. package/dist/bigconsole/hooks/useFilterUrlSync.js +87 -57
  86. package/dist/bigconsole/hooks/useFilterUrlSync.js.map +1 -1
  87. package/dist/bigconsole/hooks/useGlobalFilters.d.ts.map +1 -1
  88. package/dist/bigconsole/hooks/useGlobalFilters.js +39 -29
  89. package/dist/bigconsole/hooks/useGlobalFilters.js.map +1 -1
  90. package/dist/bigconsole/hooks/usePageOperations.d.ts.map +1 -1
  91. package/dist/bigconsole/hooks/usePageOperations.js +1 -0
  92. package/dist/bigconsole/hooks/usePageOperations.js.map +1 -1
  93. package/dist/bigconsole/hooks/usePipelineOperations.d.ts.map +1 -1
  94. package/dist/bigconsole/hooks/usePipelineOperations.js +114 -112
  95. package/dist/bigconsole/hooks/usePipelineOperations.js.map +1 -1
  96. package/dist/bigconsole/hooks/useShareRecipients.d.ts +22 -0
  97. package/dist/bigconsole/hooks/useShareRecipients.d.ts.map +1 -0
  98. package/dist/bigconsole/hooks/useShareRecipients.js +198 -0
  99. package/dist/bigconsole/hooks/useShareRecipients.js.map +1 -0
  100. package/dist/bigconsole/pages/DashboardBuilderPage.d.ts.map +1 -1
  101. package/dist/bigconsole/pages/DashboardBuilderPage.js +198 -193
  102. package/dist/bigconsole/pages/DashboardBuilderPage.js.map +1 -1
  103. package/dist/bigconsole/pages/DashboardViewPage.d.ts.map +1 -1
  104. package/dist/bigconsole/pages/DashboardViewPage.js +171 -167
  105. package/dist/bigconsole/pages/DashboardViewPage.js.map +1 -1
  106. package/dist/bigconsole/pages/DashboardsPage.d.ts.map +1 -1
  107. package/dist/bigconsole/pages/DashboardsPage.js +313 -266
  108. package/dist/bigconsole/pages/DashboardsPage.js.map +1 -1
  109. package/dist/bigconsole/pages/DataSinkBuilderPage.d.ts.map +1 -1
  110. package/dist/bigconsole/pages/DataSinkBuilderPage.js +84 -79
  111. package/dist/bigconsole/pages/DataSinkBuilderPage.js.map +1 -1
  112. package/dist/bigconsole/pages/DataSinkViewPage.d.ts.map +1 -1
  113. package/dist/bigconsole/pages/DataSinkViewPage.js +267 -257
  114. package/dist/bigconsole/pages/DataSinkViewPage.js.map +1 -1
  115. package/dist/bigconsole/pages/InsightsPage.d.ts.map +1 -1
  116. package/dist/bigconsole/pages/InsightsPage.js +465 -402
  117. package/dist/bigconsole/pages/InsightsPage.js.map +1 -1
  118. package/dist/bigconsole/pages/PipelineBuilderPage.d.ts.map +1 -1
  119. package/dist/bigconsole/pages/PipelineBuilderPage.js +169 -157
  120. package/dist/bigconsole/pages/PipelineBuilderPage.js.map +1 -1
  121. package/dist/bigconsole/pages/PipelineViewPage.d.ts.map +1 -1
  122. package/dist/bigconsole/pages/PipelineViewPage.js +370 -230
  123. package/dist/bigconsole/pages/PipelineViewPage.js.map +1 -1
  124. package/dist/bigconsole/pages/PipelinesPage.d.ts.map +1 -1
  125. package/dist/bigconsole/pages/PipelinesPage.js +181 -151
  126. package/dist/bigconsole/pages/PipelinesPage.js.map +1 -1
  127. package/dist/bigconsole/pages/SettingsPage.d.ts.map +1 -1
  128. package/dist/bigconsole/pages/SettingsPage.js +188 -208
  129. package/dist/bigconsole/pages/SettingsPage.js.map +1 -1
  130. package/dist/bigconsole/pages/WidgetDemoPage.d.ts.map +1 -1
  131. package/dist/bigconsole/pages/WidgetDemoPage.js +134 -117
  132. package/dist/bigconsole/pages/WidgetDemoPage.js.map +1 -1
  133. package/dist/bigconsole/pages/WorkflowViewPage.d.ts.map +1 -1
  134. package/dist/bigconsole/pages/WorkflowViewPage.js +315 -267
  135. package/dist/bigconsole/pages/WorkflowViewPage.js.map +1 -1
  136. package/dist/bigconsole/pages/WorkflowsPage.d.ts.map +1 -1
  137. package/dist/bigconsole/pages/WorkflowsPage.js +4 -3
  138. package/dist/bigconsole/pages/WorkflowsPage.js.map +1 -1
  139. package/dist/bigconsole/types/index.d.ts +4 -0
  140. package/dist/bigconsole/types/index.d.ts.map +1 -1
  141. package/dist/generated/wspace-operations.d.ts +148 -0
  142. package/dist/generated/wspace-operations.d.ts.map +1 -1
  143. package/dist/generated/wspace-operations.js +172 -133
  144. package/dist/generated/wspace-operations.js.map +1 -1
  145. package/dist/generated/wspace-types.d.ts +21 -0
  146. package/dist/generated/wspace-types.d.ts.map +1 -1
  147. package/dist/generated/wspace-types.js.map +1 -1
  148. package/dist/microfe-bigconsole.css +1 -1
  149. package/dist/translations/en.d.ts.map +1 -1
  150. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"WidgetWrapper.js","names":[],"sources":["../../../../src/bigconsole/components/widgets/WidgetWrapper.tsx"],"sourcesContent":["/**\n * WidgetWrapper Component (v2.1)\n *\n * Common wrapper for all widget types. Handles:\n * - Header with title and menu\n * - Loading, error, and empty states\n * - Selection highlighting\n * - Edit mode controls\n * - Real data only — no mock fallback; widgets show empty state when data is missing\n * - v2.0: Multi-renderer support via WidgetRendererFactory\n * - v2.0: Widget actions support\n */\n\nimport {\n type FC,\n type ReactNode,\n type RefObject,\n useCallback,\n memo,\n useMemo,\n useRef,\n useState,\n useEffect,\n lazy,\n Suspense,\n} from 'react';\nimport type { Widget } from '../../types';\nimport {\n useWidgetStore,\n useDashboardStore,\n useIsWidgetSelected,\n useWidgetUIState,\n useGlobalFilterValues,\n} from '../../store';\nimport {\n useWidgetAutoRefresh,\n formatTimeUntilRefresh,\n useWidgetExport,\n useDrilldown,\n useWidgetData,\n useWidgetComments,\n type DrilldownContext,\n} from '../../hooks';\nimport { useApolloClient } from '@apollo/client/react';\nimport { GetDashboardDocument } from '../../../generated/wspace-operations';\nimport { getWidgetDefinition } from './WidgetRegistry';\nimport { resolveTextData } from './text-widget/textData';\nimport { WidgetHeader } from './WidgetHeader';\nimport { WidgetLoadingState } from './states/LoadingState';\nimport { WidgetErrorState } from './states/ErrorState';\nimport { WidgetEmptyState } from './states/EmptyState';\nimport { WidgetErrorBoundary } from './WidgetErrorBoundary';\nimport { hasRenderableCustomConfig, hasCustomIframeConfig } from './custom/config';\nimport { getBindingForWidget } from '../../utils/widgetBinding';\n\n// v2.0: Renderer factory and actions\nimport { WidgetRendererFactory } from '../../renderers/factory/WidgetRendererFactory';\nimport { WidgetActions } from './widget-actions';\nimport type { WidgetAction, ActionContext, ActionResult, RendererType } from '../../renderers/types/renderer';\n// Widget components - lazy loaded for better code splitting\n// Each widget loads only when its type is rendered\nconst MetricCardWidget = lazy(() => import('./metric-card').then((m) => ({ default: m.MetricCardWidget })));\nconst ChartWidget = lazy(() => import('./chart').then((m) => ({ default: m.ChartWidget })));\nconst TableWidget = lazy(() => import('./table').then((m) => ({ default: m.TableWidget })));\nconst PivotTableWidget = lazy(() => import('./pivot-table').then((m) => ({ default: m.PivotTableWidget })));\nconst GaugeWidget = lazy(() => import('./gauge').then((m) => ({ default: m.GaugeWidget })));\nconst ProgressWidget = lazy(() => import('./progress').then((m) => ({ default: m.ProgressWidget })));\nconst ListWidget = lazy(() => import('./list').then((m) => ({ default: m.ListWidget })));\nconst HeatmapWidget = lazy(() => import('./heatmap').then((m) => ({ default: m.HeatmapWidget })));\nconst RetentionWidget = lazy(() => import('./retention').then((m) => ({ default: m.RetentionWidget })));\nconst CalendarWidget = lazy(() => import('./calendar').then((m) => ({ default: m.CalendarWidget })));\nconst KanbanWidget = lazy(() => import('./kanban').then((m) => ({ default: m.KanbanWidget })));\nconst TimelineWidget = lazy(() => import('./timeline').then((m) => ({ default: m.TimelineWidget })));\nconst KPIComparisonWidget = lazy(() => import('./kpi-comparison').then((m) => ({ default: m.KPIComparisonWidget })));\nconst TextWidget = lazy(() => import('./text-widget').then((m) => ({ default: m.TextWidget })));\nconst MapWidget = lazy(() => import('./map-widget').then((m) => ({ default: m.MapWidget })));\nconst IframeWidget = lazy(() => import('./iframe-widget').then((m) => ({ default: m.IframeWidget })));\nconst CustomWidget = lazy(() => import('./custom').then((m) => ({ default: m.CustomWidget })));\n// AdaptiveCardWidget is HUGE (984KB) - lazy load only when 'adaptive_card' type is used\nconst AdaptiveCardWidget = lazy(() => import('./adaptive-card').then((m) => ({ default: m.AdaptiveCardWidget })));\nconst FormWidget = lazy(() => import('./form').then((m) => ({ default: m.FormWidget })));\n// Comments panel - lazy loaded; only mounts when the user opens comments\nconst WidgetComments = lazy(() => import('./comments/WidgetComments').then((m) => ({ default: m.WidgetComments })));\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface WidgetWrapperProps {\n /** The widget data */\n widget: Widget;\n /** Widget content to render */\n children?: ReactNode;\n /** Data for the widget */\n data?: Record<string, unknown> | null;\n /** Custom class name */\n className?: string;\n /** Whether the widget is loading */\n isLoading?: boolean;\n /** Error message */\n error?: string | null;\n /** Callback to refresh widget data */\n onRefresh?: () => Promise<void>;\n /** Callback for drilldown navigation */\n onDrilldown?: (params: Record<string, unknown>) => void;\n /** v2.0: Widget actions */\n actions?: WidgetAction[];\n /** v2.0: Callback for action events */\n onAction?: (action: WidgetAction, context: ActionContext) => Promise<ActionResult | void>;\n /** Phase 2: Global filter values to apply to widget data */\n filterValues?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Custom comparison for memo - ensures actions changes trigger re-render\n// ============================================================================\n\nfunction arePropsEqual(prevProps: WidgetWrapperProps, nextProps: WidgetWrapperProps): boolean {\n // Always re-render if widget ID changes\n if (prevProps.widget.id !== nextProps.widget.id) return false;\n // Re-render if widget was updated\n if (prevProps.widget.updatedAt !== nextProps.widget.updatedAt) return false;\n // Re-render if loading state changes\n if (prevProps.isLoading !== nextProps.isLoading) return false;\n // Re-render if error changes\n if (prevProps.error !== nextProps.error) return false;\n // Action IDs survive edits. Compare the immutable list so label, appearance,\n // confirmation and visibility changes reach the canvas immediately after save.\n if (prevProps.actions !== nextProps.actions) return false;\n // Also check data changes\n if (prevProps.data !== nextProps.data) return false;\n // Phase 2: Re-render if filter values changed\n if (JSON.stringify(prevProps.filterValues) !== JSON.stringify(nextProps.filterValues)) return false;\n return true;\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nexport const WidgetWrapper: FC<WidgetWrapperProps> = memo(function WidgetWrapper({\n widget,\n children,\n data,\n className = '',\n isLoading: isLoadingProp,\n error: errorProp,\n onRefresh,\n onDrilldown,\n actions,\n onAction,\n filterValues,\n}) {\n // Store state - use Dashboard store for edit mode (synced with toolbar)\n const isEditMode = useDashboardStore((state) => state.viewMode === 'edit');\n const selectWidget = useWidgetStore((state) => state.selectWidget);\n const isSelected = useIsWidgetSelected(widget.id);\n const uiState = useWidgetUIState(widget.id);\n const globalFilterValues = useGlobalFilterValues();\n const apolloClient = useApolloClient();\n\n // Map a global-filter's id -> the data field it targets (`config.field`).\n // Global CATEGORY/TEXT filter values are keyed in the store by filter id (a\n // UUID), not by the data column they filter. Without this map, applyClientFilters\n // can only fall back to value/heuristic matching, which fails to narrow rows\n // whose targeted column (e.g. `country`, `cohort`) isn't in the hardcoded\n // heuristic list — so a selected Country/Cohort would not actually filter the\n // widget. We resolve the targeted field from the dashboard's globalFilters\n // (already in the Apollo cache from the page load) so a UUID-keyed filter\n // matches the row's configured field exactly.\n const widgetDashboardId = (widget as unknown as Record<string, unknown>).dashboardId as string | undefined;\n const filterFieldMap = useMemo<Record<string, string>>(() => {\n if (!widgetDashboardId) return {};\n try {\n const cached = apolloClient.readQuery<{\n getDashboard?: {\n globalFilters?: Array<{ id: string; config?: Record<string, unknown> | null }>;\n };\n }>({ query: GetDashboardDocument, variables: { id: widgetDashboardId } });\n const map: Record<string, string> = {};\n for (const f of cached?.getDashboard?.globalFilters ?? []) {\n const field = f.config?.field;\n if (typeof field === 'string' && field) map[f.id] = field;\n }\n return map;\n } catch {\n return {};\n }\n }, [apolloClient, widgetDashboardId]);\n\n // Fetch per-widget data from backend (parser-processed data)\n // This is needed because listWidgetsByDashboard uses WidgetListFields (without data)\n // for performance, so each widget fetches its own data individually\n const widgetBinding = useMemo(() => getBindingForWidget(widget), [widget]);\n const hasDataSource =\n widgetBinding.source.kind !== 'DATASINK' ||\n !!widgetBinding.source.ref ||\n !!widgetBinding.parserId ||\n !!widget.datasetId;\n const { data: fetchedWidgetData, loading: widgetDataLoading } = useWidgetData(widget.id, {\n skip: !hasDataSource,\n pollInterval: (widget.refreshInterval ?? 0) * 1000 || 0,\n });\n\n // WORKAROUND: If Zustand store is empty, directly read filter_* params from URL\n // This handles race conditions where the store hasn't been populated yet\n const urlFilterValues = useMemo(() => {\n if (typeof window === 'undefined') return {};\n\n const params = new URLSearchParams(window.location.search);\n const filters: Record<string, unknown> = {};\n\n params.forEach((value, key) => {\n if (key.startsWith('filter_')) {\n const filterId = key.slice('filter_'.length);\n // Skip internal metadata keys\n if (!filterId.startsWith('__')) {\n filters[filterId] = value;\n }\n }\n });\n\n return filters;\n }, []);\n\n // Phase 2: Merge global filter values (from URL) with explicit filterValues prop\n // This ensures both URL params (filter_*) and drilldown params work together\n const mergedFilterValues = useMemo(() => {\n const merged: Record<string, unknown> = {};\n\n // First, add URL filter values as fallback (in case Zustand store hasn't loaded yet)\n if (urlFilterValues && Object.keys(urlFilterValues).length > 0) {\n Object.assign(merged, urlFilterValues);\n }\n\n // Then, add global filter values from Zustand store (if populated)\n if (globalFilterValues && Object.keys(globalFilterValues).length > 0) {\n Object.assign(merged, globalFilterValues);\n }\n\n // Finally, add/override with explicit filterValues prop (e.g., from drilldown modal)\n if (filterValues && Object.keys(filterValues).length > 0) {\n Object.assign(merged, filterValues);\n }\n\n return merged;\n }, [urlFilterValues, globalFilterValues, filterValues]);\n\n // Track active filters (client-side filtering until backend supports it)\n const hasFilters = Object.keys(mergedFilterValues).length > 0;\n\n // Merge loading/error from props and store\n // Show loading if widget data is being fetched for the first time (no data yet)\n const isLoading = isLoadingProp ?? (widgetDataLoading && !fetchedWidgetData) ?? uiState.isLoading;\n const error = errorProp ?? uiState.errorMessage;\n\n // Get widget definition\n const definition = getWidgetDefinition(widget.type);\n\n // Stable refresh callback - use ref to avoid creating new function on each render\n const onRefreshRef = useRef(onRefresh);\n useEffect(() => {\n onRefreshRef.current = onRefresh;\n }, [onRefresh]);\n\n const stableOnRefresh = useCallback(async () => {\n if (onRefreshRef.current) {\n await onRefreshRef.current();\n }\n }, []);\n\n // Auto-refresh\n const { timeUntilRefresh, isPaused } = useWidgetAutoRefresh({\n widgetId: widget.id,\n refreshInterval: widget.refreshInterval,\n onRefresh: stableOnRefresh,\n enabled: !isEditMode && !!widget.refreshInterval,\n });\n\n // Container ref for PNG export\n const containerRef = useRef<HTMLDivElement>(null);\n\n // Comments panel. The count query stays disabled until the panel is first\n // opened, so a dashboard of N widgets doesn't fire N comment queries on load.\n const [showComments, setShowComments] = useState(false);\n const [commentsEverOpened, setCommentsEverOpened] = useState(false);\n const { count: commentCount } = useWidgetComments(widget.id, commentsEverOpened);\n const toggleComments = useCallback(() => {\n setShowComments((open) => {\n const next = !open;\n if (next) setCommentsEverOpened(true);\n return next;\n });\n }, []);\n\n // Get widget data for export (computed early for hook)\n const exportData = useMemo(() => {\n if (data && Array.isArray(data)) return data;\n const rawData = (widget as unknown as Record<string, unknown>).data as Record<string, unknown> | undefined;\n if (rawData?.processed && Array.isArray(rawData.processed)) {\n return rawData.processed;\n }\n if (rawData?.raw) {\n const parsed = typeof rawData.raw === 'string' ? JSON.parse(rawData.raw) : rawData.raw;\n if (Array.isArray(parsed)) return parsed;\n }\n return null;\n }, [data, widget]);\n\n // Export functionality\n const { exportCSV, exportPNG } = useWidgetExport(widget, {\n data: exportData,\n containerRef: containerRef as unknown as RefObject<HTMLElement>,\n });\n\n // Helper to check if data is actually usable (has real content)\n const isUsableData = useCallback((d: unknown): boolean => {\n if (d === null || d === undefined) return false;\n if (Array.isArray(d)) return d.length > 0;\n if (typeof d === 'object') {\n const obj = d as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length === 0) return false;\n // Check recursively for actual data content\n return keys.some((key) => {\n const val = obj[key];\n if (val === null || val === undefined || val === '') return false;\n if (Array.isArray(val)) return val.length > 0;\n if (typeof val === 'object') return isUsableData(val);\n return true;\n });\n }\n return true;\n }, []);\n\n // Phase 2: Client-side filter function for widget data\n const applyClientFilters = useCallback(\n (\n widgetData: Record<string, unknown> | Record<string, unknown>[]\n ): Record<string, unknown> | Record<string, unknown>[] => {\n if (!hasFilters || !widgetData) return widgetData;\n\n // Separate drilldown context filters (ctx_*) from regular filters\n const contextFilters: Record<string, unknown> = {};\n const regularFilters: Record<string, unknown> = {};\n\n Object.entries(mergedFilterValues || {}).forEach(([key, value]) => {\n if (key.startsWith('ctx_')) {\n // Strip ctx_ prefix to get the target field name\n const fieldName = key.slice(4); // Remove 'ctx_'\n contextFilters[fieldName] = value;\n } else if (!key.startsWith('__')) {\n // Skip internal metadata keys (__drilldown_depth, etc.)\n regularFilters[key] = value;\n }\n });\n\n // Helper to match a value against a filter (case-insensitive)\n const matchesFilter = (itemValue: unknown, filterValue: unknown): boolean => {\n if (filterValue === undefined || filterValue === null || filterValue === '') return true;\n if (itemValue === undefined || itemValue === null) return false;\n\n const itemStr = String(itemValue).toLowerCase();\n const filterStr = String(filterValue).toLowerCase();\n\n // Exact match or contains\n return itemStr === filterStr || itemStr.includes(filterStr);\n };\n\n // Helper to find a matching field in the item (case-insensitive key matching)\n const findFieldValue = (item: Record<string, unknown>, targetField: string): unknown => {\n const targetLower = targetField.toLowerCase();\n\n // Try exact match first\n if (item[targetField] !== undefined) return item[targetField];\n\n // Try case-insensitive match\n const matchingKey = Object.keys(item).find((k) => k.toLowerCase() === targetLower);\n if (matchingKey) return item[matchingKey];\n\n // Try partial match (e.g., 'region' matches 'regionName' or 'user_region')\n const partialMatch = Object.keys(item).find(\n (k) => k.toLowerCase().includes(targetLower) || targetLower.includes(k.toLowerCase())\n );\n if (partialMatch) return item[partialMatch];\n\n // Try stripping common prefixes from target field (e.g., 'kpiId' -> 'id', 'rowName' -> 'name')\n // This handles drilldown context where widget passes 'kpiId' but data has 'id'\n const commonPrefixes = ['kpi', 'row', 'item', 'data', 'cell', 'record', 'entry'];\n for (const prefix of commonPrefixes) {\n if (targetLower.startsWith(prefix) && targetLower.length > prefix.length) {\n const strippedField = targetLower.slice(prefix.length);\n // Try exact match with stripped field\n const strippedMatch = Object.keys(item).find((k) => k.toLowerCase() === strippedField);\n if (strippedMatch) return item[strippedMatch];\n }\n }\n\n return undefined;\n };\n\n // Helper function to filter an array of items\n const filterItems = (items: Record<string, unknown>[]): Record<string, unknown>[] => {\n return items.filter((item: Record<string, unknown>) => {\n // Only object rows are field-filterable. An array of primitives (e.g.\n // a heatmap's `rows: [\"5W-MedSurg\", …]`) carries no named fields — keep\n // every element. Without this, `findFieldValue` indexes into the string\n // by character offset and spuriously \"matches\" a filter, dropping rows.\n if (item === null || typeof item !== 'object' || Array.isArray(item)) {\n return true;\n }\n // First, apply drilldown context filters (ctx_*) - these have explicit field names\n for (const [fieldName, filterValue] of Object.entries(contextFilters)) {\n if (filterValue === undefined || filterValue === null || filterValue === '') continue;\n\n const itemValue = findFieldValue(item, fieldName);\n // If the field doesn't exist in this data item, skip this context filter.\n // Drilldown context params (e.g., source=support_status) are metadata about\n // the drilldown origin and should NOT filter out data when the target\n // dashboard's widgets don't have a matching field.\n if (itemValue === undefined) continue;\n if (!matchesFilter(itemValue, filterValue)) {\n return false;\n }\n }\n\n // Then, apply regular filters\n for (const [filterKey, filterValue] of Object.entries(regularFilters)) {\n if (filterValue === undefined || filterValue === null || filterValue === '') continue;\n\n // For date range filters\n if (typeof filterValue === 'object') {\n const fv = filterValue as Record<string, unknown>;\n if (fv.start || fv.end) {\n const dateFields = Object.entries(item).filter(\n ([k, _v]) => k.toLowerCase().includes('date') || k.toLowerCase().includes('time')\n );\n if (dateFields.length > 0) {\n const itemDate = new Date(dateFields[0][1] as string);\n if (fv.start && itemDate < new Date(fv.start as string)) return false;\n if (fv.end && itemDate > new Date(fv.end as string)) return false;\n }\n continue;\n }\n }\n\n // For numeric range filters\n if (typeof filterValue === 'object') {\n const nv = filterValue as Record<string, unknown>;\n if (nv.min !== undefined || nv.max !== undefined) {\n const numericFields = Object.entries(item).filter(([_k, v]) => typeof v === 'number');\n if (numericFields.length > 0) {\n const itemNum = numericFields[0][1] as number;\n if (nv.min !== undefined && itemNum < (nv.min as number)) return false;\n if (nv.max !== undefined && itemNum > (nv.max as number)) return false;\n }\n continue;\n }\n }\n\n // Any other object-shaped filter value (e.g. a DATE_RANGE filter set\n // to a preset like { preset: \"last_30_days\" } with no resolved\n // start/end, or a structured value we don't understand) cannot be\n // compared with the scalar matchers below. Passing it through would\n // stringify it to \"[object Object]\" and, via fuzzy field matching\n // (e.g. an `enrolledAt` filter partial-matching an `enrolled` number\n // column), spuriously exclude EVERY row. Treat such values as a no-op\n // for client-side filtering — the row set is unchanged until the\n // filter resolves to concrete start/end or scalar values.\n if (filterValue !== null && typeof filterValue === 'object' && !Array.isArray(filterValue)) {\n continue;\n }\n\n // Global CATEGORY/TEXT filters are keyed by filter id (UUID). Resolve\n // the data column they target from the filter's config.field. When the\n // widget's rows carry that column, the filter is authoritative — a\n // mismatch excludes the row; a missing column is a no-op (the filter\n // simply doesn't apply to this widget's shape). This is what makes a\n // selected Country/Cohort actually narrow the visible data.\n const targetField = filterFieldMap[filterKey];\n if (targetField) {\n const mappedValue = findFieldValue(item, targetField);\n if (mappedValue !== undefined) {\n if (!matchesFilter(mappedValue, filterValue)) {\n return false;\n }\n continue;\n }\n // Configured field absent from this widget's rows → filter is a\n // no-op for this widget (do not fall through to value heuristics,\n // which could spuriously match an unrelated column).\n continue;\n }\n\n // Try to match by filter key name first (for named filters). When\n // the widget's data actually carries the filter's field, the filter\n // is authoritative — a mismatch excludes the row.\n const fieldValue = findFieldValue(item, filterKey);\n if (fieldValue !== undefined) {\n if (!matchesFilter(fieldValue, filterValue)) {\n return false;\n }\n continue;\n }\n\n // For text/category filters - try multiple matching strategies\n const filterStr = String(filterValue).toLowerCase();\n\n // Strategy 1: Check all field values for exact or partial match\n const itemValues = Object.values(item).map((v) => String(v).toLowerCase());\n const hasMatch = itemValues.some((v) => v === filterStr || v.includes(filterStr));\n\n if (!hasMatch) {\n // Strategy 2: Try to find a field name that matches the filter value context\n const fieldNames = Object.keys(item).map((k) => k.toLowerCase());\n const possibleFields = fieldNames.filter(\n (f) =>\n f.includes('category') ||\n f.includes('type') ||\n f.includes('status') ||\n f.includes('name') ||\n f.includes('region') ||\n f.includes('group')\n );\n\n let fieldMatch = false;\n for (const fieldName of possibleFields) {\n const originalKey = Object.keys(item).find((k) => k.toLowerCase() === fieldName);\n if (originalKey) {\n const itemFieldValue = String(item[originalKey]).toLowerCase();\n if (itemFieldValue === filterStr || itemFieldValue.includes(filterStr)) {\n fieldMatch = true;\n break;\n }\n }\n }\n\n // The filter's field is NOT present in this dataset (named-field\n // lookup failed AND no value/heuristic match). A global filter that\n // doesn't apply to a widget's shape must be a no-op for that widget\n // — not a silent \"exclude every row\". This mirrors the ctx_* rule\n // above (skip when the targeted field is absent). Without this, an\n // always-active required filter (e.g. campus=main) blanks every\n // parser-derived widget whose output has no campus column.\n if (!fieldMatch) {\n continue;\n }\n }\n }\n return true;\n });\n };\n\n // If data is an array, filter the items directly\n if (Array.isArray(widgetData)) {\n const filtered = filterItems(widgetData);\n return filtered;\n }\n\n // Handle object with array properties (rows, items, members, questions, data, etc.)\n if (widgetData && typeof widgetData === 'object') {\n // Common array property names in widget data\n const arrayPropertyNames = [\n 'kpis', // KPI Comparison widget\n 'rows', // Table widget\n 'items', // List widget\n 'members', // Team/member widgets\n 'questions', // Form widget\n 'data', // Generic data\n 'records', // Database-style data\n 'results', // Search/query results\n 'entries', // Log/feed entries\n 'list', // Generic list\n 'values', // Value arrays\n 'series', // Chart series\n 'datasets', // Chart datasets\n ];\n\n for (const propName of arrayPropertyNames) {\n if (widgetData[propName] && Array.isArray(widgetData[propName])) {\n const filteredArray = filterItems(widgetData[propName]);\n return {\n ...widgetData,\n [propName]: filteredArray,\n ...(propName === 'rows' ? { totalRows: filteredArray.length } : {}),\n };\n }\n }\n\n // If no known array property found, check for any array property\n const arrayProps = Object.entries(widgetData).filter(([_key, v]) => Array.isArray(v));\n if (arrayProps.length > 0) {\n const [propName, propValue] = arrayProps[0];\n const filteredArray = filterItems(propValue as Record<string, unknown>[]);\n return {\n ...widgetData,\n [propName]: filteredArray,\n };\n }\n }\n\n // For non-filterable data, return as-is\n return widgetData;\n },\n [hasFilters, mergedFilterValues, widget.id, filterFieldMap]\n );\n\n // Get widget data from the widget itself (fetched from backend)\n const realWidgetData = useMemo(() => {\n let rawWidgetData = null;\n\n // Priority 1: Explicitly passed data prop\n if (data && isUsableData(data)) {\n rawWidgetData = data;\n }\n // Priority 2: Per-widget fetched data (from useWidgetData hook)\n // fetchedWidgetData IS a WidgetData object: { raw, processed, fetchedAt, cached }\n else if (fetchedWidgetData) {\n const fetched = fetchedWidgetData as unknown as Record<string, unknown>;\n if (fetched?.processed && isUsableData(fetched.processed)) {\n rawWidgetData = fetched.processed;\n } else if (fetched?.raw) {\n try {\n const parsed = typeof fetched.raw === 'string' ? JSON.parse(fetched.raw as string) : fetched.raw;\n if (isUsableData(parsed)) rawWidgetData = parsed;\n } catch {\n // Invalid JSON, ignore\n }\n }\n }\n // Priority 3: widget.data from GraphQL response (if already on widget object)\n else {\n const rawData = (widget as unknown as Record<string, unknown>).data as Record<string, unknown> | undefined;\n if (rawData?.processed && isUsableData(rawData.processed)) {\n rawWidgetData = rawData.processed;\n } else if (rawData?.raw) {\n try {\n const parsed = typeof rawData.raw === 'string' ? JSON.parse(rawData.raw) : rawData.raw;\n if (isUsableData(parsed)) rawWidgetData = parsed;\n } catch {\n // Invalid JSON, ignore\n }\n }\n }\n\n // Priority 4: config.mockData — user-configured sample JSON from Widget Properties Data tab\n // This is NOT auto-generated mock data; it's explicit JSON the user pasted in the UI\n if (!rawWidgetData) {\n const configMockData = (widget.config as Record<string, unknown> | undefined)?.mockData;\n if (configMockData) {\n try {\n const parsed = typeof configMockData === 'string' ? JSON.parse(configMockData) : configMockData;\n if (isUsableData(parsed)) {\n rawWidgetData = parsed;\n }\n } catch (e) {}\n }\n }\n\n // Generic parser-output resolution: a widget may bind to a parser whose\n // output is an envelope ({ byUnit:[...], house:{...} }) rather than the\n // exact array/object the renderer wants. config.dataKey / dataPath /\n // seriesPath is a dot-path INTO the resolved data that points at the\n // renderable subtree (e.g. \"byUnit\" for a table, \"rows\" for a chart).\n // Resolving it here keeps every renderer generic — the use-case-specific\n // shape knowledge lives in the widget config (set by the seed/UI), not in\n // the renderer. valueField (single-value metric path) is intentionally NOT\n // applied here: MetricCardWidget resolves it itself against the envelope.\n if (rawWidgetData && typeof rawWidgetData === 'object' && !Array.isArray(rawWidgetData)) {\n const cfg = widget.config as Record<string, unknown> | undefined;\n const pathKey = (cfg?.dataKey ?? cfg?.dataPath ?? cfg?.seriesPath) as string | undefined;\n if (pathKey && typeof pathKey === 'string') {\n const resolved = pathKey.split('.').reduce<unknown>((cur, seg) => {\n return cur && typeof cur === 'object' ? (cur as Record<string, unknown>)[seg] : undefined;\n }, rawWidgetData);\n if (resolved !== undefined && resolved !== null && isUsableData(resolved)) {\n rawWidgetData = resolved as Record<string, unknown>;\n }\n }\n }\n\n // Phase 2: Apply client-side filters if active\n if (hasFilters && rawWidgetData) {\n const filtered = applyClientFilters(rawWidgetData);\n return filtered;\n }\n\n return rawWidgetData;\n }, [data, widget, fetchedWidgetData, hasFilters, applyClientFilters, mergedFilterValues, isUsableData]);\n\n // Final widget data - real data only, no mock fallback\n const widgetData = useMemo(() => {\n return realWidgetData ?? null;\n }, [realWidgetData]);\n\n // Values rendered from a template's embedded sample rather than a connected\n // source. Only possible when no data source is configured, since a real\n // source outranks config.mockData in the resolution chain above.\n const isSampleData = useMemo(() => {\n if (!widgetData || hasDataSource) return false;\n const mock = (widget.config as Record<string, unknown> | undefined)?.mockData;\n return mock !== undefined && mock !== null;\n }, [widgetData, hasDataSource, widget.config]);\n\n // Drilldown navigation (must be after widgetData is defined)\n const { executeDrilldown, canDrilldown } = useDrilldown({\n onDrilldown: (params, _mode) => {\n onDrilldown?.(params);\n },\n });\n\n // Check if widget has drilldown configured\n const hasDrilldown = useMemo(() => canDrilldown(widget), [widget, canDrilldown]);\n\n // Handle drilldown execution with context\n const handleDrilldown = useCallback(\n (selectedData?: Record<string, unknown>) => {\n if (!widget.drilldown?.enabled) return;\n\n const context: DrilldownContext = {\n selectedData: selectedData || {},\n globalFilters: globalFilterValues || {},\n widgetData: widgetData || {},\n metadata: {\n widgetId: widget.id,\n widgetType: widget.type,\n widgetTitle: widget.title,\n },\n sourceDashboardId: widget.dashboardId,\n };\n\n void executeDrilldown(widget.drilldown, context);\n },\n [widget, widgetData, globalFilterValues, executeDrilldown]\n );\n\n // Data clicks drill down only while viewing. In edit mode a click selects\n // the widget; the builder's Preview (view mode) drills down (BOFF-7625).\n const activeDrilldown = hasDrilldown && !isEditMode ? handleDrilldown : undefined;\n\n // Track mouse position to distinguish click from drag\n const mouseDownPos = useRef<{ x: number; y: number } | null>(null);\n const DRAG_THRESHOLD = 5; // pixels - if mouse moves more than this, it's a drag\n\n // Handle mouse down - record position\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n mouseDownPos.current = { x: e.clientX, y: e.clientY };\n }, []);\n\n // Handle widget click - Edit mode only (View mode drilldown is triggered by data clicks)\n // Only trigger if mouse hasn't moved much (not a drag)\n const handleClick = useCallback(\n (e: React.MouseEvent) => {\n e.stopPropagation(); // Prevent DashboardGrid from also handling\n\n // Check if this was a drag (mouse moved significantly)\n if (mouseDownPos.current) {\n const dx = Math.abs(e.clientX - mouseDownPos.current.x);\n const dy = Math.abs(e.clientY - mouseDownPos.current.y);\n if (dx > DRAG_THRESHOLD || dy > DRAG_THRESHOLD) {\n // This was a drag, not a click - don't open config panel\n mouseDownPos.current = null;\n return;\n }\n }\n mouseDownPos.current = null;\n\n if (isEditMode) {\n // Edit mode: select widget for editing\n selectWidget(widget.id);\n }\n // View mode: drilldown is triggered by clicking specific data elements\n // (table rows, chart points, etc.) - not by clicking the widget itself\n },\n [isEditMode, selectWidget, widget.id]\n );\n\n // Handle keyboard navigation (Edit mode only)\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n event.stopPropagation();\n if (isEditMode) {\n selectWidget(widget.id);\n }\n }\n },\n [isEditMode, selectWidget, widget.id]\n );\n\n const hasRenderableCustomWidgetConfig = useMemo(\n () => widget.type === 'custom' && hasRenderableCustomConfig(widget.config),\n [widget.type, widget.config]\n );\n\n const customWidgetHasIframeConfig = useMemo(\n () => widget.type === 'custom' && hasCustomIframeConfig(widget.config),\n [widget.type, widget.config]\n );\n\n const showContainerDrilldownHints = hasDrilldown && !customWidgetHasIframeConfig;\n\n // Text widgets can render static config.content even when no parser/sink is bound.\n const isTextWithContent = useMemo(() => {\n if (widget.type !== 'text') return false;\n return resolveTextData(widget.config as Record<string, unknown> | undefined, widgetData).hasContent;\n }, [widget.type, widget.config, widgetData]);\n\n // Determine if data is empty\n const isEmpty = !isLoading && !error && !widgetData && !hasRenderableCustomWidgetConfig && !isTextWithContent;\n\n // v2.0: Check if widget has a renderer specified (non-BIGCONSOLE)\n const widgetRenderer = useMemo(() => {\n const widgetWithRenderer = widget as Widget & { renderer?: RendererType };\n return widgetWithRenderer.renderer;\n }, [widget]);\n\n // v2.0: Determine if we should use the factory (non-BIGCONSOLE renderer)\n const useRendererFactory = useMemo(() => {\n const shouldUse = widgetRenderer && widgetRenderer !== 'BIGCONSOLE';\n return shouldUse;\n }, [widgetRenderer]);\n\n // v2.0: Create action context\n const actionContext = useMemo<ActionContext>(\n () => ({\n widgetId: widget.id,\n data: widgetData || {},\n }),\n [widget.id, widgetData]\n );\n\n // v2.0: Handle action callback from WidgetRendererFactory\n // Receives (action: WidgetAction, context: ActionContext) and forwards to parent\n // Checks if a more detailed backend action exists with same name\n const handleActionFromFactory = useCallback(\n (action: WidgetAction, context: ActionContext) => {\n if (!onAction) return;\n\n // Try to find a matching backend action by name (has more details like confirmation)\n const existingAction = actions?.find((a) => a.name === action.name);\n\n if (existingAction) {\n // Use existing backend action (has confirmation, style, icon, etc.)\n onAction(existingAction, context);\n } else {\n // Use the action from WidgetRendererFactory as-is\n onAction(action, context);\n }\n },\n [onAction, actions]\n );\n\n // Render the appropriate widget component based on type (v1.0 snake_case)\n const renderWidgetComponent = useCallback(() => {\n // Extract data based on widget type expectations\n // Different widgets expect different data formats\n const getDataForWidget = () => {\n if (!widgetData) return widgetData;\n\n // If data has 'rows' property (table data), extract rows\n if (widget.type === 'table' || widget.type === 'pivot_table') {\n if (Array.isArray(widgetData)) return widgetData;\n if (widgetData && typeof widgetData === 'object' && 'rows' in widgetData) {\n return (widgetData as { rows: unknown[] }).rows;\n }\n }\n\n // If data has 'items' property (list data), extract items\n if (widget.type === 'list') {\n if (Array.isArray(widgetData)) return widgetData;\n if (widgetData && typeof widgetData === 'object' && 'items' in widgetData) {\n return (widgetData as { items: unknown[] }).items;\n }\n }\n\n // If data has 'stages' property (old funnel format), extract stages\n if (widget.type === 'funnel_chart') {\n if (Array.isArray(widgetData)) return widgetData;\n if (widgetData && typeof widgetData === 'object' && 'stages' in widgetData) {\n return (widgetData as { stages: unknown[] }).stages;\n }\n }\n\n // If data has 'datasets' property (old chart format), convert to array format\n if (widget.type === 'chart') {\n if (Array.isArray(widgetData)) return widgetData;\n if (widgetData && typeof widgetData === 'object' && 'datasets' in widgetData) {\n // Convert old format to new array format\n const oldData = widgetData as { labels?: string[]; datasets?: { name: string; data: number[] }[] };\n if (oldData.labels && oldData.datasets) {\n return oldData.labels.map((label, i) => {\n const point: Record<string, unknown> = { name: label };\n oldData.datasets?.forEach((ds) => {\n point[ds.name.toLowerCase()] = ds.data[i];\n });\n return point;\n });\n }\n }\n }\n\n // For text widgets: merge parser output with static config via the shared\n // text-data contract (string/object-with-content/object-without-content).\n if (widget.type === 'text') {\n const resolved = resolveTextData(widget.config as Record<string, unknown> | undefined, widgetData);\n return {\n content: resolved.content,\n format: resolved.format,\n alignment: resolved.alignment,\n };\n }\n\n // For custom widgets: pass data through with extracted value if configured\n if (widget.type === 'custom') {\n const config = widget.config as Record<string, unknown> | undefined;\n const valueField = config?.valueField as string | undefined;\n if (valueField && widgetData && typeof widgetData === 'object' && !Array.isArray(widgetData)) {\n const obj = widgetData as Record<string, unknown>;\n if (valueField in obj) {\n return { value: obj[valueField], label: widget.title, data: obj };\n }\n }\n }\n\n return widgetData;\n };\n\n const normalizedData = getDataForWidget();\n const props = {\n widget,\n data: normalizedData,\n onDrilldown: activeDrilldown,\n };\n\n // v2.0: Use WidgetRendererFactory for non-BIGCONSOLE renderers\n if (useRendererFactory) {\n // For factory renderers (Adaptive Card, BlockKit, Custom), pass the RAW\n // processed data — NOT the type-normalized data. Normalization (e.g., text→markdown)\n // is only for BIGCONSOLE renderer widgets. Factory renderers handle their own\n // template interpolation against the raw data object.\n let factoryData: Record<string, unknown> = {};\n\n if (\n realWidgetData &&\n typeof realWidgetData === 'object' &&\n !Array.isArray(realWidgetData) &&\n Object.keys(realWidgetData as Record<string, unknown>).length > 0\n ) {\n // Use real data from backend (raw processed, not type-normalized)\n factoryData = { ...(realWidgetData as Record<string, unknown>) };\n }\n\n // For CUSTOM renderer: enrich data with standard fields expected by built-in components.\n // Built-in components (Counter, Card, SimpleText) read specific fields from data:\n // Counter: data.value, Card: data.title/data.description, SimpleText: data.text\n // Parsed data from datasinks has domain-specific fields (totalFiles, totalMessages, etc.)\n // Use config.valueField to extract the primary value and map it to standard fields.\n const internalType = (widget.config as Record<string, unknown> | undefined)?._internalWidgetType as\n string | undefined;\n if (internalType === 'custom' && Object.keys(factoryData).length > 0) {\n const config = widget.config as Record<string, unknown> | undefined;\n const valueField = config?.valueField as string | undefined;\n if (valueField && valueField in factoryData) {\n const val = factoryData[valueField];\n const formatted = typeof val === 'number' ? val.toLocaleString() : String(val);\n // Map to standard fields for all built-in custom components\n factoryData = {\n ...factoryData,\n value: val, // Counter component\n title: factoryData.title || formatted, // Card component\n description: factoryData.description || widget.title || '', // Card component\n text: factoryData.text || formatted, // SimpleText component\n };\n }\n }\n\n return (\n <WidgetRendererFactory\n widget={widget}\n data={factoryData}\n isEditMode={isEditMode}\n isSelected={isSelected}\n isLoading={isLoading}\n error={error}\n onDrilldown={activeDrilldown}\n onAction={handleActionFromFactory}\n />\n );\n }\n\n // v1.0: Use switch-case for BIGCONSOLE renderer (default)\n // Normalize widget type to lowercase for case-insensitive matching\n const normalizedType = widget.type?.toLowerCase() || '';\n switch (normalizedType) {\n case 'metric_card':\n return <MetricCardWidget {...props} />;\n case 'kpi_card_comparison':\n return <KPIComparisonWidget {...props} />;\n case 'chart':\n case 'funnel_chart':\n return <ChartWidget {...props} />;\n case 'table':\n return <TableWidget {...props} />;\n case 'pivot_table':\n return <PivotTableWidget {...props} />;\n case 'gauge':\n return <GaugeWidget {...props} />;\n case 'progress':\n return <ProgressWidget {...props} />;\n case 'list':\n return <ListWidget {...props} />;\n case 'heatmap':\n return <HeatmapWidget {...props} />;\n case 'retention':\n return <RetentionWidget {...props} />;\n case 'calendar':\n return <CalendarWidget {...props} />;\n case 'timeline':\n return <TimelineWidget {...props} />;\n case 'kanban':\n return <KanbanWidget {...props} />;\n case 'form':\n return <FormWidget {...props} />;\n case 'text':\n return <TextWidget {...props} />;\n case 'iframe':\n return <IframeWidget {...props} />;\n case 'map':\n return <MapWidget {...props} />;\n case 'custom':\n return <CustomWidget {...props} />;\n default:\n return children || <WidgetEmptyState widgetType={widget.type} />;\n }\n }, [\n widget,\n widgetData,\n children,\n activeDrilldown,\n useRendererFactory,\n isEditMode,\n isSelected,\n isLoading,\n error,\n handleActionFromFactory,\n realWidgetData,\n ]);\n\n // Determine content to render\n const renderContent = () => {\n if (isLoading) {\n return <WidgetLoadingState />;\n }\n\n if (error) {\n return <WidgetErrorState error={error} onRetry={onRefresh} />;\n }\n\n if (isEmpty && !children) {\n // v2.0: Check parserId (primary) or dataSinkId (for context/drilldowns)\n return (\n <WidgetEmptyState\n widgetType={widget.type}\n hasDataSource={hasDataSource}\n templateSlot={\n typeof widget.metadata?.['templateDataSinkSlot'] === 'string'\n ? (widget.metadata['templateDataSinkSlot'] as string)\n : null\n }\n />\n );\n }\n\n // resetKey auto-resets the boundary on parser/sink re-bind or config edit without widget.id changing (BOFF-2242).\n const resetKey = `${widgetBinding.source.kind}|${widgetBinding.source.ref ?? ''}|${widgetBinding.parserId ?? ''}|${widget.updatedAt ?? ''}`;\n\n return (\n <WidgetErrorBoundary widgetId={widget.id} widgetType={widget.type} widgetTitle={widget.title} resetKey={resetKey}>\n {children ?? <Suspense fallback={<WidgetLoadingState />}>{renderWidgetComponent()}</Suspense>}\n </WidgetErrorBoundary>\n );\n };\n\n return (\n <div\n ref={containerRef}\n /*\n The card is an object lifted off the (sunken) canvas, so it carries the\n elevation scale rather than expressing depth as one more 1px border —\n elevation was previously almost unused in this module (BOFF-5636).\n Only colour/shadow animate, and only when motion is allowed.\n\n `--color-action-primary-border` exists as a CSS variable but is NOT in the\n shell's Tailwind `@theme`, so `border-action-primary-border` /\n `ring-action-primary-border` emit no CSS at all and the selected state\n rendered with the default border and no ring. Both go through the\n arbitrary `var()` form, which resolves per theme (BOFF-5636).\n */\n className={`\n group relative flex flex-col\n h-full w-full min-w-0\n rounded-card border\n bg-bg-surface\n shadow-[var(--shadow-elevation-1)]\n motion-safe:transition-[box-shadow,border-color] motion-safe:duration-200\n ${\n isSelected && isEditMode\n ? 'border-[var(--color-action-primary-border)] ring-2 ring-[var(--color-action-primary-border)]/30 shadow-[var(--shadow-elevation-2)]'\n : 'border-[var(--color-border-subtle)] hover:border-action-primary-bg hover:shadow-[var(--shadow-elevation-2)]'\n }\n ${isEditMode ? 'cursor-pointer' : ''}\n ${className}\n `}\n onMouseDown={handleMouseDown}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n tabIndex={isEditMode ? 0 : -1}\n role={isEditMode ? 'button' : undefined}\n aria-selected={isSelected}\n aria-label={`Widget: ${widget.title}`}\n data-widget-id={widget.id}\n data-widget-type={widget.type}\n >\n {/* Header */}\n <WidgetHeader\n widget={widget}\n definition={definition}\n isSelected={isSelected}\n isEditMode={isEditMode}\n isLoading={isLoading}\n isSampleData={isSampleData}\n timeUntilRefresh={widget.refreshInterval && !isPaused ? formatTimeUntilRefresh(timeUntilRefresh) : undefined}\n hasDrilldown={hasDrilldown}\n onRefresh={onRefresh}\n onExportCSV={exportData ? exportCSV : undefined}\n onExportPNG={exportPNG}\n onDrilldown={activeDrilldown ? () => activeDrilldown() : undefined}\n onToggleComments={toggleComments}\n commentsOpen={showComments}\n commentCount={commentsEverOpened ? commentCount : undefined}\n />\n\n {/* Content Area — the point of the card, so it gets the room */}\n <div\n className={`\n flex-1 overflow-hidden p-3 min-h-0 min-w-0 sm:p-4\n ${showContainerDrilldownHints && !isEditMode ? 'cursor-pointer' : ''}\n `}\n title={showContainerDrilldownHints && !isEditMode ? 'Click data to drill down' : undefined}\n >\n <div className=\"h-full min-w-0 overflow-auto\">{renderContent()}</div>\n </div>\n\n {/*\n v2.0: Widget Actions. A recessed control tray, deliberately lighter than\n the title band above it, so the card is no longer a symmetric sandwich of\n two identically-weighted strips.\n */}\n {actions && actions.length > 0 && !isLoading && !error && (\n <div\n className=\"min-w-0 border-t border-[var(--color-border-subtle)] bg-bg-sunken px-3 py-2 sm:px-4\"\n style={{ flexShrink: 0 }}\n >\n <WidgetActions\n actions={actions}\n context={actionContext}\n onAction={onAction}\n disabled={isEditMode}\n layout=\"horizontal\"\n size=\"sm\"\n />\n </div>\n )}\n\n {/* Edit mode: react-grid-layout provides resize handles */}\n\n {/* Drilldown Indicator */}\n {showContainerDrilldownHints && !isEditMode && (\n <div\n className=\"\n absolute bottom-2 right-2\n opacity-0 group-hover:opacity-100\n transition-opacity duration-200\n \"\n title=\"Click to drill down\"\n >\n <svg className=\"w-4 h-4 text-text-secondary\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M13 7l5 5m0 0l-5 5m5-5H6\" />\n </svg>\n </div>\n )}\n\n {/* Comments panel (overlay) */}\n {showComments && (\n <Suspense fallback={null}>\n <WidgetComments widgetId={widget.id} onClose={() => setShowComments(false)} />\n </Suspense>\n )}\n </div>\n );\n}, arePropsEqual);\n\nexport default WidgetWrapper;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAM,KAAmB,QAAW,OAAO,0BAAiB,MAAM,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC,EACrG,KAAc,QAAW,OAAO,oBAAW,MAAM,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,EACrF,KAAc,QAAW,OAAO,oBAAW,MAAM,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,EACrF,KAAmB,QAAW,OAAO,0BAAiB,MAAM,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC,EACrG,KAAc,QAAW,OAAO,oBAAW,MAAM,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,EACrF,KAAiB,QAAW,OAAO,uBAAc,MAAM,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,CAAC,EAC9F,KAAa,QAAW,OAAO,mBAAU,MAAM,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,CAAC,EAClF,KAAgB,QAAW,OAAO,sBAAa,MAAM,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,CAAC,EAC3F,KAAkB,QA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EAAgB,GAAM;KAAI,CAAA;IACrE,CAAA;GAET;;GAEP,EAAc"}
1
+ {"version":3,"file":"WidgetWrapper.js","names":[],"sources":["../../../../src/bigconsole/components/widgets/WidgetWrapper.tsx"],"sourcesContent":["/**\n * WidgetWrapper Component (v2.1)\n *\n * Common wrapper for all widget types. Handles:\n * - Header with title and menu\n * - Loading, error, and empty states\n * - Selection highlighting\n * - Edit mode controls\n * - Real data only — no mock fallback; widgets show empty state when data is missing\n * - v2.0: Multi-renderer support via WidgetRendererFactory\n * - v2.0: Widget actions support\n */\n\nimport {\n type FC,\n type ReactNode,\n type RefObject,\n useCallback,\n memo,\n useMemo,\n useRef,\n useState,\n useEffect,\n lazy,\n Suspense,\n} from 'react';\nimport type { Widget } from '../../types';\nimport {\n useWidgetStore,\n useDashboardStore,\n useIsWidgetSelected,\n useWidgetUIState,\n useGlobalFilterValues,\n} from '../../store';\nimport {\n useWidgetAutoRefresh,\n formatTimeUntilRefresh,\n useWidgetExport,\n useDrilldown,\n useWidgetData,\n useWidgetComments,\n type DrilldownContext,\n} from '../../hooks';\nimport { useApolloClient } from '@apollo/client/react';\nimport { GetDashboardDocument } from '../../../generated/wspace-operations';\nimport { getWidgetDefinition } from './WidgetRegistry';\nimport { resolveTextData } from './text-widget/textData';\nimport { WidgetHeader } from './WidgetHeader';\nimport { useBigConsoleSettings } from '../../hooks/useBigConsoleSettings';\nimport { WidgetLoadingState } from './states/LoadingState';\nimport { WidgetErrorState } from './states/ErrorState';\nimport { WidgetEmptyState } from './states/EmptyState';\nimport { WidgetErrorBoundary } from './WidgetErrorBoundary';\nimport { hasRenderableCustomConfig, hasCustomIframeConfig } from './custom/config';\nimport { getBindingForWidget } from '../../utils/widgetBinding';\n\n// v2.0: Renderer factory and actions\nimport { WidgetRendererFactory } from '../../renderers/factory/WidgetRendererFactory';\nimport { WidgetActions } from './widget-actions';\nimport type { WidgetAction, ActionContext, ActionResult, RendererType } from '../../renderers/types/renderer';\n// Widget components - lazy loaded for better code splitting\n// Each widget loads only when its type is rendered\nconst MetricCardWidget = lazy(() => import('./metric-card').then((m) => ({ default: m.MetricCardWidget })));\nconst ChartWidget = lazy(() => import('./chart').then((m) => ({ default: m.ChartWidget })));\nconst TableWidget = lazy(() => import('./table').then((m) => ({ default: m.TableWidget })));\nconst PivotTableWidget = lazy(() => import('./pivot-table').then((m) => ({ default: m.PivotTableWidget })));\nconst GaugeWidget = lazy(() => import('./gauge').then((m) => ({ default: m.GaugeWidget })));\nconst ProgressWidget = lazy(() => import('./progress').then((m) => ({ default: m.ProgressWidget })));\nconst ListWidget = lazy(() => import('./list').then((m) => ({ default: m.ListWidget })));\nconst HeatmapWidget = lazy(() => import('./heatmap').then((m) => ({ default: m.HeatmapWidget })));\nconst RetentionWidget = lazy(() => import('./retention').then((m) => ({ default: m.RetentionWidget })));\nconst CalendarWidget = lazy(() => import('./calendar').then((m) => ({ default: m.CalendarWidget })));\nconst KanbanWidget = lazy(() => import('./kanban').then((m) => ({ default: m.KanbanWidget })));\nconst TimelineWidget = lazy(() => import('./timeline').then((m) => ({ default: m.TimelineWidget })));\nconst KPIComparisonWidget = lazy(() => import('./kpi-comparison').then((m) => ({ default: m.KPIComparisonWidget })));\nconst TextWidget = lazy(() => import('./text-widget').then((m) => ({ default: m.TextWidget })));\nconst MapWidget = lazy(() => import('./map-widget').then((m) => ({ default: m.MapWidget })));\nconst IframeWidget = lazy(() => import('./iframe-widget').then((m) => ({ default: m.IframeWidget })));\nconst CustomWidget = lazy(() => import('./custom').then((m) => ({ default: m.CustomWidget })));\n// AdaptiveCardWidget is HUGE (984KB) - lazy load only when 'adaptive_card' type is used\nconst AdaptiveCardWidget = lazy(() => import('./adaptive-card').then((m) => ({ default: m.AdaptiveCardWidget })));\nconst FormWidget = lazy(() => import('./form').then((m) => ({ default: m.FormWidget })));\n// Comments panel - lazy loaded; only mounts when the user opens comments\nconst WidgetComments = lazy(() => import('./comments/WidgetComments').then((m) => ({ default: m.WidgetComments })));\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface WidgetWrapperProps {\n /** Gallery previews have no persisted widget to comment on or edit. */\n previewOnly?: boolean;\n /** The widget data */\n widget: Widget;\n /** Widget content to render */\n children?: ReactNode;\n /** Data for the widget */\n data?: Record<string, unknown> | null;\n /** Custom class name */\n className?: string;\n /** Whether the widget is loading */\n isLoading?: boolean;\n /** Error message */\n error?: string | null;\n /** Callback to refresh widget data */\n onRefresh?: () => Promise<void>;\n /** Callback for drilldown navigation */\n onDrilldown?: (params: Record<string, unknown>) => void;\n /** v2.0: Widget actions */\n actions?: WidgetAction[];\n /** v2.0: Callback for action events */\n onAction?: (action: WidgetAction, context: ActionContext) => Promise<ActionResult | void>;\n /** Phase 2: Global filter values to apply to widget data */\n filterValues?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Custom comparison for memo - ensures actions changes trigger re-render\n// ============================================================================\n\nfunction arePropsEqual(prevProps: WidgetWrapperProps, nextProps: WidgetWrapperProps): boolean {\n if (prevProps.previewOnly !== nextProps.previewOnly) return false;\n // Always re-render if widget ID changes\n if (prevProps.widget.id !== nextProps.widget.id) return false;\n // Re-render if widget was updated\n if (prevProps.widget.updatedAt !== nextProps.widget.updatedAt) return false;\n // Re-render if loading state changes\n if (prevProps.isLoading !== nextProps.isLoading) return false;\n // Re-render if error changes\n if (prevProps.error !== nextProps.error) return false;\n // Action IDs survive edits. Compare the immutable list so label, appearance,\n // confirmation and visibility changes reach the canvas immediately after save.\n if (prevProps.actions !== nextProps.actions) return false;\n // Also check data changes\n if (prevProps.data !== nextProps.data) return false;\n // Phase 2: Re-render if filter values changed\n if (JSON.stringify(prevProps.filterValues) !== JSON.stringify(nextProps.filterValues)) return false;\n return true;\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nexport const WidgetWrapper: FC<WidgetWrapperProps> = memo(function WidgetWrapper({\n widget,\n children,\n data,\n className = '',\n isLoading: isLoadingProp,\n error: errorProp,\n onRefresh,\n onDrilldown,\n actions,\n onAction,\n filterValues,\n previewOnly = false,\n}) {\n const settings = useBigConsoleSettings();\n // Store state - use Dashboard store for edit mode (synced with toolbar)\n const dashboardIsEditMode = useDashboardStore((state) => state.viewMode === 'edit');\n const isEditMode = !previewOnly && dashboardIsEditMode;\n const selectWidget = useWidgetStore((state) => state.selectWidget);\n const isSelected = useIsWidgetSelected(widget.id);\n const uiState = useWidgetUIState(widget.id);\n const globalFilterValues = useGlobalFilterValues();\n const apolloClient = useApolloClient();\n\n // Map a global-filter's id -> the data field it targets (`config.field`).\n // Global CATEGORY/TEXT filter values are keyed in the store by filter id (a\n // UUID), not by the data column they filter. Without this map, applyClientFilters\n // can only fall back to value/heuristic matching, which fails to narrow rows\n // whose targeted column (e.g. `country`, `cohort`) isn't in the hardcoded\n // heuristic list — so a selected Country/Cohort would not actually filter the\n // widget. We resolve the targeted field from the dashboard's globalFilters\n // (already in the Apollo cache from the page load) so a UUID-keyed filter\n // matches the row's configured field exactly.\n const widgetDashboardId = (widget as unknown as Record<string, unknown>).dashboardId as string | undefined;\n const filterFieldMap = useMemo<Record<string, string>>(() => {\n if (!widgetDashboardId) return {};\n try {\n const cached = apolloClient.readQuery<{\n getDashboard?: {\n globalFilters?: Array<{ id: string; config?: Record<string, unknown> | null }>;\n };\n }>({ query: GetDashboardDocument, variables: { id: widgetDashboardId } });\n const map: Record<string, string> = {};\n for (const f of cached?.getDashboard?.globalFilters ?? []) {\n const field = f.config?.field;\n if (typeof field === 'string' && field && Object.hasOwn(globalFilterValues, f.id)) map[f.id] = field;\n }\n return map;\n } catch {\n return {};\n }\n }, [apolloClient, widgetDashboardId, globalFilterValues]);\n\n // Fetch per-widget data from backend (parser-processed data)\n // This is needed because listWidgetsByDashboard uses WidgetListFields (without data)\n // for performance, so each widget fetches its own data individually\n const widgetBinding = useMemo(() => getBindingForWidget(widget), [widget]);\n const hasDataSource =\n widgetBinding.source.kind !== 'DATASINK' ||\n !!widgetBinding.source.ref ||\n !!widgetBinding.parserId ||\n !!widget.datasetId;\n const { data: fetchedWidgetData, loading: widgetDataLoading } = useWidgetData(widget.id, {\n skip: previewOnly || !hasDataSource,\n pollInterval: (widget.refreshInterval ?? 0) * 1000 || 0,\n });\n\n // WORKAROUND: If Zustand store is empty, directly read filter_* params from URL\n // This handles race conditions where the store hasn't been populated yet\n const urlFilterValues = useMemo(() => {\n if (typeof window === 'undefined') return {};\n\n const params = new URLSearchParams(window.location.search);\n const filters: Record<string, unknown> = {};\n\n params.forEach((value, key) => {\n if (key.startsWith('filter_')) {\n const filterId = key.slice('filter_'.length);\n // Skip internal metadata keys\n if (!filterId.startsWith('__')) {\n filters[filterId] = value;\n }\n }\n });\n\n return filters;\n }, []);\n\n // Phase 2: Merge global filter values (from URL) with explicit filterValues prop\n // This ensures both URL params (filter_*) and drilldown params work together\n const mergedFilterValues = useMemo(() => {\n const merged: Record<string, unknown> = {};\n\n // First, add URL filter values as fallback (in case Zustand store hasn't loaded yet)\n if (urlFilterValues && Object.keys(urlFilterValues).length > 0) {\n Object.assign(merged, urlFilterValues);\n }\n\n // Then, add global filter values from Zustand store (if populated)\n if (globalFilterValues && Object.keys(globalFilterValues).length > 0) {\n Object.assign(merged, globalFilterValues);\n }\n\n // Finally, add/override with explicit filterValues prop (e.g., from drilldown modal)\n if (filterValues && Object.keys(filterValues).length > 0) {\n Object.assign(merged, filterValues);\n }\n\n return merged;\n }, [urlFilterValues, globalFilterValues, filterValues]);\n\n // Track active filters (client-side filtering until backend supports it)\n const hasFilters = Object.keys(mergedFilterValues).length > 0;\n\n // Merge loading/error from props and store\n // Show loading if widget data is being fetched for the first time (no data yet)\n const isLoading = isLoadingProp ?? (widgetDataLoading && !fetchedWidgetData) ?? uiState.isLoading;\n const error = errorProp ?? uiState.errorMessage;\n\n // Get widget definition\n const definition = getWidgetDefinition(widget.type);\n\n // Stable refresh callback - use ref to avoid creating new function on each render\n const onRefreshRef = useRef(onRefresh);\n useEffect(() => {\n onRefreshRef.current = onRefresh;\n }, [onRefresh]);\n\n const stableOnRefresh = useCallback(async () => {\n if (onRefreshRef.current) {\n await onRefreshRef.current();\n }\n }, []);\n\n // Auto-refresh\n const { timeUntilRefresh, isPaused } = useWidgetAutoRefresh({\n widgetId: widget.id,\n refreshInterval: widget.refreshInterval,\n onRefresh: stableOnRefresh,\n enabled: !previewOnly && !isEditMode && !!widget.refreshInterval,\n });\n\n // Container ref for PNG export\n const containerRef = useRef<HTMLDivElement>(null);\n\n // Comments panel. The count query stays disabled until the panel is first\n // opened, so a dashboard of N widgets doesn't fire N comment queries on load.\n const [showComments, setShowComments] = useState(false);\n const [commentsEverOpened, setCommentsEverOpened] = useState(false);\n const { count: commentCount } = useWidgetComments(widget.id, commentsEverOpened);\n const toggleComments = useCallback(() => {\n setShowComments((open) => {\n const next = !open;\n if (next) setCommentsEverOpened(true);\n return next;\n });\n }, []);\n\n // Get widget data for export (computed early for hook)\n const exportData = useMemo(() => {\n if (data && Array.isArray(data)) return data;\n const rawData = (widget as unknown as Record<string, unknown>).data as Record<string, unknown> | undefined;\n if (rawData?.processed && Array.isArray(rawData.processed)) {\n return rawData.processed;\n }\n if (rawData?.raw) {\n const parsed = typeof rawData.raw === 'string' ? JSON.parse(rawData.raw) : rawData.raw;\n if (Array.isArray(parsed)) return parsed;\n }\n return null;\n }, [data, widget]);\n\n // Export functionality\n const { exportCSV, exportPNG } = useWidgetExport(widget, {\n data: exportData,\n containerRef: containerRef as unknown as RefObject<HTMLElement>,\n });\n\n // Helper to check if data is actually usable (has real content)\n const isUsableData = useCallback((d: unknown): boolean => {\n if (d === null || d === undefined) return false;\n if (Array.isArray(d)) return d.length > 0;\n if (typeof d === 'object') {\n const obj = d as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length === 0) return false;\n // Check recursively for actual data content\n return keys.some((key) => {\n const val = obj[key];\n if (val === null || val === undefined || val === '') return false;\n if (Array.isArray(val)) return val.length > 0;\n if (typeof val === 'object') return isUsableData(val);\n return true;\n });\n }\n return true;\n }, []);\n\n // Phase 2: Client-side filter function for widget data\n const applyClientFilters = useCallback(\n (\n widgetData: Record<string, unknown> | Record<string, unknown>[]\n ): Record<string, unknown> | Record<string, unknown>[] => {\n if (!hasFilters || !widgetData) return widgetData;\n\n // Separate drilldown context filters (ctx_*) from regular filters\n const contextFilters: Record<string, unknown> = {};\n const regularFilters: Record<string, unknown> = {};\n\n Object.entries(mergedFilterValues || {}).forEach(([key, value]) => {\n if (key.startsWith('ctx_')) {\n // Strip ctx_ prefix to get the target field name\n const fieldName = key.slice(4); // Remove 'ctx_'\n contextFilters[fieldName] = value;\n } else if (!key.startsWith('__')) {\n // Skip internal metadata keys (__drilldown_depth, etc.)\n regularFilters[key] = value;\n }\n });\n\n // Helper to match a value against a filter (case-insensitive)\n const matchesFilter = (itemValue: unknown, filterValue: unknown): boolean => {\n if (filterValue === undefined || filterValue === null || filterValue === '') return true;\n if (itemValue === undefined || itemValue === null) return false;\n\n const itemStr = String(itemValue).toLowerCase();\n const filterStr = String(filterValue).toLowerCase();\n\n // Exact match or contains\n return itemStr === filterStr || itemStr.includes(filterStr);\n };\n\n // Helper to find a matching field in the item (case-insensitive key matching)\n const findFieldValue = (item: Record<string, unknown>, targetField: string): unknown => {\n const targetLower = targetField.toLowerCase();\n\n // Try exact match first\n if (item[targetField] !== undefined) return item[targetField];\n\n // Try case-insensitive match\n const matchingKey = Object.keys(item).find((k) => k.toLowerCase() === targetLower);\n if (matchingKey) return item[matchingKey];\n\n // Try partial match (e.g., 'region' matches 'regionName' or 'user_region')\n const partialMatch = Object.keys(item).find(\n (k) => k.toLowerCase().includes(targetLower) || targetLower.includes(k.toLowerCase())\n );\n if (partialMatch) return item[partialMatch];\n\n // Try stripping common prefixes from target field (e.g., 'kpiId' -> 'id', 'rowName' -> 'name')\n // This handles drilldown context where widget passes 'kpiId' but data has 'id'\n const commonPrefixes = ['kpi', 'row', 'item', 'data', 'cell', 'record', 'entry'];\n for (const prefix of commonPrefixes) {\n if (targetLower.startsWith(prefix) && targetLower.length > prefix.length) {\n const strippedField = targetLower.slice(prefix.length);\n // Try exact match with stripped field\n const strippedMatch = Object.keys(item).find((k) => k.toLowerCase() === strippedField);\n if (strippedMatch) return item[strippedMatch];\n }\n }\n\n return undefined;\n };\n\n // Helper function to filter an array of items\n const filterItems = (items: Record<string, unknown>[]): Record<string, unknown>[] => {\n return items.filter((item: Record<string, unknown>) => {\n // Only object rows are field-filterable. An array of primitives (e.g.\n // a heatmap's `rows: [\"5W-MedSurg\", …]`) carries no named fields — keep\n // every element. Without this, `findFieldValue` indexes into the string\n // by character offset and spuriously \"matches\" a filter, dropping rows.\n if (item === null || typeof item !== 'object' || Array.isArray(item)) {\n return true;\n }\n // First, apply drilldown context filters (ctx_*) - these have explicit field names\n for (const [fieldName, filterValue] of Object.entries(contextFilters)) {\n if (filterValue === undefined || filterValue === null || filterValue === '') continue;\n\n const itemValue = findFieldValue(item, fieldName);\n // If the field doesn't exist in this data item, skip this context filter.\n // Drilldown context params (e.g., source=support_status) are metadata about\n // the drilldown origin and should NOT filter out data when the target\n // dashboard's widgets don't have a matching field.\n if (itemValue === undefined) continue;\n if (!matchesFilter(itemValue, filterValue)) {\n return false;\n }\n }\n\n // Then, apply regular filters\n for (const [filterKey, filterValue] of Object.entries(regularFilters)) {\n if (filterValue === undefined || filterValue === null || filterValue === '') continue;\n\n // For date range filters\n if (typeof filterValue === 'object') {\n const fv = filterValue as Record<string, unknown>;\n if (fv.start || fv.end) {\n const dateFields = Object.entries(item).filter(\n ([k, _v]) => k.toLowerCase().includes('date') || k.toLowerCase().includes('time')\n );\n if (dateFields.length > 0) {\n const itemDate = new Date(dateFields[0][1] as string);\n if (fv.start && itemDate < new Date(fv.start as string)) return false;\n if (fv.end && itemDate > new Date(fv.end as string)) return false;\n }\n continue;\n }\n }\n\n // For numeric range filters\n if (typeof filterValue === 'object') {\n const nv = filterValue as Record<string, unknown>;\n if (nv.min !== undefined || nv.max !== undefined) {\n const numericFields = Object.entries(item).filter(([_k, v]) => typeof v === 'number');\n if (numericFields.length > 0) {\n const itemNum = numericFields[0][1] as number;\n if (nv.min !== undefined && itemNum < (nv.min as number)) return false;\n if (nv.max !== undefined && itemNum > (nv.max as number)) return false;\n }\n continue;\n }\n }\n\n // Any other object-shaped filter value (e.g. a DATE_RANGE filter set\n // to a preset like { preset: \"last_30_days\" } with no resolved\n // start/end, or a structured value we don't understand) cannot be\n // compared with the scalar matchers below. Passing it through would\n // stringify it to \"[object Object]\" and, via fuzzy field matching\n // (e.g. an `enrolledAt` filter partial-matching an `enrolled` number\n // column), spuriously exclude EVERY row. Treat such values as a no-op\n // for client-side filtering — the row set is unchanged until the\n // filter resolves to concrete start/end or scalar values.\n if (filterValue !== null && typeof filterValue === 'object' && !Array.isArray(filterValue)) {\n continue;\n }\n\n // Global CATEGORY/TEXT filters are keyed by filter id (UUID). Resolve\n // the data column they target from the filter's config.field. When the\n // widget's rows carry that column, the filter is authoritative — a\n // mismatch excludes the row; a missing column is a no-op (the filter\n // simply doesn't apply to this widget's shape). This is what makes a\n // selected Country/Cohort actually narrow the visible data.\n const targetField = filterFieldMap[filterKey];\n if (targetField) {\n const mappedValue = findFieldValue(item, targetField);\n if (mappedValue !== undefined) {\n if (!matchesFilter(mappedValue, filterValue)) {\n return false;\n }\n continue;\n }\n // Configured field absent from this widget's rows → filter is a\n // no-op for this widget (do not fall through to value heuristics,\n // which could spuriously match an unrelated column).\n continue;\n }\n\n // Try to match by filter key name first (for named filters). When\n // the widget's data actually carries the filter's field, the filter\n // is authoritative — a mismatch excludes the row.\n const fieldValue = findFieldValue(item, filterKey);\n if (fieldValue !== undefined) {\n if (!matchesFilter(fieldValue, filterValue)) {\n return false;\n }\n continue;\n }\n\n // For text/category filters - try multiple matching strategies\n const filterStr = String(filterValue).toLowerCase();\n\n // Strategy 1: Check all field values for exact or partial match\n const itemValues = Object.values(item).map((v) => String(v).toLowerCase());\n const hasMatch = itemValues.some((v) => v === filterStr || v.includes(filterStr));\n\n if (!hasMatch) {\n // Strategy 2: Try to find a field name that matches the filter value context\n const fieldNames = Object.keys(item).map((k) => k.toLowerCase());\n const possibleFields = fieldNames.filter(\n (f) =>\n f.includes('category') ||\n f.includes('type') ||\n f.includes('status') ||\n f.includes('name') ||\n f.includes('region') ||\n f.includes('group')\n );\n\n let fieldMatch = false;\n for (const fieldName of possibleFields) {\n const originalKey = Object.keys(item).find((k) => k.toLowerCase() === fieldName);\n if (originalKey) {\n const itemFieldValue = String(item[originalKey]).toLowerCase();\n if (itemFieldValue === filterStr || itemFieldValue.includes(filterStr)) {\n fieldMatch = true;\n break;\n }\n }\n }\n\n // The filter's field is NOT present in this dataset (named-field\n // lookup failed AND no value/heuristic match). A global filter that\n // doesn't apply to a widget's shape must be a no-op for that widget\n // — not a silent \"exclude every row\". This mirrors the ctx_* rule\n // above (skip when the targeted field is absent). Without this, an\n // always-active required filter (e.g. campus=main) blanks every\n // parser-derived widget whose output has no campus column.\n if (!fieldMatch) {\n continue;\n }\n }\n }\n return true;\n });\n };\n\n // If data is an array, filter the items directly\n if (Array.isArray(widgetData)) {\n const filtered = filterItems(widgetData);\n return filtered;\n }\n\n // Handle object with array properties (rows, items, members, questions, data, etc.)\n if (widgetData && typeof widgetData === 'object') {\n // Common array property names in widget data\n const arrayPropertyNames = [\n 'kpis', // KPI Comparison widget\n 'rows', // Table widget\n 'items', // List widget\n 'members', // Team/member widgets\n 'questions', // Form widget\n 'data', // Generic data\n 'records', // Database-style data\n 'results', // Search/query results\n 'entries', // Log/feed entries\n 'list', // Generic list\n 'values', // Value arrays\n 'series', // Chart series\n 'datasets', // Chart datasets\n ];\n\n for (const propName of arrayPropertyNames) {\n if (widgetData[propName] && Array.isArray(widgetData[propName])) {\n const filteredArray = filterItems(widgetData[propName]);\n return {\n ...widgetData,\n [propName]: filteredArray,\n ...(propName === 'rows' ? { totalRows: filteredArray.length } : {}),\n };\n }\n }\n\n // If no known array property found, check for any array property\n const arrayProps = Object.entries(widgetData).filter(([_key, v]) => Array.isArray(v));\n if (arrayProps.length > 0) {\n const [propName, propValue] = arrayProps[0];\n const filteredArray = filterItems(propValue as Record<string, unknown>[]);\n return {\n ...widgetData,\n [propName]: filteredArray,\n };\n }\n }\n\n // For non-filterable data, return as-is\n return widgetData;\n },\n [hasFilters, mergedFilterValues, widget.id, filterFieldMap]\n );\n\n // Get widget data from the widget itself (fetched from backend)\n const realWidgetData = useMemo(() => {\n let rawWidgetData = null;\n\n // Priority 1: Explicitly passed data prop\n if (data && isUsableData(data)) {\n rawWidgetData = data;\n }\n // Priority 2: Per-widget fetched data (from useWidgetData hook)\n // fetchedWidgetData IS a WidgetData object: { raw, processed, fetchedAt, cached }\n else if (fetchedWidgetData) {\n const fetched = fetchedWidgetData as unknown as Record<string, unknown>;\n if (fetched?.processed && isUsableData(fetched.processed)) {\n rawWidgetData = fetched.processed;\n } else if (fetched?.raw) {\n try {\n const parsed = typeof fetched.raw === 'string' ? JSON.parse(fetched.raw as string) : fetched.raw;\n if (isUsableData(parsed)) rawWidgetData = parsed;\n } catch {\n // Invalid JSON, ignore\n }\n }\n }\n // Priority 3: widget.data from GraphQL response (if already on widget object)\n else {\n const rawData = (widget as unknown as Record<string, unknown>).data as Record<string, unknown> | undefined;\n if (rawData?.processed && isUsableData(rawData.processed)) {\n rawWidgetData = rawData.processed;\n } else if (rawData?.raw) {\n try {\n const parsed = typeof rawData.raw === 'string' ? JSON.parse(rawData.raw) : rawData.raw;\n if (isUsableData(parsed)) rawWidgetData = parsed;\n } catch {\n // Invalid JSON, ignore\n }\n }\n }\n\n // Priority 4: config.mockData — user-configured sample JSON from Widget Properties Data tab\n // This is NOT auto-generated mock data; it's explicit JSON the user pasted in the UI\n if (!rawWidgetData) {\n const configMockData = (widget.config as Record<string, unknown> | undefined)?.mockData;\n if (configMockData) {\n try {\n const parsed = typeof configMockData === 'string' ? JSON.parse(configMockData) : configMockData;\n if (isUsableData(parsed)) {\n rawWidgetData = parsed;\n }\n } catch (e) {}\n }\n }\n\n // Generic parser-output resolution: a widget may bind to a parser whose\n // output is an envelope ({ byUnit:[...], house:{...} }) rather than the\n // exact array/object the renderer wants. config.dataKey / dataPath /\n // seriesPath is a dot-path INTO the resolved data that points at the\n // renderable subtree (e.g. \"byUnit\" for a table, \"rows\" for a chart).\n // Resolving it here keeps every renderer generic — the use-case-specific\n // shape knowledge lives in the widget config (set by the seed/UI), not in\n // the renderer. valueField (single-value metric path) is intentionally NOT\n // applied here: MetricCardWidget resolves it itself against the envelope.\n if (rawWidgetData && typeof rawWidgetData === 'object' && !Array.isArray(rawWidgetData)) {\n const cfg = widget.config as Record<string, unknown> | undefined;\n const pathKey = (cfg?.dataKey ?? cfg?.dataPath ?? cfg?.seriesPath) as string | undefined;\n if (pathKey && typeof pathKey === 'string') {\n const resolved = pathKey.split('.').reduce<unknown>((cur, seg) => {\n return cur && typeof cur === 'object' ? (cur as Record<string, unknown>)[seg] : undefined;\n }, rawWidgetData);\n if (resolved !== undefined && resolved !== null && isUsableData(resolved)) {\n rawWidgetData = resolved as Record<string, unknown>;\n }\n }\n }\n\n // Phase 2: Apply client-side filters if active\n if (hasFilters && rawWidgetData) {\n const filtered = applyClientFilters(rawWidgetData);\n return filtered;\n }\n\n return rawWidgetData;\n }, [data, widget, fetchedWidgetData, hasFilters, applyClientFilters, mergedFilterValues, isUsableData]);\n\n // Final widget data - real data only, no mock fallback\n const widgetData = useMemo(() => {\n return realWidgetData ?? null;\n }, [realWidgetData]);\n\n // Values rendered from a template's embedded sample rather than a connected\n // source. Only possible when no data source is configured, since a real\n // source outranks config.mockData in the resolution chain above.\n const isSampleData = useMemo(() => {\n if (!widgetData || hasDataSource) return false;\n const mock = (widget.config as Record<string, unknown> | undefined)?.mockData;\n return mock !== undefined && mock !== null;\n }, [widgetData, hasDataSource, widget.config]);\n\n // Drilldown navigation (must be after widgetData is defined)\n const { executeDrilldown, canDrilldown } = useDrilldown({\n onDrilldown: (params, _mode) => {\n onDrilldown?.(params);\n },\n });\n\n // Check if widget has drilldown configured\n const hasDrilldown = useMemo(() => canDrilldown(widget), [widget, canDrilldown]);\n\n // Handle drilldown execution with context\n const handleDrilldown = useCallback(\n (selectedData?: Record<string, unknown>) => {\n if (!widget.drilldown?.enabled) return;\n\n const context: DrilldownContext = {\n selectedData: selectedData || {},\n globalFilters: globalFilterValues || {},\n widgetData: widgetData || {},\n metadata: {\n widgetId: widget.id,\n widgetType: widget.type,\n widgetTitle: widget.title,\n },\n sourceDashboardId: widget.dashboardId,\n };\n\n void executeDrilldown(widget.drilldown, context);\n },\n [widget, widgetData, globalFilterValues, executeDrilldown]\n );\n\n // Data clicks drill down only while viewing. In edit mode a click selects\n // the widget; the builder's Preview (view mode) drills down (BOFF-7625).\n const activeDrilldown = hasDrilldown && !isEditMode ? handleDrilldown : undefined;\n\n // Track mouse position to distinguish click from drag\n const mouseDownPos = useRef<{ x: number; y: number } | null>(null);\n const DRAG_THRESHOLD = 5; // pixels - if mouse moves more than this, it's a drag\n\n // Handle mouse down - record position\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n mouseDownPos.current = { x: e.clientX, y: e.clientY };\n }, []);\n\n // Handle widget click - Edit mode only (View mode drilldown is triggered by data clicks)\n // Only trigger if mouse hasn't moved much (not a drag)\n const handleClick = useCallback(\n (e: React.MouseEvent) => {\n e.stopPropagation(); // Prevent DashboardGrid from also handling\n\n // Check if this was a drag (mouse moved significantly)\n if (mouseDownPos.current) {\n const dx = Math.abs(e.clientX - mouseDownPos.current.x);\n const dy = Math.abs(e.clientY - mouseDownPos.current.y);\n if (dx > DRAG_THRESHOLD || dy > DRAG_THRESHOLD) {\n // This was a drag, not a click - don't open config panel\n mouseDownPos.current = null;\n return;\n }\n }\n mouseDownPos.current = null;\n\n if (isEditMode) {\n // Edit mode: select widget for editing\n selectWidget(widget.id);\n }\n // View mode: drilldown is triggered by clicking specific data elements\n // (table rows, chart points, etc.) - not by clicking the widget itself\n },\n [isEditMode, selectWidget, widget.id]\n );\n\n // Handle keyboard navigation (Edit mode only)\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n event.stopPropagation();\n if (isEditMode) {\n selectWidget(widget.id);\n }\n }\n },\n [isEditMode, selectWidget, widget.id]\n );\n\n const hasRenderableCustomWidgetConfig = useMemo(\n () => widget.type === 'custom' && hasRenderableCustomConfig(widget.config),\n [widget.type, widget.config]\n );\n\n const customWidgetHasIframeConfig = useMemo(\n () => widget.type === 'custom' && hasCustomIframeConfig(widget.config),\n [widget.type, widget.config]\n );\n\n const showContainerDrilldownHints = hasDrilldown && !customWidgetHasIframeConfig;\n\n // Text widgets can render static config.content even when no parser/sink is bound.\n const isTextWithContent = useMemo(() => {\n if (widget.type !== 'text') return false;\n return resolveTextData(widget.config as Record<string, unknown> | undefined, widgetData).hasContent;\n }, [widget.type, widget.config, widgetData]);\n\n // Determine if data is empty\n const isEmpty = !isLoading && !error && !widgetData && !hasRenderableCustomWidgetConfig && !isTextWithContent;\n\n // v2.0: Check if widget has a renderer specified (non-BIGCONSOLE)\n const widgetRenderer = useMemo(() => {\n const widgetWithRenderer = widget as Widget & { renderer?: RendererType };\n return widgetWithRenderer.renderer;\n }, [widget]);\n\n // v2.0: Determine if we should use the factory (non-BIGCONSOLE renderer)\n const useRendererFactory = useMemo(() => {\n const shouldUse = widgetRenderer && widgetRenderer !== 'BIGCONSOLE';\n return shouldUse;\n }, [widgetRenderer]);\n\n // v2.0: Create action context\n const actionContext = useMemo<ActionContext>(\n () => ({\n widgetId: widget.id,\n data: widgetData || {},\n }),\n [widget.id, widgetData]\n );\n\n // v2.0: Handle action callback from WidgetRendererFactory\n // Receives (action: WidgetAction, context: ActionContext) and forwards to parent\n // Checks if a more detailed backend action exists with same name\n const handleActionFromFactory = useCallback(\n (action: WidgetAction, context: ActionContext) => {\n if (!onAction) return;\n\n // Try to find a matching backend action by name (has more details like confirmation)\n const existingAction = actions?.find((a) => a.name === action.name);\n\n if (existingAction) {\n // Use existing backend action (has confirmation, style, icon, etc.)\n onAction(existingAction, context);\n } else {\n // Use the action from WidgetRendererFactory as-is\n onAction(action, context);\n }\n },\n [onAction, actions]\n );\n\n // Render the appropriate widget component based on type (v1.0 snake_case)\n const renderWidgetComponent = useCallback(() => {\n // Extract data based on widget type expectations\n // Different widgets expect different data formats\n const getDataForWidget = () => {\n if (!widgetData) return widgetData;\n\n // If data has 'rows' property (table data), extract rows\n if (widget.type === 'table' || widget.type === 'pivot_table') {\n if (Array.isArray(widgetData)) return widgetData;\n if (widgetData && typeof widgetData === 'object' && 'rows' in widgetData) {\n return (widgetData as { rows: unknown[] }).rows;\n }\n }\n\n // If data has 'items' property (list data), extract items\n if (widget.type === 'list') {\n if (Array.isArray(widgetData)) return widgetData;\n if (widgetData && typeof widgetData === 'object' && 'items' in widgetData) {\n return (widgetData as { items: unknown[] }).items;\n }\n }\n\n // If data has 'stages' property (old funnel format), extract stages\n if (widget.type === 'funnel_chart') {\n if (Array.isArray(widgetData)) return widgetData;\n if (widgetData && typeof widgetData === 'object' && 'stages' in widgetData) {\n return (widgetData as { stages: unknown[] }).stages;\n }\n }\n\n // If data has 'datasets' property (old chart format), convert to array format\n if (widget.type === 'chart') {\n if (Array.isArray(widgetData)) return widgetData;\n if (widgetData && typeof widgetData === 'object' && 'datasets' in widgetData) {\n // Convert old format to new array format\n const oldData = widgetData as { labels?: string[]; datasets?: { name: string; data: number[] }[] };\n if (oldData.labels && oldData.datasets) {\n return oldData.labels.map((label, i) => {\n const point: Record<string, unknown> = { name: label };\n oldData.datasets?.forEach((ds) => {\n point[ds.name.toLowerCase()] = ds.data[i];\n });\n return point;\n });\n }\n }\n }\n\n // For text widgets: merge parser output with static config via the shared\n // text-data contract (string/object-with-content/object-without-content).\n if (widget.type === 'text') {\n const resolved = resolveTextData(widget.config as Record<string, unknown> | undefined, widgetData);\n return {\n content: resolved.content,\n format: resolved.format,\n alignment: resolved.alignment,\n };\n }\n\n // For custom widgets: pass data through with extracted value if configured\n if (widget.type === 'custom') {\n const config = widget.config as Record<string, unknown> | undefined;\n const valueField = config?.valueField as string | undefined;\n if (valueField && widgetData && typeof widgetData === 'object' && !Array.isArray(widgetData)) {\n const obj = widgetData as Record<string, unknown>;\n if (valueField in obj) {\n return { value: obj[valueField], label: widget.title, data: obj };\n }\n }\n }\n\n return widgetData;\n };\n\n const normalizedData = getDataForWidget();\n const props = {\n widget,\n data: normalizedData,\n onDrilldown: activeDrilldown,\n };\n\n // v2.0: Use WidgetRendererFactory for non-BIGCONSOLE renderers\n if (useRendererFactory) {\n // For factory renderers (Adaptive Card, BlockKit, Custom), pass the RAW\n // processed data — NOT the type-normalized data. Normalization (e.g., text→markdown)\n // is only for BIGCONSOLE renderer widgets. Factory renderers handle their own\n // template interpolation against the raw data object.\n let factoryData: Record<string, unknown> = {};\n\n if (\n realWidgetData &&\n typeof realWidgetData === 'object' &&\n !Array.isArray(realWidgetData) &&\n Object.keys(realWidgetData as Record<string, unknown>).length > 0\n ) {\n // Use real data from backend (raw processed, not type-normalized)\n factoryData = { ...(realWidgetData as Record<string, unknown>) };\n }\n\n // For CUSTOM renderer: enrich data with standard fields expected by built-in components.\n // Built-in components (Counter, Card, SimpleText) read specific fields from data:\n // Counter: data.value, Card: data.title/data.description, SimpleText: data.text\n // Parsed data from datasinks has domain-specific fields (totalFiles, totalMessages, etc.)\n // Use config.valueField to extract the primary value and map it to standard fields.\n const internalType = (widget.config as Record<string, unknown> | undefined)?._internalWidgetType as\n string | undefined;\n if (internalType === 'custom' && Object.keys(factoryData).length > 0) {\n const config = widget.config as Record<string, unknown> | undefined;\n const valueField = config?.valueField as string | undefined;\n if (valueField && valueField in factoryData) {\n const val = factoryData[valueField];\n const formatted = typeof val === 'number' ? val.toLocaleString() : String(val);\n // Map to standard fields for all built-in custom components\n factoryData = {\n ...factoryData,\n value: val, // Counter component\n title: factoryData.title || formatted, // Card component\n description: factoryData.description || widget.title || '', // Card component\n text: factoryData.text || formatted, // SimpleText component\n };\n }\n }\n\n return (\n <WidgetRendererFactory\n widget={widget}\n data={factoryData}\n isEditMode={isEditMode}\n isSelected={isSelected}\n isLoading={isLoading}\n error={error}\n onDrilldown={activeDrilldown}\n onAction={handleActionFromFactory}\n />\n );\n }\n\n // v1.0: Use switch-case for BIGCONSOLE renderer (default)\n // Normalize widget type to lowercase for case-insensitive matching\n const normalizedType = widget.type?.toLowerCase() || '';\n switch (normalizedType) {\n case 'metric_card':\n return <MetricCardWidget {...props} />;\n case 'kpi_card_comparison':\n return <KPIComparisonWidget {...props} />;\n case 'chart':\n case 'funnel_chart':\n return <ChartWidget {...props} />;\n case 'table':\n return <TableWidget {...props} />;\n case 'pivot_table':\n return <PivotTableWidget {...props} />;\n case 'gauge':\n return <GaugeWidget {...props} />;\n case 'progress':\n return <ProgressWidget {...props} />;\n case 'list':\n return <ListWidget {...props} />;\n case 'heatmap':\n return <HeatmapWidget {...props} />;\n case 'retention':\n return <RetentionWidget {...props} />;\n case 'calendar':\n return <CalendarWidget {...props} />;\n case 'timeline':\n return <TimelineWidget {...props} />;\n case 'kanban':\n return <KanbanWidget {...props} />;\n case 'form':\n return <FormWidget {...props} />;\n case 'text':\n return <TextWidget {...props} />;\n case 'iframe':\n return <IframeWidget {...props} />;\n case 'map':\n return <MapWidget {...props} />;\n case 'custom':\n return <CustomWidget {...props} />;\n default:\n return children || <WidgetEmptyState widgetType={widget.type} />;\n }\n }, [\n widget,\n widgetData,\n children,\n activeDrilldown,\n useRendererFactory,\n isEditMode,\n isSelected,\n isLoading,\n error,\n handleActionFromFactory,\n realWidgetData,\n ]);\n\n // Determine content to render\n const renderContent = () => {\n if (isLoading) {\n return <WidgetLoadingState />;\n }\n\n if (error) {\n return <WidgetErrorState error={error} onRetry={onRefresh} />;\n }\n\n if (isEmpty && !children) {\n // v2.0: Check parserId (primary) or dataSinkId (for context/drilldowns)\n return (\n <WidgetEmptyState\n widgetType={widget.type}\n hideEditHint={previewOnly}\n hasDataSource={hasDataSource}\n templateSlot={\n typeof widget.metadata?.['templateDataSinkSlot'] === 'string'\n ? (widget.metadata['templateDataSinkSlot'] as string)\n : null\n }\n />\n );\n }\n\n // resetKey auto-resets the boundary on parser/sink re-bind or config edit without widget.id changing (BOFF-2242).\n const resetKey = `${widgetBinding.source.kind}|${widgetBinding.source.ref ?? ''}|${widgetBinding.parserId ?? ''}|${widget.updatedAt ?? ''}`;\n\n return (\n <WidgetErrorBoundary widgetId={widget.id} widgetType={widget.type} widgetTitle={widget.title} resetKey={resetKey}>\n {children ?? <Suspense fallback={<WidgetLoadingState />}>{renderWidgetComponent()}</Suspense>}\n </WidgetErrorBoundary>\n );\n };\n\n return (\n <div\n ref={containerRef}\n /*\n The card is an object lifted off the (sunken) canvas, so it carries the\n elevation scale rather than expressing depth as one more 1px border —\n elevation was previously almost unused in this module (BOFF-5636).\n Only colour/shadow animate, and only when motion is allowed.\n\n `--color-action-primary-border` exists as a CSS variable but is NOT in the\n shell's Tailwind `@theme`, so `border-action-primary-border` /\n `ring-action-primary-border` emit no CSS at all and the selected state\n rendered with the default border and no ring. Both go through the\n arbitrary `var()` form, which resolves per theme (BOFF-5636).\n */\n className={`\n group relative flex flex-col\n h-full w-full min-w-0\n rounded-card border\n bg-bg-surface\n shadow-[var(--shadow-elevation-1)]\n ${settings.animationsEnabled ? 'motion-safe:transition-[box-shadow,border-color] motion-safe:duration-200' : ''}\n ${\n isSelected && isEditMode\n ? 'border-[var(--color-action-primary-border)] ring-2 ring-[var(--color-action-primary-border)]/30 shadow-[var(--shadow-elevation-2)]'\n : settings.showWidgetBorders\n ? 'border-[var(--color-border-subtle)] hover:border-action-primary-bg hover:shadow-[var(--shadow-elevation-2)]'\n : 'border-transparent'\n }\n ${isEditMode ? 'cursor-pointer' : ''}\n ${className}\n `}\n onMouseDown={handleMouseDown}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n tabIndex={isEditMode ? 0 : -1}\n role={isEditMode ? 'button' : undefined}\n aria-selected={isSelected}\n aria-label={`Widget: ${widget.title}`}\n data-widget-id={widget.id}\n data-widget-type={widget.type}\n >\n {/* Header */}\n <WidgetHeader\n widget={widget}\n previewOnly={previewOnly}\n definition={definition}\n isSelected={isSelected}\n isEditMode={isEditMode}\n isLoading={isLoading}\n isSampleData={isSampleData}\n timeUntilRefresh={widget.refreshInterval && !isPaused ? formatTimeUntilRefresh(timeUntilRefresh) : undefined}\n hasDrilldown={hasDrilldown}\n onRefresh={onRefresh}\n onExportCSV={exportData ? exportCSV : undefined}\n onExportPNG={exportPNG}\n onDrilldown={activeDrilldown ? () => activeDrilldown() : undefined}\n onToggleComments={previewOnly ? undefined : toggleComments}\n commentsOpen={showComments}\n commentCount={commentsEverOpened ? commentCount : undefined}\n />\n\n {/* Content Area — the point of the card, so it gets the room */}\n <div\n className={`\n flex-1 overflow-hidden min-h-0 min-w-0\n ${settings.compactMode ? 'p-2' : 'p-3 sm:p-4'}\n ${showContainerDrilldownHints && !isEditMode ? 'cursor-pointer' : ''}\n `}\n title={showContainerDrilldownHints && !isEditMode ? 'Click data to drill down' : undefined}\n >\n <div className=\"h-full min-w-0 overflow-auto\">{renderContent()}</div>\n </div>\n\n {/*\n v2.0: Widget Actions. A recessed control tray, deliberately lighter than\n the title band above it, so the card is no longer a symmetric sandwich of\n two identically-weighted strips.\n */}\n {actions && actions.length > 0 && !isLoading && !error && (\n <div\n className=\"min-w-0 border-t border-[var(--color-border-subtle)] bg-bg-sunken px-3 py-2 sm:px-4\"\n style={{ flexShrink: 0 }}\n >\n <WidgetActions\n actions={actions}\n context={actionContext}\n onAction={onAction}\n disabled={isEditMode}\n layout=\"horizontal\"\n size=\"sm\"\n />\n </div>\n )}\n\n {/* Edit mode: react-grid-layout provides resize handles */}\n\n {/* Drilldown Indicator */}\n {showContainerDrilldownHints && !isEditMode && (\n <div\n className=\"\n absolute bottom-2 right-2\n opacity-0 group-hover:opacity-100\n transition-opacity duration-200\n \"\n title=\"Click to drill down\"\n >\n <svg className=\"w-4 h-4 text-text-secondary\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M13 7l5 5m0 0l-5 5m5-5H6\" />\n </svg>\n </div>\n )}\n\n {/* Comments panel (overlay) */}\n {showComments && (\n <Suspense fallback={null}>\n <WidgetComments widgetId={widget.id} onClose={() => setShowComments(false)} />\n </Suspense>\n )}\n </div>\n );\n}, arePropsEqual);\n\nexport default WidgetWrapper;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,IAAM,KAAmB,QAAW,OAAO,0BAAiB,MAAM,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC,EACrG,KAAc,QAAW,OAAO,oBAAW,MAAM,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,EACrF,KAAc,QAAW,OAAO,oBAAW,MAAM,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,EACrF,KAAmB,QAAW,OAAO,0BAAiB,MAAM,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC,EACrG,KAAc,QAAW,OAAO,oBAAW,MAAM,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,EACrF,KAAiB,QAAW,OAAO,uBAAc,MAAM,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,CAAC,EAC9F,KAAa,QAAW,OAAO,mBAAU,MAAM,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,CAAC,EAClF,KAAgB,QAAW,OAAO,sBAAa,MAAM,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,CAAC,EAC3F,KAAkB,QAAW,OAAO,wBAAe,MAAM,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,CAAC,EACjG,KAAiB,QAAW,OAAO,uBAAc,MAAM,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,CAAC,EAC9F,KAAe,QAAW,OAAO,qBAAY,MAAM,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,CAAC,EACxF,KAAiB,QAAW,OAAO,uBAAc,MAA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eAAe,GAAgB,GAAM;KAAI,CAAA;IACrE,CAAA;GAET;;GAEP,EAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"MetricCardWidget.d.ts","sourceRoot":"","sources":["../../../../../src/bigconsole/components/widgets/metric-card/MetricCardWidget.tsx"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,EAAE,EAA8B,MAAM,OAAO,CAAC;AAC5D,OAAO,KAAK,EAAE,MAAM,EAAoB,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EAAkB,KAAK,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAS3E,MAAM,WAAW,qBAAqB;IACpC,2BAA2B;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,mBAAmB;IACnB,IAAI,CAAC,EAAE,cAAc,CAAC;IACtB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,+CAA+C;IAC/C,WAAW,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;CAC/D;AAED,MAAM,WAAW,cAAc;IAC7B,+BAA+B;IAC/B,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,oCAAoC;IACpC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sCAAsC;IACtC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+BAA+B;IAC/B,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,4BAA4B;IAC5B,aAAa,CAAC,EAAE,kBAAkB,EAAE,CAAC;IACrC,kCAAkC;IAClC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uCAAuC;IACvC,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AA+ID,eAAO,MAAM,gBAAgB,EAAE,EAAE,CAAC,qBAAqB,CAiTrD,CAAC;AAEH,eAAe,gBAAgB,CAAC"}
1
+ {"version":3,"file":"MetricCardWidget.d.ts","sourceRoot":"","sources":["../../../../../src/bigconsole/components/widgets/metric-card/MetricCardWidget.tsx"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,EAAE,EAA8B,MAAM,OAAO,CAAC;AAC5D,OAAO,KAAK,EAAE,MAAM,EAAoB,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EAAkB,KAAK,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAS3E,MAAM,WAAW,qBAAqB;IACpC,2BAA2B;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,mBAAmB;IACnB,IAAI,CAAC,EAAE,cAAc,CAAC;IACtB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,+CAA+C;IAC/C,WAAW,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;CAC/D;AAED,MAAM,WAAW,cAAc;IAC7B,+BAA+B;IAC/B,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,oCAAoC;IACpC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sCAAsC;IACtC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+BAA+B;IAC/B,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,4BAA4B;IAC5B,aAAa,CAAC,EAAE,kBAAkB,EAAE,CAAC;IACrC,kCAAkC;IAClC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uCAAuC;IACvC,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AA+ID,eAAO,MAAM,gBAAgB,EAAE,EAAE,CAAC,qBAAqB,CAmTrD,CAAC;AAEH,eAAe,gBAAgB,CAAC"}
@@ -135,9 +135,10 @@ var b = u(function({ widget: u, data: h, onClick: b, onDrilldown: x }) {
135
135
  ]), N = !!(x || b && u.drilldowns?.length);
136
136
  return /* @__PURE__ */ m("div", {
137
137
  className: `
138
- flex flex-col h-full p-4
138
+ flex min-w-0 flex-col h-full p-4
139
139
  ${N ? "cursor-pointer hover:bg-bg-sunken/50 transition-colors" : ""}
140
140
  `,
141
+ style: { containerType: "inline-size" },
141
142
  onClick: M,
142
143
  role: N ? "button" : void 0,
143
144
  tabIndex: N ? 0 : void 0,
@@ -150,10 +151,11 @@ var b = u(function({ widget: u, data: h, onClick: b, onDrilldown: x }) {
150
151
  children: S.subtitle
151
152
  }),
152
153
  /* @__PURE__ */ m("div", {
153
- className: "flex items-baseline gap-2 mb-2",
154
+ className: "flex min-w-0 flex-wrap items-baseline gap-2 mb-2",
154
155
  children: [/* @__PURE__ */ p("span", {
155
- className: `text-3xl font-semibold tracking-tight ${j || "text-text-primary"}`,
156
- title: String(C?.value),
156
+ className: `min-w-0 max-w-full [overflow-wrap:anywhere] font-semibold tracking-tight ${j || "text-text-primary"}`,
157
+ style: { fontSize: "clamp(1rem, 12cqi, 1.875rem)" },
158
+ title: O,
157
159
  children: O
158
160
  }), S?.showTrend !== !1 && T && /* @__PURE__ */ p(c, {
159
161
  direction: w,
@@ -1 +1 @@
1
- {"version":3,"file":"MetricCardWidget.js","names":[],"sources":["../../../../../src/bigconsole/components/widgets/metric-card/MetricCardWidget.tsx"],"sourcesContent":["/**\n * MetricCardWidget Component\n *\n * Displays a single KPI/metric with trend, comparison, and optional sparkline.\n */\n\nimport { type FC, memo, useMemo, useCallback } from 'react';\nimport type { Widget, MetricCardConfig } from '../../../types';\nimport { TrendIndicator, type TrendDirection } from './TrendIndicator';\nimport { ComparisonBadge } from './ComparisonBadge';\nimport { SparklineChart, type SparklineDataPoint } from './SparklineChart';\nimport { firstObjectRow, inferValueField, unwrapRows } from '../utils/inferFields';\nimport { resolveConditionalStyle, conditionalStyleToClassName } from '../utils/conditionalFormat';\nimport { getTargetProgress, clampProgressWidth } from '../utils/targetProgress';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface MetricCardWidgetProps {\n /** Widget configuration */\n widget: Widget;\n /** Fetched data */\n data?: MetricCardData;\n /** Click handler for drilldown */\n onClick?: () => void;\n /** Drilldown handler - receives metric data */\n onDrilldown?: (selectedData: Record<string, unknown>) => void;\n}\n\nexport interface MetricCardData {\n /** Primary value to display */\n value: number | string;\n /** Previous value for comparison */\n previousValue?: number;\n /** Percentage change from previous */\n changePercent?: number;\n /** Trend direction override */\n trend?: TrendDirection;\n /** Sparkline data points */\n sparklineData?: SparklineDataPoint[];\n /** Target value for comparison */\n target?: number;\n /** Unit label (e.g., \"users\", \"$\") */\n unit?: string;\n /** Whether the metric is a currency */\n isCurrency?: boolean;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * ISO-4217 codes are exactly three letters (\"USD\"); anything else is a display\n * label (\"users\", \"ms\").\n *\n * This regex is also the safety guard on untrusted parser data: `Intl.NumberFormat`\n * throws `RangeError` for a *malformed* currency (anything that is not exactly\n * three ASCII letters — e.g. `'ms'`), but accepts any well-formed code and simply\n * renders it verbatim when unregistered (`'RPS'` -> \"RPS 243.00\"). Returning\n * undefined for everything that is not three ASCII letters means a malformed\n * value can never reach `Intl`, so no try/catch is needed downstream. Keep this\n * predicate at least as strict if it is ever changed.\n */\nfunction currencyCodeFrom(unit?: string): string | undefined {\n return unit !== undefined && /^[a-z]{3}$/i.test(unit) ? unit.toUpperCase() : undefined;\n}\n\ninterface ResolvedFormat {\n style: 'currency' | 'percentage' | 'compact' | 'number';\n currency: string;\n /** Payload unit rendered as a trailing label; undefined when the style or config already covers it. */\n unitSuffix?: string;\n}\n\n/**\n * Decide the numeric style, honouring the payload without ever overriding the user.\n *\n * `MetricCardData` documents `unit` and `isCurrency`, but nothing read them — a\n * parser emitting `{value: 482350.75, unit: \"USD\", isCurrency: true}` rendered a\n * bare \"482,350.75\". They cannot simply take precedence though: WidgetRegistry\n * seeds `format` onto every card, so a persisted `'number'` is indistinguishable\n * from a deliberate choice. `'auto'` is the sentinel that defers to the payload.\n */\nfunction resolveFormat(config?: MetricCardConfig, data?: MetricCardData): ResolvedFormat {\n const configured = config?.format;\n const explicit = configured !== undefined && configured !== 'auto';\n\n const style: ResolvedFormat['style'] = explicit\n ? configured === 'currency' || configured === 'percentage' || configured === 'compact'\n ? configured\n : 'number' // 'number' and legacy 'decimal' both render as a plain number.\n : data?.isCurrency === true\n ? 'currency'\n : 'number';\n\n return {\n style,\n currency: currencyCodeFrom(data?.unit) ?? 'USD',\n // A currency render already carries its symbol, and config.suffix is the\n // user's own unit channel — neither should be doubled up.\n unitSuffix: style === 'currency' || config?.suffix ? undefined : data?.unit,\n };\n}\n\n/**\n * Format a number based on configuration\n */\nfunction formatValue(value: number | string, config: MetricCardConfig | undefined, resolved: ResolvedFormat): string {\n if (typeof value === 'string') return value;\n\n const { prefix, suffix, decimalPlaces } = config || {};\n const format = resolved.style;\n\n // `decimalPlaces` is seeded onto every metric card by WidgetRegistry and is\n // set explicitly by templated/seeded dashboards, so it must drive the\n // fraction digits. Clamp to the Intl-legal 0–20 range; when a legacy widget\n // omits the key we keep the previous per-format defaults.\n const fixedDigits =\n typeof decimalPlaces === 'number' && Number.isFinite(decimalPlaces)\n ? Math.min(Math.max(Math.trunc(decimalPlaces), 0), 20)\n : undefined;\n\n let formatted: string;\n\n switch (format) {\n case 'currency':\n formatted = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: resolved.currency,\n minimumFractionDigits: fixedDigits ?? 0,\n maximumFractionDigits: fixedDigits ?? 2,\n }).format(value);\n break;\n\n case 'percentage':\n formatted = `${(value * 100).toFixed(fixedDigits ?? 1)}%`;\n break;\n\n case 'compact':\n formatted = new Intl.NumberFormat('en-US', {\n notation: 'compact',\n minimumFractionDigits: fixedDigits,\n maximumFractionDigits: fixedDigits ?? 1,\n }).format(value);\n break;\n\n case 'number':\n default:\n formatted = new Intl.NumberFormat('en-US', {\n minimumFractionDigits: fixedDigits,\n maximumFractionDigits: fixedDigits ?? 2,\n }).format(value);\n }\n\n // Apply prefix/suffix if provided\n if (prefix) formatted = `${prefix}${formatted}`;\n if (suffix) formatted = `${formatted}${suffix}`;\n\n // Payload unit (\"users\", \"ms\"). The endsWith guard avoids \"97.3% %\" when the\n // style already emits the symbol.\n if (resolved.unitSuffix && !formatted.endsWith(resolved.unitSuffix)) {\n formatted = `${formatted} ${resolved.unitSuffix}`;\n }\n\n return formatted;\n}\n\n/**\n * Calculate trend direction from change percent\n */\nfunction calculateTrend(changePercent?: number): TrendDirection {\n if (changePercent === undefined || changePercent === 0) return 'flat';\n return changePercent > 0 ? 'up' : 'down';\n}\n\n/**\n * Get sparkline color based on trend\n */\nfunction getSparklineColor(trend: TrendDirection, positiveIsGood: boolean): 'success' | 'error' | 'muted' {\n if (trend === 'flat') return 'muted';\n const isGood = positiveIsGood ? trend === 'up' : trend === 'down';\n return isGood ? 'success' : 'error';\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nexport const MetricCardWidget: FC<MetricCardWidgetProps> = memo(function MetricCardWidget({\n widget,\n data: rawData,\n onClick,\n onDrilldown,\n}) {\n const config = widget.config as unknown as MetricCardConfig | undefined;\n\n // Normalize data - extract value from object if valueField is configured\n const data = useMemo((): MetricCardData | undefined => {\n if (!rawData) return undefined;\n\n // Helper to get nested value using dot notation (e.g., \"summary.totalSales\")\n const getNestedValue = (obj: Record<string, unknown>, path: string): unknown => {\n return path.split('.').reduce((current, key) => {\n return current && typeof current === 'object' ? (current as Record<string, unknown>)[key] : undefined;\n }, obj as unknown);\n };\n\n // A parser can return a bare scalar (e.g. `. | length` -> 127). Handle that\n // up front: the `in` operator below throws \"Cannot use 'in' operator to\n // search for 'value' in 127\" when rawData is a primitive, which the widget\n // error boundary surfaces as \"Failed to render\" (BOFF-4110).\n if (typeof rawData === 'number' || typeof rawData === 'string') {\n return { value: rawData };\n }\n\n // An explicit `config.valueField` mapping is authoritative and MUST be\n // resolved BEFORE the `value` pass-through below. Otherwise a payload that\n // merely happens to carry a top-level `value` silently overrides the field\n // the user picked in the inspector — e.g. `{status, value, p95LatencyMs}`\n // with valueField \"p95LatencyMs\" rendered the health flag, not the latency.\n const valueField = (config as unknown as Record<string, unknown> | undefined)?.valueField as string | undefined;\n if (valueField && typeof rawData === 'object') {\n const envelope = rawData as unknown as Record<string, unknown>;\n const extractedValue = getNestedValue(envelope, valueField);\n if (extractedValue !== undefined) {\n // Also try to extract previousValue if previousValueField is configured\n const previousValueField = (config as unknown as Record<string, unknown> | undefined)?.previousValueField as\n string | undefined;\n const previousValue = previousValueField\n ? (getNestedValue(envelope, previousValueField) as number | undefined)\n : undefined;\n\n // Spread the envelope first so sibling presentation fields the\n // pass-through used to supply (target, unit, trend, sparklineData…)\n // survive when a valueField mapping is configured.\n // A configured previousValueField derives the comparison from the\n // mapped field. Without one, the envelope's own previousValue /\n // changePercent stand — assigning undefined here would spread the\n // envelope and then immediately blank the very fields it supplied.\n // Guard the divisor — a previousValue of 0 would yield Infinity and\n // render \"Infinity%\" in the comparison badge. When we cannot compute a\n // change, keep whatever the envelope already carried rather than\n // blanking it: a source may legitimately pre-compute a change against a\n // zero baseline.\n const computedChange =\n previousValue !== undefined &&\n previousValue !== 0 &&\n Number.isFinite(previousValue) &&\n typeof extractedValue === 'number'\n ? ((extractedValue - previousValue) / previousValue) * 100\n : undefined;\n const envelopeChange = (rawData as MetricCardData).changePercent;\n const derivedComparison =\n previousValue !== undefined\n ? {\n previousValue,\n changePercent: computedChange ?? (Number.isFinite(envelopeChange) ? envelopeChange : undefined),\n }\n : {};\n\n return {\n ...(rawData as MetricCardData),\n value: extractedValue as number | string,\n ...derivedComparison,\n };\n }\n }\n\n // If data already has 'value' property, use it directly. Guard the `in`\n // operator with an object check — it only accepts an object on the RHS.\n if (typeof rawData === 'object' && 'value' in rawData && rawData.value !== undefined) {\n return rawData as MetricCardData;\n }\n\n // Try common field names at top level\n const commonFields = ['value', 'total', 'amount', 'count', 'sum', 'totalSales', 'totalRevenue', 'totalOrders'];\n for (const field of commonFields) {\n if (typeof rawData === 'object' && field in rawData) {\n const val = (rawData as unknown as Record<string, unknown>)[field];\n if (typeof val === 'number' || typeof val === 'string') {\n return { value: val };\n }\n }\n }\n\n // Try looking in nested 'summary' object (common pattern)\n if (typeof rawData === 'object' && 'summary' in rawData) {\n const summary = (rawData as Record<string, unknown>).summary as Record<string, unknown> | undefined;\n if (summary && typeof summary === 'object') {\n for (const field of commonFields) {\n if (field in summary) {\n const val = summary[field];\n if (typeof val === 'number' || typeof val === 'string') {\n return { value: val };\n }\n }\n }\n }\n }\n\n // If rawData is a number or string directly, use it\n if (typeof rawData === 'number' || typeof rawData === 'string') {\n return { value: rawData };\n }\n\n // BOFF-2246 smart default: if rawData is an array (or envelope around an\n // array) with object rows, use the configured valueField if it resolves\n // on any row (supports dotted paths like \"metrics.revenue\") — otherwise\n // pick the first numeric field from row[0]. This path only fires when\n // the earlier top-level extraction didn't find anything, but an explicit\n // `config.valueField` (flat or dotted) must always win over inference.\n const firstRow = firstObjectRow(rawData);\n if (firstRow) {\n const configuredField = (config as unknown as Record<string, unknown> | undefined)?.valueField as\n string | undefined;\n if (configuredField) {\n // Configured field is authoritative. Scan every row for it so sparse\n // envelopes like `{data:[{id:1},{revenue:120}]}` with\n // `valueField:\"revenue\"` still resolve. If no row carries it, return\n // undefined rather than substituting an unrelated numeric column\n // from row[0] (that would silently misrepresent the user's mapping).\n const rows = unwrapRows(rawData) ?? [firstRow];\n for (const r of rows) {\n if (r && typeof r === 'object') {\n const resolved = getNestedValue(r as Record<string, unknown>, configuredField);\n if (typeof resolved === 'number' || typeof resolved === 'string') {\n return { value: resolved };\n }\n }\n }\n return undefined;\n }\n const inferredField = inferValueField(firstRow);\n if (inferredField) {\n const val = firstRow[inferredField];\n if (typeof val === 'number' || typeof val === 'string') {\n return { value: val };\n }\n }\n }\n\n return undefined;\n }, [rawData, config]);\n\n // Calculate derived values\n const trend = useMemo(() => {\n return data?.trend || calculateTrend(data?.changePercent);\n }, [data?.trend, data?.changePercent]);\n\n // The arrow is renderable when the payload carries an explicit direction\n // override OR a change percentage to derive one from. Gating solely on\n // `changePercent` meant a `trend`-only payload — a documented field of\n // MetricCardData, and one the sparkline colour and drilldown payload already\n // honour — rendered no indicator at all despite `showTrend` being enabled.\n // Without either field `trend` collapses to a meaningless 'flat', so we\n // still render nothing.\n const hasTrendSignal = data?.trend !== undefined || data?.changePercent !== undefined;\n\n const positiveIsGood = config?.positiveIsGood ?? true;\n\n const resolvedFormat = useMemo(() => resolveFormat(config, data), [config, data]);\n\n const formattedValue = useMemo(() => {\n // Treat 0 / \"\" as real values — only a missing value renders the em dash.\n // (`if (!data?.value)` would wrongly blank out a legitimate 0, e.g. an ED\n // boarding-compliance of 0% or an available-bed count of 0.)\n if (data?.value === undefined || data?.value === null) return '—';\n return formatValue(data.value, config, resolvedFormat);\n }, [data?.value, config, resolvedFormat]);\n\n // Null whenever no meaningful ratio exists, which also gates the whole\n // target block. Resolving `valueField` before the `value` pass-through made\n // a numeric value reachable alongside a `target: 0` from the same envelope,\n // so the previously-unreachable division now needs a real guard.\n const targetProgress = useMemo(() => getTargetProgress(data?.value, data?.target), [data?.value, data?.target]);\n\n const sparklineColor = useMemo(() => {\n return getSparklineColor(trend, positiveIsGood);\n }, [trend, positiveIsGood]);\n\n // Conditional formatting on the metric value (threshold-driven color, not\n // just trend direction). Falls back to the default primary text color.\n const valueConditionalClass = useMemo(() => {\n const style = resolveConditionalStyle(data?.value, config?.conditionalRules);\n return conditionalStyleToClassName(style);\n }, [data?.value, config?.conditionalRules]);\n\n // Handle click\n const handleClick = useCallback(() => {\n // Support both legacy onClick and new onDrilldown\n if (onDrilldown) {\n onDrilldown({\n value: data?.value,\n changePercent: data?.changePercent,\n trend,\n target: data?.target,\n });\n } else if (onClick && widget.drilldowns?.length) {\n onClick();\n }\n }, [onClick, onDrilldown, widget.drilldowns, data, trend]);\n\n // Determine if clickable\n const isClickable = Boolean(onDrilldown || (onClick && widget.drilldowns?.length));\n\n return (\n <div\n className={`\n flex flex-col h-full p-4\n ${isClickable ? 'cursor-pointer hover:bg-bg-sunken/50 transition-colors' : ''}\n `}\n onClick={handleClick}\n role={isClickable ? 'button' : undefined}\n tabIndex={isClickable ? 0 : undefined}\n onKeyDown={(e) => {\n if (isClickable && (e.key === 'Enter' || e.key === ' ')) {\n e.preventDefault();\n handleClick();\n }\n }}\n >\n {/* Subtitle/Label */}\n {config?.subtitle && <p className=\"text-xs text-text-secondary mb-1 truncate\">{config.subtitle}</p>}\n\n {/* Main Value */}\n <div className=\"flex items-baseline gap-2 mb-2\">\n <span\n className={`text-3xl font-semibold tracking-tight ${valueConditionalClass || 'text-text-primary'}`}\n title={String(data?.value)}\n >\n {formattedValue}\n </span>\n\n {/* Trend Indicator (inline) */}\n {config?.showTrend !== false && hasTrendSignal && (\n <TrendIndicator direction={trend} size=\"md\" positiveIsGood={positiveIsGood} />\n )}\n </div>\n\n {/* Comparison Badge */}\n {config?.showComparison !== false && data?.changePercent !== undefined && (\n <div className=\"mb-3\">\n <ComparisonBadge\n value={data.changePercent}\n label={config?.comparisonLabel}\n positiveIsGood={positiveIsGood}\n size=\"sm\"\n />\n </div>\n )}\n\n {/* Target Progress */}\n {targetProgress !== null && data?.target !== undefined && (\n <div className=\"mb-3\">\n <div className=\"flex justify-between text-xs text-text-secondary mb-1\">\n <span>Target: {formatValue(data.target, config, resolvedFormat)}</span>\n <span>{targetProgress.toFixed(0)}%</span>\n </div>\n <div className=\"h-1.5 bg-bg-sunken rounded-full overflow-hidden\">\n <div\n className={`h-full rounded-full transition-all ${\n targetProgress >= 100 ? 'bg-status-success-bg' : 'bg-action-primary-bg'\n }`}\n style={{\n // Clamp both ends — a negative value would otherwise emit a\n // negative width, which the browser drops entirely.\n width: `${clampProgressWidth(targetProgress)}%`,\n }}\n />\n </div>\n </div>\n )}\n\n {/* Sparkline */}\n {config?.showSparkline !== false && data?.sparklineData?.length ? (\n <div className=\"mt-auto pt-2\">\n <SparklineChart data={data.sparklineData} width={120} height={32} color={sparklineColor} showFill />\n </div>\n ) : null}\n\n {/* Drilldown Indicator */}\n {isClickable && (\n <div className=\"mt-auto pt-2 flex items-center justify-end\">\n <span className=\"text-xs text-text-secondary flex items-center gap-1\">\n View details\n <svg className=\"w-3 h-3\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M9 5l7 7-7 7\" />\n </svg>\n </span>\n </div>\n )}\n </div>\n );\n});\n\nexport default MetricCardWidget;\n"],"mappings":";;;;;;;;;AAiEA,SAAS,EAAiB,GAAmC;AAC3D,QAAO,MAAS,KAAA,KAAa,cAAc,KAAK,EAAK,GAAG,EAAK,aAAa,GAAG,KAAA;;AAmB/E,SAAS,EAAc,GAA2B,GAAuC;CACvF,IAAM,IAAa,GAAQ,QAGrB,IAFW,MAAe,KAAA,KAAa,MAAe,SAGxD,MAAe,cAAc,MAAe,gBAAgB,MAAe,YACzE,IACA,WACF,GAAM,eAAe,KACnB,aACA;AAEN,QAAO;EACL;EACA,UAAU,EAAiB,GAAM,KAAK,IAAI;EAG1C,YAAY,MAAU,cAAc,GAAQ,SAAS,KAAA,IAAY,GAAM;EACxE;;AAMH,SAAS,EAAY,GAAwB,GAAsC,GAAkC;AACnH,KAAI,OAAO,KAAU,SAAU,QAAO;CAEtC,IAAM,EAAE,WAAQ,WAAQ,qBAAkB,KAAU,EAAE,EAChD,IAAS,EAAS,OAMlB,IACJ,OAAO,KAAkB,YAAY,OAAO,SAAS,EAAc,GAC/D,KAAK,IAAI,KAAK,IAAI,KAAK,MAAM,EAAc,EAAE,EAAE,EAAE,GAAG,GACpD,KAAA,GAEF;AAEJ,SAAQ,GAAR;EACE,KAAK;AACH,OAAY,IAAI,KAAK,aAAa,SAAS;IACzC,OAAO;IAC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,GAAM,eAAe,SACvD,kBAAC,OAAD;IAAK,WAAU;cACb,kBAAC,GAAD;KAAgB,MAAM,EAAK;KAAe,OAAO;KAAK,QAAQ;KAAI,OAAO;KAAgB,UAAA;KAAW,CAAA;IAChG,CAAA,GACJ;GAGH,KACC,kBAAC,OAAD;IAAK,WAAU;cACb,kBAAC,QAAD;KAAM,WAAU;eAAhB,CAAsE,gBAEpE,kBAAC,OAAD;MAAK,WAAU;MAAU,MAAK;MAAO,QAAO;MAAe,SAAQ;gBACjE,kBAAC,QAAD;OAAM,eAAc;OAAQ,gBAAe;OAAQ,aAAa;OAAG,GAAE;OAAiB,CAAA;MAClF,CAAA,CACD;;IACH,CAAA;GAEJ;;EAER"}
1
+ {"version":3,"file":"MetricCardWidget.js","names":[],"sources":["../../../../../src/bigconsole/components/widgets/metric-card/MetricCardWidget.tsx"],"sourcesContent":["/**\n * MetricCardWidget Component\n *\n * Displays a single KPI/metric with trend, comparison, and optional sparkline.\n */\n\nimport { type FC, memo, useMemo, useCallback } from 'react';\nimport type { Widget, MetricCardConfig } from '../../../types';\nimport { TrendIndicator, type TrendDirection } from './TrendIndicator';\nimport { ComparisonBadge } from './ComparisonBadge';\nimport { SparklineChart, type SparklineDataPoint } from './SparklineChart';\nimport { firstObjectRow, inferValueField, unwrapRows } from '../utils/inferFields';\nimport { resolveConditionalStyle, conditionalStyleToClassName } from '../utils/conditionalFormat';\nimport { getTargetProgress, clampProgressWidth } from '../utils/targetProgress';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface MetricCardWidgetProps {\n /** Widget configuration */\n widget: Widget;\n /** Fetched data */\n data?: MetricCardData;\n /** Click handler for drilldown */\n onClick?: () => void;\n /** Drilldown handler - receives metric data */\n onDrilldown?: (selectedData: Record<string, unknown>) => void;\n}\n\nexport interface MetricCardData {\n /** Primary value to display */\n value: number | string;\n /** Previous value for comparison */\n previousValue?: number;\n /** Percentage change from previous */\n changePercent?: number;\n /** Trend direction override */\n trend?: TrendDirection;\n /** Sparkline data points */\n sparklineData?: SparklineDataPoint[];\n /** Target value for comparison */\n target?: number;\n /** Unit label (e.g., \"users\", \"$\") */\n unit?: string;\n /** Whether the metric is a currency */\n isCurrency?: boolean;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * ISO-4217 codes are exactly three letters (\"USD\"); anything else is a display\n * label (\"users\", \"ms\").\n *\n * This regex is also the safety guard on untrusted parser data: `Intl.NumberFormat`\n * throws `RangeError` for a *malformed* currency (anything that is not exactly\n * three ASCII letters — e.g. `'ms'`), but accepts any well-formed code and simply\n * renders it verbatim when unregistered (`'RPS'` -> \"RPS 243.00\"). Returning\n * undefined for everything that is not three ASCII letters means a malformed\n * value can never reach `Intl`, so no try/catch is needed downstream. Keep this\n * predicate at least as strict if it is ever changed.\n */\nfunction currencyCodeFrom(unit?: string): string | undefined {\n return unit !== undefined && /^[a-z]{3}$/i.test(unit) ? unit.toUpperCase() : undefined;\n}\n\ninterface ResolvedFormat {\n style: 'currency' | 'percentage' | 'compact' | 'number';\n currency: string;\n /** Payload unit rendered as a trailing label; undefined when the style or config already covers it. */\n unitSuffix?: string;\n}\n\n/**\n * Decide the numeric style, honouring the payload without ever overriding the user.\n *\n * `MetricCardData` documents `unit` and `isCurrency`, but nothing read them — a\n * parser emitting `{value: 482350.75, unit: \"USD\", isCurrency: true}` rendered a\n * bare \"482,350.75\". They cannot simply take precedence though: WidgetRegistry\n * seeds `format` onto every card, so a persisted `'number'` is indistinguishable\n * from a deliberate choice. `'auto'` is the sentinel that defers to the payload.\n */\nfunction resolveFormat(config?: MetricCardConfig, data?: MetricCardData): ResolvedFormat {\n const configured = config?.format;\n const explicit = configured !== undefined && configured !== 'auto';\n\n const style: ResolvedFormat['style'] = explicit\n ? configured === 'currency' || configured === 'percentage' || configured === 'compact'\n ? configured\n : 'number' // 'number' and legacy 'decimal' both render as a plain number.\n : data?.isCurrency === true\n ? 'currency'\n : 'number';\n\n return {\n style,\n currency: currencyCodeFrom(data?.unit) ?? 'USD',\n // A currency render already carries its symbol, and config.suffix is the\n // user's own unit channel — neither should be doubled up.\n unitSuffix: style === 'currency' || config?.suffix ? undefined : data?.unit,\n };\n}\n\n/**\n * Format a number based on configuration\n */\nfunction formatValue(value: number | string, config: MetricCardConfig | undefined, resolved: ResolvedFormat): string {\n if (typeof value === 'string') return value;\n\n const { prefix, suffix, decimalPlaces } = config || {};\n const format = resolved.style;\n\n // `decimalPlaces` is seeded onto every metric card by WidgetRegistry and is\n // set explicitly by templated/seeded dashboards, so it must drive the\n // fraction digits. Clamp to the Intl-legal 0–20 range; when a legacy widget\n // omits the key we keep the previous per-format defaults.\n const fixedDigits =\n typeof decimalPlaces === 'number' && Number.isFinite(decimalPlaces)\n ? Math.min(Math.max(Math.trunc(decimalPlaces), 0), 20)\n : undefined;\n\n let formatted: string;\n\n switch (format) {\n case 'currency':\n formatted = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: resolved.currency,\n minimumFractionDigits: fixedDigits ?? 0,\n maximumFractionDigits: fixedDigits ?? 2,\n }).format(value);\n break;\n\n case 'percentage':\n formatted = `${(value * 100).toFixed(fixedDigits ?? 1)}%`;\n break;\n\n case 'compact':\n formatted = new Intl.NumberFormat('en-US', {\n notation: 'compact',\n minimumFractionDigits: fixedDigits,\n maximumFractionDigits: fixedDigits ?? 1,\n }).format(value);\n break;\n\n case 'number':\n default:\n formatted = new Intl.NumberFormat('en-US', {\n minimumFractionDigits: fixedDigits,\n maximumFractionDigits: fixedDigits ?? 2,\n }).format(value);\n }\n\n // Apply prefix/suffix if provided\n if (prefix) formatted = `${prefix}${formatted}`;\n if (suffix) formatted = `${formatted}${suffix}`;\n\n // Payload unit (\"users\", \"ms\"). The endsWith guard avoids \"97.3% %\" when the\n // style already emits the symbol.\n if (resolved.unitSuffix && !formatted.endsWith(resolved.unitSuffix)) {\n formatted = `${formatted} ${resolved.unitSuffix}`;\n }\n\n return formatted;\n}\n\n/**\n * Calculate trend direction from change percent\n */\nfunction calculateTrend(changePercent?: number): TrendDirection {\n if (changePercent === undefined || changePercent === 0) return 'flat';\n return changePercent > 0 ? 'up' : 'down';\n}\n\n/**\n * Get sparkline color based on trend\n */\nfunction getSparklineColor(trend: TrendDirection, positiveIsGood: boolean): 'success' | 'error' | 'muted' {\n if (trend === 'flat') return 'muted';\n const isGood = positiveIsGood ? trend === 'up' : trend === 'down';\n return isGood ? 'success' : 'error';\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nexport const MetricCardWidget: FC<MetricCardWidgetProps> = memo(function MetricCardWidget({\n widget,\n data: rawData,\n onClick,\n onDrilldown,\n}) {\n const config = widget.config as unknown as MetricCardConfig | undefined;\n\n // Normalize data - extract value from object if valueField is configured\n const data = useMemo((): MetricCardData | undefined => {\n if (!rawData) return undefined;\n\n // Helper to get nested value using dot notation (e.g., \"summary.totalSales\")\n const getNestedValue = (obj: Record<string, unknown>, path: string): unknown => {\n return path.split('.').reduce((current, key) => {\n return current && typeof current === 'object' ? (current as Record<string, unknown>)[key] : undefined;\n }, obj as unknown);\n };\n\n // A parser can return a bare scalar (e.g. `. | length` -> 127). Handle that\n // up front: the `in` operator below throws \"Cannot use 'in' operator to\n // search for 'value' in 127\" when rawData is a primitive, which the widget\n // error boundary surfaces as \"Failed to render\" (BOFF-4110).\n if (typeof rawData === 'number' || typeof rawData === 'string') {\n return { value: rawData };\n }\n\n // An explicit `config.valueField` mapping is authoritative and MUST be\n // resolved BEFORE the `value` pass-through below. Otherwise a payload that\n // merely happens to carry a top-level `value` silently overrides the field\n // the user picked in the inspector — e.g. `{status, value, p95LatencyMs}`\n // with valueField \"p95LatencyMs\" rendered the health flag, not the latency.\n const valueField = (config as unknown as Record<string, unknown> | undefined)?.valueField as string | undefined;\n if (valueField && typeof rawData === 'object') {\n const envelope = rawData as unknown as Record<string, unknown>;\n const extractedValue = getNestedValue(envelope, valueField);\n if (extractedValue !== undefined) {\n // Also try to extract previousValue if previousValueField is configured\n const previousValueField = (config as unknown as Record<string, unknown> | undefined)?.previousValueField as\n string | undefined;\n const previousValue = previousValueField\n ? (getNestedValue(envelope, previousValueField) as number | undefined)\n : undefined;\n\n // Spread the envelope first so sibling presentation fields the\n // pass-through used to supply (target, unit, trend, sparklineData…)\n // survive when a valueField mapping is configured.\n // A configured previousValueField derives the comparison from the\n // mapped field. Without one, the envelope's own previousValue /\n // changePercent stand — assigning undefined here would spread the\n // envelope and then immediately blank the very fields it supplied.\n // Guard the divisor — a previousValue of 0 would yield Infinity and\n // render \"Infinity%\" in the comparison badge. When we cannot compute a\n // change, keep whatever the envelope already carried rather than\n // blanking it: a source may legitimately pre-compute a change against a\n // zero baseline.\n const computedChange =\n previousValue !== undefined &&\n previousValue !== 0 &&\n Number.isFinite(previousValue) &&\n typeof extractedValue === 'number'\n ? ((extractedValue - previousValue) / previousValue) * 100\n : undefined;\n const envelopeChange = (rawData as MetricCardData).changePercent;\n const derivedComparison =\n previousValue !== undefined\n ? {\n previousValue,\n changePercent: computedChange ?? (Number.isFinite(envelopeChange) ? envelopeChange : undefined),\n }\n : {};\n\n return {\n ...(rawData as MetricCardData),\n value: extractedValue as number | string,\n ...derivedComparison,\n };\n }\n }\n\n // If data already has 'value' property, use it directly. Guard the `in`\n // operator with an object check — it only accepts an object on the RHS.\n if (typeof rawData === 'object' && 'value' in rawData && rawData.value !== undefined) {\n return rawData as MetricCardData;\n }\n\n // Try common field names at top level\n const commonFields = ['value', 'total', 'amount', 'count', 'sum', 'totalSales', 'totalRevenue', 'totalOrders'];\n for (const field of commonFields) {\n if (typeof rawData === 'object' && field in rawData) {\n const val = (rawData as unknown as Record<string, unknown>)[field];\n if (typeof val === 'number' || typeof val === 'string') {\n return { value: val };\n }\n }\n }\n\n // Try looking in nested 'summary' object (common pattern)\n if (typeof rawData === 'object' && 'summary' in rawData) {\n const summary = (rawData as Record<string, unknown>).summary as Record<string, unknown> | undefined;\n if (summary && typeof summary === 'object') {\n for (const field of commonFields) {\n if (field in summary) {\n const val = summary[field];\n if (typeof val === 'number' || typeof val === 'string') {\n return { value: val };\n }\n }\n }\n }\n }\n\n // If rawData is a number or string directly, use it\n if (typeof rawData === 'number' || typeof rawData === 'string') {\n return { value: rawData };\n }\n\n // BOFF-2246 smart default: if rawData is an array (or envelope around an\n // array) with object rows, use the configured valueField if it resolves\n // on any row (supports dotted paths like \"metrics.revenue\") — otherwise\n // pick the first numeric field from row[0]. This path only fires when\n // the earlier top-level extraction didn't find anything, but an explicit\n // `config.valueField` (flat or dotted) must always win over inference.\n const firstRow = firstObjectRow(rawData);\n if (firstRow) {\n const configuredField = (config as unknown as Record<string, unknown> | undefined)?.valueField as\n string | undefined;\n if (configuredField) {\n // Configured field is authoritative. Scan every row for it so sparse\n // envelopes like `{data:[{id:1},{revenue:120}]}` with\n // `valueField:\"revenue\"` still resolve. If no row carries it, return\n // undefined rather than substituting an unrelated numeric column\n // from row[0] (that would silently misrepresent the user's mapping).\n const rows = unwrapRows(rawData) ?? [firstRow];\n for (const r of rows) {\n if (r && typeof r === 'object') {\n const resolved = getNestedValue(r as Record<string, unknown>, configuredField);\n if (typeof resolved === 'number' || typeof resolved === 'string') {\n return { value: resolved };\n }\n }\n }\n return undefined;\n }\n const inferredField = inferValueField(firstRow);\n if (inferredField) {\n const val = firstRow[inferredField];\n if (typeof val === 'number' || typeof val === 'string') {\n return { value: val };\n }\n }\n }\n\n return undefined;\n }, [rawData, config]);\n\n // Calculate derived values\n const trend = useMemo(() => {\n return data?.trend || calculateTrend(data?.changePercent);\n }, [data?.trend, data?.changePercent]);\n\n // The arrow is renderable when the payload carries an explicit direction\n // override OR a change percentage to derive one from. Gating solely on\n // `changePercent` meant a `trend`-only payload — a documented field of\n // MetricCardData, and one the sparkline colour and drilldown payload already\n // honour — rendered no indicator at all despite `showTrend` being enabled.\n // Without either field `trend` collapses to a meaningless 'flat', so we\n // still render nothing.\n const hasTrendSignal = data?.trend !== undefined || data?.changePercent !== undefined;\n\n const positiveIsGood = config?.positiveIsGood ?? true;\n\n const resolvedFormat = useMemo(() => resolveFormat(config, data), [config, data]);\n\n const formattedValue = useMemo(() => {\n // Treat 0 / \"\" as real values — only a missing value renders the em dash.\n // (`if (!data?.value)` would wrongly blank out a legitimate 0, e.g. an ED\n // boarding-compliance of 0% or an available-bed count of 0.)\n if (data?.value === undefined || data?.value === null) return '—';\n return formatValue(data.value, config, resolvedFormat);\n }, [data?.value, config, resolvedFormat]);\n\n // Null whenever no meaningful ratio exists, which also gates the whole\n // target block. Resolving `valueField` before the `value` pass-through made\n // a numeric value reachable alongside a `target: 0` from the same envelope,\n // so the previously-unreachable division now needs a real guard.\n const targetProgress = useMemo(() => getTargetProgress(data?.value, data?.target), [data?.value, data?.target]);\n\n const sparklineColor = useMemo(() => {\n return getSparklineColor(trend, positiveIsGood);\n }, [trend, positiveIsGood]);\n\n // Conditional formatting on the metric value (threshold-driven color, not\n // just trend direction). Falls back to the default primary text color.\n const valueConditionalClass = useMemo(() => {\n const style = resolveConditionalStyle(data?.value, config?.conditionalRules);\n return conditionalStyleToClassName(style);\n }, [data?.value, config?.conditionalRules]);\n\n // Handle click\n const handleClick = useCallback(() => {\n // Support both legacy onClick and new onDrilldown\n if (onDrilldown) {\n onDrilldown({\n value: data?.value,\n changePercent: data?.changePercent,\n trend,\n target: data?.target,\n });\n } else if (onClick && widget.drilldowns?.length) {\n onClick();\n }\n }, [onClick, onDrilldown, widget.drilldowns, data, trend]);\n\n // Determine if clickable\n const isClickable = Boolean(onDrilldown || (onClick && widget.drilldowns?.length));\n\n return (\n <div\n className={`\n flex min-w-0 flex-col h-full p-4\n ${isClickable ? 'cursor-pointer hover:bg-bg-sunken/50 transition-colors' : ''}\n `}\n style={{ containerType: 'inline-size' }}\n onClick={handleClick}\n role={isClickable ? 'button' : undefined}\n tabIndex={isClickable ? 0 : undefined}\n onKeyDown={(e) => {\n if (isClickable && (e.key === 'Enter' || e.key === ' ')) {\n e.preventDefault();\n handleClick();\n }\n }}\n >\n {/* Subtitle/Label */}\n {config?.subtitle && <p className=\"text-xs text-text-secondary mb-1 truncate\">{config.subtitle}</p>}\n\n {/* Main Value */}\n <div className=\"flex min-w-0 flex-wrap items-baseline gap-2 mb-2\">\n <span\n className={`min-w-0 max-w-full [overflow-wrap:anywhere] font-semibold tracking-tight ${valueConditionalClass || 'text-text-primary'}`}\n style={{ fontSize: 'clamp(1rem, 12cqi, 1.875rem)' }}\n title={formattedValue}\n >\n {formattedValue}\n </span>\n\n {/* Trend Indicator (inline) */}\n {config?.showTrend !== false && hasTrendSignal && (\n <TrendIndicator direction={trend} size=\"md\" positiveIsGood={positiveIsGood} />\n )}\n </div>\n\n {/* Comparison Badge */}\n {config?.showComparison !== false && data?.changePercent !== undefined && (\n <div className=\"mb-3\">\n <ComparisonBadge\n value={data.changePercent}\n label={config?.comparisonLabel}\n positiveIsGood={positiveIsGood}\n size=\"sm\"\n />\n </div>\n )}\n\n {/* Target Progress */}\n {targetProgress !== null && data?.target !== undefined && (\n <div className=\"mb-3\">\n <div className=\"flex justify-between text-xs text-text-secondary mb-1\">\n <span>Target: {formatValue(data.target, config, resolvedFormat)}</span>\n <span>{targetProgress.toFixed(0)}%</span>\n </div>\n <div className=\"h-1.5 bg-bg-sunken rounded-full overflow-hidden\">\n <div\n className={`h-full rounded-full transition-all ${\n targetProgress >= 100 ? 'bg-status-success-bg' : 'bg-action-primary-bg'\n }`}\n style={{\n // Clamp both ends — a negative value would otherwise emit a\n // negative width, which the browser drops entirely.\n width: `${clampProgressWidth(targetProgress)}%`,\n }}\n />\n </div>\n </div>\n )}\n\n {/* Sparkline */}\n {config?.showSparkline !== false && data?.sparklineData?.length ? (\n <div className=\"mt-auto pt-2\">\n <SparklineChart data={data.sparklineData} width={120} height={32} color={sparklineColor} showFill />\n </div>\n ) : null}\n\n {/* Drilldown Indicator */}\n {isClickable && (\n <div className=\"mt-auto pt-2 flex items-center justify-end\">\n <span className=\"text-xs text-text-secondary flex items-center gap-1\">\n View details\n <svg className=\"w-3 h-3\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M9 5l7 7-7 7\" />\n </svg>\n </span>\n </div>\n )}\n </div>\n );\n});\n\nexport default MetricCardWidget;\n"],"mappings":";;;;;;;;;AAiEA,SAAS,EAAiB,GAAmC;AAC3D,QAAO,MAAS,KAAA,KAAa,cAAc,KAAK,EAAK,GAAG,EAAK,aAAa,GAAG,KAAA;;AAmB/E,SAAS,EAAc,GAA2B,GAAuC;CACvF,IAAM,IAAa,GAAQ,QAGrB,IAFW,MAAe,KAAA,KAAa,MAAe,SAGxD,MAAe,cAAc,MAAe,gBAAgB,MAAe,YACzE,IACA,WACF,GAAM,eAAe,KACnB,aACA;AAEN,QAAO;EACL;EACA,UAAU,EAAiB,GAAM,KAAK,IAAI;EAG1C,YAAY,MAAU,cAAc,GAAQ,SAAS,KAAA,IAAY,GAAM;EACxE;;AAMH,SAAS,EAAY,GAAwB,GAAsC,GAAkC;AACnH,KAAI,OAAO,KAAU,SAAU,QAAO;CAEtC,IAAM,EAAE,WAAQ,WAAQ,qBAAkB,KAAU,EAAE,EAChD,IAAS,EAAS,OAMlB,IACJ,OAAO,KAAkB,YAAY,OAAO,SAAS,EAAc,GAC/D,KAAK,IAAI,KAAK,IAAI,KAAK,MAAM,EAAc,EAAE,EAAE,EAAE,GAAG,GACpD,KAAA,GAEF;AAEJ,SAAQ,GAAR;EACE,KAAK;AACH,OAAY,IAAI,KAAK,aAAa,SAAS;IACzC,OAAO;IACP,UAAU,EAAS;IACnB,uBAAuB,KAAe;IACtC,uBAAuB,KAAe;IACvC,CAAC,CAAC,OAAO,EAAM;AAChB;EAEF,KAAK;AACH,OAAY,IAAI,IAAQ,KAAK,QAAQ,KAAe,EAAE,CAAC;AACvD;EAEF,KAAK;AACH,OAAY,IAAI,KAAK,aAAa,SAAS;IACzC,UAAU;IACV,uBAAuB;IACvB,uBAAuB,KAAe;IACvC,CAAC,CAAC,OAAO,EAAM;AACh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E,kBAAC,OAAD;MAAK,WAAU;MAAU,MAAK;MAAO,QAAO;MAAe,SAAQ;gBACjE,kBAAC,QAAD;OAAM,eAAc;OAAQ,gBAAe;OAAQ,aAAa;OAAG,GAAE;OAAiB,CAAA;MAClF,CAAA,CACD;;IACH,CAAA;GAEJ;;EAER"}
@@ -2,6 +2,7 @@ import { FC } from 'react';
2
2
  import { WidgetType } from '../../../types';
3
3
 
4
4
  export interface WidgetEmptyStateProps {
5
+ hideEditHint?: boolean;
5
6
  /** Widget type for context-specific messaging */
6
7
  widgetType?: WidgetType;
7
8
  /** Whether a data source is configured */
@@ -1 +1 @@
1
- {"version":3,"file":"EmptyState.d.ts","sourceRoot":"","sources":["../../../../../src/bigconsole/components/widgets/states/EmptyState.tsx"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,EAAE,EAAQ,MAAM,OAAO,CAAC;AACtC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjD,MAAM,WAAW,qBAAqB;IACpC,iDAAiD;IACjD,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,0CAA0C;IAC1C,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,qBAAqB;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AAED,eAAO,MAAM,gBAAgB,EAAE,EAAE,CAAC,qBAAqB,CAgErD,CAAC;AAyCH,eAAe,gBAAgB,CAAC"}
1
+ {"version":3,"file":"EmptyState.d.ts","sourceRoot":"","sources":["../../../../../src/bigconsole/components/widgets/states/EmptyState.tsx"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,EAAE,EAAQ,MAAM,OAAO,CAAC;AACtC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjD,MAAM,WAAW,qBAAqB;IACpC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,iDAAiD;IACjD,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,0CAA0C;IAC1C,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,qBAAqB;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AAED,eAAO,MAAM,gBAAgB,EAAE,EAAE,CAAC,qBAAqB,CAiErD,CAAC;AAyCH,eAAe,gBAAgB,CAAC"}
@@ -1,8 +1,8 @@
1
1
  import { memo as e } from "react";
2
2
  import { jsx as t, jsxs as n } from "react/jsx-runtime";
3
3
  //#region src/bigconsole/components/widgets/states/EmptyState.tsx
4
- var r = e(function({ widgetType: e, hasDataSource: r = !1, message: a, templateSlot: o }) {
5
- let s = a || (!r && o ? `Connect the "${o}" data source to finish setting up this widget` : r ? i(e) : "Connect a data source to display data");
4
+ var r = e(function({ widgetType: e, hasDataSource: r = !1, message: a, templateSlot: o, hideEditHint: s = !1 }) {
5
+ let c = a || (!r && o ? `Connect the "${o}" data source to finish setting up this widget` : r ? i(e) : "Connect a data source to display data");
6
6
  return /* @__PURE__ */ n("div", {
7
7
  className: "\n flex flex-col items-center justify-center\n h-full w-full min-w-0 min-h-[120px]\n text-center\n px-3\n ",
8
8
  role: "status",
@@ -25,9 +25,9 @@ var r = e(function({ widgetType: e, hasDataSource: r = !1, message: a, templateS
25
25
  }),
26
26
  /* @__PURE__ */ t("p", {
27
27
  className: "max-w-[32ch] text-sm font-medium text-text-primary",
28
- children: s
28
+ children: c
29
29
  }),
30
- !r && /* @__PURE__ */ t("p", {
30
+ !r && !s && /* @__PURE__ */ t("p", {
31
31
  className: "mt-2 max-w-[32ch] text-xs text-text-secondary",
32
32
  children: "Click Edit to configure this widget"
33
33
  })
@@ -1 +1 @@
1
- {"version":3,"file":"EmptyState.js","names":[],"sources":["../../../../../src/bigconsole/components/widgets/states/EmptyState.tsx"],"sourcesContent":["/**\n * WidgetEmptyState Component\n *\n * Empty state displayed when widget has no data.\n */\n\nimport { type FC, memo } from 'react';\nimport type { WidgetType } from '../../../types';\n\nexport interface WidgetEmptyStateProps {\n /** Widget type for context-specific messaging */\n widgetType?: WidgetType;\n /** Whether a data source is configured */\n hasDataSource?: boolean;\n /** Custom message */\n message?: string;\n /**\n * Slot name when this widget came from a store template and its data source\n * has not been connected yet. Turns the generic empty state into an\n * explicitly unfinished-setup state, so it does not read as a broken widget.\n */\n templateSlot?: string | null;\n}\n\nexport const WidgetEmptyState: FC<WidgetEmptyStateProps> = memo(function WidgetEmptyState({\n widgetType,\n hasDataSource = false,\n message,\n templateSlot,\n}) {\n // A template widget awaiting its data source is a designed setup state, not\n // an absence of results — say so explicitly and name the slot to connect.\n const awaitingTemplateBinding = !hasDataSource && !!templateSlot;\n\n // Determine appropriate message\n const displayMessage =\n message ||\n (awaitingTemplateBinding\n ? `Connect the \"${templateSlot}\" data source to finish setting up this widget`\n : !hasDataSource\n ? 'Connect a data source to display data'\n : getEmptyMessageForType(widgetType));\n\n return (\n /*\n One shared recipe across the four widget states (empty / error / loading /\n crash): same icon chip, same copy width, same padding. Copy is capped in\n `ch` rather than a fixed 200px so it never overflows a narrow card\n (BOFF-5636).\n */\n <div\n className=\"\n flex flex-col items-center justify-center\n h-full w-full min-w-0 min-h-[120px]\n text-center\n px-3\n \"\n role=\"status\"\n >\n {/* Empty Icon */}\n <div\n className=\"\n w-12 h-12 mb-3 shrink-0\n flex items-center justify-center\n rounded-full\n bg-bg-sunken\n text-text-secondary\n \"\n >\n <svg aria-hidden=\"true\" className=\"w-6 h-6\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4\"\n />\n </svg>\n </div>\n\n {/* Message */}\n <p className=\"max-w-[32ch] text-sm font-medium text-text-primary\">{displayMessage}</p>\n\n {/* Data source hint */}\n {!hasDataSource && (\n <p className=\"mt-2 max-w-[32ch] text-xs text-text-secondary\">Click Edit to configure this widget</p>\n )}\n </div>\n );\n});\n\n/**\n * Get context-specific empty message for widget type (v1.0 snake_case)\n */\nfunction getEmptyMessageForType(type?: WidgetType): string {\n switch (type) {\n case 'metric_card':\n case 'kpi_card_comparison':\n return 'No metrics available';\n case 'chart':\n case 'funnel_chart':\n return 'No chart data available';\n case 'table':\n case 'pivot_table':\n return 'No rows to display';\n case 'gauge':\n case 'progress':\n return 'No value available';\n case 'list':\n return 'No items to display';\n case 'heatmap':\n return 'No heatmap data available';\n case 'calendar':\n case 'timeline':\n case 'kanban':\n return 'No schedule data available';\n case 'map':\n return 'No location data available';\n case 'form':\n return 'Form not configured';\n case 'text':\n case 'iframe':\n return 'No content configured';\n case 'custom':\n return 'Custom widget not configured';\n default:\n return 'No data available';\n }\n}\n\nexport default WidgetEmptyState;\n"],"mappings":";;;AAwBA,IAAa,IAA8C,EAAK,SAA0B,EACxF,eACA,mBAAgB,IAChB,YACA,mBACC;CAMD,IAAM,IACJ,MAJ8B,CAAC,KAAmB,IAM9C,gBAAgB,EAAa,kDAC5B,IAEC,EAAuB,EAAW,GADlC;AAGR,QAOE,kBAAC,OAAD;EACE,WAAU;EAMV,MAAK;YAPP;GAUE,kBAAC,OAAD;IACE,WAAU;cAQV,kBAAC,OAAD;KAAK,eAAY;KAAO,WAAU;KAAU,MAAK;KAAO,QAAO;KAAe,SAAQ;eACpF,kBAAC,QAAD;MACE,eAAc;MACd,gBAAe;MACf,aAAa;MACb,GAAE;MACF,CAAA;KACE,CAAA;IACF,CAAA;GAGN,kBAAC,KAAD;IAAG,WAAU;cAAsD;IAAmB,CAAA;GAGrF,CAAC,KACA,kBAAC,KAAD;IAAG,WAAU;cAAgD;IAAuC,CAAA;GAElG;;EAER;AAKF,SAAS,EAAuB,GAA2B;AACzD,SAAQ,GAAR;EACE,KAAK;EACL,KAAK,sBACH,QAAO;EACT,KAAK;EACL,KAAK,eACH,QAAO;EACT,KAAK;EACL,KAAK,cACH,QAAO;EACT,KAAK;EACL,KAAK,WACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK,UACH,QAAO;EACT,KAAK;EACL,KAAK;EACL,KAAK,SACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK;EACL,KAAK,SACH,QAAO;EACT,KAAK,SACH,QAAO;EACT,QACE,QAAO"}
1
+ {"version":3,"file":"EmptyState.js","names":[],"sources":["../../../../../src/bigconsole/components/widgets/states/EmptyState.tsx"],"sourcesContent":["/**\n * WidgetEmptyState Component\n *\n * Empty state displayed when widget has no data.\n */\n\nimport { type FC, memo } from 'react';\nimport type { WidgetType } from '../../../types';\n\nexport interface WidgetEmptyStateProps {\n hideEditHint?: boolean;\n /** Widget type for context-specific messaging */\n widgetType?: WidgetType;\n /** Whether a data source is configured */\n hasDataSource?: boolean;\n /** Custom message */\n message?: string;\n /**\n * Slot name when this widget came from a store template and its data source\n * has not been connected yet. Turns the generic empty state into an\n * explicitly unfinished-setup state, so it does not read as a broken widget.\n */\n templateSlot?: string | null;\n}\n\nexport const WidgetEmptyState: FC<WidgetEmptyStateProps> = memo(function WidgetEmptyState({\n widgetType,\n hasDataSource = false,\n message,\n templateSlot,\n hideEditHint = false,\n}) {\n // A template widget awaiting its data source is a designed setup state, not\n // an absence of results — say so explicitly and name the slot to connect.\n const awaitingTemplateBinding = !hasDataSource && !!templateSlot;\n\n // Determine appropriate message\n const displayMessage =\n message ||\n (awaitingTemplateBinding\n ? `Connect the \"${templateSlot}\" data source to finish setting up this widget`\n : !hasDataSource\n ? 'Connect a data source to display data'\n : getEmptyMessageForType(widgetType));\n\n return (\n /*\n One shared recipe across the four widget states (empty / error / loading /\n crash): same icon chip, same copy width, same padding. Copy is capped in\n `ch` rather than a fixed 200px so it never overflows a narrow card\n (BOFF-5636).\n */\n <div\n className=\"\n flex flex-col items-center justify-center\n h-full w-full min-w-0 min-h-[120px]\n text-center\n px-3\n \"\n role=\"status\"\n >\n {/* Empty Icon */}\n <div\n className=\"\n w-12 h-12 mb-3 shrink-0\n flex items-center justify-center\n rounded-full\n bg-bg-sunken\n text-text-secondary\n \"\n >\n <svg aria-hidden=\"true\" className=\"w-6 h-6\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4\"\n />\n </svg>\n </div>\n\n {/* Message */}\n <p className=\"max-w-[32ch] text-sm font-medium text-text-primary\">{displayMessage}</p>\n\n {/* Data source hint */}\n {!hasDataSource && !hideEditHint && (\n <p className=\"mt-2 max-w-[32ch] text-xs text-text-secondary\">Click Edit to configure this widget</p>\n )}\n </div>\n );\n});\n\n/**\n * Get context-specific empty message for widget type (v1.0 snake_case)\n */\nfunction getEmptyMessageForType(type?: WidgetType): string {\n switch (type) {\n case 'metric_card':\n case 'kpi_card_comparison':\n return 'No metrics available';\n case 'chart':\n case 'funnel_chart':\n return 'No chart data available';\n case 'table':\n case 'pivot_table':\n return 'No rows to display';\n case 'gauge':\n case 'progress':\n return 'No value available';\n case 'list':\n return 'No items to display';\n case 'heatmap':\n return 'No heatmap data available';\n case 'calendar':\n case 'timeline':\n case 'kanban':\n return 'No schedule data available';\n case 'map':\n return 'No location data available';\n case 'form':\n return 'Form not configured';\n case 'text':\n case 'iframe':\n return 'No content configured';\n case 'custom':\n return 'Custom widget not configured';\n default:\n return 'No data available';\n }\n}\n\nexport default WidgetEmptyState;\n"],"mappings":";;;AAyBA,IAAa,IAA8C,EAAK,SAA0B,EACxF,eACA,mBAAgB,IAChB,YACA,iBACA,kBAAe,MACd;CAMD,IAAM,IACJ,MAJ8B,CAAC,KAAmB,IAM9C,gBAAgB,EAAa,kDAC5B,IAEC,EAAuB,EAAW,GADlC;AAGR,QAOE,kBAAC,OAAD;EACE,WAAU;EAMV,MAAK;YAPP;GAUE,kBAAC,OAAD;IACE,WAAU;cAQV,kBAAC,OAAD;KAAK,eAAY;KAAO,WAAU;KAAU,MAAK;KAAO,QAAO;KAAe,SAAQ;eACpF,kBAAC,QAAD;MACE,eAAc;MACd,gBAAe;MACf,aAAa;MACb,GAAE;MACF,CAAA;KACE,CAAA;IACF,CAAA;GAGN,kBAAC,KAAD;IAAG,WAAU;cAAsD;IAAmB,CAAA;GAGrF,CAAC,KAAiB,CAAC,KAClB,kBAAC,KAAD;IAAG,WAAU;cAAgD;IAAuC,CAAA;GAElG;;EAER;AAKF,SAAS,EAAuB,GAA2B;AACzD,SAAQ,GAAR;EACE,KAAK;EACL,KAAK,sBACH,QAAO;EACT,KAAK;EACL,KAAK,eACH,QAAO;EACT,KAAK;EACL,KAAK,cACH,QAAO;EACT,KAAK;EACL,KAAK,WACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK,UACH,QAAO;EACT,KAAK;EACL,KAAK;EACL,KAAK,SACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK;EACL,KAAK,SACH,QAAO;EACT,KAAK,SACH,QAAO;EACT,QACE,QAAO"}