Skip to content

: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.

perf(dashboards): cap mounted insight tiles at 20 (#125614)

Matt Pua02c030cb1a63
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index f67fdf537b69..a9ccdb863982 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -298,7 +298,9 @@ function InsightCardInternal(
)
const { insightLoading } = useValues(insightLogic(insightLogicProps))
- const { insightDataLoading, insightDataError } = useValues(insightDataLogic(insightLogicProps))
+ const { insightDataLoading, insightDataError, savingDisplayOptions } = useValues(
+ insightDataLogic(insightLogicProps)
+ )
const [, setCooldownTick] = useState(0)
// The embedded query stores its own failure in insightDataLogic and does not set the apiError prop.
@@ -319,8 +321,11 @@ function InsightCardInternal(
const [compactInfoVisible, setCompactInfoVisible] = useState(false)
const [alertModal, setAlertModal] = useState<AlertModalState | null>(null)
useEffect(() => {
- onOverlayVisibilityChange?.(areDetailsShown || compactInfoVisible || alertModal !== null)
- }, [areDetailsShown, compactInfoVisible, alertModal, onOverlayVisibilityChange])
+ // A pending display-option save also keeps the card mounted, because unmounting its logic cancels the save.
+ onOverlayVisibilityChange?.(
+ areDetailsShown || compactInfoVisible || alertModal !== null || savingDisplayOptions
+ )
+ }, [areDetailsShown, compactInfoVisible, alertModal, savingDisplayOptions, onOverlayVisibilityChange])
const openCreateAlertModal = useCallback(() => setAlertModal({}), [])
const openEditAlertModal = useCallback((alertId: AlertType['id']) => setAlertModal({ alertId }), [])
const openCreateAnomalyAlertModal = useCallback(() => setAlertModal({ defaultToAnomalyDetection: true }), [])
diff --git a/products/dashboards/frontend/components/DashboardInsightTile.tsx b/products/dashboards/frontend/components/DashboardInsightTile.tsx
index 8f69db702936..e45988bac046 100644
--- a/products/dashboards/frontend/components/DashboardInsightTile.tsx
+++ b/products/dashboards/frontend/components/DashboardInsightTile.tsx
@@ -1,7 +1,7 @@
import { useMergeRefs } from '@floating-ui/react'
import clsx from 'clsx'
import { useActions } from 'kea'
-import { forwardRef, memo, useEffect, useMemo, useState } from 'react'
+import { forwardRef, memo, useEffect, useMemo, useRef, useState } from 'react'
import type { HTMLAttributes, ReactNode } from 'react'
import { useInView } from 'react-intersection-observer'
@@ -18,6 +18,7 @@ import type { DashboardTile, InsightModel } from '~/types'
import { DashboardPlacement } from '~/types'
import { queueDashboardInsightMount } from './dashboardInsightMountQueue'
+import { type MountedTileHandle, trackMountedDashboardTile } from './dashboardMountedTiles'
type DashboardInsightTileProps = InsightCardProps &
Pick<HTMLAttributes<HTMLDivElement>, 'onMouseDown' | 'onMouseUp' | 'onTouchStart' | 'onTouchEnd'> & {
@@ -26,6 +27,8 @@ type DashboardInsightTileProps = InsightCardProps &
}
const MemoizedInsightCard = memo(InsightCard)
+const MOUNT_MARGIN = '500px'
+const UNMOUNT_MARGIN = '1500px'
export const DashboardInsightTile = forwardRef<HTMLDivElement, DashboardInsightTileProps>(function DashboardInsightTile(
{
@@ -52,16 +55,36 @@ export const DashboardInsightTile = forwardRef<HTMLDivElement, DashboardInsightT
const [cardMounted, setCardMounted] = useState(false)
const exportPlacement = cardProps.placement === DashboardPlacement.Export
const { ref: visibilityRef, inView } = useInView({
- rootMargin: '500px',
+ rootMargin: MOUNT_MARGIN,
initialInView: exportPlacement,
- skip: exportPlacement || cardMounted,
+ skip: exportPlacement,
})
- const mergedRefs = useMergeRefs([ref, visibilityRef])
+ // A wider band than the mount margin, so a tile at the edge does not mount and unmount on small scrolls.
+ const { ref: keepRef, inView: withinKeepBand } = useInView({
+ rootMargin: UNMOUNT_MARGIN,
+ initialInView: true,
+ skip: exportPlacement,
+ })
+ const mergedRefs = useMergeRefs([ref, visibilityRef, keepRef])
useEffect(() => {
if (inView && !cardMounted) {
return queueDashboardInsightMount(() => setCardMounted(true))
}
}, [inView, cardMounted])
+ const mountedTileRef = useRef<MountedTileHandle | null>(null)
+ useEffect(() => {
+ if (cardMounted && !exportPlacement) {
+ const handle = trackMountedDashboardTile(() => setCardMounted(false))
+ mountedTileRef.current = handle
+ return () => {
+ handle.untrack()
+ mountedTileRef.current = null
+ }
+ }
+ }, [cardMounted, exportPlacement])
+ useEffect(() => {
+ mountedTileRef.current?.setReleasable(!withinKeepBand && !keepMountedForOverlay)
+ }, [cardMounted, withinKeepBand, keepMountedForOverlay])
const sharedView = isSharedView()
const tileActions = useMemo(() => {
const refresh = (updatedInsight?: InsightModel): void => {
diff --git a/products/dashboards/frontend/components/dashboardMountedTiles.test.ts b/products/dashboards/frontend/components/dashboardMountedTiles.test.ts
new file mode 100644
index 000000000000..c110021a3a1f
--- /dev/null
+++ b/products/dashboards/frontend/components/dashboardMountedTiles.test.ts
@@ -0,0 +1,38 @@
+describe('dashboardMountedTiles', () => {
+ let mod: typeof import('./dashboardMountedTiles')
+
+ beforeEach(() => {
+ jest.isolateModules(() => {
+ mod = require('./dashboardMountedTiles')
+ })
+ })
+
+ const mountTiles = (
+ count: number
+ ): { handles: ReturnType<typeof mod.trackMountedDashboardTile>[]; released: () => number[] } => {
+ const releases = Array.from({ length: count }, () => jest.fn())
+ const handles = releases.map((release) => mod.trackMountedDashboardTile(release))
+ const released = (): number[] => releases.flatMap((release, i) => (release.mock.calls.length ? [i] : []))
+ return { handles, released }
+ }
+
+ it('keeps every tile up to the limit and releases the tile that left the screen first', () => {
+ const { handles, released } = mountTiles(mod.MAX_MOUNTED_DASHBOARD_TILES)
+ handles[5].setReleasable(true)
+ handles[2].setReleasable(true)
+ expect(released()).toEqual([])
+
+ mod.trackMountedDashboardTile(jest.fn())
+
+ expect(released()).toEqual([5])
+ })
+
+ it('never releases a tile near the screen or with an open overlay, even past the limit', () => {
+ const { handles, released } = mountTiles(mod.MAX_MOUNTED_DASHBOARD_TILES + 3)
+ expect(released()).toEqual([])
+
+ handles[7].setReleasable(true)
+
+ expect(released()).toEqual([7])
+ })
+})
diff --git a/products/dashboards/frontend/components/dashboardMountedTiles.ts b/products/dashboards/frontend/components/dashboardMountedTiles.ts
new file mode 100644
index 000000000000..49e91bff8c11
--- /dev/null
+++ b/products/dashboards/frontend/components/dashboardMountedTiles.ts
@@ -0,0 +1,50 @@
+export const MAX_MOUNTED_DASHBOARD_TILES = 20
+
+type MountedTile = { releasable: boolean; leftAt: number; release: () => void }
+
+export interface MountedTileHandle {
+ setReleasable: (releasable: boolean) => void
+ untrack: () => void
+}
+
+// Small dashboards keep every tile mounted, so scrolling back stays smooth. Past the limit, the tiles that
+// left the screen first are released, so a long dashboard does not keep every chart alive after one scroll.
+const mounted = new Set<MountedTile>()
+let order = 0
+
+function releaseOverflow(): void {
+ while (mounted.size > MAX_MOUNTED_DASHBOARD_TILES) {
+ let oldest: MountedTile | null = null
+ for (const tile of mounted) {
+ if (tile.releasable && (!oldest || tile.leftAt < oldest.leftAt)) {
+ oldest = tile
+ }
+ }
+ if (!oldest) {
+ return
+ }
+ mounted.delete(oldest)
+ oldest.release()
+ }
+}
+
+export function trackMountedDashboardTile(release: () => void): MountedTileHandle {
+ const tile: MountedTile = { releasable: false, leftAt: 0, release }
+ mounted.add(tile)
+ releaseOverflow()
+ return {
+ setReleasable: (releasable) => {
+ if (releasable && !tile.releasable) {
+ // A counter, not a timestamp, so tiles that leave in the same frame keep their order.
+ tile.leftAt = ++order
+ }
+ tile.releasable = releasable
+ if (releasable && mounted.has(tile)) {
+ releaseOverflow()
+ }
+ },
+ untrack: () => {
+ mounted.delete(tile)
+ },
+ }
+}