ComposedChartHandler.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import dayjs from 'dayjs'
  2. import { List, Loader2 } from 'lucide-react'
  3. import { useRouter } from 'next/router'
  4. import React, { PropsWithChildren, useEffect, useMemo, useRef, useState } from 'react'
  5. import { Card, cn, WarningIcon } from 'ui'
  6. import type { ChartHighlightAction } from './ChartHighlightActions'
  7. import type { ChartData } from './Charts.types'
  8. import { ComposedChart } from './ComposedChart'
  9. import { MultiAttribute } from './ComposedChart.utils'
  10. import { useChartHighlight } from './useChartHighlight'
  11. import Panel from '@/components/ui/Panel'
  12. import { AnalyticsInterval, DataPoint } from '@/data/analytics/constants'
  13. import { useInfraMonitoringQueries } from '@/data/analytics/infra-monitoring-queries'
  14. import { InfraMonitoringAttribute } from '@/data/analytics/infra-monitoring-query'
  15. import { useProjectDailyStatsQueries } from '@/data/analytics/project-daily-stats-queries'
  16. import { ProjectDailyStatsAttribute } from '@/data/analytics/project-daily-stats-query'
  17. import type { UpdateDateRange } from '@/pages/project/[ref]/observability/database'
  18. import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
  19. export interface ComposedChartHandlerProps {
  20. id?: string
  21. label: string
  22. attributes: MultiAttribute[]
  23. startDate: string
  24. endDate: string
  25. interval?: string
  26. customDateFormat?: string
  27. defaultChartStyle?: 'bar' | 'line' | 'stackedAreaLine'
  28. hideChartType?: boolean
  29. data?: ChartData | DataPoint[]
  30. isLoading?: boolean
  31. format?: string
  32. highlightedValue?: string | number
  33. className?: string
  34. showTooltip?: boolean
  35. showLegend?: boolean
  36. showTotal?: boolean
  37. showMaxValue?: boolean
  38. normalizeVisibleStackToPercent?: boolean
  39. updateDateRange?: UpdateDateRange
  40. valuePrecision?: number
  41. isVisible?: boolean
  42. docsUrl?: string
  43. hide?: boolean
  44. syncId?: string
  45. YAxisProps?: {
  46. width?: number
  47. tickFormatter?: (value: number) => string
  48. domain?: [number | string, number | string]
  49. allowDataOverflow?: boolean
  50. }
  51. }
  52. /**
  53. * Wrapper component that handles intersection observer logic for lazy loading
  54. */
  55. const LazyChartWrapper = ({ children }: PropsWithChildren) => {
  56. const [isVisible, setIsVisible] = useState(false)
  57. const ref = useRef<HTMLDivElement>(null)
  58. useEffect(() => {
  59. const observer = new IntersectionObserver(
  60. ([entry]) => {
  61. if (entry.isIntersecting) {
  62. setIsVisible(true)
  63. observer.disconnect()
  64. }
  65. },
  66. {
  67. rootMargin: '150px 0px', // Start loading before the component enters viewport
  68. threshold: 0,
  69. }
  70. )
  71. const currentRef = ref.current
  72. if (currentRef) {
  73. observer.observe(currentRef)
  74. }
  75. return () => {
  76. if (currentRef) {
  77. observer.unobserve(currentRef)
  78. }
  79. }
  80. }, [])
  81. return (
  82. <div ref={ref}>
  83. {React.cloneElement(children as React.ReactElement<{ isVisible: boolean }>, { isVisible })}
  84. </div>
  85. )
  86. }
  87. /**
  88. * Controls chart display state. Optionally fetches static chart data if data is not provided.
  89. *
  90. * If the `data` prop is provided, it will disable automatic chart data fetching and pass the data directly to the chart render.
  91. * - loading state can also be provided through the `isLoading` prop, to display loading placeholders. Ignored if `data` key not provided.
  92. * - if `isLoading=true` and `data` is `undefined`, loading error message will be shown.
  93. *
  94. * Provided data must be in the expected chart format.
  95. */
  96. const ComposedChartHandler = ({
  97. label,
  98. attributes,
  99. startDate,
  100. endDate,
  101. interval,
  102. customDateFormat,
  103. children = null,
  104. defaultChartStyle = 'bar',
  105. hideChartType = false,
  106. data,
  107. isLoading,
  108. format,
  109. highlightedValue,
  110. className,
  111. showTooltip,
  112. showLegend,
  113. showMaxValue,
  114. showTotal,
  115. updateDateRange,
  116. valuePrecision,
  117. isVisible = true,
  118. id,
  119. syncId,
  120. ...otherProps
  121. }: PropsWithChildren<ComposedChartHandlerProps>) => {
  122. const router = useRouter()
  123. const { ref } = router.query
  124. const state = useDatabaseSelectorStateSnapshot()
  125. const [chartStyle, setChartStyle] = useState<string>(defaultChartStyle)
  126. const chartHighlight = useChartHighlight()
  127. const databaseIdentifier = state.selectedDatabaseId
  128. const attributeQueries = useAttributeQueries(
  129. attributes,
  130. ref,
  131. startDate,
  132. endDate,
  133. interval as AnalyticsInterval,
  134. databaseIdentifier,
  135. Array.isArray(data) ? undefined : data,
  136. isVisible
  137. )
  138. const combinedData = useMemo(() => {
  139. if (data) return Array.isArray(data) ? data : data.data
  140. const isLoading = attributeQueries.some((query: any) => query.isLoading)
  141. if (isLoading) return undefined
  142. const hasError = attributeQueries.some((query: any) => !query.data)
  143. if (hasError) return undefined
  144. const timestamps = new Set<string>()
  145. attributeQueries.forEach((query: any) => {
  146. query.data?.data?.forEach((point: any) => {
  147. if (point?.period_start) {
  148. timestamps.add(point.period_start)
  149. }
  150. })
  151. })
  152. const referenceLineQueries = attributeQueries.filter(
  153. (_, index) => attributes[index].provider === 'reference-line'
  154. )
  155. const combined = Array.from(timestamps)
  156. .sort()
  157. .map((timestamp) => {
  158. const point: any = { timestamp }
  159. attributes.forEach((attr, index) => {
  160. if (!attr) return
  161. if (attr.customValue !== undefined) {
  162. point[attr.attribute] = attr.customValue
  163. return
  164. }
  165. if (attr.provider === 'reference-line') return
  166. const queryData = attributeQueries[index]?.data?.data
  167. const matchingPoint = queryData?.find((p: any) => p.period_start === timestamp)
  168. let value = matchingPoint?.[attr.attribute] ?? 0
  169. if (attr.manipulateValue && typeof attr.manipulateValue === 'function') {
  170. const numericValue = typeof value === 'number' ? value : Number(value) || 0
  171. value = attr.manipulateValue(numericValue)
  172. }
  173. point[attr.attribute] = value
  174. })
  175. referenceLineQueries.forEach((query: any) => {
  176. const attr = query.data.attribute
  177. const value = query.data.total
  178. point[attr] = value
  179. })
  180. const formattedDataPoint: DataPoint =
  181. !('period_start' in point) && 'timestamp' in point
  182. ? { ...point, period_start: dayjs.utc(point.timestamp).unix() * 1000 }
  183. : point
  184. return formattedDataPoint
  185. })
  186. return combined as DataPoint[]
  187. }, [data, attributeQueries, attributes])
  188. const loading = isLoading || attributeQueries.some((query: any) => query.isLoading)
  189. const _highlightedValue = useMemo(() => {
  190. if (highlightedValue !== undefined) return highlightedValue
  191. const firstAttr = attributes[0]
  192. const firstQuery = attributeQueries[0]
  193. const firstData = firstQuery?.data
  194. if (!firstData) return undefined
  195. const shouldHighlightMaxValue =
  196. firstAttr.provider === 'daily-stats' &&
  197. !firstAttr.attribute.includes('ingress') &&
  198. !firstAttr.attribute.includes('egress') &&
  199. 'maximum' in firstData
  200. const shouldHighlightTotalGroupedValue = 'totalGrouped' in firstData
  201. return shouldHighlightMaxValue
  202. ? firstData.maximum
  203. : firstAttr.provider === 'daily-stats'
  204. ? firstData.total
  205. : shouldHighlightTotalGroupedValue
  206. ? firstData.totalGrouped?.[firstAttr.attribute as keyof typeof firstData.totalGrouped]
  207. : (firstData.data[firstData.data.length - 1] as any)?.[firstAttr.attribute]
  208. }, [highlightedValue, attributes, attributeQueries])
  209. const highlightActions: ChartHighlightAction[] = useMemo(() => {
  210. return [
  211. {
  212. id: 'open-logs',
  213. label: 'Open in Postgres Logs',
  214. icon: <List size={12} />,
  215. onSelect: ({ start, end }) => {
  216. const projectRef = ref as string
  217. if (!projectRef) return
  218. const url = `/project/${projectRef}/logs/postgres-logs?its=${start}&ite=${end}`
  219. router.push(url)
  220. },
  221. },
  222. ]
  223. }, [ref])
  224. if (loading) {
  225. return (
  226. <Card
  227. className={cn(
  228. 'flex min-h-[280px] w-full flex-col items-center justify-center gap-y-2',
  229. className
  230. )}
  231. >
  232. <Loader2 size={18} className="animate-spin text-border-strong" />
  233. <p className="text-xs text-foreground-lighter">Loading data for {label}</p>
  234. </Card>
  235. )
  236. }
  237. if (!combinedData) {
  238. return (
  239. <div className="flex h-52 w-full flex-col items-center justify-center gap-y-2">
  240. <WarningIcon />
  241. <p className="text-xs text-foreground-lighter">Unable to load data for {label}</p>
  242. </div>
  243. )
  244. }
  245. return (
  246. <Panel
  247. noMargin
  248. noHideOverflow
  249. className={cn('relative w-full scroll-mt-16', className)}
  250. wrapWithLoading={false}
  251. id={id ?? label.toLowerCase().replaceAll(' ', '-')}
  252. >
  253. <Panel.Content className="flex flex-col gap-4">
  254. <div className="absolute right-6 z-50 flex justify-between scroll-mt-16">{children}</div>
  255. <ComposedChart
  256. attributes={attributes}
  257. data={combinedData as DataPoint[]}
  258. format={format}
  259. // [Joshen] This is where it's messing up
  260. xAxisKey="period_start"
  261. yAxisKey={attributes[0].attribute}
  262. highlightedValue={_highlightedValue}
  263. title={label}
  264. customDateFormat={customDateFormat}
  265. chartHighlight={chartHighlight}
  266. chartStyle={chartStyle}
  267. showTooltip={showTooltip}
  268. showLegend={showLegend}
  269. showTotal={showTotal}
  270. showMaxValue={showMaxValue}
  271. onChartStyleChange={setChartStyle}
  272. updateDateRange={updateDateRange}
  273. valuePrecision={valuePrecision}
  274. hideChartType={hideChartType}
  275. syncId={syncId}
  276. highlightActions={highlightActions}
  277. {...otherProps}
  278. />
  279. </Panel.Content>
  280. </Panel>
  281. )
  282. }
  283. const useAttributeQueries = (
  284. attributes: MultiAttribute[],
  285. ref: string | string[] | undefined,
  286. startDate: string,
  287. endDate: string,
  288. interval: AnalyticsInterval,
  289. databaseIdentifier: string | undefined,
  290. data: ChartData | undefined,
  291. isVisible: boolean
  292. ) => {
  293. const infraAttributes = attributes
  294. .filter((attr) => attr?.provider === 'infra-monitoring')
  295. .map((attr) => attr.attribute as InfraMonitoringAttribute)
  296. const dailyStatsAttributes = attributes
  297. .filter((attr) => attr?.provider === 'daily-stats')
  298. .map((attr) => attr.attribute as ProjectDailyStatsAttribute)
  299. const referenceLines = attributes.filter((attr) => attr?.provider === 'reference-line')
  300. const infraQueries = useInfraMonitoringQueries(
  301. infraAttributes,
  302. ref,
  303. startDate,
  304. endDate,
  305. interval,
  306. databaseIdentifier,
  307. data,
  308. isVisible
  309. )
  310. const dailyStatsQueries = useProjectDailyStatsQueries(
  311. dailyStatsAttributes,
  312. ref,
  313. startDate,
  314. endDate,
  315. data,
  316. isVisible
  317. )
  318. const referenceLineQueries = referenceLines.map((line) => {
  319. let value = line.value ?? line.customValue ?? 0
  320. return {
  321. data: {
  322. data: [],
  323. attribute: line.attribute,
  324. total: value,
  325. maximum: value,
  326. totalGrouped: { [line.attribute]: value },
  327. },
  328. isLoading: false,
  329. isError: false,
  330. }
  331. })
  332. return [...infraQueries, ...dailyStatsQueries, ...referenceLineQueries]
  333. }
  334. export function LazyComposedChartHandler(props: ComposedChartHandlerProps) {
  335. if (props.hide) return null
  336. return (
  337. <LazyChartWrapper>
  338. <ComposedChartHandler {...props} />
  339. </LazyChartWrapper>
  340. )
  341. }