: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
perf(dashboards): improve perf when resizing tiles on dashboards (#119866)
Matt Puada612011477f
diff --git a/.agents/skills/managing-dashboards/SKILL.md b/.agents/skills/managing-dashboards/SKILL.mdindex 8aa2bf319e8a..e4db9e6177a6 100644--- a/.agents/skills/managing-dashboards/SKILL.md+++ b/.agents/skills/managing-dashboards/SKILL.md@@ -4,7 +4,8 @@ description: >Guides PostHog engineers through dashboard platform and scene changes. Use when changingDashboard, DashboardTile, dashboardLogic, dashboard layouts, dashboard sharing or embeds,public dashboards, templates, filters, variables, refresh behavior, tile loading, dashboard- lists, or dashboard permissions. Covers normal, shared, embedded, export, product-embedded,+ lists, or dashboard permissions. Also use for slow dashboard loading, scrolling, edit-mode entry or exit,+ low frame rates, chart flicker, and tile drag or resize performance. Covers normal, shared, embedded, export, product-embedded,and template surfaces; RBAC; cache and query behavior; responsive layouts; and large or smalldashboards. Use manage-dashboard-widgets instead for a widget_type or WidgetCard change.---@@ -15,6 +16,8 @@ Use this skill for a dashboard change that affects the dashboard platform, dashbUse [`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.+## 1. Route the request| Request | Primary path |diff --git a/frontend/package.json b/frontend/package.jsonindex b1ec243e79c0..97eb6679c3c5 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -277,7 +277,7 @@"react-dom": "^18.3.1","react-draggable": "^4.5.0","react-email-editor": "^1.7.11",- "react-grid-layout": "^2.2.4",+ "react-grid-layout": "^2.3.0","react-intersection-observer": "^9.5.3","react-markdown": "^9.0.0","react-modal": "^3.15.1",diff --git a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsxindex 1e9098afee4f..fea644047f17 100644--- a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx+++ b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx@@ -105,7 +105,7 @@ function ButtonTileCardInternal(</LemonButton></div>- {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (+ {(canEnterEditModeFromEdge || showResizeHandles) && onEnterEditModeFromEdge && (<EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />)}{showResizeHandles && <DashboardResizeHandles />}diff --git a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.test.tsx b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.test.tsxindex 63fcee74b5ac..b4181f9df064 100644--- a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.test.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.test.tsx@@ -83,25 +83,22 @@ describe('EditModeEdgeOverlay', () => {return el}- it('renders eight edge and corner hit areas with data attr', () => {+ it('renders five edge and corner hit areas with data attr', () => {const { getAllByTitle } = render(<EditModeEdgeOverlay onEnterEditMode={() => {}} />)const zones = getAllByTitle('Drag to resize')- expect(zones).toHaveLength(8)+ expect(zones).toHaveLength(5)zones.forEach((zone) => {expect(zone).toHaveAttribute('data-attr', 'dashboard-edit-mode-from-card-edge')})})it.each([- [0, 'n'],- [1, 's'],- [2, 'w'],- [3, 'e'],- [4, 'nw'],- [5, 'ne'],- [6, 'sw'],- [7, 'se'],+ [0, 's'],+ [1, 'w'],+ [2, 'e'],+ [3, 'sw'],+ [4, 'se'],])('calls onEnterEditMode with the pressed direction when zone %i is pressed', (zoneIndex, expectedEdge) => {const onEnterEditMode = jest.fn()@@ -132,7 +129,7 @@ describe('EditModeEdgeOverlay', () => {// Enter a corner, then the adjacent edge, before leaving the corner — count must not hit zero.fireEvent.mouseEnter(zones[0])- fireEvent.mouseEnter(zones[4])+ fireEvent.mouseEnter(zones[3])fireEvent.mouseLeave(zones[0])expect(container.querySelectorAll('.handle')).toHaveLength(1)})@@ -151,7 +148,7 @@ describe('EditModeEdgeOverlay', () => {const scrollable = fakeScrollableElement(SCROLLABLE_BASE)container.appendChild(scrollable)jest.spyOn(document, 'elementsFromPoint').mockImplementation((x: number, y: number) =>- x >= 0 && x <= 400 && y >= 0 && y <= 300 ? [zones[1], scrollable] : []+ x >= 0 && x <= 400 && y >= 0 && y <= 300 ? [zones[0], scrollable] : [])return { onEnterEditMode, zones, scrollable }}@@ -159,21 +156,21 @@ describe('EditModeEdgeOverlay', () => {it('does not enter edit mode when the press lands on a scrollbar under the zone', () => {const { onEnterEditMode, zones } = renderWithScrollableUnderneath()- fireEvent.mouseDown(zones[1], { clientX: 200, clientY: 292 })+ fireEvent.mouseDown(zones[0], { clientX: 200, clientY: 292 })expect(onEnterEditMode).not.toHaveBeenCalled()- fireEvent.mouseDown(zones[1], { clientX: 200, clientY: 150 })+ fireEvent.mouseDown(zones[0], { clientX: 200, clientY: 150 })expect(onEnterEditMode).toHaveBeenCalledTimes(1)})it('lets pointer events through while hovering a scrollbar and recaptures them after', () => {const { zones } = renderWithScrollableUnderneath()- fireEvent.mouseMove(zones[1], { clientX: 200, clientY: 292 })- expect(zones[1]).toHaveStyle({ pointerEvents: 'none' })+ fireEvent.mouseMove(zones[0], { clientX: 200, clientY: 292 })+ expect(zones[0]).toHaveStyle({ pointerEvents: 'none' })fireEvent.mouseMove(document, { clientX: 200, clientY: 150 })- expect(zones[1]).not.toHaveStyle({ pointerEvents: 'none' })+ expect(zones[0]).not.toHaveStyle({ pointerEvents: 'none' })})it('yields every zone stacked on the point, not just the hovered one', () => {@@ -181,18 +178,18 @@ describe('EditModeEdgeOverlay', () => {// Corner zones paint above edge zones near card corners. jsdom has no layout, so give the// sw corner and s edge zones their real overlapping geometry at the card's bottom-left.const rects: Array<[number, { left: number; top: number; right: number; bottom: number }]> = [- [1, { left: 0, top: 288, right: 400, bottom: 302 }],- [6, { left: -2, top: 284, right: 16, bottom: 302 }],+ [0, { left: 0, top: 288, right: 400, bottom: 302 }],+ [3, { left: -2, top: 284, right: 16, bottom: 302 }],]for (const [index, rect] of rects) {zones[index].getBoundingClientRect = () =>({ ...rect, width: rect.right - rect.left, height: rect.bottom - rect.top }) as DOMRect}- fireEvent.mouseMove(zones[6], { clientX: 8, clientY: 292 })+ fireEvent.mouseMove(zones[3], { clientX: 8, clientY: 292 })- expect(zones[6]).toHaveStyle({ pointerEvents: 'none' })- expect(zones[1]).toHaveStyle({ pointerEvents: 'none' })+ expect(zones[3]).toHaveStyle({ pointerEvents: 'none' })+ expect(zones[0]).toHaveStyle({ pointerEvents: 'none' })})})diff --git a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsxindex 7f33c250256a..e67d15fc0798 100644--- a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx@@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from 'react'import { DashboardResizeHandles } from 'lib/components/Cards/handles'-export type EditModeEdge = 'n' | 's' | 'w' | 'e' | 'nw' | 'ne' | 'sw' | 'se'+export type EditModeEdge = 's' | 'w' | 'e' | 'sw' | 'se'interface EditModeEdgeOverlayProps {onEnterEditMode: (event: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => void@@ -19,19 +19,14 @@ const edgeOverlayBaseStyle: React.CSSProperties = {background: 'none',}-// Top/bottom zones hug the tile border. They still win the shared border pixel via a higher z-index.-const TOP_BOTTOM_Z = 7+const BOTTOM_EDGE_Z = 7// Corners sit above edges so a press in the corner resolves to the diagonal handle.-const cornerZoneStyle: React.CSSProperties = { zIndex: TOP_BOTTOM_Z, width: 18, height: 18 }+const cornerZoneStyle: React.CSSProperties = { zIndex: BOTTOM_EDGE_Z, width: 18, height: 18 }const zones: { edge: EditModeEdge; style: React.CSSProperties; cursor: React.CSSProperties['cursor'] }[] = [- // Shallow on top (the card header/menu lives just below) and deeper on the bottom for a comfortable target.- { edge: 'n', style: { left: 0, right: 0, top: -2, height: 10, zIndex: TOP_BOTTOM_Z }, cursor: 'ns-resize' },- { edge: 's', style: { left: 0, right: 0, bottom: -2, height: 14, zIndex: TOP_BOTTOM_Z }, cursor: 'ns-resize' },+ { edge: 's', style: { left: 0, right: 0, bottom: -2, height: 14, zIndex: BOTTOM_EDGE_Z }, cursor: 'ns-resize' },{ edge: 'w', style: { top: 0, bottom: 0, left: -6, width: 12 }, cursor: 'ew-resize' },{ edge: 'e', style: { top: 0, bottom: 0, right: -6, width: 12 }, cursor: 'ew-resize' },- { edge: 'nw', style: { ...cornerZoneStyle, top: -2, left: -2 }, cursor: 'nw-resize' },- { edge: 'ne', style: { ...cornerZoneStyle, top: -2, right: -2 }, cursor: 'ne-resize' },{ edge: 'sw', style: { ...cornerZoneStyle, bottom: -2, left: -2 }, cursor: 'sw-resize' },{ edge: 'se', style: { ...cornerZoneStyle, bottom: -2, right: -2 }, cursor: 'se-resize' },]diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss b/frontend/src/lib/components/Cards/InsightCard/InsightCard.scssindex 5b85a61a6584..16466048edbd 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss@@ -59,11 +59,6 @@min-height: var(--insight-viz-min-height);}- // Clip while the JS-throttled pinned size lags the growing/shrinking tile mid-resize.- &--resizing {- overflow: hidden;- }-// The Metric display bleeds its sparkline to the card edges (negative margins plus a// few-pixel downward shift so the line rests on the edge), so its content sits a hair// taller than the box. Clip it — otherwise `overflow: auto` shows a permanent vertical@@ -79,9 +74,4 @@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 22b36339ddfe..05a08e109176 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, { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { LayoutItem } from 'react-grid-layout'import { useInView } from 'react-intersection-observer'@@ -32,7 +32,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 { queryVizDefinitelyRendersToCanvas, queryVizRendersToCanvas } from '~/queries/utils'+import { queryVizDefinitelyRendersToCanvas } from '~/queries/utils'import {AccessControlLevel,AccessControlResourceType,@@ -84,73 +84,6 @@ const LazyEditAlertModal = lazyWithRetry(() =>import('products/alerts/frontend/views/EditAlertModal').then(({ EditAlertModal }) => ({ default: EditAlertModal })))-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>- )-}-type AlertModalState = {alertId?: AlertType['id']defaultToAnomalyDetection?: boolean@@ -179,8 +112,6 @@ export interface InsightCardProps extends Resizeable {/** Whether the editing controls should be enabled or not. */showEditingControls?: booleanrefreshAfterDisplayOptionsChange?: (insight: InsightModel) => void- /** 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/** Layout of the card on a grid. */@@ -203,6 +134,9 @@ export interface InsightCardProps extends Resizeable {/** Priority for loading the insight, lower is earlier. */loadPriority?: numberdoNotLoad?: boolean+ keepMountedDuringInteraction?: boolean+ renderVizWhenMounted?: boolean+ onOverlayVisibilityChange?: (visible: boolean) => void/** Dashboard filters to override the ones in the insight */filtersOverride?: DashboardFilter/** Dashboard variables to override the ones in the insight */@@ -249,7 +183,6 @@ function InsightCardInternal(highlighted,refreshAfterDisplayOptionsChange,showResizeHandles,- isResizing,showEditingControls,showDetailsControls,updateColor,@@ -267,6 +200,9 @@ function InsightCardInternal(placement,loadPriority,doNotLoad,+ keepMountedDuringInteraction,+ renderVizWhenMounted,+ onOverlayVisibilityChange,filtersOverride,variablesOverride,children,@@ -284,11 +220,9 @@ function InsightCardInternal(}: InsightCardProps,ref: React.Ref<HTMLDivElement>): JSX.Element | null {- const { ref: inViewRef, inView } = useInView({ rootMargin: '500px' })+ const { ref: inViewRef, inView } = useInView({ rootMargin: '500px', skip: renderVizWhenMounted })const { isVisible: isPageVisible } = usePageVisibility()- 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.@@ -297,7 +231,7 @@ function InsightCardInternal(const shouldRenderViz = shouldRenderInsightCardViz({isStorybook: IS_STORYBOOK,placement,- inView,+ inView: inView || !!keepMountedDuringInteraction || !!renderVizWhenMounted,isPageVisible,query: insight.query,})@@ -369,7 +303,11 @@ function InsightCardInternal(}const [areDetailsShown, setAreDetailsShown] = useState(false)+ const [compactInfoVisible, setCompactInfoVisible] = useState(false)const [alertModal, setAlertModal] = useState<AlertModalState | null>(null)+ useEffect(() => {+ onOverlayVisibilityChange?.(areDetailsShown || compactInfoVisible || alertModal !== null)+ }, [areDetailsShown, compactInfoVisible, alertModal, onOverlayVisibilityChange])const openCreateAlertModal = useCallback(() => setAlertModal({}), [])const openEditAlertModal = useCallback((alertId: AlertType['id']) => setAlertModal({ alertId }), [])const openCreateAnomalyAlertModal = useCallback(() => setAlertModal({ defaultToAnomalyDetection: true }), [])@@ -451,8 +389,7 @@ function InsightCardInternal(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.+ // Keep the Query element stable so grid updates do not remount the chart.const vizInner = useMemo(() => {if (BlockingEmptyState) {return BlockingEmptyState@@ -473,9 +410,10 @@ 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 = shouldRenderViz ? (- <ResizeThrottledViz throttled={!!isResizing && rendersToCanvas}>{vizInner}</ResizeThrottledViz>+ <div className="InsightCard__viz">+ <div className="InsightCard__vizInner">{vizInner}</div>+ </div>) : (<InsightVisualizationSkeleton query={insight.query} />)@@ -522,6 +460,7 @@ function InsightCardInternal(copyToDashboard={copyToDashboard}areDetailsShown={areDetailsShown}setAreDetailsShown={setAreDetailsShown}+ onInfoVisibilityChange={setCompactInfoVisible}showEditingControls={showEditingControls}showDetailsControls={showDetailsControls}moreButtons={moreButtons}diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsxindex e7c54d969749..fd611c41ced8 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx@@ -132,6 +132,7 @@ interface InsightMetaProps extends Pick<refreshDisabledReason?: stringareDetailsShown?: booleansetAreDetailsShown?: React.Dispatch<React.SetStateAction<boolean>>+ onInfoVisibilityChange?: (visible: boolean) => voidpersistDisplayOptions?: (node: Node) => voidonCreateAlert?: () => voidonEditAlert?: (alertId: AlertType['id']) => void@@ -162,6 +163,7 @@ export function InsightMeta({copyToDashboard,areDetailsShown,setAreDetailsShown,+ onInfoVisibilityChange,showEditingControls = true,showDetailsControls = true,moreButtons,@@ -520,6 +522,7 @@ export function InsightMeta({infoPopover={showCompactTile ? (<CompactInfoPopover+ onVisibilityChange={onInfoVisibilityChange}popoverTopHeading={popoverTopHeadingEl ?? topHeadingEl}metaTitle={name}metaDescription={metaDescriptionEl}@@ -982,6 +985,7 @@ export function InsightMetaContent({}function CompactInfoPopover({+ onVisibilityChange,popoverTopHeading,metaTitle,metaDescription,@@ -989,6 +993,7 @@ function CompactInfoPopover({onMetaSave,metaDetails,}: {+ onVisibilityChange?: (visible: boolean) => voidpopoverTopHeading?: JSX.Element | nullmetaTitle: stringmetaDescription?: JSX.Element | null@@ -997,6 +1002,10 @@ function CompactInfoPopover({metaDetails?: JSX.Element | null}): JSX.Element {const [popoverVisible, setPopoverVisible] = useState(false)+ useEffect(() => {+ onVisibilityChange?.(popoverVisible)+ }, [popoverVisible, onVisibilityChange])+ useEffect(() => () => onVisibilityChange?.(false), [onVisibilityChange])const [pinned, setPinned] = useState(false)const hoverTimerRef = useRef<ReturnType<typeof setTimeout>>()diff --git a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx b/frontend/src/lib/components/Cards/TextCard/TextCard.tsxindex be39462ebd91..b1dd7446b413 100644--- a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx+++ b/frontend/src/lib/components/Cards/TextCard/TextCard.tsx@@ -123,7 +123,7 @@ function TextCardInternal(<TextContent text={text.body} className={shouldHideMoreButton ? 'p-4' : 'p-4 pr-14'} /></div>- {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (+ {(canEnterEditModeFromEdge || showResizeHandles) && onEnterEditModeFromEdge && (<EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />)}{showResizeHandles && <DashboardResizeHandles />}diff --git a/frontend/src/lib/components/TakeScreenshot/ScreenShotEditor.tsx b/frontend/src/lib/components/TakeScreenshot/ScreenShotEditor.tsxindex c98ac180ce04..a64203eb3761 100644--- a/frontend/src/lib/components/TakeScreenshot/ScreenShotEditor.tsx+++ b/frontend/src/lib/components/TakeScreenshot/ScreenShotEditor.tsx@@ -20,7 +20,7 @@ import {const HedgehogDirector = pngHoggie(director)-export function ScreenShotEditor({ screenshotKey }: { screenshotKey: string }): JSX.Element {+export function ScreenShotEditor({ screenshotKey }: { screenshotKey: string }): JSX.Element | null {const {isOpen,imageFile,@@ -367,6 +367,10 @@ export function ScreenShotEditor({ screenshotKey }: { screenshotKey: string }):downloadFile(editedFile)}+ if (!isOpen) {+ return null+ }+if (isLoading) {return (<>diff --git a/frontend/src/scenes/dashboard/DashboardItems.scss b/frontend/src/scenes/dashboard/DashboardItems.scssindex 0fa71c80927c..e7d5b801e399 100644--- a/frontend/src/scenes/dashboard/DashboardItems.scss+++ b/frontend/src/scenes/dashboard/DashboardItems.scss@@ -22,26 +22,30 @@position: relative;transition: height 100ms ease;- /* Preserve the tile border transition while spacing changes animate. */- &.dashboard-view-mode .react-grid-item {- transition: var(--dashboard-tile-transition);-- /* Skip rendering for off-screen tiles during resize/reflow */+ .react-grid-item {+ /* Entry into edit mode must not force layout for off-screen charts. */content-visibility: auto;contain-intrinsic-size: auto 30rem;/* content-visibility paint-clips the resize handles revealed on border hover; lift it while one shows */- &:has(> .handle) {+ &:hover:has(> .handle),+ &.resizing,+ &.react-draggable-dragging {content-visibility: visible;}/* Tile decorations draw outside the tile box, so the same paint clip would cut them off */- &:has(> .TileDecorations__group-title, > .TileDecorations__crown) {+ &:has(+ > .TileDecorations__group-title,+ > .TileDecorations__crown,+ > .InsightCard > .TileDecorations__group-title,+ > .InsightCard > .TileDecorations__crown+ ) {content-visibility: visible;}/* The hog only shows while hovered. On leave, hold the lift for the hog's slide down (browsers without discrete content-visibility transitions hide it at once) */- &:where(:has(> .TileDecorations__hog)) {+ &:where(:has(> .TileDecorations__hog, > .InsightCard > .TileDecorations__hog)) {&:hover {content-visibility: visible;transition-delay: 0s;@@ -59,6 +63,11 @@}}+ /* Preserve the tile border transition while spacing changes animate. */+ &.dashboard-view-mode .react-grid-item {+ transition: var(--dashboard-tile-transition);+ }+&.dashboard-tile-spacing-changing {transition: none;@@ -75,11 +84,39 @@visibility: hidden;}+ &.dashboard-edit-mode [data-attr='dashboard-edit-mode-from-card-edge'] {+ display: none;+ }+&.dashboard-layout-settling .react-grid-item:not(.react-draggable-dragging, .resizing) {transition: transform 180ms ease-out;}}+.dashboard-insight-tile {+ z-index: 3;++ &__placeholder {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ width: 100%;+ height: 100%;+ padding: 1rem;+ background: var(--color-bg-surface-primary);+ border: 1px solid var(--color-border-primary);+ border-radius: var(--radius);+ }++ > .InsightCard {+ height: 100%;+ }++ &:has(> .InsightCard--details-shown) {+ z-index: var(--z-raised);+ }+}+.dashboard-container-width-changing .react-grid-layout {transition: none;@@ -281,15 +318,6 @@cursor: ns-resize;}- & > .react-resizable-handle.react-resizable-handle-n {- top: -0.5rem;- right: 3rem;- left: 3rem;- width: auto;- height: 1rem;- cursor: ns-resize;- }-& > .react-resizable-handle.react-resizable-handle-w {top: 0;bottom: 2rem;@@ -299,22 +327,6 @@cursor: ew-resize;}- & > .react-resizable-handle.react-resizable-handle-nw {- top: -0.5rem;- left: -0.5rem;- width: 2rem;- height: 2rem;- cursor: nw-resize;- }-- & > .react-resizable-handle.react-resizable-handle-ne {- top: -0.5rem;- right: -0.5rem;- width: 2rem;- height: 2rem;- cursor: ne-resize;- }-& > .react-resizable-handle.react-resizable-handle-sw {bottom: -0.5rem;left: -0.5rem;diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsxindex 85843d9224c9..0df65df8966a 100644--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx@@ -116,6 +116,19 @@ jest.mock('lib/components/Cards/InsightCard', () => ({},}))+jest.mock('products/dashboards/frontend/components/DashboardInsightTile', () => ({+ DashboardInsightTile: (props: Record<string, unknown>) => {+ const { InsightCard } = jest.requireMock('lib/components/Cards/InsightCard')+ return <InsightCard {...props} />+ },+}))++jest.mock('products/dashboards/frontend/components/DashboardGridBackground', () => ({+ DashboardGridBackground: ({ rowHeight, margin }: { rowHeight: number; margin: [number, number] }) => (+ <div data-attr="grid-background" data-row-height={String(rowHeight)} data-margin={margin.join(',')} />+ ),+}))+jest.mock('products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem', () => ({DashboardTextItem: ({ tile, showResizeHandles }: { tile: { id: number }; showResizeHandles: boolean }) => (<div@@ -571,12 +584,7 @@ describe('DashboardItems', () => {expect(insightCard).toHaveAttribute('data-api-errored', 'true')expect(insightCard).toHaveAttribute('data-api-error-status', '400')expect(insightCard).toHaveAttribute('data-api-error-code', 'query_memory_limit')- expect(mockInsightCard).toHaveBeenCalledWith(- expect.objectContaining({- refresh: expect.any(Function),- queryId: 'failed-query-id',- })- )+ expect(mockInsightCard).toHaveBeenCalledWith(expect.objectContaining({ queryId: 'failed-query-id' }))expect(insightCard).toHaveAttribute('data-api-error-detail','This query ran out of memory before it could finish'diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsxindex c1391c676ee8..3455251daad3 100644--- a/frontend/src/scenes/dashboard/DashboardItems.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx@@ -6,13 +6,11 @@ import { router } from 'kea-router'import { RefObject, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'import { Responsive as ReactGridLayout } from 'react-grid-layout'import type { Layout, LayoutItem } from 'react-grid-layout'-import { GridBackground } from 'react-grid-layout/extras'import { DashboardWidgetItem } from '@posthog/products-dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem'import { getDashboardWidgetFetchDisplayError } from '@posthog/products-dashboards/frontend/widgets/constants'import { ApiError } from 'lib/api'-import { InsightCard } from 'lib/components/Cards/InsightCard'import { EditModeEdge, useResizeHandleScrollbarPassThrough } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'import { TileDecorations } from 'lib/components/TileDecorations/TileDecorations'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'@@ -36,9 +34,10 @@ import { getBestSurveyOpportunityFunnel } from 'scenes/surveys/utils/opportunityimport { urls } from 'scenes/urls'import { getCurrentExporterData, isSharedView } from '~/exporter/exporterViewLogic'-import { insightsModel } from '~/models/insightsModel'import { DashboardLayoutSize, DashboardPlacement, DashboardType } from '~/types'+import { DashboardGridBackground } from 'products/dashboards/frontend/components/DashboardGridBackground'+import { DashboardInsightTile } from 'products/dashboards/frontend/components/DashboardInsightTile'import { DashboardTextItem } from 'products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem'import { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'import { getGroupTitlesByTileId, hasTileDecorations } from 'products/dashboards/frontend/dashboardTileGroups'@@ -58,6 +57,8 @@ interface DashboardItemsProps {showCreateAnomalyAlertButton?: boolean}+type DashboardWidgetItemProps = React.ComponentProps<typeof DashboardWidgetItem>+/*** Shallow prop compare, except: `style` by value (react-grid-layout rebuilds it every drag/resize mousemove even* for tiles that haven't moved) and `children` ignored (the RGL-injected resize handles, recreated each render@@ -73,7 +74,6 @@ function gridTilePropsEqual(prevProps: Record<string, any>, nextProps: Record<st)}-const MemoizedInsightCard = memo(InsightCard, gridTilePropsEqual) as typeof InsightCardconst MemoizedDashboardTextItem = memo(DashboardTextItem, gridTilePropsEqual) as typeof DashboardTextItemconst MemoizedDashboardButtonTileItem = memo(DashboardButtonTileItem,@@ -109,22 +109,18 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPconst {updateLayouts,updateContainerWidth,- updateTileColor,toggleTileDescription,removeTile,duplicateTile,- refreshDashboardItem,loadDashboard,refreshDashboardWidgets,scheduleRefreshDashboardWidgets,applyWidgetIssueMetadataChange,moveToDashboard,copyToDashboard,- setTileOverride,setDashboardEditing,} = useActions(dashboardLogic)const { updateWidgetTile } = useAsyncActions(dashboardLogic)- const { renameInsight } = useActions(insightsModel)const { reportDashboardTileRepositioned } = useActions(eventUsageLogic)const { push } = useActions(router)const { data: surveyLinkedInsights, loading: surveyLinkedInsightsLoading } = useSurveyLinkedInsights({@@ -138,11 +134,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPconst retryFailedDashboardTile = isSharedView()? undefined: () => loadDashboard({ action: DashboardLoadAction.Update })- const refreshDashboardTile = isSharedView() ? undefined : refreshDashboardItem- // Tile currently being resized. Its viz is unmounted for the duration of the gesture so the chart doesn't- // redraw on every frame as the tile's dimensions change — the dominant cost that makes resizing feel laggy.- const [resizingTileId, setResizingTileId] = useState<string | null>(null)const [containerHeight, setContainerHeight] = useState<number | undefined>(undefined)// cannot click links when dragging and 250ms after@@ -269,6 +261,16 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP}),[tiles, layouts, activeBreakpoint, dashboard?.customization?.group_titles, gridCompactor, widgetTilesShown])+ const decorationsByTileId = useMemo(+ () =>+ new Map(+ (tiles ?? []).map((tile) => [+ tile.id,+ <TileDecorations key={tile.id} badge={tile.badge} groupTitle={groupTitlesByTileId[tile.id]} />,+ ])+ ),+ [tiles, groupTitlesByTileId]+ )const showDecorationSpace = hasTileDecorations({ tiles: tiles || [], groupTitlesByTileId, widgetTilesShown })const showResizeHandles = layoutEditMode && !isMobileView && isEditablePlacement && !isLayoutZoomToggled@@ -291,59 +293,53 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPconst resizeConfig = useMemo(() => ({enabled: canEditDashboard && layoutEditMode && !isMobileView && !isLayoutZoomToggled,- handles: ['s', 'e', 'se', 'n', 'w', 'nw', 'ne', 'sw'] as const,+ handles: ['s', 'e', 'se', 'w', 'sw'] as const,}),[canEditDashboard, layoutEditMode, isMobileView, isLayoutZoomToggled])useResizeHandleScrollbarPassThrough(layoutEditMode && !isMobileView)- const onEnterEditModeFromEdge = useMemo(- () =>- canEnterEditModeFromEdge- ? (e: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => {- whenPressBecomesDrag(e, (moveEvent) => {- setDashboardEditing({ filters: true, layout: true }, DashboardEventSource.CardEdgeHover)- // continue the press into a live resize so the user doesn't have to release and grab again- continueResizeGestureInEditMode(e, edge, moveEvent)- })- }- : undefined,- [canEnterEditModeFromEdge, setDashboardEditing]+ const canEnterEditModeFromEdgeRef = useRef(canEnterEditModeFromEdge)+ canEnterEditModeFromEdgeRef.current = canEnterEditModeFromEdge+ const onEnterEditModeFromEdge = useCallback(+ (e: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge): void => {+ if (!canEnterEditModeFromEdgeRef.current) {+ return+ }+ setDashboardEditing({ filters: true, layout: true }, DashboardEventSource.CardEdgeHover)+ continueResizeGestureInEditMode(e, edge, e.nativeEvent)+ },+ [setDashboardEditing])- const onDragHandleMouseDown = useMemo(- () =>- canEnterEditModeFromEdge- ? (e: React.MouseEvent) => {- const target = e.target as Element | null- if (!target) {- return- }-- const gridItem = target.closest('.react-grid-item')- if (!gridItem) {- return- }-- // Don't trigger when clicking obvious interactive controls or readonly rich text (TipTap/LemonMarkdown).- if (- target.closest(- 'input,textarea,button,select,a,p,h4,[contenteditable="true"],[role="textbox"],.ProseMirror,.LemonMarkdown'- )- ) {- return- }- e.preventDefault()- e.stopPropagation()- whenPressBecomesDrag(e, (moveEvent) => {- setDashboardEditing({ filters: true, layout: true }, DashboardEventSource.CardDragHandle)- // continue the press into a live drag so the user doesn't have to release and grab again- continueDragGestureInEditMode(e, moveEvent)- })- }- : undefined,- [canEnterEditModeFromEdge, setDashboardEditing]+ const onDragHandleMouseDown = useCallback(+ (e: React.MouseEvent): void => {+ if (!canEnterEditModeFromEdgeRef.current) {+ return+ }+ const target = e.target as Element | null+ if (!target || !target.closest('.react-grid-item')) {+ return+ }+ if (+ target.closest(+ 'input,textarea,button,select,a,p,h4,[contenteditable="true"],[role="textbox"],.ProseMirror,.LemonMarkdown'+ )+ ) {+ return+ }+ e.preventDefault()+ e.stopPropagation()+ whenPressBecomesDrag(e, (moveEvent) => {+ if (!canEnterEditModeFromEdgeRef.current) {+ return+ }+ setDashboardEditing({ filters: true, layout: true }, DashboardEventSource.CardDragHandle)+ continueDragGestureInEditMode(e, moveEvent)+ })+ },+ [setDashboardEditing])const requireDashboardId = useCallback(@@ -356,6 +352,62 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP[dashboard])+ const onWidgetIssueMetadataChange = useCallback<+ NonNullable<DashboardWidgetItemProps['onApplyWidgetIssueMetadataChange']>+ >(+ (tileId, issueId, delta, context): void => {+ applyWidgetIssueMetadataChange({ tileId, issueId, delta, context })+ },+ [applyWidgetIssueMetadataChange]+ )+ const onWidgetConfigPublished = useCallback((): void => {+ loadDashboard({ action: DashboardLoadAction.Update })+ }, [loadDashboard])++ const tileActionsById = useMemo(+ () =>+ new Map(+ (tiles ?? []).map((tile) => [+ tile.id,+ {+ moveToDashboard: ({ id, name }: Pick<DashboardType, 'id' | 'name'>): void => {+ moveToDashboard(tile, requireDashboardId('move this tile'), id, name)+ },+ copyToDashboard: ({ id, name }: Pick<DashboardType, 'id' | 'name'>): void => {+ copyToDashboard(tile, requireDashboardId('copy this tile'), id, name)+ },+ removeFromDashboard: (): void => removeTile(tile),+ duplicate: (): void => duplicateTile(tile),+ edit: (): void => {+ if (dashboard?.id) {+ push(urls.dashboardTile(dashboard.id, tile.id))+ }+ },+ refreshWidget: (): void => refreshDashboardWidgets({ tileIds: [tile.id], forceRefresh: true }),+ updateWidget: async (+ patch: Parameters<NonNullable<DashboardWidgetItemProps['onUpdateWidgetTile']>>[0]+ ): Promise<void> => {+ await updateWidgetTile({ tile, ...patch })+ },+ toggleDescription: (): void => toggleTileDescription(tile.id),+ },+ ])+ ),+ [+ tiles,+ dashboard?.id,+ requireDashboardId,+ moveToDashboard,+ copyToDashboard,+ removeTile,+ duplicateTile,+ push,+ refreshDashboardWidgets,+ updateWidgetTile,+ toggleTileDescription,+ ]+ )+const flushPendingLayouts = useCallback(() => {finishInteraction()// Remeasure once the gesture settles, since height updates were suppressed during it.@@ -375,7 +427,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP)const handleResizeStart = useCallback(- (layout: Layout, _oldItem: LayoutItem | null, newItem: LayoutItem | null) => {+ (+ layout: Layout,+ _oldItem: LayoutItem | null,+ newItem: LayoutItem | null,+ _placeholder: LayoutItem | null,+ event: Event+ ) => {+ event.preventDefault()if (!newItem) {return}@@ -384,13 +443,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP[startInteraction])- const handleResize = useCallback((_layout: any, _oldItem: any, newItem: any) => {- // Setting state to the same id bails out of re-rendering, so this only re-renders once per gesture.- setResizingTileId(newItem.i)- }, [])-const handleResizeStop = useCallback(() => {- setResizingTileId(null)flushPendingLayouts()if (dashboard?.id) {reportDashboardTileRepositioned(dashboard.id, 'resized', effectiveZoom)@@ -483,15 +536,12 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP{gridWidth > 0 && (<div className={clsx('relative', showDecorationSpace && 'mt-10')}>{layoutEditMode && !isMobileView && (- <GridBackground+ <DashboardGridBackgroundwidth={gridWidth}cols={BREAKPOINT_COLUMN_COUNTS.sm}rowHeight={rowHeight}margin={margin}- containerPadding={CONTAINER_PADDING}- rows="auto"height={containerHeight} // kept in sync via ResizeObserver- color="var(--color-bg-surface-secondary)"/>)}@@ -511,7 +561,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPbreakpoints={BREAKPOINTS}cols={BREAKPOINT_COLUMN_COUNTS}onResizeStart={handleResizeStart}- onResize={handleResize}onResizeStop={handleResizeStop}onDragStart={handleDragStart}onDrag={handleDrag}@@ -519,13 +568,12 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP>{tiles?.map((tile) => {const { insight, text, button_tile, widget } = tile+ const tileActions = tileActionsById.get(tile.id)!const smLayout = layouts['sm']?.find((l) => {return l.i == tile.id.toString()})- const decorations = (- <TileDecorations badge={tile.badge} groupTitle={groupTitlesByTileId[tile.id]} />- )+ const decorations = decorationsByTileId.get(tile.id)const commonTileProps = {dashboardId: dashboard?.id,@@ -535,13 +583,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPonEnterEditModeFromEdge,onDragHandleMouseDown,showEditingControls,- moveToDashboard: ({ id, name }: Pick<DashboardType, 'id' | 'name'>) => {- moveToDashboard(tile, requireDashboardId('move this tile'), id, name)- },- copyToDashboard: ({ id, name }: Pick<DashboardType, 'id' | 'name'>) => {- copyToDashboard(tile, requireDashboardId('copy this tile'), id, name)- },- removeFromDashboard: () => removeTile(tile),+ moveToDashboard: tileActions.moveToDashboard,+ copyToDashboard: tileActions.copyToDashboard,+ removeFromDashboard: tileActions.removeFromDashboard,}if (tile.error && !insight) {@@ -581,7 +625,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPconst loading = isErrorTile ? false : isRefreshing(insight.short_id)return (- <MemoizedInsightCard+ <DashboardInsightTilekey={tile.id}tile={tile}insight={insight}@@ -591,27 +635,10 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPapiError={apiError}queryId={insight.query_status?.id}highlighted={highlightedInsightId && insight.short_id === highlightedInsightId}- updateColor={(color) => updateTileColor(tile.id, color)}- toggleShowDescription={() => toggleTileDescription(tile.id)}ribbonColor={tile.color}- refresh={- refreshDashboardTile ? () => refreshDashboardTile({ tile }) : undefined- }- refreshAfterDisplayOptionsChange={- refreshDashboardTile- ? (updatedInsight) =>- refreshDashboardTile({- tile: { ...tile, insight: updatedInsight },- })- : undefined- }- rename={() => renameInsight(insight)}- duplicate={() => duplicateTile(tile)}- setOverride={() => setTileOverride(tile)}showDetailsControls={showDetailsControls}placement={placement}loadPriority={smLayout ? smLayout.y * 1000 + smLayout.x : undefined}- isResizing={resizingTileId === tile.id.toString()}filtersOverride={effectiveEditBarFilters}variablesOverride={currentDashboardVariables}// :HACKY: The two props below aren't actually used in the component, but are needed to trigger a re-render@@ -619,10 +646,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPdataColorThemeId={dataColorThemeId}surveyOpportunity={tile.id === bestSurveyOpportunityFunnel?.id}showCreateAnomalyAlertButton={showCreateAnomalyAlertButton}+ decorations={decorations}{...commonTileProps}- >- {decorations}- </MemoizedInsightCard>+ />)}@@ -633,14 +659,10 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPtile={tile}placement={placement}dashboardId={dashboard?.id}- onEdit={() => {- if (dashboard?.id) {- push(urls.dashboardTile(dashboard.id, tile.id))- }- }}+ onEdit={tileActions.edit}onMoveToDashboard={commonTileProps.moveToDashboard}onCopyToDashboard={commonTileProps.copyToDashboard}- onDuplicate={() => duplicateTile(tile)}+ onDuplicate={tileActions.duplicate}onRemove={commonTileProps.removeFromDashboard}showResizeHandles={commonTileProps.showResizeHandles}showEditingControls={commonTileProps.showEditingControls}@@ -661,13 +683,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPplacement={placement}dashboardId={dashboard?.id}isDraggingRef={isDragging}- onEdit={() => {- if (dashboard?.id) {- push(urls.dashboardTile(dashboard.id, tile.id))- }- }}+ onEdit={tileActions.edit}onMoveToDashboard={commonTileProps.moveToDashboard}- onDuplicate={() => duplicateTile(tile)}+ onDuplicate={tileActions.duplicate}onRemove={commonTileProps.removeFromDashboard}showResizeHandles={commonTileProps.showResizeHandles}showEditingControls={commonTileProps.showEditingControls}@@ -698,24 +716,13 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP)}loading={!!refreshState?.loading}lastFetchedAt={refreshState?.fetchedAt}- onRefresh={() =>- refreshDashboardWidgets({ tileIds: [tile.id], forceRefresh: true })- }+ onRefresh={tileActions.refreshWidget}onRefreshWidgetData={scheduleRefreshDashboardWidgets}- onApplyWidgetIssueMetadataChange={(tileId, issueId, delta, context) => {- applyWidgetIssueMetadataChange({- tileId,- issueId,- delta,- context,- })- }}- onUpdateWidgetTile={async (patch) => {- await updateWidgetTile({ tile, ...patch })- }}- onConfigPublished={() => loadDashboard({ action: DashboardLoadAction.Update })}- toggleShowDescription={() => toggleTileDescription(tile.id)}- onDuplicate={() => duplicateTile(tile)}+ onApplyWidgetIssueMetadataChange={onWidgetIssueMetadataChange}+ onUpdateWidgetTile={tileActions.updateWidget}+ onConfigPublished={onWidgetConfigPublished}+ toggleShowDescription={tileActions.toggleDescription}+ onDuplicate={tileActions.duplicate}onRemove={commonTileProps.removeFromDashboard}onMoveToDashboard={commonTileProps.moveToDashboard}onCopyToDashboard={commonTileProps.copyToDashboard}diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex c8c470853aef..af2f185117d2 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -917,26 +917,6 @@ export interface dashboardLogicActions {editing: DashboardEditing | nullsource: DashboardEventSource}- setDashboardEditingFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- setDashboardEditingSuccess: (- dashboard: DashboardType | null,- payload?: {- editing: DashboardEditing | null- source: DashboardEventSource- }- ) => {- dashboard: DashboardType | null- payload?: {- editing: DashboardEditing | null- source: DashboardEventSource- }- }setDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => {layoutCompaction: DashboardGridCompaction}@@ -1398,7 +1378,7 @@ export interface dashboardLogicMeta {) => number | nulldataColorTheme: (dataColorThemeId: number | null,- getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null+ getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null // dataThemeLogic) => DataColorTheme | nullautoBreakdownColorsEnabled: (featureFlags: FeatureFlagsSet) => booleanbreakdownValuesIncomplete: (itemsLoading: boolean, insightTiles: DashboardTile[]) => boolean@@ -1956,25 +1936,6 @@ export const dashboardLogic = kea<dashboardLogicType>([} as DashboardType}},- setDashboardEditing: async ({ editing, source }) => {- if (- editing === null &&- source === DashboardEventSource.DashboardHeaderDiscardChanges &&- values.dashboard?.tiles- ) {- // layout changes were discarded so need to reset to original state- // (as a new object — selectors only recompute when the reference changes)- return {- ...values.dashboard,- tiles: values.dashboard.tiles.map((tile) => ({- ...tile,- layouts: values.dashboardLayouts?.[tile.id],- })),- }- }-- return values.dashboard- },duplicateTile: async ({ tile }) => {try {const newTile = { ...tile } as Partial<DashboardTile>@@ -4855,7 +4816,9 @@ export const dashboardLogic = kea<dashboardLogicType>([exitFilterEditModeWhenSaved(values, actions)},saveLayoutChanges: () => {- actions.saveEditModeChanges('layout')+ if (values.hasUnsavedLayoutChanges) {+ actions.saveEditModeChanges('layout')+ }actions.setLayoutZoom(1)if (values.dashboardSettingsState === 'unsavedChanges') {actions.setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardFilters)@@ -4870,7 +4833,9 @@ export const dashboardLogic = kea<dashboardLogicType>([actions.cancelLayoutEdit()},saveLayout: () => {- actions.saveEditModeChanges('layout')+ if (values.hasUnsavedLayoutChanges) {+ actions.saveEditModeChanges('layout')+ }actions.setLayoutZoom(1)if (values.dashboardSettingsState === 'unsavedChanges') {actions.setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardFilters)@@ -4988,6 +4953,22 @@ export const dashboardLogic = kea<dashboardLogicType>([})},setDashboardEditing: async ({ editing, source }) => {+ if (+ editing === null &&+ source === DashboardEventSource.DashboardHeaderDiscardChanges &&+ values.dashboard?.tiles+ ) {+ actions.applyDashboardUpdate(+ {+ ...values.dashboard,+ tiles: values.dashboard.tiles.map((tile) => ({+ ...tile,+ layouts: values.dashboardLayouts[tile.id],+ })),+ },+ values.dashboardLayouts+ )+ }if (editing?.layout && source !== DashboardEventSource.DashboardHeaderDiscardChanges) {clearDOMTextSelection()lemonToast.info('Now editing the dashboard – press E or click Save to persist changes')diff --git a/frontend/src/scenes/dashboard/dashboardResizeCompactor.ts b/frontend/src/scenes/dashboard/dashboardResizeCompactor.tsindex 2451c2bf7d69..99968d38028a 100644--- a/frontend/src/scenes/dashboard/dashboardResizeCompactor.ts+++ b/frontend/src/scenes/dashboard/dashboardResizeCompactor.ts@@ -16,7 +16,7 @@ export function restoreUnmovedItemPositions(return layout.map((item) => {const baselineItem = baselineById.get(item.i)- if (item.i === activeItemId || !baselineItem) {+ if (item.i === activeItemId || !baselineItem || (item.x === baselineItem.x && item.y === baselineItem.y)) {return item}@@ -58,6 +58,9 @@ export function resizeNeighborToFitRow(return item}+ if (item.x === activeRight && item.y === rightNeighbor.y && item.w === nextWidth) {+ return item+ }return { ...item, x: activeRight, y: rightNeighbor.y, w: nextWidth }})}@@ -75,6 +78,9 @@ export function resizeNeighborToFitRow(return item}+ if (item.y === leftNeighbor.y && item.w === nextWidth) {+ return item+ }return { ...item, y: leftNeighbor.y, w: nextWidth }})}diff --git a/frontend/src/scenes/dashboard/editLayoutGesture.test.ts b/frontend/src/scenes/dashboard/editLayoutGesture.test.tsindex d2ed580975ce..8dac00bf5869 100644--- a/frontend/src/scenes/dashboard/editLayoutGesture.test.ts+++ b/frontend/src/scenes/dashboard/editLayoutGesture.test.ts@@ -14,21 +14,16 @@ describe('editLayoutGesture', () => {describe('resolveResizeHandleDirection', () => {it.each([- ['n', 150, 0, 'n'],['s', 150, 200, 's'],['w', 0, 100, 'w'],['e', 300, 100, 'e'],- ['n', 10, 0, 'nw'],- ['n', 295, 0, 'ne'],['s', 10, 200, 'sw'],['s', 295, 200, 'se'],- ['w', 0, 10, 'nw'],+ ['w', 0, 10, 'w'],['w', 0, 195, 'sw'],- ['e', 300, 10, 'ne'],+ ['e', 300, 10, 'e'],['e', 300, 195, 'se'],// Corner presses pass through directly, ignoring the edge-upgrade thresholds.- ['nw', 150, 100, 'nw'],- ['ne', 150, 100, 'ne'],['sw', 150, 100, 'sw'],['se', 150, 100, 'se'],])('maps edge %s at (%i, %i) to handle %s', (edge, clientX, clientY, expected) => {@@ -151,27 +146,28 @@ describe('editLayoutGesture', () => {it('replays the mousedown on the matching resize handle once it renders', () => {const onHandleMouseDown = jest.fn()- continueResizeGestureInEditMode(pressEvent(gridItem, 150, 0), 'n', moveEvent(150, 12))+ continueResizeGestureInEditMode(pressEvent(gridItem, 150, 200), 's', moveEvent(150, 188))flushFrames() // handle not rendered yet — keeps waiting- const handle = mountResizeHandle('n')+ const handle = mountResizeHandle('s')handle.addEventListener('mousedown', onHandleMouseDown)+ grid.className = 'react-grid-layout dashboard-edit-mode'flushFrames()expect(onHandleMouseDown).toHaveBeenCalledTimes(1)const replayed = onHandleMouseDown.mock.calls[0][0] as MouseEventexpect(replayed.clientX).toBe(150)- expect(replayed.clientY).toBe(0)+ expect(replayed.clientY).toBe(200)expect(replayed.bubbles).toBe(true)})it('does not replay if the mouse button is released before the handle renders', () => {const onHandleMouseDown = jest.fn()- continueResizeGestureInEditMode(pressEvent(gridItem, 150, 0), 'n', moveEvent(150, 12))+ continueResizeGestureInEditMode(pressEvent(gridItem, 150, 200), 's', moveEvent(150, 188))window.dispatchEvent(new MouseEvent('mouseup'))- const handle = mountResizeHandle('n')+ const handle = mountResizeHandle('s')handle.addEventListener('mousedown', onHandleMouseDown)flushFrames(3)@@ -181,10 +177,10 @@ describe('editLayoutGesture', () => {it('gives up after the frame budget if edit mode never renders', () => {const onHandleMouseDown = jest.fn()- continueResizeGestureInEditMode(pressEvent(gridItem, 150, 0), 'n', moveEvent(150, 12))+ continueResizeGestureInEditMode(pressEvent(gridItem, 150, 200), 's', moveEvent(150, 188))flushFrames(15)- const handle = mountResizeHandle('n')+ const handle = mountResizeHandle('s')handle.addEventListener('mousedown', onHandleMouseDown)flushFrames(3)@@ -217,6 +213,8 @@ describe('editLayoutGesture', () => {continueDragGestureInEditMode(pressEvent(cardMeta, 50, 20), moveEvent(80, 45))grid.className = 'react-grid-layout dashboard-edit-mode'flushFrames()+ gridItem.classList.add('react-draggable-dragging')+ flushFrames()document.removeEventListener('mousemove', onDocumentMouseMove)const replayedPress = onDragHandleMouseDown.mock.calls[0][0] as MouseEventdiff --git a/frontend/src/scenes/dashboard/editLayoutGesture.ts b/frontend/src/scenes/dashboard/editLayoutGesture.tsindex 58c0ba29b9d9..88ca48c38b6f 100644--- a/frontend/src/scenes/dashboard/editLayoutGesture.ts+++ b/frontend/src/scenes/dashboard/editLayoutGesture.ts@@ -45,10 +45,10 @@ export function resolveResizeHandleDirection(clientY: number): string {// Corner presses already name the diagonal handle directly.- if (['nw', 'ne', 'sw', 'se'].includes(edge)) {+ if (edge === 'sw' || edge === 'se') {return edge}- if (edge === 'n' || edge === 's') {+ if (edge === 's') {if (clientX - rect.left <= CORNER_THRESHOLD_PX) {return `${edge}w`}@@ -57,9 +57,6 @@ export function resolveResizeHandleDirection(}return edge}- if (clientY - rect.top <= CORNER_THRESHOLD_PX) {- return `n${edge}`- }if (rect.bottom - clientY <= CORNER_THRESHOLD_PX) {return `s${edge}`}@@ -71,48 +68,106 @@ export function resolveResizeHandleDirection(* before edit mode rendered continues without the user having to release and press again. react-grid-layout* only listens for mousedown while drag/resize is enabled, so the original press never reaches it.*/-function replayMouseDown(event: ReactMouseEvent, findTarget: () => Element | null, pointerNow: MouseEvent): void {+function replayMouseDown(+ event: ReactMouseEvent,+ gridItem: Element,+ findTarget: () => Element | null,+ activeClass: 'resizing' | 'react-draggable-dragging',+ pointerNow: MouseEvent+): void {const { clientX, clientY, button } = eventlet cancelled = false+ let latestPointer = pointerNow+ let frame: number | undefined+ let observer: MutationObserver | undefined+ let framesLeft = MAX_FRAMES_TO_WAIT+ let pressedTarget: Element | null = null++ const cleanup = (): void => {+ if (frame !== undefined) {+ cancelAnimationFrame(frame)+ }+ observer?.disconnect()+ window.removeEventListener('mousemove', trackPointer, { capture: true })+ window.removeEventListener('mouseup', cancel, { capture: true })+ }const cancel = (): void => {cancelled = true+ cleanup()}- // If the button is released before edit mode renders, replaying would leave a drag/resize stuck "in progress"- window.addEventListener('mouseup', cancel, { capture: true, once: true })-- let framesLeft = MAX_FRAMES_TO_WAIT- const tryReplay = (): void => {- if (cancelled) {+ const trackPointer = (moveEvent: MouseEvent): void => {+ latestPointer = moveEvent+ if (!(moveEvent.buttons & 1)) {+ cancel()+ pressedTarget?.ownerDocument.dispatchEvent(+ new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window, button })+ )+ }+ }+ const replayMove = (): void => {+ if (cancelled || !pressedTarget) {return}- const target = findTarget()- if (!target) {- framesLeft -= 1- if (framesLeft > 0) {- requestAnimationFrame(tryReplay)- } else {- window.removeEventListener('mouseup', cancel, { capture: true })- }+ if (!pressedTarget.isConnected) {+ cancel()return}- window.removeEventListener('mouseup', cancel, { capture: true })- target.dispatchEvent(- new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window, clientX, clientY, button })- )- // Replaying the press at its origin keeps the tile from jumping, but leaves react-grid-layout- // believing the pointer never moved. This hands it the travel it missed.- target.ownerDocument.dispatchEvent(+ if (!gridItem.classList.contains(activeClass)) {+ return+ }+ cleanup()+ cancelled = true+ pressedTarget.ownerDocument.dispatchEvent(new MouseEvent('mousemove', {bubbles: true,cancelable: true,view: window,- clientX: pointerNow.clientX,- clientY: pointerNow.clientY,+ clientX: latestPointer.clientX,+ clientY: latestPointer.clientY,button,+ buttons: 1,}))}- requestAnimationFrame(tryReplay)+ const tryReplay = (): void => {+ if (cancelled) {+ return+ }+ if (!pressedTarget) {+ pressedTarget = findTarget()+ if (pressedTarget) {+ observer = new MutationObserver(replayMove)+ observer.observe(gridItem, { attributes: true, attributeFilter: ['class'] })+ pressedTarget.dispatchEvent(+ new MouseEvent('mousedown', {+ bubbles: true,+ cancelable: true,+ view: window,+ clientX,+ clientY,+ button,+ buttons: 1,+ })+ )+ }+ }+ replayMove()+ if (cancelled) {+ return+ }+ framesLeft -= 1+ if (framesLeft > 0) {+ frame = requestAnimationFrame(tryReplay)+ } else {+ cleanup()+ pressedTarget?.ownerDocument.dispatchEvent(+ new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window, button })+ )+ }+ }+ window.addEventListener('mouseup', cancel, { capture: true, once: true })+ window.addEventListener('mousemove', trackPointer, { capture: true })+ frame = requestAnimationFrame(tryReplay)}/** Continue a press on a tile edge into a live resize once edit mode's resize handles have rendered. */@@ -127,7 +182,16 @@ export function continueResizeGestureInEditMode(}const rect = gridItem.getBoundingClientRect()const direction = resolveResizeHandleDirection(edge, rect, event.clientX, event.clientY)- replayMouseDown(event, () => gridItem.querySelector(`.react-resizable-handle-${direction}`), pointerNow)+ replayMouseDown(+ event,+ gridItem,+ () =>+ gridItem.closest('.react-grid-layout.dashboard-edit-mode')+ ? gridItem.querySelector(`.react-resizable-handle-${direction}`)+ : null,+ 'resizing',+ pointerNow+ )}/** Continue a press on a tile's drag handle into a live drag once edit mode has enabled dragging. */@@ -139,9 +203,11 @@ export function continueDragGestureInEditMode(event: ReactMouseEvent, pointerNow}replayMouseDown(event,+ gridItem,() =>// the grid signals that dragging is live by swapping to the edit-mode classtarget.isConnected && gridItem.closest('.react-grid-layout.dashboard-edit-mode') ? target : null,+ 'react-draggable-dragging',pointerNow)}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b0feb89aaaeb..07f3ba58cfa7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1236,8 +1236,8 @@ importers:specifier: ^1.7.11version: 1.7.11([email protected])react-grid-layout:- specifier: ^2.2.4+ specifier: ^2.3.0react-intersection-observer:specifier: ^9.5.3version: 9.5.3([email protected])@@ -3096,9 +3096,12 @@ importers:specifier: 18.3.1version: 18.3.1react-grid-layout:- specifier: ^2.2.4+ specifier: ^2.3.0devDependencies:+ '@testing-library/jest-dom':+ specifier: ^5.17.0+ version: 5.17.0'@testing-library/react':specifier: ^14.3.1@@ -3183,6 +3186,9 @@ importers:products/dashboards:dependencies:+ '@floating-ui/react':+ specifier: ^0.27.19'@posthog/brand':specifier: 'catalog:'version: 0.12.3([email protected])@@ -3228,6 +3234,9 @@ importers:react-grid-layout:specifier: ^2.2.4+ react-intersection-observer:+ specifier: ^9.5.3+ version: 9.5.3([email protected])devDependencies:'@storybook/react':specifier: 'catalog:'@@ -21202,6 +21211,12 @@ packages:react: 18.3.1react-dom: 18.3.1+ resolution: {integrity: sha512-4ofzuR/MlYchp+ixDUVBxH6ybaw+JH51M+rpf675ik/++4Dn0Kax/Vf2Gv/7Z++mV1ZC7mY9UV2sRRycjGjKXQ==}+ peerDependencies:+ react: 18.3.1+ react-dom: 18.3.1+resolution: {integrity: sha512-NJzagSdUPS5rPhaLsHXYeJbsvdpbJwL6yCHtMk91hc0ufQ2BnXis+0QQ9NBh6n9n+Q3OyjR6OQLShYbaNBkThQ==}peerDependencies:@@ -43610,6 +43625,17 @@ snapshots:resize-observer-polyfill: 1.5.1+ dependencies:+ clsx: 2.1.1+ fast-equals: 4.0.3+ prop-types: 15.8.1+ react: 18.3.1+ react-dom: 18.3.1([email protected])+ resize-observer-polyfill: 1.5.1+dependencies:react: 18.3.1diff --git a/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx b/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsxindex 14d1e9e690d2..b067c30041a5 100644--- a/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx+++ b/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx@@ -34,7 +34,7 @@ const CONTAINER_PADDING: [number, number] = [0, 0]// Single-project edit mode's handle, cancel and edge set.const DRAG_HANDLE = '.CardMeta,.DashboardTileCard__body,.WidgetCard__header,.drag-handle'const DRAG_CANCEL = 'a,table,button,input,.Popover'-const RESIZE_HANDLES = ['s', 'e', 'se', 'n', 'w', 'nw', 'ne', 'sw'] as const+const RESIZE_HANDLES = ['s', 'e', 'se', 'w', 'sw'] as constconst NOT_A_DRAG_HANDLE ='input,textarea,button,select,a,p,h4,[contenteditable="true"],[role="textbox"],.ProseMirror,.LemonMarkdown'@@ -69,7 +69,6 @@ export function CrossProjectDashboardGrid({}: CrossProjectDashboardGridProps): JSX.Element {const { width, containerRef, mounted } = useContainerWidth()const [containerHeight, setContainerHeight] = useState(0)- const [resizingTileId, setResizingTileId] = useState<string | null>(null)const scrollContainerRef = useRef<HTMLElement | null>(null)const scrollContainerRectRef = useRef<DOMRect | null>(null)const scrollAnimationRef = useRef<number | null>(null)@@ -171,13 +170,7 @@ export function CrossProjectDashboardGrid({[startInteraction])- const handleResize = useCallback((_layout: unknown, _oldItem: unknown, newItem: LayoutItem | null) => {- // Setting state to the same id bails out of re-rendering, so this re-renders once per gesture.- setResizingTileId(newItem?.i ?? null)- }, [])-const handleResizeStop = useCallback(() => {- setResizingTileId(null)finishGesture()}, [finishGesture])@@ -284,7 +277,6 @@ export function CrossProjectDashboardGrid({breakpoints={GRID_BREAKPOINTS}cols={GRID_COLUMN_COUNTS}onResizeStart={handleResizeStart}- onResize={handleResize}onResizeStop={handleResizeStop}onDragStart={handleDragStart}onDrag={handleDrag}@@ -299,7 +291,6 @@ export function CrossProjectDashboardGrid({showTimezone={timezonesDiverge}missingPropertyKeys={missingPropertyKeys[tile.project_id]}dashboardFilters={dashboardFilters}- isResizing={resizingTileId === tile.id}showResizeHandles={canEditLayout}canEnterEditModeFromEdge={canEnterEditModeFromEdge}onEnterEditModeFromEdge={onEnterEditModeFromEdge}diff --git a/products/cross_project_dashboards/frontend/CrossProjectTile.tsx b/products/cross_project_dashboards/frontend/CrossProjectTile.tsxindex c0ee3cabcce4..fab366a9c340 100644--- a/products/cross_project_dashboards/frontend/CrossProjectTile.tsx+++ b/products/cross_project_dashboards/frontend/CrossProjectTile.tsx@@ -50,7 +50,6 @@ export interface CrossProjectTileProps extends React.HTMLAttributes<HTMLDivElemeshowTimezone?: booleanmissingPropertyKeys?: string[]dashboardFilters?: CrossProjectDashboardFilters- isResizing?: booleancanEnterEditModeFromEdge?: booleanonEnterEditModeFromEdge?: (event: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => voidonDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>@@ -67,7 +66,6 @@ function CrossProjectTileInternal(showTimezone,missingPropertyKeys,dashboardFilters,- isResizing,canEnterEditModeFromEdge,onEnterEditModeFromEdge,onDragHandleMouseDown,@@ -151,7 +149,6 @@ function CrossProjectTileInternal(setOverride={onSetOverride}removeFromDashboard={onRemove}showResizeHandles={showResizeHandles}- isResizing={isResizing}canEnterEditModeFromEdge={canEnterEditModeFromEdge}onEnterEditModeFromEdge={onEnterEditModeFromEdge}onDragHandleMouseDown={onDragHandleMouseDown}diff --git a/products/cross_project_dashboards/package.json b/products/cross_project_dashboards/package.jsonindex 75b8fc61daa9..7fb0d3a1cbc9 100644--- a/products/cross_project_dashboards/package.json+++ b/products/cross_project_dashboards/package.json@@ -13,6 +13,7 @@"posthog-js": "catalog:"},"devDependencies": {+ "@testing-library/jest-dom": "^5.17.0","@testing-library/react": "^14.3.1","kea-test-utils": "catalog:"},@@ -21,6 +22,6 @@"@posthog/icons": "catalog:","@types/react": "*","react": "*",- "react-grid-layout": "^2.2.4"+ "react-grid-layout": "^2.3.0"}}diff --git a/products/dashboards/AGENTS.md b/products/dashboards/AGENTS.mdindex c4bfcabc65b8..fed42f5609a9 100644--- a/products/dashboards/AGENTS.md+++ b/products/dashboards/AGENTS.md@@ -6,6 +6,7 @@ Do not treat every dashboard change as a widget change.## Choose the change type- For dashboard metadata, layouts, insight tiles, text cards, button tiles, or templates, use the product models and API in this directory.+- For dashboard performance work, read [PERFORMANCE.md](./PERFORMANCE.md) before changing loading, scrolling, edit-mode transitions, tile movement, resize, or chart rendering. It covers work across tiles, browser layout, chart drawing, and measurement.- For a tile with `widget_id`, read [`CONTRIBUTING.md`](./CONTRIBUTING.md). It defines widget architecture, registry parity, generated files, and validation commands.- For dashboard creation or updates through PostHog tools, read [`building-a-dashboard`](./skills/building-a-dashboard/SKILL.md).- For scheduled dashboard delivery, read [`managing-subscriptions`](../subscriptions/skills/managing-subscriptions/SKILL.md).diff --git a/products/dashboards/PERFORMANCE.md b/products/dashboards/PERFORMANCE.mdnew file mode 100644index 000000000000..c5a86e6b4fe6--- /dev/null+++ b/products/dashboards/PERFORMANCE.md@@ -0,0 +1,199 @@+# Dashboard performance++Use this guide for dashboard loading, edit mode, scrolling, tile movement, tile resize, and panel resize.+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.+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.++Separate the phases before choosing an optimization:++| Phase | Costs to inspect |+| ------------------------- | -------------------------------------------------------------------------------- |+| Initial load | Requests, response processing, tile mounts, chart initialization, image decoding |+| Enter or exit edit mode | State propagation, React renders, DOM changes, style and layout |+| First movement | Input handlers, grid activation, synchronous work before the first paint |+| Continuous move or resize | Grid calculations, affected tile renders, layout, chart drawing, paint |+| Release and save | Final geometry, chart redraw, serialization, request time, response processing |+| Scroll and revisit | Mounts, retained resources, observer callbacks, repeated queries |++At 60 Hz, a frame lasts about 16.7 ms. JavaScript shares this time with browser rendering and other work.+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++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.++| 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. |++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.++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.++## Limit how far state changes spread++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.+- 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.+- Keep comparisons correct. Ignoring changed callbacks or content can preserve stale behavior.+- Preserve tile keys and chart instances across geometry and mode changes.+- Keep local edit-mode state changes out of dashboard data loaders when no dashboard data changed.++Memoization reduces repeated React work. It does not prevent browser layout or canvas drawing after dimensions change.+For example, moving a tile usually needs a position update; resizing it can also require text layout and a chart redraw.++## Control work frequency++Pointer events, resize observers, state updates, and chart schedulers can request the same work more than once per frame.+Keep the latest required state and combine redundant updates at the appropriate boundary.++- Update visible pixel geometry at the cadence needed to follow the pointer.+- Run collision and compaction calculations when their grid inputs change.+- Combine chart draw requests through the existing frame scheduler.+- Keep persistence out of the pointer event path. Save the completed layout.+- Cancel scheduled work and listeners when the interaction ends or its target disappears.++Do not assume throttling fixes expensive work. A long callback can still block every frame in which it runs.+Check first movement, final movement, quick release, and cancellation when changing scheduling.+Deferred activation must retain the latest pointer position and wait until the grid can accept it.++## Bound browser layout and paint++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.++- Inspect browser style and layout costs alongside React commits.+- Avoid alternating geometry reads and DOM writes across tiles. Group required reads before writes.+- Avoid mounting large control trees solely because edit mode changes.+- Defer hidden controls that perform measurements or other expensive initialization.+- Use containment or content visibility where appropriate, and check overflow, overlays, focus, and active gestures.+- Keep decorative DOM bounded. Repeated backgrounds need not create an element for every grid cell.+- Count DOM nodes before and after mode changes. CSS containment cannot remove the cost of creating thousands of nodes.++Transforms can reduce layout work for position changes. Width and height changes can require layout through the tile's content.+Containment does not remove React work, query work, timers, or canvas resources by itself.+In a vertically compacted grid, shrinking a tile from its top edge opens space above it. Compaction can pull lower tiles upward during that gesture. Keep the top edge fixed when that movement is unwanted.++## Bound mounted content and retained resources++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.++- 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.+- 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.+- 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.++## Make chart resize proportional to the change++Chart cost depends on visible chart count, series count, point count, labels, axes, and canvas pixel area.+Higher device pixel ratios increase backing-store area. A larger canvas can cost more even with unchanged data.++- Reuse chart instances and query results when only dimensions change.+- Separate data preparation from size-dependent ranges and drawing.+- Cache expensive calculations only when all invalidation inputs are understood.+- Include data, axis configuration, stacking, scale type, and size-dependent tick choices where they affect a cached result.+- Profile point processing, text measurement, axes, and drawing separately before choosing a cache or data reduction.+- Preserve hidden-page limits and context-loss recovery.++Keep the chart visible while replacing its image.+Changing a canvas width or height clears its bitmap; update the backing store and draw the replacement in the same scheduled operation.+A frozen or stretched chart changes the experience. Treat that as a product tradeoff when live redraw is required.++## Separate data work from geometry++Moving or resizing a tile should reuse its current data unless dimensions are an explicit query input.+Mode changes and virtualization must not accidentally invalidate queries or start duplicate requests.++- 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.+- 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.++A fast network response can still cause a slow interface if parsing, state propagation, or rendering is expensive.+A slow request does not explain a delayed local drag unless the interaction actually waits for it.++## Measure the affected experience++Respect the user's constraints on runtime checks, tests, and publishing.+If checks are paused, identify the unverified behavior and leave the change local.++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.+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.++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.+If a change improves only a helper benchmark while the browser frame intervals remain unchanged, report the helper result without claiming smoother interaction.++Check the following boundaries for interaction changes:++- Entry, first movement, continuous movement, release, exit, and saved-layout reload.+- One movement followed by a pause, movement below the drag threshold, quick release, and cancellation.+- 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.+- 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.+Focused regression tests can protect behavior; they do not establish frame rate.+Do not convert one local result into a general performance guarantee.++## Code references++- [Dashboard grid and event handlers](../../frontend/src/scenes/dashboard/DashboardItems.tsx).+- [Interaction state and layout commits](../../frontend/src/scenes/dashboard/useDashboardLayoutInteraction.ts).+- [Neighbor resize](../../frontend/src/scenes/dashboard/dashboardResizeCompactor.ts) and [compaction modes](./frontend/dashboardCustomization.ts).+- [Insight card lifecycle](../../frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx).+- [Canvas sizing](../../packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts) and [draw scheduling](../../packages/quill/packages/charts/src/core/hooks/useChartDraw.ts).+- [Dashboard engineering skill](../../.agents/skills/managing-dashboards/SKILL.md) for access, queries, and surface contracts.++Read other dashboard implementations to form hypotheses about architecture and scheduling.+Check their library versions and workload before transferring an approach. Measure the result in PostHog.diff --git a/products/dashboards/frontend/components/DashboardGridBackground.tsx b/products/dashboards/frontend/components/DashboardGridBackground.tsxnew file mode 100644index 000000000000..32f6ec946b93--- /dev/null+++ b/products/dashboards/frontend/components/DashboardGridBackground.tsx@@ -0,0 +1,55 @@+import { useId } from 'react'+import { calcGridCellDimensions } from 'react-grid-layout/core'++interface DashboardGridBackgroundProps {+ width: number+ cols: number+ rowHeight: number+ margin: [number, number]+ height?: number+}++export function DashboardGridBackground({+ width,+ cols,+ rowHeight,+ margin,+ height,+}: DashboardGridBackgroundProps): JSX.Element {+ const patternId = useId()+ const { cellWidth, cellHeight, gapX, gapY } = calcGridCellDimensions({+ width,+ cols,+ rowHeight,+ margin,+ containerPadding: [0, 0],+ })+ const rowCount = height ? Math.ceil((height + gapY) / (cellHeight + gapY)) : 10+ const totalHeight = rowCount * (cellHeight + gapY) - gapY++ return (+ <svg+ className="absolute top-0 left-0 pointer-events-none"+ width={width}+ height={totalHeight}+ aria-hidden="true"+ >+ <defs>+ <pattern+ id={patternId}+ width={cellWidth + gapX}+ height={cellHeight + gapY}+ patternUnits="userSpaceOnUse"+ >+ <rect+ width={Math.max(0, cellWidth)}+ height={cellHeight}+ rx={4}+ fill="var(--color-bg-surface-secondary)"+ />+ </pattern>+ </defs>+ <rect width={width} height={totalHeight} fill={`url(#${patternId})`} />+ </svg>+ )+}diff --git a/products/dashboards/frontend/components/DashboardInsightTile.tsx b/products/dashboards/frontend/components/DashboardInsightTile.tsxnew file mode 100644index 000000000000..0c912a034cab--- /dev/null+++ b/products/dashboards/frontend/components/DashboardInsightTile.tsx@@ -0,0 +1,119 @@+import { useMergeRefs } from '@floating-ui/react'+import clsx from 'clsx'+import { useActions } from 'kea'+import { forwardRef, memo, 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 { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'++import { isSharedView } from '~/exporter/exporterViewLogic'+import { insightsModel } from '~/models/insightsModel'+import type { DashboardTile, InsightModel } from '~/types'+import { DashboardPlacement } from '~/types'++type DashboardInsightTileProps = InsightCardProps &+ Pick<HTMLAttributes<HTMLDivElement>, 'onMouseDown' | 'onMouseUp' | 'onTouchStart' | 'onTouchEnd'> & {+ tile: DashboardTile+ decorations: ReactNode+ }++const MemoizedInsightCard = memo(InsightCard)++export const DashboardInsightTile = forwardRef<HTMLDivElement, DashboardInsightTileProps>(function DashboardInsightTile(+ {+ className,+ style,+ children,+ decorations,+ showResizeHandles,+ canEnterEditModeFromEdge,+ onEnterEditModeFromEdge,+ onMouseDown,+ onMouseUp,+ onTouchStart,+ onTouchEnd,+ ...cardProps+ },+ ref+): JSX.Element {+ const { updateTileColor, toggleTileDescription, duplicateTile, refreshDashboardItem, setTileOverride } =+ useActions(dashboardLogic)+ const { renameInsight } = useActions(insightsModel)+ const { tile, insight } = cardProps+ const [keepMountedForOverlay, setKeepMountedForOverlay] = useState(false)+ const exportPlacement = cardProps.placement === DashboardPlacement.Export+ const { ref: visibilityRef, inView } = useInView({+ rootMargin: '500px',+ triggerOnce: true,+ initialInView: exportPlacement,+ skip: exportPlacement,+ })+ const mergedRefs = useMergeRefs([ref, visibilityRef])+ const sharedView = isSharedView()+ const tileActions = useMemo(() => {+ const refresh = (updatedInsight?: InsightModel): void => {+ refreshDashboardItem({ tile: updatedInsight ? { ...tile, insight: updatedInsight } : tile })+ }+ return {+ updateColor: (color: DashboardTile['color']): void => updateTileColor(tile.id, color),+ toggleShowDescription: (): void => toggleTileDescription(tile.id),+ duplicate: (): void => duplicateTile(tile),+ rename: (): void => renameInsight(insight),+ setOverride: (): void => setTileOverride(tile),+ refresh: sharedView ? undefined : (): void => refresh(),+ refreshAfterDisplayOptionsChange: sharedView ? undefined : refresh,+ }+ }, [+ tile,+ insight,+ sharedView,+ updateTileColor,+ toggleTileDescription,+ duplicateTile,+ refreshDashboardItem,+ setTileOverride,+ renameInsight,+ ])+ const gridClasses = className?.split(' ') ?? []+ const interactionActive = gridClasses.includes('resizing') || gridClasses.includes('react-draggable-dragging')+ const shouldMountCard = inView || exportPlacement || interactionActive || keepMountedForOverlay++ return (+ <div+ ref={mergedRefs}+ className={clsx('dashboard-insight-tile DashboardTileCard', className)}+ style={style}+ onMouseDown={onMouseDown}+ onMouseUp={onMouseUp}+ onTouchStart={onTouchStart}+ onTouchEnd={onTouchEnd}+ >+ {shouldMountCard ? (+ <MemoizedInsightCard+ {...cardProps}+ {...tileActions}+ keepMountedDuringInteraction={interactionActive}+ onOverlayVisibilityChange={setKeepMountedForOverlay}+ renderVizWhenMounted+ >+ {decorations}+ </MemoizedInsightCard>+ ) : (+ <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} />+ </div>+ )}+ {showResizeHandles && <DashboardResizeHandles />}+ {(canEnterEditModeFromEdge || showResizeHandles) && onEnterEditModeFromEdge && (+ <EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />+ )}+ {children}+ </div>+ )+})diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsxindex de7eda744884..3cb5953fcd35 100644--- a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx@@ -15,6 +15,12 @@ import { getDashboardWidgetCatalogEntry, tryGetDashboardWidgetCatalogEntry } froimport { userHasDashboardWidgetProductAccess } from '../../widgetProductAccess'import { DashboardWidgetItem } from './DashboardWidgetItem'+let mockInView = true++jest.mock('react-intersection-observer', () => ({+ useInView: () => ({ ref: jest.fn(), inView: mockInView }),+}))+jest.mock('lib/utils/accessControlUtils', () => ({userHasAccess: () => true,}))@@ -112,6 +118,7 @@ const tileWithoutDescription = {describe('DashboardWidgetItem', () => {beforeEach(() => {+ mockInView = truejest.mocked(userHasDashboardWidgetProductAccess).mockReturnValue(true)initKeaTests(true, {...MOCK_DEFAULT_TEAM,@@ -141,6 +148,33 @@ describe('DashboardWidgetItem', () => {}).unmount()})+ it('mounts widget content only near the viewport', () => {+ mockInView = false+ const widgetItem = (placement = DashboardPlacement.Dashboard): JSX.Element => (+ <DashboardWidgetItem+ tile={tile}+ placement={placement}+ dashboardId={99}+ result={null}+ loading={false}+ onRefresh={jest.fn()}+ />+ )+ const { rerender } = render(widgetItem())++ expect(screen.queryByText('Widget body')).not.toBeInTheDocument()++ mockInView = true+ rerender(widgetItem())++ expect(screen.getByText('Widget body')).toBeInTheDocument()++ mockInView = false+ rerender(widgetItem(DashboardPlacement.Export))++ expect(screen.getByText('Widget body')).toBeInTheDocument()+ })+it('does not render tile filters or widget actions without product access', async () => {jest.mocked(userHasDashboardWidgetProductAccess).mockReturnValue(false)diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsxindex 610c1944b319..2c0aa0f86109 100644--- a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx@@ -1,7 +1,8 @@import clsx from 'clsx'import { useValues } from 'kea'-import React, { Suspense, useState } from 'react'+import React, { Suspense, useCallback, useState } from 'react'import { createPortal } from 'react-dom'+import { useInView } from 'react-intersection-observer'import { CardMetaRefreshButton } from 'lib/components/Cards/CardMetaRefreshButton'import { DashboardTileRefreshDataButton } from 'lib/components/Cards/InsightCard/DashboardTileRefreshDataButton'@@ -10,6 +11,7 @@ import { DashboardWidgetPlacementMenus } from 'lib/components/Cards/InsightCard/import { EditModeEdge } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { ErrorBoundary } from '~/layout/ErrorBoundary'import { DashboardPlacement, DashboardTile, DashboardType } from '~/types'@@ -92,6 +94,7 @@ type DashboardWidgetItemContentProps = Omit<copyToDestinations: ReturnType<typeof useValues<typeof dashboardWidgetMenusLogic>>['copyToDestinations']editOpen: booleansetEditOpen: (open: boolean) => void+ showBody: boolean}type DashboardWidgetItemBodyProps = {@@ -159,6 +162,7 @@ function DashboardWidgetItemContent({copyToDestinations,editOpen,setEditOpen,+ showBody,}: DashboardWidgetItemContentProps): JSX.Element {const widgetTypeLabel = getDashboardWidgetGroupLabel(headerCatalogEntry.groupId)const defaultTitle = headerCatalogEntry.headerTitle ?? widgetTypeLabel@@ -335,21 +339,25 @@ function DashboardWidgetItemContent({onRefresh={isUnknownWidgetType ? undefined : onRefresh}refreshing={isUnknownWidgetType ? false : loading}>- <ErrorBoundary- className="flex min-h-0 min-w-0 flex-1 w-full max-w-full flex-col"- exceptionProps={{- feature: 'dashboard_widget',- widget_type: widget.widget_type,- tile_id: tile.id,- }}- >- <DashboardWidgetItemBody- widget={widget}- definition={definition}- componentProps={componentProps}- dashboardId={dashboardId}- />- </ErrorBoundary>+ {showBody ? (+ <ErrorBoundary+ className="flex min-h-0 min-w-0 flex-1 w-full max-w-full flex-col"+ exceptionProps={{+ feature: 'dashboard_widget',+ widget_type: widget.widget_type,+ tile_id: tile.id,+ }}+ >+ <DashboardWidgetItemBody+ widget={widget}+ definition={definition}+ componentProps={componentProps}+ dashboardId={dashboardId}+ />+ </ErrorBoundary>+ ) : (+ <LemonSkeleton className="min-h-0 w-full flex-1" active={false} />+ )}</WidgetCardBody>)}{EditModal &&@@ -410,6 +418,26 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWid): JSX.Element | null {const widget = tile.widgetconst [editOpen, setEditOpen] = useState(false)+ const exportPlacement = placement === DashboardPlacement.Export+ const { ref: visibilityRef, inView } = useInView({+ rootMargin: '500px',+ triggerOnce: true,+ initialInView: exportPlacement,+ skip: exportPlacement,+ })+ const mergedRef = useCallback(+ (node: HTMLDivElement | null): void => {+ visibilityRef(node)+ if (typeof ref === 'function') {+ ref(node)+ } else if (ref) {+ ref.current = node+ }+ },+ [ref, visibilityRef]+ )+ const gridClasses = className?.split(' ') ?? []+ const interactionActive = gridClasses.includes('resizing') || gridClasses.includes('react-draggable-dragging')const { copyToDestinations } = useValues(dashboardWidgetMenusLogic({@@ -431,12 +459,13 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWidconst headerCatalogEntry =catalogEntryOrUndefined ?? getUnknownDashboardWidgetCatalogFallback(widget.widget_type)const isUnknownWidgetType = catalogEntryOrUndefined === undefined+ const showBody = inView || exportPlacement || interactionActive || editOpen || !!headerCatalogEntry.live// react-grid-layout injects className/style via cloneElement — WidgetCard must be the root node// so decorative resize handles and RGL's .react-resizable-handle siblings share a parent (see InsightCard).return (<WidgetCard- ref={ref}+ ref={mergedRef}className={clsx('min-h-0', className)}style={style}{...divProps}@@ -474,6 +503,7 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWidcopyToDestinations={copyToDestinations}editOpen={editOpen}setEditOpen={setEditOpen}+ showBody={showBody}/></WidgetCard>)diff --git a/products/dashboards/frontend/components/ImageTile/DashboardImageTile.tsx b/products/dashboards/frontend/components/ImageTile/DashboardImageTile.tsxindex 92fb0165ce66..fb3bc5f6110a 100644--- a/products/dashboards/frontend/components/ImageTile/DashboardImageTile.tsx+++ b/products/dashboards/frontend/components/ImageTile/DashboardImageTile.tsx@@ -107,7 +107,7 @@ function DashboardImageTileInternal(</button>)}</div>- {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (+ {(canEnterEditModeFromEdge || showResizeHandles) && onEnterEditModeFromEdge && (<EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />)}{showResizeHandles && <DashboardResizeHandles />}diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCard.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCard.tsxindex f9f61ed07430..82f02139f880 100644--- a/products/dashboards/frontend/components/WidgetCard/WidgetCard.tsx+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCard.tsx@@ -41,7 +41,7 @@ export const WidgetCard = React.forwardRef<HTMLDivElement, WidgetCardProps>(func>{children}{showResizeHandles && <DashboardResizeHandles />}- {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (+ {(canEnterEditModeFromEdge || showResizeHandles) && onEnterEditModeFromEdge && (<EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />)}{gridChildren}diff --git a/products/dashboards/package.json b/products/dashboards/package.jsonindex 01ccb593ea3d..b91169720fa7 100644--- a/products/dashboards/package.json+++ b/products/dashboards/package.json@@ -4,13 +4,15 @@"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},"dependencies": {+ "@floating-ui/react": "^0.27.19","fast-equals": "catalog:","kea": "catalog:","kea-forms": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:","posthog-js": "catalog:",- "react-grid-layout": "^2.2.4"+ "react-grid-layout": "^2.2.4",+ "react-intersection-observer": "^9.5.3"},"devDependencies": {"@storybook/react": "catalog:",