: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): keep the last frame on screen while a chart resizes (#118667)
Sam Pennington9675c8cc718b
diff --git a/packages/quill/packages/charts/src/core/canvas-size.ts b/packages/quill/packages/charts/src/core/canvas-size.tsindex c133c6d848f7..2883a8494211 100644--- a/packages/quill/packages/charts/src/core/canvas-size.ts+++ b/packages/quill/packages/charts/src/core/canvas-size.ts@@ -17,14 +17,9 @@ function backingSize(cssSize: number, dpr: number): number {* 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. */+ * Assigning `canvas.width` or `canvas.height` resets the bitmap to transparent black and+ * reallocates it, even when the assigned value is identical to the current one. Callers sync on+ * every paint, so a redundant assignment would reallocate the bitmap on every frame. */export function syncCanvasSize(canvas: HTMLCanvasElement, rect: SizeRect, dpr: number): boolean {const width = backingSize(rect.width, dpr)const height = backingSize(rect.height, dpr)diff --git a/packages/quill/packages/charts/src/core/hooks/clearCanvas.test.ts b/packages/quill/packages/charts/src/core/hooks/clearCanvas.test.tsindex 74d3136c6f5b..8af6ba36b4c0 100644--- a/packages/quill/packages/charts/src/core/hooks/clearCanvas.test.ts+++ b/packages/quill/packages/charts/src/core/hooks/clearCanvas.test.ts@@ -1,5 +1,4 @@import type { ChartDimensions } from '../types'-import { clearAndPrepare } from './clearCanvas'function makeCtx(backingWidth: number): {@@ -7,8 +6,10 @@ function makeCtx(backingWidth: number): {transforms: number[][]} {const transforms: number[][] = []+ const canvas = document.createElement('canvas')+ canvas.width = backingWidthconst ctx = {- canvas: { width: backingWidth } as HTMLCanvasElement,+ canvas,save: () => {},setTransform: (a: number, b: number, c: number, d: number, e: number, f: number) =>transforms.push([a, b, c, d, e, f]),@@ -28,27 +29,19 @@ describe('clearAndPrepare', () => {Object.defineProperty(window, 'devicePixelRatio', { value: originalDpr, configurable: true })})- it('scales the transform by the backing-store ratio, ignoring a mismatched window.devicePixelRatio', () => {- // Backing sized at dpr=1 (canvas.width === css width) while the global now reports 2 — the- // export's resize-under-device_scale_factor=2 case. The transform must follow the backing- // (1), not the stale global (2), or every coordinate doubles and the chart magnifies/clips.- Object.defineProperty(window, 'devicePixelRatio', { value: 2, configurable: true })- const { ctx, transforms } = makeCtx(784)-- clearAndPrepare(ctx, dims(784))-- expect(transforms[0][0]).toBe(1)- expect(transforms[0][3]).toBe(1)- })-- it('uses the backing ratio for a normal hi-dpi canvas', () => {- Object.defineProperty(window, 'devicePixelRatio', { value: 2, configurable: true })- const { ctx, transforms } = makeCtx(1568)+ it.each([+ ['resizes a backing store sized at a stale dpr', 784, 2, 1568],+ ['keeps a backing store sized at the current dpr', 1568, 2, 1568],+ ['resizes a backing store sized for an old css width', 640, 1, 784],+ ])('%s and scales the transform to match it', (_, backingWidth, dpr, expectedBackingWidth) => {+ Object.defineProperty(window, 'devicePixelRatio', { value: dpr, configurable: true })+ const { ctx, transforms } = makeCtx(backingWidth)clearAndPrepare(ctx, dims(784))- expect(transforms[0][0]).toBe(2)- expect(transforms[0][3]).toBe(2)+ expect(ctx.canvas.width).toBe(expectedBackingWidth)+ expect(transforms[0][0]).toBe(dpr)+ expect(transforms[0][3]).toBe(dpr)})it('falls back to window.devicePixelRatio when dimensions have no width', () => {diff --git a/packages/quill/packages/charts/src/core/hooks/clearCanvas.ts b/packages/quill/packages/charts/src/core/hooks/clearCanvas.tsindex 368f960b6e9f..0e516244626c 100644--- a/packages/quill/packages/charts/src/core/hooks/clearCanvas.ts+++ b/packages/quill/packages/charts/src/core/hooks/clearCanvas.ts@@ -1,14 +1,17 @@+import { syncCanvasSize } from '../canvas-size'import type { ChartDimensions } from '../types'-/** Reset the transform to device-pixel scale and clear the whole canvas, leaving the ctx in a- * saved state the caller restores after drawing. Shared by the static and hover draw loops.+/** Size the backing store to `dimensions`, reset the transform to device-pixel scale, and clear+ * the whole canvas, leaving the ctx in a saved state the caller restores after drawing. Shared by+ * the static and hover draw loops.*- * The scale is derived from the backing store the canvas was actually sized with- * (`canvas.width / dimensions.width`) rather than a fresh `window.devicePixelRatio` read. A- * redraw can run at a different devicePixelRatio than the one that sized the backing (e.g. a- * headless export that resizes the viewport under device_scale_factor=2); reading it again here- * would scale the transform inconsistently with the canvas and magnify/clip the drawing. */+ * The resize happens here, in the same frame as the repaint, because a resize wipes the bitmap.+ * Until the draw loop runs, the canvas keeps showing the last frame.+ *+ * The scale is derived from the backing store (`canvas.width / dimensions.width`), so the+ * transform always matches the rounded integer size the canvas actually has. */export function clearAndPrepare(ctx: CanvasRenderingContext2D, dimensions: ChartDimensions): void {+ syncCanvasSize(ctx.canvas, dimensions, window.devicePixelRatio || 1)const dpr = dimensions.width > 0 ? ctx.canvas.width / dimensions.width : window.devicePixelRatio || 1ctx.save()ctx.setTransform(dpr, 0, 0, dpr, 0, 0)diff --git a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsxindex 9a0a06c3ba61..bdc8540837e5 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx+++ b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx@@ -51,6 +51,27 @@ describe('useChartCanvas', () => {resizeObserverSpy.mockRestore()})+ it('keeps the last frame until the repaint resizes the backing store', () => {+ const drawStatic = jest.fn()+ const canvas = renderChart(drawStatic)+ const frames: FrameRequestCallback[] = []+ const rafSpy = jest.spyOn(globalThis, 'requestAnimationFrame').mockImplementation((cb) => frames.push(cb))+ drawStatic.mockClear()++ try {+ reportWrapperSize(640, 300)+ expect(canvas.width).toBe(mockRect.width)+ expect(drawStatic).not.toHaveBeenCalled()++ act(() => frames.forEach((frame) => frame(0)))+ expect(canvas.width).toBe(640)+ expect(canvas.height).toBe(300)+ expect(drawStatic).toHaveBeenCalled()+ } finally {+ rafSpy.mockRestore()+ }+ })+it('keeps the painted canvas when the wrapper collapses to zero size and comes back', () => {const drawStatic = jest.fn()const canvas = renderChart(drawStatic)diff --git a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.tsindex 981692e31682..5c8fdc6f0ebd 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts@@ -1,7 +1,6 @@import { useEffect, useRef, useState } from 'react'-import { buildDimensions, sameDimensions, syncCanvasSize, type SizeRect } from '../canvas-size'-import { markPaintPending } from '../paint-state'+import { buildDimensions, sameDimensions, type SizeRect } from '../canvas-size'import type { ChartDimensions, ChartMargins } from '../types'import { useLatest } from './useLatest'@@ -58,8 +57,6 @@ export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasRereturn}- // 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) {@@ -68,8 +65,8 @@ export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasReconst rect = layoutRect ?? wrapper.getBoundingClientRect()// A sub-pixel wrapper (a `display: none` ancestor, Chromium shrinking the viewport for a tall- // screenshot) has nothing to draw, and resizing to it would wipe the bitmap. Keep the last frame,- // and replay a requested repaint (a restored context) once a real size arrives.+ // screenshot) has nothing to draw. Keep the last frame, and replay a requested repaint+ // (a restored context) once a real size arrives.if (rect.width < 1 || rect.height < 1) {deferredRepaint ||= forceRepaintreturn@@ -77,25 +74,19 @@ export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasReconst repaint = forceRepaint || deferredRepaintdeferredRepaint = falserectRef.current = rect- const dpr = window.devicePixelRatio || 1-- const staticWiped = syncCanvasSize(canvas, rect, dpr)- const overlayWiped = syncCanvasSize(overlayCanvas, rect, dpr)- if (staticWiped || repaint) {- markPaintPending(canvas)- }+ // The backing stores are not resized here. `clearAndPrepare` resizes them in the same+ // frame as the repaint, because a resize wipes the bitmap. A wipe here, in the observer+ // callback, paints one blank frame before the draw loop runs, and a continuous resize+ // (dragging a dashboard tile) keeps the chart blank until it stops.+ //// 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.+ // schedules a repaint. A restored context needs one even though no value moved, so+ // `repaint` skips the reuse of `prev`.const next = buildDimensions(rect, marginsRef.current)setCanvasState((prev) =>prev &&!repaint &&- !staticWiped &&- !overlayWiped &&prev.ctx === context &&prev.overlayCtx === overlayContext &&sameDimensions(prev.dimensions, next)diff --git a/packages/quill/packages/charts/src/testing/jsdom.ts b/packages/quill/packages/charts/src/testing/jsdom.tsindex 22e9ed2d2c54..7c90cec324b0 100644--- a/packages/quill/packages/charts/src/testing/jsdom.ts+++ b/packages/quill/packages/charts/src/testing/jsdom.ts@@ -50,8 +50,22 @@ export function setupJsdom(): () => void {* returned cleanup function in afterEach. */export function setupSyncRaf(): () => void {const original = global.requestAnimationFrame+ // A callback that requests its next frame (the hover fade) is queued and run after it returns.+ // A direct call would add one stack level per frame and overflow before the fade ends.+ let queue: FrameRequestCallback[] | null = nullglobal.requestAnimationFrame = ((cb: FrameRequestCallback) => {- cb(0)+ if (queue) {+ queue.push(cb)+ return 0+ }+ queue = [cb]+ try {+ for (let next = queue.shift(); next; next = queue.shift()) {+ next(0)+ }+ } finally {+ queue = null+ }return 0}) as typeof global.requestAnimationFrame