import { useState } from 'react'
import { cn, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from 'ui'
import { CHART_COLORS, DateTimeFormats } from './Charts.constants'
import type { Datum } from './Charts.types'
import { formatPercentage, numberFormatter } from './Charts.utils'
import { getThresholdZoneValues } from './ComposedChartThresholdZones.utils'
import { useFormatDateTime, useTimezone } from '@/lib/datetime'
import { formatBytes, formatBytesMinMB } from '@/lib/helpers'
export interface ReportAttributes {
id?: string
titleTooltip?: string
label: string
attributes?: (MultiAttribute | false)[]
thresholdZones?: ThresholdZone[]
thresholdZoneAttribute?: string
defaultChartStyle?: 'bar' | 'line' | 'stackedAreaLine'
hide?: boolean
entitlement?: string
requiredPlan?: string
hideChartType?: boolean
format?: string
className?: string
showTooltip?: boolean
showLegend?: boolean
showTotal?: boolean
showMaxValue?: boolean
valuePrecision?: number
docsUrl?: string
syncId?: string
showGrid?: boolean
YAxisProps?: {
width?: number
tickFormatter?: (value: any) => string
domain?: [number | string, number | string]
allowDataOverflow?: boolean
}
normalizeVisibleStackToPercent?: boolean
hideHighlightedValue?: boolean
}
export type ThresholdZone = {
label: string
color: string
textColor?: string
badgeLabel?: string
tooltipLabel?: string
isAlwaysVisible?: boolean
tooltip: string
getRanges: (data: Datum[]) => ([number, number] | null)[]
}
export type Provider = 'infra-monitoring' | 'daily-stats' | 'mock' | 'reference-line' | 'logs'
export type ThemedColor = {
light?: string
dark?: string
}
export const resolveChartColor = (
color: string | ThemedColor | undefined,
isDarkMode: boolean | undefined
) => {
if (typeof color === 'string') return color
return isDarkMode ? color?.dark : color?.light
}
export type MultiAttribute = {
attribute: string
provider?: Provider
label?: string
color?: string | { light: string; dark: string }
fill?: string | ThemedColor
statusCode?: string
grantType?: string
providerType?: string
stackId?: string
format?: string
description?: string
docsLink?: string
isMaxValue?: boolean
type?: 'line' | 'area-bar'
omitFromTotal?: boolean
tooltip?: string
customValue?: number
[key: string]: any
/**
* Manipulate the value of the attribute before it is displayed on the chart.
* @param value - The value of the attribute.
* @returns The manipulated value.
*/
manipulateValue?: (value: number) => number
/**
* Create a virtual attribute by combining values from other attributes.
* Expression should use attribute names and basic math operators (+, -, *, /).
* Example: 'disk_fs_used - pg_database_size - disk_fs_used_wal'
*/
combine?: string
id?: string
value?: number
isReferenceLine?: boolean
strokeDasharray?: string
className?: string
hide?: boolean
enabled?: boolean
}
interface CustomIconProps {
color: string
}
const CustomIcon = ({ color }: CustomIconProps) => (
)
const MaxConnectionsIcon = ({ color }: { color?: string }) => (
)
interface TooltipProps {
active?: boolean
payload?: any[]
label?: string | number
attributes?: MultiAttribute[]
data?: Datum[]
thresholdZones?: ThresholdZone[]
xAxisKey?: string
isPercentage?: boolean
format?: string | ((value: unknown) => string)
valuePrecision?: number
showMaxValue?: boolean
showTotal?: boolean
isActiveHoveredChart?: boolean
}
const isMaxAttribute = (attributes?: MultiAttribute[]) => attributes?.find((a) => a.isMaxValue)
/**
* Resolve the recharts `stackId` for a series.
*
* Series that share a `stackId` are stacked additively, so overlaid series
* (e.g. min/max/avg of the same metric) must each get a distinct id. Bar
* charts pass `'1'` as the fallback to stack together; area charts pass the
* attribute name so each series overlays independently. An explicit per-
* attribute `stackId` always wins.
*/
export const getStackId = (
attributes: (MultiAttribute | false | null | undefined)[] | null | undefined,
name: string | null | undefined,
fallback: string
): string => {
const configured = Array.isArray(attributes)
? attributes.find((a): a is MultiAttribute => !!a && a.attribute === name)?.stackId
: undefined
return configured ?? fallback
}
/**
* Calculate the total aggregate of the chart values
* by summing the values of the attributes
* that are not in the `ignoreAttributes` array
*/
export const calculateTotalChartAggregate = (
payload: { dataKey: string; value: number }[],
ignoreAttributes?: string[]
) =>
payload
?.filter((p) => !ignoreAttributes?.includes(p.dataKey))
.reduce((acc, curr) => acc + curr.value, 0)
export const CustomTooltip = ({
active,
payload,
label: _label,
attributes,
data,
thresholdZones,
xAxisKey = 'period_start',
isPercentage,
format,
valuePrecision,
showTotal,
isActiveHoveredChart,
}: TooltipProps) => {
const formatDateTime = useFormatDateTime()
const { timezone } = useTimezone()
if (active && payload && payload.length) {
/**
* Depending on the data source, the timestamp key could be 'timestamp' or 'period_start'
*/
const firstItem = payload[0].payload
const timestampKey = firstItem?.hasOwnProperty('timestamp') ? 'timestamp' : 'period_start'
const timestamp = payload[0].payload[timestampKey]
const rawDataPoint = data?.find(
(point) => point[xAxisKey] === timestamp || point[timestampKey] === timestamp
)
const thresholdValues = getThresholdZoneValues(rawDataPoint, thresholdZones)
const maxValueAttribute = isMaxAttribute(attributes)
const maxValue =
maxValueAttribute && rawDataPoint
? Number(rawDataPoint[maxValueAttribute.attribute])
: undefined
const hasFiniteMaxValue = typeof maxValue === 'number' && Number.isFinite(maxValue)
const isRamChart =
!payload?.some((p: any) => p.dataKey.toLowerCase() === 'ram_usage') &&
payload?.some((p: any) => p.dataKey.toLowerCase().includes('ram_'))
const isSwapChart = payload?.some((p: any) => p.dataKey.toLowerCase().includes('swap_'))
const isMemoryChart = isRamChart || isSwapChart
const isDBSizeChart =
payload?.some((p: any) => p.dataKey.toLowerCase().includes('disk_fs_')) ||
payload?.some((p: any) => p.dataKey.toLowerCase().includes('pg_database_size'))
const isNetworkChart = payload?.some((p: any) => p.dataKey.toLowerCase().includes('network_'))
const isBytesFormat = format === 'bytes' || format === 'bytes-per-second'
const shouldFormatBytes = isBytesFormat || isMemoryChart || isDBSizeChart || isNetworkChart
const byteUnitSuffix = format === 'bytes-per-second' ? '/s' : ''
const attributesToIgnore =
attributes?.filter((a) => a.omitFromTotal)?.map((a) => a.attribute) ?? []
const referenceLines =
attributes
?.filter((attribute: MultiAttribute) => attribute?.provider === 'reference-line')
?.map((a: MultiAttribute) => a.attribute) ?? []
const attributesToIgnoreFromTotal = [
...attributesToIgnore,
...referenceLines,
...(maxValueAttribute?.attribute ? [maxValueAttribute.attribute] : []),
]
const localTimeZone = timezone
const rawPayload = payload.map((entry: any) => ({
...entry,
value:
rawDataPoint && typeof rawDataPoint[entry.dataKey] === 'number'
? Number(rawDataPoint[entry.dataKey])
: entry.value,
}))
const total = showTotal && calculateTotalChartAggregate(rawPayload, attributesToIgnoreFromTotal)
const getIcon = (color: string, isMax: boolean) =>
isMax ?
{localTimeZone}
{formatDateTime(timestamp, DateTimeFormats.FULL_SECONDS)}