: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(billing): render the billing line graph with quill charts (#77178)
Sam Pennington5ce37d37e901
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 920d3a9bda57..6ed820a629d9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7506,6 +7506,14 @@ snapshots:hash: v1.k794b7964.aabe99692a6a19e22aacc0cad741a2b20cc97e4a6561b9ff6813d8e51f4f77aa.qIcBPh1akofg3x6zWnlFcCCeKTUDIGR4WKYPL0aMvaMscenes-other-billing--billing-without-icon-keys--light:hash: v1.k794b7964.6cb8c47887a0fa3fd3f81379090febcc05c3be3610cde5873d507766c595c191.YbRefpyPdf31OQpgZ1GTQTwADlF14qzTEzsk3uGAXNo+ scenes-other-billing-billinglinegraph--with-billing-period-marker--dark:+ hash: v1.k794b7964.659ef2a9028cee6b7cce11fb4e474ec2150c73517c90bd58b2f52188a438f2d6.l9cj9-MUsCDWVTb3L3gnWa00mdyg6rS2skRWbP92TGY+ scenes-other-billing-billinglinegraph--with-billing-period-marker--light:+ hash: v1.k794b7964.39589e33115d9b6e977d464c2656b0fc2e132017c469f1ad31c2c13cd12c2260.-YE5Bgc3uP4iB9JuUSvQEmgzwDjNWImvSqJg1YgVLuw+ scenes-other-billing-billinglinegraph--with-marker-at-range-start--dark:+ hash: v1.k794b7964.5bcd95a5b7d58b483401ea42f0762bc1894ac406beebf5c8b45b89304b908ce9.Ox9Cw0TvU8tIvrVTgeAC92FRtCGjTaLnVOx8S9nRzCA+ scenes-other-billing-billinglinegraph--with-marker-at-range-start--light:+ hash: v1.k794b7964.5948fea6ef855d327f6d59f1ed10eb3fd55808540eda078bee5fed552523a4c0.FTXekbDFuL1YE5ad9VyyBtq5lOBiNalah41lHdISQOEscenes-other-billing-product--billing-product-inclusion-only-with-addon--dark:hash: v1.k794b7964.ce05ab37980f7fc148ea8681fee7b0eeb1f046266e8a7df22fbfc5cc8cefb8e7.hjk8pf9SicO_kBVjVXooUrPaBUj_76AzOPVXuwydGkEscenes-other-billing-product--billing-product-inclusion-only-with-addon--light:diff --git a/frontend/src/scenes/billing/BillingDataTable.tsx b/frontend/src/scenes/billing/BillingDataTable.tsxindex c49cf585a83d..73867e82944f 100644--- a/frontend/src/scenes/billing/BillingDataTable.tsx+++ b/frontend/src/scenes/billing/BillingDataTable.tsx@@ -5,7 +5,11 @@ import { LemonCheckbox, LemonTable, LemonTableColumn, LemonTableColumns } from 'import { getSeriesColor } from 'lib/colors'import { dayjs } from 'lib/dayjs'-import { BillingSeriesType, SeriesColorDot } from './BillingLineGraph'+import { BillingSeriesType } from './BillingLineGraph'++export function SeriesColorDot({ colorIndex }: { colorIndex: number }): JSX.Element {+ return <div className={`series-color-dot series-color-dot-${colorIndex % 15}`} />+}export interface BillingDataTableProps {series: BillingSeriesType[]diff --git a/frontend/src/scenes/billing/BillingLineGraph.scss b/frontend/src/scenes/billing/BillingLineGraph.scssdeleted file mode 100644index 808a16a243d0..000000000000--- a/frontend/src/scenes/billing/BillingLineGraph.scss+++ /dev/null@@ -1,34 +0,0 @@-.BillingMarkersOverlay {- position: absolute;- top: var(--billing-markers-chart-area-top);- left: var(--billing-markers-chart-area-left);- pointer-events: none;-}--.BillingMarker {- position: absolute;- top: -20px;- left: var(--billing-marker-left);- pointer-events: auto;- cursor: default;- transform: translateX(-50%);-- .BillingMarkerLabel {- display: flex;- gap: 4px;- align-items: center;- padding: 4px 8px;- font-size: 12px;- font-weight: normal;- color: var(--billing-marker-text-color);- white-space: nowrap;- background-color: var(--billing-marker-bg-color);- border: 1px solid var(--billing-marker-border-color);- border-radius: 4px;-- .anticon {- width: 12px;- height: 12px;- }- }-}diff --git a/frontend/src/scenes/billing/BillingLineGraph.stories.tsx b/frontend/src/scenes/billing/BillingLineGraph.stories.tsxnew file mode 100644index 000000000000..39ac5d0efba5--- /dev/null+++ b/frontend/src/scenes/billing/BillingLineGraph.stories.tsx@@ -0,0 +1,56 @@+import { Meta, StoryObj } from '@storybook/react'++import { dayjs } from 'lib/dayjs'++import { BillingLineGraph, type BillingSeriesType } from './BillingLineGraph'++const DATES = Array.from({ length: 30 }, (_, i) => dayjs.utc('2024-02-15').add(i, 'day').format('YYYY-MM-DD'))++const seriesFrom = (id: number, label: string, base: number, amplitude: number): BillingSeriesType => ({+ id,+ label,+ dates: DATES,+ // Deterministic wave so the story stays screenshot-stable.+ data: DATES.map((_, i) => Math.round(base + amplitude * Math.sin(i / 3))),+})++const SERIES: BillingSeriesType[] = [+ seriesFrom(0, 'Product analytics', 1_200_000, 400_000),+ seriesFrom(1, 'Session replay', 480_000, 120_000),+ seriesFrom(2, 'Feature flags', 90_000, 30_000),+]++const meta: Meta<typeof BillingLineGraph> = {+ title: 'Scenes-Other/Billing/BillingLineGraph',+ component: BillingLineGraph,+ parameters: { layout: 'padded' },+ // The chart sizes itself from its container via ResizeObserver, so the wrapper needs a definite+ // width — the snapshot runtime shrink-wraps the story root, which squeezes the plot to a few+ // hundred pixels and drops most of the x-axis ticks.+ decorators: [+ (Story) => (+ <div className="w-[960px]">+ <Story />+ </div>+ ),+ ],+ // `showLegend: false` mirrors both callers (BillingUsage, BillingSpendView). Left at the+ // component default these snapshots would guard a legend the app never renders.+ args: { series: SERIES, dates: DATES, hiddenSeries: [], showLegend: false },+}+export default meta++type Story = StoryObj<typeof BillingLineGraph>++/**+ * Only two stories, both with a marker: a screenshot's one advantage over BillingLineGraph.test.tsx+ * is showing whether the label clears the plot and survives the wrapper's `overflow: hidden`.+ */+export const WithBillingPeriodMarker: Story = {+ args: { billingPeriodMarkers: [{ date: dayjs.utc('2024-03-01') }] },+}++/** A period starting on the first plotted bucket, where the label overhangs the y-axis edge. */+export const WithMarkerAtRangeStart: Story = {+ args: { billingPeriodMarkers: [{ date: dayjs.utc(DATES[0]) }] },+}diff --git a/frontend/src/scenes/billing/BillingLineGraph.test.tsx b/frontend/src/scenes/billing/BillingLineGraph.test.tsxnew file mode 100644index 000000000000..2eb03d0e8ef0--- /dev/null+++ b/frontend/src/scenes/billing/BillingLineGraph.test.tsx@@ -0,0 +1,152 @@+import { cleanup, render, screen, waitFor } from '@testing-library/react'++import {+ createDefaultTooltipAccessor,+ ensureJsdom,+ getHogChart,+ hoverUntilTooltip,+} from '@posthog/quill-charts/testing'++import { dayjs } from 'lib/dayjs'++import { initKeaTests } from '~/test/init'++import { BillingLineGraph, type BillingSeriesType } from './BillingLineGraph'++// jsdom has no CSS custom properties, so the real `getSeriesColor` resolves every index to the+// same fallback color — masking a regression where colouring switches from series id to position.+// Mock only that function (keeping the rest of the module, e.g. the theme's graph colors) to+// distinct, valid CSS colors so the two are distinguishable in this test.+jest.mock('lib/colors', () => ({+ ...jest.requireActual('lib/colors'),+ getSeriesColor: (index: number) => ['#ff0000', '#0000ff'][index],+}))++const DATES = ['2026-01-01', '2026-01-02', '2026-01-03']++const SERIES: BillingSeriesType[] = [+ { id: 0, label: 'Events', data: [10, 20, 30], dates: DATES },+ { id: 1, label: 'Recordings', data: [1, 2, 3], dates: DATES },+]++describe('BillingLineGraph', () => {+ beforeEach(() => {+ ensureJsdom()+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ it('renders only the series that are not hidden', async () => {+ render(<BillingLineGraph series={SERIES} dates={DATES} hiddenSeries={[1]} />)++ await waitFor(() => expect(getHogChart().seriesCount).toBe(1))+ })++ it('colors the surviving series by its id, not its position after filtering', async () => {+ render(<BillingLineGraph series={SERIES} dates={DATES} hiddenSeries={[0]} />)++ const chart = getHogChart()+ await waitFor(() => expect(chart.seriesCount).toBe(1))++ const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 0, DATES.length))+ await waitFor(() => expect(tooltip.rows()).toEqual(['Recordings']))+ // If colouring switched to positional index, the survivor would wrongly pick up series 0's color+ // (mocked '#ff0000') instead of its own id's color (mocked '#0000ff').+ expect(tooltip.swatchColors()).toEqual(['rgb(0, 0, 255)'])+ })++ it('labels the most recent billing period marker that falls inside the range', async () => {+ render(+ <BillingLineGraph+ series={SERIES}+ dates={DATES}+ hiddenSeries={[]}+ billingPeriodMarkers={[{ date: dayjs.utc('2026-01-02') }]}+ />+ )++ expect(await screen.findByText('New billing period')).toBeTruthy()+ })++ it('draws a dashed line per in-range marker but labels only the most recent one', async () => {+ const { container } = render(+ <BillingLineGraph+ series={SERIES}+ dates={DATES}+ hiddenSeries={[]}+ billingPeriodMarkers={[+ { date: dayjs.utc('2025-12-01') }, // out of range — no line, no label+ { date: dayjs.utc('2026-01-01') },+ { date: dayjs.utc('2026-01-02') }, // most recent in-range marker+ ]}+ />+ )++ await screen.findByText('New billing period')++ const lines = container.querySelectorAll('[data-attr="billing-period-marker-line"]')+ expect(lines).toHaveLength(2)++ const labels = container.querySelectorAll('[data-attr="billing-period-marker-label"]')+ expect(labels).toHaveLength(1)++ const lineLefts = Array.from(lines).map((line) => (line as HTMLElement).style.left)+ const labelLeft = (labels[0] as HTMLElement).style.left+ // The label anchors to the later of the two in-range markers, not just the last line drawn.+ expect(labelLeft).toBe(lineLefts[1])+ })++ it('snaps a mid-day marker timestamp to midnight UTC rather than drifting toward the next label', async () => {+ const lineLeftFor = async (date: ReturnType<typeof dayjs.utc>): Promise<string> => {+ const { container, unmount } = render(+ <BillingLineGraph series={SERIES} dates={DATES} hiddenSeries={[]} billingPeriodMarkers={[{ date }]} />+ )+ await screen.findByText('New billing period')+ const line = container.querySelector<HTMLElement>('[data-attr="billing-period-marker-line"]')+ const left = line!.style.left+ unmount()+ return left+ }++ // Without startOf('day') the mid-day timestamp would resolve partway between the Jan 2+ // and Jan 3 labels instead of landing exactly on Jan 2's x, same as an exact-midnight marker.+ const midnightLeft = await lineLeftFor(dayjs.utc('2026-01-02'))+ const midDayLeft = await lineLeftFor(dayjs.utc('2026-01-02T14:30:00Z'))+ expect(midDayLeft).toBe(midnightLeft)+ })++ it('applies valueFormatter to both the y-axis ticks and the tooltip values', async () => {+ render(+ <BillingLineGraph+ series={SERIES}+ dates={DATES}+ hiddenSeries={[]}+ valueFormatter={(value) => `$${value.toLocaleString()}`}+ />+ )++ const chart = getHogChart()+ await waitFor(() => expect(chart.yTicks().length).toBeGreaterThan(0))+ expect(chart.yTicks().every((tick) => tick.startsWith('$'))).toBe(true)++ const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 0, DATES.length))+ await waitFor(() => expect(tooltip.value('Events')).toBe('$10'))+ })++ it('draws no marker when the billing period start is outside the plotted range', async () => {+ render(+ <BillingLineGraph+ series={SERIES}+ dates={DATES}+ hiddenSeries={[]}+ billingPeriodMarkers={[{ date: dayjs.utc('2025-12-01') }]}+ />+ )++ await waitFor(() => expect(getHogChart().seriesCount).toBe(2))+ expect(screen.queryByText('New billing period')).toBeNull()+ })+})diff --git a/frontend/src/scenes/billing/BillingLineGraph.tsx b/frontend/src/scenes/billing/BillingLineGraph.tsxindex ba55d0b61cbc..7eec52c92291 100644--- a/frontend/src/scenes/billing/BillingLineGraph.tsx+++ b/frontend/src/scenes/billing/BillingLineGraph.tsx@@ -1,39 +1,21 @@-import './BillingLineGraph.scss'+import { useMemo } from 'react'-import annotationPlugin from 'chartjs-plugin-annotation'-import { useValues } from 'kea'-import { useCallback, useEffect, useRef, useState } from 'react'-import { Root, createRoot } from 'react-dom/client'+import { TimeSeriesLineChart } from '@posthog/quill-charts'+import type { Series, TimeSeriesLineChartConfig } from '@posthog/quill-charts'-import { IconInfo } from '@posthog/icons'--import { Chart, ChartDataset, ChartOptions, TooltipModel } from 'lib/Chart'+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'import { getSeriesColor } from 'lib/colors'-import { getGraphColors } from 'lib/colors'-import { Dayjs } from 'lib/dayjs'-import { useChart } from 'lib/hooks/useChart'-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'-import { Tooltip } from 'lib/lemon-ui/Tooltip'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'-// eslint-disable-next-line import/no-cycle-import { BillingLineGraphTooltip } from './BillingLineGraphTooltip'-import { useBillingMarkersPositioning } from './useBillingMarkersPositioning'+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'-Chart.register(annotationPlugin)+import { BillingPeriodMarkers } from './BillingPeriodMarkers'+import type { BillingPeriodMarker } from './BillingPeriodMarkers'export interface BillingSeriesType {id: numberlabel: stringdata: number[]dates: string[]- valueFormatter?: (value: number) => string- showLegend?: boolean-}--export interface BillingPeriodMarker {- date: Dayjs}export interface BillingLineGraphProps {@@ -49,49 +31,9 @@ export interface BillingLineGraphProps {const defaultFormatter = (value: number): string => value.toLocaleString()-function useBillingTooltip(): {- ensureBillingTooltip: () => [Root, HTMLElement]- hideBillingTooltip: () => void-} {- const tooltipElRef = useRef<HTMLElement | null>(null)- const tooltipRootRef = useRef<Root | null>(null)-- const ensureBillingTooltip = useCallback((): [Root, HTMLElement] => {- if (!tooltipElRef.current) {- tooltipElRef.current = document.createElement('div')- tooltipElRef.current.id = 'BillingTooltipWrapper'- tooltipElRef.current.className =- 'BillingTooltipWrapper hidden absolute z-10 p-2 bg-bg-light rounded shadow-md text-xs pointer-events-none border border-border'- document.body.appendChild(tooltipElRef.current)- }- if (!tooltipRootRef.current) {- tooltipRootRef.current = createRoot(tooltipElRef.current)- }- return [tooltipRootRef.current, tooltipElRef.current]- }, [])-- const hideBillingTooltip = useCallback((): void => {- if (tooltipElRef.current) {- tooltipElRef.current.classList.add('hidden')- tooltipElRef.current.classList.remove('block')- }- }, [])+const handleChartError = makeChartErrorHandler('billing-line-chart')- useOnMountEffect(() => {- return () => {- if (tooltipRootRef.current) {- tooltipRootRef.current.unmount()- }- tooltipElRef.current?.remove()- }- })-- return { ensureBillingTooltip, hideBillingTooltip }-}--export function SeriesColorDot({ colorIndex }: { colorIndex: number }): JSX.Element {- return <div className={`series-color-dot series-color-dot-${colorIndex % 15}`} />-}+const NO_MARKERS: BillingPeriodMarker[] = []export function BillingLineGraph({series,@@ -101,318 +43,56 @@ export function BillingLineGraph({valueFormatter = defaultFormatter,showLegend = true,interval = 'day',- billingPeriodMarkers = [],+ billingPeriodMarkers = NO_MARKERS,}: BillingLineGraphProps): JSX.Element {- const [chartReady, setChartReady] = useState(false)- const [chartDimensions, setChartDimensions] = useState({ width: 0, height: 0 })- const [axisLabelColor, setAxisLabelColor] = useState('#666666')- const [markersReady, setMarkersReady] = useState(false)- const [stableChartAreaLeft, setStableChartAreaLeft] = useState<number | null>(null)- const markerTimeoutRef = useRef<NodeJS.Timeout | null>(null)- const { ensureBillingTooltip, hideBillingTooltip } = useBillingTooltip()- const { isDarkModeOn } = useValues(themeLogic)-- const visibleSeries = series.filter((s) => !hiddenSeries.includes(s.id))-- const { canvasRef, chartRef } = useChart<'line'>({- getConfig: () => {- const graphColors = getGraphColors()- const currentAxisLabelColor = graphColors.axisLabel || '#666666'- setAxisLabelColor(currentAxisLabelColor)-- const datasets: ChartDataset<'line'>[] = visibleSeries.map((s) => ({+ const theme = useChartTheme()++ // Hide via `visibility.excluded` rather than by filtering the array, so a hidden series stays+ // listed (dimmed) if the legend is ever turned on. Color by series id, not by position: the+ // ribbons in BillingDataTable are keyed to the id, and the two have to agree.+ const chartSeries = useMemo<Series[]>(+ () =>+ series.map((s) => ({+ key: String(s.id),label: s.label,data: s.data,- borderColor: getSeriesColor(s.id % 15),- backgroundColor: getSeriesColor(s.id % 15),- borderWidth: 2,- tension: 0.1,- pointRadius: 0,- pointHoverRadius: 4,- pointHoverBackgroundColor: getSeriesColor(s.id % 15),- pointHoverBorderColor: getSeriesColor(s.id % 15),- }))-- const options: ChartOptions<'line'> = {- responsive: true,- maintainAspectRatio: false,- animation: false,- interaction: {- mode: 'nearest',- axis: 'x',- intersect: false,- },- scales: {- x: {- type: 'time',- time: {- unit: interval,- displayFormats: {- day: 'MMM DD',- },- },- ticks: {- source: 'labels',- color: currentAxisLabelColor,- },- grid: {- display: false,- },- },- y: {- beginAtZero: true,- grid: {- color: graphColors.axisLine || 'rgba(0, 0, 0, 0.1)',- },- ticks: {- callback: function (value) {- return typeof value === 'number' ? valueFormatter(value) : value- },- color: currentAxisLabelColor,- },- },- },- plugins: {- // @ts-expect-error Types of library are out of date- crosshair: false,- tooltip: {- enabled: false,- external: ({ chart, tooltip }: { chart: Chart; tooltip: TooltipModel<'line'> }) => {- const canvas = chart.canvas- if (!canvas) {- return- }-- const [tooltipRoot, tooltipEl] = ensureBillingTooltip()-- if (tooltip.opacity === 0 || !tooltip.body?.length) {- hideBillingTooltip()- return- }-- try {- const title = tooltip.title?.[0] || ''- const dataPoints = tooltip.dataPoints || []-- const sortedSeries = dataPoints- .map((point) => {- const dataset =- point.datasetIndex < visibleSeries.length- ? visibleSeries[point.datasetIndex]- : null- if (!dataset) {- return null- }- const value = point.parsed.y- if (value === null) {- return null- }- return {- id: dataset.id,- label: dataset.label,- value: value,- formattedValue: valueFormatter(value),- color: getSeriesColor(dataset.id % 15),- datasetIndex: point.datasetIndex,- }- })- .filter((item): item is NonNullable<typeof item> => item !== null)- .sort((a, b) => b.value - a.value)-- tooltipRoot.render(- <BillingLineGraphTooltip title={title} sortedSeries={sortedSeries} />- )-- tooltipEl.classList.remove('hidden')- tooltipEl.classList.add('block')-- const bounds = canvas.getBoundingClientRect()- const tooltipWidth = tooltipEl.offsetWidth- const tooltipHeight = tooltipEl.offsetHeight-- const scrollX = window.scrollX- const scrollY = window.scrollY-- let tooltipX = bounds.left + scrollX + tooltip.caretX + 8- let tooltipY = bounds.top + scrollY + tooltip.caretY - tooltipHeight / 2-- if (tooltipX + tooltipWidth > bounds.right + scrollX) {- tooltipX = bounds.left + scrollX + tooltip.caretX - tooltipWidth - 8- }- tooltipX = Math.max(tooltipX, bounds.left + scrollX)- tooltipY = Math.max(tooltipY, bounds.top + scrollY)- tooltipY = Math.min(tooltipY, bounds.bottom + scrollY - tooltipHeight)-- tooltipEl.style.top = `${tooltipY}px`- tooltipEl.style.left = `${tooltipX}px`- } catch {- hideBillingTooltip()- }- },- mode: 'index',- intersect: false,- },- legend: {- display: showLegend,- position: 'bottom',- labels: {- usePointStyle: true,- boxWidth: 6,- },- },- annotation: {- annotations: billingPeriodMarkers.reduce((acc: Record<string, any>, marker, idx) => {- acc[`billing-period-${idx}`] = {- type: 'line',- xMin: marker.date.utc().format('YYYY-MM-DD'),- xMax: marker.date.utc().format('YYYY-MM-DD'),- borderColor: isDarkModeOn ? 'rgba(255, 255, 255, 0.4)' : 'rgba(0, 0, 0, 0.4)',- borderWidth: 2,- borderDash: [8, 4],- }- return acc- }, {}),- },- },- }-- return {- type: 'line' as const,- data: {- labels: dates,- datasets,- },- options,- }- },- deps: [- series,- dates,- hiddenSeries,- valueFormatter,- showLegend,- interval,- ensureBillingTooltip,- hideBillingTooltip,- isDarkModeOn,- billingPeriodMarkers,- ],- })-- const { chartAreaLeft, chartAreaTop, getMarkerPosition } = useBillingMarkersPositioning(- chartRef.current || undefined,- chartDimensions.width,- chartDimensions.height+ color: getSeriesColor(s.id),+ visibility: { excluded: hiddenSeries.includes(s.id) },+ })),+ [series, hiddenSeries])- useEffect(() => {- const chartInstance = chartRef.current- if (!chartInstance) {- setChartReady(false)- setMarkersReady(false)- return- }-- setChartDimensions({- width: chartInstance.width,- height: chartInstance.height,- })- setChartReady(true)- const currentChartAreaLeft = chartInstance.chartArea?.left-- if (stableChartAreaLeft !== null && Math.abs(currentChartAreaLeft - stableChartAreaLeft) < 1) {- setMarkersReady(true)- } else {- setStableChartAreaLeft(currentChartAreaLeft)- setMarkersReady(false)-- if (markerTimeoutRef.current) {- clearTimeout(markerTimeoutRef.current)- }- markerTimeoutRef.current = setTimeout(() => {- setMarkersReady(true)- }, 200)- }-- return () => {- if (markerTimeoutRef.current) {- clearTimeout(markerTimeoutRef.current)- }- }- }, [chartRef.current]) // oxlint-disable-line react-hooks/exhaustive-deps+ const config = useChartConfig<TimeSeriesLineChartConfig>(+ () => ({+ xAxis: { timezone: 'UTC', interval },+ yAxis: { tickFormatter: valueFormatter },+ legend: { show: showLegend, position: 'bottom', interactive: false },+ tooltip: { sortedByValue: true, valueFormatter, placement: 'cursor' },+ }),+ [interval, valueFormatter, showLegend]+ )return (- <div className="relative h-96" onMouseLeave={hideBillingTooltip}>+ // pt-8 reserves room above the plot for the billing period label, which sits outside the plot+ // area so that hovering it takes the cursor out of the chart's hover region.+ <div className="relative flex flex-col h-96 pt-8">{isLoading && (<div className="absolute inset-0 flex items-center justify-center bg-bg-light bg-opacity-75 z-10"><div className="text-muted">Loading...</div></div>)}- <canvas ref={canvasRef} />- {/* Billing period marker overlays with tooltips */}- {chartReady && markersReady && billingPeriodMarkers.length > 0 && (- <div- className="BillingMarkersOverlay"- style={- {- '--billing-markers-chart-area-left': `${chartAreaLeft}px`,- '--billing-markers-chart-area-top': `${chartAreaTop}px`,- '--billing-marker-text-color': axisLabelColor,- '--billing-marker-bg-color': 'var(--color-bg-surface-primary)',- '--billing-marker-border-color': 'var(--color-border-primary)',- } as React.CSSProperties & Record<string, string>- }- >- {billingPeriodMarkers- .filter((marker) => getMarkerPosition(marker.date).visible)- .slice(-1) // Show only the most recent visible marker- .map((marker, idx) => {- const position = getMarkerPosition(marker.date)-- return (- <div- key={`marker-${idx}`}- className="BillingMarker"- style={- {- '--billing-marker-left': `${position.left}px`,- } as React.CSSProperties & Record<string, string>- }- onMouseEnter={hideBillingTooltip}- >- <Tooltip- title={- <div className="p-2">- <strong>New billing period started</strong>- <p className="mt-2 text-xs">- Pricing tiers reset when billing periods begin, which can cause- temporary usage and spend changes:- </p>- <ul className="mt-1 text-xs list-disc list-inside">- <li>- Usage may drop to zero in last days of the billing period after- billing limits are reached- </li>- <li>Zero spend in first days due to free tier allowance</li>- <li>- Higher daily spend in first days due to higher rates at lower- volume tiers- </li>- </ul>- </div>- }- placement="bottom"- >- <div className="BillingMarkerLabel">- New billing period- <IconInfo className="w-3 h-3" />- </div>- </Tooltip>- </div>- )- })}- </div>- )}+ <TimeSeriesLineChart+ series={chartSeries}+ labels={dates}+ theme={theme}+ config={config}+ onError={handleChartError}+ // The billing period label is anchored above the plot, so it sits outside the chart+ // wrapper's box and would otherwise be cut off by its `overflow-hidden`.+ className="overflow-visible!"+ >+ <BillingPeriodMarkers markers={billingPeriodMarkers} />+ </TimeSeriesLineChart></div>)}diff --git a/frontend/src/scenes/billing/BillingLineGraphTooltip.tsx b/frontend/src/scenes/billing/BillingLineGraphTooltip.tsxdeleted file mode 100644index abae15042c6c..000000000000--- a/frontend/src/scenes/billing/BillingLineGraphTooltip.tsx+++ /dev/null@@ -1,35 +0,0 @@-// eslint-disable-next-line import/no-cycle-import { SeriesColorDot } from './BillingLineGraph'--export interface BillingLineGraphTooltipSeriesItem {- id: number- label: string- value: number- formattedValue: string- color: string- datasetIndex: number-}--export interface BillingLineGraphTooltipProps {- title: string- sortedSeries: BillingLineGraphTooltipSeriesItem[]-}--export function BillingLineGraphTooltip({ title, sortedSeries }: BillingLineGraphTooltipProps): JSX.Element {- return (- <div className="space-y-1">- <div className="font-semibold text-text-primary">{title}</div>- {sortedSeries.map((item) => (- <div key={item.id} className="flex items-center justify-between gap-2">- <div className="flex items-center gap-1">- <SeriesColorDot colorIndex={item.id} />- <span className="text-text-secondary whitespace-nowrap overflow-hidden text-ellipsis max-w-xs">- {item.label}- </span>- </div>- <span className="font-medium text-text-primary whitespace-nowrap">{item.formattedValue}</span>- </div>- ))}- </div>- )-}diff --git a/frontend/src/scenes/billing/BillingPeriodMarkers.test.ts b/frontend/src/scenes/billing/BillingPeriodMarkers.test.tsnew file mode 100644index 000000000000..5a78696b5eb1--- /dev/null+++ b/frontend/src/scenes/billing/BillingPeriodMarkers.test.ts@@ -0,0 +1,40 @@+import { resolveMarkerX } from './BillingPeriodMarkers'++describe('resolveMarkerX', () => {+ const labelTimestamps = [+ Date.UTC(2026, 0, 1), // Jan 1+ Date.UTC(2026, 1, 1), // Feb 1+ Date.UTC(2026, 2, 1), // Mar 1+ ]+ const labelX = [0, 100, 200]++ it('places a marker sitting exactly on a label at that label', () => {+ expect(resolveMarkerX(labelTimestamps[1], labelTimestamps, labelX)).toBe(100)+ })++ it('interpolates a marker that falls between two labels', () => {+ // Jan 16 is 15 days into the 31-day January bucket: (15 / 31) * 100 = 48.387...+ const x = resolveMarkerX(Date.UTC(2026, 0, 16), labelTimestamps, labelX)+ expect(x).toBeCloseTo((15 / 31) * 100, 5)+ })++ it.each([+ ['before the first label', Date.UTC(2025, 11, 15)],+ ['after the last label', Date.UTC(2026, 2, 2)],+ ])('returns null for a marker %s', (_, markerTs) => {+ expect(resolveMarkerX(markerTs, labelTimestamps, labelX)).toBeNull()+ })++ it.each([+ ['on the first label', Date.UTC(2026, 0, 1), 0],+ ['on the last label', Date.UTC(2026, 2, 1), 200],+ ])('resolves a marker landing exactly %s as an in-range x', (_, markerTs, expectedX) => {+ expect(resolveMarkerX(markerTs, labelTimestamps, labelX)).toBe(expectedX)+ })++ it('resolves an exact match on a single-bucket chart, which has no interval to interpolate', () => {+ const single = [Date.UTC(2026, 0, 1)]+ expect(resolveMarkerX(single[0], single, [42])).toBe(42)+ expect(resolveMarkerX(Date.UTC(2026, 0, 2), single, [42])).toBeNull()+ })+})diff --git a/frontend/src/scenes/billing/BillingPeriodMarkers.tsx b/frontend/src/scenes/billing/BillingPeriodMarkers.tsxnew file mode 100644index 000000000000..2d6294fa0c31--- /dev/null+++ b/frontend/src/scenes/billing/BillingPeriodMarkers.tsx@@ -0,0 +1,123 @@+import { useMemo } from 'react'++import { IconInfo } from '@posthog/icons'+import { useChartLayout } from '@posthog/quill-charts'++import { Dayjs, dayjs } from 'lib/dayjs'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++export interface BillingPeriodMarker {+ date: Dayjs+}++/** Gap between the label and the top of the plot, so it clears the topmost y-axis tick. */+const LABEL_GAP = 4++/**+ * Resolves a marker timestamp to an x pixel by interpolating between the two labels that bracket it.+ * A billing period rarely starts exactly on a bucket boundary — on week and month intervals it lands+ * between two labels — so snapping to the nearest label would misplace the marker by up to half a+ * bucket. Returns null when the timestamp falls outside the plotted range.+ */+export function resolveMarkerX(markerTs: number, labelTimestamps: number[], labelX: number[]): number | null {+ for (let i = 0; i < labelTimestamps.length - 1; i++) {+ const [from, to] = [labelTimestamps[i], labelTimestamps[i + 1]]+ if (markerTs < from || markerTs > to) {+ continue+ }+ // Guards the division below: chart date labels are distinct in practice, but two equal+ // adjacent timestamps would otherwise divide by zero.+ if (to === from) {+ return labelX[i]+ }+ return labelX[i] + ((markerTs - from) / (to - from)) * (labelX[i + 1] - labelX[i])+ }+ // A single-bucket chart has no interval to interpolate across.+ if (labelTimestamps.length === 1 && markerTs === labelTimestamps[0]) {+ return labelX[0]+ }+ return null+}++function BillingPeriodExplanation(): JSX.Element {+ return (+ <div className="p-2">+ <strong>New billing period started</strong>+ <p className="mt-2 text-xs">+ Pricing tiers reset when billing periods begin, which can cause temporary usage and spend changes:+ </p>+ <ul className="mt-1 text-xs list-disc list-inside">+ <li>Usage may drop to zero in last days of the billing period after billing limits are reached</li>+ <li>Zero spend in first days due to free tier allowance</li>+ <li>Higher daily spend in first days due to higher rates at lower volume tiers</li>+ </ul>+ </div>+ )+}++/**+ * Renders as a chart overlay child, reading pixel positions off the chart's own scales.+ *+ * Not built on quill's `ReferenceLine`: its vertical variant resolves x through `scales.x(label)`, so+ * it can only sit exactly on a label, and a billing period routinely starts mid-bucket on week and+ * month intervals. Its label is also a plain string, not a node, so it can't carry the explanation+ * tooltip. Teaching `ReferenceLine` to take an interpolated x would let this collapse into it.+ */+export function BillingPeriodMarkers({ markers }: { markers: BillingPeriodMarker[] }): JSX.Element | null {+ const { labels, scales, dimensions, theme } = useChartLayout()++ const labelTimestamps = useMemo(() => labels.map((label) => dayjs.utc(label).valueOf()), [labels])++ const positions = useMemo(() => {+ if (!markers.length) {+ return []+ }+ const labelX = labels.map((label) => scales.x(label) ?? NaN)+ return markers+ .map((marker) => resolveMarkerX(marker.date.utc().startOf('day').valueOf(), labelTimestamps, labelX))+ .filter((left): left is number => left !== null && isFinite(left))+ // eslint-disable-next-line react-hooks/exhaustive-deps -- only `scales.x` is read; `scales` itself is unused.+ }, [markers, labels, labelTimestamps, scales.x])++ if (!positions.length) {+ return null+ }++ const lineColor = theme.axisLineColor+ const labelLeft = Math.max(...positions)++ // Positions and the theme's line color resolve at runtime from the chart's scales, so they stay+ // inline — everything static is a utility class.+ return (+ <>+ {positions.map((left, idx) => (+ <div+ key={`billing-period-line-${idx}`}+ data-attr="billing-period-marker-line"+ className="absolute -translate-x-1/2 border-l-2 border-dashed"+ style={{+ left,+ top: dimensions.plotTop,+ height: dimensions.plotHeight,+ borderLeftColor: lineColor,+ }}+ />+ ))}+ {/* Anchored just above the plot: that keeps it clear of the data and of the topmost y-axis+ tick, and puts the cursor outside the plot area while hovering it, which is what makes+ the chart drop its own tooltip instead of showing two at once. */}+ <div+ data-attr="billing-period-marker-label"+ className="absolute -translate-x-1/2 -translate-y-full pointer-events-auto cursor-default"+ style={{ left: labelLeft, top: dimensions.plotTop - LABEL_GAP }}+ >+ <Tooltip title={<BillingPeriodExplanation />} placement="bottom">+ <div className="flex items-center gap-1 px-2 py-1 text-xs font-normal whitespace-nowrap rounded-sm border border-primary bg-surface-primary text-secondary">+ New billing period+ <IconInfo className="w-3 h-3" />+ </div>+ </Tooltip>+ </div>+ </>+ )+}diff --git a/frontend/src/scenes/billing/BillingTooltip.tsx b/frontend/src/scenes/billing/BillingTooltip.tsxdeleted file mode 100644index 6b6af1f38daa..000000000000--- a/frontend/src/scenes/billing/BillingTooltip.tsx+++ /dev/null@@ -1,34 +0,0 @@-import { SeriesColorDot } from './BillingLineGraph'--export interface BillingLineGraphTooltipSeriesItem {- id: number | string- label: string- value: number- formattedValue: string- color: string- datasetIndex: number-}--export interface BillingLineGraphTooltipProps {- title: string- sortedSeries: BillingLineGraphTooltipSeriesItem[]-}--export function BillingLineGraphTooltip({ title, sortedSeries }: BillingLineGraphTooltipProps): JSX.Element {- return (- <div className="space-y-1">- <div className="font-semibold text-text-primary">{title}</div>- {sortedSeries.map((item) => (- <div key={item.id} className="flex items-center justify-between gap-2">- <div className="flex items-center gap-1">- <SeriesColorDot colorIndex={item.datasetIndex} />- <span className="text-text-secondary whitespace-nowrap overflow-hidden text-ellipsis max-w-xs">- {item.label}- </span>- </div>- <span className="font-medium text-text-primary whitespace-nowrap">{item.formattedValue}</span>- </div>- ))}- </div>- )-}diff --git a/frontend/src/scenes/billing/billingSpendLogic.ts b/frontend/src/scenes/billing/billingSpendLogic.tsindex ac9640ee2bbc..b323d0f42a8d 100644--- a/frontend/src/scenes/billing/billingSpendLogic.ts+++ b/frontend/src/scenes/billing/billingSpendLogic.ts@@ -24,8 +24,8 @@ import {syncBillingSearchParams,updateBillingSearchParams,} from './billing-utils'-import type { BillingPeriodMarker } from './BillingLineGraph'import { billingLogic } from './billingLogic'+import type { BillingPeriodMarker } from './BillingPeriodMarkers'import type { BillingFilters } from './types'import type { BillingUsageInteractionProps } from './types'diff --git a/frontend/src/scenes/billing/billingUsageLogic.ts b/frontend/src/scenes/billing/billingUsageLogic.tsindex 807f03329ea3..35acc10d3bd8 100644--- a/frontend/src/scenes/billing/billingUsageLogic.ts+++ b/frontend/src/scenes/billing/billingUsageLogic.ts@@ -24,8 +24,8 @@ import {syncBillingSearchParams,updateBillingSearchParams,} from './billing-utils'-import type { BillingPeriodMarker } from './BillingLineGraph'import { billingLogic } from './billingLogic'+import type { BillingPeriodMarker } from './BillingPeriodMarkers'import type { BillingFilters } from './types'import type { BillingUsageInteractionProps } from './types'diff --git a/frontend/src/scenes/billing/useBillingMarkersPositioning.ts b/frontend/src/scenes/billing/useBillingMarkersPositioning.tsdeleted file mode 100644index dcbbd1906d67..000000000000--- a/frontend/src/scenes/billing/useBillingMarkersPositioning.ts+++ /dev/null@@ -1,47 +0,0 @@-import { useMemo } from 'react'--import { Chart } from 'lib/Chart'-import { Dayjs } from 'lib/dayjs'--export interface BillingMarkersPositioning {- chartAreaLeft: number- chartAreaTop: number- getMarkerPosition: (date: Dayjs) => { left: number; visible: boolean }-}--export function useBillingMarkersPositioning(- chart: Chart | undefined,- chartWidth: number,- chartHeight: number-): BillingMarkersPositioning {- return useMemo<BillingMarkersPositioning>(() => {- if (!chart || !chart.scales.x) {- return {- chartAreaLeft: 0,- chartAreaTop: 0,- getMarkerPosition: () => ({ left: 0, visible: false }),- }- }-- const xScale = chart.scales.x- const yScale = chart.scales.y-- return {- chartAreaLeft: xScale.left,- chartAreaTop: yScale.top,- getMarkerPosition: (date: Dayjs) => {- // Use midnight UTC of the same day to match Chart.js annotation date string interpretation- const utcMidnightTimestamp = date.utc().startOf('day').valueOf()- const xPos = xScale.getPixelForValue(utcMidnightTimestamp)-- // Check if position is within visible chart area- const visible = xPos !== undefined && xPos >= xScale.left && xPos <= xScale.right-- return {- left: visible ? xPos - xScale.left : 0, // Relative to chart area- visible,- }- },- }- }, [chart, chartWidth, chartHeight])-}