: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import './MetricRowGroup.scss'
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import React, { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { IconTrending } from '@posthog/icons'
import { IconTrendingDown } from 'lib/lemon-ui/icons'
import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'
import { MetricBreakdownError } from 'scenes/experiments/MetricBreakdowns/MetricBreakdownError'
import { MetricBreakdowns } from 'scenes/experiments/MetricBreakdowns/MetricBreakdowns'
import { formatBreakdownLabel } from 'scenes/insights/utils'
import {
Breakdown,
ExperimentMetric,
ExperimentStatsBaseValidated,
NewExperimentQueryResponse,
} from '~/queries/schema/schema-general'
import { NodeKind } from '~/queries/schema/schema-general'
import { experimentLogic } from '~/scenes/experiments/experimentLogic'
import { experimentMetricsLogic } from '~/scenes/experiments/experimentMetricsLogic'
import { useColumnWidthSync } from '~/scenes/experiments/MetricsView/hooks/useColumnWidthSync'
import { ChartEmptyState } from '~/scenes/experiments/MetricsView/shared/ChartEmptyState'
import { SkeletonResultCells } from '~/scenes/experiments/MetricsView/shared/ChartLoadingSkeleton'
import { ChartLoadingState } from '~/scenes/experiments/MetricsView/shared/ChartLoadingState'
import { useChartColors } from '~/scenes/experiments/MetricsView/shared/colors'
import { MetricHeader } from '~/scenes/experiments/MetricsView/shared/MetricHeader'
import { MetricRetryState } from '~/scenes/experiments/MetricsView/shared/MetricRetryState'
import {
FIXED_HEIGHT_STYLE,
getMinHeightStyle,
getScaledHeightStyle,
} from '~/scenes/experiments/MetricsView/shared/rowHeights'
import {
type ExperimentVariantResult,
formatChanceToWinForGoal,
formatDeltaPercent,
formatMetricValue,
formatPValue,
getDelta,
getMetricSubtitleValues,
getNiceTickValues,
isBayesianResult,
isDeltaPositive,
isSignificant,
isWinning,
} from '~/scenes/experiments/MetricsView/shared/utils'
import { Experiment, BreakdownAttributionType } from '~/types'
import { isLaunched } from 'products/experiments/frontend/experimentStatus'
import { DetailsModal } from 'products/experiments/frontend/modals/DetailsModal/DetailsModal'
import { TimeseriesModal } from 'products/experiments/frontend/modals/TimeseriesModal/TimeseriesModal'
import { ChartCell } from './ChartCell'
import {
CELL_HEIGHT,
CHART_CELL_VIEW_BOX_HEIGHT,
EMPTY_STATE_ROW_MIN_HEIGHT,
GRID_LINES_OPACITY,
SIGNIFICANT_CELL_BG_ALPHA,
SIGNIFICANT_ROW_BG_ALPHA,
SVG_EDGE_MARGIN,
VIEW_BOX_WIDTH,
} from './constants'
import { DetailsButton } from './DetailsButton'
import { GridLines } from './GridLines'
import { renderTooltipContent } from './MetricRowGroupTooltip'
import { useAxisScale } from './useAxisScale'
interface CollapsibleBreakdownSectionProps {
breakdownResults: any[]
metric: ExperimentMetric
experiment: Experiment
axisRange: number
isAlternatingRow: boolean
isLastMetric: boolean
isLoading?: boolean
exposuresLoading?: boolean
isRecalculating?: boolean
colors: ReturnType<typeof useChartColors>
scale: ReturnType<typeof useAxisScale>
onRemoveBreakdown: (index: number) => void
onBreakdownAttributionChange: (attributionType: BreakdownAttributionType, attributionValue?: number) => void
onBreakdownLimitChange: (breakdownLimit: number) => void
onRetry: () => void
query?: Record<string, any>
handleTooltipMouseEnter: (e: React.MouseEvent, variantResult: ExperimentVariantResult) => void
handleTooltipMouseLeave: (e: React.MouseEvent) => void
handleTooltipMouseMove: (e: React.MouseEvent, variantResult: ExperimentVariantResult) => void
}
function CollapsibleBreakdownSection({
breakdownResults,
metric,
experiment,
axisRange,
isAlternatingRow,
isLoading,
exposuresLoading,
isRecalculating,
colors,
scale,
onRemoveBreakdown,
onBreakdownAttributionChange,
onBreakdownLimitChange,
onRetry,
query,
handleTooltipMouseEnter,
handleTooltipMouseLeave,
handleTooltipMouseMove,
}: CollapsibleBreakdownSectionProps): JSX.Element {
const [isExpanded, setIsExpanded] = useState(false)
const mainTableRef = useRef<HTMLTableRowElement>(null)
const nestedTableRef = useRef<HTMLTableElement>(null)
/**
* Collapse the section when a recalculation starts. The results are stale and the panel is
* disabled, so close it rather than have it snap back open when fresh results land
*/
useEffect(() => {
if (isRecalculating) {
setIsExpanded(false)
}
}, [isRecalculating])
const totalRows = 1 + (breakdownResults[0]?.variants?.length || 0)
const totalRowsHeightStyle = getScaledHeightStyle(totalRows)
// Sync nested breakdown table column widths with parent table (only when expanded)
useColumnWidthSync(
{
parentRowRef: mainTableRef,
nestedTableRef,
},
[breakdownResults, axisRange, isExpanded]
)
const ratioMetricLabel = (variant: ExperimentStatsBaseValidated, metric: ExperimentMetric): JSX.Element => {
return (
<div className="text-xs text-muted">
{(() => {
const { numerator, denominator } = getMetricSubtitleValues(variant, metric)
return (
<>
{humanFriendlyLargeNumber(numerator)} / {humanFriendlyLargeNumber(denominator)}
</>
)
})()}
</div>
)
}
return (
<tr ref={mainTableRef} data-breakdown-row className="hover:bg-bg-hover group">
<td colSpan={7} className={`p-0 border-t border-b ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}>
<LemonCollapse
multiple={false}
embedded
size="small"
activeKey={isExpanded ? 'breakdowns' : undefined}
className={`breakdown-collapse breakdown-collapse--${isAlternatingRow ? 'alt-row' : 'normal-row'}`}
panels={[
{
key: 'breakdowns',
header: (
<div onClick={(e) => e.stopPropagation()}>
<MetricBreakdowns
metric={metric}
onRemoveBreakdown={onRemoveBreakdown}
onAttributionChange={onBreakdownAttributionChange}
onBreakdownLimitChange={onBreakdownLimitChange}
/>
</div>
),
// Render no content (non-expandable disabled header) when recalculating (stale
// results) or when there are no breakdown results yet (freshly added, pending) —
// expanding onto an empty table looks broken.
content:
isRecalculating || breakdownResults.length === 0 ? null : (
<div className="p-0 -m-4">
<table ref={nestedTableRef} className="w-full">
<tbody>
{breakdownResults.map((breakdownResult, breakdownIndex) => {
const baselineResult = breakdownResult.baseline
const variantResults = breakdownResult.variants || []
// The wrapping cell already draws the bottom border, so the last group must not add its own
const isLastBreakdown =
breakdownIndex === breakdownResults.length - 1
if (variantResults.length === 0) {
return (
<tr
key={breakdownResult.breakdown_value}
className="hover:bg-bg-hover"
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<td
className={`w-1/5 border-r p-3 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
>
{formatBreakdownLabel(
breakdownResult.breakdown_value,
metric.breakdownFilter,
[],
undefined,
0,
undefined
)}
</td>
<td
colSpan={6}
className={`p-3 text-center ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
{isLoading || exposuresLoading ? (
<ChartLoadingState height={CELL_HEIGHT} />
) : (
<ChartEmptyState
height={CELL_HEIGHT}
experimentStarted={isLaunched(experiment)}
query={query}
onRetry={onRetry}
retryDisabledReason={
isRecalculating
? 'Recalculation in progress'
: undefined
}
/>
)}
</td>
</tr>
)
}
return (
<React.Fragment key={breakdownResult.breakdown_value}>
{/* Baseline row */}
<tr
className="hover:bg-bg-hover"
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<td
className={`w-1/5 border-r p-3 align-top ${isLastBreakdown ? '' : 'border-b'} ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} text-xs`}
rowSpan={totalRows}
// eslint-disable-next-line react/forbid-dom-props
style={totalRowsHeightStyle}
>
{formatBreakdownLabel(
breakdownResult.breakdown_value,
metric.breakdownFilter,
[],
undefined,
0,
undefined
)}
</td>
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<VariantTag variantKey={baselineResult.key} />
</td>
<td
className={`w-24 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<div className="metric-cell">
<div>
{formatMetricValue(baselineResult, metric)}
</div>
{ratioMetricLabel(baselineResult, metric)}
</div>
</td>
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<div />
</td>
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 text-center ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<div />
</td>
{/* Empty Details column for alignment (per-row; variant rows render their own) */}
<td
className={`w-20 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
/>
<td
className={`p-0 align-top text-center relative overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
{axisRange && axisRange > 0 ? (
<div className="relative h-full">
<svg
viewBox={`0 0 ${VIEW_BOX_WIDTH} ${CHART_CELL_VIEW_BOX_HEIGHT}`}
preserveAspectRatio="none"
className="h-full w-full"
>
<GridLines
tickValues={getNiceTickValues(
axisRange
)}
scale={scale}
height={CHART_CELL_VIEW_BOX_HEIGHT}
viewBoxWidth={VIEW_BOX_WIDTH}
zeroLineColor={colors.ZERO_LINE}
gridLineColor={
colors.BOUNDARY_LINES
}
zeroLineWidth={1.25}
gridLineWidth={0.75}
opacity={GRID_LINES_OPACITY}
/>
</svg>
</div>
) : (
<div className="flex items-center justify-center h-full text-muted text-xs">
—
</div>
)}
</td>
</tr>
{/* Variant rows */}
{variantResults.map(
(variant: ExperimentVariantResult, index: number) => {
const isLastRow =
index === variantResults.length - 1 &&
!isLastBreakdown
const significant = isSignificant(variant)
const deltaPositive = isDeltaPositive(variant)
const winning = isWinning(variant, metric.goal)
const deltaText = formatDeltaPercent(variant)
const rowBackgroundColor = significant
? winning
? `${colors.BAR_POSITIVE}${SIGNIFICANT_ROW_BG_ALPHA}`
: `${colors.BAR_NEGATIVE}${SIGNIFICANT_ROW_BG_ALPHA}`
: undefined
const rowBackgroundImage = rowBackgroundColor
? `linear-gradient(${rowBackgroundColor}, ${rowBackgroundColor})`
: undefined
return (
<tr
key={`${metric.uuid}-${variant.key}`}
className="hover:bg-bg-hover"
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
onMouseEnter={(e) =>
handleTooltipMouseEnter(e, variant)
}
onMouseLeave={handleTooltipMouseLeave}
onMouseMove={(e) =>
handleTooltipMouseMove(e, variant)
}
>
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{
...FIXED_HEIGHT_STYLE,
backgroundImage: rowBackgroundImage,
}}
>
<VariantTag variantKey={variant.key} />
</td>
<td
className={`w-24 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{
...FIXED_HEIGHT_STYLE,
backgroundImage: rowBackgroundImage,
}}
>
<div className="metric-cell">
<div>
{formatMetricValue(
variant,
metric
)}
</div>
{ratioMetricLabel(variant, metric)}
</div>
</td>
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{
...FIXED_HEIGHT_STYLE,
backgroundImage: rowBackgroundImage,
}}
>
<div className="flex items-center gap-1">
<span
className={`metric-cell font-bold ${significant ? (winning ? 'text-success' : 'text-danger') : ''}`}
>
{deltaText}
</span>
{significant &&
deltaPositive !== undefined && (
<span
className={`flex-shrink-0 ${winning ? 'text-success' : 'text-danger'}`}
>
{deltaPositive ? (
<IconTrending
className="w-5 h-5"
style={{
strokeWidth: 2.5,
}}
/>
) : (
<IconTrendingDown
className="w-5 h-5"
style={{
strokeWidth: 2.5,
}}
/>
)}
</span>
)}
</div>
</td>
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 text-center whitespace-nowrap overflow-hidden ${!significant ? (isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light') : ''} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{
...FIXED_HEIGHT_STYLE,
backgroundColor: significant
? winning
? `${colors.BAR_POSITIVE}${SIGNIFICANT_CELL_BG_ALPHA}`
: `${colors.BAR_NEGATIVE}${SIGNIFICANT_CELL_BG_ALPHA}`
: undefined,
}}
>
<span
className={`metric-cell ${significant ? (winning ? 'text-success font-bold' : 'text-danger font-bold') : ''}`}
>
{isBayesianResult(variant)
? formatChanceToWinForGoal(
variant,
metric.goal
)
: formatPValue(variant.p_value)}
</span>
</td>
{/* Details (empty, for alignment) */}
<td
className={`w-20 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{
...FIXED_HEIGHT_STYLE,
backgroundImage: rowBackgroundImage,
}}
/>
<ChartCell
variantResult={variant}
metric={metric}
axisRange={axisRange}
metricUuid={metric.uuid}
isAlternatingRow={isAlternatingRow}
isLastRow={isLastRow}
isSecondary={false}
gradientSuffix={String(
breakdownResult.breakdown_value
)}
highlightBackgroundColor={
rowBackgroundColor
}
/>
</tr>
)
}
)}
</React.Fragment>
)
})}
</tbody>
</table>
</div>
),
},
]}
onChange={(activeKey) => setIsExpanded(activeKey === 'breakdowns')}
/>
</td>
</tr>
)
}
interface MetricRowGroupProps {
metric: ExperimentMetric
result: NewExperimentQueryResponse | null
experiment: Experiment
displayOrder: number
axisRange: number
isSecondary: boolean
isLastMetric: boolean
isAlternatingRow: boolean
dragHandle?: JSX.Element | null
onDuplicateMetric?: () => void
onDuplicateAsSingleUseMetric?: () => void
onDeleteMetric?: () => void
onBreakdownChange: (breakdown: Breakdown) => void
onRemoveBreakdown: (index: number) => void
onBreakdownAttributionChange: (attributionType: BreakdownAttributionType, attributionValue?: number) => void
onBreakdownLimitChange: (breakdownLimit: number) => void
error?: any
isLoading?: boolean
exposuresLoading?: boolean
showDetailsModal: boolean
}
/**
* Tooltip state is per MetricRowGroup, and a tooltip can outlive the cursor on its
* close-grace timer. Without coordination, sweeping the cursor across groups shows
* several tooltips at once. The group that owns the open tooltip registers its close
* function here, and the next group to open a tooltip calls it first.
*/
let closeOpenTooltip: (() => void) | null = null
export function MetricRowGroup({
metric,
result,
experiment,
displayOrder,
axisRange,
isSecondary,
isLastMetric,
isAlternatingRow,
dragHandle,
onDuplicateMetric,
onDuplicateAsSingleUseMetric,
onDeleteMetric,
onBreakdownChange,
onRemoveBreakdown,
onBreakdownAttributionChange,
onBreakdownLimitChange,
error,
isLoading,
exposuresLoading = false,
showDetailsModal,
}: MetricRowGroupProps): JSX.Element {
const [isModalOpen, setIsModalOpen] = useState(false)
const [timeseriesModalState, setTimeseriesModalState] = useState<{
isOpen: boolean
variantResult: ExperimentVariantResult | null
}>({
isOpen: false,
variantResult: null,
})
const [tooltipState, setTooltipState] = useState<{
isVisible: boolean
variantResult: ExperimentVariantResult | null
position: { x: number; y: number }
isPositioned: boolean
}>({
isVisible: false,
variantResult: null,
position: { x: 0, y: 0 },
isPositioned: false,
})
const tooltipRef = useRef<HTMLDivElement>(null)
const tooltipCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const ownsOpenTooltipRef = useRef(false)
const colors = useChartColors()
const clearTooltipCloseTimer = (): void => {
if (tooltipCloseTimerRef.current !== null) {
clearTimeout(tooltipCloseTimerRef.current)
tooltipCloseTimerRef.current = null
}
}
const hideTooltipState = (): void => {
if (ownsOpenTooltipRef.current) {
ownsOpenTooltipRef.current = false
closeOpenTooltip = null
}
setTooltipState((prev) => ({
...prev,
isVisible: false,
variantResult: null,
isPositioned: false,
}))
}
const scheduleTooltipClose = (): void => {
clearTooltipCloseTimer()
tooltipCloseTimerRef.current = setTimeout(() => {
tooltipCloseTimerRef.current = null
hideTooltipState()
}, 150)
}
const closeTooltipNow = (): void => {
clearTooltipCloseTimer()
hideTooltipState()
}
useEffect(() => {
return () => {
clearTooltipCloseTimer()
if (ownsOpenTooltipRef.current) {
ownsOpenTooltipRef.current = false
closeOpenTooltip = null
}
}
}, [])
// The tooltip is fixed-positioned from coordinates captured on hover, so it
// doesn't track the page on scroll — dismiss it instead, like native tooltips.
useEffect(() => {
if (!tooltipState.isVisible) {
return
}
const handleScroll = (): void => {
clearTooltipCloseTimer()
hideTooltipState()
}
// Capture phase so scrolls of any ancestor scroll container are caught, not just the window
window.addEventListener('scroll', handleScroll, { capture: true, passive: true })
return () => window.removeEventListener('scroll', handleScroll, { capture: true })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tooltipState.isVisible])
const scale = useAxisScale(axisRange, VIEW_BOX_WIDTH, SVG_EDGE_MARGIN)
const { reportExperimentTimeseriesViewed, refreshExperimentResults } = useActions(experimentLogic)
const { variants } = useValues(experimentLogic)
const { isRecalculating, metricRetries } = useValues(experimentMetricsLogic({ experiment }))
const { triggerRecalculation } = useActions(experimentMetricsLogic({ experiment }))
const handleRetry = (): void => {
triggerRecalculation('manual_retry')
refreshExperimentResults(true, 'manual')
}
// Build query for debugger link
const debugQuery = metric
? {
kind: NodeKind.ExperimentQuery,
metric: metric,
experiment_id: experiment.id,
}
: undefined
// Helper function to calculate tooltip position
const calculateTooltipPosition = (
chartCell: HTMLElement,
variantResult: ExperimentVariantResult
): { x: number; y: number } | null => {
if (!tooltipRef.current) {
return null
}
const chartCellRect = chartCell.getBoundingClientRect()
const tooltipRect = tooltipRef.current.getBoundingClientRect()
// Calculate the delta position within the SVG
const delta = getDelta(variantResult)
const deltaX = scale(delta)
// Convert SVG coordinates to pixel coordinates
const svgToPixelRatio = chartCellRect.width / VIEW_BOX_WIDTH
const deltaPixelX = deltaX * svgToPixelRatio
// Calculate tooltip position: center it above the confidence interval bar
let x = chartCellRect.left + deltaPixelX - tooltipRect.width / 2
const y = chartCellRect.top - tooltipRect.height - 8
// Keep tooltip within viewport bounds
const padding = 8
x = Math.max(padding, Math.min(x, window.innerWidth - tooltipRect.width - padding))
return { x, y }
}
// Tooltip handlers
const handleTooltipMouseEnter = (e: React.MouseEvent, variantResult: ExperimentVariantResult): void => {
const chartCell = e.currentTarget.querySelector('[data-table-cell="chart"]') as HTMLElement
if (!chartCell) {
return
}
clearTooltipCloseTimer()
if (!ownsOpenTooltipRef.current) {
closeOpenTooltip?.()
}
closeOpenTooltip = closeTooltipNow
ownsOpenTooltipRef.current = true
const position = calculateTooltipPosition(chartCell, variantResult)
setTooltipState({
isVisible: true,
variantResult,
position: position || { x: 0, y: 0 },
isPositioned: !!position,
})
}
// The portaled tooltip sits above the row. Defer closing only when the cursor
// exits upward (toward the tooltip) so the click affordance is reachable.
// Sideways or downward exits — i.e. moving to another variant row — close
// immediately so row-to-row transitions stay snappy.
const handleTooltipMouseLeave = (e: React.MouseEvent): void => {
const rect = e.currentTarget.getBoundingClientRect()
if (e.clientY <= rect.top + 1) {
scheduleTooltipClose()
} else {
closeTooltipNow()
}
}
const handleTooltipMouseMove = (e: React.MouseEvent, variantResult: ExperimentVariantResult): void => {
// Only reposition if not already positioned
if (!tooltipState.isPositioned) {
const chartCell = e.currentTarget.querySelector('[data-table-cell="chart"]') as HTMLElement
if (!chartCell) {
return
}
const position = calculateTooltipPosition(chartCell, variantResult)
if (position) {
setTooltipState((prev) => ({
...prev,
position,
isPositioned: true,
}))
}
}
}
const handleTimeseriesClick = (variantResult: ExperimentVariantResult): void => {
setTimeseriesModalState({
isOpen: true,
variantResult,
})
reportExperimentTimeseriesViewed(experiment.id, metric)
}
const handleTimeseriesModalClose = (): void => {
setTimeseriesModalState({
isOpen: false,
variantResult: null,
})
}
/**
* Skeleton-with-variants only when there's no result yet. A metric that already has a value renders
* its result, dimmed while recalculating, so a refresh never flashes the skeleton over real data.
*/
if (!result && !error && (isLoading || exposuresLoading)) {
const skeletonVariantKeys = variants.length > 0 ? variants.map((variant) => variant.key) : ['control']
const bg = isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
// Between failed attempts the chart column (and only it) explains the wait; every other cell keeps
// its skeleton. One cell spans the variant rows, so subsequent rows omit theirs.
const metricRetry = metric.uuid ? metricRetries[metric.uuid] : undefined
const retryChartCell = metricRetry ? (
<td
className={clsx(
'p-0 align-middle text-center relative overflow-hidden',
!isLastMetric && 'border-b',
bg
)}
rowSpan={skeletonVariantKeys.length}
// eslint-disable-next-line react/forbid-dom-props
style={getScaledHeightStyle(skeletonVariantKeys.length)}
>
<MetricRetryState retry={metricRetry} />
</td>
) : undefined
return (
<>
<tr
className="hover:bg-bg-hover group"
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
{/* Metric column: real header spanning every variant row, stays interactive while loading */}
<td
className={`group/metric-cell w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${
!isLastMetric ? 'border-b' : ''
} ${bg}`}
rowSpan={skeletonVariantKeys.length}
// eslint-disable-next-line react/forbid-dom-props
style={getScaledHeightStyle(skeletonVariantKeys.length)}
>
<MetricHeader
dragHandle={dragHandle}
displayOrder={displayOrder}
metric={metric}
isPrimaryMetric={!isSecondary}
experiment={experiment}
onDuplicateMetricClick={() => onDuplicateMetric?.()}
onDuplicateAsSingleUseMetricClick={() => onDuplicateAsSingleUseMetric?.()}
onDeleteMetricClick={onDeleteMetric ? () => onDeleteMetric() : undefined}
onBreakdownChange={onBreakdownChange}
/>
</td>
<SkeletonResultCells
variantKey={skeletonVariantKeys[0]}
className={clsx(bg, skeletonVariantKeys.length === 1 && 'border-b')}
chartCell={retryChartCell}
detailsCell={
<td
className={clsx(
'w-20 pt-3 align-top relative overflow-hidden',
!isLastMetric && 'border-b',
bg
)}
rowSpan={skeletonVariantKeys.length}
// eslint-disable-next-line react/forbid-dom-props
style={getScaledHeightStyle(skeletonVariantKeys.length)}
>
{/* Reserve the Details button's footprint so the chart column doesn't shift when results land */}
{showDetailsModal && (
<div className="flex justify-end">
<LemonSkeleton className="h-6 w-[74px]" />
</div>
)}
</td>
}
/>
</tr>
{skeletonVariantKeys.slice(1).map((variantKey, index) => (
<tr
key={variantKey}
className="hover:bg-bg-hover group"
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<SkeletonResultCells
variantKey={variantKey}
className={clsx(bg, index === skeletonVariantKeys.length - 2 && 'border-b')}
chartCell={metricRetry ? null : undefined}
/>
</tr>
))}
</>
)
}
if (error || !result) {
const noResultHeight = error ? CELL_HEIGHT : Math.max(CELL_HEIGHT, EMPTY_STATE_ROW_MIN_HEIGHT)
const noResultStateStyle = getMinHeightStyle(noResultHeight)
return (
<>
<tr
className="hover:bg-bg-hover group"
// eslint-disable-next-line react/forbid-dom-props
style={noResultStateStyle}
>
{/* Metric column - always visible */}
<td
className={`group/metric-cell w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${
!isLastMetric ? 'border-b' : ''
} ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
// eslint-disable-next-line react/forbid-dom-props
style={noResultStateStyle}
>
<MetricHeader
dragHandle={dragHandle}
displayOrder={displayOrder}
metric={metric}
isPrimaryMetric={!isSecondary}
experiment={experiment}
onDuplicateMetricClick={() => onDuplicateMetric?.()}
onDuplicateAsSingleUseMetricClick={() => onDuplicateAsSingleUseMetric?.()}
onDeleteMetricClick={onDeleteMetric ? () => onDeleteMetric() : undefined}
onBreakdownChange={onBreakdownChange}
/>
</td>
{/* Combined columns for error/empty state */}
<td
colSpan={6}
className={`p-3 text-center ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${
!isLastMetric ? 'border-b' : ''
}`}
// eslint-disable-next-line react/forbid-dom-props
style={noResultStateStyle}
>
<ChartEmptyState
height={noResultHeight}
experimentStarted={isLaunched(experiment)}
error={error}
query={debugQuery}
onRetry={error?.retriable === true ? handleRetry : undefined}
retryDisabledReason={isRecalculating ? 'Recalculation in progress' : undefined}
/>
</td>
</tr>
{metric.breakdownFilter?.breakdowns && metric.breakdownFilter.breakdowns.length > 0 && (
<MetricBreakdownError
metric={metric}
isAlternatingRow={isAlternatingRow}
onRemoveBreakdown={onRemoveBreakdown}
onAttributionChange={onBreakdownAttributionChange}
onBreakdownLimitChange={onBreakdownLimitChange}
/>
)}
</>
)
}
// At this point, we know result is defined, so we can safely access its properties
const baselineResult = result.baseline
const variantResults = result.variant_results || []
const totalRowsHeightStyle = getScaledHeightStyle(variantResults.length + 1)
const ratioMetricLabel = (variant: ExperimentStatsBaseValidated, metric: ExperimentMetric): JSX.Element => {
return (
<div className="text-xs text-muted">
{(() => {
const { numerator, denominator } = getMetricSubtitleValues(variant, metric)
return (
<>
{humanFriendlyLargeNumber(numerator)} / {humanFriendlyLargeNumber(denominator)}
</>
)
})()}
</div>
)
}
return (
<>
{/* Tooltip portal */}
{tooltipState.isVisible &&
tooltipState.variantResult &&
createPortal(
<div
ref={tooltipRef}
className="fixed bg-bg-light border border-border px-3 py-2 rounded-md text-[13px] shadow-md z-[100] min-w-[280px] cursor-pointer hover:border-primary"
// eslint-disable-next-line react/forbid-dom-props
style={{
left: tooltipState.position.x,
top: tooltipState.position.y,
visibility: tooltipState.isPositioned ? 'visible' : 'hidden',
}}
onMouseEnter={clearTooltipCloseTimer}
onMouseLeave={(e) => {
// Defer only when leaving downward — toward a row that may pick the tooltip back up.
const rect = e.currentTarget.getBoundingClientRect()
if (e.clientY >= rect.bottom - 1) {
scheduleTooltipClose()
} else {
closeTooltipNow()
}
}}
onClick={
tooltipState.variantResult
? () => handleTimeseriesClick(tooltipState.variantResult!)
: undefined
}
>
{renderTooltipContent(tooltipState.variantResult, metric, baselineResult.key)}
</div>,
document.body
)}
{/* Baseline row */}
<tr
className="hover:bg-bg-hover group"
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
{/* Metric column - with rowspan */}
<td
className={`group/metric-cell w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${!isLastMetric ? 'border-b' : ''} ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
rowSpan={variantResults.length + 1}
// eslint-disable-next-line react/forbid-dom-props
style={totalRowsHeightStyle}
>
<MetricHeader
dragHandle={dragHandle}
displayOrder={displayOrder}
metric={metric}
isPrimaryMetric={!isSecondary}
experiment={experiment}
onDuplicateMetricClick={() => onDuplicateMetric?.()}
onDuplicateAsSingleUseMetricClick={() => onDuplicateAsSingleUseMetric?.()}
onDeleteMetricClick={onDeleteMetric ? () => onDeleteMetric() : undefined}
onBreakdownChange={onBreakdownChange}
/>
</td>
{/* Variant name */}
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 whitespace-nowrap overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${variantResults.length === 0 ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<VariantTag variantKey={baselineResult.key} />
</td>
{/* Value */}
<td
className={`w-24 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${variantResults.length === 0 ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<div className="metric-cell">
<div>{formatMetricValue(baselineResult, metric)}</div>
{ratioMetricLabel(baselineResult, metric)}
</div>
</td>
{/* Change (empty for baseline) */}
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${variantResults.length === 0 ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<div />
</td>
{/* P-value / Win probability (empty for baseline) */}
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 text-center whitespace-nowrap overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${variantResults.length === 0 ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
<div />
</td>
{/* Details column (per-row cells so significant-row tints align pixel-perfectly; variant rows render their own) */}
<td
className={`w-20 pt-3 align-top relative overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${variantResults.length === 0 ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
{showDetailsModal && (
<>
<div className="flex justify-end">
<DetailsButton metric={metric} setIsModalOpen={setIsModalOpen} />
</div>
<DetailsModal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
metric={metric}
result={result}
experiment={experiment}
/>
</>
)}
</td>
{/* Chart (grid lines only for baseline) */}
<td
className={`p-0 align-top text-center relative overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${variantResults.length === 0 ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
>
{axisRange && axisRange > 0 ? (
<div className="relative h-full">
<svg
viewBox={`0 0 ${VIEW_BOX_WIDTH} ${CHART_CELL_VIEW_BOX_HEIGHT}`}
preserveAspectRatio="none"
className="h-full w-full"
>
<GridLines
tickValues={getNiceTickValues(axisRange)}
scale={scale}
height={CHART_CELL_VIEW_BOX_HEIGHT}
viewBoxWidth={VIEW_BOX_WIDTH}
zeroLineColor={colors.ZERO_LINE}
gridLineColor={colors.BOUNDARY_LINES}
zeroLineWidth={1.25}
gridLineWidth={0.75}
opacity={GRID_LINES_OPACITY}
/>
</svg>
</div>
) : (
<div className="flex items-center justify-center h-full text-muted text-xs">—</div>
)}
</td>
</tr>
{/* Variant rows */}
{variantResults.map((variant, index) => {
const isLastRow = index === variantResults.length - 1
const significant = isSignificant(variant)
const deltaPositive = isDeltaPositive(variant)
const winning = isWinning(variant, metric.goal)
const deltaText = formatDeltaPercent(variant)
const rowBackgroundColor = significant
? winning
? `${colors.BAR_POSITIVE}${SIGNIFICANT_ROW_BG_ALPHA}`
: `${colors.BAR_NEGATIVE}${SIGNIFICANT_ROW_BG_ALPHA}`
: undefined
const rowBackgroundImage = rowBackgroundColor
? `linear-gradient(${rowBackgroundColor}, ${rowBackgroundColor})`
: undefined
return (
<tr
key={`${metric.uuid}-${variant.key}`}
className="hover:bg-bg-hover group"
// eslint-disable-next-line react/forbid-dom-props
style={FIXED_HEIGHT_STYLE}
onMouseEnter={(e) => handleTooltipMouseEnter(e, variant)}
onMouseLeave={handleTooltipMouseLeave}
onMouseMove={(e) => handleTooltipMouseMove(e, variant)}
>
{/* Variant name */}
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{ ...FIXED_HEIGHT_STYLE, backgroundImage: rowBackgroundImage }}
>
<VariantTag variantKey={variant.key} />
</td>
{/* Value */}
<td
className={`w-24 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{ ...FIXED_HEIGHT_STYLE, backgroundImage: rowBackgroundImage }}
>
<div className="metric-cell">
<div>{formatMetricValue(variant, metric)}</div>
{ratioMetricLabel(variant, metric)}
</div>
</td>
{/* Delta */}
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${
isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'
} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{ ...FIXED_HEIGHT_STYLE, backgroundImage: rowBackgroundImage }}
>
<div className="flex items-center gap-1">
<span
className={`metric-cell font-bold ${significant ? (winning ? 'text-success' : 'text-danger') : ''}`}
>
{deltaText}
</span>
{significant && deltaPositive !== undefined && (
<span className={`flex-shrink-0 ${winning ? 'text-success' : 'text-danger'}`}>
{deltaPositive ? (
<IconTrending className="w-5 h-5" style={{ strokeWidth: 2.5 }} />
) : (
<IconTrendingDown className="w-5 h-5" style={{ strokeWidth: 2.5 }} />
)}
</span>
)}
</div>
</td>
{/* P-value / Win probability */}
<td
className={`w-20 pt-1 pl-3 pr-3 pb-1 text-center whitespace-nowrap overflow-hidden ${
!significant ? (isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light') : ''
} ${isLastRow ? 'border-b' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={{
...FIXED_HEIGHT_STYLE,
backgroundColor: significant
? winning
? `${colors.BAR_POSITIVE}${SIGNIFICANT_CELL_BG_ALPHA}`
: `${colors.BAR_NEGATIVE}${SIGNIFICANT_CELL_BG_ALPHA}`
: undefined,
}}
>
<span
className={`metric-cell ${significant ? (winning ? 'text-success font-bold' : 'text-danger font-bold') : ''}`}
>
{isBayesianResult(variant)
? formatChanceToWinForGoal(variant, metric.goal)
: formatPValue(variant.p_value)}
</span>
</td>
{/* Details (button lives in the baseline row's cell) */}
<td
className={`w-20 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${
isLastRow ? 'border-b' : ''
}`}
// eslint-disable-next-line react/forbid-dom-props
style={{ ...FIXED_HEIGHT_STYLE, backgroundImage: rowBackgroundImage }}
/>
{/* Chart */}
<ChartCell
variantResult={variant}
metric={metric}
axisRange={axisRange}
metricUuid={metric.uuid}
isAlternatingRow={isAlternatingRow}
isLastRow={isLastRow}
isSecondary={isSecondary}
onTimeseriesClick={() => handleTimeseriesClick(variant)}
highlightBackgroundColor={rowBackgroundColor}
/>
</tr>
)
})}
{/* Collapsible Breakdown Section. */}
{(metric.breakdownFilter?.breakdowns?.length ?? 0) > 0 && (
<CollapsibleBreakdownSection
breakdownResults={result.breakdown_results ?? []}
metric={metric}
experiment={experiment}
axisRange={axisRange}
isAlternatingRow={isAlternatingRow}
isLastMetric={isLastMetric}
isLoading={isLoading}
exposuresLoading={exposuresLoading}
isRecalculating={isRecalculating}
colors={colors}
scale={scale}
onRemoveBreakdown={onRemoveBreakdown}
onBreakdownAttributionChange={onBreakdownAttributionChange}
onBreakdownLimitChange={onBreakdownLimitChange}
onRetry={handleRetry}
query={debugQuery}
handleTooltipMouseEnter={handleTooltipMouseEnter}
handleTooltipMouseLeave={handleTooltipMouseLeave}
handleTooltipMouseMove={handleTooltipMouseMove}
/>
)}
{timeseriesModalState.variantResult && (
<TimeseriesModal
isOpen={timeseriesModalState.isOpen}
onClose={handleTimeseriesModalClose}
metric={metric}
variantResult={timeseriesModalState.variantResult}
experiment={experiment}
/>
)}
</>
)
}