Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

12.1 KB
Raw Blame
import { type ReactElement, useState } from 'react'

import { emptyStateIllustration } from '@posthog/mcp-ui'
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'
import {
    BarChart as BarValueChart,
    buildYTickFormatter,
    ciRanges,
    DefaultTooltip,
    PieChart,
    ProportionBar,
    SlopeChart,
    TimeSeriesBarChart,
    TimeSeriesLineChart,
    type TimeInterval,
    type TooltipContext,
} from '@posthog/quill-charts'

import { trendsFilterToYFormatterConfig } from 'products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat'
import { buildTrendsBarChartModel } from 'products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms'
import {
    buildTrendsBarValueConfig,
    buildTrendsBarValueSeries,
} from 'products/product_analytics/frontend/insights/trends/TrendsBarValueChart/trendsBarValueChartTransforms'
import {
    buildTrendsLineTimeSeriesConfig,
    buildTrendsSeries,
} from 'products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms'

import { captureInsightDisplayChanged } from '../analytics/posthog'
import { ChartHeader } from './ChartHeader'
import { BigNumber, Select } from './charts'
import { colorAt, fadedColorAt, useMcpChartTheme } from './charts/theme'
import { ChartSettings } from './ChartSettings'
import {
    type ChartType,
    chartConfigFromTrendsFilter,
    defaultChartType,
    displayForChartType,
    isBarFamily,
    pieViewFromTrendsFilter,
    resolveChartView,
    supportsPercentStack,
} from './chartSettingsConfig'
import type { TrendsResultItem, TrendsVisualizerProps } from './types'
import { buildProportionBarSeries, formatDate, formatTooltipDate, getDisplayType, getSeriesLabel } from './utils'

const TITLE = 'Trends'

const CHART_TYPE_OPTIONS = [
    { value: 'line' as const, label: 'Line' },
    { value: 'area' as const, label: 'Area' },
    { value: 'bar' as const, label: 'Bar' },
    { value: 'stacked-bar' as const, label: 'Stacked bar' },
]

const SLOPE_TYPE_OPTION = { value: 'slope' as const, label: 'Slope' }

const TOOLTIP_CONFIG = { pinnable: true, placement: 'cursor' as const }

const LEGEND_CONFIG = { show: true, position: 'bottom' } as const

// DefaultTooltip shows the raw x label; format it like the axis.
const dateTooltip =
    (interval: string | undefined) =>
    (ctx: TooltipContext): ReactElement => <DefaultTooltip {...ctx} label={formatTooltipDate(ctx.label, interval)} />

function calculateTotal(results: TrendsResultItem[]): number {
    return results.reduce((sum, item) => {
        if (typeof item.aggregated_value === 'number') {
            return sum + item.aggregated_value
        }
        if (typeof item.count === 'number') {
            return sum + item.count
        }
        if (item.data && item.data.length > 0) {
            return sum + item.data.reduce((a, b) => a + b, 0)
        }
        return sum
    }, 0)
}

export function TrendsVisualizer({
    query,
    results,
    title = TITLE,
    overlay,
    showControls = true,
    chartClassName = 'h-[400px]',
    showTitle = true,
    showLegend = false,
    highlightedSeries,
}: TrendsVisualizerProps): ReactElement {
    const displayType = getDisplayType(query)
    const [chartType, setChartType] = useState<ChartType>(defaultChartType(displayType))
    const [chartConfig, setChartConfig] = useState(() => chartConfigFromTrendsFilter(query?.trendsFilter))
    const theme = useMcpChartTheme()

    if (!results || results.length === 0) {
        return (
            <div>
                {showTitle && <ChartHeader title={title} />}
                <Empty>
                    <EmptyHeader>
                        <EmptyMedia>{emptyStateIllustration('chart')}</EmptyMedia>
                        <EmptyDescription>No data available</EmptyDescription>
                    </EmptyHeader>
                </Empty>
            </div>
        )
    }

    if (displayType === 'BoldNumber') {
        const total = calculateTotal(results)
        const label = results[0] ? getSeriesLabel(results[0], 0) : 'Total'
        return (
            <div>
                {showTitle && <ChartHeader title={title} />}
                <BigNumber value={total} label={label} />
            </div>
        )
    }

    if (displayType === 'ActionsProportionBar') {
        return (
            <div>
                {showTitle && <ChartHeader title={title} />}
                <div className="flex flex-col w-full justify-center p-4">
                    <ProportionBar
                        series={buildProportionBarSeries(results, colorAt)}
                        theme={theme}
                        valueFormatter={buildYTickFormatter(trendsFilterToYFormatterConfig(query?.trendsFilter, false))}
                    />
                </div>
            </div>
        )
    }

    // ActionsBarValue is aggregated totals per series (no days[]) — a horizontal bar, not a time series.
    if (displayType === 'ActionsBarValue') {
        const items = results.map((item, i) => ({
            label: getSeriesLabel(item, i),
            value: item.aggregated_value,
        }))
        const barSeries = buildTrendsBarValueSeries(items, { getColor: colorAt })
        const barConfig = buildTrendsBarValueConfig()
        return (
            <div>
                {showTitle && <ChartHeader title={title} />}
                <div className={`flex flex-col w-full ${chartClassName}`}>
                    <BarValueChart
                        series={barSeries}
                        labels={items.map((item) => item.label)}
                        theme={theme}
                        config={barConfig}
                    />
                </div>
            </div>
        )
    }

    if (displayType === 'ActionsPie' || displayType === 'ActionsDonut') {
        const slices = results.map((item, i) => ({
            key: String(i),
            label: getSeriesLabel(item, i),
            data: [item.aggregated_value ?? 0],
            color: colorAt(i),
        }))
        const pieView = pieViewFromTrendsFilter(query?.trendsFilter, displayType === 'ActionsDonut')
        return (
            <div>
                {showTitle && <ChartHeader title={title} />}
                <div className={`flex flex-col w-full ${chartClassName}`}>
                    <PieChart
                        series={slices}
                        theme={theme}
                        config={pieView.config}
                        valueFormatter={buildYTickFormatter(pieView.valueFormat)}
                    />
                </div>
            </div>
        )
    }

    const labels = results[0]?.days ?? results[0]?.labels ?? []
    // Trends returns each day as wall-clock time with no offset, so reading it as UTC keeps it as written.
    const xAxisDates = {
        interval: (query?.interval ?? 'day') as TimeInterval,
        timezone: 'UTC',
        allDays: labels.map(String),
    }
    const trendResults = results.map((item, i) => ({
        id: i,
        label: getSeriesLabel(item, i),
        data: item.data ?? [],
        days: item.days,
        incompleteEnd: !!item.incomplete_end,
    }))
    const { slopeAvailable, effectiveType } = resolveChartView(chartType, labels.length)
    const handleChartTypeChange = (next: ChartType): void => {
        const from = effectiveType === defaultChartType(displayType) ? displayType : displayForChartType(effectiveType)
        captureInsightDisplayChanged({ from, to: displayForChartType(next) })
        setChartType(next)
    }
    const chartTypeOptions = slopeAvailable ? [...CHART_TYPE_OPTIONS, SLOPE_TYPE_OPTION] : CHART_TYPE_OPTIONS

    const seriesColor = (index: number): string =>
        highlightedSeries?.length && !highlightedSeries.includes(index) ? fadedColorAt(index) : colorAt(index)
    // Area auto-stacks, so derived overlays would draw against the stacked totals — disable them.
    const derivedSeriesDisabled = effectiveType === 'area'
    const isPercentStackView = chartConfig.percentStack && supportsPercentStack(effectiveType)
    const effectiveTrendsFilter = { ...query?.trendsFilter, aggregationAxisFormat: chartConfig.yUnit }
    const valueLabels = chartConfig.showValueLabels ? true : undefined

    const renderChart = (): ReactElement => {
        if (effectiveType === 'slope') {
            const slopeSeries = trendResults
                .filter((item) => item.data.length >= 2)
                .map((item) => ({
                    key: String(item.id),
                    label: item.label,
                    color: colorAt(item.id),
                    data: item.data,
                    meta: item.incompleteEnd ? { incompleteEnd: true } : undefined,
                }))
            const slopeLabels = labels.map((label) => formatDate(String(label)))
            return (
                <SlopeChart
                    series={slopeSeries}
                    labels={slopeLabels}
                    theme={theme}
                    config={{ showSeriesLabels: false, legend: { show: true, position: 'bottom' } }}
                />
            )
        }
        if (isBarFamily(effectiveType)) {
            const { series, config } = buildTrendsBarChartModel(trendResults, {
                getColor: (_, index) => seriesColor(index),
                labels,
                trendsFilter: effectiveTrendsFilter,
                isPercentStackView,
                isGrouped: effectiveType === 'bar',
                valueLabels,
                ...xAxisDates,
                tooltip: TOOLTIP_CONFIG,
            })
            return (
                <TimeSeriesBarChart
                    series={series}
                    labels={labels}
                    theme={theme}
                    config={showLegend ? { ...config, legend: LEGEND_CONFIG } : config}
                    tooltip={dateTooltip(xAxisDates.interval)}
                >
                    {overlay}
                </TimeSeriesBarChart>
            )
        }
        const series = buildTrendsSeries(trendResults, {
            isArea: effectiveType === 'area',
            getColor: (_, index) => seriesColor(index),
        })
        const config = buildTrendsLineTimeSeriesConfig({
            results: trendResults,
            trendsFilter: effectiveTrendsFilter,
            isPercentStackView,
            showTrendLines: chartConfig.showTrendLine && !derivedSeriesDisabled,
            showConfidenceIntervals: chartConfig.showConfidenceIntervals && !derivedSeriesDisabled,
            confidenceLevel: chartConfig.confidenceLevel,
            ciRanges,
            valueLabels,
            showCrosshair: true,
            ...xAxisDates,
            tooltip: TOOLTIP_CONFIG,
        })
        return (
            <TimeSeriesLineChart
                series={series}
                labels={labels}
                theme={theme}
                config={showLegend ? { ...config, legend: LEGEND_CONFIG } : config}
                tooltip={dateTooltip(xAxisDates.interval)}
            >
                {overlay}
            </TimeSeriesLineChart>
        )
    }

    return (
        <div>
            {(showTitle || showControls) && (
                <ChartHeader title={showTitle ? title : ''}>
                    {showControls && (
                        <>
                            {/* eslint-disable-next-line react/forbid-elements */}
                            <Select value={effectiveType} onChange={handleChartTypeChange} options={chartTypeOptions} />
                            {effectiveType !== 'slope' && (
                                <ChartSettings
                                    family={isBarFamily(effectiveType) ? 'bar' : 'line'}
                                    config={chartConfig}
                                    onChange={setChartConfig}
                                    derivedSeriesDisabled={derivedSeriesDisabled}
                                    percentStackDisabled={!supportsPercentStack(effectiveType)}
                                />
                            )}
                        </>
                    )}
                </ChartHeader>
            )}
            <div className={`flex flex-col w-full ${chartClassName}`}>{renderChart()}</div>
        </div>
    )
}