: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
fix(charts): repaint the canvas after a lost 2D context is restored (#73875)
Sam Pennington79c8ea3ab2c8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a032b5e961ba..b4aeafb510b7 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2209,9 +2209,9 @@ snapshots:errortracking-volumesparkline--events-before-data-range--light:hash: v1.k794b7964.683c24f2509215d174cda4a69fd2aa0f021af91d45f7ccdab742f78755c2e4ca.l0oCDgytHq-3gkB5Nza3SN1Tpmvc_LP_dsSdGCfoXxoexporter-funnels--funnel-time-to-convert-insight--dark:- hash: v1.k794b7964.df689a0663d5c8465aff7085aafd8a71ff018e3b311bb9cc625bfbdc82fbe411.D4ShgJ5fysJWLIdyxzR19hb47kaQEHUJbeDtTXHPcvw+ hash: v1.k794b7964.31a385f5b5a985aebeb8cbd538c3402fc02bfebbf632e6aebf2371d19f78b247.y7Y0UzQ4rQRJKVMFIN8Vwnv2F_fg93Ld8tOVLeYlUnQexporter-funnels--funnel-time-to-convert-insight--light:- hash: v1.k794b7964.f1729da9a6b27a50180136e94c602c3c63e004093653e7c602ae6609626e19a2.v-HhwgvZ4eFuV-PADE_y_cUFWzt2O2_k5rdjhOivZPU+ hash: v1.k794b7964.beb4ef7a66e9e0155d079a87b09364badff660b95d23cddca36b8ab7db4b2bd1.nYFm-3qtqbTWpOZyN_xoy9C-Y9Fp6QhQVIyUix0eonUexporter-funnels--funnel-top-to-bottom-insight--dark:hash: v1.k794b7964.de29e0a4751c337b9e03170399ae123d95e414ee6603c95927ba75832595fc0d.Dm1yLDqoTUl0jdPmKIzu7LPNjt1x2-gxz4JhoXe88ioexporter-funnels--funnel-top-to-bottom-insight--light:diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 5ec79f8e8f71..7378e67265d3 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -53,6 +53,12 @@ const series: Series[] = [Charts fill their container and need a parent with real dimensions — a `0`-height flex child renders nothing. Give the wrapper an explicit height (`h-64`, `flex-1` in a sized column). Sparkline alone takes `height`/`width` props.+Overlays (axis labels, axis titles, reference/goal lines, value labels, legend, tooltip) are DOM, positioned from the scales; the grid, axis lines, tick marks, and the series themselves are canvas.+That split is the first thing to check when a chart looks broken: if the labels and goal lines render in the right places but the plot area is empty, the layout is fine and the canvas alone failed.+Check the cheap causes first: `theme.skipDraw` suppresses all canvas painting by design, and a `drawStatic` that throws leaves the frame it was clearing empty.+Beyond those, the bitmap is discarded either by `syncCanvasSize` reallocating it (a real resize) or by the browser losing the 2D context, and `useChartCanvas` repaints after both — so a blank plot under correct overlays means one of those paths didn't schedule its repaint.+Safari is the exception: it never fires `contextrestored`, so a context lost there stays blank.+## Composition```tsx@@ -95,7 +101,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-heiImport test helpers from `@posthog/quill-charts/testing` (jsdom-only).-- `getHogChart(scope?)` reads rendered overlays via stable `data-attr` hooks — `yTicks()`, `xTicks()`, `valueLabels()`, `referenceLines()`, axis titles, `seriesCount`, etc. Its `waitForTooltip()` returns a structured `TooltipSnapshot` but only when the chart was mounted via `renderHogChart` (it needs the captured tooltip context).+- `getHogChart(scope?)` reads rendered overlays via stable `data-attr` hooks — `yTicks()`, `xTicks()`, `valueLabels()`, `referenceLines()`, axis titles, `seriesCount`, etc. Its `waitForTooltip()` returns a structured `TooltipSnapshot` but only when the chart was mounted via `renderHogChart` (it needs the captured tooltip context). `canvas` is the static (data) canvas, for asserting the backing store or dispatching a canvas-level event — use it instead of `container.querySelector('canvas')`.- For a chart rendered outside `renderHogChart` (e.g. a real product scene), read the tooltip from the DOM: `getHogChartTooltip()` / `waitForHogChartTooltip()` return the portal element; `createHogChartTooltip(el)` wraps it as `{ element, isPinned }`. If the chart renders the built-in `DefaultTooltip`, use `createDefaultTooltipAccessor(el)` for `label()`, `rows()`, `value(seriesLabel)`, `swatchColors()`, and `total()` — it reads `DefaultTooltip`'s `data-attr="hog-chart-tooltip-*"` hooks (a stable testing contract; keep the accessor and the component's attrs in sync).## Maintenancediff --git a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts b/packages/quill/packages/charts/src/core/canvas-renderer.test.tsindex e469f919ba54..ed2fa0f09c16 100644--- a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts+++ b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts@@ -13,6 +13,7 @@ import {drawSelectionRect,drawTickMarks,resolveAxisLineColor,+ withVerticalClip,} from './canvas-renderer'import type { ChartDrawArgs, ChartTheme } from './types'@@ -1144,7 +1145,12 @@ describe('hog-charts canvas-renderer', () => {it('clamps a 2D drag that extends past the vertical plot edges', () => {const ctx = mockCanvasContext()composeDrawHoverWithSelection(jest.fn())(- makeSelectionArgs(ctx, { x0: plotLeft + 100, x1: plotLeft + 250, y0: -500, y1: plotTop + plotHeight + 500 })+ makeSelectionArgs(ctx, {+ x0: plotLeft + 100,+ x1: plotLeft + 250,+ y0: -500,+ y1: plotTop + plotHeight + 500,+ }))expect(ctx.fillRect).toHaveBeenCalledWith(plotLeft + 100, plotTop, 150, plotHeight)})@@ -1176,3 +1182,34 @@ describe('hog-charts canvas-renderer', () => {)})})++describe('withVerticalClip', () => {+ it.each([+ { name: 'a normal plot box', width: 800, plotLeft: 48, clips: true },+ { name: 'a left margin wider than the container', width: 40, plotLeft: 48, clips: false },+ { name: 'a left margin exactly at the container edge', width: 48, plotLeft: 48, clips: false },+ { name: 'a non-finite width', width: Number.NaN, plotLeft: 48, clips: false },+ ])('with clipLeft on and $name, clips=$clips', ({ width, plotLeft, clips }) => {+ const ctx = mockCanvasContext()+ const draw = jest.fn()++ withVerticalClip(ctx, { ...dimensions, width, plotLeft }, draw, undefined, true)++ // A reserved left gutter wider than the container makes the rect negative, which canvas+ // reads as a reversed rectangle off the right edge — clipping to it would discard the whole+ // series layer, so the draw has to run unclipped instead.+ expect(draw).toHaveBeenCalledTimes(1)+ expect(ctx.clip).toHaveBeenCalledTimes(clips ? 1 : 0)+ })++ it('restores the context even when draw throws', () => {+ const ctx = mockCanvasContext()++ expect(() =>+ withVerticalClip(ctx, dimensions, () => {+ throw new Error('boom')+ })+ ).toThrow('boom')+ expect(ctx.restore).toHaveBeenCalledTimes(1)+ })+})diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.tsindex 7e51fbefbeb3..974b1d94d273 100644--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts@@ -922,9 +922,19 @@ export function withVerticalClip(// Matches drawAxes' snapping: the axis line's 1px column starts at round(plotLeft), so trimming// there leaves the stroke flush against the axis line.const left = clipLeft ? Math.round(dimensions.plotLeft) : 0+ const clipWidth = dimensions.width - left+ // `useChartMargins` grows the left margin from measured label widths with a floor but no ceiling+ // against the container, so a narrow chart with stacked y-axis gutters can reserve more than it+ // has. That makes the rect negative, which canvas reads as a reversed rectangle sitting entirely+ // off the right edge — clipping to it would discard the whole series layer while the DOM axis+ // labels still render. Draw unclipped rather than invisibly. `!(> 0)` also bails on a NaN width.+ if (!(clipWidth > 0)) {+ draw()+ return+ }ctx.save()ctx.beginPath()- ctx.rect(left, dimensions.plotTop - pad, dimensions.width - left, dimensions.plotHeight + pad * 2)+ ctx.rect(left, dimensions.plotTop - pad, clipWidth, dimensions.plotHeight + pad * 2)ctx.clip()try {draw()diff --git a/packages/quill/packages/charts/src/core/canvas-size.test.ts b/packages/quill/packages/charts/src/core/canvas-size.test.tsnew file mode 100644index 000000000000..7d022e75ee36--- /dev/null+++ b/packages/quill/packages/charts/src/core/canvas-size.test.ts@@ -0,0 +1,111 @@+import { dimensions, mockRect } from '../testing'+import { buildDimensions, sameDimensions, syncCanvasSize } from './canvas-size'+import { DEFAULT_MARGINS } from './hooks/useChartMargins'++/** Records assignments to an integer canvas dimension, which jsdom would otherwise apply silently. */+function trackWrites(canvas: HTMLCanvasElement, prop: 'width' | 'height', writes: string[]): void {+ let value = canvas[prop]+ Object.defineProperty(canvas, prop, {+ configurable: true,+ get: () => value,+ set: (next: number) => {+ writes.push(`${prop}=${next}`)+ value = next+ },+ })+}++describe('canvas-size', () => {+ describe('syncCanvasSize', () => {+ it.each([+ ['an integer css size', 800, 400, 1],+ ['a fractional css size', 507.328125, 311.5, 1],+ ['a fractional css size at dpr 2', 507.328125, 311.5, 2],+ ])('leaves the backing store alone on a repeat sync with %s', (_, width, height, dpr) => {+ const canvas = document.createElement('canvas')+ syncCanvasSize(canvas, { width, height }, dpr)++ const writes: string[] = []+ trackWrites(canvas, 'width', writes)+ trackWrites(canvas, 'height', writes)++ expect(syncCanvasSize(canvas, { width, height }, dpr)).toBe(false)+ expect(writes).toEqual([])+ expect(canvas.width).toBe(Math.round(width * dpr))+ expect(canvas.height).toBe(Math.round(height * dpr))+ expect(canvas.style.width).toBe(`${width}px`)+ expect(canvas.style.height).toBe(`${height}px`)+ })++ it.each([+ ['the css width changes', { width: 640, height: 400 }, 1, 640, 400],+ ['the css height changes', { width: 800, height: 300 }, 1, 800, 300],+ ['only the device pixel ratio changes', { width: 800, height: 400 }, 2, 1600, 800],+ ])('reallocates when %s', (_, rect, dpr, expectedWidth, expectedHeight) => {+ const canvas = document.createElement('canvas')+ syncCanvasSize(canvas, { width: 800, height: 400 }, 1)++ expect(syncCanvasSize(canvas, rect, dpr)).toBe(true)+ expect(canvas.width).toBe(expectedWidth)+ expect(canvas.height).toBe(expectedHeight)+ })++ it('still updates the css size when a sub-pixel change rounds to the same backing store', () => {+ const canvas = document.createElement('canvas')+ syncCanvasSize(canvas, { width: 507.4, height: 400 }, 1)++ // The style writes sit outside the `resized` bookkeeping on purpose; folding them into+ // it would stretch a 507px bitmap over a stale CSS box.+ expect(syncCanvasSize(canvas, { width: 507.45, height: 400 }, 1)).toBe(false)+ expect(canvas.width).toBe(507)+ expect(canvas.style.width).toBe('507.45px')+ })+ })++ describe('buildDimensions', () => {+ it.each([+ { name: 'a normal container', rect: mockRect, plotWidth: 736, plotHeight: 352 },+ {+ name: 'a width narrower than the horizontal margins',+ rect: { width: 40, height: 400 },+ plotWidth: 0,+ plotHeight: 352,+ },+ {+ name: 'a height shorter than the vertical margins',+ rect: { width: 800, height: 40 },+ plotWidth: 736,+ plotHeight: 0,+ },+ ])('clamps the plot box to zero for $name', ({ rect, plotWidth, plotHeight }) => {+ // Literal expectations on purpose: this is the only independent statement of the plot box,+ // since `testing/jsdom.ts`'s shared `dimensions` fixture is itself built from this.+ expect(buildDimensions(rect, DEFAULT_MARGINS)).toEqual({+ width: rect.width,+ height: rect.height,+ plotLeft: 48,+ plotTop: 16,+ plotWidth,+ plotHeight,+ })+ })+ })++ describe('sameDimensions', () => {+ it.each([+ { name: 'a rebuilt but identical box', other: buildDimensions(mockRect, DEFAULT_MARGINS), same: true },+ {+ name: 'a margin-only change',+ other: buildDimensions(mockRect, { ...DEFAULT_MARGINS, left: 64 }),+ same: false,+ },+ {+ name: 'a size-only change',+ other: buildDimensions({ width: 799, height: 400 }, DEFAULT_MARGINS),+ same: false,+ },+ ])('reports $name as same=$same', ({ other, same }) => {+ expect(sameDimensions(dimensions, other)).toBe(same)+ })+ })+})diff --git a/packages/quill/packages/charts/src/core/canvas-size.ts b/packages/quill/packages/charts/src/core/canvas-size.tsnew file mode 100644index 000000000000..31114b5d8dc8--- /dev/null+++ b/packages/quill/packages/charts/src/core/canvas-size.ts@@ -0,0 +1,71 @@+import type { ChartDimensions, ChartMargins } from './types'++/** The subset of `DOMRect` the canvas sizing needs. */+export interface SizeRect {+ width: number+ height: number+}++/** `canvas.width`/`height` are integers, so a fractional target has to be rounded before it's+ * compared or assigned — otherwise it never equals the stored value and every sync reads as a+ * change. */+function backingSize(cssSize: number, dpr: number): number {+ return Math.round(cssSize * dpr)+}++/** Size a canvas to `rect` at `dpr`, touching `width`/`height` only when they actually change.+ * Returns whether the backing store was reallocated — i.e. whether the bitmap was wiped and a+ * repaint is now mandatory.+ *+ * Assigning `canvas.width` or `canvas.height` resets the bitmap to transparent black — even when+ * the assigned value is identical to the current one. The draw loops repaint on the *next*+ * animation frame, so every redundant assignment costs one fully blank painted frame, and a+ * container that keeps reporting resizes (a scrollbar appearing and disappearing on an+ * `overflow: auto` ancestor, an animating panel) wipes the bitmap faster than it is repainted —+ * the chart reads as blank while its DOM axis labels keep rendering. `ResizeObserver` also+ * delivers an initial observation on top of the synchronous first measure, so the redundant case+ * happens on every mount. */+export function syncCanvasSize(canvas: HTMLCanvasElement, rect: SizeRect, dpr: number): boolean {+ const width = backingSize(rect.width, dpr)+ const height = backingSize(rect.height, dpr)+ let resized = false+ if (canvas.width !== width) {+ canvas.width = width+ resized = true+ }+ if (canvas.height !== height) {+ canvas.height = height+ resized = true+ }+ const cssWidth = `${rect.width}px`+ const cssHeight = `${rect.height}px`+ if (canvas.style.width !== cssWidth) {+ canvas.style.width = cssWidth+ }+ if (canvas.style.height !== cssHeight) {+ canvas.style.height = cssHeight+ }+ return resized+}++export function buildDimensions(rect: SizeRect, margins: ChartMargins): ChartDimensions {+ return {+ width: rect.width,+ height: rect.height,+ plotLeft: margins.left,+ plotTop: margins.top,+ plotWidth: Math.max(0, rect.width - margins.left - margins.right),+ plotHeight: Math.max(0, rect.height - margins.top - margins.bottom),+ }+}++export function sameDimensions(a: ChartDimensions, b: ChartDimensions): boolean {+ return (+ a.width === b.width &&+ a.height === b.height &&+ a.plotLeft === b.plotLeft &&+ a.plotTop === b.plotTop &&+ a.plotWidth === b.plotWidth &&+ a.plotHeight === b.plotHeight+ )+}diff --git a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsxnew file mode 100644index 000000000000..0419accc0f41--- /dev/null+++ b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx@@ -0,0 +1,47 @@+import { act } from '@testing-library/react'++import { mockRect, renderHogChart } from '../../testing'+import { Chart } from '../Chart'+import type { ChartDrawArgs, ChartScales, ChartTheme, Series } from '../types'++const THEME: ChartTheme = { colors: ['#f00'], gridColor: '#eee', crosshairColor: '#888' }++const SERIES: Series[] = [{ key: 'a', label: 'A', data: [10, 20, 30] }]++const LABELS = ['Mon', 'Tue', 'Wed']++const createScales = (): ChartScales => ({+ x: () => 100,+ y: (value: number) => 200 - value,+ yTicks: () => [0, 50, 100],+})++function renderChart(drawStatic: (args: ChartDrawArgs) => void): HTMLCanvasElement {+ const { chart } = renderHogChart(+ <Chart+ series={SERIES}+ labels={LABELS}+ theme={THEME}+ createScales={createScales}+ drawStatic={drawStatic}+ drawHover={() => false}+ />+ )+ return chart.canvas+}++describe('useChartCanvas', () => {+ it('repaints against a restored backing store after the 2D context is lost', () => {+ const drawStatic = jest.fn()+ const canvas = renderChart(drawStatic)+ expect(drawStatic).toHaveBeenCalled()++ drawStatic.mockClear()+ act(() => {+ canvas.dispatchEvent(new Event('contextrestored'))+ })++ expect(drawStatic).toHaveBeenCalled()+ expect(canvas.width).toBe(mockRect.width)+ })+})diff --git a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.tsindex 36c54109567c..34b174070889 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts@@ -1,5 +1,6 @@import { useEffect, useRef, useState } from 'react'+import { buildDimensions, sameDimensions, syncCanvasSize, type SizeRect } from '../canvas-size'import type { ChartDimensions, ChartMargins } from '../types'import { useLatest } from './useLatest'@@ -22,24 +23,6 @@ interface UseChartCanvasResult {overlayCtx: CanvasRenderingContext2D | null}-function sizeCanvas(canvas: HTMLCanvasElement, rect: DOMRect, dpr: number): void {- canvas.width = rect.width * dpr- canvas.height = rect.height * dpr- canvas.style.width = `${rect.width}px`- canvas.style.height = `${rect.height}px`-}--function buildDimensions(rect: DOMRect, margins: ChartMargins): ChartDimensions {- return {- width: rect.width,- height: rect.height,- plotLeft: margins.left,- plotTop: margins.top,- plotWidth: Math.max(0, rect.width - margins.left - margins.right),- plotHeight: Math.max(0, rect.height - margins.top - margins.bottom),- }-}-export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasResult {const { margins } = optionsconst canvasRef = useRef<HTMLCanvasElement | null>(null)@@ -51,7 +34,7 @@ export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasRe// without re-binding when only margins change — re-binding risks a feedback loop with// y-tick-width measurement.const marginsRef = useLatest(margins)- const rectRef = useRef<DOMRect | null>(null)+ const rectRef = useRef<SizeRect | null>(null)// Attach the ResizeObserver once. updateSize reads margins from the ref; when margins// change, the secondary effect below recomputes dimensions from the cached rect.@@ -61,31 +44,47 @@ export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasRereturn}- const updateSize = (): void => {+ // `forceRepaint` publishes fresh state even when nothing moved — for a restored context,+ // whose bitmap came back blank while every value stayed identical.+ const updateSize = (forceRepaint = false): void => {const canvas = canvasRef.currentconst overlayCanvas = overlayCanvasRef.currentif (!canvas || !overlayCanvas) {return}- const rect = wrapper.getBoundingClientRect()- rectRef.current = rect- const dpr = window.devicePixelRatio || 1-- sizeCanvas(canvas, rect, dpr)- sizeCanvas(overlayCanvas, rect, dpr)-+ // Resolve the contexts *before* touching the canvas size. Bailing out afterwards+ // would leave both bitmaps wiped with no state change to schedule a repaint.const context = canvas.getContext('2d')const overlayContext = overlayCanvas.getContext('2d')if (!context || !overlayContext) {return}- setCanvasState({- ctx: context,- overlayCtx: overlayContext,- dimensions: buildDimensions(rect, marginsRef.current),- })+ const rect = wrapper.getBoundingClientRect()+ rectRef.current = rect+ const dpr = window.devicePixelRatio || 1++ const staticWiped = syncCanvasSize(canvas, rect, dpr)+ const overlayWiped = syncCanvasSize(overlayCanvas, rect, dpr)++ // The draw loops key on `dimensions` *identity*, so publishing a fresh object is what+ // schedules a repaint. That matters whenever a bitmap was discarded without any value+ // moving (a device-pixel-ratio change, a restored context): the wipe flags and+ // `forceRepaint` are the only reasons a new object goes out. Reusing `prev.dimensions`+ // when the values match would silently reinstate the blank canvas.+ const next = buildDimensions(rect, marginsRef.current)+ setCanvasState((prev) =>+ prev &&+ !forceRepaint &&+ !staticWiped &&+ !overlayWiped &&+ prev.ctx === context &&+ prev.overlayCtx === overlayContext &&+ sameDimensions(prev.dimensions, next)+ ? prev+ : { ctx: context, overlayCtx: overlayContext, dimensions: next }+ )}updateSize()@@ -95,13 +94,25 @@ export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasRe})observer.observe(wrapper)+ // A 2D context can be lost when the browser reclaims canvas memory. Its bitmap comes back+ // blank on `contextrestored` and nothing repaints on its own, so the canvas stays empty+ // while every DOM overlay (axis labels, goal lines, tooltip) keeps rendering against valid+ // dimensions. Not supported everywhere: Firefox 125+ and Chrome 99+ fire it, Safari never+ // does. `contextlost` is deliberately not handled — preventing its default tells the browser+ // we'll restore the context ourselves, and then it never restores.+ const onContextRestored = (): void => updateSize(true)+ const restoreTargets = [canvasRef.current, overlayCanvasRef.current].filter(+ (canvas): canvas is HTMLCanvasElement => !!canvas+ )+ restoreTargets.forEach((canvas) => canvas.addEventListener('contextrestored', onContextRestored))+return () => {observer.disconnect()+ restoreTargets.forEach((canvas) => canvas.removeEventListener('contextrestored', onContextRestored))}// Bind the observer once. `marginsRef` is a ref so `updateSize` always reads the// latest margins; depending on `marginsRef.current` here would disconnect and re-run- // `updateSize` on every margins change, synchronously clearing the canvas bitmap- // (a visible blank flash). The effect below handles margins-only updates instead.+ // `updateSize` on every margins change. The effect below handles margins-only updates.// eslint-disable-next-line react-hooks/exhaustive-deps}, [])@@ -111,7 +122,13 @@ export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasReif (!rect) {return}- setCanvasState((prev) => (prev ? { ...prev, dimensions: buildDimensions(rect, margins) } : prev))+ setCanvasState((prev) => {+ if (!prev) {+ return prev+ }+ const next = buildDimensions(rect, margins)+ return sameDimensions(prev.dimensions, next) ? prev : { ...prev, dimensions: next }+ })}, [margins.left, margins.right, margins.top, margins.bottom, margins])return {diff --git a/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts b/packages/quill/packages/charts/src/core/hooks/useChartDraw.tsindex cb5e16a7a4c7..aef44e9df5a6 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts@@ -62,19 +62,22 @@ export function useChartDraw({staticRafRef.current = requestAnimationFrame(() => {staticRafRef.current = nullclearAndPrepare(ctx, dimensions)- drawStatic({- ctx,- dimensions,- scales,- series,- labels,- hoverIndex: -1,- hoverPosition: null,- theme,- hoverProgress: 1,- resetHoverFade: () => 1,- })- ctx.restore()+ try {+ drawStatic({+ ctx,+ dimensions,+ scales,+ series,+ labels,+ hoverIndex: -1,+ hoverPosition: null,+ theme,+ hoverProgress: 1,+ resetHoverFade: () => 1,+ })+ } finally {+ ctx.restore()+ }})return () => {if (staticRafRef.current != null) {diff --git a/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts b/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.tsindex e50a88c59d05..358130273d69 100644--- a/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts+++ b/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts@@ -92,20 +92,24 @@ export function useHoverAnimation({const elapsed = monotonicNow() - hoverAnimRef.current.startTimeconst hoverProgress = hoverAnimationMs > 0 ? Math.min(1, elapsed / hoverAnimationMs) : 1clearAndPrepare(overlayCtx, dimensions)- const drewVisible = drawHoverRef.current({- ctx: overlayCtx,- dimensions,- scales,- series: seriesRef.current,- labels: labelsRef.current,- hoverIndex,- hoverPosition: hoverPositionRef.current,- theme: themeRef.current,- hoverProgress,- resetHoverFade,- dragRect: dragRectRef.current,- })- overlayCtx.restore()+ let drewVisible: DrawHoverResult+ try {+ drewVisible = drawHoverRef.current({+ ctx: overlayCtx,+ dimensions,+ scales,+ series: seriesRef.current,+ labels: labelsRef.current,+ hoverIndex,+ hoverPosition: hoverPositionRef.current,+ theme: themeRef.current,+ hoverProgress,+ resetHoverFade,+ dragRect: dragRectRef.current,+ })+ } 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.diff --git a/packages/quill/packages/charts/src/docs/TESTING.md b/packages/quill/packages/charts/src/docs/TESTING.mdindex 4ffcee4b0bc9..9e1dd3576b89 100644--- a/packages/quill/packages/charts/src/docs/TESTING.md+++ b/packages/quill/packages/charts/src/docs/TESTING.md@@ -36,6 +36,7 @@ The accessor surface (full list in `testing/accessor.ts`):```tschart.element // wrapper div for the chart+chart.canvas // the static (data) canvas, not the aria-hidden hover overlaychart.seriesCount // visible series count, from the canvas's aria-labelchart.yTicks() // ['0', '20', '40', …]chart.yRightTicks() // right-axis ticks (multi-axis charts)@@ -173,7 +174,7 @@ it('reports render errors through onError', () => {**Don't inspect canvas pixels.** No `getContext('2d')` spies, no pixel snapshots — JSdom's canvas is a stub anyway.-**Don't fall back to `container.querySelector('canvas')` for canvas presence.** `renderHogChart` already throws when the canvas is missing.+**Don't fall back to `container.querySelector('canvas')` for canvas presence.** `renderHogChart` already throws when the canvas is missing. To act on a rendered canvas — asserting its backing store, dispatching a canvas-level event like `contextrestored` — use `chart.canvas` rather than re-querying the DOM. Absence assertions (`expect(container.querySelector('canvas')).toBeNull()`) still need a raw query, since the accessor throws when there's no canvas.**Don't write `it.each` matrices that only assert "a canvas rendered".** Each row should read at least one observable property of that permutation — `chart.yTicks().some(t => t.endsWith('%'))` for percent layout, `chart.hasRightAxis` for a multi-axis case.diff --git a/packages/quill/packages/charts/src/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.tsindex 88109d41bae9..59692924e6ec 100644--- a/packages/quill/packages/charts/src/testing/accessor.ts+++ b/packages/quill/packages/charts/src/testing/accessor.ts@@ -63,6 +63,8 @@ interface SlopeLegendItemSummary {export interface HogChart<Meta = unknown> {/** The wrapper div of this chart. */element: HTMLElement+ /** The static (data) canvas, as opposed to the `aria-hidden` hover overlay. */+ canvas: HTMLCanvasElement/** Number of non-excluded data series rendered (read from the chart's aria-label). */seriesCount: number/** Visible y-axis tick labels (left axis). */@@ -175,6 +177,7 @@ export function getHogChart<Meta = unknown>(return {element: wrapper,+ canvas,seriesCount,get hasRightAxis(): boolean {return wrapper.querySelectorAll('[data-attr="hog-chart-axis-tick-yr"]').length > 0diff --git a/packages/quill/packages/charts/src/testing/jsdom.ts b/packages/quill/packages/charts/src/testing/jsdom.tsindex 9ca721f55b40..22e9ed2d2c54 100644--- a/packages/quill/packages/charts/src/testing/jsdom.ts+++ b/packages/quill/packages/charts/src/testing/jsdom.ts@@ -1,27 +1,21 @@+import { buildDimensions } from '../core/canvas-size'import { DEFAULT_MARGINS } from '../core/hooks/useChartMargins'import type { ChartDimensions, ResolvedSeries, Series } from '../core/types'-export const dimensions: ChartDimensions = {- width: 800,- height: 400,- plotLeft: DEFAULT_MARGINS.left,- plotTop: DEFAULT_MARGINS.top,- plotWidth: 800 - DEFAULT_MARGINS.left - DEFAULT_MARGINS.right,- plotHeight: 400 - DEFAULT_MARGINS.top - DEFAULT_MARGINS.bottom,-}-export const mockRect: DOMRect = {x: 0,y: 0,- width: dimensions.width,- height: dimensions.height,+ width: 800,+ height: 400,top: 0,left: 0,- bottom: dimensions.height,- right: dimensions.width,+ bottom: 400,+ right: 800,toJSON: () => ({}),}+export const dimensions: ChartDimensions = buildDimensions(mockRect, DEFAULT_MARGINS)+export function makeSeries(overrides: Partial<Series> & { key: string; data: number[] }): ResolvedSeries {return { label: overrides.key, color: '#000', ...overrides }}