: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(insights): remove feature flag and make canvas detection deterministic (#72077)
Matt Pua5b0ad6256af0
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.ts b/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.tsnew file mode 100644index 000000000000..9b9297dfa928--- /dev/null+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.ts@@ -0,0 +1,87 @@+import { NodeKind } from '~/queries/schema/schema-general'+import { ChartDisplayType, DashboardPlacement, QueryBasedInsightModel } from '~/types'++import { shouldRenderInsightCardViz } from './InsightCard'++const tableQuery = { kind: NodeKind.DataTableNode } as QueryBasedInsightModel['query']+const autoSqlQuery = {+ kind: NodeKind.DataVisualizationNode,+ display: ChartDisplayType.Auto,+} as QueryBasedInsightModel['query']+const canvasQuery = {+ kind: NodeKind.DataVisualizationNode,+ display: ChartDisplayType.ActionsLineGraph,+} as QueryBasedInsightModel['query']++describe('InsightCard', () => {+ it.each([+ {+ name: 'keeps a visible table mounted when the page is hidden',+ input: {+ isStorybook: false,+ placement: DashboardPlacement.Dashboard,+ inView: true,+ isPageVisible: false,+ query: tableQuery,+ },+ expected: true,+ },+ {+ name: 'keeps an auto SQL visualization mounted because it may render a table',+ input: {+ isStorybook: false,+ placement: DashboardPlacement.Dashboard,+ inView: true,+ isPageVisible: false,+ query: autoSqlQuery,+ },+ expected: true,+ },+ {+ name: 'unmounts a visible canvas chart when the page is hidden',+ input: {+ isStorybook: false,+ placement: DashboardPlacement.Dashboard,+ inView: true,+ isPageVisible: false,+ query: canvasQuery,+ },+ expected: false,+ },+ {+ name: 'unmounts an offscreen table',+ input: {+ isStorybook: false,+ placement: DashboardPlacement.Dashboard,+ inView: false,+ isPageVisible: true,+ query: tableQuery,+ },+ expected: false,+ },+ {+ name: 'renders a visible canvas chart on a visible page',+ input: {+ isStorybook: false,+ placement: DashboardPlacement.Dashboard,+ inView: true,+ isPageVisible: true,+ query: canvasQuery,+ },+ expected: true,+ },+ {+ name: 'renders exports regardless of visibility',+ input: {+ isStorybook: false,+ placement: DashboardPlacement.Export,+ inView: false,+ isPageVisible: false,+ query: canvasQuery,+ },+ expected: true,+ },+ ])('$name', ({ input, expected }) => {+ expect(shouldRenderInsightCardViz(input)).toBe(expected)+ })+})diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsxindex 3b5a9bd9e78c..9952d5adc6ce 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx@@ -9,10 +9,8 @@ import { useInView } from 'react-intersection-observer'import { ApiError } from 'lib/api'import { Resizeable } from 'lib/components/Cards/CardMeta'-import { FEATURE_FLAGS } from 'lib/constants'import { usePageVisibility } from 'lib/hooks/usePageVisibility'import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { themeLogic } from 'lib/logic/themeLogic'import { accessLevelSatisfied, getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'@@ -30,7 +28,7 @@ import { ErrorBoundary } from '~/layout/ErrorBoundary'import { extractValidationError, extractValidationErrorCode } 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 { queryVizDefinitelyRendersToCanvas, queryVizRendersToCanvas } from '~/queries/utils'import {AccessControlLevel,AccessControlResourceType,@@ -52,6 +50,30 @@ import { InsightMeta } from './InsightMeta'const IS_STORYBOOK = inStorybook() || inStorybookTestRunner()+export function shouldRenderInsightCardViz({+ isStorybook,+ placement,+ inView,+ isPageVisible,+ query,+}: {+ isStorybook: boolean+ placement: DashboardPlacement | 'SavedInsightGrid'+ inView: boolean+ isPageVisible: boolean+ query: QueryBasedInsightModel['query']+}): boolean {+ if (isStorybook || placement === DashboardPlacement.Export) {+ return true+ }++ if (!inView) {+ return false+ }++ return isPageVisible || !queryVizDefinitelyRendersToCanvas(query)+}+const LazyEditAlertModal = React.lazy(() =>import('products/alerts/frontend/views/EditAlertModal').then(({ EditAlertModal }) => ({ default: EditAlertModal })))@@ -240,19 +262,23 @@ function InsightCardInternal(}: InsightCardProps,ref: React.Ref<HTMLDivElement>): JSX.Element | null {- const { featureFlags } = useValues(featureFlagLogic)const { ref: inViewRef, inView } = useInView({ rootMargin: '500px' })const { isVisible: isPageVisible } = usePageVisibility()- /** Wether the page is active and the line graph is currently in view. Used to free resources, by not rendering- * insight cards that aren't visible. See also https://wiki.whatwg.org/wiki/Canvas_Context_Loss_and_Restoration.- *- * We add an extra check to make sure all insights are visible in Storybook.+ const rendersToCanvas = queryVizRendersToCanvas(insight.query)++ /**+ * Hidden canvas visualizations are unmounted to release their backing stores and reduce the risk of context loss.+ * When the page is hidden, DOM and SVG visualizations stay mounted to preserve state such as table scroll position.+ * See https://wiki.whatwg.org/wiki/Canvas_Context_Loss_and_Restoration.*/- const isVisible =- featureFlags[FEATURE_FLAGS.EXPERIMENTAL_DASHBOARD_ITEM_RENDERING] === false- ? true- : IS_STORYBOOK || placement === DashboardPlacement.Export || (inView && isPageVisible)+ const shouldRenderViz = shouldRenderInsightCardViz({+ isStorybook: IS_STORYBOOK,+ placement,+ inView,+ isPageVisible,+ query: insight.query,+ })const mergedRefs = useMergeRefs([ref, inViewRef])@@ -379,10 +405,8 @@ function InsightCardInternal(}, [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>+ const vizContent = shouldRenderViz ? (+ <ResizeThrottledViz throttled={!!isResizing && rendersToCanvas}>{vizInner}</ResizeThrottledViz>) : nullreturn (diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex ec240c0c30b6..ffdf72ae34d4 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -203,9 +203,6 @@ export const FEATURE_FLAGS = {CALENDAR_HEATMAP_INSIGHT: 'calendar-heatmap-insight', // owner: @jabahamondes #team-web-analyticsCOOKIELESS_SERVER_HASH_MODE_SETTING: 'cookieless-server-hash-mode-setting', // owner: #team-web-analyticsEXPERIMENT_INTERVAL_TIMESERIES: 'experiments-interval-timeseries', // owner: @jurajmajerik #team-experiments- /* The below flag is used to activate unmounting charts outside the viewport, as we're currently investigating frontend performance- issues related to this and want to know the impact of having it on vs. off. */- EXPERIMENTAL_DASHBOARD_ITEM_RENDERING: 'experimental-dashboard-item-rendering', // owner: @thmsobrmlr #team-product-analyticsGATEWAY_PERSONAL_API_KEY: 'gateway-personal-api-key', // owner: #team-platform-featuresHEATMAPS_COHORT_FILTER: 'heatmaps-cohort-filter', // owner: #team-web-analyticsHEATMAPS_RECORDING_CLICKMAP: 'heatmaps-recording-clickmap', // owner: #team-web-analyticsdiff --git a/frontend/src/queries/utils.test.ts b/frontend/src/queries/utils.test.tsindex 12d197269af2..91710106f01a 100644--- a/frontend/src/queries/utils.test.ts+++ b/frontend/src/queries/utils.test.ts@@ -15,6 +15,7 @@ import {escapeHogQLString,escapePropertyAsHogQLIdentifier,hogql,+ queryVizDefinitelyRendersToCanvas,queryVizRendersToCanvas,supportsBarValueStacking,} from './utils'@@ -259,26 +260,65 @@ describe('queryVizRendersToCanvas', () => {({ kind: NodeKind.TrendsQuery, series: [], trendsFilter: display ? { display } : {} }) as InsightQueryNodeit.each([- { name: 'HogQL data table', query: { kind: NodeKind.DataTableNode } as any, expected: false },+ {+ name: 'HogQL data table',+ query: { kind: NodeKind.DataTableNode } as any,+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: false,+ },{name: 'SQL viz as chart',query: { kind: NodeKind.DataVisualizationNode, display: ChartDisplayType.ActionsLineGraph } as any,- expected: true,+ expectedMayRenderToCanvas: true,+ expectedDefinitelyRendersToCanvas: true,},{name: 'SQL viz as table (no display)',query: { kind: NodeKind.DataVisualizationNode } as any,- expected: false,+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: false,+ },+ {+ name: 'SQL viz with auto display',+ query: { kind: NodeKind.DataVisualizationNode, display: ChartDisplayType.Auto } as any,+ expectedMayRenderToCanvas: true,+ expectedDefinitelyRendersToCanvas: false,+ },+ {+ name: 'trends line chart',+ query: insightViz(trends(ChartDisplayType.ActionsLineGraph)),+ expectedMayRenderToCanvas: true,+ expectedDefinitelyRendersToCanvas: true,+ },+ {+ name: 'trends default display',+ query: insightViz(trends()),+ expectedMayRenderToCanvas: true,+ expectedDefinitelyRendersToCanvas: true,+ },+ {+ name: 'trends bold number',+ query: insightViz(trends(ChartDisplayType.BoldNumber)),+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: false,+ },+ {+ name: 'trends table',+ query: insightViz(trends(ChartDisplayType.ActionsTable)),+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: false,+ },+ {+ name: 'trends world map',+ query: insightViz(trends(ChartDisplayType.WorldMap)),+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: 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,+ expectedMayRenderToCanvas: true,+ expectedDefinitelyRendersToCanvas: true,},{name: 'funnel flow (Sankey)',@@ -287,7 +327,8 @@ describe('queryVizRendersToCanvas', () => {series: [],funnelsFilter: { funnelVizType: FunnelVizType.Flow },} as InsightQueryNode),- expected: false,+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: false,},{name: 'funnel time to convert (table)',@@ -296,7 +337,8 @@ describe('queryVizRendersToCanvas', () => {series: [],funnelsFilter: { funnelVizType: FunnelVizType.TimeToConvert },} as InsightQueryNode),- expected: false,+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: false,},{name: 'funnel trends (line chart)',@@ -305,16 +347,29 @@ describe('queryVizRendersToCanvas', () => {series: [],funnelsFilter: { funnelVizType: FunnelVizType.Trends },} as InsightQueryNode),- expected: true,+ expectedMayRenderToCanvas: true,+ expectedDefinitelyRendersToCanvas: true,},{name: 'retention',query: insightViz({ kind: NodeKind.RetentionQuery } as InsightQueryNode),- expected: false,+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: 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)+ {+ name: 'paths',+ query: insightViz({ kind: NodeKind.PathsQuery } as InsightQueryNode),+ expectedMayRenderToCanvas: false,+ expectedDefinitelyRendersToCanvas: false,+ },+ {+ name: 'null query',+ query: null,+ expectedMayRenderToCanvas: true,+ expectedDefinitelyRendersToCanvas: false,+ },+ ])('classifies $name', ({ query, expectedMayRenderToCanvas, expectedDefinitelyRendersToCanvas }) => {+ expect(queryVizRendersToCanvas(query)).toBe(expectedMayRenderToCanvas)+ expect(queryVizDefinitelyRendersToCanvas(query)).toBe(expectedDefinitelyRendersToCanvas)})})diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.tsindex aecd0fa8c58a..d2a76affcb85 100644--- a/frontend/src/queries/utils.ts+++ b/frontend/src/queries/utils.ts@@ -531,31 +531,47 @@ const CANVAS_CHART_DISPLAY_TYPES = new Set<ChartDisplayType>([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 {+type QueryVizCanvasClassification = 'canvas' | 'non-canvas' | 'unknown'++function classifyQueryVizCanvas(query?: Node | null): QueryVizCanvasClassification {if (isDataTableNode(query)) {- return false+ return 'non-canvas'}if (isDataVisualizationNode(query)) {- return !!query.display && CANVAS_CHART_DISPLAY_TYPES.has(query.display)+ if (!query.display) {+ return 'non-canvas'+ }+ if (query.display === ChartDisplayType.Auto) {+ return 'unknown'+ }+ return CANVAS_CHART_DISPLAY_TYPES.has(query.display) ? 'canvas' : 'non-canvas'}if (isInsightVizNode(query)) {const source = query.sourceif (isRetentionQuery(source) || isPathsQuery(source)) {- return false+ return 'non-canvas'}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 vizType !== FunnelVizType.Flow && vizType !== FunnelVizType.TimeToConvert ? 'canvas' : 'non-canvas'}- return CANVAS_CHART_DISPLAY_TYPES.has(getDisplay(source) ?? ChartDisplayType.Auto)+ return CANVAS_CHART_DISPLAY_TYPES.has(getDisplay(source) ?? ChartDisplayType.Auto) ? 'canvas' : 'non-canvas'}- return true+ return 'unknown'+}++/**+ * Whether an insight's viz may paint to a <canvas>. Unknown visualizations count as canvas so resize throttling+ * remains conservative.+ */+export function queryVizRendersToCanvas(query?: Node | null): boolean {+ return classifyQueryVizCanvas(query) !== 'non-canvas'+}++/** Whether an insight's viz is definitely canvas-backed and safe to unmount when the page is hidden. */+export function queryVizDefinitelyRendersToCanvas(query?: Node | null): boolean {+ return classifyQueryVizCanvas(query) === 'canvas'}export const getFormula = (query: InsightQueryNode | null): string | undefined => {