Skip to content

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

chore(hog-charts): make library self-contained (#58089)

Sam Penningtona7a24661dfbc
diff --git a/frontend/src/lib/hog-charts/charts/LineChart.stories.tsx b/frontend/src/lib/hog-charts/charts/LineChart.stories.tsx
index 70433b498813..b665bc75bd76 100644
--- a/frontend/src/lib/hog-charts/charts/LineChart.stories.tsx
+++ b/frontend/src/lib/hog-charts/charts/LineChart.stories.tsx
@@ -1,8 +1,7 @@
import { Meta, StoryObj } from '@storybook/react'
-import { DEFAULT_Y_AXIS_ID, LineChart, ReferenceLine, ValueLabels } from 'lib/hog-charts'
+import { ciRanges, DEFAULT_Y_AXIS_ID, LineChart, ReferenceLine, trendLine, ValueLabels } from 'lib/hog-charts'
import type { LineChartConfig, Series } from 'lib/hog-charts'
-import { ciRanges, trendLine } from 'lib/statistics'
import { playHoverAtFraction, Stage, useReactiveTheme } from '../story-helpers'
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
index 17ff47491713..ad07876a5ea9 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
@@ -1,8 +1,7 @@
import { Meta, StoryObj } from '@storybook/react'
-import { TimeSeriesLineChart } from 'lib/hog-charts'
+import { ciRanges, TimeSeriesLineChart } from 'lib/hog-charts'
import type { Series, TimeInterval, YAxisConfig } from 'lib/hog-charts'
-import { ciRanges } from 'lib/statistics'
import { Stage, useReactiveTheme } from '../../story-helpers'
import {
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts
index a4ec48564b29..96fadc01d577 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts
@@ -1,7 +1,6 @@
-import { linearRegression, movingAverage, trendLine } from 'lib/statistics'
-
import type { Series } from '../../../core/types'
import { dimHex } from '../../../utils/comparison-dimming'
+import { linearRegression, movingAverage, trendLine } from '../../../utils/statistics'
const TREND_LINE_DIM_OPACITY = 0.5
const CI_FILL_OPACITY = 0.2
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index 01061cad5140..3a0de680b7bb 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -1,5 +1,13 @@
-import type { ChartTheme } from 'lib/charts/types'
-export type { ChartTheme }
+/** Visual theme colours consumed by chart rendering. */
+export interface ChartTheme {
+ colors: string[]
+ backgroundColor?: string
+ axisColor?: string
+ gridColor?: string
+ crosshairColor?: string
+ tooltipBackground?: string
+ tooltipColor?: string
+}
/** Default axis id used when a series doesn't specify one. */
export const DEFAULT_Y_AXIS_ID = 'left'
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index 20318ced360a..63f50ff53b07 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -77,3 +77,6 @@ export type { YAxisFormat, YFormatterConfig } from './utils/y-formatters'
export type { XAxisConfig, YAxisConfig } from './utils/use-axis-formatters'
export { buildGoalLineReferenceLines, computeSeriesNonZeroMax } from './utils/goal-lines'
export type { GoalLineConfig } from './utils/goal-lines'
+
+// Statistics helpers (used by trend-line / moving-average / confidence-interval features)
+export { ciRanges, linearRegression, movingAverage, trendLine } from './utils/statistics'
diff --git a/frontend/src/lib/hog-charts/story-helpers.tsx b/frontend/src/lib/hog-charts/story-helpers.tsx
index 60769a9dc51e..e3537edb3f0a 100644
--- a/frontend/src/lib/hog-charts/story-helpers.tsx
+++ b/frontend/src/lib/hog-charts/story-helpers.tsx
@@ -1,10 +1,45 @@
import { fireEvent, waitFor } from '@testing-library/react'
import { useEffect, useState } from 'react'
-import { buildTheme } from 'lib/charts/utils/theme'
-
import type { ChartTheme } from './core/types'
+const DATA_COLOR_VARS = [
+ 'data-color-1',
+ 'data-color-2',
+ 'data-color-3',
+ 'data-color-4',
+ 'data-color-5',
+ 'data-color-6',
+ 'data-color-7',
+ 'data-color-8',
+ 'data-color-9',
+ 'data-color-10',
+ 'data-color-11',
+ 'data-color-12',
+ 'data-color-13',
+ 'data-color-14',
+ 'data-color-15',
+]
+
+function readCssVar(name: string): string | undefined {
+ const value = getComputedStyle(document.body)
+ .getPropertyValue('--' + name)
+ .trim()
+ return value || undefined
+}
+
+function buildTheme(): ChartTheme {
+ return {
+ colors: DATA_COLOR_VARS.map((v) => readCssVar(v) ?? '#000'),
+ backgroundColor: readCssVar('color-bg-surface-primary') ?? '#ffffff',
+ axisColor: readCssVar('color-graph-axis-label'),
+ gridColor: readCssVar('color-graph-axis-line'),
+ crosshairColor: readCssVar('color-graph-crosshair'),
+ tooltipBackground: readCssVar('color-bg-surface-tooltip'),
+ tooltipColor: readCssVar('color-text-primary'),
+ }
+}
+
/**
* `buildTheme()` reads CSS variables from `document.body` once. The Storybook
* test runner takes a second screenshot after flipping `body[theme="dark"]`,
diff --git a/frontend/src/lib/hog-charts/utils/comparison-dimming.ts b/frontend/src/lib/hog-charts/utils/comparison-dimming.ts
index 2d0742b100c8..9aec4239ef51 100644
--- a/frontend/src/lib/hog-charts/utils/comparison-dimming.ts
+++ b/frontend/src/lib/hog-charts/utils/comparison-dimming.ts
@@ -1,6 +1,5 @@
-import { hexToRGBA } from 'lib/utils'
-
import type { Series } from '../core/types'
+import { hexToRGBA } from './format'
const COMPARISON_DIM_OPACITY = 0.5
diff --git a/frontend/src/lib/hog-charts/utils/dates.ts b/frontend/src/lib/hog-charts/utils/dates.ts
index 1388f726fd22..e73a2cae3d18 100644
--- a/frontend/src/lib/hog-charts/utils/dates.ts
+++ b/frontend/src/lib/hog-charts/utils/dates.ts
@@ -1,5 +1,4 @@
-import { Dayjs } from 'lib/dayjs'
-import { parseDateInTimezone } from 'lib/utils/dateTimeUtils'
+import { type Dayjs, parseDateInTimezone } from './dayjs'
/** Bucket size for a date-based X axis. Mirrors `IntervalType` from product code without
* coupling hog-charts to it. */
diff --git a/frontend/src/lib/hog-charts/utils/dayjs.ts b/frontend/src/lib/hog-charts/utils/dayjs.ts
new file mode 100644
index 000000000000..a85bb37ce546
--- /dev/null
+++ b/frontend/src/lib/hog-charts/utils/dayjs.ts
@@ -0,0 +1,36 @@
+// Self-contained dayjs setup for hog-charts. Registers only the plugins this library
+// needs so it can move into a standalone UI package without depending on PostHog's
+// `lib/dayjs`. The wider PostHog app also extends dayjs, but `dayjs.extend` is
+// idempotent so calling it again here is safe.
+
+// oxlint-disable-next-line no-restricted-imports
+import dayjs, { Dayjs as DayjsOriginal } from 'dayjs'
+import customParseFormat from 'dayjs/plugin/customParseFormat'
+import timezone from 'dayjs/plugin/timezone'
+import utc from 'dayjs/plugin/utc'
+
+dayjs.extend(customParseFormat)
+dayjs.extend(utc)
+dayjs.extend(timezone)
+
+export { dayjs }
+export interface Dayjs extends DayjsOriginal {}
+
+/** Parse a date string into a Dayjs in the given timezone, browser-tz-independent.
+ *
+ * - Strings without explicit timezone info ("2026-03-08", "2026-03-08 14:00:00")
+ * are treated as wall-clock time in the given timezone.
+ * - Strings with explicit timezone info (trailing "Z" or "±HH:MM") are real instants;
+ * parse them as such and convert into the requested timezone. */
+export function parseDateInTimezone(dateStr: string, tz: string): Dayjs {
+ const hasExplicitTz = /([Zz]|[+-]\d{2}:?\d{2})$/.test(dateStr)
+ try {
+ if (hasExplicitTz) {
+ const instant = dayjs(dateStr)
+ return instant.isValid() ? instant.tz(tz) : dayjs(null)
+ }
+ return dayjs.tz(dateStr, tz)
+ } catch {
+ return dayjs(null)
+ }
+}
diff --git a/frontend/src/lib/hog-charts/utils/format.ts b/frontend/src/lib/hog-charts/utils/format.ts
new file mode 100644
index 000000000000..9527f15b3603
--- /dev/null
+++ b/frontend/src/lib/hog-charts/utils/format.ts
@@ -0,0 +1,155 @@
+// Self-contained number/colour/currency formatting helpers. hog-charts is intended to
+// move into a standalone UI library, so this file deliberately has no PostHog imports —
+// only standard browser APIs.
+
+const DEFAULT_DECIMAL_PLACES = 2
+const COMPACT_NUMBER_MAGNITUDES = ['', 'K', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y']
+
+function validateFractionDigits(maximumFractionDigits: number, fallback: number): number {
+ if (
+ isNaN(maximumFractionDigits) ||
+ !Number.isInteger(maximumFractionDigits) ||
+ maximumFractionDigits < 0 ||
+ maximumFractionDigits > 100
+ ) {
+ return fallback
+ }
+ return maximumFractionDigits
+}
+
+export function humanFriendlyNumber(
+ d: number,
+ maximumFractionDigits: number = DEFAULT_DECIMAL_PLACES,
+ minimumFractionDigits: number = 0
+): string {
+ return d.toLocaleString('en-US', {
+ maximumFractionDigits: validateFractionDigits(maximumFractionDigits, DEFAULT_DECIMAL_PLACES),
+ minimumFractionDigits: validateFractionDigits(minimumFractionDigits, 0),
+ })
+}
+
+export function humanFriendlyCurrency(
+ d: string | undefined | number,
+ precision: number = DEFAULT_DECIMAL_PLACES
+): string {
+ if (!d) {
+ d = '0.00'
+ }
+ const number = typeof d === 'string' ? parseFloat(d) : d
+ const validatedPrecision = validateFractionDigits(precision, DEFAULT_DECIMAL_PLACES)
+ return `$${number.toLocaleString('en-US', { maximumFractionDigits: validatedPrecision, minimumFractionDigits: validatedPrecision })}`
+}
+
+export function humanFriendlyDuration(
+ d: string | number | null | undefined,
+ {
+ maxUnits,
+ secondsPrecision,
+ secondsFixed,
+ }: { maxUnits?: number; secondsPrecision?: number; secondsFixed?: number } = {}
+): string {
+ if (d === '' || d === null || d === undefined || maxUnits === 0) {
+ return ''
+ }
+ d = Number(d)
+ if (d < 0) {
+ return `-${humanFriendlyDuration(-d, { maxUnits, secondsPrecision, secondsFixed })}`
+ }
+ if (d === 0) {
+ return `0s`
+ }
+ if (d < 1) {
+ return `${Math.round(d * 1000)}ms`
+ }
+ if (d < 60) {
+ if (secondsPrecision != null) {
+ return `${parseFloat(d.toPrecision(secondsPrecision))}s`
+ }
+ return `${parseFloat(d.toFixed(secondsFixed ?? 0))}s`
+ }
+
+ const days = Math.floor(d / 86400)
+ const h = Math.floor((d % 86400) / 3600)
+ const m = Math.floor((d % 3600) / 60)
+ const s = Math.floor((d % 3600) % 60)
+
+ const dayDisplay = days > 0 ? days + 'd' : ''
+ const hDisplay = h > 0 ? h + 'h' : ''
+ const mDisplay = m > 0 ? m + 'm' : ''
+ const sDisplay = s > 0 ? s + 's' : hDisplay || mDisplay ? '' : '0s'
+
+ let units: string[] = []
+ if (days > 0) {
+ units = [dayDisplay, hDisplay].filter(Boolean)
+ } else {
+ units = [hDisplay, mDisplay, sDisplay].filter(Boolean)
+ }
+ return units.slice(0, maxUnits ?? undefined).join(' ')
+}
+
+export function percentage(
+ division: number,
+ maximumFractionDigits: number = DEFAULT_DECIMAL_PLACES,
+ fixedPrecision: boolean = false
+): string {
+ if (division === Infinity) {
+ return '∞%'
+ }
+ const maxDigits = validateFractionDigits(maximumFractionDigits, DEFAULT_DECIMAL_PLACES)
+ return division.toLocaleString('en-US', {
+ style: 'percent',
+ maximumFractionDigits: maxDigits,
+ minimumFractionDigits: fixedPrecision ? maxDigits : undefined,
+ })
+}
+
+export function compactNumber(value: number | null): string {
+ if (value === null) {
+ return '-'
+ }
+ value = parseFloat(value.toPrecision(3))
+ let magnitude = 0
+ while (Math.abs(value) >= 1000) {
+ magnitude++
+ value /= 1000
+ }
+ return magnitude > 0 ? `${value} ${COMPACT_NUMBER_MAGNITUDES[magnitude]}` : value.toString()
+}
+
+/** Format an amount as currency, prefixed/suffixed by the locale-derived symbol.
+ * Accepts any string the runtime `Intl.NumberFormat` accepts as a currency code. */
+export function formatCurrency(amount: number, currency: string): string {
+ const { symbol, isPrefix } = getCurrencySymbol(currency)
+ return `${isPrefix ? symbol : ''}${humanFriendlyNumber(amount, 2, 2)}${isPrefix ? '' : ' ' + symbol}`
+}
+
+function getCurrencySymbol(currency: string): { symbol: string; isPrefix: boolean } {
+ const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency })
+ const parts = formatter.formatToParts(0)
+ const symbol = parts.find((part) => part.type === 'currency')?.value
+ const isPrefix = symbol ? parts[0].type === 'currency' : true
+ return { symbol: symbol ?? currency, isPrefix }
+}
+
+function hexToRGB(hex: string): { r: number; g: number; b: number; a: number } {
+ hex = hex.replace(/^#/, '')
+ if (hex.length === 3 || hex.length === 4) {
+ hex = hex
+ .split('')
+ .map((char) => char + char)
+ .join('')
+ }
+ if (hex.length !== 6 && hex.length !== 8) {
+ return { r: 0, g: 0, b: 0, a: 0 }
+ }
+ const r = parseInt(hex.slice(0, 2), 16)
+ const g = parseInt(hex.slice(2, 4), 16)
+ const b = parseInt(hex.slice(4, 6), 16)
+ const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1
+ return { r, g, b, a }
+}
+
+export function hexToRGBA(hex: string, alpha = 1): string {
+ const { r, g, b } = hexToRGB(hex)
+ return `rgba(${[r, g, b, alpha].join(',')})`
+}
diff --git a/frontend/src/lib/hog-charts/utils/statistics.ts b/frontend/src/lib/hog-charts/utils/statistics.ts
new file mode 100644
index 000000000000..f3d011649704
--- /dev/null
+++ b/frontend/src/lib/hog-charts/utils/statistics.ts
@@ -0,0 +1,50 @@
+// Self-contained statistics helpers for hog-charts. Wraps `simple-statistics`
+// directly so the library has no PostHog imports.
+
+import { linearRegression as ssLinearRegression, probit, standardDeviation } from 'simple-statistics'
+
+export function linearRegression(data: ReadonlyArray<readonly [number, number]>): { m: number; b: number } {
+ return ssLinearRegression(data as [number, number][])
+}
+
+/** Symmetric confidence interval bounds for a sample of values, using the normal
+ * approximation (`±z·SE`). Returns `[lower, upper]` arrays, both the same length
+ * as the input. */
+export function ciRanges(values: number[], ci: number = 0.95): [number[], number[]] {
+ const n = values.length
+ if (n < 2) {
+ return [values, values]
+ }
+ const sd = standardDeviation(values)
+ const se = sd / Math.sqrt(n)
+ const z = probit((1 + ci) / 2)
+ const h = z * se
+ const upper = values.map((v) => v + h)
+ const lower = values.map((v) => v - h)
+ return [lower, upper]
+}
+
+export function trendLine(values: number[], fitUpTo?: number): number[] {
+ const n = values.length
+ if (n < 2) {
+ return values
+ }
+ const fitEnd = fitUpTo != null ? Math.max(2, Math.min(fitUpTo, n)) : n
+ const coordinates: [number, number][] = values.slice(0, fitEnd).map((y, x) => [x, y])
+ const { m, b } = linearRegression(coordinates)
+ return values.map((_, x) => m * x + b)
+}
+
+export function movingAverage(values: number[], intervals: number = 7): number[] {
+ const n = values.length
+ if (n < intervals) {
+ return values
+ }
+ return values.map((_, index) => {
+ const start = Math.max(0, index - Math.floor(intervals / 2))
+ const end = Math.min(n, start + intervals)
+ const actualStart = Math.max(0, end - intervals)
+ const slice = values.slice(actualStart, end)
+ return slice.reduce((sum, val) => sum + val, 0) / slice.length
+ })
+}
diff --git a/frontend/src/lib/hog-charts/utils/y-formatters.ts b/frontend/src/lib/hog-charts/utils/y-formatters.ts
index 20b1f3bbbd83..392938c2a81b 100644
--- a/frontend/src/lib/hog-charts/utils/y-formatters.ts
+++ b/frontend/src/lib/hog-charts/utils/y-formatters.ts
@@ -1,5 +1,11 @@
-import { compactNumber, humanFriendlyCurrency, humanFriendlyDuration, humanFriendlyNumber, percentage } from 'lib/utils'
-import { formatCurrency } from 'lib/utils/geography/currency'
+import {
+ compactNumber,
+ formatCurrency,
+ humanFriendlyCurrency,
+ humanFriendlyDuration,
+ humanFriendlyNumber,
+ percentage,
+} from './format'
export type YAxisFormat =
| 'numeric'
@@ -21,12 +27,6 @@ export interface YFormatterConfig {
currency?: string
}
-// `formatCurrency` requires a `CurrencyCode` enum imported from `~/queries/schema/...`,
-// which `lib/hog-charts` cannot pull in. The runtime call uses `getCurrencySymbol`
-// which already validates the string, so the cast is safe — invalid codes throw and
-// fall through to the `humanFriendlyCurrency` branch below.
-const formatCurrencyAny = formatCurrency as (amount: number, currency: string) => string
-
export function buildYTickFormatter(config: YFormatterConfig): (value: number) => string {
const { format, prefix, suffix, decimalPlaces, minDecimalPlaces, currency } = config
return (value: number): string => {
@@ -46,7 +46,7 @@ export function buildYTickFormatter(config: YFormatterConfig): (value: number) =
break
case 'currency':
try {
- formatted = currency ? formatCurrencyAny(value, currency) : humanFriendlyCurrency(value)
+ formatted = currency ? formatCurrency(value, currency) : humanFriendlyCurrency(value)
} catch {
formatted = humanFriendlyCurrency(value)
}