: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
feat(insights): add hog-charts PieChart and gate Trends pie behind it (#59812)
Sam Penningtonedd553e0af18
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 224f7b140ba6..8d85d2934262 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -517,17 +517,17 @@ snapshots:components-hogcharts-linechart--error-boundary--light:hash: v1.k794b7964.71c1966fb319e455c7d712cd4a480e99ea73e66b04d72d4d1fe4222b058a5a3e.A2RMx3ED_wk_NM0l603i9XWa8hTv5r9JQgHOT5M7L9Ucomponents-hogcharts-linechart--hovering-interior--dark:- hash: v1.k794b7964.ef98fd77573e2acaf7bf7bfca859813671b738d8ee2877cc5e55e2b34535cf55.aR1BfOgHFXK08TIMw7PMiiz6Ameaz8lRvAjeXo070_Q+ hash: v1.k794b7964.106a98b78fdf3d33e9945449c237d568674bb73e6cac2824b068d9dde18f8eb8.IiK8CXDqFcxbK38JcDZ2VvsvJC_hMF4CfeOCTALU61Mcomponents-hogcharts-linechart--hovering-interior--light:- hash: v1.k794b7964.a5de82ff7b46d82c52fc0d8ce4b4aba505884feadbc44c02bf216186ce1c8edd.wryTORlIhCWy9Ysreyx0oBnf_PwqdA3XUDWpiwx0uTQ+ hash: v1.k794b7964.fbdce955d57f7fc414239a7dc502951925a647a510f59307b273a87a68acaa0a.tS4JZrw3ECahuMoFYTO3xoEJ89UQ84lFgvXFTKGwMNAcomponents-hogcharts-linechart--hovering-multi-series--dark:hash: v1.k794b7964.bc43065d43bc1e1238b514efd6bfbb3d1a2cc53f18c3cdcb59fdac8df9fe259b.zwrzaU3pqo3joC6IzW5dlDzp63ST6fjfuPyou6_72uccomponents-hogcharts-linechart--hovering-multi-series--light:hash: v1.k794b7964.fbfe3904fa22e1871488ca2f9ddb30b569100259708a16b6fcb722a450857b1c.-4mxJ92opWKeOvWoHto-KHEH6pTxG56-q0ddN3nxW7Qcomponents-hogcharts-linechart--hovering-over-aux-series--dark:- hash: v1.k794b7964.6b522e2b58799b5e9dbb17bee0e99b42c2ffc788c88cabe8f44e68ef82388086.7qlPt0jhAFGfLQ1whJLLTmgeJu1SIWk5rh7RVuUnJio+ hash: v1.k794b7964.1381975ad1f3cd6f0bd026ed40e2cdbb4d2f373af40565d3e04b681767987402.4ZDmXP-Pet9NoUXCH9u5N9IYRT4kiX_tBklnhDqz7TUcomponents-hogcharts-linechart--hovering-over-aux-series--light:- hash: v1.k794b7964.3c2769b13db2f7447396f79660f704885e2e378a3cfd5968d61e6c72703a2f18.MjtcmlOjrin3pCpNGPJ7awvzw0FGv1x3qF3MkRPA0-Y+ hash: v1.k794b7964.4c84ad5286c9fcbe5e781d8b33a8d0e7dc60b8f9743b64a5da4d4e01a54f0339.DXXeFCIu41B9QbBUxA8mdzHNLFZLLHQpZHReBIy9xwQcomponents-hogcharts-linechart--in-progress-tail--dark:hash: v1.k794b7964.c1f47391f93db83d4d9943cc8dec3bd9fcbbe8084ca3df54a1a74ebdf5afc656.q1YrKA5xq1YQMAYEh27agv4WfGjiWgVU5KaPC5LOLIMcomponents-hogcharts-linechart--in-progress-tail--light:@@ -568,6 +568,34 @@ snapshots:hash: v1.k794b7964.4c03eb4162445e32a74dc1ff8083feed9788b930aea5a4ce49e15c5da22d1b0b.OgPSbq_YYg9wIYaUs5jvjS-8YAzzBf5RgZIjtgXuZp8components-hogcharts-linechart--with-zeros-and-negatives--light:hash: v1.k794b7964.5d0d5d5cf4963ac46b4ed2bfdcedf7b24a63a47b7d84e259882e0606cbf43ce1.UtJNbmKgq3ZFS9AdrrOLJzsEejeh19IDdI9aOwxy9Ps+ components-hogcharts-piechart--donut--dark:+ hash: v1.k794b7964.53683ceb5ed88f7d3542094db1fb764fc6a2f8908036b3748ac4504695032427.qQAVMSvoraiafCrTL62wowzgaXHrdULwrGIb8d2VwBk+ components-hogcharts-piechart--donut--light:+ hash: v1.k794b7964.acf56c27510ab47148eb147dac441df1fb203c73461fae7d38aed39c9883759b.aGBuBjyBEhAJPjrrC_BepNi2g5zmX73vd2WhSO-tjj0+ components-hogcharts-piechart--long-label-tooltip--dark:+ hash: v1.k794b7964.d3bcb578618ec73e343c11fc05ccdad95e303c3973e1af922b0bbfd6e36b5dac.5sDDWcQqlACUZke1N8tCP6-3iPy-NvAREIJwMNDWAgY+ components-hogcharts-piechart--long-label-tooltip--light:+ hash: v1.k794b7964.083ff76dc306fc7cd2036b03d9d5545140cd24ba616951831fe210565a0bace7.q90E7qfNvWc7LpMhEVA5Wy8UiRWL8Zj_qK0GvU7aqZA+ components-hogcharts-piechart--no-hover-offset--dark:+ hash: v1.k794b7964.36ec7ed69ab9a16b562f6d59643a450c26e48fa07f5630696f38594aa49c610b.1kVPOF_OuCp_r0Hokh0cNZ-K6kSC-9KW-5uhiGl-1OI+ components-hogcharts-piechart--no-hover-offset--light:+ hash: v1.k794b7964.4ba748898ca2f36f7100332d96c4f3c51cd8a927253a21f187a2a4f3e93db95e.x_GSJSYhXipQxj4gd12Q4qwF5jiKopceWXXqdER9IzY+ components-hogcharts-piechart--percent--dark:+ hash: v1.k794b7964.503efa02ae97c5c60aa9adf056939622179a9864ce03906e86223027db2ce1b8.RWxBXw3OJ9zzy6F2aY-rp3EBJ2-HLfdOx2-E3k7oOsA+ components-hogcharts-piechart--percent--light:+ hash: v1.k794b7964.e282bbc15ed4820ca911ef9e676f6819be7c86a62958c6ae8be3dd08fc5c44cf.FIU7hDUrHSgX6UtMev4GBzMyQi1jTrndbEGZOm_nUpg+ components-hogcharts-piechart--pie-default--dark:+ hash: v1.k794b7964.36ec7ed69ab9a16b562f6d59643a450c26e48fa07f5630696f38594aa49c610b.n2FYmxpqqzT6_FtrjqvjpdLLhlGH5xSktNBnEyN3xX8+ components-hogcharts-piechart--pie-default--light:+ hash: v1.k794b7964.4ba748898ca2f36f7100332d96c4f3c51cd8a927253a21f187a2a4f3e93db95e.Iu2223knt2d5773R-s6_ke_oXweHsnv_nL-CmysPasI+ components-hogcharts-piechart--single-slice--dark:+ hash: v1.k794b7964.92bc7531883a5830155772e9df2b63b96baf8611980c1195b66cb75716fe4a79.7zFlXhqZqOTrUg3V38lXuMA6YaGwCA_-s_CsBKtwgtM+ components-hogcharts-piechart--single-slice--light:+ hash: v1.k794b7964.1a2540afa90064f951baa69e40405eb36459312978920ba46f2826cab097294a.JFioVV2KSnHa9Y-hREGuuT__I5ShHTvv8TgNVw7F0XU+ components-hogcharts-piechart--with-breakdown-labels--dark:+ hash: v1.k794b7964.e8aaf3e63d88d917b6511232aff85b4bf54f4c3b71fc267fde59a1170ba056a9.EL-FQ7Hqbd4FOdgbpZv2ynzzwJt2j6OQZkymgQXMC4U+ components-hogcharts-piechart--with-breakdown-labels--light:+ hash: v1.k794b7964.811f8e01cbeeb97d8319a76668d33864b6be08a2b8f270e5980fe951fafbc1bb.UoRHUDWOOnMGSCQcBN8D5TwfE6LL3IG58n0wUC_WOwocomponents-hogcharts-referenceline--fill-sides--dark:hash: v1.k794b7964.88be514f5436eb4c62b3db30e81e6d2f2c2b71cc6cf19bca459ed13dc901258a.mhwEtPTUGmbBcNrc9l0arcCL92Fzc-tT6uIfVDkGgpgcomponents-hogcharts-referenceline--fill-sides--light:diff --git a/frontend/src/lib/charts/types.ts b/frontend/src/lib/charts/types.tsindex dca6476f3ae1..15d40f3b748d 100644--- a/frontend/src/lib/charts/types.ts+++ b/frontend/src/lib/charts/types.ts@@ -2,6 +2,7 @@ export type AxisFormat = 'number' | 'compact' | 'percent' | 'duration' | 'duratiexport interface ChartTheme {colors: string[]+ /** Required by radial charts (PieChart) for the hover pop-out mask — without it the pop-out is skipped. */backgroundColor?: stringaxisColor?: stringgridColor?: stringdiff --git a/frontend/src/lib/colors.ts b/frontend/src/lib/colors.tsindex 6f6c3cb02583..6a4c10c95576 100644--- a/frontend/src/lib/colors.ts+++ b/frontend/src/lib/colors.ts@@ -122,10 +122,12 @@ export function getGraphColors(): Record<string, string | null> {axis: getColorVar('color-graph-axis'),crosshair: getColorVar('color-graph-crosshair'),- // TODO: these are not used anywhere, but setting them to the correct valuestooltipBackground: getColorVar('color-bg-surface-tooltip'),- tooltipTitle: getColorVar('color-text-primary'),- tooltipBody: getColorVar('color-bg-surface-tooltip'),+ // Pair the inverse text colour with the tooltip background — the tooltip surface is+ // already an inverse colour itself, so the default text-primary would match the+ // background in one of the two modes and render the text invisible.+ tooltipTitle: getColorVar('color-text-primary-inverse'),+ tooltipBody: getColorVar('color-text-primary-inverse'),}}diff --git a/frontend/src/lib/hog-charts/charts/PieChart/PieChart.stories.tsx b/frontend/src/lib/hog-charts/charts/PieChart/PieChart.stories.tsxnew file mode 100644index 000000000000..f8c19564e212--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/PieChart/PieChart.stories.tsx@@ -0,0 +1,120 @@+import { Meta, StoryObj } from '@storybook/react'++import type { Series } from '../../core/types'+import { Stage, useReactiveTheme } from '../../story-helpers'+import { PieChart } from './PieChart'+import type { PieChartConfig } from './PieChart'++const BROWSERS: Series[] = [+ { key: 'chrome', label: 'Chrome', color: '', data: [4200] },+ { key: 'safari', label: 'Safari', color: '', data: [1800] },+ { key: 'firefox', label: 'Firefox', color: '', data: [620] },+ { key: 'edge', label: 'Edge', color: '', data: [410] },+ { key: 'other', label: 'Other', color: '', data: [80] },+]++const ONE_BIG_TWO_TINY: Series[] = [+ { key: 'dominant', label: 'Direct', color: '', data: [9500] },+ { key: 'small-1', label: 'Search', color: '', data: [80] },+ { key: 'small-2', label: 'Social', color: '', data: [60] },+]++const meta: Meta = { title: 'Components/HogCharts/PieChart', parameters: { layout: 'centered' } }+export default meta++type Story = StoryObj<{}>++export const PieDefault: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <PieChart series={BROWSERS} theme={theme} />+ </Stage>+ )+ },+}++export const Donut: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const config: PieChartConfig = { innerRadiusRatio: 0.55 }+ const total = BROWSERS.reduce((acc, s) => acc + s.data[0], 0)+ return (+ <Stage>+ <PieChart+ series={BROWSERS}+ theme={theme}+ config={config}+ centerLabel={+ <div>+ <div style={{ fontSize: 12, opacity: 0.7 }}>Sessions</div>+ <div style={{ fontSize: 22, fontWeight: 700 }}>{total.toLocaleString()}</div>+ </div>+ }+ />+ </Stage>+ )+ },+}++export const Percent: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const config: PieChartConfig = { isPercent: true }+ return (+ <Stage>+ <PieChart series={BROWSERS} theme={theme} config={config} />+ </Stage>+ )+ },+}++export const SingleSlice: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [{ key: 'only', label: 'All events', color: '', data: [12345] }]+ return (+ <Stage>+ <PieChart series={series} theme={theme} />+ </Stage>+ )+ },+}++export const WithBreakdownLabels: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const config: PieChartConfig = { showLabelOnSlice: true, showValueOnSlice: true }+ return (+ <Stage>+ <PieChart series={BROWSERS} theme={theme} config={config} />+ </Stage>+ )+ },+}++export const LongLabelTooltip: Story = {+ render: () => {+ const theme = useReactiveTheme()+ // Slices below 5% are hidden from on-slice labels — but the tooltip should still show+ // their full label on hover, even when the breakdown text is long.+ return (+ <Stage>+ <PieChart series={ONE_BIG_TWO_TINY} theme={theme} />+ </Stage>+ )+ },+}++export const NoHoverOffset: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const config: PieChartConfig = { disableHoverOffset: true }+ return (+ <Stage>+ <PieChart series={BROWSERS} theme={theme} config={config} />+ </Stage>+ )+ },+}diff --git a/frontend/src/lib/hog-charts/charts/PieChart/PieChart.tsx b/frontend/src/lib/hog-charts/charts/PieChart/PieChart.tsxnew file mode 100644index 000000000000..1e18ef3d0fe7--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/PieChart/PieChart.tsx@@ -0,0 +1,328 @@+import React, { useCallback, useMemo } from 'react'++import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'+import type { RadialSlicePayload } from '../../core/hooks/useRadialInteraction'+import { useRadialLayout } from '../../core/radial-context'+import { RadialChart } from '../../core/RadialChart'+import type { RadialLayoutBuilder } from '../../core/RadialChart'+import type { ChartDrawArgs, ChartTheme, ResolvedSeries, Series, TooltipContext } from '../../core/types'+import { computePieLayout } from './computePieLayout'+import type { PieLayout } from './computePieLayout'+import { PieTooltip } from './PieTooltip'+import { SliceLabels } from './SliceLabels'++export interface PieChartConfig<Meta = unknown> {+ /** 0 = pie (default), 0.5 = donut. Clamped to [0, 0.95]. */+ innerRadiusRatio?: number+ /** Show the slice value above the slice (per Chart.js parity). Default true. */+ showValueOnSlice?: boolean+ /** Show the breakdown label above the slice. Default false. */+ showLabelOnSlice?: boolean+ /** Render slice values as percentages of total. Drives both axes-label-style formatting+ * and the on-slice / tooltip formatting. */+ isPercent?: boolean+ /** Pixels the hovered slice slides out along its bisector. Default 16. */+ hoverOffset?: number+ /** Disable the hover pop-out — useful for snapshot stability or constrained layouts. */+ disableHoverOffset?: boolean+ /** Hide on-slice labels for slices smaller than this fraction of the total. Default 0.05. */+ minSlicePercentForLabel?: number+ /** Radians gap between slices. Default 0. */+ padAngle?: number+ /** Slice ordering. `null` (default) preserves input order — needed for stable+ * per-series colors. Pass a comparator on slice magnitudes to sort visually. */+ sort?: ((a: number, b: number) => number) | null+ /** Slice magnitude resolver. Defaults to sum of finite, positive entries in `series.data`. */+ sliceValue?: (series: ResolvedSeries<Meta>) => number+ /** Tooltip behavior. */+ tooltip?: {+ enabled?: boolean+ }+}++export interface PieChartProps<Meta = unknown> {+ series: Series<Meta>[]+ theme: ChartTheme+ config?: PieChartConfig<Meta>+ tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode+ onSliceClick?: (payload: RadialSlicePayload<Meta>) => void+ className?: string+ /** `data-attr` applied to the chart wrapper. */+ dataAttr?: string+ /** Custom value formatter used by the on-slice value label and the default tooltip.+ * Receives the raw slice magnitude; the chart handles percent conversion when+ * `isPercent` is on. */+ valueFormatter?: (value: number) => string+ /** Optional content rendered at the center of the chart — typically the aggregation+ * total for a donut. Receives the layout so consumers can position custom content. */+ centerLabel?: React.ReactNode+ /** React children passed through to the radial overlay layer (custom decorations). */+ children?: React.ReactNode+ onError?: (error: Error, info: React.ErrorInfo) => void+}++const DEFAULT_HOVER_OFFSET = 16+const DEFAULT_MIN_SLICE_PERCENT = 0.05++const CENTER_LABEL_STYLE: React.CSSProperties = {+ position: 'absolute',+ pointerEvents: 'none',+ transform: 'translate(-50%, -50%)',+ textAlign: 'center',+ whiteSpace: 'nowrap',+}++interface CenterLabelProps {+ children: React.ReactNode+ cx: number+ cy: number+}++function CenterLabel({ children, cx, cy }: CenterLabelProps): React.ReactElement {+ return <div style={{ ...CENTER_LABEL_STYLE, left: cx, top: cy }}>{children}</div>+}++export function PieChart<Meta = unknown>({ onError, ...rest }: PieChartProps<Meta>): React.ReactElement {+ return (+ <ChartErrorBoundary onError={onError}>+ <PieChartInner {...rest} />+ </ChartErrorBoundary>+ )+}++function defaultValueFormatter(value: number): string {+ return value.toLocaleString()+}++function PieChartInner<Meta = unknown>({+ series,+ theme,+ config,+ tooltip,+ onSliceClick,+ className,+ dataAttr,+ valueFormatter = defaultValueFormatter,+ centerLabel,+ children,+}: Omit<PieChartProps<Meta>, 'onError'>): React.ReactElement {+ const {+ innerRadiusRatio = 0,+ showValueOnSlice = true,+ showLabelOnSlice = false,+ isPercent = false,+ hoverOffset = DEFAULT_HOVER_OFFSET,+ disableHoverOffset = false,+ minSlicePercentForLabel = DEFAULT_MIN_SLICE_PERCENT,+ padAngle = 0,+ sort = null,+ sliceValue,+ tooltip: tooltipConfig,+ } = config ?? {}++ const showTooltip = tooltipConfig?.enabled !== false++ const buildLayout = useCallback<RadialLayoutBuilder<Meta>>(+ (resolvedSeries, dimensions) =>+ computePieLayout<Meta>({+ series: resolvedSeries,+ dimensions,+ sliceValue,+ innerRadiusRatio,+ padAngle,+ sort,+ }),+ [sliceValue, innerRadiusRatio, padAngle, sort]+ )++ const effectiveHoverOffset = disableHoverOffset ? 0 : hoverOffset++ const drawStatic = useCallback((args: ChartDrawArgs) => {+ const layout = getLayoutFromArgs<Meta>(args)+ if (!layout) {+ return+ }+ drawSlices(args.ctx, layout, args.theme, { skipIndex: -1, offset: 0 })+ }, [])++ const drawHover = useCallback(+ (args: ChartDrawArgs) => {+ const layout = getLayoutFromArgs<Meta>(args)+ if (!layout || args.hoverIndex < 0) {+ return+ }+ // Single-slice charts have nothing to pop out — drawing the offset would visually+ // shift the whole wheel.+ if (layout.slices.length <= 1 || effectiveHoverOffset === 0) {+ return+ }+ // The mask step below relies on `theme.backgroundColor` to erase the static-canvas+ // copy of the slice. Without one, the popped-out slice would partially overlap the+ // original and smear — better to skip the pop-out than render that.+ if (!args.theme.backgroundColor) {+ return+ }+ const slice = layout.slices[args.hoverIndex]+ if (!slice) {+ return+ }+ // Two-pass paint on the (always-cleared) overlay canvas:+ // 1. Fill the slice's original footprint with the theme background. The overlay+ // sits above the static canvas, so this *visually* erases the un-offset copy+ // that `useChartDraw` re-paints on the static layer every render.+ // 2. Paint the slice in its real color at the offset position.+ // Without step 1 the offset copy only partially overlaps the original, leaving a+ // crescent of the un-offset slice visible — a smear, not a clean pop-out.+ drawSliceShape(args.ctx, slice, layout, {+ offset: 0,+ fillStyle: args.theme.backgroundColor,+ withStroke: undefined,+ })+ drawSliceShape(args.ctx, slice, layout, {+ offset: effectiveHoverOffset,+ fillStyle: slice.color,+ withStroke: layout.slices.length > 1 ? args.theme.backgroundColor : undefined,+ })+ },+ [effectiveHoverOffset]+ )++ const renderTooltip = useMemo(+ () =>+ tooltip ??+ ((ctx: TooltipContext<Meta>): React.ReactNode => (+ <PieTooltip ctx={ctx} valueFormatter={valueFormatter} isPercent={isPercent} />+ )),+ [tooltip, valueFormatter, isPercent]+ )++ return (+ <RadialChart<Meta>+ series={series}+ theme={theme}+ buildLayout={buildLayout}+ drawStatic={drawStatic}+ drawHover={drawHover}+ tooltip={renderTooltip}+ showTooltip={showTooltip}+ onSliceClick={onSliceClick}+ hitOuterSlack={effectiveHoverOffset}+ className={className}+ dataAttr={dataAttr}+ >+ <SliceLabels+ valueFormatter={valueFormatter}+ showValueOnSlice={showValueOnSlice}+ showLabelOnSlice={showLabelOnSlice}+ minSlicePercentForLabel={minSlicePercentForLabel}+ isPercent={isPercent}+ />+ <PieCenterLabel>{centerLabel}</PieCenterLabel>+ {children}+ </RadialChart>+ )+}++function PieCenterLabel({ children }: { children: React.ReactNode }): React.ReactElement | null {+ const { layout } = useRadialLayout()+ if (!children) {+ return null+ }+ return (+ <CenterLabel cx={layout.cx} cy={layout.cy}>+ {children}+ </CenterLabel>+ )+}++function getLayoutFromArgs<Meta>(args: ChartDrawArgs): PieLayout<Meta> | null {+ const priv = args.scales._private as { __radialChart?: { layout: PieLayout<Meta> } } | undefined+ return priv?.__radialChart?.layout ?? null+}++interface DrawSlicesOptions {+ skipIndex: number+ offset: number+}++function drawSlices<Meta>(+ ctx: CanvasRenderingContext2D,+ layout: PieLayout<Meta>,+ theme: ChartTheme,+ { skipIndex, offset }: DrawSlicesOptions+): void {+ for (let i = 0; i < layout.slices.length; i++) {+ if (i === skipIndex) {+ continue+ }+ drawSlice(ctx, layout.slices[i], layout, theme, { offset })+ }+}++interface DrawSliceOptions {+ offset: number+}++function drawSlice<Meta>(+ ctx: CanvasRenderingContext2D,+ slice: PieLayout<Meta>['slices'][number],+ layout: PieLayout<Meta>,+ theme: ChartTheme,+ { offset }: DrawSliceOptions+): void {+ // Inter-slice stroke in the theme background — visually separates adjacent slices+ // without a heavy outline. Skipped when there's only one slice (no neighbour to separate from).+ const withStroke = layout.slices.length > 1 ? theme.backgroundColor : undefined+ drawSliceShape(ctx, slice, layout, { offset, fillStyle: slice.color, withStroke })+}++interface DrawSliceShapeOptions {+ offset: number+ fillStyle: string+ /** Inter-slice stroke color (typically `theme.backgroundColor`). Omit to skip stroking. */+ withStroke: string | undefined+}++/** Lower-level slice painter — takes explicit fill / stroke so the hover layer can both+ * mask (background fill, no stroke) and re-paint (slice color, with stroke) using the same+ * arc geometry. */+function drawSliceShape<Meta>(+ ctx: CanvasRenderingContext2D,+ slice: PieLayout<Meta>['slices'][number],+ layout: PieLayout<Meta>,+ { offset, fillStyle, withStroke }: DrawSliceShapeOptions+): void {+ const halfPad = layout.padAngle / 2+ const start = slice.startAngle + halfPad+ const end = slice.endAngle - halfPad+ if (start >= end) {+ return+ }+ const offsetX = offset === 0 ? 0 : Math.sin(slice.centroidAngle) * offset+ const offsetY = offset === 0 ? 0 : -Math.cos(slice.centroidAngle) * offset+ const cx = layout.cx + offsetX+ const cy = layout.cy + offsetY++ // Canvas arc convention: 0 = 3 o'clock, increasing clockwise. d3.pie uses+ // 0 = 12 o'clock. Subtract π/2 to align.+ const cStart = start - Math.PI / 2+ const cEnd = end - Math.PI / 2++ ctx.fillStyle = fillStyle+ ctx.beginPath()+ if (layout.innerRadius > 0) {+ ctx.arc(cx, cy, layout.outerRadius, cStart, cEnd, false)+ ctx.arc(cx, cy, layout.innerRadius, cEnd, cStart, true)+ } else {+ ctx.moveTo(cx, cy)+ ctx.arc(cx, cy, layout.outerRadius, cStart, cEnd, false)+ }+ ctx.closePath()+ ctx.fill()++ if (withStroke) {+ ctx.lineWidth = 1+ ctx.strokeStyle = withStroke+ ctx.stroke()+ }+}diff --git a/frontend/src/lib/hog-charts/charts/PieChart/PieTooltip.tsx b/frontend/src/lib/hog-charts/charts/PieChart/PieTooltip.tsxnew file mode 100644index 000000000000..055e7d97d326--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/PieChart/PieTooltip.tsx@@ -0,0 +1,58 @@+import React from 'react'++import { useChartLayout } from '../../core/chart-context'+import type { TooltipContext } from '../../core/types'++export interface PieTooltipProps<Meta> {+ ctx: TooltipContext<Meta>+ valueFormatter?: (value: number) => string+ isPercent?: boolean+}++const DEFAULT_TOOLTIP_BG = '#1d2330'+const DEFAULT_TOOLTIP_COLOR = '#ffffff'++function defaultFormatter(v: number): string {+ return v.toLocaleString()+}++function formatPercent(fraction: number): string {+ return `${Math.round(fraction * 1000) / 10}%`+}++export function PieTooltip<Meta>({+ ctx,+ valueFormatter = defaultFormatter,+ isPercent = false,+}: PieTooltipProps<Meta>): React.ReactElement | null {+ const { theme } = useChartLayout()+ const entry = ctx.seriesData[0]+ if (!entry) {+ return null+ }+ const share = entry.fraction ?? 0++ return (+ <div+ className="px-3 py-2 rounded-lg shadow-lg text-[13px]"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ backgroundColor: theme.tooltipBackground ?? DEFAULT_TOOLTIP_BG,+ color: theme.tooltipColor ?? DEFAULT_TOOLTIP_COLOR,+ }}+ >+ <div className="flex items-center gap-2 mb-1">+ <span+ className="inline-block size-2 rounded-full"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ backgroundColor: entry.color }}+ />+ <span className="font-semibold">{entry.series.label}</span>+ </div>+ <div className="flex items-center gap-2">+ <strong>{isPercent ? formatPercent(share) : valueFormatter(entry.value)}</strong>+ {!isPercent && share > 0 ? <span className="opacity-70">({formatPercent(share)})</span> : null}+ </div>+ </div>+ )+}diff --git a/frontend/src/lib/hog-charts/charts/PieChart/SliceLabels.test.tsx b/frontend/src/lib/hog-charts/charts/PieChart/SliceLabels.test.tsxnew file mode 100644index 000000000000..3e5fd29c45b4--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/PieChart/SliceLabels.test.tsx@@ -0,0 +1,105 @@+import { cleanup, render, type RenderResult } from '@testing-library/react'+import React from 'react'++import { RadialLayoutContext } from '../../core/radial-context'+import type { RadialLayoutContextValue } from '../../core/radial-context'+import type { ResolvedSeries } from '../../core/types'+import { computePieLayout } from './computePieLayout'+import type { PieLayout } from './computePieLayout'+import { SliceLabels } from './SliceLabels'++const PLOT = { plotLeft: 0, plotTop: 0, plotWidth: 400, plotHeight: 400 }++function s(key: string, value: number, extras: Partial<ResolvedSeries> = {}): ResolvedSeries {+ return { key, label: key.toUpperCase(), data: [value], color: '#000', ...extras }+}++function renderWithLayout(layout: PieLayout, node: React.ReactNode): RenderResult {+ const value: RadialLayoutContextValue = { layout, canvasBounds: () => null }+ return render(<RadialLayoutContext.Provider value={value}>{node}</RadialLayoutContext.Provider>)+}++function labels(container: HTMLElement): HTMLDivElement[] {+ return Array.from(container.querySelectorAll<HTMLDivElement>('[data-attr="hog-chart-pie-slice-label"]'))+}++describe('SliceLabels', () => {+ afterEach(() => cleanup())++ it('renders one label per slice when all are above the threshold', () => {+ const layout = computePieLayout({+ series: [s('a', 25), s('b', 25), s('c', 25), s('d', 25)],+ dimensions: PLOT,+ })+ const { container } = renderWithLayout(layout, <SliceLabels />)+ expect(labels(container)).toHaveLength(4)+ })++ it('hides slices below minSlicePercentForLabel', () => {+ const layout = computePieLayout({+ series: [s('a', 96), s('b', 2), s('c', 2)],+ dimensions: PLOT,+ })+ const { container } = renderWithLayout(layout, <SliceLabels minSlicePercentForLabel={0.05} />)+ // only the 96-value slice is >= 5%+ expect(labels(container)).toHaveLength(1)+ })++ it('respects visibility.valueLabel = false', () => {+ const layout = computePieLayout({+ series: [s('a', 25), s('b', 25, { visibility: { valueLabel: false } }), s('c', 25), s('d', 25)],+ dimensions: PLOT,+ })+ const { container } = renderWithLayout(layout, <SliceLabels />)+ expect(labels(container)).toHaveLength(3)+ expect(labels(container).map((d) => d.textContent)).not.toContain(expect.stringContaining('B'))+ })++ it('renders nothing when both value and label are disabled', () => {+ const layout = computePieLayout({+ series: [s('a', 25), s('b', 25)],+ dimensions: PLOT,+ })+ const { container } = renderWithLayout(+ layout,+ <SliceLabels showValueOnSlice={false} showLabelOnSlice={false} />+ )+ expect(labels(container)).toHaveLength(0)+ })++ it('uses the provided formatter for values', () => {+ const layout = computePieLayout({+ series: [s('a', 1500)],+ dimensions: PLOT,+ })+ const { container } = renderWithLayout(+ layout,+ <SliceLabels valueFormatter={(v) => `$${(v / 1000).toFixed(1)}k`} />+ )+ expect(labels(container)[0].textContent).toContain('$1.5k')+ })++ it('renders percent strings when isPercent is true', () => {+ const layout = computePieLayout({+ series: [s('a', 25), s('b', 75)],+ dimensions: PLOT,+ })+ const { container } = renderWithLayout(layout, <SliceLabels isPercent />)+ const text = labels(container)+ .map((d) => d.textContent ?? '')+ .join('|')+ expect(text).toContain('25%')+ expect(text).toContain('75%')+ })++ it('shows the breakdown label above the value when showLabelOnSlice is true', () => {+ const layout = computePieLayout({+ series: [s('a', 50), s('b', 50)],+ dimensions: PLOT,+ })+ const { container } = renderWithLayout(layout, <SliceLabels showLabelOnSlice showValueOnSlice />)+ const a = labels(container)[0]+ expect(a.textContent).toContain('A')+ expect(a.textContent).toContain('50')+ })+})diff --git a/frontend/src/lib/hog-charts/charts/PieChart/SliceLabels.tsx b/frontend/src/lib/hog-charts/charts/PieChart/SliceLabels.tsxnew file mode 100644index 000000000000..46f0fb2b9539--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/PieChart/SliceLabels.tsx@@ -0,0 +1,78 @@+import React from 'react'++import { useRadialLayout } from '../../core/radial-context'++export interface SliceLabelsProps {+ valueFormatter?: (value: number) => string+ /** Show the slice's value above the slice. Default true. */+ showValueOnSlice?: boolean+ /** Show the breakdown label above the slice. Default false. When both are true, the+ * label sits above the value. */+ showLabelOnSlice?: boolean+ /** Hide labels for slices with `fraction < threshold`. Default 0.05. */+ minSlicePercentForLabel?: number+ isPercent?: boolean+}++const LABEL_STYLE_BASE: React.CSSProperties = {+ position: 'absolute',+ pointerEvents: 'none',+ color: 'white',+ fontSize: 12,+ fontWeight: 600,+ lineHeight: 1.2,+ textAlign: 'center',+ textShadow: '0 1px 2px rgba(0, 0, 0, 0.45)',+ whiteSpace: 'nowrap',+ transform: 'translate(-50%, -50%)',+}++function defaultFormatter(v: number): string {+ return v.toLocaleString()+}++function formatPercent(fraction: number): string {+ return `${Math.round(fraction * 1000) / 10}%`+}++export function SliceLabels({+ valueFormatter = defaultFormatter,+ showValueOnSlice = true,+ showLabelOnSlice = false,+ minSlicePercentForLabel = 0.05,+ isPercent = false,+}: SliceLabelsProps): React.ReactElement | null {+ const { layout } = useRadialLayout()+ if (!showValueOnSlice && !showLabelOnSlice) {+ return null+ }+ const midR = layout.innerRadius + (layout.outerRadius - layout.innerRadius) / 2+ return (+ <>+ {layout.slices.map((slice, i) => {+ if (slice.series.visibility?.valueLabel === false) {+ return null+ }+ if (slice.fraction < minSlicePercentForLabel) {+ return null+ }+ const x = layout.cx + Math.sin(slice.centroidAngle) * midR+ const y = layout.cy - Math.cos(slice.centroidAngle) * midR+ const valueText = isPercent ? formatPercent(slice.fraction) : valueFormatter(slice.value)+ return (+ <div+ // Slice positions can shift when the input series changes, but `seriesIndex`+ // is stable across re-renders of the same series, which keeps React's+ // reconciliation predictable.+ key={slice.series.key || i}+ data-attr="hog-chart-pie-slice-label"+ style={{ ...LABEL_STYLE_BASE, left: Math.round(x), top: Math.round(y) }}+ >+ {showLabelOnSlice ? <div>{slice.series.label}</div> : null}+ {showValueOnSlice ? <div>{valueText}</div> : null}+ </div>+ )+ })}+ </>+ )+}diff --git a/frontend/src/lib/hog-charts/charts/PieChart/computePieLayout.test.ts b/frontend/src/lib/hog-charts/charts/PieChart/computePieLayout.test.tsnew file mode 100644index 000000000000..89b886c1bc42--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/PieChart/computePieLayout.test.ts@@ -0,0 +1,238 @@+import type { ResolvedSeries } from '../../core/types'+import { computePieLayout, cursorOffsetToAngle, sliceAt } from './computePieLayout'++const PLOT = { plotLeft: 0, plotTop: 0, plotWidth: 400, plotHeight: 400 }++function s(key: string, data: number[], extras: Partial<ResolvedSeries> = {}): ResolvedSeries {+ return { key, label: key.toUpperCase(), data, color: '#000', ...extras }+}++describe('computePieLayout', () => {+ it('spans the full 2π across all slices (no gaps when padAngle = 0)', () => {+ const layout = computePieLayout({+ series: [s('a', [10]), s('b', [20]), s('c', [30])],+ dimensions: PLOT,+ })+ const total = layout.slices.reduce((sum, sl) => sum + (sl.endAngle - sl.startAngle), 0)+ expect(total).toBeCloseTo(2 * Math.PI, 6)+ })++ it('subtracts padAngle gaps from total span', () => {+ const padAngle = 0.02+ const layout = computePieLayout({+ series: [s('a', [10]), s('b', [20]), s('c', [30])],+ dimensions: PLOT,+ padAngle,+ })+ // d3.pie keeps the total spanned but reduces the drawable arc by padAngle per slice.+ // Per d3 docs the gross extent stays 2π, so we just sanity-check there are 3 slices+ // and padAngle is reflected.+ expect(layout.slices).toHaveLength(3)+ expect(layout.padAngle).toBe(padAngle)+ })++ it('drops excluded series from layout', () => {+ const layout = computePieLayout({+ series: [s('a', [10]), s('b', [20], { visibility: { excluded: true } }), s('c', [30])],+ dimensions: PLOT,+ })+ expect(layout.slices.map((sl) => sl.series.key)).toEqual(['a', 'c'])+ expect(layout.total).toBe(40)+ })++ it('preserves original seriesIndex through excluded filtering', () => {+ const layout = computePieLayout({+ series: [s('a', [10]), s('b', [20], { visibility: { excluded: true } }), s('c', [30])],+ dimensions: PLOT,+ })+ // 'c' is at index 2 in the input; the slice must preserve that for click attribution.+ const sliceC = layout.slices.find((sl) => sl.series.key === 'c')+ expect(sliceC?.seriesIndex).toBe(2)+ })++ it('produces donut radii when innerRadiusRatio > 0', () => {+ const layout = computePieLayout({+ series: [s('a', [10]), s('b', [10])],+ dimensions: PLOT,+ innerRadiusRatio: 0.5,+ })+ expect(layout.outerRadius).toBeGreaterThan(0)+ expect(layout.innerRadius).toBeCloseTo(layout.outerRadius * 0.5, 6)+ })++ it('clamps innerRadiusRatio into [0, 0.95]', () => {+ const layout = computePieLayout({+ series: [s('a', [10]), s('b', [10])],+ dimensions: PLOT,+ innerRadiusRatio: 5,+ })+ expect(layout.innerRadius).toBeCloseTo(layout.outerRadius * 0.95, 6)+ })++ it('preserves input order when sort is null (default)', () => {+ const layout = computePieLayout({+ series: [s('big', [100]), s('mid', [50]), s('small', [10])],+ dimensions: PLOT,+ })+ expect(layout.slices.map((sl) => sl.series.key)).toEqual(['big', 'mid', 'small'])+ })++ it('respects a sort comparator on slice magnitudes (slice angles reflect sort, not array order)', () => {+ // d3.pie keeps the output array aligned with the input data so consumers can join by+ // index; the sort affects start/end angles instead. Validate the *visual* order.+ const layout = computePieLayout({+ series: [s('small', [10]), s('big', [100]), s('mid', [50])],+ dimensions: PLOT,+ sort: (a, b) => b - a,+ })+ const byStart = [...layout.slices].sort((a, b) => a.startAngle - b.startAngle)+ expect(byStart.map((sl) => sl.series.key)).toEqual(['big', 'mid', 'small'])+ })++ it('clamps negative values to 0', () => {+ const layout = computePieLayout({+ series: [s('a', [-50]), s('b', [10])],+ dimensions: PLOT,+ })+ expect(layout.total).toBe(10)+ // Negative-valued slice contributes 0 so its arc collapses.+ const sliceA = layout.slices.find((sl) => sl.series.key === 'a')+ expect(sliceA).not.toBeUndefined()+ expect(sliceA!.endAngle - sliceA!.startAngle).toBeCloseTo(0, 6)+ })++ it('returns an empty layout when total is 0', () => {+ const layout = computePieLayout({+ series: [s('a', [0]), s('b', [0])],+ dimensions: PLOT,+ })+ expect(layout.slices).toHaveLength(0)+ expect(layout.total).toBe(0)+ })++ it('returns an empty layout when no series', () => {+ const layout = computePieLayout({ series: [], dimensions: PLOT })+ expect(layout.slices).toHaveLength(0)+ expect(layout.total).toBe(0)+ })++ it('normalizes fractions to sum to 1', () => {+ const layout = computePieLayout({+ series: [s('a', [3]), s('b', [3]), s('c', [3]), s('d', [1])],+ dimensions: PLOT,+ })+ const sum = layout.slices.reduce((acc, sl) => acc + sl.fraction, 0)+ expect(sum).toBeCloseTo(1, 6)+ })++ it('uses a custom sliceValue resolver when provided', () => {+ const layout = computePieLayout({+ series: [s('a', [10, 20]), s('b', [5])],+ dimensions: PLOT,+ sliceValue: (sr) => sr.data.length,+ })+ // a has 2 entries, b has 1.+ const sliceA = layout.slices.find((sl) => sl.series.key === 'a')+ const sliceB = layout.slices.find((sl) => sl.series.key === 'b')+ expect(sliceA?.value).toBe(2)+ expect(sliceB?.value).toBe(1)+ })+})++describe('cursorOffsetToAngle', () => {+ it.each<[string, number, number, number]>([+ ["12 o'clock", 0, -1, 0],+ ["3 o'clock", 1, 0, Math.PI / 2],+ ["6 o'clock", 0, 1, Math.PI],+ ["9 o'clock", -1, 0, (3 * Math.PI) / 2],+ ])('%s', (_name, dx, dy, expected) => {+ expect(cursorOffsetToAngle(dx, dy)).toBeCloseTo(expected, 6)+ })++ it.each<[number]>([[0], [17], [45], [90], [127], [180], [225], [270], [315], [340]])(+ 'returns an angle in [0, 2π) for %sdeg',+ (deg) => {+ const rad = (deg * Math.PI) / 180+ const a = cursorOffsetToAngle(Math.sin(rad), -Math.cos(rad))+ expect(a).toBeGreaterThanOrEqual(0)+ expect(a).toBeLessThan(2 * Math.PI)+ }+ )+})++describe('sliceAt', () => {+ const baseLayout = computePieLayout({+ series: [s('a', [25]), s('b', [25]), s('c', [25]), s('d', [25])],+ dimensions: PLOT,+ })+ // four equal slices: each 90deg, starting at 12 o'clock and progressing clockwise.+ // slice 0 → 12 to 3, slice 1 → 3 to 6, slice 2 → 6 to 9, slice 3 → 9 to 12.++ function cursorAt(angleDeg: number, radius: number): { x: number; y: number } {+ const rad = (angleDeg * Math.PI) / 180+ return {+ x: baseLayout.cx + Math.sin(rad) * radius,+ y: baseLayout.cy - Math.cos(rad) * radius,+ }+ }++ it('identifies the slice under the cursor for each cardinal direction', () => {+ const midR = (baseLayout.innerRadius + baseLayout.outerRadius) / 2 || baseLayout.outerRadius / 2+ expect(sliceAt(baseLayout, cursorAt(45, midR))).toBe(0)+ expect(sliceAt(baseLayout, cursorAt(135, midR))).toBe(1)+ expect(sliceAt(baseLayout, cursorAt(225, midR))).toBe(2)+ expect(sliceAt(baseLayout, cursorAt(315, midR))).toBe(3)+ })++ it('returns -1 outside outerRadius', () => {+ expect(sliceAt(baseLayout, cursorAt(45, baseLayout.outerRadius + 50))).toBe(-1)+ })++ it('accepts a cursor inside the outerSlack band', () => {+ const slack = 20+ expect(sliceAt(baseLayout, cursorAt(45, baseLayout.outerRadius + 10), { outerSlack: slack })).toBe(0)+ })++ it('returns -1 inside the donut inner hole', () => {+ const donut = computePieLayout({+ series: [s('a', [25]), s('b', [25]), s('c', [25]), s('d', [25])],+ dimensions: PLOT,+ innerRadiusRatio: 0.6,+ })+ const insideHole = { x: donut.cx + 5, y: donut.cy + 5 }+ expect(sliceAt(donut, insideHole)).toBe(-1)+ })++ it('returns -1 inside a padAngle gap', () => {+ const padded = computePieLayout({+ series: [s('a', [25]), s('b', [25]), s('c', [25]), s('d', [25])],+ dimensions: PLOT,+ padAngle: 0.2, // wide gap so we can land in it+ })+ // boundary at 90deg between slice 0 and slice 1+ const midR = padded.outerRadius / 2+ const boundary = {+ x: padded.cx + Math.sin(Math.PI / 2) * midR,+ y: padded.cy - Math.cos(Math.PI / 2) * midR,+ }+ expect(sliceAt(padded, boundary)).toBe(-1)+ })++ it.each<[number]>([[0], [90], [180], [270], [359]])(+ "handles the 12 o'clock wraparound at %sdeg for a single slice",+ (deg) => {+ const full = computePieLayout({+ series: [s('only', [100])],+ dimensions: PLOT,+ })+ const midR = full.outerRadius / 2+ const rad = (deg * Math.PI) / 180+ expect(sliceAt(full, { x: full.cx + Math.sin(rad) * midR, y: full.cy - Math.cos(rad) * midR })).toBe(0)+ }+ )++ it('returns -1 when there are no slices', () => {+ const empty = computePieLayout({ series: [], dimensions: PLOT })+ expect(sliceAt(empty, { x: empty.cx, y: empty.cy })).toBe(-1)+ })+})diff --git a/frontend/src/lib/hog-charts/charts/PieChart/computePieLayout.ts b/frontend/src/lib/hog-charts/charts/PieChart/computePieLayout.tsnew file mode 100644index 000000000000..f3c955b708dd--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/PieChart/computePieLayout.ts@@ -0,0 +1,200 @@+import * as d3 from 'd3'++import type { ResolvedSeries } from '../../core/types'++export interface PieSlice<Meta = unknown> {+ /** Index into the *original* (pre-exclusion) series array. */+ seriesIndex: number+ series: ResolvedSeries<Meta>+ /** Absolute slice magnitude. Negative inputs are clamped to 0 — a pie can't render them. */+ value: number+ /** value / total (0 when total is 0). */+ fraction: number+ /** Radians, 12 o'clock = 0, increasing clockwise (d3.pie convention). */+ startAngle: number+ endAngle: number+ /** Bisector angle — anchor for pop-out and on-slice labels. */+ centroidAngle: number+ color: string+}++export interface PieLayout<Meta = unknown> {+ slices: PieSlice<Meta>[]+ total: number+ cx: number+ cy: number+ /** Outer slice radius, *excluding* hover pop-out room. */+ outerRadius: number+ /** Inner radius (0 for pie, > 0 for donut). */+ innerRadius: number+ /** Radians gap between adjacent slices. */+ padAngle: number+}++export interface PlotBox {+ plotLeft: number+ plotTop: number+ plotWidth: number+ plotHeight: number+}++export interface ComputePieLayoutOptions<Meta = unknown> {+ series: ResolvedSeries<Meta>[]+ dimensions: PlotBox+ /** Magnitude resolver. Defaults to sum of finite, positive entries in `series.data`. */+ sliceValue?: (series: ResolvedSeries<Meta>) => number+ /** 0 = pie, 0.5 = donut. Clamped to [0, 0.95]. */+ innerRadiusRatio?: number+ /** Radians gap between slices. Defaults to 0. */+ padAngle?: number+ /** Sort comparator on slice magnitudes, or `null` to preserve input order. Defaults to `null`. */+ sort?: ((a: number, b: number) => number) | null+ /** Outer-radius scale factor — pulls the outer edge in to leave room for hover pop-out+ * and labels. Defaults to 0.92. */+ radiusPadding?: number+}++export function defaultSliceValue<Meta>(s: ResolvedSeries<Meta>): number {+ // Naive sum — `computePieLayout` clamps the result to 0 for negative totals. Keep this+ // close to "sum(series.data)" so a custom `sliceValue` that wants a different aggregation+ // (e.g. last point only, average) replaces the whole resolver rather than fighting a+ // pre-clamp here.+ let sum = 0+ for (const v of s.data) {+ if (typeof v === 'number' && Number.isFinite(v)) {+ sum += v+ }+ }+ return sum+}++export function computePieLayout<Meta = unknown>(opts: ComputePieLayoutOptions<Meta>): PieLayout<Meta> {+ const {+ series,+ dimensions,+ sliceValue = defaultSliceValue,+ innerRadiusRatio = 0,+ padAngle = 0,+ sort = null,+ radiusPadding = 0.92,+ } = opts++ const cx = dimensions.plotLeft + dimensions.plotWidth / 2+ const cy = dimensions.plotTop + dimensions.plotHeight / 2+ const shorterSide = Math.min(dimensions.plotWidth, dimensions.plotHeight)+ const outerRadius = Math.max(0, (shorterSide / 2) * radiusPadding)+ const clampedInnerRatio = Math.max(0, Math.min(innerRadiusRatio, 0.95))+ const innerRadius = clampedInnerRatio * outerRadius++ // Index *before* filtering so click handlers can recover the original series position.+ type Indexed = { series: ResolvedSeries<Meta>; value: number; seriesIndex: number }+ const indexed: Indexed[] = []+ for (let i = 0; i < series.length; i++) {+ const s = series[i]+ if (s.visibility?.excluded) {+ continue+ }+ const raw = sliceValue(s)+ const value = typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : 0+ indexed.push({ series: s, value, seriesIndex: i })+ }++ let total = 0+ for (const i of indexed) {+ total += i.value+ }++ if (total <= 0 || indexed.length === 0 || outerRadius <= 0) {+ return { slices: [], total: 0, cx, cy, outerRadius, innerRadius, padAngle }+ }++ const pieGenerator = d3+ .pie<Indexed>()+ .value((d) => d.value)+ .padAngle(padAngle)+ if (sort === null) {+ pieGenerator.sort(null)+ } else {+ pieGenerator.sort((a, b) => sort(a.value, b.value))+ }+ const arcs = pieGenerator(indexed)++ const slices: PieSlice<Meta>[] = arcs.map((arc) => {+ const centroidAngle = (arc.startAngle + arc.endAngle) / 2+ return {+ seriesIndex: arc.data.seriesIndex,+ series: arc.data.series,+ value: arc.data.value,+ fraction: arc.data.value / total,+ startAngle: arc.startAngle,+ endAngle: arc.endAngle,+ centroidAngle,+ color: arc.data.series.color,+ }+ })++ return { slices, total, cx, cy, outerRadius, innerRadius, padAngle }+}++/** Maps a cursor offset (dx, dy) from the chart center to an angle in radians, matching+ * the d3.pie convention: 12 o'clock = 0, increasing clockwise, range [0, 2π). */+export function cursorOffsetToAngle(dx: number, dy: number): number {+ // 12 o'clock = (0, -1) → atan2(0, 1) = 0+ // 3 o'clock = (1, 0) → atan2(1, 0) = π/2+ // 6 o'clock = (0, 1) → atan2(0, -1) = π+ // 9 o'clock = (-1, 0) → atan2(-1, 0) = -π/2 → normalized to 3π/2+ let a = Math.atan2(dx, -dy)+ if (a < 0) {+ a += 2 * Math.PI+ }+ return a+}++export interface SliceAtOptions {+ /** Allowance beyond `outerRadius` so the popped-out slice still registers as hovered. */+ outerSlack?: number+}++/** Returns the index of the slice under the cursor, or -1.+ * - Misses the donut inner hole (`r < innerRadius`).+ * - Misses past the outer edge plus optional slack.+ * - Treats `padAngle/2` of each slice's start/end as a gap (no hit).+ * - Handles d3.pie's 12 o'clock wraparound (slice that crosses 0). */+export function sliceAt<Meta>(+ layout: PieLayout<Meta>,+ cursor: { x: number; y: number },+ { outerSlack = 0 }: SliceAtOptions = {}+): number {+ if (layout.slices.length === 0) {+ return -1+ }+ const dx = cursor.x - layout.cx+ const dy = cursor.y - layout.cy+ const r = Math.hypot(dx, dy)+ if (r < layout.innerRadius || r > layout.outerRadius + outerSlack) {+ return -1+ }+ const a = cursorOffsetToAngle(dx, dy)+ const halfPad = layout.padAngle / 2+ for (let i = 0; i < layout.slices.length; i++) {+ const s = layout.slices[i]+ let start = s.startAngle + halfPad+ let end = s.endAngle - halfPad+ if (start >= end) {+ continue+ }+ if (start < 0 || end > 2 * Math.PI) {+ // Wraparound — slice crosses 12 o'clock. Split into the [start, 2π) ∪ [0, end mod 2π) check.+ const sNorm = ((start % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI)+ const eNorm = ((end % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI)+ if (a >= sNorm || a < eNorm) {+ return i+ }+ continue+ }+ if (a >= start && a < end) {+ return i+ }+ }+ return -1+}diff --git a/frontend/src/lib/hog-charts/core/RadialChart.tsx b/frontend/src/lib/hog-charts/core/RadialChart.tsxnew file mode 100644index 000000000000..8b866621e74a--- /dev/null+++ b/frontend/src/lib/hog-charts/core/RadialChart.tsx@@ -0,0 +1,227 @@+import React, { useCallback, useMemo } from 'react'++import type { PieLayout } from '../charts/PieChart/computePieLayout'+import { DefaultTooltip } from '../overlays/DefaultTooltip'+import { Tooltip } from '../overlays/Tooltip'+import { ChartHoverContext, ChartLayoutContext } from './chart-context'+import type { ChartHoverContextValue, ChartLayoutContextValue } from './chart-context'+import { useChartCanvas } from './hooks/useChartCanvas'+import { useChartDraw } from './hooks/useChartDraw'+import { useRadialInteraction } from './hooks/useRadialInteraction'+import type { RadialSlicePayload } from './hooks/useRadialInteraction'+import { RadialLayoutContext } from './radial-context'+import type { RadialLayoutContextValue } from './radial-context'+import type {+ ChartDrawArgs,+ ChartMargins,+ ChartScales,+ ChartTheme,+ ResolvedSeries,+ Series,+ TooltipContext,+} from './types'+import { defaultResolveValue } from './types'++const OVERLAY_STYLE: React.CSSProperties = {+ position: 'absolute',+ top: 0,+ left: 0,+ width: '100%',+ height: '100%',+ pointerEvents: 'none',+}+const WRAPPER_STYLE_BASE: React.CSSProperties = {+ position: 'relative',+ width: '100%',+ flex: 1,+ minHeight: 0,+ overflow: 'hidden',+}+const WRAPPER_STYLE_DEFAULT: React.CSSProperties = { ...WRAPPER_STYLE_BASE, cursor: 'default' }+const WRAPPER_STYLE_POINTER: React.CSSProperties = { ...WRAPPER_STYLE_BASE, cursor: 'pointer' }++const STATIC_CANVAS_STYLE: React.CSSProperties = { position: 'absolute', top: 0, left: 0 }+const OVERLAY_CANVAS_STYLE: React.CSSProperties = {+ position: 'absolute',+ top: 0,+ left: 0,+ pointerEvents: 'none',+}++/** Near-zero margins — the radial chart computes center + radius from the full plot box and+ * pulls the outer edge back via `radiusPadding`. The tiny pad here keeps slice strokes off+ * the wrapper edge. */+export const RADIAL_MARGINS: ChartMargins = { top: 8, right: 8, bottom: 8, left: 8 }++/** Builds the geometry — and the matching ChartScales / RadialLayoutContext — from the+ * current dimensions and resolved series. Pie/Donut variants supply their own builder. */+export type RadialLayoutBuilder<Meta = unknown> = (+ series: ResolvedSeries<Meta>[],+ dimensions: { plotLeft: number; plotTop: number; plotWidth: number; plotHeight: number }+) => PieLayout<Meta>++export interface RadialChartProps<Meta = unknown> {+ series: Series<Meta>[]+ theme: ChartTheme+ buildLayout: RadialLayoutBuilder<Meta>+ drawStatic: (args: ChartDrawArgs) => void+ drawHover: (args: ChartDrawArgs) => void+ tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode+ showTooltip?: boolean+ onSliceClick?: (payload: RadialSlicePayload<Meta>) => void+ /** Slack beyond `outerRadius` for hit-testing — typically the hover pop-out distance. */+ hitOuterSlack?: number+ className?: string+ dataAttr?: string+ children?: React.ReactNode+}++export function RadialChart<Meta = unknown>({+ series,+ theme,+ buildLayout,+ drawStatic,+ drawHover,+ tooltip: renderTooltip = DefaultTooltip,+ showTooltip = true,+ onSliceClick,+ hitOuterSlack = 0,+ className,+ dataAttr,+ children,+}: RadialChartProps<Meta>): React.ReactElement {+ const { canvasRef, overlayCanvasRef, wrapperRef, dimensions, ctx, overlayCtx } = useChartCanvas({+ margins: RADIAL_MARGINS,+ })++ const coloredSeries = useMemo<ResolvedSeries<Meta>[]>(+ () =>+ series.map((s, i) => ({+ ...s,+ color: s.color || theme.colors[i % theme.colors.length],+ })),+ [series, theme.colors]+ )++ const layout = useMemo(() => {+ if (!dimensions) {+ return null+ }+ return buildLayout(coloredSeries, dimensions)+ }, [coloredSeries, dimensions, buildLayout])++ // Expose the layout through a minimal ChartScales-shaped object so the shared `useChartDraw`+ // can pass it through `drawStatic` / `drawHover` without special-casing radial. Library code+ // never reads `_private`; consumers do via the typed radial context below.+ const scales = useMemo<ChartScales | null>(() => {+ if (!layout) {+ return null+ }+ return {+ x: () => undefined,+ y: () => 0,+ yTicks: () => [],+ _private: { __radialChart: { layout } },+ }+ }, [layout])++ const { hoverIndex, tooltipCtx, handlers } = useRadialInteraction<Meta>({+ layout,+ canvasRef,+ wrapperRef,+ showTooltip,+ onSliceClick,+ hitOuterSlack,+ })++ useChartDraw({+ ctx,+ overlayCtx,+ dimensions,+ scales,+ series: coloredSeries,+ // No x-axis category labels in a radial chart; preserve the contract by passing []. Slice+ // labels live in the SliceLabels overlay, which reads from the radial layout directly.+ labels: [],+ hoverIndex,+ hoverPosition: null,+ theme,+ drawStatic,+ drawHover,+ })++ const ariaLabel = useMemo(() => {+ const visible = coloredSeries.reduce((n, s) => n + (s.visibility?.excluded ? 0 : 1), 0)+ return `Pie chart with ${visible} slices`+ }, [coloredSeries])++ const wrapperStyle = hoverIndex >= 0 && onSliceClick ? WRAPPER_STYLE_POINTER : WRAPPER_STYLE_DEFAULT++ const canvasBounds = useCallback(+ (): DOMRect | null => canvasRef.current?.getBoundingClientRect() ?? null,+ [canvasRef]+ )++ // Provide the standard ChartLayoutContext so existing shared overlays (e.g. custom user+ // overlays accessing `useChartLayout()` for `theme`) continue to work. Most cartesian-only+ // overlays (AxisLabels, ValueLabels) shouldn't be used inside a radial chart, but the+ // context is still useful for theme + dimensions access.+ const layoutValue = useMemo<ChartLayoutContextValue<Meta> | null>(() => {+ if (!scales || !dimensions) {+ return null+ }+ return {+ scales,+ dimensions,+ labels: [],+ series: coloredSeries,+ theme,+ resolvePositionValue: defaultResolveValue,+ canvasBounds,+ axis: { orientation: 'vertical', xTickFormatter: undefined, isPercent: false },+ }+ }, [scales, dimensions, coloredSeries, theme, canvasBounds])++ const radialValue = useMemo<RadialLayoutContextValue<Meta> | null>(() => {+ if (!layout) {+ return null+ }+ return { layout, canvasBounds }+ }, [layout, canvasBounds])++ const hoverValue = useMemo<ChartHoverContextValue>(() => ({ hoverIndex }), [hoverIndex])++ return (+ <ChartLayoutContext.Provider value={layoutValue as ChartLayoutContextValue | null}>+ <RadialLayoutContext.Provider value={radialValue as RadialLayoutContextValue | null}>+ <ChartHoverContext.Provider value={hoverValue}>+ <div+ ref={wrapperRef}+ className={className}+ data-attr={dataAttr}+ style={wrapperStyle}+ onMouseMove={handlers.onMouseMove}+ onMouseLeave={handlers.onMouseLeave}+ onClick={handlers.onClick}+ >+ <canvas ref={canvasRef} role="img" aria-label={ariaLabel} style={STATIC_CANVAS_STYLE} />+ <canvas ref={overlayCanvasRef} aria-hidden="true" style={OVERLAY_CANVAS_STYLE} />++ {dimensions && layout && (+ <div style={OVERLAY_STYLE}>+ {children}+ {tooltipCtx && showTooltip && (+ <Tooltip+ context={tooltipCtx}+ renderTooltip={renderTooltip}+ placement="follow-data"+ />+ )}+ </div>+ )}+ </div>+ </ChartHoverContext.Provider>+ </RadialLayoutContext.Provider>+ </ChartLayoutContext.Provider>+ )+}diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts b/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.tsindex 53bbedc523c4..e49c4fc4f3f8 100644--- a/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts+++ b/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts@@ -1,4 +1,4 @@-import React, { useCallback, useEffect, useMemo, useState } from 'react'+import React, { useCallback, useMemo } from 'react'import {buildLabelPositions,@@ -17,35 +17,7 @@ import type {TooltipContext,} from '../types'import { useLatest } from './useLatest'--function isTooltipContextEquivalent<Meta>(a: TooltipContext<Meta>, b: TooltipContext<Meta>): boolean {- if (a.dataIndex !== b.dataIndex || a.label !== b.label) {- return false- }- if (a.position.x !== b.position.x || a.position.y !== b.position.y) {- return false- }- if (a.seriesData.length !== b.seriesData.length) {- return false- }- for (let i = 0; i < a.seriesData.length; i++) {- const ai = a.seriesData[i]- const bi = b.seriesData[i]- // Compare series by stable `key` rather than identity: the parent rebuilds- // `coloredSeries` (and so each entry's `series` reference) on every render, so- // an identity check would defeat the equivalence bail. `label` is also compared- // because it's user-visible in the tooltip and can change while the key stays.- if (- ai.value !== bi.value ||- ai.color !== bi.color ||- ai.series.key !== bi.series.key ||- ai.series.label !== bi.series.label- ) {- return false- }- }- return true-}+import { useTooltipLifecycle } from './useTooltipLifecycle'interface UseChartInteractionOptions<Meta> {scales: ChartScales | null@@ -95,52 +67,23 @@ export function useChartInteraction<Meta = unknown>({// Falls back to the value resolver when the chart doesn't distinguish position from// value (i.e. non-stacked charts, where the two are identical).const effectivePositionResolve = resolvePositionValue ?? resolveValue- const [hoverIndex, setHoverIndex] = useState<number>(-1)- const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null)- const [tooltipCtx, setTooltipCtx] = useState<TooltipContext<Meta> | null>(null)- // Read by onClick to decide pin/unpin/passthrough. Event handlers fire after the- // most recent commit, so an effect-deferred ref is correct here.- const hoverIndexRef = useLatest(hoverIndex)-- const clearTooltip = useCallback(() => {- setHoverIndex(-1)- setHoverPosition(null)- setTooltipCtx(null)- }, [])-- const unpin = useCallback(() => {- setTooltipCtx((prev) => (prev?.isPinned ? null : prev))- }, [])-- const isPinned = tooltipCtx?.isPinned ?? false-- // Precompute the (coord, index) lookup table once per (labels, scale) change.- const labelPositions = useMemo(- () => (scales ? buildLabelPositions(labels, labelToCoord ?? scales.x) : []),- [labels, scales, labelToCoord]- )- // Rebuild or clear the pinned tooltip when its underlying inputs change.- // Without this, the pin keeps stale values at stale pixel positions after the- // parent updates series/labels/scales/dimensions. resolveValue is read live via- // a ref so unmemoized closures don't trigger a rebuild every render — see the- // contract on `ChartProps.resolveValue`: any external toggle that changes the- // resolver's output must also update series or scales.+ // resolveValue / effectivePositionResolve are read live in the pinned-rebuild path so an+ // unmemoized closure on either doesn't trigger a rebuild every render — see the contract+ // on `ChartProps.resolveValue`.const resolveValueRef = useLatest(resolveValue)const effectivePositionResolveRef = useLatest(effectivePositionResolve)- useEffect(() => {- if (!isPinned || !scales || !dimensions) {- return- }- setTooltipCtx((prev) => {- if (!prev || !prev.isPinned) {++ const rebuildPinnedCtx = useCallback(+ (prev: TooltipContext<Meta>): TooltipContext<Meta> | null => {+ if (!scales || !dimensions) {return prev}if (prev.dataIndex >= labels.length) {return null}const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()- const fresh = buildTooltipContext(+ return buildTooltipContext(prev.dataIndex,series,labels,@@ -153,85 +96,37 @@ export function useChartInteraction<Meta = unknown>({prev.hoverPosition,effectivePositionResolveRef.current)- if (!fresh) {- return null- }- // Bail when the rebuilt context is value-equal to prev. Avoids identity churn- // re-rendering the tooltip overlay when the parent rerenders for unrelated- // reasons (e.g. dashboard-level state) while the pin is held.- if (isTooltipContextEquivalent(prev, fresh)) {- return prev- }- return { ...fresh, isPinned: true, onUnpin: unpin }- })- // Omitted on purpose:- // - isPinned / tooltipCtx: would feedback-loop with setTooltipCtx- // - unpin / canvasRef: stable for the lifetime of the hook (useCallback([])/useRef)- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [series, labels, scales, dimensions])-- // Dismiss the tooltip on scroll — pinned or not — since the anchor moves- // with the page and a stale tooltip is worse than no tooltip.- const tooltipShown = tooltipCtx !== null- useEffect(() => {- if (!tooltipShown) {- return- }- const handleScroll = (e: Event): void => {- // Allow scrolling inside the tooltip itself (long pinned content)- // or the chart wrapper (a nested legend) without dismissing.- const target = e.target- if (target instanceof Element) {- if (target.closest('[data-hog-charts-tooltip]')) {- return- }- if (wrapperRef.current?.contains(target)) {- return- }- }- clearTooltip()- }- window.addEventListener('scroll', handleScroll, { passive: true, capture: true })- return () => {- window.removeEventListener('scroll', handleScroll, true)- }- }, [tooltipShown, wrapperRef, clearTooltip])-- // Dismiss listeners for pinned tooltip- useEffect(() => {- if (!isPinned) {- return- }-- const handleClickOutside = (e: MouseEvent): void => {- const target = e.target- if (target instanceof Element && target.closest('[data-hog-charts-tooltip]')) {- return- }- const wrapper = wrapperRef.current- if (wrapper && !wrapper.contains(target as Node)) {- clearTooltip()- }- }+ },+ // resolveValueRef / effectivePositionResolveRef are stable+ [+ scales,+ dimensions,+ labels,+ series,+ canvasRef,+ labelToCoord,+ interactionAxis,+ resolveValueRef,+ effectivePositionResolveRef,+ ]+ )- const handleKeyDown = (e: KeyboardEvent): void => {- if (e.key === 'Escape') {- clearTooltip()- }- }+ const { hoverIndex, hoverPosition, tooltipCtx, setHover, setTooltipCtx, isPinned, clearTooltip, pin } =+ useTooltipLifecycle<Meta>({+ wrapperRef,+ rebuildPinnedCtx,+ rebuildDeps: [series, labels, scales, dimensions],+ })- // Delay click listener so the pinning click doesn't immediately unpin- const timer = setTimeout(() => {- document.addEventListener('click', handleClickOutside, { passive: true })- }, 0)- document.addEventListener('keydown', handleKeyDown, { passive: true })+ // Read by onClick to decide pin/unpin/passthrough. Event handlers fire after the most+ // recent commit, so an effect-deferred ref is correct here.+ const hoverIndexRef = useLatest(hoverIndex)- return () => {- clearTimeout(timer)- document.removeEventListener('click', handleClickOutside)- document.removeEventListener('keydown', handleKeyDown)- }- }, [isPinned, wrapperRef, clearTooltip])+ // Precompute the (coord, index) lookup table once per (labels, scale) change.+ const labelPositions = useMemo(+ () => (scales ? buildLabelPositions(labels, labelToCoord ?? scales.x) : []),+ [labels, scales, labelToCoord]+ )const onMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {@@ -250,8 +145,7 @@ export function useChartInteraction<Meta = unknown>({const probe = interactionAxis === 'y' ? mouseY : mouseXconst index = findNearestIndexFromPositions(probe, labelPositions)- setHoverIndex(index)- setHoverPosition({ x: mouseX, y: mouseY })+ setHover(index, { x: mouseX, y: mouseY })if (index >= 0 && showTooltip) {const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()@@ -287,6 +181,8 @@ export function useChartInteraction<Meta = unknown>({labelPositions,labelToCoord,interactionAxis,+ setHover,+ setTooltipCtx,])@@ -313,7 +209,7 @@ export function useChartInteraction<Meta = unknown>({// consumer's own row handler. With a single series there's nothing to pin, so// onPointClick fires immediately instead.if (pinnable && tooltipCtx && tooltipCtx.seriesData.length > 1) {- setTooltipCtx({ ...tooltipCtx, isPinned: true, onUnpin: unpin })+ pin()return}@@ -323,7 +219,7 @@ export function useChartInteraction<Meta = unknown>({onPointClick(clickData)}}- }, [onPointClick, series, labels, resolveValue, pinnable, tooltipCtx, isPinned, clearTooltip, unpin, hoverIndexRef])+ }, [onPointClick, series, labels, resolveValue, pinnable, tooltipCtx, isPinned, clearTooltip, pin, hoverIndexRef])const handlers = useMemo(() => ({ onMouseMove, onMouseLeave, onClick }), [onMouseMove, onMouseLeave, onClick])diff --git a/frontend/src/lib/hog-charts/core/hooks/useRadialInteraction.ts b/frontend/src/lib/hog-charts/core/hooks/useRadialInteraction.tsnew file mode 100644index 000000000000..fd964c24ed4d--- /dev/null+++ b/frontend/src/lib/hog-charts/core/hooks/useRadialInteraction.ts@@ -0,0 +1,157 @@+import React, { useCallback, useMemo } from 'react'++import { sliceAt } from '../../charts/PieChart/computePieLayout'+import type { PieLayout, PieSlice } from '../../charts/PieChart/computePieLayout'+import type { ResolvedSeries, TooltipContext } from '../types'+import { useLatest } from './useLatest'+import { useTooltipLifecycle } from './useTooltipLifecycle'++export interface RadialSlicePayload<Meta = unknown> {+ sliceIndex: number+ series: ResolvedSeries<Meta>+ value: number+ fraction: number+}++interface UseRadialInteractionOptions<Meta> {+ layout: PieLayout<Meta> | null+ canvasRef: React.RefObject<HTMLCanvasElement>+ wrapperRef: React.RefObject<HTMLDivElement>+ showTooltip: boolean+ onSliceClick?: (payload: RadialSlicePayload<Meta>) => void+ /** Allowance beyond `outerRadius` for hit-testing so the popped-out slice still hovers.+ * Typically equal to `hoverOffset`. */+ hitOuterSlack?: number+}++interface UseRadialInteractionResult<Meta> {+ hoverIndex: number+ hoverPosition: { x: number; y: number } | null+ tooltipCtx: TooltipContext<Meta> | null+ handlers: {+ onMouseMove: (e: React.MouseEvent<HTMLDivElement>) => void+ onMouseLeave: () => void+ onClick: () => void+ }+}++function buildPieTooltipCtx<Meta>(+ slice: PieSlice<Meta>,+ layout: PieLayout<Meta>,+ cursor: { x: number; y: number } | null,+ canvasBounds: DOMRect+): TooltipContext<Meta> {+ // Anchor at the centroid of the slice (mid-radius along bisector) so the tooltip points+ // at the slice it describes, not at the cursor.+ const midR = (layout.innerRadius + layout.outerRadius) / 2+ const ax = layout.cx + Math.sin(slice.centroidAngle) * midR+ const ay = layout.cy - Math.cos(slice.centroidAngle) * midR+ return {+ // Slot the slice index into `dataIndex` so generic overlays / equivalence checks still work.+ dataIndex: slice.seriesIndex,+ label: slice.series.label,+ seriesData: [{ series: slice.series, value: slice.value, color: slice.color, fraction: slice.fraction }],+ position: { x: ax, y: ay },+ hoverPosition: cursor,+ canvasBounds,+ isPinned: false,+ }+}++export function useRadialInteraction<Meta = unknown>({+ layout,+ canvasRef,+ wrapperRef,+ showTooltip,+ onSliceClick,+ hitOuterSlack = 0,+}: UseRadialInteractionOptions<Meta>): UseRadialInteractionResult<Meta> {+ // The pin tracks a *series key* across rebuilds (rather than slice index) so reordering or+ // hiding adjacent slices doesn't silently move the pin to a different slice.+ const layoutRef = useLatest(layout)++ const rebuildPinnedCtx = useCallback(+ (prev: TooltipContext<Meta>): TooltipContext<Meta> | null => {+ const lo = layoutRef.current+ if (!lo) {+ return prev+ }+ const prevKey = prev.seriesData[0]?.series.key+ const slice = lo.slices.find((s) => s.series.key === prevKey)+ if (!slice) {+ return null+ }+ const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()+ return buildPieTooltipCtx(slice, lo, prev.hoverPosition, canvasBounds)+ },+ [layoutRef, canvasRef]+ )++ const { hoverIndex, hoverPosition, tooltipCtx, setHover, setTooltipCtx, isPinned, clearTooltip } =+ useTooltipLifecycle<Meta>({+ wrapperRef,+ rebuildPinnedCtx,+ rebuildDeps: [layout],+ })++ const hoverIndexRef = useLatest(hoverIndex)++ const onMouseMove = useCallback(+ (e: React.MouseEvent<HTMLDivElement>) => {+ if (isPinned) {+ return+ }+ const lo = layoutRef.current+ if (!lo || lo.slices.length === 0) {+ return+ }+ const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()+ const mouseX = e.clientX - rect.left+ const mouseY = e.clientY - rect.top+ const cursor = { x: mouseX, y: mouseY }+ const idx = sliceAt(lo, cursor, { outerSlack: hitOuterSlack })+ if (idx < 0) {+ clearTooltip()+ return+ }+ setHover(idx, cursor)+ if (showTooltip) {+ const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()+ setTooltipCtx(buildPieTooltipCtx(lo.slices[idx], lo, cursor, canvasBounds))+ }+ },+ [isPinned, layoutRef, hitOuterSlack, showTooltip, setHover, setTooltipCtx, clearTooltip, canvasRef]+ )++ const onMouseLeave = useCallback(() => {+ if (isPinned) {+ return+ }+ clearTooltip()+ }, [isPinned, clearTooltip])++ const onClick = useCallback(() => {+ const idx = hoverIndexRef.current+ if (idx < 0 || !onSliceClick) {+ return+ }+ const lo = layoutRef.current+ if (!lo) {+ return+ }+ const slice = lo.slices[idx]+ if (!slice) {+ return+ }+ onSliceClick({+ sliceIndex: idx,+ series: slice.series,+ value: slice.value,+ fraction: slice.fraction,+ })+ }, [hoverIndexRef, layoutRef, onSliceClick])++ const handlers = useMemo(() => ({ onMouseMove, onMouseLeave, onClick }), [onMouseMove, onMouseLeave, onClick])++ return { hoverIndex, hoverPosition, tooltipCtx, handlers }+}diff --git a/frontend/src/lib/hog-charts/core/hooks/useTooltipLifecycle.test.ts b/frontend/src/lib/hog-charts/core/hooks/useTooltipLifecycle.test.tsnew file mode 100644index 000000000000..bd004fcce9a5--- /dev/null+++ b/frontend/src/lib/hog-charts/core/hooks/useTooltipLifecycle.test.ts@@ -0,0 +1,392 @@+import { renderHook, type RenderHookResult } from '@testing-library/react'+import { act } from 'react'++import type { TooltipContext } from '../types'+import { isTooltipContextEquivalent, useTooltipLifecycle } from './useTooltipLifecycle'++interface Meta {+ id: number+}++const FAKE_CANVAS_BOUNDS = {+ x: 0,+ y: 0,+ width: 800,+ height: 400,+ top: 0,+ right: 800,+ bottom: 400,+ left: 0,+ toJSON: () => ({}),+} as DOMRect++function makeCtx(overrides: Partial<TooltipContext<Meta>> = {}): TooltipContext<Meta> {+ return {+ dataIndex: 1,+ label: 'Tue',+ seriesData: [+ { series: { key: 'a', label: 'A', data: [1, 2, 3], meta: { id: 1 } }, value: 20, color: '#f00' },+ { series: { key: 'b', label: 'B', data: [5, 6, 7], meta: { id: 2 } }, value: 6, color: '#0f0' },+ ],+ position: { x: 100, y: 50 },+ hoverPosition: { x: 100, y: 50 },+ canvasBounds: FAKE_CANVAS_BOUNDS,+ isPinned: false,+ ...overrides,+ }+}++function makeRefs(): { wrapperRef: React.RefObject<HTMLDivElement> } {+ const wrapper = document.createElement('div')+ document.body.appendChild(wrapper)+ return { wrapperRef: { current: wrapper } }+}++type LifecycleResult = ReturnType<typeof useTooltipLifecycle<Meta>>++describe('useTooltipLifecycle', () => {+ let refs: { wrapperRef: React.RefObject<HTMLDivElement> }+ let rebuildPinnedCtx: jest.Mock<TooltipContext<Meta> | null, [TooltipContext<Meta>]>++ beforeEach(() => {+ jest.useFakeTimers()+ refs = makeRefs()+ // Default rebuild keeps the prev context. Tests override per-case.+ rebuildPinnedCtx = jest.fn((prev: TooltipContext<Meta>) => prev)+ })++ afterEach(() => {+ jest.useRealTimers()+ if (refs.wrapperRef.current) {+ document.body.removeChild(refs.wrapperRef.current)+ }+ })++ function renderLifecycle(+ rebuildDeps: React.DependencyList = []+ ): RenderHookResult<LifecycleResult, { rebuildDeps: React.DependencyList }> {+ return renderHook(+ ({ rebuildDeps }) =>+ useTooltipLifecycle<Meta>({+ wrapperRef: refs.wrapperRef,+ rebuildPinnedCtx,+ rebuildDeps,+ }),+ { initialProps: { rebuildDeps } }+ )+ }++ function publishHoverCtx(result: { current: LifecycleResult }, ctx: TooltipContext<Meta> = makeCtx()): void {+ act(() => {+ result.current.setHover(ctx.dataIndex, ctx.hoverPosition)+ result.current.setTooltipCtx(ctx)+ })+ }++ function pinFromHover(result: { current: LifecycleResult }, ctx: TooltipContext<Meta> = makeCtx()): void {+ publishHoverCtx(result, ctx)+ act(() => {+ result.current.pin()+ })+ expect(result.current.isPinned).toBe(true)+ }++ it('starts empty', () => {+ const { result } = renderLifecycle()+ expect(result.current.tooltipCtx).toBeNull()+ expect(result.current.hoverIndex).toBe(-1)+ expect(result.current.hoverPosition).toBeNull()+ expect(result.current.isPinned).toBe(false)+ })++ it('publishes a hover tooltip via setHover + setTooltipCtx', () => {+ const { result } = renderLifecycle()+ publishHoverCtx(result)+ expect(result.current.tooltipCtx).not.toBeNull()+ expect(result.current.tooltipCtx!.isPinned).toBe(false)+ expect(result.current.hoverIndex).toBe(1)+ expect(result.current.hoverPosition).toEqual({ x: 100, y: 50 })+ })++ it('promotes hover ctx to pinned via pin()', () => {+ const { result } = renderLifecycle()+ pinFromHover(result)+ expect(result.current.tooltipCtx).not.toBeNull()+ expect(result.current.tooltipCtx!.onUnpin).toBeInstanceOf(Function)+ })++ it('pin() is a no-op when there is no current ctx', () => {+ const { result } = renderLifecycle()+ act(() => {+ result.current.pin()+ })+ expect(result.current.tooltipCtx).toBeNull()+ expect(result.current.isPinned).toBe(false)+ })++ it('unpin() drops only the pin, leaving hover state intact', () => {+ const { result } = renderLifecycle()+ pinFromHover(result)++ act(() => {+ result.current.unpin()+ })++ expect(result.current.tooltipCtx).toBeNull()+ expect(result.current.hoverIndex).toBe(1)+ expect(result.current.hoverPosition).toEqual({ x: 100, y: 50 })+ })++ it('clearTooltip() clears tooltip + hover state', () => {+ const { result } = renderLifecycle()+ pinFromHover(result)++ act(() => {+ result.current.clearTooltip()+ })++ expect(result.current.tooltipCtx).toBeNull()+ expect(result.current.hoverIndex).toBe(-1)+ expect(result.current.hoverPosition).toBeNull()+ })++ it.each<[string, () => void]>([+ ['Escape key', () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))],+ [+ 'scroll outside the chart wrapper',+ () => {+ const outside = document.createElement('div')+ document.body.appendChild(outside)+ outside.dispatchEvent(new Event('scroll', { bubbles: true }))+ document.body.removeChild(outside)+ },+ ],+ [+ 'click outside',+ () => {+ jest.runAllTimers()+ document.body.dispatchEvent(new MouseEvent('click', { bubbles: true }))+ },+ ],+ ])('clears pinned tooltip on %s', (_name, trigger) => {+ const { result } = renderLifecycle()+ pinFromHover(result)++ act(() => {+ trigger()+ })++ expect(result.current.tooltipCtx).toBeNull()+ })++ it('does not clear pinned tooltip on non-Escape key', () => {+ const { result } = renderLifecycle()+ pinFromHover(result)++ act(() => {+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }))+ })++ expect(result.current.tooltipCtx).not.toBeNull()+ expect(result.current.tooltipCtx!.isPinned).toBe(true)+ })++ it('does not clear pinned tooltip on click inside the wrapper', () => {+ const { result } = renderLifecycle()+ pinFromHover(result)+ act(() => {+ jest.runAllTimers()+ })++ act(() => {+ refs.wrapperRef.current!.dispatchEvent(new MouseEvent('click', { bubbles: true }))+ })++ expect(result.current.tooltipCtx).not.toBeNull()+ expect(result.current.tooltipCtx!.isPinned).toBe(true)+ })++ it('does not clear pinned tooltip on scroll inside the tooltip element', () => {+ const { result } = renderLifecycle()+ pinFromHover(result)++ // Scrollable child of an element bearing the tooltip marker (the Tooltip overlay portals+ // outside the wrapper but tags itself with data-hog-charts-tooltip).+ const tooltipEl = document.createElement('div')+ tooltipEl.setAttribute('data-hog-charts-tooltip', '')+ const scrollableChild = document.createElement('div')+ tooltipEl.appendChild(scrollableChild)+ document.body.appendChild(tooltipEl)++ act(() => {+ scrollableChild.dispatchEvent(new Event('scroll', { bubbles: true }))+ })++ expect(result.current.tooltipCtx).not.toBeNull()+ expect(result.current.tooltipCtx!.isPinned).toBe(true)+ document.body.removeChild(tooltipEl)+ })++ it('does not clear pinned tooltip on scroll inside the chart wrapper', () => {+ const { result } = renderLifecycle()+ pinFromHover(result)++ const inner = document.createElement('div')+ refs.wrapperRef.current!.appendChild(inner)++ act(() => {+ inner.dispatchEvent(new Event('scroll', { bubbles: true }))+ })++ expect(result.current.tooltipCtx).not.toBeNull()+ expect(result.current.tooltipCtx!.isPinned).toBe(true)+ })++ it('clears unpinned tooltip on scroll outside the wrapper', () => {+ const { result } = renderLifecycle()+ publishHoverCtx(result)++ const outside = document.createElement('div')+ document.body.appendChild(outside)+ act(() => {+ outside.dispatchEvent(new Event('scroll', { bubbles: true }))+ })+ document.body.removeChild(outside)++ expect(result.current.tooltipCtx).toBeNull()+ })++ it('rebuilds the pinned tooltip when rebuildDeps change', () => {+ // Rebuild returns a fresh ctx with a different value so the equivalence bail doesn't kick in.+ const updated = makeCtx({+ seriesData: [+ { series: { key: 'a', label: 'A', data: [999, 999, 999], meta: { id: 1 } }, value: 999, color: '#f00' },+ { series: { key: 'b', label: 'B', data: [777, 777, 777], meta: { id: 2 } }, value: 777, color: '#0f0' },+ ],+ })+ rebuildPinnedCtx.mockImplementation(() => updated)++ const { result, rerender } = renderLifecycle([1])+ pinFromHover(result)++ const before = result.current.tooltipCtx+ expect(before).not.toBeNull()+ expect(before!.seriesData[0].value).toBe(20)++ rerender({ rebuildDeps: [2] })++ expect(rebuildPinnedCtx).toHaveBeenCalled()+ expect(result.current.tooltipCtx).not.toBeNull()+ expect(result.current.tooltipCtx!.isPinned).toBe(true)+ expect(result.current.tooltipCtx!.seriesData[0].value).toBe(999)+ })++ it('clears the pin when rebuildPinnedCtx returns null (data point gone)', () => {+ rebuildPinnedCtx.mockImplementation(() => null)+ const { result, rerender } = renderLifecycle([1])+ pinFromHover(result)++ rerender({ rebuildDeps: [2] })++ expect(result.current.tooltipCtx).toBeNull()+ })++ it('keeps the same tooltipCtx reference when the rebuild is value-equal (equivalence bail)', () => {+ // Return a clone with new identity but identical values.+ rebuildPinnedCtx.mockImplementation((prev) => ({ ...prev, seriesData: prev.seriesData.map((d) => ({ ...d })) }))+ const { result, rerender } = renderLifecycle([1])+ pinFromHover(result)++ const before = result.current.tooltipCtx+ rerender({ rebuildDeps: [2] })++ expect(result.current.tooltipCtx).toBe(before)+ })++ it('does not call rebuildPinnedCtx when not pinned', () => {+ const { result, rerender } = renderLifecycle([1])+ publishHoverCtx(result)+ rebuildPinnedCtx.mockClear()++ rerender({ rebuildDeps: [2] })++ expect(rebuildPinnedCtx).not.toHaveBeenCalled()+ })++ it('exposes onUnpin on the pinned ctx and the callback drops the pin', () => {+ const { result } = renderLifecycle()+ pinFromHover(result)+ expect(result.current.tooltipCtx).not.toBeNull()+ const onUnpin = result.current.tooltipCtx!.onUnpin+ expect(onUnpin).toBeInstanceOf(Function)++ act(() => {+ onUnpin!()+ })++ expect(result.current.tooltipCtx).toBeNull()+ // hover state untouched+ expect(result.current.hoverIndex).toBe(1)+ })+})++describe('isTooltipContextEquivalent', () => {+ const base = (): TooltipContext<Meta> => ({+ dataIndex: 1,+ label: 'Tue',+ seriesData: [+ { series: { key: 'a', label: 'A', data: [1, 2, 3] }, value: 20, color: '#f00' },+ { series: { key: 'b', label: 'B', data: [5, 6, 7] }, value: 6, color: '#0f0' },+ ],+ position: { x: 100, y: 50 },+ hoverPosition: { x: 100, y: 50 },+ canvasBounds: FAKE_CANVAS_BOUNDS,+ isPinned: false,+ })++ it.each<[string, (b: TooltipContext<Meta>) => TooltipContext<Meta>, boolean]>([+ ['identical', (b) => ({ ...b, seriesData: b.seriesData.map((d) => ({ ...d })) }), true],+ ['different dataIndex', (b) => ({ ...b, dataIndex: 2 }), false],+ ['different label', (b) => ({ ...b, label: 'Wed' }), false],+ ['different position.x', (b) => ({ ...b, position: { ...b.position, x: 999 } }), false],+ ['different position.y', (b) => ({ ...b, position: { ...b.position, y: 999 } }), false],+ ['different seriesData length', (b) => ({ ...b, seriesData: b.seriesData.slice(0, 1) }), false],+ [+ 'different value',+ (b) => ({+ ...b,+ seriesData: [{ ...b.seriesData[0], value: 999 }, b.seriesData[1]],+ }),+ false,+ ],+ [+ 'different color',+ (b) => ({+ ...b,+ seriesData: [{ ...b.seriesData[0], color: '#abc' }, b.seriesData[1]],+ }),+ false,+ ],+ [+ 'different series.label (same key)',+ (b) => ({+ ...b,+ seriesData: [+ { ...b.seriesData[0], series: { ...b.seriesData[0].series, label: 'A!' } },+ b.seriesData[1],+ ],+ }),+ false,+ ],+ [+ 'same key, new series identity, same values',+ (b) => ({+ ...b,+ seriesData: b.seriesData.map((d) => ({ ...d, series: { ...d.series } })),+ }),+ true,+ ],+ ])('%s -> %s', (_name, mutate, expected) => {+ expect(isTooltipContextEquivalent(base(), mutate(base()))).toBe(expected)+ })+})diff --git a/frontend/src/lib/hog-charts/core/hooks/useTooltipLifecycle.ts b/frontend/src/lib/hog-charts/core/hooks/useTooltipLifecycle.tsnew file mode 100644index 000000000000..c55581360b77--- /dev/null+++ b/frontend/src/lib/hog-charts/core/hooks/useTooltipLifecycle.ts@@ -0,0 +1,204 @@+import React, { useCallback, useEffect, useState } from 'react'++import type { TooltipContext } from '../types'++/** Value-equality check used by the pinned-rebuild effect to skip no-op updates. Compares+ * dataIndex, label, position, and per-row value/color/series.key/series.label. Series are+ * compared by stable `key` rather than identity because the parent typically rebuilds the+ * resolved-series array on every render. */+export function isTooltipContextEquivalent<Meta>(a: TooltipContext<Meta>, b: TooltipContext<Meta>): boolean {+ if (a.dataIndex !== b.dataIndex || a.label !== b.label) {+ return false+ }+ if (a.position.x !== b.position.x || a.position.y !== b.position.y) {+ return false+ }+ if (a.seriesData.length !== b.seriesData.length) {+ return false+ }+ for (let i = 0; i < a.seriesData.length; i++) {+ const ai = a.seriesData[i]+ const bi = b.seriesData[i]+ if (+ ai.value !== bi.value ||+ ai.color !== bi.color ||+ ai.fraction !== bi.fraction ||+ ai.series.key !== bi.series.key ||+ ai.series.label !== bi.series.label+ ) {+ return false+ }+ }+ return true+}++export interface UseTooltipLifecycleOptions<Meta> {+ wrapperRef: React.RefObject<HTMLDivElement>+ /** Rebuilds the pinned tooltip context when `rebuildDeps` change while a pin is held. Receives+ * the previous pinned context (without `isPinned`/`onUnpin` mutations re-applied — the lifecycle+ * re-pins after the rebuild). Return `null` to drop the pin (e.g. the data point no longer exists). */+ rebuildPinnedCtx: (prev: TooltipContext<Meta>) => TooltipContext<Meta> | null+ /** Inputs that should retrigger a pinned rebuild (typically series, labels, scales, dimensions). */+ rebuildDeps: React.DependencyList+}++export interface UseTooltipLifecycleResult<Meta> {+ hoverIndex: number+ hoverPosition: { x: number; y: number } | null+ tooltipCtx: TooltipContext<Meta> | null+ /** Sets hover index + position together. Geometry hooks call this when the cursor enters/moves over a data point. */+ setHover: (index: number, position: { x: number; y: number } | null) => void+ /** Direct setter for the tooltip context. Geometry hooks use this to publish a freshly-built ctx on mousemove. */+ setTooltipCtx: React.Dispatch<React.SetStateAction<TooltipContext<Meta> | null>>+ isPinned: boolean+ /** Clear everything — hover index, hover position, tooltip context (pinned or not). */+ clearTooltip: () => void+ /** Drop only the pin, leaving hover state intact. Bound to `TooltipContext.onUnpin`. */+ unpin: () => void+ /** Promote the current tooltipCtx to pinned. No-op when there's no current ctx. */+ pin: () => void+}++/** Geometry-independent tooltip state and dismiss lifecycle.+ *+ * Owns: tooltipCtx (and the boolean `isPinned`), hoverIndex/hoverPosition, the three dismiss+ * effects (scroll outside the chart, click outside, Escape), and the pinned-rebuild effect+ * with its value-equivalence bail.+ *+ * Does NOT own: cursor → index hit-testing (cartesian or radial), or anchor positioning. Geometry+ * hooks compute those and call `setHover` + `setTooltipCtx` to publish results, and pass a+ * `rebuildPinnedCtx` callback so the lifecycle can refresh the pin when its inputs change. */+export function useTooltipLifecycle<Meta = unknown>({+ wrapperRef,+ rebuildPinnedCtx,+ rebuildDeps,+}: UseTooltipLifecycleOptions<Meta>): UseTooltipLifecycleResult<Meta> {+ const [hoverIndex, setHoverIndex] = useState<number>(-1)+ const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null)+ const [tooltipCtx, setTooltipCtx] = useState<TooltipContext<Meta> | null>(null)++ const setHover = useCallback((index: number, position: { x: number; y: number } | null) => {+ setHoverIndex(index)+ setHoverPosition(position)+ }, [])++ const clearTooltip = useCallback(() => {+ setHoverIndex(-1)+ setHoverPosition(null)+ setTooltipCtx(null)+ }, [])++ const unpin = useCallback(() => {+ setTooltipCtx((prev) => (prev?.isPinned ? null : prev))+ }, [])++ const isPinned = tooltipCtx?.isPinned ?? false++ const pin = useCallback(() => {+ setTooltipCtx((prev) => (prev && !prev.isPinned ? { ...prev, isPinned: true, onUnpin: unpin } : prev))+ }, [unpin])++ // Rebuild or clear the pinned tooltip when its underlying inputs change. Without this,+ // the pin keeps stale values at stale pixel positions after the parent updates series /+ // labels / scales / dimensions.+ useEffect(() => {+ if (!isPinned) {+ return+ }+ setTooltipCtx((prev) => {+ if (!prev || !prev.isPinned) {+ return prev+ }+ const fresh = rebuildPinnedCtx(prev)+ if (!fresh) {+ return null+ }+ // Skip identity churn when the rebuilt context is value-equal to the previous one.+ if (isTooltipContextEquivalent(prev, fresh)) {+ return prev+ }+ return { ...fresh, isPinned: true, onUnpin: unpin }+ })+ // Omitted on purpose:+ // - isPinned / tooltipCtx — would feedback-loop with setTooltipCtx+ // - unpin — stable for the hook's lifetime (useCallback([]))+ // - rebuildPinnedCtx — read live via the closure; caller is responsible for stability if it+ // wants to avoid extra rebuilds (typically wrapped in useCallback by the geometry hook)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, rebuildDeps)++ // Dismiss the tooltip on scroll — pinned or not — since the anchor moves with the page and+ // a stale tooltip is worse than no tooltip.+ const tooltipShown = tooltipCtx !== null+ useEffect(() => {+ if (!tooltipShown) {+ return+ }+ const handleScroll = (e: Event): void => {+ // Allow scrolling inside the tooltip (long pinned content) or the chart wrapper+ // (a nested legend) without dismissing.+ const target = e.target+ if (target instanceof Element) {+ if (target.closest('[data-hog-charts-tooltip]')) {+ return+ }+ if (wrapperRef.current?.contains(target)) {+ return+ }+ }+ clearTooltip()+ }+ window.addEventListener('scroll', handleScroll, { passive: true, capture: true })+ return () => {+ window.removeEventListener('scroll', handleScroll, true)+ }+ }, [tooltipShown, wrapperRef, clearTooltip])++ // Dismiss listeners for pinned tooltip (click outside, Escape).+ useEffect(() => {+ if (!isPinned) {+ return+ }++ const handleClickOutside = (e: MouseEvent): void => {+ const target = e.target+ if (target instanceof Element && target.closest('[data-hog-charts-tooltip]')) {+ return+ }+ const wrapper = wrapperRef.current+ if (wrapper && !wrapper.contains(target as Node)) {+ clearTooltip()+ }+ }++ const handleKeyDown = (e: KeyboardEvent): void => {+ if (e.key === 'Escape') {+ clearTooltip()+ }+ }++ // Delay click listener so the pinning click doesn't immediately unpin.+ const timer = setTimeout(() => {+ document.addEventListener('click', handleClickOutside, { passive: true })+ }, 0)+ document.addEventListener('keydown', handleKeyDown, { passive: true })++ return () => {+ clearTimeout(timer)+ document.removeEventListener('click', handleClickOutside)+ document.removeEventListener('keydown', handleKeyDown)+ }+ }, [isPinned, wrapperRef, clearTooltip])++ return {+ hoverIndex,+ hoverPosition,+ tooltipCtx,+ setHover,+ setTooltipCtx,+ isPinned,+ clearTooltip,+ unpin,+ pin,+ }+}diff --git a/frontend/src/lib/hog-charts/core/radial-context.ts b/frontend/src/lib/hog-charts/core/radial-context.tsnew file mode 100644index 000000000000..c590a63b14d5--- /dev/null+++ b/frontend/src/lib/hog-charts/core/radial-context.ts@@ -0,0 +1,22 @@+import { createContext, useContext } from 'react'++import type { PieLayout } from '../charts/PieChart/computePieLayout'++/** Layout-stable values exposed to radial overlays (slice labels, custom decorations). Identity+ * does NOT change on hover. */+export interface RadialLayoutContextValue<Meta = unknown> {+ layout: PieLayout<Meta>+ /** Returns the current canvas bounding rect, or null if the canvas is unmounted. */+ canvasBounds: () => DOMRect | null+}++export const RadialLayoutContext = createContext<RadialLayoutContextValue | null>(null)++/** Subscribes to radial layout state. Throws if used outside a `<RadialChart>` / `<PieChart>`. */+export function useRadialLayout<Meta = unknown>(): RadialLayoutContextValue<Meta> {+ const ctx = useContext(RadialLayoutContext)+ if (!ctx) {+ throw new Error('useRadialLayout must be used inside a radial chart component (e.g. <PieChart>)')+ }+ return ctx as RadialLayoutContextValue<Meta>+}diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.tsindex 4eaf25f476e2..1ab6dde7a09b 100644--- a/frontend/src/lib/hog-charts/core/types.ts+++ b/frontend/src/lib/hog-charts/core/types.ts@@ -104,8 +104,9 @@ export interface TooltipContext<Meta = unknown> {dataIndex: number/** The x-axis label at this index. */label: string- /** One entry per visible series with its value and color at this index. */- seriesData: { series: Series<Meta>; value: number; color: string }[]+ /** One entry per visible series with its value and color at this index. `fraction` is set+ * for radial charts (share of total) so renderers don't need to look the slice back up. */+ seriesData: { series: Series<Meta>; value: number; color: string; fraction?: number }[]/** Pixel position (relative to the chart container) for anchoring the tooltip. */position: { x: number; y: number }/** Cursor position in canvas pixels, or `null` for non-mousemove snapshots (e.g. pinned rebuild). */diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.tsindex 6d8c69afdecc..232975ce98cf 100644--- a/frontend/src/lib/hog-charts/index.ts+++ b/frontend/src/lib/hog-charts/index.ts@@ -18,8 +18,23 @@ export type { TimeSeriesBarChartConfig, TimeSeriesBarChartProps } from './charts// Base chart (for building new chart types)export { Chart } from './core/Chart'export type { ChartProps } from './core/Chart'+export { RadialChart, RADIAL_MARGINS } from './core/RadialChart'+export type { RadialChartProps, RadialLayoutBuilder } from './core/RadialChart'export { DEFAULT_MARGINS } from './core/hooks/useChartMargins'+// Pie / donut+export { PieChart } from './charts/PieChart/PieChart'+export type { PieChartConfig, PieChartProps } from './charts/PieChart/PieChart'+export { computePieLayout, cursorOffsetToAngle, sliceAt, defaultSliceValue } from './charts/PieChart/computePieLayout'+export type { PieLayout, PieSlice } from './charts/PieChart/computePieLayout'+export { SliceLabels } from './charts/PieChart/SliceLabels'+export type { SliceLabelsProps } from './charts/PieChart/SliceLabels'+export { PieTooltip } from './charts/PieChart/PieTooltip'+export type { PieTooltipProps } from './charts/PieChart/PieTooltip'+export { useRadialLayout } from './core/radial-context'+export type { RadialLayoutContextValue } from './core/radial-context'+export type { RadialSlicePayload } from './core/hooks/useRadialInteraction'+// Chart context (for custom overlay children)export { useChart, useChartHover, useChartLayout } from './core/chart-context'export type { BaseChartContext, ChartHoverContextValue, ChartLayoutContextValue } from './core/chart-context'diff --git a/frontend/src/lib/hog-charts/story-helpers.tsx b/frontend/src/lib/hog-charts/story-helpers.tsxindex ddd1a54d0487..7ced56cf9b3c 100644--- a/frontend/src/lib/hog-charts/story-helpers.tsx+++ b/frontend/src/lib/hog-charts/story-helpers.tsx@@ -36,7 +36,7 @@ function buildTheme(): ChartTheme {gridColor: readCssVar('color-graph-axis-line'),crosshairColor: readCssVar('color-graph-crosshair'),tooltipBackground: readCssVar('color-bg-surface-tooltip'),- tooltipColor: readCssVar('color-text-primary'),+ tooltipColor: readCssVar('color-text-primary-inverse'),}}@@ -96,17 +96,20 @@ export async function playHoverAtFraction(},{ timeout: 3000 })- const rect = wrapper.getBoundingClientRect()- fireEvent.mouseMove(wrapper, {- clientX: rect.left + rect.width * fraction,- clientY: rect.top + rect.height * yFraction,- })+ // Re-fire mousemove inside the waitFor: the chart's onMouseMove bails until+ // ResizeObserver has populated scales/dimensions, so a single dispatch races+ // the first measurement pass. Re-dispatching is cheap and idempotent.await waitFor(() => {+ const rect = wrapper.getBoundingClientRect()+ fireEvent.mouseMove(wrapper, {+ clientX: rect.left + rect.width * fraction,+ clientY: rect.top + rect.height * yFraction,+ })if (!document.querySelector('[data-hog-charts-tooltip]')) {throw new Error('tooltip not yet rendered')}},- { timeout: 1000 }+ { timeout: 3000 })}diff --git a/frontend/src/scenes/trends/Trends.tsx b/frontend/src/scenes/trends/Trends.tsxindex db4e062d0046..22d850f15cd8 100644--- a/frontend/src/scenes/trends/Trends.tsx+++ b/frontend/src/scenes/trends/Trends.tsx@@ -34,6 +34,11 @@ const TrendsBarChart = lazy(() =>default: m.TrendsBarChart,})))+const TrendsPieChart = lazy(() =>+ import('products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart').then((m) => ({+ default: m.TrendsPieChart,+ }))+)const TrendsLifecycleChart = lazy(() =>import('products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart').then((m) => ({@@ -107,6 +112,11 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode })}if (display === ChartDisplayType.ActionsPie) {+ if (hogChartsTrendsEnabled) {+ return (+ <TrendsPieChart context={context} inSharedMode={inSharedMode} showPersonsModal={showPersonsModal} />+ )+ }return <ActionsPie {...commonProps} />}if (display === ChartDisplayType.ActionsBarValue) {diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsxnew file mode 100644index 000000000000..27666f50ad5f--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx@@ -0,0 +1,254 @@+import { useValues } from 'kea'+import posthog from 'posthog-js'+import { useCallback, useMemo, type ErrorInfo } from 'react'++import { buildTheme } from 'lib/charts/utils/theme'+import { PieChart } from 'lib/hog-charts'+import type { PieChartConfig, RadialSlicePayload, Series, TooltipContext } from 'lib/hog-charts'+import {+ formatAggregationAxisValue,+ formatAggregationAxisValueWithShareOfTotal,+} from 'scenes/insights/aggregationAxisFormat'+import { InsightEmptyState } from 'scenes/insights/EmptyStates'+import { insightLogic } from 'scenes/insights/insightLogic'+import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'+import { formatBreakdownLabel } from 'scenes/insights/utils'+import { teamLogic } from 'scenes/teamLogic'+import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'+import type { IndexedTrendResult } from 'scenes/trends/types'+import { datasetToActorsQuery } from 'scenes/trends/viz/datasetToActorsQuery'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { cohortsModel } from '~/models/cohortsModel'+import { groupsModel } from '~/models/groupsModel'+import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'+import { InsightVizNode } from '~/queries/schema/schema-general'+import { QueryContext } from '~/queries/types'++import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'+import { TrendsTooltip } from '../shared/TrendsTooltip'+import { buildTrendsPieSeries } from './trendsPieTransforms'++interface TrendsPieChartProps {+ context?: QueryContext<InsightVizNode>+ inSharedMode?: boolean+ showPersonsModal?: boolean+}++const handleChartError = (error: Error, info: ErrorInfo): void => {+ posthog.captureException(error, {+ feature: 'trends-pie-chart',+ componentStack: info.componentStack ?? undefined,+ })+}++export function TrendsPieChart({+ context,+ inSharedMode = false,+ showPersonsModal = true,+}: TrendsPieChartProps): JSX.Element | null {+ const { isDarkModeOn } = useValues(themeLogic)+ // isDarkModeOn invalidates the memo so buildTheme() re-reads CSS vars on dark-mode toggle.+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])++ const { insightProps } = useValues(insightLogic)+ const { baseCurrency } = useValues(teamLogic)+ const { allCohorts } = useValues(cohortsModel)+ const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const { aggregationLabel } = useValues(groupsModel)++ const {+ indexedResults,+ trendsFilter,+ formula,+ showValuesOnSeries,+ showLabelOnSeries,+ pieChartVizOptions,+ hasDataWarehouseSeries,+ querySource,+ breakdownFilter,+ labelGroupType,+ getTrendsColor,+ getTrendsHidden,+ } = useValues(trendsDataLogic(insightProps))++ const resolvedGroupTypeLabel =+ context?.groupTypeLabel ??+ (labelGroupType === 'people'+ ? 'people'+ : labelGroupType === 'none'+ ? ''+ : aggregationLabel(labelGroupType).plural)++ const onDataPointClick = context?.onDataPointClick+ const showAggregation = !pieChartVizOptions?.hideAggregation++ const getLabel = useCallback(+ (r: IndexedTrendResult): string =>+ breakdownFilter+ ? formatBreakdownLabel(+ r.breakdown_value,+ breakdownFilter,+ allCohorts.results,+ formatPropertyValueForDisplay+ )+ : (r.label ?? ''),+ [breakdownFilter, allCohorts.results, formatPropertyValueForDisplay]+ )++ const series: Series<TrendsSeriesMeta>[] = useMemo(+ () =>+ buildTrendsPieSeries(indexedResults ?? [], {+ getColor: getTrendsColor,+ getHidden: getTrendsHidden,+ getLabel,+ }),+ [indexedResults, getTrendsColor, getTrendsHidden, getLabel]+ )++ const visibleResults = useMemo(+ () => ((indexedResults ?? []) as IndexedTrendResult[]).filter((r) => !getTrendsHidden(r)),+ [indexedResults, getTrendsHidden]+ )++ const total = useMemo(+ () => visibleResults.reduce((acc: number, r: IndexedTrendResult) => acc + (r.aggregated_value ?? 0), 0),+ [visibleResults]+ )++ const valueFormatter = useCallback(+ (v: number) => formatAggregationAxisValue(trendsFilter, v, baseCurrency),+ [trendsFilter, baseCurrency]+ )++ const pieConfig: PieChartConfig<TrendsSeriesMeta> = useMemo(+ () => ({+ showValueOnSlice: !!showValuesOnSeries,+ showLabelOnSlice: !!showLabelOnSeries,+ disableHoverOffset: !!pieChartVizOptions?.disableHoverOffset,+ }),+ [showValuesOnSeries, showLabelOnSeries, pieChartVizOptions?.disableHoverOffset]+ )++ // ActionsPie disables clicks entirely when the insight has data-warehouse series (see+ // ActionsPie.tsx — `onClick={hasDataWarehouseSeries ? undefined : onClick}`); match that here.+ const canHandleClick = !hasDataWarehouseSeries && (!!onDataPointClick || (showPersonsModal && !formula))++ // Click parity with ActionsPie. The legacy path builds an InsightActorsQuery from the+ // GraphDataset.breakdownValues array; here each slice is already a single result, so we+ // pull its breakdown/compare straight from the IndexedTrendResult.+ const handleSliceClick = useCallback(+ (seriesKey: string, label: string | undefined) => {+ const result = visibleResults.find((r: IndexedTrendResult) => String(r.id) === seriesKey)+ if (!result) {+ return+ }+ if (onDataPointClick) {+ onDataPointClick(+ {+ breakdown: result.breakdown_value,+ compare: result.compare_label || undefined,+ },+ // Legacy parity with ActionsPie — passes the first result, not the clicked one.+ (indexedResults ?? [])[0]+ )+ return+ }+ if (!showPersonsModal || formula || hasDataWarehouseSeries || !querySource) {+ return+ }+ openPersonsModal({+ title: label || '',+ query: datasetToActorsQuery({+ dataset: {+ action: result.action,+ breakdown_value: result.breakdown_value,+ compare_label: result.compare_label,+ },+ query: querySource,+ }),+ additionalSelect: {+ value_at_data_point: 'event_count',+ matched_recordings: 'matched_recordings',+ },+ orderBy: ['event_count DESC, actor_id DESC'],+ })+ },+ [+ visibleResults,+ indexedResults,+ onDataPointClick,+ showPersonsModal,+ formula,+ hasDataWarehouseSeries,+ querySource,+ ]+ )++ const onSliceClick = useCallback(+ (payload: RadialSlicePayload<TrendsSeriesMeta>) => handleSliceClick(payload.series.key, payload.series.label),+ [handleSliceClick]+ )++ const renderCount = useCallback(+ (value: number) => formatAggregationAxisValueWithShareOfTotal(trendsFilter, value, total, baseCurrency),+ [trendsFilter, total, baseCurrency]+ )++ const onRowClick = useMemo(+ () => (canHandleClick ? (datum: SeriesDatum) => handleSliceClick(String(datum.id), datum.label) : undefined),+ [canHandleClick, handleSliceClick]+ )++ const renderTooltip = useCallback(+ (ctx: TooltipContext<TrendsSeriesMeta>) => (+ <TrendsTooltip+ context={ctx}+ breakdownFilter={breakdownFilter ?? undefined}+ trendsFilter={trendsFilter}+ formula={formula}+ baseCurrency={baseCurrency}+ groupTypeLabel={resolvedGroupTypeLabel}+ formatCompareLabel={context?.formatCompareLabel}+ onRowClick={onRowClick}+ showHeader={false}+ renderCount={renderCount}+ />+ ),+ [+ breakdownFilter,+ trendsFilter,+ formula,+ baseCurrency,+ resolvedGroupTypeLabel,+ context?.formatCompareLabel,+ onRowClick,+ renderCount,+ ]+ )++ if (!visibleResults.length) {+ return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />+ }++ return (+ <div className={`flex flex-col w-full h-full ${inSharedMode ? 'ActionsPie--shared' : 'ActionsPie'}`}>+ <PieChart<TrendsSeriesMeta>+ series={series}+ theme={theme}+ config={pieConfig}+ tooltip={renderTooltip}+ onSliceClick={canHandleClick ? onSliceClick : undefined}+ valueFormatter={valueFormatter}+ dataAttr="trend-pie-graph"+ onError={handleChartError}+ />+ {showAggregation && (+ <div className="text-7xl text-center font-bold m-0">+ {formatAggregationAxisValue(trendsFilter, total, baseCurrency)}+ </div>+ )}+ </div>+ )+}diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.ts b/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.tsnew file mode 100644index 000000000000..a6d28ebfa825--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.ts@@ -0,0 +1,92 @@+import type { IndexedTrendResult } from 'scenes/trends/types'+import { datasetToActorsQuery } from 'scenes/trends/viz/datasetToActorsQuery'++import type { InsightActorsQuery } from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'+import type { ActionFilter, GraphDataset } from '~/types'++/** Verifies that the hog-charts TrendsPieChart click handler builds the same `InsightActorsQuery`+ * as the legacy ActionsPie. Both call `datasetToActorsQuery` — ActionsPie passes a `GraphDataset`+ * whose `breakdownValues` / `compareLabels` arrays carry one entry per slice plus the slice+ * `index`, while the hog-charts path passes a one-slice dataset assembled from the source+ * `IndexedTrendResult` (no `index` needed because the breakdown is already singular).+ * This test pins that the resulting query objects are deeply equal across both call shapes. */+describe('persons modal parity between ActionsPie and TrendsPieChart', () => {+ const querySource: InsightActorsQuery['source'] = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ dateRange: { date_from: '-7d' },+ } as unknown as InsightActorsQuery['source']++ const action: ActionFilter = { id: 99, math: 'total', order: 2 } as unknown as ActionFilter++ const indexedResults: IndexedTrendResult[] = [+ {+ id: 0,+ seriesIndex: 0,+ colorIndex: 0,+ label: 'Chrome',+ aggregated_value: 100,+ data: [100],+ days: [],+ labels: [],+ count: 100,+ action,+ breakdown_value: 'chrome',+ compare_label: 'current',+ } as IndexedTrendResult,+ {+ id: 1,+ seriesIndex: 1,+ colorIndex: 1,+ label: 'Safari',+ aggregated_value: 50,+ data: [50],+ days: [],+ labels: [],+ count: 50,+ action,+ breakdown_value: 'safari',+ compare_label: 'current',+ } as IndexedTrendResult,+ ]++ // Build the input ActionsPie passes to datasetToActorsQuery.+ function legacyActionsPieDataset(): Pick<+ GraphDataset,+ 'action' | 'breakdownValues' | 'compareLabels' | 'breakdown_value' | 'compare_label'+ > {+ return {+ action,+ breakdownValues: indexedResults.map((r) => r.breakdown_value),+ compareLabels: indexedResults.map((r) => r.compare_label),+ }+ }++ // Build the input the hog-charts TrendsPieChart passes to datasetToActorsQuery — single slice.+ function newPieDatasetForSlice(+ slice: IndexedTrendResult+ ): Pick<GraphDataset, 'action' | 'breakdown_value' | 'compare_label'> {+ return {+ action: slice.action,+ breakdown_value: slice.breakdown_value,+ compare_label: slice.compare_label,+ }+ }++ it.each<[number, IndexedTrendResult]>([+ [0, indexedResults[0]],+ [1, indexedResults[1]],+ ])('produces an identical query for slice %i', (sliceIndex, slice) => {+ const legacyQuery = datasetToActorsQuery({+ dataset: legacyActionsPieDataset(),+ query: querySource,+ index: sliceIndex,+ })+ const newQuery = datasetToActorsQuery({+ dataset: newPieDatasetForSlice(slice),+ query: querySource,+ })+ expect(newQuery).toEqual(legacyQuery)+ })+})diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.test.tsnew file mode 100644index 000000000000..c0a00185f778--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.test.ts@@ -0,0 +1,96 @@+import type { IndexedTrendResult } from 'scenes/trends/types'++import { buildTrendsPieSeries } from './trendsPieTransforms'++function makeResult(overrides: Partial<IndexedTrendResult> = {}): IndexedTrendResult {+ return {+ id: 0,+ seriesIndex: 0,+ colorIndex: 0,+ label: 'Default',+ aggregated_value: 0,+ data: [],+ days: [],+ labels: [],+ count: 0,+ action: undefined,+ breakdown_value: undefined,+ compare_label: undefined,+ ...overrides,+ } as IndexedTrendResult+}++describe('buildTrendsPieSeries', () => {+ const getColor = (_: IndexedTrendResult, i: number): string => ['#001', '#002', '#003'][i] ?? '#fff'++ it('maps one slice per IndexedTrendResult with aggregated_value as the slice magnitude', () => {+ const results = [+ makeResult({ id: 0, label: 'A', aggregated_value: 10 }),+ makeResult({ id: 1, label: 'B', aggregated_value: 30 }),+ makeResult({ id: 2, label: 'C', aggregated_value: 60 }),+ ]+ const series = buildTrendsPieSeries(results, { getColor })++ expect(series).toHaveLength(3)+ expect(series.map((s) => s.key)).toEqual(['0', '1', '2'])+ expect(series.map((s) => s.label)).toEqual(['A', 'B', 'C'])+ expect(series.map((s) => s.data)).toEqual([[10], [30], [60]])+ })++ it('assigns colors via getColor', () => {+ const results = [makeResult({ id: 0 }), makeResult({ id: 1 }), makeResult({ id: 2 })]+ const series = buildTrendsPieSeries(results, { getColor })+ expect(series.map((s) => s.color)).toEqual(['#001', '#002', '#003'])+ })++ it('marks hidden series as visibility.excluded', () => {+ const results = [makeResult({ id: 0 }), makeResult({ id: 1 }), makeResult({ id: 2 })]+ const series = buildTrendsPieSeries(results, {+ getColor,+ getHidden: (_, i) => i === 1,+ })+ expect(series.map((s) => s.visibility?.excluded === true)).toEqual([false, true, false])+ })++ it('uses getLabel to format breakdown labels when provided', () => {+ const results = [+ makeResult({ id: 0, label: 'raw-a', breakdown_value: 'a' }),+ makeResult({ id: 1, label: 'raw-b', breakdown_value: 'b' }),+ ]+ const series = buildTrendsPieSeries(results, {+ getColor,+ getLabel: (r) => `Breakdown: ${r.breakdown_value}`,+ })+ expect(series.map((s) => s.label)).toEqual(['Breakdown: a', 'Breakdown: b'])+ })++ it('falls back to label when getLabel is omitted', () => {+ const results = [makeResult({ id: 0, label: 'fallback' })]+ const series = buildTrendsPieSeries(results, { getColor })+ expect(series[0].label).toBe('fallback')+ })++ it('clamps missing aggregated_value to 0', () => {+ // aggregated_value is required by the type, but we want to be defensive against partial data.+ const results = [makeResult({ id: 0, label: 'A', aggregated_value: undefined as unknown as number })]+ const series = buildTrendsPieSeries(results, { getColor })+ expect(series[0].data).toEqual([0])+ })++ it('carries action / breakdown_value / compare_label through TrendsSeriesMeta', () => {+ const action = { id: 7, order: 3 } as unknown as IndexedTrendResult['action']+ const results = [+ makeResult({+ id: 0,+ label: 'A',+ action,+ breakdown_value: 'chrome',+ days: ['2024-01-01'],+ }),+ ]+ const series = buildTrendsPieSeries(results, { getColor })+ expect(series[0].meta?.action).toBe(action)+ expect(series[0].meta?.breakdown_value).toBe('chrome')+ expect(series[0].meta?.days).toEqual(['2024-01-01'])+ })+})diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.tsnew file mode 100644index 000000000000..f3eba6d35ada--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts@@ -0,0 +1,47 @@+import type { Series } from 'lib/hog-charts'+import type { IndexedTrendResult } from 'scenes/trends/types'++import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'++export interface BuildTrendsPieSeriesOpts<R> {+ /** Resolved color per result (typically `getTrendsColor`). */+ getColor: (r: R, index: number) => string+ /** True when the result should be excluded from rendering. */+ getHidden?: (r: R, index: number) => boolean+ /** Optional label override per result — used to format breakdown values. */+ getLabel?: (r: R, index: number) => string+}++/** Maps the kea-side `IndexedTrendResult` list to hog-charts `Series<TrendsSeriesMeta>[]`,+ * one slice per result. The pie chart consumes each series's first `data` entry as the slice+ * magnitude via the default `sliceValue` resolver — see `PieChart`'s `sliceValue` config to+ * override when the input data isn't already aggregated to a single value (the Trends adapter+ * hits this path because `aggregated_value` is stored as `data[0]`). */+export function buildTrendsPieSeries<R extends IndexedTrendResult>(+ results: R[],+ opts: BuildTrendsPieSeriesOpts<R>+): Series<TrendsSeriesMeta>[] {+ return results.map((r, index) => {+ const excluded = opts.getHidden ? opts.getHidden(r, index) : false+ const label = opts.getLabel ? opts.getLabel(r, index) : (r.label ?? '')+ return {+ // Match the line/bar adapters — keying by `${r.id}` lets the click handler resolve+ // back to the source IndexedTrendResult without stashing it on meta.+ key: String(r.id),+ label,+ // Pie consumes `data[0]` as the magnitude (`aggregated_value` is the only numeric+ // value Trends carries for pie). Wrapped in an array because `Series.data` is a list.+ data: [r.aggregated_value ?? 0],+ color: opts.getColor(r, index),+ meta: {+ action: r.action,+ breakdown_value: r.breakdown_value,+ compare_label: r.compare_label,+ days: r.days,+ order: r.action?.order ?? r.id,+ filter: r.filter,+ },+ visibility: excluded ? { excluded: true } : undefined,+ }+ })+}diff --git a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsxindex 19e313600ba6..03ec28ee4a83 100644--- a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx@@ -28,6 +28,9 @@ interface TrendsTooltipProps {formatCompareLabel?: (label: string, dateLabel?: string) => stringonRowClick?: (datum: SeriesDatum) => voidshowHeader?: boolean+ /** Overrides the default value formatter — needed for the pie chart, which renders the+ * raw aggregation plus the slice's share of the total. */+ renderCount?: (value: number) => string// Overrides the default SeriesLetter + InsightLabel row renderer. Mirrors the// legacy ActionsLineGraph escape hatch used for lifecycle, where the label// is the lifecycle status itself (e.g. "New") and InsightLabel's action.name@@ -53,6 +56,7 @@ export function TrendsTooltip({formatCompareLabel,onRowClick,showHeader,+ renderCount: renderCountOverride,renderSeriesOverride,}: TrendsTooltipProps): React.ReactElement {const seriesData = useMemo<SeriesDatum[]>(@@ -81,6 +85,9 @@ export function TrendsTooltip({const renderCount = useCallback((value: number): string => {+ if (renderCountOverride) {+ return renderCountOverride(value)+ }if (showPercentView) {// Stickiness percent view: value is already a percentage.return `${value.toFixed(1)}%`@@ -90,7 +97,7 @@ export function TrendsTooltip({}return formatPercentStackAxisValue(trendsFilter, value, isPercentStackView, baseCurrency)},- [showPercentView, isPercentStackView, trendsFilter, baseCurrency]+ [renderCountOverride, showPercentView, isPercentStackView, trendsFilter, baseCurrency])const hasMultipleSeries = seriesData.length > 1