: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(dashboards): keep tile content visible while resizing (#69453)
Matt Puaa1dc422e8c3a
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss b/frontend/src/lib/components/Cards/InsightCard/InsightCard.scssindex 19ba2c780e04..39066067f79b 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss@@ -58,4 +58,22 @@.WebAnalyticsDashboard .InsightVizDisplay & {min-height: var(--insight-viz-min-height);}++ // Clip while the JS-throttled pinned size lags the growing/shrinking tile mid-resize.+ &--resizing {+ overflow: hidden;+ }+}++.InsightCard__vizInner {+ display: flex;+ flex: 1;+ flex-direction: column;+ width: 100%;+ min-height: 0;++ .InsightCard__viz--resizing & {+ flex: none;+ pointer-events: none;+ }}diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsxindex 7d5d5f7c2126..cb8be304eb83 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx@@ -3,7 +3,7 @@ import './InsightCard.scss'import { useMergeRefs } from '@floating-ui/react'import clsx from 'clsx'import { BindLogic, useActions, useValues } from 'kea'-import React, { useMemo, useState } from 'react'+import React, { useLayoutEffect, useMemo, useRef, useState } from 'react'import { LayoutItem } from 'react-grid-layout'import { useInView } from 'react-intersection-observer'@@ -29,6 +29,7 @@ import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { extractValidationError } from '~/queries/nodes/InsightViz/utils'import { Query } from '~/queries/Query/Query'import { DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'+import { queryVizRendersToCanvas } from '~/queries/utils'import {AccessControlLevel,AccessControlResourceType,@@ -47,6 +48,73 @@ import { InsightMeta } from './InsightMeta'const IS_STORYBOOK = inStorybook() || inStorybookTestRunner()+const RESIZE_REDRAW_THROTTLE_MS = 33 // ~30x/sec++/**+ * Throttles a canvas chart's redraws while its dashboard tile is resized, instead of repainting on every frame.+ * Pinning the inner wrapper to a fixed size means the chart's own ResizeObserver only fires when we push a new+ * size, which we do at most once per {@link RESIZE_REDRAW_THROTTLE_MS}. Unpinning on resize-stop redraws once+ * at the exact final size.+ */+function ResizeThrottledViz({ throttled, children }: { throttled: boolean; children: React.ReactNode }): JSX.Element {+ const outerRef = useRef<HTMLDivElement>(null)+ const innerRef = useRef<HTMLDivElement>(null)++ useLayoutEffect(() => {+ const outer = outerRef.current+ const inner = innerRef.current+ if (!throttled || !outer || !inner) {+ return+ }++ let lastPush = 0+ let trailing: ReturnType<typeof setTimeout> | undefined++ const pushSize = (): void => {+ lastPush = performance.now()+ const rect = outer.getBoundingClientRect()+ inner.style.width = `${rect.width}px`+ inner.style.height = `${rect.height}px`+ }+ pushSize()++ const onOuterResize = (): void => {+ const elapsed = performance.now() - lastPush+ if (elapsed >= RESIZE_REDRAW_THROTTLE_MS) {+ if (trailing) {+ clearTimeout(trailing)+ trailing = undefined+ }+ pushSize()+ } else if (!trailing) {+ trailing = setTimeout(() => {+ trailing = undefined+ pushSize()+ }, RESIZE_REDRAW_THROTTLE_MS - elapsed)+ }+ }+ const observer = new ResizeObserver(onOuterResize)+ observer.observe(outer)++ return () => {+ observer.disconnect()+ if (trailing) {+ clearTimeout(trailing)+ }+ inner.style.width = ''+ inner.style.height = ''+ }+ }, [throttled])++ return (+ <div ref={outerRef} className={clsx('InsightCard__viz', throttled && 'InsightCard__viz--resizing')}>+ <div ref={innerRef} className="InsightCard__vizInner">+ {children}+ </div>+ </div>+ )+}+export interface InsightCardProps extends Resizeable {/** Insight to display. */insight: QueryBasedInsightModel@@ -66,7 +134,7 @@ export interface InsightCardProps extends Resizeable {timedOut?: boolean/** Whether the editing controls should be enabled or not. */showEditingControls?: boolean- /** While this tile is being resized: unmount the viz so the chart doesn't redraw on every frame. */+ /** While this tile is being resized: throttle canvas chart redraws instead of repainting on every frame. */isResizing?: boolean/** Whether the controls for showing details should be enabled or not. */showDetailsControls?: boolean@@ -262,39 +330,34 @@ function InsightCardInternal(return null})()- // Memoize the viz so the (expensive) chart subtree isn't reconciled when the card re-renders only because- // react-grid-layout reflowed it — e.g. while a sibling tile is dragged or resized. React reuses the cached- // element when these inputs are unchanged, so only the tiles whose data actually changed redraw.- const vizContent = useMemo(() => {- if (isResizing) {- // Skip the chart while resizing — keeping it mounted would redraw the canvas on every frame as the- // tile's dimensions change. Remounts from cached results once resizing stops.- return <div className="InsightCard__viz" />- }- if (!isVisible) {- return null+ // Excludes isResizing from the deps so the element stays referentially stable across resize toggles — that's+ // what lets ResizeThrottledViz throttle the live chart instead of remounting (and reloading) it.+ const vizInner = useMemo(() => {+ if (BlockingEmptyState) {+ return BlockingEmptyState}return (- <div className="InsightCard__viz">- {BlockingEmptyState ? (- BlockingEmptyState- ) : (- <Query- query={insight.query}- cachedResults={insight}- context={{- insightProps: insightLogicProps,- }}- readOnly- embedded- inSharedMode={placement === DashboardPlacement.Public}- variablesOverride={variablesOverride}- editMode={false}- />- )}- </div>+ <Query+ query={insight.query}+ cachedResults={insight}+ context={{+ insightProps: insightLogicProps,+ }}+ readOnly+ embedded+ inSharedMode={placement === DashboardPlacement.Public}+ variablesOverride={variablesOverride}+ editMode={false}+ />)- }, [isResizing, isVisible, BlockingEmptyState, insight, insightLogicProps, variablesOverride, placement])+ }, [BlockingEmptyState, insight, insightLogicProps, variablesOverride, placement])++ // Only canvas viz (charts) redraw per resize frame; tables/numbers/maps are cheap DOM/SVG and stay fully live.+ const vizContent = isVisible ? (+ <ResizeThrottledViz throttled={!!isResizing && queryVizRendersToCanvas(insight.query)}>+ {vizInner}+ </ResizeThrottledViz>+ ) : nullreturn (<divdiff --git a/frontend/src/queries/utils.test.ts b/frontend/src/queries/utils.test.tsindex 5c33a46ee1bf..12d197269af2 100644--- a/frontend/src/queries/utils.test.ts+++ b/frontend/src/queries/utils.test.ts@@ -7,7 +7,7 @@ import { teamLogic } from 'scenes/teamLogic'import { DataTableNode, DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'import type { InsightQueryNode } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { AppContext, ChartDisplayType, TeamType } from '~/types'+import { AppContext, ChartDisplayType, FunnelVizType, TeamType } from '~/types'import {convertDataTableNodeToDataVisualizationNode,@@ -15,6 +15,7 @@ import {escapeHogQLString,escapePropertyAsHogQLIdentifier,hogql,+ queryVizRendersToCanvas,supportsBarValueStacking,} from './utils'@@ -251,3 +252,69 @@ describe('supportsBarValueStacking', () => {expect(supportsBarValueStacking(query)).toBe(expected)})})++describe('queryVizRendersToCanvas', () => {+ const insightViz = (source: InsightQueryNode): any => ({ kind: NodeKind.InsightVizNode, source })+ const trends = (display?: ChartDisplayType): InsightQueryNode =>+ ({ kind: NodeKind.TrendsQuery, series: [], trendsFilter: display ? { display } : {} }) as InsightQueryNode++ it.each([+ { name: 'HogQL data table', query: { kind: NodeKind.DataTableNode } as any, expected: false },+ {+ name: 'SQL viz as chart',+ query: { kind: NodeKind.DataVisualizationNode, display: ChartDisplayType.ActionsLineGraph } as any,+ expected: true,+ },+ {+ name: 'SQL viz as table (no display)',+ query: { kind: NodeKind.DataVisualizationNode } as any,+ expected: false,+ },+ { name: 'trends line chart', query: insightViz(trends(ChartDisplayType.ActionsLineGraph)), expected: true },+ { name: 'trends default display', query: insightViz(trends()), expected: true },+ { name: 'trends bold number', query: insightViz(trends(ChartDisplayType.BoldNumber)), expected: false },+ { name: 'trends table', query: insightViz(trends(ChartDisplayType.ActionsTable)), expected: false },+ { name: 'trends world map', query: insightViz(trends(ChartDisplayType.WorldMap)), expected: false },+ {+ name: 'funnel steps (default)',+ query: insightViz({ kind: NodeKind.FunnelsQuery, series: [] } as InsightQueryNode),+ expected: true,+ },+ {+ name: 'funnel flow (Sankey)',+ query: insightViz({+ kind: NodeKind.FunnelsQuery,+ series: [],+ funnelsFilter: { funnelVizType: FunnelVizType.Flow },+ } as InsightQueryNode),+ expected: false,+ },+ {+ name: 'funnel time to convert (table)',+ query: insightViz({+ kind: NodeKind.FunnelsQuery,+ series: [],+ funnelsFilter: { funnelVizType: FunnelVizType.TimeToConvert },+ } as InsightQueryNode),+ expected: false,+ },+ {+ name: 'funnel trends (line chart)',+ query: insightViz({+ kind: NodeKind.FunnelsQuery,+ series: [],+ funnelsFilter: { funnelVizType: FunnelVizType.Trends },+ } as InsightQueryNode),+ expected: true,+ },+ {+ name: 'retention',+ query: insightViz({ kind: NodeKind.RetentionQuery } as InsightQueryNode),+ expected: false,+ },+ { name: 'paths', query: insightViz({ kind: NodeKind.PathsQuery } as InsightQueryNode), expected: false },+ { name: 'null query', query: null, expected: true },+ ])('returns $expected for $name', ({ query, expected }) => {+ expect(queryVizRendersToCanvas(query)).toBe(expected)+ })+})diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.tsindex 45c4ba9505b4..c841f894f71b 100644--- a/frontend/src/queries/utils.ts+++ b/frontend/src/queries/utils.ts@@ -79,7 +79,7 @@ import {WebVitalsPathBreakdownQuery,WebVitalsQuery,} from '~/queries/schema/schema-general'-import { BaseMathType, ChartDisplayType, GroupTypeIndex, IntervalType } from '~/types'+import { BaseMathType, ChartDisplayType, FunnelVizType, GroupTypeIndex, IntervalType } from '~/types'import { LATEST_VERSIONS } from './latest-versions'@@ -508,6 +508,51 @@ export const getDisplay = (query: InsightQueryNode): ChartDisplayType | undefinereturn undefined}+// Display types whose viz paints to a <canvas> (Chart.js / quill-charts), which repaints on every resize+// frame. Everything else renders as DOM/SVG and is cheap to keep mounted while a tile is resized.+const CANVAS_CHART_DISPLAY_TYPES = new Set<ChartDisplayType>([+ ChartDisplayType.Auto,+ ChartDisplayType.ActionsLineGraph,+ ChartDisplayType.ActionsLineGraphCumulative,+ ChartDisplayType.ActionsAreaGraph,+ ChartDisplayType.ActionsBar,+ ChartDisplayType.ActionsUnstackedBar,+ ChartDisplayType.ActionsStackedBar,+ ChartDisplayType.ActionsBarValue,+ ChartDisplayType.ActionsPie,+ ChartDisplayType.Metric,+ ChartDisplayType.BoxPlot,+ ChartDisplayType.SlopeGraph,+ ChartDisplayType.TwoDimensionalHeatmap,+])++/**+ * Whether an insight's viz paints to a <canvas>. Canvas viz redraws on every resize frame, so a dashboard tile+ * throttles its redraws while resizing; DOM/SVG viz (tables, bold numbers, world maps, retention, paths) is cheap+ * and stays fully live. Unrecognised node types default to true so we never regress resize perf for unknown viz.+ */+export function queryVizRendersToCanvas(query?: Node | null): boolean {+ if (isDataTableNode(query)) {+ return false+ }+ if (isDataVisualizationNode(query)) {+ return !!query.display && CANVAS_CHART_DISPLAY_TYPES.has(query.display)+ }+ if (isInsightVizNode(query)) {+ const source = query.source+ if (isRetentionQuery(source) || isPathsQuery(source)) {+ return false+ }+ if (isFunnelsQuery(source)) {+ // Steps (default) and Trends paint to canvas; Flow (Sankey) is SVG and TimeToConvert is a DOM table.+ const vizType = source.funnelsFilter?.funnelVizType+ return vizType !== FunnelVizType.Flow && vizType !== FunnelVizType.TimeToConvert+ }+ return CANVAS_CHART_DISPLAY_TYPES.has(getDisplay(source) ?? ChartDisplayType.Auto)+ }+ return true+}+export const getFormula = (query: InsightQueryNode | null): string | undefined => {if (isTrendsQuery(query)) {return (