: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(error-tracking): migrate the volume sparkline to quill charts (#77249)
Sam Penningtonff594fa38ed4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5782be89d511..3bd6a229e8b8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1000,6 +1000,10 @@ snapshots:hash: v1.k794b7964.d73bc90081c99635a4f2375ae304c05400b3901ba3d509f8298e162c3cf667ac.wATXB75WX7nlJWS1vBM3a5slvElZHoT7vF2Rchkxxt0components-hogcharts-timeseriesbarchart--percent--light:hash: v1.k794b7964.19f53e3f52d7ddc1e43240e6213988f5342787070babed3caf6a110d07530e5a.Uhf_1MLcQlajd8yI6X-7Vx1Etxgn3kriO_6rEk3A4QI+ components-hogcharts-timeseriesbarchart--pinned-value-domain--dark:+ hash: v1.k794b7964.2d2170e87edcb123da7b7a178078416430a18e93d569a8d6b967343f7e875dd0.25lPQvDOU2blPcpYwQ9a1YclWoVm2FfekRmh0PIuJ2Q+ components-hogcharts-timeseriesbarchart--pinned-value-domain--light:+ hash: v1.k794b7964.587d923f519887971a0612017d8eed58e0d8bc7b55b9a751b123b0410d536bab.9zxePwGZZon54Wpoxm4Zp_u--ivEY3e_YmrAOdR_DFYcomponents-hogcharts-timeseriesbarchart--rotated-category-labels--dark:hash: v1.k794b7964.8fb57e1a3c38f7f6e7597b553c53b8b245369398ca67b4934bafb0083c3a099f.93IBBtsIvSkDCxreJ9AJZMoqw8Af1dvNGic6Lsn8Ueocomponents-hogcharts-timeseriesbarchart--rotated-category-labels--light:@@ -2069,29 +2073,33 @@ snapshots:errortracking-stacktracedisplay--generic-display-with-stacktrace--light:hash: v1.k794b7964.ae0c08aecfbd10220b331128d6ec8e198a41797b1395076232f7e424e24dd755.UfVTetDNuBKEM3LJ-ZYHVKo-1UDriQklgCRKleHSyMgerrortracking-volumesparkline--compact-issues-list--dark:- hash: v1.k794b7964.561577f67d28a4a75e1fe28f400edc4dbf60e34c17651da440a4d7737960f4b9.qKEotlvPBIlaPDR7a4CAykgaup3QugCHyTYOFRNvUmk+ hash: v1.k794b7964.bb0dfbb32407e11c00536d45a728f893ad87111830a80eb9753aea7f358fc812.-ezzLGQJjrkNFmi8Nzk5jhR2NG_DDzCS8j9_rnyK99Merrortracking-volumesparkline--compact-issues-list--light:- hash: v1.k794b7964.aa6ef4d5388be5caf58be4bc884ea41a306e71a67172b261175d55f34b3bbb89.mKl3ul8rZAzodehi6bk704-E9Mw0xgjsQPmm7wOUQf8+ hash: v1.k794b7964.24c7b32430b53240b2dd850722f89c410377ae29d1c89ba93bd860b581d787c1.bHZSqU3ooYQagaYxml8Rtj7ddEAekUWSvCyFshr-0mUerrortracking-volumesparkline--detailed-full-axis-with-events--dark:- hash: v1.k794b7964.556a2c5604a375ec675023413c765a2c0fa9eb7822a7687a3d15dc141a855310.pbMC4h8Z_JP9Vt9L68yXsuYvYZpen1fINVPTZluSr38+ hash: v1.k794b7964.2835aaf6d0a00660ad0265d6d4aab1c3ba9f1bb81717f5da401d82d3717c62fa.3Rdqrgs7RL2Z-a35fc6U5AKb6T50iHdQlQf2i-2adjwerrortracking-volumesparkline--detailed-full-axis-with-events--light:- hash: v1.k794b7964.1e35128eebcfc871a809853cd229996cb84b232e5fd1b87f4997087f88d3c92c.W7W1k8IY80wxVGtpqAgr-Z-GDOTtolyzXf0SBKdOLiI+ hash: v1.k794b7964.bdbb4d8591a096fa9da4adc0e99d5ce240f7aaa49783f2d3b9df1bdfceea03bb.gtH820unXuGFwObQJt1i0pKq94v8gHJ5ghayzNzR2L4errortracking-volumesparkline--detailed-mostly-zeros--dark:- hash: v1.k794b7964.22b09bf843406ceef4ded183ed74321df2f96283037ca4523e6ffccff11dade0.X-8hTJLor-Gk6j-gTQTQTpztjJ3pfbo1SIs9LVSNEJ4+ hash: v1.k794b7964.63bfcb25f18ca809144f3da86933e6c904bcc1fbaa201e5303a4516c419532dd.P9K9O-Lzyy3HQEVhxOyt4MBRetl2v-cBGcuUurirmCoerrortracking-volumesparkline--detailed-mostly-zeros--light:- hash: v1.k794b7964.df4116dcd72b5267644d35df087dc46f042c93f86d482210e68a84c3cbf0d5d2.YGbzjHuWqjpn20II44kp0zx0QJkQ9p7u5A4km1rd7I4+ hash: v1.k794b7964.4c5e28989a0459c30a10cfd4b094eb968b2c7f8a90d2b4150b68fd07e1f0d723.p9TXOg4rWilz8F-xPv4MTWAdoeuTfC168hULwamX26Yerrortracking-volumesparkline--detailed-overlapping-event-dates--dark:- hash: v1.k794b7964.0ed11b9380131f8eeb36cef878c33c3d7b8322a9dc9f0c7abff390413b5129d0.EFAY4753N7vyKdV9gLhVeYqSglp0iebmQt4vrvlN09A+ hash: v1.k794b7964.4ab38321e69e8fc2d0cba4cf5735e986395b2b6bf682088a2170d0dd2f6095db.OnHNv-QrV47cKSm_C-vQMZ92cOPUJkMKpYxM0jHquCUerrortracking-volumesparkline--detailed-overlapping-event-dates--light:- hash: v1.k794b7964.6ba1d3e01cc913bf7e280b6f7cf5b6097c6f348258c093bee1a91ec45bb88db7.K4faN_OCVnkWCgxLmSKINDo4ZsNgOhjB-tew7b_xPTc+ hash: v1.k794b7964.a3f1dcacb05c167c43e757780833b5a9d9baf69d07b351d42da10a67d700471e.ozDWA4W8l6ZIHgGKSwJhMX3XMyvdxrupTAD2pEX6A5I+ errortracking-volumesparkline--detailed-with-spikes--dark:+ hash: v1.k794b7964.38b18635463fb7c345dbd87b10427e3e3b2206a3028b9f50709101db4bd8bcdf.hpwsjAr0rlWsXptEPCxgNScbKOgBvCgZDsKaOWmvXAc+ errortracking-volumesparkline--detailed-with-spikes--light:+ hash: v1.k794b7964.c67d13aa6395db8e1f05ce65af76cd198176824962a021d1e461cad73301a928.0PWC4wVqzvPhtBTe0JHZgK-4Ggh0KyWkmupevkyO6Hwerrortracking-volumesparkline--detailed-zeros-and-ones--dark:- hash: v1.k794b7964.994e520041337f20158b02c7a4fe149d38d4400ee9bca69483d6a00c0f827cb8.Lbvx9EvkhiKu7vw6IWBUsqUVgHDV9VBOp1CZ6rG3PvY+ hash: v1.k794b7964.664a3161d35020814151df60c77f8d4e45978f48801583ddcda1f8d3555c3149.tjPI1XETiveDpLAmwxdkSCMw7Pmt0mBDz1L3SO0MxeYerrortracking-volumesparkline--detailed-zeros-and-ones--light:- hash: v1.k794b7964.0d59ea17d1f75ccc2bf730aa5ac0b15c8c1950d20bb42905614008353b991027.Yv-h6O2RuKPLdnwVmZMpg7swh9d64Ry33mL_HviuAyM+ hash: v1.k794b7964.b7d1f95e1492bdc399321cc8de1a7c7ee95a421aaf1135717eef2233f0f36621.bSKXY_IbYl5PLJnhRFt2jAelLAPgBH1suxwc-R9h75werrortracking-volumesparkline--events-before-data-range--dark:- hash: v1.k794b7964.1a0a4711a1563eca04be3a9e29b60956083b7b9cba3d124ee744d75198fff574.SOjgU2ZEa9Xbd1W_t7Ggh-N5oIncIRUZhTt6eoV_YeY+ hash: v1.k794b7964.d59e36f12a812ad81bfe87a667bac644ccd806ec7ef08bba8406c56c4c384275.UiTTwDxfntJBUdYNxiPU-1zQWfGwMIfxVvEy97dhcskerrortracking-volumesparkline--events-before-data-range--light:- hash: v1.k794b7964.683c24f2509215d174cda4a69fd2aa0f021af91d45f7ccdab742f78755c2e4ca.l0oCDgytHq-3gkB5Nza3SN1Tpmvc_LP_dsSdGCfoXxo+ hash: v1.k794b7964.124227295a3079c9a271b5b1b1de997d8f1a9b536928ac8fc0e5e806afd2f8f5.9CCTbFhZMpAVVger6Xuyp0kXNjRjdlk9vf1PwtmZEZwexporter-funnels--funnel-time-to-convert-insight--dark:hash: v1.k794b7964.32e0fdd763e52aa74a859cc74be91c34aa9bc415f698cd276a1cbf5165e07e96.83HRBJWS8NFTguzPf-6KQ58qPcfF8byzAZ6DrhaMS4Mexporter-funnels--funnel-time-to-convert-insight--light:@@ -5975,17 +5983,17 @@ snapshots:scenes-app-error-project-unavailable--no-selectable-projects--light:hash: v1.k794b7964.25cba9f347696eb78fc20a05e5f37e514e17b483c0e7f2cbc2a0ff581eef2b72.Z1uJTP8R_ATm8aciECP4ScSzcSTFpYd7VQI6kVswSMgscenes-app-errortracking--group-page--dark:- hash: v1.k794b7964.effa172f53e0be752b64baf59ec6eb6d8d1394084844090bc09e7ef90a7bad06.Ez9jT5d8PoIOaqzCrvVXd1-PgMzu_wVuE69ziQkNYEA+ hash: v1.k794b7964.e2a6dba7c901151f01a63b1ea107c63c728a3be27eee3cff3bad30afced8c6fe.g8GkgWuNAUVz3_mG9uSSEqgXg3VfVmH2QYlwDbSC4ecscenes-app-errortracking--group-page--light:- hash: v1.k794b7964.ec5dcd889de8bf9fff7fe365a739272b442202e9e16287424f1fbbcfb9ba66f5.73VkDZwxaOr8lS6XVTl-77-nkJnWYud2zj9tfDIH0QA+ hash: v1.k794b7964.01fbb3dd6df45045087dfb63c4d6648ad7b91d9e9e04a98c84757a11f8d0bae2.DiXK3fovaZKZurualgSciuqWpXupscK9DsYT0kWpm1Iscenes-app-errortracking--group-page-loading--dark:- hash: v1.k794b7964.9039f3f13e03d9546145b8158c0dc2343a2f0d689b0e1886999a730844326678.VhSeZB_vduqN8mmG2pLlYqYuz5xvItxvmOyAws6IdAQ+ hash: v1.k794b7964.657207ec087926384dc6f6df591193ea9ce11f1d76019b9888a84889f4309302.qkMCILWJ4GNwGj7qef5t2f796ZEJVYxXONyAU6MOLyQscenes-app-errortracking--group-page-loading--light:- hash: v1.k794b7964.1842e7909e950d59be4d3302ae9e6ada8e9860a79d116dd4a645a7ac5958eda9.w-1LVrCGpRQ6TINTHvufsTWDsGfLe1M_LJ9W5ZYzj7E+ hash: v1.k794b7964.01724131c2ac110b1fb2739f9d26d641c1d4c1a45ae27926c52fb5290976d3ef.dQxMiBcI0_7M_bNbHO0TGpKkHQkbOzWIflVq1i6VB9Escenes-app-errortracking--group-page-with-self-driving--dark:- hash: v1.k794b7964.91621c05d1d7cd3e7199addfb39c61e7bade523fed3c2fda0a3cf54c1b9e9309.snphNnQjReEqqnodEXJsljN0iTO0j2r-ev3-aEdW0bE+ hash: v1.k794b7964.619b7115fb9418fc0f54c870f49e1f6eaacb21384e4dc95da752ec37a687598c.NdUJYPjzt1A0AJ244u1G9cLbzMGc7m5uIRj1glrWClYscenes-app-errortracking--group-page-with-self-driving--light:- hash: v1.k794b7964.6f92e665bb93faf3c56a0c3ce2b539f7af479198acf4fe860880227049ed4173.rBYaujVCRGRAkcFatI2HJdBGNXDXZtAtwDWtdGShtXk+ hash: v1.k794b7964.1e983ebbcfb9994db466338e4ad071b58b4887e43d3fb4d581cee942eb230fe4.f9T2y4DXRcp72GQaSZOcXG4nifbVU_NnyDbJekoYskEscenes-app-errortracking--list-page--dark:hash: v1.k794b7964.f474d0d6caf49e7b9a4cfd469546ab9de031039030fb9da704293bc40d87e69a.WxsvGwytEdwdnq8_Ywy_dgGBBYoSYCX9hX72AB42bgsscenes-app-errortracking--list-page--light:diff --git a/frontend/src/styles/base.scss b/frontend/src/styles/base.scssindex 43992b8a5e88..94a9074323d5 100644--- a/frontend/src/styles/base.scss+++ b/frontend/src/styles/base.scss@@ -2031,6 +2031,28 @@animation: setup-highlight-pulse 1s ease-in-out 3 !important;}+// One cell is one period along the 135deg axis, so the loop is seamless.+@keyframes VolumeSparkline__spikeStripes {+ to {+ background-position: 0 -12px;+ }+}++// A class, not a Tailwind `animate-[…]` utility: the keyframe name's `__` would need+// underscore-escaping there, and Tailwind's raw-source scanner and the JSX-evaluated+// class attribute disagree on backslashes, so the utility's selector never matches.+.VolumeSparkline__spikeStripes {+ animation: VolumeSparkline__spikeStripes 1.5s linear infinite;++ .storybook-test-runner & {+ animation: none;+ }++ @media (prefers-reduced-motion: reduce) {+ animation: none;+ }+}+/* stylelint-disable-next-line keyframes-name-pattern */@keyframes setup-highlight-pulse {0%,diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex e4e0d921a5af..57373c32f8a0 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -98,6 +98,7 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes the sparkline from that index onward (e.g. an in-progress trailing period). `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).- The composable form of `MetricCard` lives one layer up as `Metric` in `@posthog/quill-components` (it needs `Card`/`Badge` from primitives, which charts can't depend on). It's built on `Sparkline` plus the headless metric helpers this package exports — `resolveDelta` / `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell) — and the `MetricChange` / `ResolvedDelta` types. Reach for `Metric` when you need a custom layout; use the monolithic `MetricCard` here for the default self-contained tile.- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped' | 'percent'`), `divergingStack` (stacked only — negative bar values stack below the zero baseline instead of being clamped to 0, same semantics as `BarsConfig.divergingStack`), and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.+- `TimeSeriesBarChart` also takes `config.valueDomain` (same `ValueDomain` semantics as `BarChartConfig.bars.valueDomain`): a fixed `[min, max]` skips `d3.nice()` and wins over the goal-line stretch — pin `[0, dataMax]` so the tallest bar reaches the plot top on an axis-less volume chart, where nice-rounded headroom is invisible waste; `{ include }` merges with the goal-line stretch (`mergeValueDomains` in `utils/goal-lines.ts`).- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration_ms | duration_ns`, plus `prefix`/`suffix`. Numeric and percentage ticks default to two decimals but gain a decimal per leading zero below 0.1, so a small-valued axis (say latency in seconds over 0–0.012) doesn't render every tick as `0.01`; `decimalPlaces` pins the precision instead.- Fixed x-axis tick rotation: set `xAxis.tickLabelRotation` on a time-series chart (`-45` tilts labels left). Values are clamped to `-90..90`; omit it to keep horizontal labels and existing collision behavior.- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsxindex 5ed00a934def..e4318d6d01b0 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx@@ -238,6 +238,44 @@ export const MinBarSize: Story = {),}+// A max of 246 nices up to 300–400 depending on plot height, so without the pin the tallest bar+// stops well short of the plot top.+const PINNED_DOMAIN_SERIES: Series[] = [{ key: 'volume', label: 'Volume', data: [0, 246, 0, 12, 0, 3, 0] }]++function PinnedValueDomainCell({ title, pinned }: { title: string; pinned: boolean }): JSX.Element {+ const theme = useReactiveTheme()+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>+ <span className="text-xs text-muted-foreground">{title}</span>+ <Stage>+ <TimeSeriesBarChart+ series={PINNED_DOMAIN_SERIES}+ labels={DAYS}+ theme={theme}+ config={{+ yAxis: { hide: true },+ minBarSize: 2,+ valueDomain: pinned ? [0, 246] : undefined,+ }}+ />+ </Stage>+ </div>+ )+}++/** A fixed `valueDomain` skips `d3.nice()`, so `[0, dataMax]` makes the tallest bar reach the plot+ * top — the sparkline treatment, where the hidden axis makes nice-rounded headroom pure waste. */+export const PinnedValueDomain: Story = {+ render: () => (+ // eslint-disable-next-line react/forbid-dom-props+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, auto)', gap: 24 }}>+ <PinnedValueDomainCell title="default (niced headroom)" pinned={false} />+ <PinnedValueDomainCell title="valueDomain: [0, dataMax]" pinned />+ </div>+ ),+}+export const DateAxis: Story = {render: () => {const cells: { interval: TimeInterval; labels: string[]; series: Series[]; title: string }[] = [diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsxindex 234b7d131e26..d7ad69047a02 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx@@ -273,6 +273,43 @@ describe('TimeSeriesBarChart', () => {})})+ describe('config.valueDomain', () => {+ // 246 nices past the data max at every tick count (e.g. → 300 or 400), so a tick above+ // 246 is the observable signature of the default un-pinned domain.+ const SPIKY_SERIES: Series[] = [{ key: 'a', label: 'A', data: [10, 246, 30] }]+ const maxTick = (chart: { yTicks: () => string[] }): number =>+ Math.max(...chart.yTicks().map((t) => Number(t.replace(/,/g, ''))))++ it('pins the value axis to a fixed domain instead of nicing past the data max', () => {+ const unpinned = renderHogChart(+ <TimeSeriesBarChart series={SPIKY_SERIES} labels={LABELS} theme={THEME} />+ ).chart+ expect(maxTick(unpinned)).toBeGreaterThan(246)++ const pinned = renderHogChart(+ <TimeSeriesBarChart+ series={SPIKY_SERIES}+ labels={LABELS}+ theme={THEME}+ config={{ valueDomain: [0, 246] }}+ />+ ).chart+ expect(maxTick(pinned)).toBeLessThanOrEqual(246)+ })++ it('a fixed domain wins over the goal-line stretch', () => {+ const { chart } = renderHogChart(+ <TimeSeriesBarChart+ series={SPIKY_SERIES}+ labels={LABELS}+ theme={THEME}+ config={{ valueDomain: [0, 246], goalLines: [{ value: 1000, label: 'Target' }] }}+ />+ )+ expect(maxTick(chart)).toBeLessThanOrEqual(246)+ })+ })+describe('config.barLayout', () => {it.each(['stacked', 'grouped', 'percent'] as const)('renders ticks for %s layout', (barLayout) => {const series: Series[] = [@@ -351,9 +388,7 @@ describe('TimeSeriesBarChart', () => {const { chart: widenedChart } = renderHogChart(<TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME} config={{ margins: { left: 200 } }} />)- const widenedTick = widenedChart.element.querySelector<HTMLElement>(- '[data-attr="hog-chart-axis-tick-y"]'- )+ const widenedTick = widenedChart.element.querySelector<HTMLElement>('[data-attr="hog-chart-axis-tick-y"]')expect(defaultTick).not.toBeNull()expect(widenedTick).not.toBeNull()// Left-side tick position is `right: box.width - box.plotLeft + gap` — widening the leftdiff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsxindex ad8d2f091dde..a742edc2a616 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx@@ -1,4 +1,4 @@-import React from 'react'+import React, { useMemo } from 'react'import { ChartLegend } from '../../components/Legend/ChartLegend'import type {@@ -13,11 +13,12 @@ import type {Series,TooltipConfig,TooltipContext,+ ValueDomain,} from '../../core/types'import { ReferenceLines } from '../../overlays/ReferenceLine'import { TrendLineOverlay } from '../../overlays/TrendLineOverlay'import { ValueLabels } from '../../overlays/ValueLabels'-import type { GoalLineConfig } from '../../utils/goal-lines'+import { mergeValueDomains, type GoalLineConfig } from '../../utils/goal-lines'import { useTimeSeriesTooltipConfig, type XAxisConfig, type YAxisConfig } from '../../utils/use-axis-formatters'import { BarChart } from '../BarChart/BarChart'import { useTrendLineSeries, type TrendLineConfig } from '../utils/use-derived-series'@@ -30,6 +31,11 @@ export interface TimeSeriesBarChartConfig {yAxis?: YAxisConfig | YAxisConfig[]valueLabels?: boolean | ValueLabelsConfiggoalLines?: GoalLineConfig[]+ /** Value-axis domain control — omit for data-derived auto-scaling. A fixed `[min, max]` skips+ * `d3.nice()` and wins over the goal-line stretch (pin `[0, dataMax]` so the tallest bar+ * reaches the plot top on an axis-less chart); `{ include }` merges with it. See+ * {@link ValueDomain}. */+ valueDomain?: ValueDomain/** Defaults to `stacked`. */barLayout?: BarChartConfig['barLayout']/** Defaults to `vertical`. */@@ -99,6 +105,7 @@ export function TimeSeriesBarChart<Meta = unknown>({yAxis,valueLabels,goalLines,+ valueDomain,barLayout,axisOrientation,barCornerRadius,@@ -131,7 +138,11 @@ export function TimeSeriesBarChart<Meta = unknown>({// `axisOrientation` flows through `barChartConfig` into chart context, so `ReferenceLine`// reads it automatically — no need to stamp each line here.- const { referenceLines, valueDomain } = useGoalLines(goalLines, chartSeries)+ const { referenceLines, valueDomain: goalLineDomain } = useGoalLines(goalLines, chartSeries)+ const resolvedValueDomain = useMemo(+ () => mergeValueDomains(valueDomain, goalLineDomain),+ [valueDomain, goalLineDomain]+ )const trendSeries = useTrendLineSeries(visibleSeries, trendLines)@@ -157,7 +168,7 @@ export function TimeSeriesBarChart<Meta = unknown>({barCornerRadius,bars: {divergingStack,- valueDomain,+ valueDomain: resolvedValueDomain,fillStyle,bandPadding,minBarSize,diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.tsindex 54834f0723a2..b43d3b78dd2c 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts@@ -54,8 +54,13 @@ describe('useChartMargins', () => {expect(render({ xAxisLabel: ' ' }).bottom).toBe(DEFAULT_MARGINS.bottom)})- it('collapses left margin when hideYAxis is true', () => {- expect(render({ hideYAxis: true }).left).toBe(8)+ it('collapses the left margin when hideYAxis is true, floored on the first x label half-width', () => {+ // Widest label "Mon" measures 30px mocked → half 15 + 4 edge padding = 19.+ expect(render({ hideYAxis: true }).left).toBe(19)+ })++ it('fully collapses the left margin when both axes are hidden', () => {+ expect(render({ hideYAxis: true, hideXAxis: true }).left).toBe(8)})it('left margin is at least 20 when y-axis is shown', () => {diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.tsindex aba5676774cc..dc03f1a69d1f 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts@@ -303,8 +303,10 @@ export function useChartMargins({? COLLAPSED_AXIS_MARGIN: DEFAULT_MARGINS.bottom + xLabelExtraBottom + (normalizedXAxisLabel ? X_AXIS_TITLE_MARGIN : 0)const leftLabelReserve = gutterReserves ? gutterReserves.left : Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDING+ // Even with the y-axis collapsed, the first x label still overhangs the plot's left edge,+ // so its edge reserve keeps the floor (the right margin already does the same).const left = hideYAxis- ? COLLAPSED_AXIS_MARGIN+ ? Math.max(COLLAPSED_AXIS_MARGIN, xLabelEdgeReserves.left + X_LABEL_EDGE_PADDING): Math.max(MIN_LEFT_MARGIN,leftLabelReserve + Y_LABEL_LEFT_GUTTER,diff --git a/packages/quill/packages/charts/src/utils/goal-lines.test.ts b/packages/quill/packages/charts/src/utils/goal-lines.test.tsindex ca06cd2f0de7..0a0e92174d65 100644--- a/packages/quill/packages/charts/src/utils/goal-lines.test.ts+++ b/packages/quill/packages/charts/src/utils/goal-lines.test.ts@@ -1,5 +1,10 @@import type { Series } from '../core/types'-import { buildGoalLineReferenceLines, computeSeriesNonZeroMax, type GoalLineConfig } from './goal-lines'+import {+ buildGoalLineReferenceLines,+ computeSeriesNonZeroMax,+ mergeValueDomains,+ type GoalLineConfig,+} from './goal-lines'const makeSeries = (data: number[], overrides: Partial<Series> = {}): Series => ({key: 'a',@@ -81,4 +86,14 @@ describe('goal-lines', () => {expect(buildGoalLineReferenceLines(lines, series)).toHaveLength(2)})})++ describe('mergeValueDomains', () => {+ it.each([+ ['returns the defined side when the other is undefined', undefined, { include: [5] }, { include: [5] }],+ ['a fixed domain wins over an include set', [0, 10] as const, { include: [50] }, [0, 10]],+ ['two include sets merge', { include: [5] }, { include: [50] }, { include: [5, 50] }],+ ] as const)('%s', (_, a, b, expected) => {+ expect(mergeValueDomains(a, b)).toEqual(expected)+ })+ })})diff --git a/packages/quill/packages/charts/src/utils/goal-lines.ts b/packages/quill/packages/charts/src/utils/goal-lines.tsindex da6852d5ab1f..9a6ef4df78a4 100644--- a/packages/quill/packages/charts/src/utils/goal-lines.ts+++ b/packages/quill/packages/charts/src/utils/goal-lines.ts@@ -56,3 +56,19 @@ export function goalLineValueDomain(referenceLines: readonly ReferenceLineProps[const values = referenceLines.map((line) => line.value).filter((v): v is number => typeof v === 'number')return values.length > 0 ? { include: values } : undefined}++/** Combine a consumer-set {@link ValueDomain} with the goal-line stretch. A fixed `[min, max]`+ * wins outright — the consumer pinned the axis, so nothing may stretch it — while two `include`+ * sets merge, so an explicit include and off-scale goal lines both widen the auto domain. */+export function mergeValueDomains(a: ValueDomain | undefined, b: ValueDomain | undefined): ValueDomain | undefined {+ if (!a || !b) {+ return a ?? b+ }+ if (!('include' in a)) {+ return a+ }+ if (!('include' in b)) {+ return b+ }+ return { include: [...a.include, ...b.include] }+}diff --git a/products/error_tracking/frontend/components/IssueMetadata.tsx b/products/error_tracking/frontend/components/IssueMetadata.tsxindex 2bd0e3f113d8..6da482addb5a 100644--- a/products/error_tracking/frontend/components/IssueMetadata.tsx+++ b/products/error_tracking/frontend/components/IssueMetadata.tsx@@ -27,11 +27,10 @@ export const Metadata = ({className,onScrollNearEnd,}: PropsWithChildren<{ className?: string; onScrollNearEnd?: () => void }>): JSX.Element => {- const { aggregations, summaryLoading, issueLoading, firstSeen, lastSeen, issueId, spikeEvents } =- useValues(errorTrackingIssueSceneLogic)+ const { issueId, spikeEvents } = useValues(errorTrackingIssueSceneLogic)const { setDateRange } = useActions(errorTrackingIssueSceneLogic)const sparklineKey = issueId || 'issue-unknown'- const { hoverSelection, clickedSpike } = useValues(errorTrackingVolumeSparklineLogic({ sparklineKey }))+ const { clickedSpike } = useValues(errorTrackingVolumeSparklineLogic({ sparklineKey }))const { setClickedSpike } = useActions(errorTrackingVolumeSparklineLogic({ sparklineKey }))const sparklineData = useSparklineDataIssueScene()const sparklineEvents = useSparklineEvents()@@ -78,81 +77,90 @@ export const Metadata = ({return (<div className={className}>+ <MetadataHeader sparklineKey={sparklineKey} />+ <div+ onClick={cancelEvent}+ ref={sparklineContainerRef}+ className="relative w-full min-h-[160px] shrink-0 flex flex-col px-4"+ >+ <VolumeSparkline+ data={sparklineData}+ layout="detailed"+ xAxis="full"+ events={sparklineEvents}+ sparklineKey={sparklineKey}+ className="h-full min-h-[160px]"+ onRangeSelect={handleRangeSelect}+ onSpikeClick={handleSpikeClick}+ />+ </div>+ {clickedSpike && (+ <SpikeDetailsPopover+ datum={clickedSpike.datum}+ clientX={clickedSpike.clientX}+ clientY={clickedSpike.clientY}+ spikeEvent={matchedSpikeEvent}+ onClose={() => setClickedSpike(null)}+ sparklineContainerRef={sparklineContainerRef}+ />+ )}<div className="flex-1 min-h-0 overflow-y-auto [scrollbar-gutter:stable]" onScroll={handleScroll}>- <div className="flex justify-between items-center h-[40px] px-4">- <div className="flex justify-end items-center h-full">- {match(hoverSelection)- .when(- (data) => shouldRenderIssueMetrics(data),- () => <IssueMetrics aggregations={aggregations} summaryLoading={summaryLoading} />- )- .with({ kind: 'bin' }, (data) => renderDataPoint(data.datum))- .with({ kind: 'event' }, (data) => renderEventPoint(data.event))- .otherwise(() => null)}- </div>- <div className="flex justify-end items-center h-full">- {match(hoverSelection)- .with({ kind: 'bin' }, (data) => renderDate(data.datum.date))- .with({ kind: 'event' }, (data) => renderDate(data.event.date))- .otherwise(() => (- <>- <TimeBoundary- time={firstSeen}- loading={issueLoading}- label="First Seen"- updateDateRange={(dateRange) => {- dateRange.date_from = firstSeen?.toISOString()- return dateRange- }}- />- <IconChevronRight />- <TimeBoundary- time={lastSeen}- loading={summaryLoading}- label="Last Seen"- updateDateRange={(dateRange) => {- dateRange.date_to = lastSeen?.endOf('minute').toISOString()- return dateRange- }}- />- </>- ))}- </div>- </div>- <div- onClick={cancelEvent}- ref={sparklineContainerRef}- className="relative w-full min-h-[160px] flex flex-col px-4"- >- <VolumeSparkline- data={sparklineData}- layout="detailed"- xAxis="full"- events={sparklineEvents}- sparklineKey={sparklineKey}- className="h-full min-h-[160px]"- onRangeSelect={handleRangeSelect}- onSpikeClick={handleSpikeClick}- />- </div>- {clickedSpike && (- <div className="contents">- <SpikeDetailsPopover- datum={clickedSpike.datum}- clientX={clickedSpike.clientX}- clientY={clickedSpike.clientY}- spikeEvent={matchedSpikeEvent}- onClose={() => setClickedSpike(null)}- sparklineContainerRef={sparklineContainerRef}- />- </div>- )}{children}</div></div>)}+/** Owns the `hoverSelection` read: it changes on every hovered bucket, and reading it in+ * `Metadata` would re-render the whole chart subtree per mousemove. */+function MetadataHeader({ sparklineKey }: { sparklineKey: string }): JSX.Element {+ const { aggregations, summaryLoading, issueLoading, firstSeen, lastSeen } = useValues(errorTrackingIssueSceneLogic)+ const { hoverSelection } = useValues(errorTrackingVolumeSparklineLogic({ sparklineKey }))++ return (+ <div className="flex justify-between items-center h-[40px] px-4 shrink-0">+ <div className="flex justify-end items-center h-full">+ {match(hoverSelection)+ .when(+ (data) => shouldRenderIssueMetrics(data),+ () => <IssueMetrics aggregations={aggregations} summaryLoading={summaryLoading} />+ )+ .with({ kind: 'bin' }, (data) => renderDataPoint(data.datum))+ .with({ kind: 'event' }, (data) => renderEventPoint(data.event))+ .otherwise(() => null)}+ </div>+ <div className="flex justify-end items-center h-full">+ {match(hoverSelection)+ .with({ kind: 'bin' }, (data) => renderDate(data.datum.date))+ .with({ kind: 'event' }, (data) => renderDate(data.event.date))+ .otherwise(() => (+ <>+ <TimeBoundary+ time={firstSeen}+ loading={issueLoading}+ label="First Seen"+ updateDateRange={(dateRange) => {+ dateRange.date_from = firstSeen?.toISOString()+ return dateRange+ }}+ />+ <IconChevronRight />+ <TimeBoundary+ time={lastSeen}+ loading={summaryLoading}+ label="Last Seen"+ updateDateRange={(dateRange) => {+ dateRange.date_to = lastSeen?.endOf('minute').toISOString()+ return dateRange+ }}+ />+ </>+ ))}+ </div>+ </div>+ )+}+function shouldRenderIssueMetrics(data: VolumeSparklineHoverSelection | null): boolean {if (data == null) {return true@@ -221,7 +229,7 @@ function renderDataPoint(d: SparklineDatum): JSX.Element {return (<div className="flex items-center h-full gap-3">{renderMetric('Occurrences', d.value, false)}- {d.animated && (+ {d.isSpike && (<div className="flex items-center gap-1.5 text-warning-foreground"><IconTrending className="text-base" /><span className="text-xs font-semibold">Spike</span>diff --git a/products/error_tracking/frontend/components/VolumeSparkline/EventMarkers.tsx b/products/error_tracking/frontend/components/VolumeSparkline/EventMarkers.tsxnew file mode 100644index 000000000000..5bdd15e1fe4e--- /dev/null+++ b/products/error_tracking/frontend/components/VolumeSparkline/EventMarkers.tsx@@ -0,0 +1,173 @@+import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'++import { useChartLayout } from '@posthog/quill-charts'++import { buildTimePositioner } from './buildTimePositioner'+import { spreadLabels } from './spreadLabels'+import type { SparklineEvent } from './types'++/** With `EVENT_LABEL_HEIGHT`, sizes the chart's top margin so pills sit above the bars. */+export const EVENT_LABEL_BAR_GAP = 10+export const EVENT_LABEL_HEIGHT = 20+const EVENT_LABEL_MIN_GAP = 2+const ANCHOR_RADIUS = 6+const DEFAULT_EVENT_COLOR = 'black'++export type EventMarkersProps = {+ events: SparklineEvent<string>[]+ /** Bucket start dates, one per chart label — the timeline the event timestamps are placed on. */+ dates: Date[]+ onHover: (event: SparklineEvent<string> | null) => void+}++/** DOM positioned off `useChartLayout()`, so an event can sit between two buckets — quill's band+ * scale only resolves whole labels. Memoized: it renders inside the chart host, whose props are+ * stable across the hover-driven re-renders `useChartLayout` deliberately doesn't cause. */+export const EventMarkers = memo(function EventMarkers({+ events,+ dates,+ onHover,+}: EventMarkersProps): JSX.Element | null {+ const { scales, dimensions, labels, theme } = useChartLayout()+ const labelRefs = useRef<(HTMLDivElement | null)[]>([])+ const [halfWidths, setHalfWidths] = useState<number[] | null>(null)++ const { plotLeft, plotTop, plotWidth, plotHeight } = dimensions+ const plotRight = plotLeft + plotWidth+ const plotBottom = plotTop + plotHeight++ const positionAt = useMemo(() => buildTimePositioner(dates, labels, scales.x), [dates, labels, scales])++ // React fires no `onMouseLeave` when it unmounts a hovered pill, which would strand its hover+ // in the state the bar hover shares.+ const hoveredId = useRef<string | null>(null)+ const handleHover = useCallback(+ (event: SparklineEvent<string> | null) => {+ hoveredId.current = event?.id ?? null+ onHover(event)+ },+ [onHover]+ )+ const clearStrandedHover = useCallback(() => {+ if (hoveredId.current != null) {+ hoveredId.current = null+ onHover(null)+ }+ }, [onHover])++ useEffect(() => {+ if (hoveredId.current != null && !events.some((event) => event.id === hoveredId.current)) {+ clearStrandedHover()+ }+ }, [events, clearStrandedHover])++ useEffect(() => clearStrandedHover, [clearStrandedHover])++ const anchors = useMemo(+ () => (positionAt ? events.map((event) => positionAt(event.date.getTime())) : []),+ [events, positionAt]+ )++ // Pill widths aren't known until laid out.+ const measurePills = useCallback(() => {+ const measured = labelRefs.current.slice(0, events.length).map((node) => (node?.offsetWidth ?? 0) / 2)+ setHalfWidths((previous) =>+ previous && previous.length === measured.length && previous.every((w, i) => w === measured[i])+ ? previous+ : measured+ )+ }, [events.length])++ const pillTexts = useMemo(() => events.map((event) => event.payload).join('\u0000'), [events])+ useLayoutEffect(() => {+ measurePills()+ }, [measurePills, pillTexts, plotWidth])++ // A webfont arriving after first paint changes pill widths without any prop changing.+ useEffect(() => {+ let cancelled = false+ document.fonts?.ready.then(() => {+ if (!cancelled) {+ measurePills()+ }+ })+ return () => {+ cancelled = true+ }+ }, [measurePills])++ const labelCenters = useMemo(() => {+ if (!halfWidths || halfWidths.length !== anchors.length) {+ return null+ }+ const items = anchors.map((center, index) => ({ center, halfWidth: halfWidths[index] }))+ return spreadLabels(items, EVENT_LABEL_MIN_GAP, plotLeft, plotRight)+ }, [anchors, halfWidths, plotLeft, plotRight])++ if (!positionAt || events.length === 0) {+ return null+ }++ const labelTop = Math.max(0, plotTop - EVENT_LABEL_BAR_GAP - EVENT_LABEL_HEIGHT)++ return (+ <>+ <svg className="absolute inset-0 w-full h-full pointer-events-none overflow-visible">+ {events.map((event, index) => {+ const anchorX = anchors[index]+ // Off-range events keep a clamped pill but drop the connector, which would+ // otherwise point at nothing.+ if (anchorX < plotLeft || anchorX > plotRight) {+ return null+ }+ const color = event.color || DEFAULT_EVENT_COLOR+ return (+ <g key={event.id}>+ <line+ x1={anchorX}+ y1={plotBottom}+ x2={labelCenters?.[index] ?? anchorX}+ y2={labelTop + EVENT_LABEL_HEIGHT}+ stroke={color}+ strokeWidth={2}+ />+ {/* The dot is a knockout against the chart surface, not literally white. */}+ <circle+ cx={anchorX}+ cy={plotBottom}+ r={ANCHOR_RADIUS}+ fill={theme.backgroundColor ?? 'white'}+ stroke={color}+ strokeWidth={2}+ />+ </g>+ )+ })}+ </svg>+ {events.map((event, index) => (+ <div+ key={event.id}+ ref={(node) => {+ labelRefs.current[index] = node+ }}+ data-attr="error-tracking-volume-event-label"+ className="absolute flex items-center px-[5px] rounded text-[10px] font-semibold text-white whitespace-nowrap cursor-default"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ top: labelTop,+ height: EVENT_LABEL_HEIGHT,+ // Hidden at its anchor until measured, so no unspread frame is visible.+ left: labelCenters ? labelCenters[index] - (halfWidths?.[index] ?? 0) : anchors[index],+ visibility: labelCenters ? 'visible' : 'hidden',+ backgroundColor: event.color || DEFAULT_EVENT_COLOR,+ pointerEvents: 'auto',+ }}+ onMouseEnter={() => handleHover(event)}+ onMouseLeave={() => handleHover(null)}+ >+ {event.payload}+ </div>+ ))}+ </>+ )+})diff --git a/products/error_tracking/frontend/components/VolumeSparkline/SpikeStripes.tsx b/products/error_tracking/frontend/components/VolumeSparkline/SpikeStripes.tsxnew file mode 100644index 000000000000..35d6f8685c8d--- /dev/null+++ b/products/error_tracking/frontend/components/VolumeSparkline/SpikeStripes.tsx@@ -0,0 +1,80 @@+import { useMemo } from 'react'++import { useChartLayout } from '@posthog/quill-charts'++import { cn } from 'lib/utils/css-classes'++import type { SparklineData } from './types'++export type SpikeStripesProps = {+ data: SparklineData+ /** The chart's `minBarSize`, so a floored tiny bar is striped over its full drawn height. */+ minBarSize: number+ /** The chart's `barCornerRadius`, so the stripes don't spill past a bar's rounded cap. */+ cornerRadius: number+}++type StripeRect = { index: number; left: number; top: number; width: number; height: number }++/** Animated stripes over the spike bars. A DOM overlay rather than a quill bar fill: quill's canvas+ * repaints only on change, so a scrolling fill would need a permanent rAF loop per chart, and the+ * issues list renders one per row. */+export function SpikeStripes({ data, minBarSize, cornerRadius }: SpikeStripesProps): JSX.Element | null {+ const { scales, labels } = useChartLayout()++ const rects = useMemo(() => {+ const baseline = scales.y(0)+ const found: StripeRect[] = []+ data.forEach((datum, index) => {+ // No bar to stripe, and skipping it stops the flooring below inventing one.+ if (!datum.isSpike || datum.value <= 0) {+ return+ }+ const label = labels[index]+ const center = scales.x(label)+ // Single-series vertical bars fill the whole band, so `extent` is the bar width.+ const width = scales.extent?.(label)+ if (center == null || !width) {+ return+ }+ const top = Math.min(scales.y(datum.value), baseline - minBarSize)+ if (baseline - top <= 0) {+ return+ }+ found.push({ index, left: center - width / 2, top, width, height: baseline - top })+ })+ return found+ }, [data, labels, scales, minBarSize])++ if (rects.length === 0) {+ return null+ }++ return (+ <>+ {rects.map((rect) => (+ <div+ key={rect.index}+ data-attr="error-tracking-volume-spike-stripes"+ // `bg-[size:12px_12px]` tiles one cell; at `auto` the tile is the bar's own box,+ // so the repeat seam lands mid-pattern and scrolls an out-of-phase strip up.+ // The animation (and its reduced-motion/snapshot opt-outs) lives on the+ // `VolumeSparkline__spikeStripes` class in base.scss, beside its keyframes.+ className={cn(+ 'VolumeSparkline__spikeStripes absolute pointer-events-none',+ 'bg-[repeating-linear-gradient(135deg,rgb(255_255_255/40%)_0_4.2426px,transparent_4.2426px_8.4853px)]',+ 'bg-[size:12px_12px]'+ )}+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ left: rect.left,+ top: rect.top,+ width: rect.width,+ height: rect.height,+ borderRadius: cornerRadius,+ }}+ />+ ))}+ </>+ )+}diff --git a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.stories.tsx b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.stories.tsxindex 64e0dc203164..325a227ec167 100644--- a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.stories.tsx+++ b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.stories.tsx@@ -1,5 +1,5 @@import { Meta, StoryObj } from '@storybook/react'-import * as d3 from 'd3'+import { randomLcg } from 'd3'import { dayjs } from 'lib/dayjs'@@ -13,6 +13,8 @@ const meta: Meta<VolumeSparklineProps> = {parameters: {layout: 'centered',viewMode: 'story',+ // Bars paint asynchronously (ResizeObserver → rAF); chromium alone keeps the snapshot stable.+ testOptions: { snapshotBrowsers: ['chromium'] },},component: VolumeSparkline,args: {@@ -74,6 +76,15 @@ export const EventsBeforeDataRange: Story = {},}+export const DetailedWithSpikes: Story = {+ args: {+ data: withSpikes(buildData(), [20, 45]),+ layout: 'detailed',+ xAxis: 'full',+ className: 'w-[800px] h-[200px]',+ },+}+export const CompactIssuesList: Story = {args: {data: buildData(),@@ -89,7 +100,7 @@ function buildData(minDate: string = '2022-01-01',maxDate: string = '2022-02-01'): SparklineData {- const generator = d3.randomLcg(42)+ const generator = randomLcg(42)const dayJsStart = dayjs(minDate)const dayJsEnd = dayjs(maxDate)const binSize = dayJsEnd.diff(dayJsStart, 'seconds') / resolution@@ -101,6 +112,13 @@ function buildData(})}+function withSpikes(data: SparklineData, indexes: number[]): SparklineData {+ const spikes = new Set(indexes)+ return data.map((datum, index) =>+ spikes.has(index) ? { ...datum, isSpike: true, color: 'var(--brand-yellow)' } : datum+ )+}+function buildEvents(firstDate: string, lastDate: string): SparklineEvent<string>[] {return [{diff --git a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.test.tsx b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.test.tsxnew file mode 100644index 000000000000..493b43c54781--- /dev/null+++ b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.test.tsx@@ -0,0 +1,268 @@+import { cleanup, fireEvent, render } from '@testing-library/react'++import { dragSelection, getHogChart, hoverAtIndex, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { initKeaTests } from '~/test/init'++import { errorTrackingVolumeSparklineLogic } from './errorTrackingVolumeSparklineLogic'+import type { SparklineData, SparklineEvent } from './types'+import { VolumeSparkline } from './VolumeSparkline'++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ initKeaTests()+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++const BUCKET_MS = 60 * 60 * 1000 // 1 hour, matches the fixture spacing below++function buildData(overrides: Partial<Record<number, Partial<SparklineData[number]>>> = {}): SparklineData {+ const base = Date.parse('2024-01-01T00:00:00.000Z')+ return [0, 1, 2, 3, 4].map((index) => ({+ date: new Date(base + index * BUCKET_MS),+ value: 10,+ ...overrides[index],+ }))+}++const SPARKLINE_KEY = 'test-volume-sparkline'++function renderChart(props: Partial<React.ComponentProps<typeof VolumeSparkline>> = {}): HTMLElement {+ const { container } = render(+ <VolumeSparkline sparklineKey={SPARKLINE_KEY} data={buildData()} layout="detailed" xAxis="full" {...props} />+ )+ return getHogChart(container).element+}++describe('VolumeSparkline', () => {+ describe('drag-to-zoom', () => {+ it('widens the selection to the end of the last dragged bucket', () => {+ const onRangeSelect = jest.fn()+ const data = buildData()+ const wrapper = renderChart({ data, onRangeSelect })++ dragSelection(wrapper, 1, 3, data.length)++ expect(onRangeSelect).toHaveBeenCalledWith(data[1].date, new Date(data[3].date.getTime() + BUCKET_MS))+ })++ // Pins quill's contract of normalizing the drag indices before invoking the callback —+ // the component itself no longer orders them.+ it('produces the same range when the drag direction is reversed', () => {+ const onRangeSelect = jest.fn()+ const data = buildData()+ const wrapper = renderChart({ data, onRangeSelect })++ dragSelection(wrapper, 3, 1, data.length)++ expect(onRangeSelect).toHaveBeenCalledWith(data[1].date, new Date(data[3].date.getTime() + BUCKET_MS))+ })++ it('does not fire when every bucket carries the same timestamp (placeholder data)', () => {+ const onRangeSelect = jest.fn()+ const date = new Date('2024-01-01T00:00:00.000Z')+ const data: SparklineData = [0, 1, 2, 3, 4].map(() => ({ date, value: 0 }))+ const wrapper = renderChart({ data, onRangeSelect })++ dragSelection(wrapper, 1, 3, data.length)++ expect(onRangeSelect).not.toHaveBeenCalled()+ })++ it('does not fire when no handler is passed', () => {+ const data = buildData()+ const wrapper = renderChart({ data, onRangeSelect: undefined })++ expect(() => dragSelection(wrapper, 1, 3, data.length)).not.toThrow()+ })+ })++ describe('spike clicks', () => {+ it('fires onSpikeClick with the viewport cursor position when a flagged bucket is clicked', () => {+ const onSpikeClick = jest.fn()+ const data = buildData({ 2: { isSpike: true, color: 'var(--brand-red)' } })+ const { container } = render(+ <VolumeSparkline+ sparklineKey={SPARKLINE_KEY}+ data={data}+ layout="detailed"+ xAxis="full"+ onSpikeClick={onSpikeClick}+ />+ )+ const wrapper = getHogChart(container).element++ hoverAtIndex(wrapper, 2, data.length)+ // On the outer container, past the chart's own wrapper-level handlers, so the hover+ // index survives — this is the viewport position the popover should anchor to.+ fireEvent.mouseMove(container.firstElementChild as HTMLElement, { clientX: 123, clientY: 45 })+ fireEvent.click(wrapper)++ expect(onSpikeClick).toHaveBeenCalledTimes(1)+ expect(onSpikeClick).toHaveBeenCalledWith(data[2], 123, 45)+ })++ it('does not fire onSpikeClick for an ordinary (non-spike) bucket', () => {+ const onSpikeClick = jest.fn()+ // A spike elsewhere enables the handler (`hasSpikes`); the click lands on an+ // unflagged bucket.+ const data = buildData({ 2: { isSpike: true, color: 'var(--brand-red)' } })+ const wrapper = renderChart({ data, onSpikeClick })++ hoverAtIndex(wrapper, 0, data.length)+ fireEvent.click(wrapper)++ expect(onSpikeClick).not.toHaveBeenCalled()+ })++ it('never fires when no bucket in the data is flagged as a spike', () => {+ const onSpikeClick = jest.fn()+ const data = buildData()+ const wrapper = renderChart({ data, onSpikeClick })++ hoverAtIndex(wrapper, 2, data.length)+ fireEvent.click(wrapper)++ expect(onSpikeClick).not.toHaveBeenCalled()+ })+ })++ describe('spike stripes', () => {+ const SPIKE = { isSpike: true, color: 'var(--brand-yellow)' }++ function renderStripes(data: SparklineData): HTMLElement[] {+ const { container } = render(+ <VolumeSparkline sparklineKey={SPARKLINE_KEY} data={data} layout="detailed" xAxis="full" />+ )+ return Array.from(+ container.querySelectorAll<HTMLElement>('[data-attr="error-tracking-volume-spike-stripes"]')+ )+ }++ it('overlays one striped element per spike bucket', () => {+ expect(renderStripes(buildData({ 1: SPIKE, 3: SPIKE }))).toHaveLength(2)+ })++ it('overlays nothing when no bucket is a spike', () => {+ expect(renderStripes(buildData())).toHaveLength(0)+ })++ // The overlay mirrors quill's `minBarSize` flooring, which quill skips for a zero bucket —+ // so the overlay must too, or it stripes empty plot.+ it('overlays nothing for a spike bucket with no occurrences', () => {+ expect(renderStripes(buildData({ 2: { ...SPIKE, value: 0 } }))).toHaveLength(0)+ })++ it('places each overlay over its own bucket, in bucket order', () => {+ const [first, second] = renderStripes(buildData({ 1: SPIKE, 3: SPIKE }))++ expect(parseFloat(first.style.left)).toBeLessThan(parseFloat(second.style.left))+ expect(parseFloat(first.style.width)).toBeGreaterThan(0)+ expect(parseFloat(first.style.height)).toBeGreaterThan(0)+ })+ })++ describe('bar hover reporting', () => {+ it('publishes the hovered bin to the logic', () => {+ const data = buildData()+ const wrapper = renderChart({ data })++ hoverAtIndex(wrapper, 2, data.length)++ expect(errorTrackingVolumeSparklineLogic({ sparklineKey: SPARKLINE_KEY }).values.hoverSelection).toEqual({+ kind: 'bin',+ index: 2,+ datum: data[2],+ })+ })++ it('clears the hover when the chart unmounts', () => {+ // Keep the logic alive past the chart teardown, like a parent still rendering from it.+ const logic = errorTrackingVolumeSparklineLogic({ sparklineKey: SPARKLINE_KEY })+ const unmountLogic = logic.mount()+ const data = buildData()+ const { container, unmount } = render(+ <VolumeSparkline sparklineKey={SPARKLINE_KEY} data={data} layout="detailed" xAxis="full" />+ )+ hoverAtIndex(getHogChart(container).element, 2, data.length)+ expect(logic.values.hoverSelection).not.toBeNull()++ unmount()++ expect(logic.values.hoverSelection).toBeNull()+ unmountLogic()+ })+ })++ describe('event marker hover', () => {+ const data = buildData()+ const firstSeen: SparklineEvent<string> = { id: 'first_seen', date: data[1].date, payload: 'First Seen' }+ const lastSeen: SparklineEvent<string> = { id: 'last_seen', date: data[3].date, payload: 'Last Seen' }++ function renderWithEvents(events: SparklineEvent<string>[]): {+ container: HTMLElement+ rerenderWith: (next: SparklineEvent<string>[]) => void+ } {+ const { container, rerender } = render(+ <VolumeSparkline+ sparklineKey={SPARKLINE_KEY}+ data={data}+ layout="detailed"+ xAxis="full"+ events={events}+ />+ )+ return {+ container,+ rerenderWith: (next) =>+ rerender(+ <VolumeSparkline+ sparklineKey={SPARKLINE_KEY}+ data={data}+ layout="detailed"+ xAxis="full"+ events={next}+ />+ ),+ }+ }++ function hoverFirstPill(container: HTMLElement): void {+ fireEvent.mouseEnter(container.querySelectorAll('[data-attr="error-tracking-volume-event-label"]')[0])+ }++ it('publishes the hovered event to the logic', () => {+ const { container } = renderWithEvents([firstSeen, lastSeen])++ hoverFirstPill(container)++ expect(errorTrackingVolumeSparklineLogic({ sparklineKey: SPARKLINE_KEY }).values.hoverSelection).toEqual({+ kind: 'event',+ event: firstSeen,+ })+ })++ // React fires no `onMouseLeave` on unmount, so without cleanup the removed event stays in+ // `hoverSelection` and keeps the bar hover paused.+ it.each([+ { name: 'the hovered event drops out of the list', remaining: [lastSeen] },+ { name: 'every event disappears at once', remaining: [] },+ ])('clears the hover when $name', ({ remaining }) => {+ const { container, rerenderWith } = renderWithEvents([firstSeen, lastSeen])+ hoverFirstPill(container)++ rerenderWith(remaining)++ expect(errorTrackingVolumeSparklineLogic({ sparklineKey: SPARKLINE_KEY }).values.hoverSelection).toBeNull()+ })+ })+})diff --git a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsxindex 3470984d991a..acafe54e3c03 100644--- a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx+++ b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx@@ -1,12 +1,25 @@-import { useActions } from 'kea'-import { useCallback, useEffect, useRef } from 'react'-import { match } from 'ts-pattern'-import useResizeObserver from 'use-resize-observer'+import { useActions, useValues } from 'kea'+import { useEffect, useMemo, useRef } from 'react'+import {+ type ChartMargins,+ createXAxisTickCallback,+ type DateRangeZoomData,+ type PointClickData,+ type Series,+ TimeSeriesBarChart,+ type TimeSeriesBarChartConfig,+ useChartHover,+} from '@posthog/quill-charts'++import { useChartConfig, useChartTheme } from 'lib/charts/hooks'+import { resolveVariableColor } from 'lib/charts/utils/color'import { cn } from 'lib/utils/css-classes'+import { teamLogic } from 'scenes/teamLogic'-import { useSparklineOptions } from '../../hooks/use-sparkline-options'import { errorTrackingVolumeSparklineLogic } from './errorTrackingVolumeSparklineLogic'+import { EVENT_LABEL_BAR_GAP, EVENT_LABEL_HEIGHT, EventMarkers } from './EventMarkers'+import { SpikeStripes } from './SpikeStripes'import type {SparklineData,SparklineDatum,@@ -14,10 +27,29 @@ import type {VolumeSparklineLayout,VolumeSparklineXAxisMode,} from './types'-import { renderVolumeSparkline } from './volumeSparklineRender'export type { VolumeSparklineLayout, VolumeSparklineXAxisMode } from './types'+/** zinc-400. Hex, not the token: its value is `oklch()`, which d3-color can't parse, so quill's+ * hover shade falls back to the bar's own color and the highlight disappears. */+const BAR_COLOR = '#9f9fa9'++const SERIES_KEY = 'volume'++type LayoutPreset = {+ minBarSize: number+ barCornerRadius: number+ bandPadding: number+ padding: string+}++const LAYOUTS = {+ compact: { minBarSize: 2, barCornerRadius: 3, bandPadding: 0.22, padding: 'p-1' },+ detailed: { minBarSize: 10, barCornerRadius: 4, bandPadding: 0.1, padding: 'p-0' },+} as const satisfies Record<VolumeSparklineLayout, LayoutPreset>++const COMPACT_MARGINS = { left: 0, right: 0, top: 2, bottom: 2 }+export type VolumeSparklineProps = {data: SparklineDatalayout: VolumeSparklineLayout@@ -39,106 +71,162 @@ export function VolumeSparkline({onRangeSelect,onSpikeClick,}: VolumeSparklineProps): JSX.Element {- const { setHoveredBin, setHoveredEvent } = useActions(errorTrackingVolumeSparklineLogic({ sparklineKey }))- const svgRef = useRef<SVGSVGElement>(null)- const { height, width, ref: containerRef } = useResizeObserver({ box: 'content-box' })-- const onHoverChange = useCallback(- (index: number | null, datum: SparklineDatum | null) => {- if (index == null || datum == null) {- setHoveredBin(null)- } else {- setHoveredBin({ index, datum })- }- },- [setHoveredBin]- )+ const theme = useChartTheme()+ const { timezone } = useValues(teamLogic)+ const { setHoveredEvent } = useActions(errorTrackingVolumeSparklineLogic({ sparklineKey }))+ // Quill reports clicks relative to its wrapper; the spike popover anchors in viewport coords.+ const cursorRef = useRef({ x: 0, y: 0 })- const onEventHoverChange = useCallback(- (e: SparklineEvent<string> | null) => {- setHoveredEvent(e)- },- [setHoveredEvent]+ const dates = useMemo(() => data.map((datum) => datum.date), [data])+ const labels = useMemo(() => dates.map((date) => date.toISOString()), [dates])+ // The y-axis is hidden, so quill's default `d3.nice()` rounding would only add invisible+ // headroom that shortens every bar — pin the domain so the tallest bar reaches the plot top.+ const maxValue = useMemo(() => Math.max(1, ...data.map((datum) => datum.value)), [data])++ const series = useMemo<Series[]>(+ () => [+ {+ key: SERIES_KEY,+ label: 'Occurrences',+ // Canvas can't resolve `var(--…)`; `BAR_COLOR` is already a hex literal.+ color: BAR_COLOR,+ data: data.map((datum) => datum.value),+ // Solid here, striped by `SpikeStripes`. quill's `hatch` is a de-emphasis+ // treatment, so it reads as unfinished rather than flagged.+ bars: data.map((datum) =>+ datum.isSpike && datum.color ? { color: resolveVariableColor(datum.color) } : {}+ ),+ },+ ],+ [data])- const chartStyle = useSparklineOptions(- match(layout)- .with('compact', () => ({ minBarHeight: 2, borderRadius: 3, eventLabelHeight: 0 }))- .with('detailed', () => ({- minBarHeight: 10,- borderRadius: 4,- eventLabelHeight: events.length > 0 ? 20 : 0,- }))- .exhaustive(),- [layout, events.length]+ const showAxis = xAxis !== 'none'+ const eventLabelReserve = events.length > 0 ? EVENT_LABEL_HEIGHT + EVENT_LABEL_BAR_GAP : undefined+ // Quill's own tick callback: project-timezone labels at the granularity it infers from the+ // bucket spacing, deduped per period. Only built when ticks actually render.+ const tickFormatter = useMemo(+ () => (xAxis === 'full' ? createXAxisTickCallback({ timezone, allDays: labels }) : undefined),+ [labels, timezone, xAxis])- const barWidthFraction = layout === 'compact' ? 0.78 : 0.9+ const config = useChartConfig<TimeSeriesBarChartConfig>(+ () => ({+ minBarSize: LAYOUTS[layout].minBarSize,+ barCornerRadius: LAYOUTS[layout].barCornerRadius,+ bandPadding: LAYOUTS[layout].bandPadding,+ margins: resolveMargins(layout, eventLabelReserve),+ valueDomain: [0, maxValue],+ xAxis: { hide: xAxis !== 'full', tickFormatter },+ yAxis: { hide: true },+ showAxisLines: { x: showAxis, y: false },+ showTickMarks: false,+ showCrosshair: showAxis,+ showGrid: false,+ // Hover is surfaced as issue metrics beside the chart, not as a tooltip over it.+ tooltip: { enabled: false },+ }),+ [layout, xAxis, showAxis, eventLabelReserve, tickFormatter, maxValue]+ )- useEffect(() => {- const svg = svgRef.current- if (!svg || width == null || height == null) {- return+ const onDateRangeZoom = useMemo(() => {+ if (!onRangeSelect || data.length < 2) {+ return undefined+ }+ // Zero when the data is a placeholder filled with a single timestamp (see+ // `generateFallbackData`) — a drag would select an empty range.+ const bucketMs = data[1].date.getTime() - data[0].date.getTime()+ if (bucketMs <= 0) {+ return undefined}+ return ({ startIndex, endIndex }: DateRangeZoomData) => {+ const start = data[startIndex]?.date+ const end = data[endIndex]?.date+ if (!start || !end) {+ return+ }+ // The selection covers whole buckets, so the range runs to the end of the last one.+ onRangeSelect(start, new Date(end.getTime() + bucketMs))+ }+ }, [data, onRangeSelect])- const cleanup = renderVolumeSparkline(svg, {- sparklineKey,- data,- width,- height,- xAxis,- backgroundColor: chartStyle.backgroundColor,- hoverBackgroundColor: chartStyle.hoverBackgroundColor,- axisColor: chartStyle.axisColor,- borderRadius: chartStyle.borderRadius,- minBarHeight: chartStyle.minBarHeight,- eventLabelHeight: chartStyle.eventLabelHeight,- barWidthFraction,- onHoverChange,- events,- onEventHoverChange,- eventLabelPaddingX: chartStyle.eventLabelPaddingX,- eventLabelPaddingY: chartStyle.eventLabelPaddingY,- eventMinSpace: chartStyle.eventMinSpace,- onRangeSelect,- onSpikeClick,- })-- return cleanup- }, [- data,- width,- height,- xAxis,- chartStyle.backgroundColor,- chartStyle.hoverBackgroundColor,- chartStyle.axisColor,- chartStyle.borderRadius,- chartStyle.minBarHeight,- chartStyle.eventLabelHeight,- chartStyle.eventLabelPaddingX,- chartStyle.eventLabelPaddingY,- chartStyle.eventMinSpace,- barWidthFraction,- onHoverChange,- events,- onEventHoverChange,- onRangeSelect,- onSpikeClick,- sparklineKey,- ])-- const paddingClass = match(layout)- .with('compact', () => 'p-1')- .with('detailed', () => 'p-0')- .exhaustive()+ // Only wired when a spike exists: `onPointClick` sets a pointer cursor chart-wide, which+ // would mask the drag-select crosshair.+ const hasSpikes = useMemo(() => data.some((datum) => datum.isSpike), [data])++ const onPointClick = useMemo(+ () =>+ onSpikeClick && hasSpikes+ ? ({ dataIndex }: PointClickData) => {+ const datum = data[dataIndex]+ if (datum?.isSpike) {+ onSpikeClick(datum, cursorRef.current.x, cursorRef.current.y)+ }+ }+ : undefined,+ [data, hasSpikes, onSpikeClick]+ )return (<div- ref={containerRef}- className={cn('h-full w-full min-h-0 min-w-0 overflow-hidden', paddingClass, className)}+ className={cn('h-full w-full min-h-0 min-w-0 flex flex-col', LAYOUTS[layout].padding, className)}+ onMouseMove={(e) => {+ cursorRef.current = { x: e.clientX, y: e.clientY }+ }}>- <svg ref={svgRef} className="block overflow-visible" height="100%" width="100%" />+ <TimeSeriesBarChart+ series={series}+ labels={labels}+ theme={theme}+ config={config}+ onDateRangeZoom={onDateRangeZoom}+ onPointClick={onPointClick}+ dataAttr="error-tracking-volume-sparkline"+ >+ <HoverReporter sparklineKey={sparklineKey} data={data} />+ {hasSpikes && (+ <SpikeStripes+ data={data}+ minBarSize={LAYOUTS[layout].minBarSize}+ cornerRadius={LAYOUTS[layout].barCornerRadius}+ />+ )}+ {events.length > 0 && <EventMarkers events={events} dates={dates} onHover={setHoveredEvent} />}+ </TimeSeriesBarChart></div>)}++/** A chart child because `useChartHover` only works inside the chart. Yields to an event marker's+ * hover (which writes the same logic field), reading it here rather than in the chart host so+ * mousemove-driven re-renders stay contained to this null-rendering component. */+function HoverReporter({ sparklineKey, data }: { sparklineKey: string; data: SparklineData }): null {+ const { hoverIndex } = useChartHover()+ const { hoverSelection } = useValues(errorTrackingVolumeSparklineLogic({ sparklineKey }))+ const { setHoveredBin } = useActions(errorTrackingVolumeSparklineLogic({ sparklineKey }))+ const paused = hoverSelection?.kind === 'event'++ useEffect(() => {+ if (paused) {+ return+ }+ const datum = data[hoverIndex]+ setHoveredBin(hoverIndex >= 0 && datum ? { index: hoverIndex, datum } : null)+ }, [hoverIndex, paused, data, setHoveredBin])++ // Reset on unmount so a parent still mounted after the chart tears down doesn't keep showing+ // the last hovered bucket (mirrors quill's own `Sparkline.tsx` `HoverWatcher`).+ useEffect(() => () => setHoveredBin(null), [setHoveredBin])++ return null+}++/** Plot insets. The left and right edges are left to the chart's own computed margins, which+ * reserve enough for the widest axis label at the real axis font; a flat override here would just+ * reintroduce the clipping they prevent. */+function resolveMargins(layout: VolumeSparklineLayout, eventLabelReserve: number | undefined): Partial<ChartMargins> {+ if (layout === 'compact') {+ return COMPACT_MARGINS+ }+ return { top: eventLabelReserve }+}diff --git a/products/error_tracking/frontend/components/VolumeSparkline/buildTimePositioner.test.ts b/products/error_tracking/frontend/components/VolumeSparkline/buildTimePositioner.test.tsnew file mode 100644index 000000000000..3ab9b24e48f7--- /dev/null+++ b/products/error_tracking/frontend/components/VolumeSparkline/buildTimePositioner.test.ts@@ -0,0 +1,45 @@+import { buildTimePositioner } from './buildTimePositioner'++describe('buildTimePositioner', () => {+ // Hourly buckets, band centers 20px apart from x=10. A bucket's timestamp is its left edge+ // (x=0), not its center.+ const HOUR_MS = 60 * 60 * 1000+ const dates = [0, 1, 2, 3].map((i) => new Date(i * HOUR_MS))+ const labels = dates.map((d) => d.toISOString())+ // `Map.get` already yields `undefined` for an unresolved label.+ const positions = new Map(labels.map((label, index) => [label, 10 + index * 20]))+ const scaleX = (label: string): number | undefined => positions.get(label)++ it.each([+ {+ // Left edges are x=0 and x=20, so halfway in time between them lands at x=30.+ name: 'places an event exactly between two bucket starts at the midpoint',+ time: dates[1].getTime() + HOUR_MS / 2,+ expected: 30,+ },+ {+ name: 'extrapolates for an event before the first bucket',+ time: dates[0].getTime() - HOUR_MS,+ expected: -20,+ },+ ])('$name', ({ time, expected }) => {+ const positionAt = buildTimePositioner(dates, labels, scaleX)+ expect(positionAt).not.toBeNull()+ const position = positionAt!+ expect(position(time)).toBe(expected)+ })++ it.each([+ { name: 'a single-bucket chart', dates: [dates[0]], labels: [labels[0]], scale: scaleX },+ { name: 'adjacent buckets at the same x', dates, labels, scale: () => 10 },+ {+ name: 'adjacent buckets sharing a timestamp',+ dates: [dates[0], dates[0], dates[2], dates[3]],+ labels,+ scale: scaleX,+ },+ { name: 'a scale that has not resolved a label', dates, labels, scale: () => undefined },+ ])('returns null for $name', ({ dates: d, labels: l, scale }) => {+ expect(buildTimePositioner(d, l, scale)).toBeNull()+ })+})diff --git a/products/error_tracking/frontend/components/VolumeSparkline/buildTimePositioner.ts b/products/error_tracking/frontend/components/VolumeSparkline/buildTimePositioner.tsnew file mode 100644index 000000000000..63e56aeecb8e--- /dev/null+++ b/products/error_tracking/frontend/components/VolumeSparkline/buildTimePositioner.ts@@ -0,0 +1,24 @@+/** Continuous time → x, so an event can sit between two bucket starts rather than snapping to one.+ * A bucket's timestamp is its left edge, not its center. `null` when the step can't be derived. */+export function buildTimePositioner(+ dates: Date[],+ labels: string[],+ scaleX: (label: string) => number | undefined+): ((time: number) => number) | null {+ if (dates.length < 2 || labels.length < 2) {+ return null+ }+ const firstCenter = scaleX(labels[0])+ const secondCenter = scaleX(labels[1])+ if (firstCenter == null || secondCenter == null || !isFinite(firstCenter) || !isFinite(secondCenter)) {+ return null+ }+ const step = secondCenter - firstCenter+ const bucketMs = dates[1].getTime() - dates[0].getTime()+ if (step === 0 || bucketMs === 0) {+ return null+ }+ const originX = firstCenter - step / 2+ const originTime = dates[0].getTime()+ return (time: number) => originX + ((time - originTime) / bucketMs) * step+}diff --git a/products/error_tracking/frontend/components/VolumeSparkline/spreadLabels.test.ts b/products/error_tracking/frontend/components/VolumeSparkline/spreadLabels.test.tsnew file mode 100644index 000000000000..824171e57319--- /dev/null+++ b/products/error_tracking/frontend/components/VolumeSparkline/spreadLabels.test.ts@@ -0,0 +1,56 @@+import { spreadLabels } from './spreadLabels'++describe('spreadLabels', () => {+ const MIN_GAP = 2+ const MIN = 0+ const MAX = 200++ // On a short-lived issue both pills want the same x. Without the second right-to-left pass the+ // clamp at `max` piles them back on top of each other.+ it.each([+ {+ name: 'identical centers',+ items: [+ { center: 100, halfWidth: 25 },+ { center: 100, halfWidth: 25 },+ ],+ expected: [100, 152],+ },+ {+ name: 'both pinned at the right edge',+ items: [+ { center: 200, halfWidth: 30 },+ { center: 198, halfWidth: 30 },+ ],+ expected: [170, 108],+ },+ {+ name: 'both pinned at the left edge',+ items: [+ { center: 0, halfWidth: 30 },+ { center: 2, halfWidth: 30 },+ ],+ expected: [30, 92],+ },+ {+ name: 'three crowded labels',+ items: [+ { center: 90, halfWidth: 28 },+ { center: 100, halfWidth: 28 },+ { center: 110, halfWidth: 28 },+ ],+ expected: [56, 114, 172],+ },+ ])('separates $name', ({ items, expected }) => {+ expect(spreadLabels(items, MIN_GAP, MIN, MAX)).toEqual(expected)+ })++ it('spills the leftmost labels past `min` when they cannot all fit', () => {+ const items = [+ { center: 100, halfWidth: 60 },+ { center: 100, halfWidth: 60 },+ { center: 100, halfWidth: 60 },+ ]+ expect(spreadLabels(items, MIN_GAP, MIN, MAX)).toEqual([-104, 18, 140])+ })+})diff --git a/products/error_tracking/frontend/components/VolumeSparkline/spreadLabels.ts b/products/error_tracking/frontend/components/VolumeSparkline/spreadLabels.tsnew file mode 100644index 000000000000..e9d45b85856d--- /dev/null+++ b/products/error_tracking/frontend/components/VolumeSparkline/spreadLabels.ts@@ -0,0 +1,34 @@+export type LabelSpreadItem = {+ /** Where the label wants to sit — the x of the thing it points at. */+ center: number+ halfWidth: number+}++/** Spread overlapping labels along one axis, preserving order and staying within `[min, max]`.+ * When they can't all fit, the leftmost spill past `min` rather than stacking up. */+export function spreadLabels(items: LabelSpreadItem[], minGap: number, min: number, max: number): number[] {+ const centers = items.map((item) => item.center)+ const order = items.map((_, index) => index).sort((a, b) => items[a].center - items[b].center)++ for (let k = 0; k < order.length; k++) {+ const i = order[k]+ let center = Math.max(centers[i], min + items[i].halfWidth)+ if (k > 0) {+ const previous = order[k - 1]+ center = Math.max(center, centers[previous] + items[previous].halfWidth + minGap + items[i].halfWidth)+ }+ centers[i] = center+ }++ for (let k = order.length - 1; k >= 0; k--) {+ const i = order[k]+ let center = Math.min(centers[i], max - items[i].halfWidth)+ if (k < order.length - 1) {+ const next = order[k + 1]+ center = Math.min(center, centers[next] - items[next].halfWidth - minGap - items[i].halfWidth)+ }+ centers[i] = center+ }++ return centers+}diff --git a/products/error_tracking/frontend/components/VolumeSparkline/types.ts b/products/error_tracking/frontend/components/VolumeSparkline/types.tsindex a7b52a0d8e74..bb4f4ab63650 100644--- a/products/error_tracking/frontend/components/VolumeSparkline/types.ts+++ b/products/error_tracking/frontend/components/VolumeSparkline/types.ts@@ -1,10 +1,9 @@export type SparklineDatum = {date: Datevalue: number- label?: stringcolor?: string- /** When true with `color`, bar uses diagonal stripe fill + animation */- animated?: boolean+ /** With `color`, flags the bar as a detected spike: its own color plus animated stripes. */+ isSpike?: boolean}export type SparklineData = SparklineDatum[]@@ -13,7 +12,6 @@ export type SparklineEvent<T = string> = {id: stringdate: Datepayload: T- radius?: numbercolor?: string}@@ -31,15 +29,3 @@ export type ErrorTrackingVolumeSparklineHoverValues = {isBarHighlighted: booleanhoverSelection: VolumeSparklineHoverSelection | null}--export type SparklineOptions = {- backgroundColor: string- hoverBackgroundColor: string- axisColor: string- borderRadius: number- eventLabelHeight: number- eventMinSpace: number- eventLabelPaddingX: number- eventLabelPaddingY: number- minBarHeight: number-}diff --git a/products/error_tracking/frontend/components/VolumeSparkline/volumeSparklineEvents.ts b/products/error_tracking/frontend/components/VolumeSparkline/volumeSparklineEvents.tsdeleted file mode 100644index 858a80d1d58b..000000000000--- a/products/error_tracking/frontend/components/VolumeSparkline/volumeSparklineEvents.ts+++ /dev/null@@ -1,239 +0,0 @@-import * as d3 from 'd3'--import type { SparklineDatum, SparklineEvent } from './types'--type EventGroupSel = d3.Selection<SVGGElement, SparklineEvent<string>, SVGGElement, SparklineEvent<string>>-type LabelGroupSel = d3.Selection<SVGGElement, SparklineEvent<string>, SVGGElement, SparklineEvent<string>>--export type VolumeSparklineEventLayoutOptions = {- eventLabelHeight: number- eventLabelPaddingX: number- eventLabelPaddingY: number- eventMinSpace: number- borderRadius: number-}--const COLLISION_TICKS = 500--export function renderVolumeSparklineEventMarkers(- svg: d3.Selection<SVGSVGElement, unknown, null, undefined>,- events: SparklineEvent<string>[],- xScale: d3.ScaleTime<number, number>,- chartHeight: number,- width: number,- options: VolumeSparklineEventLayoutOptions,- onHoverChange?: (index: number | null, datum: SparklineDatum | null) => void,- onEventHoverChange?: (event: SparklineEvent<string> | null) => void-): void {- if (events.length === 0) {- return- }-- svg.selectAll<SVGGElement, SparklineEvent<string>>('g.volume-sparkline-event')- .data(events)- .join('g')- .attr('class', 'volume-sparkline-event')- .each(function () {- const selection = d3.select(this as SVGGElement) as unknown as EventGroupSel- selection.selectAll('*').remove()- selection- .append('g')- .attr('class', 'label')- .call((sel) => buildVolumeSparklineEventLabelContent(sel as unknown as LabelGroupSel, xScale, options))- })-- spreadSparklineEventPillLabels(svg, 'g.volume-sparkline-event g.label', options, width)-- svg.selectAll<SVGGElement, SparklineEvent<string>>('g.volume-sparkline-event').each(function (d) {- const selection = d3.select(this as SVGGElement) as unknown as EventGroupSel- selection.call(buildEventLine, xScale, chartHeight, width)- selection.call(buildEventAnchor, xScale, chartHeight)-- selection.style('cursor', 'default')- selection- .on('mouseover', () => {- onHoverChange?.(null, null)- onEventHoverChange?.(d)- })- .on('mouseout', () => {- onEventHoverChange?.(null)- })- })-}--export function buildVolumeSparklineEventLabelContent(- selection: LabelGroupSel,- xScale: d3.ScaleTime<number, number>,- options: VolumeSparklineEventLayoutOptions-): void {- const paddingX = options.eventLabelPaddingX- const paddingY = options.eventLabelPaddingY- const baseLine = options.eventLabelHeight / 2-- const text = selection- .append('text')- .attr('class', 'font-semibold')- .attr('x', (d) => xScale(d.date))- .attr('y', baseLine)- .attr('fill', 'white')- .attr('text-anchor', 'middle')- .attr('dominant-baseline', 'central')- .style('font-size', '10px')- .text((d) => d.payload)-- const textNodes = text.nodes()-- selection- .insert('rect', 'text')- .attr('x', (_, i) => textNodes[i].getBBox().x - paddingX)- .attr('y', (_, i) => textNodes[i].getBBox().y - paddingY)- .attr('width', (_, i) => textNodes[i].getBBox().width + paddingX * 2)- .attr('height', (_, i) => textNodes[i].getBBox().height + paddingY * 2)- .attr('rx', options.borderRadius)- .attr('ry', options.borderRadius)- .attr('fill', (d) => d.color || 'black')-}--type MovingLabelNode = {- x: number- y: number- vx: number- vy: number- radius: number- halfWidth: number-}--function chartLabelHorizontalMargin(options: VolumeSparklineEventLayoutOptions): number {- return Math.max(4, options.eventMinSpace)-}--export function spreadSparklineEventPillLabels(- svg: d3.Selection<SVGSVGElement, unknown, null, undefined>,- labelSelector: string,- options: VolumeSparklineEventLayoutOptions,- contentWidth: number-): void {- const labelNodes = svg.selectAll<SVGGElement, SparklineEvent<string>>(labelSelector).nodes()- if (labelNodes.length === 0) {- return- }-- const margin = chartLabelHorizontalMargin(options)-- const movingNodes: MovingLabelNode[] = labelNodes.map((node) => {- const bbox = node.getBBox()- const center = { x: bbox.x + bbox.width / 2, y: bbox.y + bbox.height / 2 }- const halfWidth = bbox.width / 2- return {- x: center.x,- y: center.y,- vx: 0,- vy: 0,- halfWidth,- radius: halfWidth + options.eventMinSpace,- }- })-- const initialY = movingNodes.map((n) => n.y)- const clonedNodes = movingNodes.map((n) => ({ ...n }))-- if (labelNodes.length === 1) {- const node = movingNodes[0]- const minCenterX = margin + node.halfWidth- const maxCenterX = contentWidth - margin - node.halfWidth- let newX = node.x- if (minCenterX > maxCenterX) {- newX = contentWidth / 2- } else {- newX = Math.min(maxCenterX, Math.max(minCenterX, newX))- }- const deltaX = newX - node.x- d3.select(labelNodes[0]).attr('transform', `translate(${deltaX}, 0)`).attr('dx', deltaX).attr('dy', 0)- return- }-- const simulation = d3- .forceSimulation(movingNodes)- .velocityDecay(0.9)- .force(- 'collision',- d3.forceCollide<MovingLabelNode>().radius((d) => d.radius)- )- .force('boundaries', forceHorizontalBoundaries(movingNodes, contentWidth, margin))-- simulation.stop()- for (let i = 0; i < COLLISION_TICKS; i++) {- simulation.tick(1)- movingNodes.forEach((node, index) => {- node.y = initialY[index] ?? node.y- node.vy = 0- })- }-- movingNodes.forEach((node, index) => {- const deltaX = node.x - clonedNodes[index].x- const deltaY = node.y - clonedNodes[index].y- d3.select(labelNodes[index])- .attr('transform', `translate(${deltaX}, ${deltaY})`)- .attr('dx', deltaX)- .attr('dy', deltaY)- })-}--function buildEventAnchor(selection: EventGroupSel, xScale: d3.ScaleTime<number, number>, contentHeight: number): void {- selection- .append('circle')- .attr('cx', (d) => xScale(d.date))- .attr('cy', contentHeight)- .attr('r', 6)- .attr('fill', 'white')- .attr('stroke', (d) => d.color || 'black')- .attr('stroke-width', 2)-}--function buildEventLine(- selection: EventGroupSel,- xScale: d3.ScaleTime<number, number>,- contentHeight: number,- contentWidth: number-): void {- selection- .insert('line', 'g.label')- .attr('x1', (d) => xScale(d.date))- .attr('y1', contentHeight)- .attr('x2', (_, index) => {- const labelNode = selection- .selectAll('.label')- .nodes()- .find((_, i) => i === index) as SVGGElement- const dx = parseFloat(labelNode.getAttribute('dx') || '0')- const labelBbox = labelNode.getBBox()- return labelBbox?.x + dx + labelBbox?.width / 2 || 0- })- .attr('y2', 5)- .attr('stroke-width', 2)- .attr('stroke', (d) => {- const xPos = xScale(d.date)- if (xPos < 0 || xPos > contentWidth) {- return 'transparent'- }- return d.color || 'black'- })-}--function forceHorizontalBoundaries(nodes: MovingLabelNode[], contentWidth: number, margin: number) {- return () => {- nodes.forEach((node) => {- node.vy = 0- const minCenterX = margin + node.halfWidth- const maxCenterX = contentWidth - margin - node.halfWidth- if (minCenterX > maxCenterX) {- node.vx += contentWidth / 2 - node.x- } else if (node.x > maxCenterX) {- node.vx += maxCenterX - node.x- } else if (node.x < minCenterX) {- node.vx += minCenterX - node.x- }- })- }-}diff --git a/products/error_tracking/frontend/components/VolumeSparkline/volumeSparklineRender.ts b/products/error_tracking/frontend/components/VolumeSparkline/volumeSparklineRender.tsdeleted file mode 100644index 2b0cf9954270..000000000000--- a/products/error_tracking/frontend/components/VolumeSparkline/volumeSparklineRender.ts+++ /dev/null@@ -1,536 +0,0 @@-import * as d3 from 'd3'--import type { SparklineData, SparklineDatum, SparklineEvent, VolumeSparklineXAxisMode } from './types'-import { renderVolumeSparklineEventMarkers } from './volumeSparklineEvents'--const VOLUME_SPARKLINE_X_AXIS_RESERVE_PX: Record<VolumeSparklineXAxisMode, number> = {- full: 26,- minimal: 2,- none: 0,-}--const VOLUME_SPARKLINE_EVENT_LABEL_BAR_GAP_PX = 10--const STRIPE_CELL = 12--const DRAG_MIN_DISTANCE_PX = 5--export type VolumeSparklineRenderArgs = {- data: SparklineData- width: number- height: number- xAxis: VolumeSparklineXAxisMode- backgroundColor: string- hoverBackgroundColor: string- axisColor: string- borderRadius: number- minBarHeight: number- eventLabelHeight: number- barWidthFraction?: number- onHoverChange?: (index: number | null, datum: SparklineDatum | null) => void- events?: SparklineEvent<string>[]- onEventHoverChange?: (event: SparklineEvent<string> | null) => void- eventLabelPaddingX?: number- eventLabelPaddingY?: number- eventMinSpace?: number- onRangeSelect?: (startDate: Date, endDate: Date) => void- onSpikeClick?: (datum: SparklineDatum, clientX: number, clientY: number) => void- /** Used to namespace window-level d3 drag listeners so multiple sparklines do not clobber each other */- sparklineKey: string-}--function roundedTopBarBottomClipPx(borderRadius: number): number {- return borderRadius + 1-}--function roundedTopBarClipPathPx(borderRadius: number): string {- return `inset(0 0 ${roundedTopBarBottomClipPx(borderRadius)}px 0)`-}--function hashColorId(color: string): string {- let h = 0- for (let i = 0; i < color.length; i++) {- h = (h * 31 + color.charCodeAt(i)) | 0- }- return `spike-${(h >>> 0).toString(36)}`-}--function spikeBarFill(d: SparklineDatum, defaultColor: string, patternIdFor: (c: string) => string): string {- if (d.animated && d.color) {- return `url(#${patternIdFor(d.color)})`- }- return d.color || defaultColor-}--function createeStripePatterns(- defs: d3.Selection<SVGDefsElement, unknown, null, undefined>,- animatedColors: string[]-): (color: string) => string {- const idByColor = new Map<string, string>()- for (const color of animatedColors) {- if (!idByColor.has(color)) {- const id = hashColorId(color)- idByColor.set(color, id)-- const pattern = defs- .append('pattern')- .attr('id', id)- .attr('patternUnits', 'userSpaceOnUse')- .attr('width', STRIPE_CELL)- .attr('height', STRIPE_CELL)-- pattern.append('rect').attr('width', STRIPE_CELL).attr('height', STRIPE_CELL).attr('fill', color)-- pattern- .append('path')- .attr(- 'd',- `M-1,1 l2,-2 M0,${STRIPE_CELL} l${STRIPE_CELL},-${STRIPE_CELL} M${STRIPE_CELL - 1},${STRIPE_CELL + 1} l2,-2`- )- .attr('stroke', 'rgba(255,255,255,0.4)')- .attr('stroke-width', (STRIPE_CELL * Math.SQRT2) / 4)-- pattern- .append('animateTransform')- .attr('attributeName', 'patternTransform')- .attr('type', 'translate')- .attr('from', '0 0')- .attr('to', `0 -${STRIPE_CELL}`)- .attr('dur', '1.5s')- .attr('repeatCount', 'indefinite')- }- }- return (color: string) => idByColor.get(color) ?? hashColorId(color)-}--export function renderVolumeSparkline(svgEl: SVGSVGElement, args: VolumeSparklineRenderArgs): () => void {- const {- data,- width,- height,- xAxis,- backgroundColor,- hoverBackgroundColor,- axisColor,- borderRadius,- minBarHeight,- eventLabelHeight,- barWidthFraction = 0.9,- onHoverChange,- events = [],- onEventHoverChange,- eventLabelPaddingX = 5,- eventLabelPaddingY = 3,- eventMinSpace = 2,- onRangeSelect,- onSpikeClick,- sparklineKey,- } = args-- const svg = d3.select(svgEl)- svg.selectAll('*').remove()-- if (width <= 0 || height <= 0 || data.length < 2) {- return () => {}- }-- let isDragging = false-- const gatedOnHoverChange = onHoverChange- ? (index: number | null, datum: SparklineDatum | null): void => {- if (isDragging) {- return- }- onHoverChange(index, datum)- }- : undefined-- const gatedOnEventHoverChange = onEventHoverChange- ? (event: SparklineEvent<string> | null): void => {- if (isDragging) {- return- }- onEventHoverChange(event)- }- : undefined-- const axisReserve = VOLUME_SPARKLINE_X_AXIS_RESERVE_PX[xAxis]- const chartHeight = Math.max(1, height - axisReserve)-- const occurrences = data- const timeDiff = Math.abs(occurrences[1].date.getTime() - occurrences[0].date.getTime())- const extent = d3.extent(occurrences.map((d) => d.date)) as [Date, Date]- const maxDate = new Date(extent[1])- maxDate.setTime(extent[1].getTime() + timeDiff)-- const xScale = d3.scaleTime().domain([extent[0], maxDate]).range([0, width])-- const maxValue = d3.max(occurrences.map((d) => d.value)) || 0- const barPlotTop =- eventLabelHeight > 0 ? eventLabelHeight + VOLUME_SPARKLINE_EVENT_LABEL_BAR_GAP_PX : eventLabelHeight- const yScale = d3- .scaleLinear()- .domain([0, maxValue || 1])- .range([chartHeight - minBarHeight, barPlotTop])-- const animatedColors = [...new Set(occurrences.filter((d) => d.animated && d.color).map((d) => d.color as string))]-- const defs = svg.append('defs')- const patternIdFor = createeStripePatterns(defs, animatedColors)-- const xTicks = d3.timeTicks(extent[0], maxDate, 8)- const xAxisFull = d3.axisBottom(xScale).tickValues(xTicks).tickSize(0).tickPadding(5)-- const bandwidth = xScale(occurrences[1].date) - xScale(occurrences[0].date)-- const axisLineY = chartHeight- const showAxisHover = xAxis === 'minimal' || xAxis === 'full'-- if (xAxis === 'minimal') {- svg.append('line')- .attr('class', 'volume-sparkline-x-axis-baseline')- .attr('x1', 0)- .attr('x2', width)- .attr('y1', axisLineY)- .attr('y2', axisLineY)- .attr('stroke', 'currentColor')- .attr('stroke-opacity', 0.22)- .attr('pointer-events', 'none')- }-- const barGroups = svg- .selectAll<SVGGElement, SparklineDatum>('g.volume-bar')- .data(occurrences)- .join('g')- .attr('class', 'volume-bar')- .style('cursor', (d) => {- if (onSpikeClick && d.animated) {- return 'pointer'- }- return onRangeSelect ? 'crosshair' : 'default'- })-- barGroups.each(function (d, i) {- const g = d3.select(this)- const binLeft = xScale(d.date)- const barW = bandwidth * barWidthFraction- const barX = binLeft + (bandwidth - barW) / 2-- const barTop = yScale(d.value)- const barHeight = d.value > 0 ? chartHeight - yScale(d.value) : 0-- const fill = spikeBarFill(d, backgroundColor, patternIdFor)-- if (barHeight > 0) {- const clip = roundedTopBarClipPathPx(borderRadius)- const bottomClipPx = roundedTopBarBottomClipPx(borderRadius)- const barRectHeight = chartHeight - barTop + bottomClipPx- g.append('rect')- .attr('class', 'bar-main')- .attr('x', barX)- .attr('y', barTop)- .attr('width', barW)- .attr('height', barRectHeight)- .attr('rx', borderRadius)- .attr('ry', borderRadius)- .style('clip-path', clip)- .style('fill', fill)-- g.append('rect')- .attr('class', 'bar-hover-overlay')- .attr('x', barX)- .attr('y', barTop)- .attr('width', barW)- .attr('height', barRectHeight)- .attr('rx', borderRadius)- .attr('ry', borderRadius)- .style('clip-path', clip)- .style('fill', 'black')- .style('opacity', 0)- .style('pointer-events', 'none')- }-- const maxDomain = Math.max(...yScale.domain())- g.append('rect')- .attr('class', 'bar-hit')- .attr('x', binLeft)- .attr('y', yScale(maxDomain))- .attr('width', bandwidth)- .attr('height', chartHeight - yScale(maxDomain))- .style('fill', 'transparent')- .style('pointer-events', 'all')-- g.on('mouseover', () => {- gatedOnEventHoverChange?.(null)- gatedOnHoverChange?.(i, d)- if (showAxisHover) {- const axis = svg.select('.volume-sparkline-x-axis-hover')- if (d.value === 0) {- axis.attr('x1', barX)- .attr('x2', barX + barW)- .attr('stroke-opacity', 0.55)- } else {- axis.attr('stroke-opacity', 0)- }- }- if (isDragging) {- return- }- if (d.animated && d.color) {- g.select('.bar-hover-overlay').style('fill', 'white').style('opacity', 0.22)- } else {- g.select('.bar-main').style('fill', hoverBackgroundColor)- }- })-- g.on('mouseout', () => {- if (isDragging) {- return- }- g.select('.bar-hover-overlay').style('opacity', 0).style('fill', 'black')- g.select('.bar-main').style('fill', spikeBarFill(d, backgroundColor, patternIdFor))- })-- if (onSpikeClick && d.animated && !onRangeSelect) {- g.on('click', (event: MouseEvent) => {- event.stopPropagation()- onSpikeClick(d, event.clientX, event.clientY)- })- }- })-- if (xAxis === 'full') {- svg.append('g').attr('transform', `translate(0,${chartHeight})`).style('color', axisColor).call(xAxisFull)- }-- if (showAxisHover) {- svg.append('line')- .attr('class', 'volume-sparkline-x-axis-hover')- .attr('x1', 0)- .attr('x2', 0)- .attr('y1', axisLineY)- .attr('y2', axisLineY)- .attr('stroke', 'currentColor')- .attr('stroke-opacity', 0)- .attr('stroke-width', 2.5)- .attr('pointer-events', 'none')- }-- if (events.length > 0) {- renderVolumeSparklineEventMarkers(- svg,- events,- xScale,- chartHeight,- width,- {- eventLabelHeight,- eventLabelPaddingX,- eventLabelPaddingY,- eventMinSpace,- borderRadius,- },- gatedOnHoverChange,- gatedOnEventHoverChange- )- }-- // Hover cursor line (vertical indicator) – only for range-selectable charts- let hoverCursorLine: d3.Selection<SVGLineElement, unknown, null, undefined> | null = null- if (onRangeSelect) {- hoverCursorLine = svg- .append('line')- .attr('class', 'volume-sparkline-hover-cursor')- .attr('y1', barPlotTop)- .attr('y2', chartHeight)- .attr('stroke', 'rgba(128, 128, 128, 0.5)')- .attr('stroke-width', 1)- .attr('pointer-events', 'none')- .style('opacity', 0)-- svg.on('mousemove.cursor', (event: MouseEvent) => {- if (isDragging) {- return- }- const [mx] = d3.pointer(event)- hoverCursorLine!.attr('x1', mx).attr('x2', mx).style('opacity', 1)- })- }-- svg.on('mouseleave', () => {- if (isDragging) {- return- }- hoverCursorLine?.style('opacity', 0)- gatedOnEventHoverChange?.(null)- gatedOnHoverChange?.(null, null)- if (showAxisHover) {- svg.select('.volume-sparkline-x-axis-hover').attr('stroke-opacity', 0)- }- svg.selectAll<SVGGElement, SparklineDatum>('g.volume-bar').each(function (d) {- const g = d3.select(this)- g.select('.bar-hover-overlay').style('opacity', 0).style('fill', 'black')- g.select('.bar-main').style('fill', spikeBarFill(d, backgroundColor, patternIdFor))- })- })-- // Drag-to-select range- if (onRangeSelect) {- let dragStartX = -1-- const selectionOverlay = svg- .append('rect')- .attr('class', 'drag-selection-overlay')- .attr('y', barPlotTop)- .attr('height', chartHeight - barPlotTop)- .attr('rx', 0)- .attr('ry', 0)- .style('fill', 'rgba(128, 128, 128, 0.15)')- .style('stroke', 'none')- .style('pointer-events', 'none')- .style('opacity', 0)-- function resetBarStyles(): void {- barGroups.each(function (d: SparklineDatum) {- const g = d3.select(this)- g.select('.bar-main')- .style('fill', spikeBarFill(d, backgroundColor, patternIdFor))- .style('opacity', null)- g.select('.bar-hover-overlay').style('opacity', 0).style('fill', 'black')- })- }-- svg.on('mousedown', (event: MouseEvent) => {- if (event.button !== 0) {- return- }- event.preventDefault()-- const [mx] = d3.pointer(event)- dragStartX = mx-- onHoverChange?.(null, null)- onEventHoverChange?.(null)-- isDragging = true-- svg.style('cursor', 'col-resize')- hoverCursorLine?.style('opacity', 0)- })-- const handleMouseMove = (event: MouseEvent): void => {- if (!isDragging) {- return- }-- const [mx] = d3.pointer(event, svgEl)- const clampedX = Math.max(0, Math.min(mx, width))- const left = Math.min(dragStartX, clampedX)- const right = Math.max(dragStartX, clampedX)-- selectionOverlay- .attr('x', left)- .attr('width', Math.max(0, right - left))- .style('opacity', 1)-- for (let i = 0; i < occurrences.length; i++) {- const binLeft = xScale(occurrences[i].date)- if (clampedX >= binLeft && clampedX < binLeft + bandwidth) {- onHoverChange?.(i, occurrences[i])- break- }- }-- // Highlight bars inside selection, dim bars outside- barGroups.each(function (d: SparklineDatum) {- const g = d3.select(this)- const binLeft = xScale(d.date)- const binCenter = binLeft + bandwidth / 2- const inSelection = binCenter >= left && binCenter <= right-- if (inSelection) {- g.select('.bar-main').style('opacity', null)- if (d.animated && d.color) {- g.select('.bar-hover-overlay').style('fill', 'white').style('opacity', 0.15)- } else {- g.select('.bar-main').style('fill', hoverBackgroundColor)- }- } else {- g.select('.bar-main')- .style('fill', spikeBarFill(d, backgroundColor, patternIdFor))- .style('opacity', 0.3)- g.select('.bar-hover-overlay').style('opacity', 0)- }- })- }-- const handleMouseUp = (event: MouseEvent): void => {- if (!isDragging) {- return- }- isDragging = false-- svg.style('cursor', 'crosshair')-- const [mx] = d3.pointer(event, svgEl)- const clampedX = Math.max(0, Math.min(mx, width))- const dragDist = Math.abs(clampedX - dragStartX)-- selectionOverlay.style('opacity', 0)-- resetBarStyles()-- if (dragDist < DRAG_MIN_DISTANCE_PX) {- if (onSpikeClick) {- for (let i = 0; i < occurrences.length; i++) {- const binLeft = xScale(occurrences[i].date)- if (clampedX >= binLeft && clampedX < binLeft + bandwidth) {- if (occurrences[i].animated) {- onSpikeClick(occurrences[i], event.clientX, event.clientY)- }- break- }- }- }- return- }-- const left = Math.min(dragStartX, clampedX)- const right = Math.max(dragStartX, clampedX)-- let startDate: Date | null = null- let endDate: Date | null = null-- for (const d of occurrences) {- const binLeft = xScale(d.date)- const binCenter = binLeft + bandwidth / 2- if (binCenter >= left && binCenter <= right) {- if (!startDate || d.date < startDate) {- startDate = d.date- }- if (!endDate || d.date > endDate) {- endDate = d.date- }- }- }-- if (startDate && endDate) {- onRangeSelect(startDate, new Date(endDate.getTime() + timeDiff))- }- }-- const namespace = `sparkline-drag-${sparklineKey}`- d3.select(window as EventTarget as Window).on(`mousemove.${namespace}`, handleMouseMove)- d3.select(window as EventTarget as Window).on(`mouseup.${namespace}`, handleMouseUp)-- return () => {- d3.select(window as EventTarget as Window).on(`mousemove.${namespace}`, null)- d3.select(window as EventTarget as Window).on(`mouseup.${namespace}`, null)- svg.on('mousemove.cursor', null)- }- }-- return () => {- svg.on('mousemove.cursor', null)- }-}diff --git a/products/error_tracking/frontend/hooks/use-sparkline-data.tsx b/products/error_tracking/frontend/hooks/use-sparkline-data.tsxindex db828b895f3e..2d926e42104e 100644--- a/products/error_tracking/frontend/hooks/use-sparkline-data.tsx+++ b/products/error_tracking/frontend/hooks/use-sparkline-data.tsx@@ -84,6 +84,6 @@ export function applyVolumeSpikeHighlights(return data.map((datum) => {const datumTime = datum.date.getTime()const hasSpikeInBin = spikeTimestamps.some((st) => st >= datumTime && st < datumTime + binSizeMs)- return hasSpikeInBin ? { ...datum, color: spikeStripeColor, animated: true } : datum+ return hasSpikeInBin ? { ...datum, color: spikeStripeColor, isSpike: true } : datum})}diff --git a/products/error_tracking/frontend/hooks/use-sparkline-events.tsx b/products/error_tracking/frontend/hooks/use-sparkline-events.tsxindex ee813e489563..62172c4f715a 100644--- a/products/error_tracking/frontend/hooks/use-sparkline-events.tsx+++ b/products/error_tracking/frontend/hooks/use-sparkline-events.tsx@@ -18,7 +18,6 @@ export function useSparklineEvents(): SparklineEvent<string>[] {date: firstSeen.toDate(),color: 'var(--brand-blue)',payload: 'First Seen',- radius: 6,})}if (selectedEvent && !isFirstOrLastEvent(firstSeen, lastSeen, selectedEvent)) {@@ -27,7 +26,6 @@ export function useSparklineEvents(): SparklineEvent<string>[] {date: new Date(selectedEvent.timestamp),color: 'var(--brand-yellow)',payload: 'Current',- radius: 6,})}if (lastSeen) {@@ -36,7 +34,6 @@ export function useSparklineEvents(): SparklineEvent<string>[] {date: lastSeen.toDate(),color: 'var(--brand-red)',payload: 'Last Seen',- radius: 6,})}return eventsdiff --git a/products/error_tracking/frontend/hooks/use-sparkline-options.tsx b/products/error_tracking/frontend/hooks/use-sparkline-options.tsxdeleted file mode 100644index aa79e978b120..000000000000--- a/products/error_tracking/frontend/hooks/use-sparkline-options.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { useValues } from 'kea'-import { useMemo } from 'react'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'--import type { SparklineOptions } from '../components/VolumeSparkline/types'--export function useSparklineOptions(overrides: Partial<SparklineOptions> = {}, deps: any[] = []): SparklineOptions {- const colorVars = useDefaultSparklineColorVars()- return useMemo(() => {- return {- backgroundColor: `var(--${colorVars[0]})`,- hoverBackgroundColor: `var(--${colorVars[1]})`,- axisColor: `var(--${colorVars[0]})`,- borderRadius: 5,- eventLabelHeight: 20,- eventLabelPaddingX: 5,- eventLabelPaddingY: 3,- eventMinSpace: 2,- minBarHeight: 10,- ...overrides,- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [colorVars, ...deps])-}--const DARK_MODE_COLORS = ['color-zinc-400', 'color-zinc-200']-const LIGHT_MODE_COLORS = ['color-zinc-400', 'color-zinc-600']--export function useDefaultSparklineColorVars(): [string, string] {- const { isDarkModeOn } = useValues(themeLogic)- return useMemo(() => (isDarkModeOn ? DARK_MODE_COLORS : LIGHT_MODE_COLORS), [isDarkModeOn]) as [string, string]-}