: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
chore(quill-charts): simplify the hover draw loop (#129014)
Sam Pennington608d1e908e5f
diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsxindex cbab5c4eb225..dcc99b996bd8 100644--- a/packages/quill/packages/charts/src/core/Chart.tsx+++ b/packages/quill/packages/charts/src/core/Chart.tsx@@ -25,7 +25,6 @@ import { useChartDraw } from './hooks/useChartDraw'import { useChartInteraction } from './hooks/useChartInteraction'import { useChartMargins } from './hooks/useChartMargins'import { useChartScales } from './hooks/useChartScales'-import { useLatest } from './hooks/useLatest'import { useStableResolveValue } from './hooks/useStableResolveValue'import { useYAxisMaps } from './hooks/useYAxisMaps'import { useResolvedChartTheme } from './theme'@@ -329,10 +328,8 @@ export function Chart<Meta = unknown>({resolveHoverIndex,})- // ref keeps composedDrawHover stable across drawHover identity changes- const drawHoverRef = useLatest(drawHover)const composedDrawHover = useMemo(() => {- const withCrosshair = composeDrawHoverWithCrosshair(() => drawHoverRef.current, {+ const withCrosshair = composeDrawHoverWithCrosshair(drawHover, {crosshairColor: theme.crosshairColor,crosshairDash: theme.crosshairDashPattern,showCrosshair,@@ -340,14 +337,7 @@ export function Chart<Meta = unknown>({labelToCoord,})return composeDrawHoverWithSelection(withCrosshair)- }, [- showCrosshair,- theme.crosshairColor,- theme.crosshairDashPattern,- axisOrientation,- labelToCoord,- drawHoverRef.current,- ])+ }, [showCrosshair, theme.crosshairColor, theme.crosshairDashPattern, axisOrientation, labelToCoord, drawHover])useChartDraw({ctx,diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts b/packages/quill/packages/charts/src/core/canvas-renderer.test.tsindex 026ce18ddf6e..fd88afddd37e 100644--- a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts+++ b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts@@ -1058,7 +1058,7 @@ describe('hog-charts canvas-renderer', () => {it('always invokes the underlying drawHover', () => {const ctx = mockCanvasContext()const drawHover = jest.fn()- const composed = composeDrawHoverWithCrosshair(() => drawHover, {+ const composed = composeDrawHoverWithCrosshair(drawHover, {crosshairColor: '#f00',showCrosshair: true,})@@ -1068,7 +1068,7 @@ describe('hog-charts canvas-renderer', () => {it('dashes the crosshair with crosshairDash and resets to solid for subsequent hover drawing', () => {const ctx = mockCanvasContext()- const composed = composeDrawHoverWithCrosshair(() => jest.fn(), {+ const composed = composeDrawHoverWithCrosshair(jest.fn(), {crosshairColor: '#f00',crosshairDash: [3, 3],showCrosshair: true,@@ -1079,7 +1079,7 @@ describe('hog-charts canvas-renderer', () => {it('skips crosshair when showCrosshair is false', () => {const ctx = mockCanvasContext()- const composed = composeDrawHoverWithCrosshair(() => jest.fn(), {+ const composed = composeDrawHoverWithCrosshair(jest.fn(), {crosshairColor: '#f00',showCrosshair: false,})@@ -1089,7 +1089,7 @@ describe('hog-charts canvas-renderer', () => {it('skips crosshair when crosshairColor is undefined', () => {const ctx = mockCanvasContext()- const composed = composeDrawHoverWithCrosshair(() => jest.fn(), {+ const composed = composeDrawHoverWithCrosshair(jest.fn(), {crosshairColor: undefined,showCrosshair: true,})@@ -1099,7 +1099,7 @@ describe('hog-charts canvas-renderer', () => {it('skips crosshair when hoverIndex is negative', () => {const ctx = mockCanvasContext()- const composed = composeDrawHoverWithCrosshair(() => jest.fn(), {+ const composed = composeDrawHoverWithCrosshair(jest.fn(), {crosshairColor: '#f00',showCrosshair: true,})@@ -1109,7 +1109,7 @@ describe('hog-charts canvas-renderer', () => {it('skips crosshair when scales.x returns a non-finite value', () => {const ctx = mockCanvasContext()- const composed = composeDrawHoverWithCrosshair(() => jest.fn(), {+ const composed = composeDrawHoverWithCrosshair(jest.fn(), {crosshairColor: '#f00',showCrosshair: true,})@@ -1120,7 +1120,7 @@ describe('hog-charts canvas-renderer', () => {it('draws the crosshair on the happy path', () => {const ctx = mockCanvasContext()const drawHover = jest.fn()- const composed = composeDrawHoverWithCrosshair(() => drawHover, {+ const composed = composeDrawHoverWithCrosshair(drawHover, {crosshairColor: '#abc',showCrosshair: true,})@@ -1134,7 +1134,7 @@ describe('hog-charts canvas-renderer', () => {const ctx = mockCanvasContext()const drawHover = jest.fn()const labelToCoord = jest.fn((label: string) => (label === 'Tue' ? 150 : undefined))- const composed = composeDrawHoverWithCrosshair(() => drawHover, {+ const composed = composeDrawHoverWithCrosshair(drawHover, {crosshairColor: '#0f0',showCrosshair: true,axisOrientation: 'horizontal',@@ -1149,22 +1149,6 @@ describe('hog-charts canvas-renderer', () => {expect(lastMove[1]).toBeCloseTo(lastLine[1])expect(lastMove[0]).not.toBeCloseTo(lastLine[0])})-- it('reads the latest drawHover via the getter on each call', () => {- const ctx = mockCanvasContext()- const first = jest.fn()- const second = jest.fn()- let current = first- const composed = composeDrawHoverWithCrosshair(() => current, {- crosshairColor: '#f00',- showCrosshair: false,- })- composed(makeArgs(ctx, 0, 100))- current = second- composed(makeArgs(ctx, 0, 100))- expect(first).toHaveBeenCalledTimes(1)- expect(second).toHaveBeenCalledTimes(1)- })})describe('drawSelectionRect', () => {diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.tsindex 01ed4a2bec44..e757facb3346 100644--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts@@ -1545,10 +1545,7 @@ interface ComposeDrawHoverOptions {}// Crosshair drawn first so the chart-type's highlight rings render on top.-export function composeDrawHoverWithCrosshair(- getDrawHover: () => DrawHoverFn,- options: ComposeDrawHoverOptions-): DrawHoverFn {+export function composeDrawHoverWithCrosshair(drawHover: DrawHoverFn, options: ComposeDrawHoverOptions): DrawHoverFn {const { crosshairColor, crosshairDash, showCrosshair, axisOrientation = 'vertical', labelToCoord } = optionsreturn (args) => {if (showCrosshair && crosshairColor && args.hoverIndex >= 0) {@@ -1558,7 +1555,7 @@ export function composeDrawHoverWithCrosshair(drawCrosshair(args.ctx, args.dimensions, coord, crosshairColor, axisOrientation, crosshairDash)}}- return getDrawHover()(args)+ return drawHover(args)}}diff --git a/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts b/packages/quill/packages/charts/src/core/hooks/useChartDraw.tsindex bd3d91eaa6f5..aa79329af8b5 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts@@ -1,4 +1,4 @@-import { useEffect, useRef } from 'react'+import { useEffect } from 'react'import { markPaintDone, markPaintPending } from '../paint-state'import type {@@ -51,16 +51,8 @@ export function useChartDraw({drawHover,hoverAnimationMs = 0,}: UseChartDrawOptions): void {- // Cancel the prior RAF on effect re-run — relying on cleanup ordering alone leaves a- // window where a stale RAF can paint after the new setup runs.- const staticRafRef = useRef<number | null>(null)-// hoverIndex is deliberately not a dep — a hover sweep shouldn't repaint the static layer.useEffect(() => {- if (staticRafRef.current != null) {- cancelAnimationFrame(staticRafRef.current)- staticRafRef.current = null- }if (!ctx) {return}@@ -70,8 +62,7 @@ export function useChartDraw({return}markPaintPending(ctx.canvas)- staticRafRef.current = requestAnimationFrame(() => {- staticRafRef.current = null+ const raf = requestAnimationFrame(() => {clearAndPrepare(ctx, dimensions)try {drawStatic({@@ -91,13 +82,7 @@ export function useChartDraw({markPaintDone(ctx.canvas)}})- return () => {- if (staticRafRef.current != null) {- cancelAnimationFrame(staticRafRef.current)- staticRafRef.current = null- }- }- // eslint-disable-next-line react-hooks/exhaustive-deps+ return () => cancelAnimationFrame(raf)}, [ctx, dimensions, scales, series, labels, theme, drawStatic])useHoverAnimation({diff --git a/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts b/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.tsindex a8c6d345080a..9dd6f5e26af2 100644--- a/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts+++ b/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts@@ -11,7 +11,6 @@ import type {ResolvedSeries,} from '../types'import { clearAndPrepare, releaseCanvas } from './clearCanvas'-import { useLatest } from './useLatest'interface UseHoverAnimationOptions {/** Context for the hover overlay (highlight rings). Redrawn on every hoverIndex change. */@@ -47,103 +46,78 @@ export function useHoverAnimation({drawHover,hoverAnimationMs,}: UseHoverAnimationOptions): void {- // Cancel the prior RAF on effect re-run — relying on cleanup ordering alone leaves a- // window where a stale RAF can paint after the new setup runs.- const hoverRafRef = useRef<number | null>(null)- const hoverAnimRef = useRef<{ idx: number; startTime: number }>({ idx: -1, startTime: 0 })- // Freezes the fade timer while invisible (cursor in a band gap) so the fade always- // starts at progress 0 when something visible first appears.- const drewVisibleRef = useRef(false)- // Mirror everything that changes per-mousemove so the effect's dep array stays small —- // otherwise we'd tear down and re-arm the RAF every mouse pixel.- const drawHoverRef = useLatest(drawHover)- const hoverPositionRef = useLatest(hoverPosition)- const seriesRef = useLatest(series)- const labelsRef = useLatest(labels)- const themeRef = useLatest(theme)- const dragRectRef = useLatest(dragRect)+ const fade = useRef({ index: -1, startTime: 0, visible: false })- // The RAF loop ticks until hoverProgress reaches 1, then exits and waits for the next- // dep change. Timer is held in a ref so cancel/restart cycles resume the fade smoothly.+ // Bar charts hit-test per frame, so a move within one band must redraw.useEffect(() => {- if (hoverRafRef.current != null) {- cancelAnimationFrame(hoverRafRef.current)- hoverRafRef.current = null- }- if (!overlayCtx || !dimensions || !scales || themeRef.current.skipDraw) {+ if (!overlayCtx || !dimensions || !scales || theme.skipDraw) {return}- // Restart the fade on hoverIndex change — invalidate drewVisible too so the next- // visible frame starts at progress 0, not where the previous bar's fade left off.- if (hoverIndex !== hoverAnimRef.current.idx) {- hoverAnimRef.current.idx = hoverIndex- hoverAnimRef.current.startTime = monotonicNow()- drewVisibleRef.current = false+ const state = fade.current+ if (hoverIndex !== state.index) {+ state.index = hoverIndex+ state.startTime = monotonicNow()+ state.visible = false}+ const progress = (): number =>+ hoverAnimationMs > 0 ? Math.min(1, (monotonicNow() - state.startTime) / hoverAnimationMs) : 1const resetHoverFade = (): number => {- hoverAnimRef.current.startTime = monotonicNow()+ state.startTime = monotonicNow()return 0}+ let raf: number | null = nullconst tick = (): void => {- // Pin progress to 0 while invisible — see drewVisibleRef comment above.- if (!drewVisibleRef.current) {- hoverAnimRef.current.startTime = monotonicNow()+ raf = null+ if (!state.visible) {+ state.startTime = monotonicNow()}- const elapsed = monotonicNow() - hoverAnimRef.current.startTime- const hoverProgress = hoverAnimationMs > 0 ? Math.min(1, elapsed / hoverAnimationMs) : 1// Idle (no hover, no drag) draws nothing, so release the bitmap instead of clearing a// full-size one. drawHover still runs, against the empty canvas, so chart types can// reset their own hover state.- const idle = hoverIndex < 0 && !dragRectRef.current- if (idle) {+ if (hoverIndex < 0 && !dragRect) {releaseCanvas(overlayCtx.canvas)overlayCtx.save()} else {clearAndPrepare(overlayCtx, dimensions)}- let drewVisible: DrawHoverResulttry {- drewVisible = drawHoverRef.current({+ state.visible = drawHover({ctx: overlayCtx,dimensions,scales,- series: seriesRef.current,- labels: labelsRef.current,+ series,+ labels,hoverIndex,- hoverPosition: hoverPositionRef.current,- theme: themeRef.current,- hoverProgress,+ hoverPosition,+ theme,+ hoverProgress: progress(),resetHoverFade,- dragRect: dragRectRef.current,+ dragRect,})} finally {overlayCtx.restore()}- drewVisibleRef.current = drewVisible- // Recompute after the draw — the chart type may have called resetHoverFade- // mid-draw, which would leave the cached hoverProgress stale.- const liveElapsed = monotonicNow() - hoverAnimRef.current.startTime- const liveProgress = hoverAnimationMs > 0 ? Math.min(1, liveElapsed / hoverAnimationMs) : 1- if (drewVisible && liveProgress < 1 && hoverIndex >= 0) {- hoverRafRef.current = requestAnimationFrame(tick)- } else {- hoverRafRef.current = null+ if (state.visible && hoverIndex >= 0 && progress() < 1) {+ raf = requestAnimationFrame(tick)}}- hoverRafRef.current = requestAnimationFrame(tick)+ raf = requestAnimationFrame(tick)return () => {- if (hoverRafRef.current != null) {- cancelAnimationFrame(hoverRafRef.current)- hoverRafRef.current = null+ if (raf != null) {+ cancelAnimationFrame(raf)}}- // hoverPosition is in the dep array (not the ref) so the overlay redraws when the- // cursor moves *within* the same band — bar charts decide on a hit per-frame in- // `drawHover`, and entering a bar from canvas-empty-space doesn't change hoverIndex.- // The fade timer only resets on hoverIndex change (see check above), so re-running- // the effect per mousemove doesn't restart the animation.- // series/labels/theme/drawHover/dragRect are read via refs — dragRect is also in the dep- // array below so the overlay repaints the selection as the drag rectangle changes.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [overlayCtx, dimensions, scales, hoverIndex, hoverPosition, hoverAnimationMs, dragRect])+ }, [+ overlayCtx,+ dimensions,+ scales,+ series,+ labels,+ theme,+ drawHover,+ hoverIndex,+ hoverPosition,+ dragRect,+ hoverAnimationMs,+ ])}