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): improve large dashboard interaction latency (#122176)

Matt Puaead1d7fbf627
diff --git a/.agents/skills/managing-dashboards/SKILL.md b/.agents/skills/managing-dashboards/SKILL.md
index e4db9e6177a6..b06f9cef5bfa 100644
--- a/.agents/skills/managing-dashboards/SKILL.md
+++ b/.agents/skills/managing-dashboards/SKILL.md
@@ -17,6 +17,8 @@ Use this skill for a dashboard change that affects the dashboard platform, dashb
Use [`manage-dashboard-widgets`](../manage-dashboard-widgets/SKILL.md) for a new `widget_type` or a `WidgetCard` change.
For dashboard loading, scrolling, edit-mode transitions, tile movement, resize, or chart flicker, read the [dashboard performance guide](../../../products/dashboards/PERFORMANCE.md) before implementation.
+For drag or resize delays, measure start, movement, and release separately. On a long dashboard, repeat after scrolling through every tile before accepting a fix.
+For loading or scroll delays, compare a cold fast scroll with a settled repeat. Measure frame stalls and time until visible tiles display results.
## 1. Route the request
diff --git a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.test.tsx b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.test.tsx
index b4181f9df064..41a4f7344c3b 100644
--- a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.test.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.test.tsx
@@ -173,6 +173,16 @@ describe('EditModeEdgeOverlay', () => {
expect(zones[0]).not.toHaveStyle({ pointerEvents: 'none' })
})
+ it('keeps the southeast corner available over a scrollbar', () => {
+ const { onEnterEditMode, zones } = renderWithScrollableUnderneath()
+
+ fireEvent.mouseMove(zones[4], { clientX: 392, clientY: 292 })
+ expect(zones[4]).not.toHaveStyle({ pointerEvents: 'none' })
+
+ fireEvent.mouseDown(zones[4], { clientX: 392, clientY: 292 })
+ expect(onEnterEditMode).toHaveBeenCalledTimes(1)
+ })
+
it('yields every zone stacked on the point, not just the hovered one', () => {
const { zones } = renderWithScrollableUnderneath()
// Corner zones paint above edge zones near card corners. jsdom has no layout, so give the
@@ -246,6 +256,24 @@ describe('EditModeEdgeOverlay', () => {
expect(handle.style.pointerEvents).toBe('none')
})
+ it('keeps the southeast corner available over a table scrollbar', () => {
+ const { gridItem, handle } = mountEditModeTile()
+ const cornerHandle = document.createElement('span')
+ cornerHandle.className = 'react-resizable-handle react-resizable-handle-se'
+ cornerHandle.getBoundingClientRect = () =>
+ ({ left: 368, top: 268, right: 400, bottom: 300, width: 32, height: 32 }) as DOMRect
+ gridItem.appendChild(cornerHandle)
+ const cornerPress = jest.fn()
+ gridItem.addEventListener('mousedown', cornerPress)
+
+ fireEvent.mouseMove(cornerHandle, { clientX: 392, clientY: 292 })
+ expect(cornerHandle.style.pointerEvents).toBe('')
+ expect(handle.style.pointerEvents).toBe('')
+
+ fireEvent.mouseDown(cornerHandle, { clientX: 392, clientY: 292 })
+ expect(cornerPress).toHaveBeenCalledTimes(1)
+ })
+
it('stops a press over a scrollbar from reaching the grid item, but not one elsewhere', () => {
const { gridItem, scrollable } = mountEditModeTile()
const gridItemPress = jest.fn()
diff --git a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx
index e67d15fc0798..d1824a60b846 100644
--- a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx
@@ -166,14 +166,16 @@ export function useResizeHandleScrollbarPassThrough(enabled: boolean): void {
if (
!(hovered instanceof HTMLElement) ||
!(gridItem instanceof HTMLElement) ||
+ hovered.classList.contains('react-resizable-handle-se') ||
yielded.has(hovered) ||
!pointIsOverScrollbarInside(gridItem, event.clientX, event.clientY)
) {
return
}
- // Corner handles overlap the edge handles at the ends, so yield every handle stacked on
- // the point at once — otherwise the one beneath swallows a press until its own mousemove.
for (const handle of gridItem.querySelectorAll<HTMLElement>('.react-resizable-handle')) {
+ if (handle.classList.contains('react-resizable-handle-se')) {
+ continue
+ }
const rect = handle.getBoundingClientRect()
if (
event.clientX >= rect.left &&
@@ -188,6 +190,9 @@ export function useResizeHandleScrollbarPassThrough(enabled: boolean): void {
}
const handlePressCapture = (event: MouseEvent): void => {
+ if (event.target instanceof Element && event.target.closest('.react-resizable-handle-se')) {
+ return
+ }
const gridItem = event.target instanceof Element ? event.target.closest('.react-grid-item') : null
if (gridItem instanceof HTMLElement && pointIsOverScrollbarInside(gridItem, event.clientX, event.clientY)) {
event.stopPropagation()
@@ -228,7 +233,7 @@ export const EditModeEdgeOverlay: React.FC<EditModeEdgeOverlayProps> = ({ onEnte
const evaluateScrollbarPassThrough = (event: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge): void => {
const container = event.currentTarget.parentElement
- if (!container || scrollbarPassThroughEdges.has(edge)) {
+ if (!container || edge === 'se' || scrollbarPassThroughEdges.has(edge)) {
return
}
const { clientX, clientY } = event
@@ -242,7 +247,7 @@ export const EditModeEdgeOverlay: React.FC<EditModeEdgeOverlayProps> = ({ onEnte
setScrollbarPassThroughEdges((prev) => {
let next: Set<EditModeEdge> | null = null
for (const [zoneEdge, zone] of zoneRefs.current) {
- if (!zone || prev.has(zoneEdge)) {
+ if (!zone || zoneEdge === 'se' || prev.has(zoneEdge)) {
continue
}
const rect = zone.getBoundingClientRect()
@@ -295,7 +300,7 @@ export const EditModeEdgeOverlay: React.FC<EditModeEdgeOverlayProps> = ({ onEnte
// the scrollbar below. The press is lost either way (it targeted the zone), but it must not
// throw the user into edit mode when they were aiming at a scrollbar.
const container = event.currentTarget.parentElement
- if (container && pointIsOverScrollbarInside(container, event.clientX, event.clientY)) {
+ if (edge !== 'se' && container && pointIsOverScrollbarInside(container, event.clientX, event.clientY)) {
return
}
// Claim the press so it does not start a text selection; pointer travel decides whether it becomes a resize.
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 05a08e109176..7274be4fae5d 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -400,6 +400,10 @@ function InsightCardInternal(
cachedResults={insight}
context={{
insightProps: insightLogicProps,
+ dataVisualizationTableVirtualized:
+ renderVizWhenMounted && placement === DashboardPlacement.Dashboard,
+ // Small tables keep natural column widths because their full row count is cheap to render.
+ dataVisualizationTableVirtualizationCellThreshold: 100,
}}
readOnly
embedded
@@ -408,7 +412,7 @@ function InsightCardInternal(
editMode={false}
/>
)
- }, [BlockingEmptyState, insight, insightLogicProps, variablesOverride, placement])
+ }, [BlockingEmptyState, insight, insightLogicProps, variablesOverride, placement, renderVizWhenMounted])
const vizContent = shouldRenderViz ? (
<div className="InsightCard__viz">
diff --git a/frontend/src/lib/utils/reactDraggable.test.tsx b/frontend/src/lib/utils/reactDraggable.test.tsx
new file mode 100644
index 000000000000..9a9d64f2df63
--- /dev/null
+++ b/frontend/src/lib/utils/reactDraggable.test.tsx
@@ -0,0 +1,47 @@
+import { act, cleanup, fireEvent, render } from '@testing-library/react'
+import { createRef } from 'react'
+import { DraggableCore } from 'react-draggable'
+
+describe('drag selection suppression', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.runOnlyPendingTimers()
+ jest.useRealTimers()
+ })
+
+ it.each(['release', 'unmount'])('restores text selection after %s without changing body styles', (end) => {
+ const nodeRef = createRef<HTMLDivElement>()
+ const { getByTestId, unmount } = render(
+ <DraggableCore nodeRef={nodeRef}>
+ <div ref={nodeRef} data-attr="drag-target">
+ Selectable text
+ </div>
+ </DraggableCore>
+ )
+ const target = getByTestId('drag-target')
+ const beforeDrag = new Event('selectstart', { bubbles: true, cancelable: true })
+ fireEvent(target, beforeDrag)
+ expect(beforeDrag.defaultPrevented).toBe(false)
+
+ fireEvent.mouseDown(target, { button: 0, clientX: 10, clientY: 10 })
+ const duringDrag = new Event('selectstart', { bubbles: true, cancelable: true })
+ fireEvent(target, duringDrag)
+ expect(duringDrag.defaultPrevented).toBe(true)
+ expect(document.body.classList.contains('react-draggable-transparent-selection')).toBe(false)
+
+ if (end === 'release') {
+ fireEvent.mouseUp(document, { button: 0, clientX: 20, clientY: 20 })
+ } else {
+ unmount()
+ }
+ act(() => jest.runOnlyPendingTimers())
+
+ const afterDrag = new Event('selectstart', { bubbles: true, cancelable: true })
+ fireEvent(document, afterDrag)
+ expect(afterDrag.defaultPrevented).toBe(false)
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
index 409beeb1576f..564b38ea1470 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
@@ -150,7 +150,6 @@ function ColumnHeaderTitle({
export const Table = (props: TableProps): JSX.Element => {
const { isDarkModeOn } = useValues(themeLogic)
- const virtualized = !!props.embedded && !!props.context?.dataVisualizationTableVirtualized
const {
tabularData,
@@ -171,6 +170,11 @@ export const Table = (props: TableProps): JSX.Element => {
hogVm,
hogVmLoadFailed,
} = useValues(dataVisualizationLogic)
+ const virtualizationCellThreshold = props.context?.dataVisualizationTableVirtualizationCellThreshold ?? 0
+ const virtualized =
+ !!props.embedded &&
+ !!props.context?.dataVisualizationTableVirtualized &&
+ tabularData.length * tabularColumns.length > virtualizationCellThreshold
const { toggleColumnPin, setTableSorted } = useActions(dataVisualizationLogic)
const sourceTabularColumnsByName = new Map(sourceTabularColumns.map((column) => [column.column.name, column]))
diff --git a/frontend/src/queries/types.ts b/frontend/src/queries/types.ts
index 10fc1cb456f3..5459a44d8c26 100644
--- a/frontend/src/queries/types.ts
+++ b/frontend/src/queries/types.ts
@@ -70,6 +70,7 @@ export interface QueryContext<Q extends QuerySchema = QuerySchema> {
dataTableAllowContentScroll?: boolean
/** Virtualize rows in an embedded SQL result table with a bounded height. */
dataVisualizationTableVirtualized?: boolean
+ dataVisualizationTableVirtualizationCellThreshold?: number
/** Keep the Data Table header row visible while the page scrolls. See `LemonTable`'s `stickyHeader`. */
dataTableStickyHeader?: boolean
/** Override the nouns used by Data Table counts and pagination. */
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index ee41d04f2444..b8f17da7ae04 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -108,7 +108,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
} = useValues(dashboardLogic)
const { layoutZoom = 1 } = useValues(dashboardLogic)
const {
- updateLayouts,
+ stageLayouts,
updateContainerWidth,
toggleTileDescription,
removeTile,
@@ -197,7 +197,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
useDashboardLayoutInteraction({
layoutEditMode,
layoutCompaction: dashboard?.customization?.layout_compaction,
- updateLayouts,
+ updateLayouts: stageLayouts,
})
useEffect(() => {
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index b263f1d8de10..376a27a930ab 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -1983,6 +1983,134 @@ describe('dashboardLogic', () => {
})
describe('hasUnsavedLayoutChanges selector', () => {
+ it('keeps dashboard data stable while a gesture stages a layout', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ const dashboard = logic.values.dashboard
+ const firstTile = dashboard!.tiles[0]
+ const layouts = logic.values.layouts
+ const changedLayouts = {
+ ...layouts,
+ sm: layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: layout.x + 1 } : layout
+ ),
+ }
+
+ logic.actions.stageLayouts(changedLayouts)
+
+ expect(logic.values.dashboard).toBe(dashboard)
+ expect(logic.values.dashboard!.tiles[0]).toBe(firstTile)
+ expect(logic.values.layouts).toEqual(changedLayouts)
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ }).toFinishAllListeners()
+
+ expect(logic.values.draftLayouts).toBeNull()
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(false)
+ })
+
+ it('saves staged geometry', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ const firstTile = logic.values.dashboard!.tiles[0]
+ const layouts = logic.values.layouts
+ const changedLayouts = {
+ ...layouts,
+ sm: layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: layout.x + 1 } : layout
+ ),
+ }
+ logic.actions.stageLayouts(changedLayouts)
+
+ await expectLogic(logic, () => {
+ logic.actions.saveLayoutChanges()
+ }).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledWith(
+ `api/projects/${MOCK_TEAM_ID}/dashboards/5`,
+ expect.objectContaining({
+ tiles: expect.arrayContaining([
+ expect.objectContaining({
+ id: firstTile.id,
+ layouts: { sm: changedLayouts.sm?.find((layout) => layout.i === String(firstTile.id)) },
+ }),
+ ]),
+ })
+ )
+ })
+
+ it('keeps staged tile order and height when the scene becomes narrow', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ const layouts = logic.values.layouts
+ const first = layouts.sm![0]
+ const lastY = Math.max(...layouts.sm!.map((layout) => layout.y + layout.h))
+ const changedHeight = first.h + 2
+ logic.actions.stageLayouts({
+ ...layouts,
+ sm: layouts.sm?.map((layout) =>
+ layout.i === first.i ? { ...layout, y: lastY, h: changedHeight } : layout
+ ),
+ })
+ logic.actions.updateContainerWidth(500, 1)
+
+ expect(logic.values.layout?.at(-1)?.i).toBe(first.i)
+ expect(logic.values.layout?.at(-1)?.h).toBe(changedHeight)
+ })
+
+ it('keeps edits made while a layout save is in flight', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ const dashboard = logic.values.dashboard!
+ const firstTile = dashboard.tiles[0]
+ const layouts = logic.values.layouts
+ const firstDraft = {
+ ...layouts,
+ sm: layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: layout.x + 1 } : layout
+ ),
+ }
+ const secondDraft = {
+ ...layouts,
+ sm: layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: layout.x + 2 } : layout
+ ),
+ }
+ logic.actions.stageLayouts(firstDraft)
+
+ let finishSave: (dashboard: DashboardType) => void = () => {}
+ ;(api.update as jest.Mock).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishSave = resolve
+ })
+ )
+ const save = expectLogic(logic, () => {
+ logic.actions.saveLayoutChanges()
+ }).toFinishAllListeners()
+
+ logic.actions.stageLayouts(secondDraft)
+ finishSave({
+ ...dashboard,
+ tiles: dashboard.tiles.map((tile) =>
+ tile.id === firstTile.id
+ ? {
+ ...tile,
+ layouts: {
+ sm: firstDraft.sm!.find((layout) => layout.i === String(tile.id))!,
+ } as DashboardTile['layouts'],
+ }
+ : tile
+ ),
+ })
+ await save
+
+ expect(logic.values.draftLayouts).toEqual(secondDraft)
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
+ })
+
const moveFirstTile = (): void => {
const firstTile = logic.values.dashboard!.tiles[0]
const currentLayouts = logic.values.layouts
@@ -4937,21 +5065,43 @@ describe('dashboardLogic', () => {
})
it('duplicateTile refreshes newly duplicated widget tiles', async () => {
+ const savedSm = { x: 0, y: 0, w: 4, h: 5 }
+ const shiftedSm = { ...savedSm, y: 15 }
+ dashboards[5].tiles[0] = {
+ ...dashboards[5].tiles[0],
+ layouts: { sm: savedSm } as DashboardTile['layouts'],
+ }
+ const duplicatedSm = { i: '99', x: 0, y: 10, w: 6, h: 5 }
const duplicatedTile = {
id: 99,
widget: { id: '3', widget_type: 'error_tracking_list', config: { limit: 5 } },
- layouts: { sm: { i: '99', x: 0, y: 10, w: 6, h: 5 } },
+ layouts: { sm: duplicatedSm },
color: null,
} as unknown as DashboardTile
jest.spyOn(api, 'update').mockResolvedValueOnce(
- dashboardResult(5, [...dashboards[5].tiles, WIDGET_TILE, duplicatedTile])
+ dashboardResult(5, [
+ { ...dashboards[5].tiles[0], layouts: { sm: shiftedSm } as DashboardTile['layouts'] },
+ ...dashboards[5].tiles.slice(1),
+ WIDGET_TILE,
+ duplicatedTile,
+ ])
)
logic = dashboardLogic({ id: 5 })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
+ const firstTile = logic.values.dashboard!.tiles[0]
+ const layouts = logic.values.layouts
+ const changedX = (layouts.sm?.find((layout) => layout.i === String(firstTile.id))?.x ?? 0) + 1
+ logic.actions.stageLayouts({
+ ...layouts,
+ sm: layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: changedX } : layout
+ ),
+ })
+
fetchRunWidgetsMock.mockResolvedValueOnce([
{
tile_id: duplicatedTile.id,
@@ -4977,6 +5127,39 @@ describe('dashboardLogic', () => {
results: [{ id: 'issue-1' }],
hasMore: false,
})
+ expect(logic.values.layouts.sm?.find((layout) => layout.i === String(firstTile.id))).toMatchObject(
+ shiftedSm
+ )
+ expect(logic.values.layouts.sm?.find((layout) => layout.i === String(duplicatedTile.id))).toMatchObject(
+ duplicatedSm
+ )
+
+ logic.actions.stageLayouts({
+ ...logic.values.layouts,
+ sm: logic.values.layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: changedX } : layout
+ ),
+ })
+ expect(logic.values.layouts.sm?.find((layout) => layout.i === String(firstTile.id))?.x).toBe(changedX)
+
+ await expectLogic(logic, () => {
+ logic.actions.saveLayoutChanges()
+ }).toFinishAllListeners()
+ expect(api.update).toHaveBeenCalledWith(
+ `api/projects/${MOCK_TEAM_ID}/dashboards/5`,
+ expect.objectContaining({
+ tiles: expect.arrayContaining([
+ expect.objectContaining({
+ id: firstTile.id,
+ layouts: { sm: expect.objectContaining({ ...shiftedSm, x: changedX }) },
+ }),
+ expect.objectContaining({
+ id: duplicatedTile.id,
+ layouts: { sm: expect.objectContaining(duplicatedSm) },
+ }),
+ ]),
+ })
+ )
})
it('surfaces a failed tile duplicate instead of resolving it as a success', async () => {
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 101932845846..178844d48fd1 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -298,6 +298,28 @@ const tileLayoutsFromDashboard = (
return tileIdToLayouts
}
+function calculateDraftLayouts(
+ tiles: DashboardTile[],
+ draftLayouts: ResponsiveLayouts | null,
+ dashboardLayouts?: Record<DashboardTile['id'], DashboardTile['layouts']>
+): ResponsiveLayouts {
+ if (!draftLayouts) {
+ return calculateLayouts(tiles)
+ }
+
+ const draftSmByTile = new Map(draftLayouts.sm?.map((layout) => [layout.i, layout]))
+ const tilesWithDraft = tiles.map((tile) => {
+ const savedSm = dashboardLayouts?.[tile.id]?.sm
+ const serverSm = tile.layouts?.sm
+ const serverChangedSm = savedSm && serverSm && !equal(savedSm, serverSm)
+ const sm = serverChangedSm ? serverSm : (draftSmByTile.get(String(tile.id)) ?? serverSm)
+
+ return sm ? ({ ...tile, layouts: { ...tile.layouts, sm } } as DashboardTile) : tile
+ })
+
+ return calculateLayouts(tilesWithDraft)
+}
+
function mergeUpdatedWidgetTileIntoDashboard(dashboard: DashboardType, updatedTile: DashboardTile): DashboardType {
return {
...dashboard,
@@ -384,6 +406,7 @@ export interface dashboardLogicValues {
dashboardTileSpacingSaving: boolean
dataColorTheme: DataColorTheme | null
dataColorThemeId: number | null
+ draftLayouts: ResponsiveLayouts | null
effectiveBreakdownColors: BreakdownColorConfig[]
effectiveEditBarFilters: DashboardFilter
effectiveLastRefresh: Dayjs | null
@@ -417,7 +440,7 @@ export interface dashboardLogicValues {
layoutEditMode: boolean
layoutForItem: Record<string, TileLayout>
layoutZoom: number
- layouts: Partial<Record<DashboardLayoutSize, Layout>>
+ layouts: ResponsiveLayouts
loadLayoutFromServerOnPreview: boolean
loadTimer: Date | null
loadingPreview: boolean
@@ -545,6 +568,7 @@ export interface dashboardLogicActions {
clearDashboardSettingsUrlOverrides: () => {
value: true
}
+ clearDraftLayouts: () => boolean
clearInitialDashboardSettingsOverride: () => {
value: true
}
@@ -1059,6 +1083,9 @@ export interface dashboardLogicActions {
setWidgetRunResults: (results: Record<number, DashboardWidgetRunResultApi>) => {
results: Record<number, DashboardWidgetRunResultApi>
}
+ stageLayouts: (layouts: ResponsiveLayouts) => {
+ layouts: Partial<Record<string, Layout>>
+ }
tileStreamingComplete: () => {
value: true
}
@@ -1263,7 +1290,8 @@ export interface dashboardLogicMeta {
dashboardLayouts: Record<
number,
Record<string, never> | Record<DashboardLayoutSize, TileLayout> | undefined
- >
+ >,
+ draftLayouts: Partial<Record<string, Layout>> | null
) => boolean
effectiveVariablesAndAssociatedInsights: (
dashboard: DashboardType | null,
@@ -1352,9 +1380,9 @@ export interface dashboardLogicMeta {
currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType
) => boolean
sizeKey: (columns: number | null) => DashboardLayoutSize | undefined
- layouts: (tiles: DashboardTile[]) => Partial<Record<DashboardLayoutSize, Layout>>
+ layouts: (tiles: DashboardTile[], draftLayouts: Partial<Record<string, Layout>> | null) => ResponsiveLayouts
layout: (
- layouts: Partial<Record<DashboardLayoutSize, Layout>>,
+ layouts: Partial<Record<string, Layout>>,
sizeKey: DashboardLayoutSize | undefined
) => Layout | undefined
layoutForItem: (layout: Layout | undefined) => Record<string, TileLayout>
@@ -1626,6 +1654,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
* Dashboard layout & tiles.
*/
updateLayouts: (layouts: ResponsiveLayouts) => ({ layouts }),
+ stageLayouts: (layouts: ResponsiveLayouts) => ({ layouts }),
+ clearDraftLayouts: () => true,
applyDashboardUpdate: (dashboard: DashboardType, layouts: Record<number, DashboardTile['layouts']>) => ({
dashboard,
layouts,
@@ -1813,12 +1843,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
saveEditModeChanges: async ({ scope }, breakpoint) => {
cache.dashboardChangesPersisted = false
+ cache.draftLayoutsAtSave = values.draftLayouts
try {
// Only persist sm layouts; xs layouts are derived on the fly
- const layoutsToUpdate = (values.dashboard?.tiles || []).map((tile) => ({
- id: tile.id,
- layouts: tile.layouts?.sm ? { sm: tile.layouts.sm } : {},
- }))
+ const draftByTile = values.draftLayouts ? layoutsByTile(values.layouts) : null
+ const layoutsToUpdate = (values.dashboard?.tiles || []).map((tile) => {
+ const sm = draftByTile?.[tile.id]?.sm ?? tile.layouts?.sm
+ return { id: tile.id, layouts: sm ? { sm } : {} }
+ })
const currentDashboard = values.dashboard
if (!currentDashboard) {
@@ -2223,6 +2255,18 @@ export const dashboardLogic = kea<dashboardLogicType>([
}),
},
],
+ draftLayouts: [
+ null as ResponsiveLayouts | null,
+ {
+ stageLayouts: (_, { layouts }) => layouts,
+ clearDraftLayouts: () => null,
+ updateLayouts: () => null,
+ loadDashboardSuccess: () => null,
+ loadDashboardMetadataSuccess: () => null,
+ setDashboardEditing: (state, { editing, source }) =>
+ editing === null && source === DashboardEventSource.DashboardHeaderDiscardChanges ? null : state,
+ },
+ ],
// Unsaved color edits only — merged over dashboard.breakdown_colors in effectiveBreakdownColors
temporaryBreakdownColors: [
[] as BreakdownColorConfig[],
@@ -3054,17 +3098,19 @@ export const dashboardLogic = kea<dashboardLogicType>([
(settings: DashboardSettings) => settings.variables,
],
hasUnsavedLayoutChanges: [
- (s) => [s.dashboard, s.dashboardLayouts],
+ (s) => [s.dashboard, s.dashboardLayouts, s.draftLayouts],
(
dashboard: DashboardType | null,
- dashboardLayouts: Record<DashboardTile['id'], DashboardTile['layouts']>
+ dashboardLayouts: Record<DashboardTile['id'], DashboardTile['layouts']>,
+ draftLayouts: ResponsiveLayouts | null
): boolean => {
if (!dashboard) {
return false
}
+ const draftByTile = draftLayouts ? layoutsByTile(draftLayouts) : null
return (dashboard.tiles || []).some((tile: DashboardTile) => {
const originalSm = dashboardLayouts?.[tile.id]?.sm
- const currentSm = tile.layouts?.sm
+ const currentSm = draftByTile?.[tile.id]?.sm ?? tile.layouts?.sm
return !equal(originalSm || {}, currentSm || {})
})
},
@@ -3396,8 +3442,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
],
layouts: [
- (s) => [s.tiles],
- (tiles: DashboardTile[]) => calculateLayouts(tiles),
+ (s) => [s.tiles, s.draftLayouts],
+ (tiles: DashboardTile[], draftLayouts: ResponsiveLayouts | null): ResponsiveLayouts =>
+ calculateDraftLayouts(tiles, draftLayouts),
// Tile refreshes replace `tiles` once per insight response without touching geometry;
// keeping the result reference stable stops react-grid-layout re-laying-out every tile
// N times per dashboard refresh cycle.
@@ -3999,6 +4046,16 @@ export const dashboardLogic = kea<dashboardLogicType>([
return
}
+ if (values.draftLayouts) {
+ actions.stageLayouts(
+ calculateDraftLayouts(
+ dashboard.tiles.filter((tile) => !tile.deleted),
+ values.draftLayouts,
+ values.dashboardLayouts
+ )
+ )
+ }
+
const previousTileIds = cache.widgetTileIdsBeforeDuplicate as Set<number> | undefined
cache.widgetTileIdsBeforeDuplicate = undefined
if (!previousTileIds) {
@@ -4854,6 +4911,15 @@ export const dashboardLogic = kea<dashboardLogicType>([
// dashboardsModel so the sidebar and other global views stay up to date
dashboardsModel.actions.updateDashboardSuccess(dashboard, { layoutsPersisted: true })
}
+ if (
+ dashboard &&
+ payload?.scope === 'layout' &&
+ values.draftLayouts === cache.draftLayoutsAtSave &&
+ (cache.dashboardChangesPersisted || !values.hasUnsavedLayoutChanges)
+ ) {
+ actions.clearDraftLayouts()
+ }
+ cache.draftLayoutsAtSave = null
// Only toast when changes were actually persisted — the no-op exit path skips the PATCH.
if (cache.dashboardChangesPersisted) {
cache.dashboardChangesPersisted = false
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 000000000000..c92a51c37a68
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,34 @@
+diff --git a/build/cjs/utils/domFns.js b/build/cjs/utils/domFns.js
+index 8431a7f2529162109a92f82fa908341b5af54c53..3f701a7e2d277ad717a6a2b4163c55ed1fb5cecd 100644
+--- a/build/cjs/utils/domFns.js
++++ b/build/cjs/utils/domFns.js
+@@ -172,16 +172,10 @@ function getTouchIdentifier(e /*: MouseTouchEvent*/) /*: ?number*/{
+ // Note we're passing `document` b/c we could be iframed
++function preventUserSelect(event) {
++ event.preventDefault();
++}
+ function addUserSelectStyles(doc /*: ?Document*/) {
+ if (!doc) return;
+- let styleEl = doc.getElementById('react-draggable-style-el');
+- if (!styleEl) {
+- styleEl = doc.createElement('style');
+- styleEl.type = 'text/css';
+- styleEl.id = 'react-draggable-style-el';
+- styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {all: inherit;}\n';
+- styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {all: inherit;}\n';
+- doc.getElementsByTagName('head')[0].appendChild(styleEl);
+- }
+- if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');
++ doc.addEventListener('selectstart', preventUserSelect);
+ }
+ function scheduleRemoveUserSelectStyles(doc /*: ?Document*/) {
+ // Prevent a possible "forced reflow"
+@@ -196,7 +190,7 @@ function scheduleRemoveUserSelectStyles(doc /*: ?Document*/) {
+ function removeUserSelectStyles(doc /*: ?Document*/) {
+ if (!doc) return;
+ try {
+- if (doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');
++ doc.removeEventListener('selectstart', preventUserSelect);
+ // $FlowIgnore: IE
+ if (doc.selection) {
+ // $FlowIgnore: IE
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 21733f6043e0..bff368363ca4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -192,6 +192,9 @@ patchedDependencies:
'@base-ui/[email protected]':
hash: e0be9f964398f2e05b65153968c757a2869a3c5ddc6c2d3a32bf3140a4a8b34f
path: patches/@[email protected]
+ hash: b88af139afc5e153f59c5614bc991ce1404e950acff31e86a86d2f81bcf659e6
+ path: patches/[email protected]
'@connectrpc/[email protected]':
hash: a8248109885bda6ff3ce8663332190cabec9ca5da4deab47603ea6b1dbca27c4
path: patches/@[email protected]
@@ -1237,7 +1240,7 @@ importers:
version: 18.3.1([email protected])
react-draggable:
specifier: ^4.5.0
+ version: 4.5.0(patch_hash=b88af139afc5e153f59c5614bc991ce1404e950acff31e86a86d2f81bcf659e6)([email protected]([email protected]))([email protected])
react-email-editor:
specifier: ^1.7.11
version: 1.7.11([email protected])
@@ -43810,7 +43813,7 @@ snapshots:
react: 18.3.1
scheduler: 0.23.2
+ [email protected](patch_hash=b88af139afc5e153f59c5614bc991ce1404e950acff31e86a86d2f81bcf659e6)([email protected]([email protected]))([email protected]):
dependencies:
clsx: 2.1.1
prop-types: 15.8.1
@@ -43829,7 +43832,7 @@ snapshots:
prop-types: 15.8.1
react: 18.3.1
react-dom: 18.3.1([email protected])
+ react-draggable: 4.5.0(patch_hash=b88af139afc5e153f59c5614bc991ce1404e950acff31e86a86d2f81bcf659e6)([email protected]([email protected]))([email protected])
resize-observer-polyfill: 1.5.1
@@ -43840,7 +43843,7 @@ snapshots:
prop-types: 15.8.1
react: 18.3.1
react-dom: 18.3.1([email protected])
+ react-draggable: 4.5.0(patch_hash=b88af139afc5e153f59c5614bc991ce1404e950acff31e86a86d2f81bcf659e6)([email protected]([email protected]))([email protected])
resize-observer-polyfill: 1.5.1
@@ -43922,7 +43925,7 @@ snapshots:
prop-types: 15.8.1
react: 18.3.1
react-dom: 18.3.1([email protected])
+ react-draggable: 4.5.0(patch_hash=b88af139afc5e153f59c5614bc991ce1404e950acff31e86a86d2f81bcf659e6)([email protected]([email protected]))([email protected])
dependencies:
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index d2d31209b40e..d9e393011fee 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -114,6 +114,11 @@ overrides:
'@tiptap/extension-underline': 3.20.6
patchedDependencies:
+ # The drag library changes a body-wide selection style, which stalls dense dashboards.
+ # Remove this patch after an upstream release avoids that style change, or after the grid
+ # passes enableUserSelectHack=false to both drag and resize.
+ # Track https://github.com/react-grid-layout/react-draggable/issues/709.
# Browser process shims must not select v86's Node-only scheduler.
diff --git a/products/dashboards/PERFORMANCE.md b/products/dashboards/PERFORMANCE.md
index c5a86e6b4fe6..82665e0f55fb 100644
--- a/products/dashboards/PERFORMANCE.md
+++ b/products/dashboards/PERFORMANCE.md
@@ -5,9 +5,10 @@ It applies to insight, text, image, button, and widget tiles.
## Understand the cost
-Dashboard cost depends on how often work runs, how many tiles it reaches, and how expensive each tile is.
+Dashboard cost depends on how often work runs, how many elements it reaches, and how expensive each element is.
A small cost repeated across hundreds of tiles on every pointer event can block interaction.
A large cost paid once can delay the start even when subsequent frames are smooth.
+Tile count alone is a weak measure. Include rendered cells, chart points, DOM nodes, observers, and retained memory.
Separate the phases before choosing an optimization:
@@ -24,38 +25,24 @@ At 60 Hz, a frame lasts about 16.7 ms. JavaScript shares this time with browser
An animation frame callback schedules work before a paint; it does not make that work cheaper.
A save request can overlap UI work. Use the browser timeline to separate server wait from work that blocks the interface.
-## Findings from a dense local dashboard
+## Identify the limiting resource
-We compared one change group at a time on a local dashboard with 89 mixed tiles.
-The browser viewport was 1504 by 1575 pixels at a device pixel ratio of 2, with no CPU throttle.
-Each run entered and exited edit mode six times, scrolled through the dashboard, then repeated the mode change three times.
-The table uses the median of those final three changes. The current implementation ranged from 156 to 179 ms to enter and 139 to 166 ms to exit across reference runs.
+The browser main thread runs input handlers, JavaScript, React commits, style calculation, layout, and paint.
+Any one of these can delay the next frame. A slow network request can delay content without blocking input.
+The two delays need different fixes.
-| Change removed for one run | Edit entry | Edit exit | Finding |
-| ------------------------------------------- | ---------: | --------: | ------------------------------------------------------------------------------------------------------------------------------- |
-| Local edit-mode state change | 311 ms | 273 ms | State changes through the async dashboard loader caused the largest transition cost. |
-| Stable tile callbacks and decorations | 280 ms | 242 ms | New references spread a mode change into card renders. |
-| SVG grid background | 278 ms | 162 ms | Thousands of grid-cell elements mainly delayed entry. |
-| Skip save work when the layout is unchanged | 230 ms | 286 ms | Local save work delayed exit even when neither version sent a dashboard PATCH request. |
-| Mount insight cards near the viewport | 240 ms | 225 ms | Mounted insight cards rose from 2 to 49 without this limit. This run used an earlier version that unmounted cards after scroll. |
+- **CPU:** Repeated selectors, renders, data transforms, and chart drawing compete for frame time.
+- **DOM and style:** Many nodes and broad CSS changes increase style and layout work, including for content outside view.
+- **Memory:** Mounted tables, chart buffers, images, and observers remain after a scroll unless their lifecycle releases them.
+- **Network and server:** Query execution, bounded concurrency, and cache state determine when data becomes available.
+- **Scheduling:** Work that is cheap alone can cause a stall when many tiles start it in the same frame.
-These results measure each group's contribution to the current branch. They are not additive or a comparison against `master`.
-Fresh-load timing varied, so small differences need more evidence. At normal CPU speed, drag and resize had a median frame interval near 16.7 ms with every measured variant. The changes above mainly improved mode transitions and retained work; they did not establish a continuous-frame-rate gain.
+Measure cold and warm states separately. A fresh load can mount tiles, build caches, and initialize grid controls during the first interaction.
+A repeat gesture on the same page omits those costs. A full scroll can leave more content mounted than either state.
+Compare those states with the same viewport, data, and input gesture.
-A separate browser run compared the dashboard code before this PR with the current code, while both used the installed grid library version 2.3.0. The local dashboard had 89 mixed tiles. The viewport was 1504 by 1519 pixels at device pixel ratio 2, with no CPU throttle. Each variant ran three 60-frame corner resizes and three 60-frame drags.
-
-| Interaction | Before: median / p95 frame interval | Current: median / p95 frame interval | Frames over 25 ms |
-| ------------- | ----------------------------------- | ------------------------------------ | ---------------------------------- |
-| Corner resize | 16.7 / 33.3–33.7 ms | 16.7 / 17.4–17.6 ms | 10 of 177 before; 0 of 177 current |
-| Drag | 16.7 / 17.5–17.6 ms | 16.7 / 17.4–17.6 ms | 0 of 177 in both |
-
-The resize comparison shows fewer slow frames in this synthetic local gesture. It does not measure the grid library upgrade, slower devices, or production dashboards. Median FPS stayed near 60 in both variants, so the result is a reduction in resize frame spikes, not a median FPS increase.
-
-Removing content visibility, closed screenshot-editor deferral, the insight-card memo boundary alone, or persistent edge controls produced small or inconsistent timing differences in this setup.
-Do not rank those as proven gains without another workload that exposes their cost.
-A layout-compactor change reduced one 89-item helper call from about 0.009 to 0.002 ms in isolation. That difference alone cannot explain a visible delay.
-An isolated line-chart scale cache reduced calculation time but did not improve frame intervals, so we removed it.
-The grid-library upgrade, pointer handoff, and live chart redraw also affect correctness or visible behavior. This comparison did not isolate their performance effect.
+Optimize the user-visible result, not only one resource. Deferring mounts can shorten a frame stall but extend placeholder time.
+Virtualizing rows can reduce DOM size but change column sizing. Reducing query concurrency can protect the server but delay visible tiles.
## Limit how far state changes spread
@@ -63,6 +50,7 @@ React work grows with the number of components affected by a change.
Dashboard-wide state can make every card render even when only one tile moves.
- Keep transient geometry close to the grid or active tile.
+- Keep completed layout edits separate from dashboard tile data until Save. Replacing every tile on pointer release can invalidate dashboard-wide selectors and delay the next paint.
- Separate a light geometry wrapper from expensive card content.
- Preserve references for unchanged data, configuration, layout items, and callbacks where render boundaries depend on them.
- Check which props actually change before adding memoization.
@@ -92,6 +80,7 @@ Deferred activation must retain the latest pointer position and wait until the g
DOM size, CSS dependencies, and visible area affect style calculation, layout, paint, and compositing.
A global class change can invalidate many tiles even when React skips their renders.
+Check third-party drag and resize code for global style changes. Recheck upstream behavior before changing a local workaround.
- Inspect browser style and layout costs alongside React commits.
- Avoid alternating geometry reads and DOM writes across tiles. Group required reads before writes.
@@ -109,22 +98,28 @@ In a vertically compacted grid, shrinking a tile from its top edge opens space a
A long dashboard should avoid mounting every expensive card at initial load.
Track DOM nodes, chart instances, observers, timers, decoded images, and memory after a full scroll and return.
+Measure edit entry after a full scroll. Dense SQL tables can make this transition slow even when the tile count is unchanged.
+Count rendered cells and DOM nodes as well as tiles. A few dense tables can cost more than many simple charts.
- Mount expensive content near the viewport when the surface permits it.
- Apply that limit to widget bodies as well as insight charts. Offscreen list widgets can retain thousands of DOM nodes.
-- Keep live widget bodies mounted because their data streams update in the component.
+- Before unmounting a live widget, preserve its data stream and recovery state outside the component.
- Keep a card mounted after its first display if it owns saves, query results, refresh polling, or mutation recovery.
- Release offscreen resources only after their work and state have a durable owner elsewhere.
- Preserve active gestures, open dialogs or details, and export rendering.
- Keep enough layout information to preserve tile positions while content is absent.
- Render a cheap placeholder for an unmounted tile so a fast scroll never exposes an empty grid cell.
-- Avoid a second visibility delay after the tile mounts; the mount boundary already limits offscreen work.
+- When many tiles enter view together, spread expensive mounts across frames and show a useful placeholder.
+- Cancel a pending mount if its tile leaves view before the mount starts.
- Avoid remounting neighboring content solely because its position changes.
- Inspect existing observer sharing before introducing another observer layer.
Choose the viewport margin from the tradeoff between preparation time and retained work.
A mount-once policy delays initial cost but can still retain the entire dashboard after scrolling.
Unmounting can also cause repeated initialization or queries; measure both resource use and revisit behavior.
+For a fast scroll jump, measure the longest frame and the time until every newly visible card displays content.
+Spreading mounts across frames can reduce one stall while increasing the time a visible card shows a placeholder.
+For virtualized tables, check column widths, pinned columns, horizontal scroll, the last row, and export.
## Make chart resize proportional to the change
@@ -150,6 +145,8 @@ Mode changes and virtualization must not accidentally invalidate queries or star
- Distinguish data loading state from local interaction state.
- Inspect request counts during mode changes, gestures, scrolling, and revisits.
- Bound query concurrency and response processing during dashboard load or refresh.
+- Trace tile delivery, card mount, query queue wait, query execution, and result paint separately during a cold load.
+- Check whether visible tiles wait behind offscreen tiles in a bounded refresh queue.
- Avoid unnecessary saves when no persisted state changed.
- Preserve save errors, cancellation, and final layout correctness when moving work off the interaction path.
- Check the local work done by an unchanged save. Zero network requests do not prove that exit is cheap.
@@ -164,10 +161,16 @@ If checks are paused, identify the unverified behavior and leave the change loca
1. Define the phase and observable result: input-to-paint latency, frame intervals, long tasks, request count, or retained resources.
2. Use invented data with representative tile types, chart complexity, dashboard length, and layout density.
+ Include dense SQL tables and tiles with different row and column counts.
3. Record a baseline with fixed viewport, zoom, device pixel ratio, browser, and CPU settings.
4. Use a browser trace to locate scripting, React, style, layout, paint, and network costs.
5. Change one suspected cause. Repeat the same interaction and report variation.
-6. Stop traces and detach diagnostic sessions. Repeat timing measurements without profiling overhead.
+6. Measure pointer release separately from continuous movement. Include the synchronous work before mouse-up returns and the next paint.
+7. For a long dashboard, scroll through every tile before the gesture. Retained tables and charts can change the release cost.
+8. If release is slow, trace the final grid callback through Kea actions, reducers, selectors, React commits, and browser work. A fast grid calculation does not prove a fast commit.
+9. Compare against a temporary no-op for the suspected update, then restore it. Confirm that the measured cost belongs to that update before changing state ownership.
+10. Stop traces and detach diagnostic sessions. Repeat timing measurements without profiling overhead.
+11. Compare the first gesture after a fresh load with a repeat gesture on the same page. Record whether tiles still mount during the gesture.
An A/B comparison needs a stable outcome as well as a timing difference.
Check that both variants save, cancel, move, resize, and display charts correctly.
@@ -180,6 +183,7 @@ Check the following boundaries for interaction changes:
- Horizontal and vertical resize, affected neighbors, and supported compaction modes.
- A narrow scene with an open side panel, plus a wide scene.
- A full scroll and return, including mounted content, memory, and request counts.
+- A fast jump to the middle of a cold dashboard, including frame time, placeholder duration, and query queue wait.
- Chart line visibility throughout resize. A screenshot at rest cannot establish the absence of blank frames.
Report the conditions, user-visible result, and remaining gaps.
diff --git a/products/dashboards/frontend/components/DashboardInsightTile.tsx b/products/dashboards/frontend/components/DashboardInsightTile.tsx
index 0c912a034cab..8f69db702936 100644
--- a/products/dashboards/frontend/components/DashboardInsightTile.tsx
+++ b/products/dashboards/frontend/components/DashboardInsightTile.tsx
@@ -1,13 +1,14 @@
import { useMergeRefs } from '@floating-ui/react'
import clsx from 'clsx'
import { useActions } from 'kea'
-import { forwardRef, memo, useMemo, useState } from 'react'
+import { forwardRef, memo, useEffect, useMemo, useState } from 'react'
import type { HTMLAttributes, ReactNode } from 'react'
import { useInView } from 'react-intersection-observer'
import { DashboardResizeHandles } from 'lib/components/Cards/handles'
import { EditModeEdgeOverlay } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
import { InsightCard, InsightCardProps } from 'lib/components/Cards/InsightCard/InsightCard'
+import { InsightVisualizationSkeleton } from 'lib/components/Cards/InsightCard/InsightVisualizationSkeleton'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
@@ -16,6 +17,8 @@ import { insightsModel } from '~/models/insightsModel'
import type { DashboardTile, InsightModel } from '~/types'
import { DashboardPlacement } from '~/types'
+import { queueDashboardInsightMount } from './dashboardInsightMountQueue'
+
type DashboardInsightTileProps = InsightCardProps &
Pick<HTMLAttributes<HTMLDivElement>, 'onMouseDown' | 'onMouseUp' | 'onTouchStart' | 'onTouchEnd'> & {
tile: DashboardTile
@@ -46,14 +49,19 @@ export const DashboardInsightTile = forwardRef<HTMLDivElement, DashboardInsightT
const { renameInsight } = useActions(insightsModel)
const { tile, insight } = cardProps
const [keepMountedForOverlay, setKeepMountedForOverlay] = useState(false)
+ const [cardMounted, setCardMounted] = useState(false)
const exportPlacement = cardProps.placement === DashboardPlacement.Export
const { ref: visibilityRef, inView } = useInView({
rootMargin: '500px',
- triggerOnce: true,
initialInView: exportPlacement,
- skip: exportPlacement,
+ skip: exportPlacement || cardMounted,
})
const mergedRefs = useMergeRefs([ref, visibilityRef])
+ useEffect(() => {
+ if (inView && !cardMounted) {
+ return queueDashboardInsightMount(() => setCardMounted(true))
+ }
+ }, [inView, cardMounted])
const sharedView = isSharedView()
const tileActions = useMemo(() => {
const refresh = (updatedInsight?: InsightModel): void => {
@@ -81,7 +89,7 @@ export const DashboardInsightTile = forwardRef<HTMLDivElement, DashboardInsightT
])
const gridClasses = className?.split(' ') ?? []
const interactionActive = gridClasses.includes('resizing') || gridClasses.includes('react-draggable-dragging')
- const shouldMountCard = inView || exportPlacement || interactionActive || keepMountedForOverlay
+ const shouldMountCard = cardMounted || exportPlacement || interactionActive || keepMountedForOverlay
return (
<div
@@ -106,7 +114,11 @@ export const DashboardInsightTile = forwardRef<HTMLDivElement, DashboardInsightT
) : (
<div className="dashboard-insight-tile__placeholder" aria-hidden="true">
<LemonSkeleton className="h-3 w-2/5" active={false} />
- <LemonSkeleton className="min-h-0 w-full flex-1" active={false} />
+ {inView ? (
+ <InsightVisualizationSkeleton query={insight.query} />
+ ) : (
+ <LemonSkeleton className="min-h-0 w-full flex-1" active={false} />
+ )}
</div>
)}
{showResizeHandles && <DashboardResizeHandles />}
diff --git a/products/dashboards/frontend/components/dashboardInsightMountQueue.ts b/products/dashboards/frontend/components/dashboardInsightMountQueue.ts
new file mode 100644
index 000000000000..a9c2be8e2d6e
--- /dev/null
+++ b/products/dashboards/frontend/components/dashboardInsightMountQueue.ts
@@ -0,0 +1,33 @@
+type MountRequest = { mount: () => void; cancelled: boolean }
+
+// A shared queue prevents a fast scroll from mounting all newly visible insight cards in one frame.
+const pending: MountRequest[] = []
+let scheduled = false
+
+function processNextMount(): void {
+ scheduled = false
+ let request = pending.shift()
+ while (request?.cancelled) {
+ request = pending.shift()
+ }
+ request?.mount()
+ if (pending.length > 0) {
+ scheduleNextMount()
+ }
+}
+
+function scheduleNextMount(): void {
+ if (!scheduled) {
+ scheduled = true
+ requestAnimationFrame(processNextMount)
+ }
+}
+
+export function queueDashboardInsightMount(mount: () => void): () => void {
+ const request = { mount, cancelled: false }
+ pending.push(request)
+ scheduleNextMount()
+ return () => {
+ request.cancelled = true
+ }
+}