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(charts): delete the Chart.js LegacySparkline path (#88049)

Sam Pennington301f0f9b7d6f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e610f41e0f2d..e247741646bd 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1944,22 +1944,18 @@ snapshots:
hash: v1.k794b7964.65da75bd15e9d0d9f2e575e4eb04e0aaafdb39e02dbc19ba5006cf3651cb792d.zeJ6dGjiWJ_9biIrGypyok73SsFJJ-NLmGNHZJDCJ-w
components-sparkline--bar-chart--light:
hash: v1.k794b7964.6eb3adde804dad4d1679afdac8ba0885d492ce67b8b9e6165a8c249f44ecdd15.WmlBW3Ty9XLHt-AeaJBxjzmnlYaDXpGa28EO2xhdVvo
- components-sparkline--bar-chart-quill--dark:
- hash: v1.k794b7964.65da75bd15e9d0d9f2e575e4eb04e0aaafdb39e02dbc19ba5006cf3651cb792d.4h71v2aMuCoUCk73AbsUPFhaiOPh4OZNrsDfJF_hB8g
- components-sparkline--bar-chart-quill--light:
- hash: v1.k794b7964.6eb3adde804dad4d1679afdac8ba0885d492ce67b8b9e6165a8c249f44ecdd15.ch68xtIx6_gqRUW9iJtAYsQgLI9yWafMHdNiABRmSOM
- components-sparkline--line-chart-quill--dark:
- hash: v1.k794b7964.3f80f2e2ad5ecb11b49b40e0c8293cbbbb1b8ff2309dac2352e61106a558ad31.FIhBn_k2DHJBVrbBtjcsJ98lzMyE3WX314pjRXPaL3o
- components-sparkline--line-chart-quill--light:
- hash: v1.k794b7964.8a485c8268bf80fc31f15248a14e8313792aab3dcbd19cec7f9b2d949f77cd40.pK48prQY4E_mKVhX9AieWtWjecgVHYLG7_JlTdBx_Gg
- components-sparkline--stacked-bar-chart-quill--dark:
- hash: v1.k794b7964.8b8cfdf1368aca38505c7d33c1325cfabe1182bd63ee2c24f26c2c81d2169d6e.jqQyZDit67S6ex-m780qpZoPElLpC3ta6xDR8H6iCfA
- components-sparkline--stacked-bar-chart-quill--light:
- hash: v1.k794b7964.2acecce6124d42c05297ea6becbc68fe4c2e5683d963123df0be9c159746e838.MvDZ47SSb1LeD59U3glRLe8gM_bDBfLCPzaxRdnaI40
- components-sparkline--timeseries-chart--dark:
- hash: v1.k794b7964.69943832ea0d231f0a5600318dea944b617e1109f8075b233905915790d08b8d.qzAP9q8SkcIOogn967c1ONIEcKJxILqd1oDgYk9jYCE
- components-sparkline--timeseries-chart--light:
- hash: v1.k794b7964.df56709971c9a0136fe2c85721186e6609a414d145ac480bd55d832a17b6a5bb.GLDpGByihHQ4DiRSmydjZMBZ36Hky9i_zbrYvmtiGdU
+ components-sparkline--line-chart--dark:
+ hash: v1.k794b7964.3f80f2e2ad5ecb11b49b40e0c8293cbbbb1b8ff2309dac2352e61106a558ad31._AbrkfIqGVOYD6HOLBLiueDLLOE8XbkBDcF8By8s_Js
+ components-sparkline--line-chart--light:
+ hash: v1.k794b7964.8a485c8268bf80fc31f15248a14e8313792aab3dcbd19cec7f9b2d949f77cd40.7Khnxp0PY3tcX5Fa8iF31K8EiKJMLLhhBlrRAsVcFwI
+ components-sparkline--stacked-bar-chart--dark:
+ hash: v1.k794b7964.8b8cfdf1368aca38505c7d33c1325cfabe1182bd63ee2c24f26c2c81d2169d6e.vODMyiusSeP6H3FnueJ28hUyIKt4xPhruXBi5Uabm_Q
+ components-sparkline--stacked-bar-chart--light:
+ hash: v1.k794b7964.2acecce6124d42c05297ea6becbc68fe4c2e5683d963123df0be9c159746e838.E_crPp64rlQJ-xBqAx_Ib3XVwI40uh4AxWzih8vUtEU
+ components-sparkline--timeseries--dark:
+ hash: v1.k794b7964.ca55690558d6edbfea3cb20f468e3668b0df923a67cdcac7744292c71f3bfe9d.7AXp9ihpLb6sTo90gPTM071PERJHw0L_AuZsw8SGcHo
+ components-sparkline--timeseries--light:
+ hash: v1.k794b7964.58f4bdca2d732007bcf6e1ca4c3bfee15021c79b5f09e04042db4e750ca52331.yP8LO_DAqYpCbilVH94-4SDMLbysndTF4fnGorMCVm8
components-sso-select--sso-select--dark:
hash: v1.k794b7964.173067780026a31bcbd328a0e5a49417da614e9a7283ac96deee462f4264b5f4.PrHHHFIdmzwaKRJ22Ws7bY9ytpe5sqUavscBvrUhkcI
components-sso-select--sso-select--light:
@@ -2021,17 +2017,17 @@ snapshots:
components-usage-limit-paywall--without-current-usage--light:
hash: v1.k794b7964.a1c0eb7d57fada7673c06c4479c1f6cfaa6988e33fb856d960c3c4f15252c90b.SYDcL2rptYSzwBw4TLb4Bh10L03ul2djTsovjkeFnUY
components-usagemetriccard--long-metric-name-truncates--dark:
- hash: v1.k794b7964.8817ba0dc8bf42ede90722428d3557f85ffdc683440ee7bb1985b84cb8443adc.WKXtTZJiClbqbbbvb_2elWMRSyBVb2go1uldHswTyjA
+ hash: v1.k794b7964.786f48f287185a1248302b817872e977ea02b68f6302ad6931fc10cee3076580.bJ4fJRue7QaTii_AFx_8LJU0MFZr3r7X3h1hfQSpOcw
components-usagemetriccard--long-metric-name-truncates--light:
- hash: v1.k794b7964.f5b8a2f5582a2ef7cabb567df2ccb6061f0c7367031e67b15e8c2f40f01a00e2.k_nfdzfFMGyZXkmoJMS_oXrBOR6xT1tHjPcwa0a37ec
+ hash: v1.k794b7964.4fc3ddb75598d73a81b4b411f37e61729ea677257a9d14ee9fc1df4f45968db5.gZ-7ZZYYIDJ8yIlG4E0frC61tlORW2-R-ljZJEIWHiQ
components-usagemetriccard--mixed-grid-at-narrow-breakpoint--dark:
- hash: v1.k794b7964.483570de82e4a01707d6568f6914cdfc4bd3cf2a12959230b2bb902d2039b7bb.AKloV0nHtGRv9cQdnVIaud_a_QgkFVzJ1XyTVeNZjFo
+ hash: v1.k794b7964.2db0bddcff5e93fdffbe2c3d7cf56672354e91952fa78c283c1005cc9bada3c6.Qw98fmEtdeck01NI1_IcZr6DmFmy6Z_GPhOlkArtsks
components-usagemetriccard--mixed-grid-at-narrow-breakpoint--light:
- hash: v1.k794b7964.7251df94db025f0c3168631fdf3cb73d350e78be800e8b521628dd856c34ebd0.NGr9vDfonQeTHL0-75N05gpKR1WECAKtSDJhdnS9Uy0
+ hash: v1.k794b7964.5c31b559d2ee365b74cbd1edf93ba0045f837d4eda3001a06a432a89eca1d024.Vg_-Q9kQLWfYVKxarebRCXmS-Jon3DN-1_gtd6RM_QQ
components-usagemetriccard--null-trend--dark:
- hash: v1.k794b7964.fd4e5573a396e73c3d79ee50663c4d9715477429a05d008f66f28564b45f3c48.oZCn7_6bvzweKs_5ISVqTM2ekPfs3dbuPNmTnVL38fs
+ hash: v1.k794b7964.8ea9bc2eb30c1f93dea56243cc3d76438962281e956832a1764c5bdec4a2ec39._ku02CSQwRpOuGCeoBWOuG1Xo4WgcObOV49AhLTag0M
components-usagemetriccard--null-trend--light:
- hash: v1.k794b7964.8ed08bdd55dbfe84d2855b6823c47d88c57125212fda8bee43bdb420dcac8a1f.n-RYdD-Epm2uFiQGOSdCAsXRPdbUs2RQuhRK57ZsEpY
+ hash: v1.k794b7964.1b1543de51a82e7359b49e1e9eec4d535a4404905d94102be3047d4fc87e7093.-SMG2-BkYZxBusdMXQCdWnSKT2zD1h2SCXJ9pZCGytE
components-usagemetriccard--number-card--dark:
hash: v1.k794b7964.cb6d6a93745be605fda83ec887ca813efcc618d3652cc4006b8b21e90fba3faf.mWprxMswqWc4YgylZXN1yehXJx5Xm4nuM4WpiPZLLbY
components-usagemetriccard--number-card--light:
@@ -2045,9 +2041,9 @@ snapshots:
components-usagemetriccard--skeleton--light:
hash: v1.k794b7964.cb37ec44dd2bbdfb33dcd158e7cad95ee6f6dd80e2e53fea5bac4750d91f9a93.R-IrcLcDX6VckPKUcIG3TEdEnCGTmgn4TUPvS6A3zJY
components-usagemetriccard--sparkline-card--dark:
- hash: v1.k794b7964.ad312a3f0ac8497246980a21b2ad8e2f1179dc882249ed71afe0b0492f666abe.Vl0cxCk8kIGEHxMrDcK7hREs2lshCksBJ0E-uN1vBVQ
+ hash: v1.k794b7964.0ee6e2fe7b674821b683bd3315b4c1d76621c87605acd9863ba7b34d09809c47.fYUDyDfYWcTazSvMiG248bvMsmGaXEeTjVXP_zBs8Vg
components-usagemetriccard--sparkline-card--light:
- hash: v1.k794b7964.122ca821c9ea402e93199503df00d6f40973761b0e9d3ca199079bfbb73ddf48.pPCBgvS9-sbzQ0l4CJVCkJmylh6sHunNHaxPS4DuA5s
+ hash: v1.k794b7964.0eb621333b704929d1c7878250cd54ffe0e65d25e1aee1aad1279c91c278bd17.nKqzXeEKwJoscSotvb-zZDPSYT4CCre-kJLk2J9WsNM
components-verticalnesteddnd--base--dark:
hash: v1.k794b7964.536f41c62e83935877a0b961d6b2a1aa0e4199dfab49f84587178447e844a8ba.tpDdDBmJuJBZKOX_RFz8CcNUGsUdse6LfVJWG1XNDeQ
components-verticalnesteddnd--base--light:
diff --git a/frontend/src/lib/components/AppMetrics/AppMetricsSparkline.tsx b/frontend/src/lib/components/AppMetrics/AppMetricsSparkline.tsx
index b55b9c535669..5f7343a93ade 100644
--- a/frontend/src/lib/components/AppMetrics/AppMetricsSparkline.tsx
+++ b/frontend/src/lib/components/AppMetrics/AppMetricsSparkline.tsx
@@ -68,7 +68,7 @@ export function AppMetricsSparkline({
) : !appMetricsTrends || appMetricsTrendsLoading ? (
<LemonSkeleton className="h-8 max-w-24" />
) : (
- <Sparkline labels={labels} data={displayData} className="h-8 max-w-24" maximumIndicator={false} />
+ <Sparkline labels={labels} data={displayData} className="h-8 max-w-24" />
)}
</div>
)
diff --git a/frontend/src/lib/components/Sparkline.stories.tsx b/frontend/src/lib/components/Sparkline.stories.tsx
index 558b5cac05d4..225153e6562d 100644
--- a/frontend/src/lib/components/Sparkline.stories.tsx
+++ b/frontend/src/lib/components/Sparkline.stories.tsx
@@ -2,94 +2,58 @@ import type { Meta, StoryObj } from '@storybook/react'
import { dayjs } from 'lib/dayjs'
-import { AnyScaleOptions, QuillSparkline, Sparkline, SparklineProps } from './Sparkline'
+import { Sparkline, SparklineProps } from './Sparkline'
type Story = StoryObj<SparklineProps>
const meta: Meta<SparklineProps> = {
title: 'Components/Sparkline',
component: Sparkline,
- render: (args) => {
- return <Sparkline {...args} className="w-full" />
- },
+ render: (args) => <Sparkline {...args} className="w-64 h-16" />,
}
export default meta
+const LABELS = ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']
+
export const BarChart: Story = {
args: {
data: [10, 5, 3, 30, 22, 10, 2],
- labels: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
+ labels: LABELS,
},
// `Sparkline` now dispatches to the quill chart, whose canvas has no intrinsic size, so the
// wrapper needs an explicit height — a bare `w-full` collapses to zero height under the runner.
render: (args) => <Sparkline {...args} className="w-64 h-16" />,
}
-const dataRange = Array.from({ length: 50 }, (_, i) => i)
-export const TimeseriesChart: Story = {
+export const StackedBarChart: Story = {
args: {
data: [
- {
- name: 'occurrence',
- values: dataRange.map(() => Math.floor(Math.random() * 100)),
- color: 'primitive-neutral-800',
- hoverColor: 'primary-3000',
- },
+ { name: 'success', values: [10, 5, 3, 30, 22, 10, 2], color: 'success' },
+ { name: 'failure', values: [1, 0, 2, 4, 0, 1, 0], color: 'danger' },
],
- labels: dataRange.map((i) => dayjs().subtract(i, 'day').format()),
- renderLabel: (label) => dayjs(label).format('MMM D'),
- withXScale: (scale: AnyScaleOptions) => {
- return {
- ...scale,
- type: 'timeseries',
- ticks: {
- ...scale.ticks,
- display: true,
- maxRotation: 0,
- maxTicksLimit: 5,
- },
- time: {
- unit: 'day',
- round: 'day',
- displayFormats: {
- day: 'MMM D',
- },
- },
- } as AnyScaleOptions
- },
+ labels: LABELS,
},
}
-// Quill-rendered variants, for side-by-side comparison with the legacy stories above. These
-// render `QuillSparkline` directly: the dispatch in `Sparkline` is unusable under Storybook,
-// whose implicit-action args inject an `onSelectionChange` spy that the dispatch reads as a
-// legacy-only feature. The quill chart paints onto an absolutely-positioned canvas that adds no
-// intrinsic size, so the wrapper needs an explicit width and height — a `w-full` here would
-// collapse to a zero-width, unsnapshottable root under the test runner.
-export const BarChartQuill: Story = {
+export const LineChart: Story = {
args: {
data: [10, 5, 3, 30, 22, 10, 2],
- labels: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
+ labels: LABELS,
+ type: 'line',
+ color: 'success',
},
- render: (args) => <QuillSparkline {...args} className="w-64 h-16" />,
}
-export const StackedBarChartQuill: Story = {
+const dataRange = Array.from({ length: 50 }, (_, i) => i)
+export const Timeseries: Story = {
args: {
data: [
- { name: 'success', values: [10, 5, 3, 30, 22, 10, 2], color: 'success' },
- { name: 'failure', values: [1, 0, 2, 4, 0, 1, 0], color: 'danger' },
+ {
+ name: 'occurrence',
+ values: dataRange.map((i) => (i * 37) % 100),
+ color: 'primitive-neutral-800',
+ },
],
- labels: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
- },
- render: (args) => <QuillSparkline {...args} className="w-64 h-16" />,
-}
-
-export const LineChartQuill: Story = {
- args: {
- data: [10, 5, 3, 30, 22, 10, 2],
- labels: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
- type: 'line',
- color: 'success',
+ labels: dataRange.map((i) => dayjs().subtract(i, 'day').format()),
+ renderLabel: (label) => dayjs(label).format('MMM D'),
},
- render: (args) => <QuillSparkline {...args} className="w-64 h-16" />,
}
diff --git a/frontend/src/lib/components/Sparkline.test.tsx b/frontend/src/lib/components/Sparkline.test.tsx
index 586abba102ff..1b154e9ae88b 100644
--- a/frontend/src/lib/components/Sparkline.test.tsx
+++ b/frontend/src/lib/components/Sparkline.test.tsx
@@ -33,34 +33,10 @@ function renderSparkline(props: SparklineProps): void {
render(<Sparkline {...props} />)
}
-// Quill charts label their main canvas for a11y and add an aria-hidden hover-overlay canvas;
-// the legacy Chart.js canvas carries neither attribute.
-const quillCanvas = (): Element | null => document.querySelector('canvas[aria-label]')
-const legacyCanvas = (): Element | null => document.querySelector('canvas:not([aria-label]):not([aria-hidden])')
-
const DATA = [10, 5, 3, 30]
const LABELS = ['Mon', 'Tue', 'Wed', 'Thu']
describe('Sparkline', () => {
- it('renders via quill when only simple props are used', () => {
- renderSparkline({ data: DATA, labels: LABELS })
- expect(quillCanvas()).toBeTruthy()
- expect(legacyCanvas()).toBeNull()
- })
-
- it.each<{ feature: string; props: Partial<SparklineProps> }>([
- { feature: 'onSelectionChange', props: { onSelectionChange: () => {} } },
- { feature: 'highlightedRange', props: { highlightedRange: { xMin: 'Mon', xMax: 'Tue' } } },
- { feature: 'incompleteBars', props: { incompleteBars: { indices: [3] } } },
- { feature: 'referenceLines', props: { referenceLines: [{ value: 20 }] } },
- { feature: 'withXScale', props: { withXScale: (x) => x } },
- { feature: 'withYScale', props: { withYScale: (y) => y } },
- ])('keeps Chart.js when $feature is passed', ({ props }) => {
- renderSparkline({ data: DATA, labels: LABELS, ...props })
- expect(legacyCanvas()).toBeTruthy()
- expect(quillCanvas()).toBeNull()
- })
-
it.each<{ shape: string; data: SparklineProps['data']; seriesCount: number }>([
{ shape: 'a flat number array', data: DATA, seriesCount: 1 },
{
@@ -77,8 +53,6 @@ describe('Sparkline', () => {
})
it('wires tooltip formatting and zero-row filtering through to the quill tooltip', async () => {
- // Line type: bar charts hit-test the cursor against filled segments before showing a
- // tooltip, while lines surface all series — and the tooltip wiring under test is shared.
renderSparkline({
data: [
{ name: 'volume', values: [10, 0, 3, 30] },
@@ -96,7 +70,7 @@ describe('Sparkline', () => {
// The portal mounts before its content commits, so poll until the header lands.
await waitFor(() => expect(tooltip.label()).toBe('Day: Wed'))
expect(tooltip.value('volume')).toBe('$3.00')
- expect(tooltip.rows()).toEqual(['volume']) // the zero 'errors' row is hidden
+ expect(tooltip.rows()).toEqual(['volume'])
})
it('shows a skeleton instead of a chart while loading', () => {
diff --git a/frontend/src/lib/components/Sparkline.tsx b/frontend/src/lib/components/Sparkline.tsx
index f0bced9cca01..a3eae5514442 100644
--- a/frontend/src/lib/components/Sparkline.tsx
+++ b/frontend/src/lib/components/Sparkline.tsx
@@ -1,41 +1,14 @@
-import annotationPlugin from 'chartjs-plugin-annotation'
import clsx from 'clsx'
-import { useCallback, useMemo, useRef, useState } from 'react'
+import { useCallback, useMemo } from 'react'
-import { IconWarning } from '@posthog/icons'
-import { Popover } from '@posthog/lemon-ui'
import { DefaultTooltip, Sparkline as QuillSparklineChart, useChartTheme } from '@posthog/quill-charts'
import type { Series, TooltipContext } from '@posthog/quill-charts'
-import { Chart, ScaleOptions, TooltipModel } from 'lib/Chart'
import { getColorVar } from 'lib/colors'
-import { useChart } from 'lib/hooks/useChart'
-import { useEventListener } from 'lib/hooks/useEventListener'
-import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
-import { useLingeringTooltip } from 'lib/hooks/useLingeringTooltip'
-import { hexToRGBA } from 'lib/utils/colors'
import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
import { LemonSkeleton } from '../lemon-ui/LemonSkeleton'
-// Register once at module load. Chart.register is idempotent so re-registers (eg. by
-// AlertHistoryChart, which also uses the annotation plugin) are safe.
-Chart.register(annotationPlugin)
-
-const HIGHLIGHT_COLOR = '#8f8f8f'
-
-export interface SparklineReferenceLine {
- /** Y-axis value the dashed line is drawn at, in the same units as the series data. */
- value: number
- /** Color name from `vars.scss` (e.g. 'danger'). @default 'danger' */
- color?: string
- /** Optional label to anchor at the end of the line (shown only when provided). */
- label?: string
- /** Where to anchor the optional label. @default 'end' */
- labelPosition?: 'start' | 'center' | 'end'
-}
-
export interface SparklineTimeSeries {
name: string
values: number[]
@@ -44,22 +17,6 @@ export interface SparklineTimeSeries {
hoverColor?: string
}
-export interface SparklineMarker {
- /**
- * X position in the x-axis's own units: epoch ms (or a parseable date string) for a
- * time scale, a label for a category scale.
- */
- xValue: number | string
- /** Y position in data units. Omit to pin the marker to the bottom of the chart. */
- yValue?: number
- /** Color name from `vars.scss`. @default 'primary' */
- color?: string
- /** Makes the marker clickable (e.g. to open the trace behind an exemplar). */
- onClick?: () => void
-}
-
-export type AnyScaleOptions = ScaleOptions<'linear' | 'logarithmic' | 'time' | 'timeseries' | 'category'>
-
export interface SparklineProps {
/** Either a list of numbers for a muted graph or an array of time series */
data: number[] | SparklineTimeSeries[]
@@ -73,57 +30,19 @@ export interface SparklineProps {
labels?: string[]
/** @default 'bar' */
type?: 'bar' | 'line'
- /** Whether the Y-axis maximum should be indicated in the graph. @default true */
- maximumIndicator?: boolean
/** A skeleton is shown during loading. */
loading?: boolean
- /** Update the X-axis scale. */
- withXScale?: (x: AnyScaleOptions) => AnyScaleOptions
- /** Update the Y-axis scale. */
- withYScale?: (y: AnyScaleOptions) => AnyScaleOptions
/** Render a label for the tooltip. */
renderLabel?: (label: string) => string
className?: string
- onSelectionChange?: (selection: { startIndex: number; endIndex: number }) => void
- /** Maximum number of series to show in tooltip. @default 8 */
- tooltipRowCutoff?: number
/** Hide series with zero values from tooltip. @default false */
hideZerosInTooltip?: boolean
/** Sort tooltip items by count (descending). @default false */
sortTooltipByCount?: boolean
- /** Optional horizontal dashed reference lines (thresholds, goals, limits). */
- referenceLines?: SparklineReferenceLine[]
- /**
- * Point markers drawn over the chart (e.g. trace exemplars). Hover shows the marker's
- * label; a marker with `onClick` is clickable.
- */
- markers?: SparklineMarker[]
/** Format the per-series tooltip value. Defaults to `humanFriendlyNumber`. */
renderTooltipValue?: (value: number) => string
- /**
- * X-axis value range to highlight as a translucent box behind the bars. Values are
- * in the x-axis's own units: epoch ms for a time scale (positioned with sub-bar
- * precision), or a label for a category scale. Used to mirror an external selection
- * (e.g. the rows currently visible in a paired virtualized list) onto the chart.
- * Callers pass an already-ordered `xMin <= xMax`; pass `null`/`undefined` to clear.
- */
- highlightedRange?: { xMin: number | string; xMax: number | string } | null
- /**
- * Bar indices that are still being ingested (incomplete). Those bars render with a faded
- * diagonal-hatch fill, and hovering one adds `tooltip` to the hover tooltip. Used to flag the
- * most recent bucket(s) when ingestion hasn't caught up. Pass `null`/`undefined` or an empty
- * `indices` array to clear.
- */
- incompleteBars?: { indices: number[]; tooltip?: string } | null
- /**
- * Let the pointer move onto the tooltip without dismissing it, so a tooltip taller than its
- * max height can be scrolled. Off by default: an interactive tooltip sits over the canvas and
- * would swallow clicks meant for the chart (e.g. clickable markers or drag-to-select).
- */
- interactiveTooltip?: boolean
}
-/** Normalize the permissive `data` prop into one `SparklineTimeSeries` per series. */
function normalizeSparklineData(
data: SparklineProps['data'],
name?: string,
@@ -173,31 +92,13 @@ function sparklineClassName(dataPointCount: number, className?: string): string
)
}
-export function Sparkline(props: SparklineProps): JSX.Element {
- // Features the quill path doesn't cover yet. Consumers passing them stay on Chart.js until
- // their migration wave lands.
- const needsLegacyFeatures = !!(
- props.onSelectionChange ||
- props.highlightedRange ||
- props.incompleteBars?.indices?.length ||
- props.referenceLines?.length ||
- props.markers?.length ||
- props.withXScale ||
- props.withYScale
- )
- return needsLegacyFeatures ? <LegacySparkline {...props} /> : <QuillSparkline {...props} />
-}
-
-/** Legacy consumers pass vars.scss color names ('success', 'danger', 'muted'); quill takes CSS colors. */
+/** Consumers pass vars.scss color names ('success', 'danger', 'muted'); quill takes CSS colors. */
function resolveSparklineColor(color: string | undefined): string {
const value = color || 'muted'
return /^(#|rgb|hsl|var\()/.test(value) ? value : getColorVar(value)
}
-/** The quill rendering path. Exported for Storybook only — the dispatch in `Sparkline` is
- * unusable there (Storybook's implicit-action args inject an `onSelectionChange` spy, which the
- * dispatch reads as a legacy-only feature). Consumers always use `Sparkline`. */
-export function QuillSparkline({
+export function Sparkline({
data,
color,
colors,
@@ -262,440 +163,3 @@ export function QuillSparkline({
</div>
)
}
-
-/**
- * Build a faded diagonal-hatch CanvasPattern for an incomplete bar: a translucent fill of the series
- * colour overlaid with hatch lines, so the bar reads as "still loading" while keeping its colour.
- */
-function createHashedPattern(color: string): CanvasPattern | string {
- const size = 6
- const canvas = document.createElement('canvas')
- canvas.width = size
- canvas.height = size
- const ctx = canvas.getContext('2d')
- if (!ctx) {
- return color
- }
- ctx.fillStyle = hexToRGBA(color, 0.25)
- ctx.fillRect(0, 0, size, size)
- ctx.strokeStyle = hexToRGBA(color, 0.6)
- ctx.lineWidth = 1
- // Three offset diagonals so the hatch tiles seamlessly across the bar.
- ctx.beginPath()
- ctx.moveTo(0, size)
- ctx.lineTo(size, 0)
- ctx.moveTo(-1, 1)
- ctx.lineTo(1, -1)
- ctx.moveTo(size - 1, size + 1)
- ctx.lineTo(size + 1, size - 1)
- ctx.stroke()
- return ctx.createPattern(canvas, 'repeat') ?? color
-}
-
-function LegacySparkline({
- data,
- color,
- colors,
- name,
- names,
- labels,
- type = 'bar',
- maximumIndicator = true,
- loading = false,
- withXScale,
- withYScale,
- renderLabel,
- onSelectionChange,
- className,
- tooltipRowCutoff,
- hideZerosInTooltip = false,
- sortTooltipByCount = false,
- referenceLines,
- renderTooltipValue,
- highlightedRange,
- incompleteBars,
- markers,
- interactiveTooltip = false,
-}: SparklineProps): JSX.Element {
- const tooltipRef = useRef<HTMLDivElement | null>(null)
-
- const [tooltip, setTooltip] = useState<TooltipModel<'bar'> | null>(null)
- const dragStartRef = useRef<{ index: number; x: number } | null>(null)
- const [isDragging, setIsDragging] = useState(false)
-
- const incompleteBarSet = useMemo(() => new Set(incompleteBars?.indices ?? []), [incompleteBars])
-
- const adjustedData: SparklineTimeSeries[] = useMemo(
- () => normalizeSparklineData(data, name, names, color, colors),
- [data] // oxlint-disable-line react-hooks/exhaustive-deps
- )
-
- const { canvasRef } = useChart({
- getConfig: () => {
- // data should always be provided but React can render this without it,
- // so, fall back to null for safety
- if (data === undefined || data.length === 0) {
- return null
- }
- const defaultXScale: AnyScaleOptions = {
- // X axis not needed in line charts without indicators
- display: type === 'bar' || maximumIndicator,
- bounds: 'data',
- stacked: true,
- ticks: {
- display: false,
- },
- grid: {
- drawTicks: false,
- display: false,
- },
- alignToPixels: true,
- }
-
- // Make sure reference lines always fit on the chart — Chart.js would otherwise
- // auto-scale to the data only and a threshold above the peak would be clipped.
- const referenceLineMax =
- referenceLines && referenceLines.length > 0 ? Math.max(...referenceLines.map((l) => l.value)) : 0
-
- const defaultYScale: AnyScaleOptions = {
- // We use the Y axis for the maximum indicator
- display: maximumIndicator,
- bounds: 'data',
- min: 0, // Always starting at 0
- // Headroom above whichever is taller — data or a reference line — so a threshold
- // sitting near the chart top still has room for its label without clipping.
- suggestedMax: referenceLineMax > 0 ? referenceLineMax * 1.2 : 1,
- stacked: true,
- ticks: {
- includeBounds: true,
- autoSkip: true,
- maxTicksLimit: 1, // Only the max
- align: 'start',
- callback: (tickValue) =>
- typeof tickValue === 'number' && tickValue > 0 // Hide the zero tick
- ? humanFriendlyNumber(tickValue)
- : null,
- font: {
- size: 10,
- lineHeight: 1,
- },
- },
- grid: {
- tickBorderDash: [2],
- display: true,
- tickLength: 0,
- },
- border: { display: false },
- alignToPixels: true,
- afterFit: (axis) => {
- // Remove unnecessary padding
- axis.paddingTop = 1 // 1px and not 0 to avoid clipping of the grid
- axis.paddingBottom = 1
- },
- }
-
- const xScale = withXScale ? withXScale(defaultXScale) : defaultXScale
- const yScale = withYScale ? withYScale(defaultYScale) : defaultYScale
-
- return {
- type,
- data: {
- labels: labels || adjustedData[0].values.map((_, i) => `Entry ${i}`),
- datasets: adjustedData.map((timeseries) => {
- const seriesColor = getColorVar(timeseries.color || 'muted')
- const hoverColor = getColorVar(timeseries.hoverColor || timeseries.color || 'muted')
- // Incomplete (still-ingesting) bars get a faded hatch of the series colour so
- // they read as "not final" without losing which series they belong to.
- const hatched = incompleteBarSet.size > 0 ? createHashedPattern(seriesColor) : null
- const fillFor = (
- base: string
- ): typeof base | CanvasPattern | ((ctx: { dataIndex: number }) => string | CanvasPattern) =>
- hatched
- ? (ctx: { dataIndex: number }) => (incompleteBarSet.has(ctx.dataIndex) ? hatched : base)
- : base
- return {
- label: timeseries.name,
- data: timeseries.values,
- minBarLength: 0,
- categoryPercentage: 0.9, // Slightly tighter bar spacing than the default 0.8
- backgroundColor: fillFor(seriesColor),
- hoverBackgroundColor: fillFor(hoverColor),
- borderColor: seriesColor,
- borderWidth: type === 'line' ? 2 : 0,
- pointRadius: 0,
- borderRadius: 2,
- }
- }),
- },
- options: {
- scales: {
- x: xScale,
- y: yScale,
- },
- plugins: {
- crosshair: false,
- legend: {
- display: false,
- },
- tooltip: {
- enabled: false, // Using external tooltip
- external({ tooltip }) {
- // We spread it otherwise it just ends up being a reference to the tooltip object
- setTooltip({ ...tooltip } as TooltipModel<'bar'>)
- },
- },
- ...(() => {
- const annotations: Record<string, any> = {}
-
- if (referenceLines && referenceLines.length > 0) {
- referenceLines.forEach((line, i) => {
- const lineColor = getColorVar(line.color || 'danger')
- annotations[`referenceLine${i}`] = {
- type: 'line',
- yMin: line.value,
- yMax: line.value,
- borderColor: lineColor,
- borderWidth: 1.5,
- borderDash: [5, 4],
- ...(line.label
- ? {
- label: {
- display: true,
- content: line.label,
- position: line.labelPosition || 'end',
- font: { size: 9 },
- color: lineColor,
- backgroundColor: 'transparent',
- // Sit the label just above the line so it doesn't render on top of it.
- // The 20% y-axis headroom set above guarantees it stays inside the chart.
- yAdjust: -8,
- },
- }
- : {}),
- }
- })
- }
-
- if (highlightedRange && labels && labels.length > 0) {
- annotations.highlightedRange = {
- type: 'box',
- xMin: highlightedRange.xMin,
- xMax: highlightedRange.xMax,
- // Drawn under the bars so the data stays legible.
- drawTime: 'beforeDatasetsDraw',
- // Faint fill with a stronger border to mark the window edges.
- backgroundColor: hexToRGBA(HIGHLIGHT_COLOR, 0.1),
- borderColor: hexToRGBA(HIGHLIGHT_COLOR, 0.8),
- borderWidth: 1,
- }
- }
-
- if (markers && markers.length > 0) {
- markers.forEach((marker, i) => {
- const markerColor = getColorVar(marker.color || 'primary')
- annotations[`marker${i}`] = {
- type: 'point',
- xValue: marker.xValue,
- // Markers don't participate in autoscaling, so an absent
- // yValue pins to the bottom of whatever range the data set —
- // exemplar-tick style, immune to out-of-range raw values.
- yValue:
- marker.yValue ?? ((ctx: { chart: Chart }) => ctx.chart.scales.y?.min ?? 0),
- radius: 4,
- backgroundColor: hexToRGBA(markerColor, 0.85),
- borderColor: markerColor,
- borderWidth: 1,
- // enter/leave double as hover affordance for clickable markers.
- enter: (ctx: { chart: Chart; element: { options: { radius: number } } }) => {
- ctx.element.options.radius = 6
- if (marker.onClick) {
- ctx.chart.canvas.style.cursor = 'pointer'
- }
- return true
- },
- leave: (ctx: { chart: Chart; element: { options: { radius: number } } }) => {
- ctx.element.options.radius = 4
- ctx.chart.canvas.style.cursor = ''
- return true
- },
- ...(marker.onClick ? { click: () => marker.onClick?.() } : {}),
- }
- })
- }
-
- return Object.keys(annotations).length > 0 ? { annotation: { annotations } } : {}
- })(),
- },
- maintainAspectRatio: false,
- interaction: {
- mode: 'index',
- axis: 'x',
- intersect: false,
- },
- },
- }
- },
- deps: [
- labels,
- adjustedData,
- withXScale,
- withYScale,
- renderLabel,
- data,
- maximumIndicator,
- type,
- referenceLines,
- highlightedRange,
- incompleteBars,
- markers,
- ],
- })
-
- const finalClassName = sparklineClassName(adjustedData[0]?.values?.length || 0, className)
-
- // Chart.js keeps `dataPoints` populated after it zeroes `opacity`, so the content survives the
- // linger — only visibility needs holding open.
- const {
- visible: tooltipVisible,
- onMouseEnter: onTooltipMouseEnter,
- onMouseLeave: onTooltipMouseLeave,
- } = useLingeringTooltip(!!(tooltip && tooltip.opacity > 0), interactiveTooltip)
- const toolTipDataPoints = tooltip && tooltip.dataPoints ? tooltip.dataPoints : []
-
- const hoveredElementX = toolTipDataPoints[0]?.element?.x ?? 0
- const hoveredElementWidth = (toolTipDataPoints[0]?.element as any)?.width ?? 0
-
- useKeyboardHotkeys({
- escape: {
- action: () => {
- setIsDragging(false)
- },
- },
- })
-
- useEventListener(
- 'mouseup',
- () => {
- if (!isDragging) {
- return
- }
-
- setIsDragging(false)
-
- if (!onSelectionChange || !toolTipDataPoints.length || !dragStartRef.current) {
- return
- }
-
- const startIndex = dragStartRef.current.index
- const endIndex = toolTipDataPoints[0].dataIndex
- dragStartRef.current = null
-
- if (typeof startIndex !== 'number' || typeof endIndex !== 'number') {
- return
- }
-
- if (startIndex !== endIndex) {
- onSelectionChange({
- startIndex: Math.min(startIndex, endIndex),
- endIndex: Math.max(startIndex, endIndex),
- })
- }
- },
- window,
- [isDragging, onSelectionChange]
- )
-
- const onMouseDown = (): void => {
- if (!onSelectionChange) {
- return
- }
- setIsDragging(true)
- dragStartRef.current = { index: toolTipDataPoints[0].dataIndex, x: hoveredElementX }
- }
-
- let selectionLeft = hoveredElementX
- let selectionWidth = 1
-
- if (isDragging && dragStartRef.current) {
- if (hoveredElementX === dragStartRef.current.x) {
- // If the same we just show it in the middle of the bar
- } else if (hoveredElementX > dragStartRef.current.x) {
- // If we are hovering past where we started we set it to be before the bar and after the next
- selectionLeft = dragStartRef.current.x - hoveredElementWidth / 2
- selectionWidth = hoveredElementX + hoveredElementWidth / 2 - selectionLeft
- } else {
- // If we are hovering before where we started we set it to be after the bar and before the next
- selectionLeft = hoveredElementX - hoveredElementWidth / 2
- selectionWidth = dragStartRef.current.x + hoveredElementWidth / 2 - selectionLeft
- }
- }
-
- return !loading ? (
- <div className={finalClassName} onMouseDown={onSelectionChange ? onMouseDown : undefined}>
- <canvas ref={canvasRef} />
- <>
- {tooltipVisible && onSelectionChange && (
- <div className="absolute inset-0 pointer-events-none">
- <div
- className="rounded opacity-50 border absolute"
- style={{
- left: selectionLeft ?? 0,
- width: selectionWidth,
- height: '100%',
- backgroundColor: 'rgba(0, 0, 0, 0.5)',
- }}
- />
- </div>
- )}
- <Popover
- visible={tooltipVisible}
- overlay={
- <>
- {incompleteBarSet.has(toolTipDataPoints[0]?.dataIndex) && (
- <div className="flex items-center gap-1 px-2 pt-1 text-xs text-warning">
- <IconWarning className="shrink-0" />
- {incompleteBars?.tooltip ?? 'Some logs are still processing'}
- </div>
- )}
- <InsightTooltip
- embedded
- hideInspectActorsSection
- showHeader={!!labels}
- altTitle={
- toolTipDataPoints.length > 0
- ? renderLabel
- ? renderLabel(toolTipDataPoints[0].label)
- : toolTipDataPoints[0].label
- : ''
- }
- seriesData={toolTipDataPoints
- .map((dp, i) => ({
- id: i,
- dataIndex: 0,
- datasetIndex: 0,
- order: i,
- label: dp.dataset.label,
- color: dp.dataset.borderColor as string,
- count: (dp.dataset.data?.[dp.dataIndex] as number) || 0,
- }))
- .filter((item) => !hideZerosInTooltip || item.count > 0)
- .sort((a, b) => (sortTooltipByCount ? b.count - a.count : a.order - b.order))}
- renderSeries={(value) => value}
- renderCount={(count) => (renderTooltipValue ?? humanFriendlyNumber)(count)}
- rowCutoff={tooltipRowCutoff}
- />
- </>
- }
- placement="bottom-start"
- padded={false}
- onMouseEnterInside={interactiveTooltip ? onTooltipMouseEnter : undefined}
- onMouseLeaveInside={interactiveTooltip ? onTooltipMouseLeave : undefined}
- >
- <div ref={tooltipRef} />
- </Popover>
- </>
- </div>
- ) : (
- <LemonSkeleton className={finalClassName} />
- )
-}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index cfa8394d75f5..8ef6bf5b12be 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -274,7 +274,6 @@ function CustomPropertyHistoryCell({
data={chartPoints.map(([, value]) => value)}
labels={chartPoints.map(([timestamp]) => dayjs.unix(timestamp).format('MMM D, YYYY HH:mm'))}
renderTooltipValue={formatValue}
- maximumIndicator={false}
/>
</div>
)
diff --git a/products/customer_analytics/frontend/components/UsageMetricCard.tsx b/products/customer_analytics/frontend/components/UsageMetricCard.tsx
index 45bc70b7e49a..38d397e5aeb2 100644
--- a/products/customer_analytics/frontend/components/UsageMetricCard.tsx
+++ b/products/customer_analytics/frontend/components/UsageMetricCard.tsx
@@ -88,11 +88,8 @@ export const UsageMetricCard = ({ metric }: { metric: UsageMetric }): JSX.Elemen
data={metric.timeseries}
labels={metric.timeseries_labels}
type="bar"
- maximumIndicator={false}
color="muted"
className="w-full h-full"
- withXScale={(x) => ({ ...x, display: false })}
- withYScale={(y) => ({ ...y, display: false })}
/>
</div>
)}
diff --git a/products/engineering_analytics/frontend/components/TrendCard.tsx b/products/engineering_analytics/frontend/components/TrendCard.tsx
index f2a9c4f7ed0d..1cf9aa1266dd 100644
--- a/products/engineering_analytics/frontend/components/TrendCard.tsx
+++ b/products/engineering_analytics/frontend/components/TrendCard.tsx
@@ -67,7 +67,6 @@ export function TrendCard({
name={title}
type="line"
color={lineColor}
- maximumIndicator={false}
className="h-16 w-full"
renderLabel={(label) => label}
renderTooltipValue={renderTooltipValue}
diff --git a/products/links/frontend/LinkMetricSparkline.tsx b/products/links/frontend/LinkMetricSparkline.tsx
index 9c1350dd7a9e..fc7a8788d2ee 100644
--- a/products/links/frontend/LinkMetricSparkline.tsx
+++ b/products/links/frontend/LinkMetricSparkline.tsx
@@ -26,7 +26,6 @@ export function LinkMetricSparkline({ id }: Props): JSX.Element {
labels={sparklineData?.labels}
data={displayData}
className="h-8 max-w-24"
- maximumIndicator={false}
/>
)
}
diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
index a49a3167fafd..e2345a2aa18d 100644
--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
@@ -253,12 +253,7 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {
render: (_, row) =>
row.sparkline.length ? (
<div className="w-24 h-6">
- <Sparkline
- data={row.sparkline}
- labels={sparklineLabels}
- className="w-full h-full"
- maximumIndicator={false}
- />
+ <Sparkline data={row.sparkline} labels={sparklineLabels} className="w-full h-full" />
</div>
) : (
<span className="text-muted">-</span>
diff --git a/products/logs/frontend/components/LogsServices/LogsServices.tsx b/products/logs/frontend/components/LogsServices/LogsServices.tsx
index 05ba733e352c..2eb6a90c699c 100644
--- a/products/logs/frontend/components/LogsServices/LogsServices.tsx
+++ b/products/logs/frontend/components/LogsServices/LogsServices.tsx
@@ -272,12 +272,7 @@ export function LogsServices(): JSX.Element {
}
return (
<div className="w-24 h-6">
- <Sparkline
- data={sparkline.values}
- labels={sparkline.labels}
- className="w-full h-full"
- maximumIndicator={false}
- />
+ <Sparkline data={sparkline.values} labels={sparkline.labels} className="w-full h-full" />
</div>
)
},