:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(dashboards): move tiles without holding the mouse button (#129625)
Matt Pua6a66fa35d8ca
diff --git a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsxindex 29e683c913fc..0de38e803178 100644--- a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx+++ b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx@@ -128,14 +128,12 @@ export function DashboardAddTileButton(): JSX.Element | null {}export function DashboardEditSaveCancelButtons({- withShortcuts = true,applyFiltersButton,}: {- withShortcuts?: boolean/** The large-dashboard "Apply filters" preview button, rendered between Cancel and Save. */applyFiltersButton?: JSX.Element | null}): JSX.Element {- const { dashboardLoading, canEditDashboard } = useValues(dashboardLogic)+ const { dashboardLoading, canEditDashboard, layoutEditShortcutsEnabled } = useValues(dashboardLogic)const { cancelLayoutEdit, saveLayout } = useActions(dashboardLogic)const cancelButton = (@@ -170,7 +168,7 @@ export function DashboardEditSaveCancelButtons({</LemonButton>)- if (!withShortcuts) {+ if (!layoutEditShortcutsEnabled) {return (<>{cancelButton}@@ -207,28 +205,13 @@ export function DashboardEditSaveCancelButtons({}export function EditModeActions(): JSX.Element {- const {- canEditDashboard,- layoutEditMode,- tiles,- dashboardCustomizeMenuOpen,- showTextTileModal,- showImageTileModal,- showButtonTileModal,- addWidgetModalOpen,- } = useValues(dashboardLogic)+ const { canEditDashboard, layoutEditMode, tiles, dashboardCustomizeMenuOpen } = useValues(dashboardLogic)const { setDashboardCustomizeMenuOpen } = useActions(dashboardLogic)return (<><DashboardSubscribeButton />- {layoutEditMode && (- <DashboardEditSaveCancelButtons- withShortcuts={- !(showTextTileModal || showImageTileModal || showButtonTileModal || addWidgetModalOpen)- }- />- )}+ {layoutEditMode && <DashboardEditSaveCancelButtons />}{canEditDashboard && !layoutEditMode && tiles.length > 0 && <DashboardCustomizeButton />}{layoutEditMode && tiles.length > 0 && (<LemonMenudiff --git a/frontend/src/scenes/dashboard/DashboardItems.scss b/frontend/src/scenes/dashboard/DashboardItems.scssindex e7d5b801e399..6b0f0c87e7d7 100644--- a/frontend/src/scenes/dashboard/DashboardItems.scss+++ b/frontend/src/scenes/dashboard/DashboardItems.scss@@ -164,10 +164,19 @@z-index: 2;max-width: 100%;user-select: none;- border: 1px solid var(--color-accent);+ background:+ linear-gradient(var(--color-accent-highlight-secondary), var(--color-accent-highlight-secondary)),+ var(--color-bg-surface-primary);+ border: 2px dashed var(--color-accent);border-radius: var(--radius);- outline: 1px solid var(--color-accent);transition: 100ms ease;++ // A resize preview sits under the tile, so a fill would hide its content.+ &.placeholder-resizing {+ background: none;+ border: 1px solid var(--color-accent);+ outline: 1px solid var(--color-accent);+ }}.react-resizable-hide > .react-resizable-handle {diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsxindex 7dcfc4f26507..4aa0e1875afd 100644--- a/frontend/src/scenes/dashboard/DashboardItems.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx@@ -3,7 +3,8 @@ import './DashboardItems.scss'import clsx from 'clsx'import { useActions, useAsyncActions, useMountedLogic, useValues } from 'kea'import { router } from 'kea-router'-import { RefObject, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { RefObject, memo, useCallback, useEffect, useMemo, useRef } from 'react'+import { createPortal } from 'react-dom'import { GridLayout, Responsive as ReactGridLayout } from 'react-grid-layout'import type { Layout, LayoutItem } from 'react-grid-layout'import { type PositionStrategy, setTransform } from 'react-grid-layout/core'@@ -52,6 +53,7 @@ import { TileGroupTakeOutDropZone } from 'products/dashboards/frontend/componentimport { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'import { getGroupTitlesByTileId, hasTileDecorations } from 'products/dashboards/frontend/dashboardTileGroups'import { type DashboardSection, getSectionGroupKey } from 'products/dashboards/frontend/dashboardTileSections'+import { useClickToMoveTile } from 'products/dashboards/frontend/useClickToMoveTile'import { useDashboardContainerWidth } from 'products/dashboards/frontend/useDashboardContainerWidth'import { TAKE_OUT_DROP_ZONE_KEY, useTileGroupDrag } from 'products/dashboards/frontend/useTileGroupDrag'@@ -171,6 +173,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPselectTileGroupTab,updateTileGroupSectionLayout,moveTileToSection,+ setCarryingTile,} = useActions(dashboardLogic)const { updateWidgetTile } = useAsyncActions(dashboardLogic)// dashboard_tiles is empty because this selector covers a whole group, not one tile; the@@ -191,8 +194,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP? undefined: () => loadDashboard({ action: DashboardLoadAction.Update })- const [containerHeight, setContainerHeight] = useState<number | undefined>(undefined)-// cannot click links when dragging and 250ms afterconst isDragging = useRef(false)// While a drag/resize is in progress the grid drives itself from its own internal state and ignores the@@ -243,41 +244,13 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPconst { width: gridWidth, containerRef } = useDashboardContainerWidth()const showBands = tileGroupSections.length > 0const activeTabIndex = tileGroupSections.findIndex((section) => getSectionGroupKey(section) === activeTileGroupTab)- const { gridCompactor, handleLayoutChange, interactionInProgress, startInteraction, finishInteraction } =- useDashboardLayoutInteraction({- layoutEditMode,- layoutCompaction: dashboard?.customization?.layout_compaction,- // Each band grid reports only its own tiles.- updateLayouts: showBands ? updateTileGroupSectionLayout : stageLayouts,- })-- useEffect(() => {- if (!containerRef.current) {- return- }-- const element = containerRef.current- const observer = new ResizeObserver((entries) => {- // Skip per-frame height commits during a gesture — they re-render every tile just for GridBackground,- // lagging the cursor. flushPendingLayouts remeasures on stop.- if (interactionInProgress.current) {- return- }- for (const entry of entries) {- if (entry.target === element) {- setContainerHeight(entry.contentRect.height)- }- }- })-- // Set initial height- setContainerHeight(element.clientHeight)- observer.observe(element)+ const { gridCompactor, handleLayoutChange, startInteraction, finishInteraction } = useDashboardLayoutInteraction({+ layoutEditMode,+ layoutCompaction: dashboard?.customization?.layout_compaction,+ // Each band grid reports only its own tiles.+ updateLayouts: showBands ? updateTileGroupSectionLayout : stageLayouts,+ })- return () => {- observer.disconnect()- }- }, [containerRef])const isMobileView = !!gridWidth && gridWidth <= BREAKPOINTS['sm']const isEditablePlacement =!readOnly &&@@ -397,6 +370,13 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPrestoreLayout: (layout) => stageLayouts({ sm: layout }),})const boundedStrategy = useMemo(() => sidewaysBoundedStrategy(gridWidth), [gridWidth])+ const { tileMoveInputRef, carryHeldDrag } = useClickToMoveTile({+ containerRef: containerRef as RefObject<HTMLElement>,+ enabled: dragConfig.enabled,+ handleSelector: dragConfig.handle,+ cancelSelector: dragConfig.cancel,+ onCarryingChange: setCarryingTile,+ })const resizeConfig = useMemo(() => ({@@ -519,17 +499,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP])- const flushPendingLayouts = useCallback(() => {- finishInteraction()- // Remeasure once the gesture settles, since height updates were suppressed during it.- requestAnimationFrame(() => {- if (containerRef.current) {- setContainerHeight(containerRef.current.clientHeight)- }- })- // oxlint-disable-next-line react-hooks/exhaustive-deps -- ref reads inside requestAnimationFrame aren't valid deps- }, [finishInteraction])-const handleWidthChange = useCallback((containerWidth: number, _: unknown, newCols: number) => {updateContainerWidth(containerWidth, newCols)@@ -576,11 +545,11 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP)const handleResizeStop = useCallback(() => {- flushPendingLayouts()+ finishInteraction()if (dashboard?.id) {reportDashboardTileRepositioned(dashboard.id, 'resized', effectiveZoom)}- }, [dashboard?.id, effectiveZoom, flushPendingLayouts])+ }, [dashboard?.id, effectiveZoom, finishInteraction])const handleDragStart = useCallback((@@ -597,8 +566,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPstartInteraction(layout, newItem, 'drag')startTileDrag(newItem, element)startAutoScroll()+ carryHeldDrag(element)},- [startInteraction, startTileDrag, startAutoScroll]+ [startInteraction, startTileDrag, startAutoScroll, carryHeldDrag])const handleDrag = useCallback(@@ -629,13 +599,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPdragEndTimeout.current = window.setTimeout(() => {isDragging.current = false}, 250)- flushPendingLayouts()+ finishInteraction()finishTileDrag(newItem, element, event)- if (dashboard?.id) {- reportDashboardTileRepositioned(dashboard.id, 'moved', effectiveZoom)+ const input = tileMoveInputRef.current+ if (dashboard?.id && input !== 'canceled') {+ reportDashboardTileRepositioned(dashboard.id, 'moved', effectiveZoom, input)}},- [dashboard?.id, effectiveZoom, flushPendingLayouts, finishTileDrag, stopAutoScroll]+ [dashboard?.id, effectiveZoom, finishInteraction, finishTileDrag, stopAutoScroll, tileMoveInputRef])const renderTile = (tile: DashboardTile): JSX.Element | undefined => {@@ -833,8 +804,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPconst isLastSection = activeTabIndex >= 0 || (index === tileGroupSections.length - 1 && !showTakeOutDropZone)const isDraggingOutOfSection =!!dropTargetKey && section.tiles.some((tile) => tile.id.toString() === draggingTileId)- // One empty row below the tiles gives a dragged tile somewhere to land.- const sectionRows = Math.max(0, ...(sectionLayouts.sm ?? []).map((item) => item.y + item.h)) + 1return (<divclassName="relative"@@ -847,7 +816,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPcols={BREAKPOINT_COLUMN_COUNTS.sm}rowHeight={rowHeight}margin={margin}- height={sectionRows * (rowHeight + margin[1]) - margin[1]}/>)}{/* Not Responsive: its layout copy and the inner grid's can swap on every render while tiles stream in. */}@@ -941,7 +909,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPcols={BREAKPOINT_COLUMN_COUNTS.sm}rowHeight={rowHeight}margin={margin}- height={containerHeight} // kept in sync via ResizeObserver/>)}@@ -963,6 +930,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP</ReactGridLayout></div>)}+ <TileMoveHint />{dashboardStreaming && (<div className="mt-4 flex items-center justify-center"><div className="flex items-center gap-2 text-muted">@@ -974,3 +942,23 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP</div>)}++// Reads carryingTile itself, so a carry starting or ending re-renders only this pill and not every tile in the grid.+// The portal keeps the pill out of the grid's subtree, where inserting a node restyles every tile.+function TileMoveHint(): JSX.Element | null {+ const { carryingTile } = useValues(dashboardLogic)+ if (!carryingTile) {+ return null+ }+ return createPortal(+ // Ignores the pointer, because the next click drops the tile wherever this pill is.+ <div+ role="status"+ className="pointer-events-none fixed bottom-6 left-1/2 z-top flex -translate-x-1/2 items-center gap-2 rounded-full border bg-surface-primary px-3 py-1 text-sm shadow"+ >+ <span>Click to drop the tile</span>+ <span className="text-secondary">· Esc to cancel</span>+ </div>,+ document.body+ )+}diff --git a/frontend/src/scenes/dashboard/DashboardModals.test.tsx b/frontend/src/scenes/dashboard/DashboardModals.test.tsxindex 3b0419a84e42..045528853a39 100644--- a/frontend/src/scenes/dashboard/DashboardModals.test.tsx+++ b/frontend/src/scenes/dashboard/DashboardModals.test.tsx@@ -199,7 +199,7 @@ describe('dashboard layout edit shortcut with a tile dialog', () => {jest.clearAllMocks()})- const renderActions = (visibleKey?: string): ReturnType<typeof render> => {+ const renderActions = (overrides: Record<string, boolean> = {}): ReturnType<typeof render> => {mockedUseValues.mockImplementation((logic) =>logic === dashboardLogic? {@@ -208,11 +208,8 @@ describe('dashboard layout edit shortcut with a tile dialog', () => {canEditDashboard: true,layoutEditMode: true,dashboardLoading: false,- showImageTileModal: false,- showButtonTileModal: false,- showTextTileModal: false,- addWidgetModalOpen: false,- ...(visibleKey ? { [visibleKey]: true } : {}),+ layoutEditShortcutsEnabled: true,+ ...overrides,}: {})@@ -220,21 +217,16 @@ describe('dashboard layout edit shortcut with a tile dialog', () => {return render(<EditModeActions />)}- it.each(['showImageTileModal', 'showButtonTileModal', 'showTextTileModal', 'addWidgetModalOpen'] as const)(- 'does not bind Escape to discard while %s is open',- (visibleKey) => {- const { container } = renderActions(visibleKey)-- expect(container.querySelector('[data-shortcut-name="CancelDashboardEdit"]')).toBeNull()- const cancelButton = container.querySelector(- '[data-attr="dashboard-edit-mode-discard"]'- ) as HTMLButtonElement- expect(cancelButton.disabled).toBe(false)- expect(cancelLayoutEdit).not.toHaveBeenCalled()- }- )+ it('does not bind Escape to discard while layout edit shortcuts are off', () => {+ const { container } = renderActions({ layoutEditShortcutsEnabled: false })++ expect(container.querySelector('[data-shortcut-name="CancelDashboardEdit"]')).toBeNull()+ const cancelButton = container.querySelector('[data-attr="dashboard-edit-mode-discard"]') as HTMLButtonElement+ expect(cancelButton.disabled).toBe(false)+ expect(cancelLayoutEdit).not.toHaveBeenCalled()+ })- it('binds Escape to discard when no tile dialog is open', () => {+ it('binds Escape to discard while layout edit shortcuts are on', () => {const { container } = renderActions()expect(container.querySelector('[data-shortcut-name="CancelDashboardEdit"]')).not.toBeNull()diff --git a/frontend/src/scenes/dashboard/QuillDashboardHeaderActions.tsx b/frontend/src/scenes/dashboard/QuillDashboardHeaderActions.tsxindex 7ae24469c5d6..780d5358ec13 100644--- a/frontend/src/scenes/dashboard/QuillDashboardHeaderActions.tsx+++ b/frontend/src/scenes/dashboard/QuillDashboardHeaderActions.tsx@@ -30,10 +30,7 @@ export function QuillDashboardHeaderActions(): JSX.Element | null {layoutEditMode,tiles,dashboardCustomizeMenuOpen,- showTextTileModal,- showImageTileModal,- showButtonTileModal,- addWidgetModalOpen,+ layoutEditShortcutsEnabled,} = useValues(dashboardLogic)const { setDashboardMode, setDashboardCustomizeMenuOpen, cancelLayoutEdit, saveLayout } = useActions(dashboardLogic)const { push } = useActions(router)@@ -43,7 +40,6 @@ export function QuillDashboardHeaderActions(): JSX.Element | null {}if (dashboardEditing) {- const withShortcuts = !(showTextTileModal || showImageTileModal || showButtonTileModal || addWidgetModalOpen)const cancelButton = (<Buttondata-attr="dashboard-edit-mode-discard"@@ -76,7 +72,7 @@ export function QuillDashboardHeaderActions(): JSX.Element | null {<><QuillDashboardSubscribeButton />{layoutEditMode &&- (withShortcuts ? (+ (layoutEditShortcutsEnabled ? (<><Shortcutname="CancelDashboardEdit"diff --git a/frontend/src/scenes/dashboard/dashboardEvents.ts b/frontend/src/scenes/dashboard/dashboardEvents.tsindex 83111bc7e7f7..10455d4c9574 100644--- a/frontend/src/scenes/dashboard/dashboardEvents.ts+++ b/frontend/src/scenes/dashboard/dashboardEvents.ts@@ -179,12 +179,14 @@ export function reportDashboardInsightDeleteAfterRemovalClicked(otherDashboardCoexport function reportDashboardTileRepositioned(dashboardId: number,action: 'moved' | 'resized',- layoutZoom: number+ layoutZoom: number,+ input: 'drag' | 'click' = 'drag'): void {posthog.capture('dashboard tile repositioned', {dashboard_id: dashboardId,action,layout_zoom: layoutZoom,+ input,})}diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex ee42cf7362c8..fcf9a5ffd463 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -3762,6 +3762,29 @@ describe('dashboardLogic', () => {}).toNotHaveDispatchedActions([logic.actionCreators.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges),])++ await expectLogic(logic, () => {+ logic.actions.cancelLayoutEdit()+ })+ .toFinishAllListeners()+ .toMatchValues({ discardPromptOpen: true, layoutEditShortcutsEnabled: false })+ expect(dialogOpenSpy).toHaveBeenCalledTimes(1)++ dialogOpenSpy.mock.calls[0][0].onAfterClose()+ await expectLogic(logic, () => {+ logic.actions.cancelLayoutEdit()+ }).toFinishAllListeners()+ expect(dialogOpenSpy).toHaveBeenCalledTimes(2)+ })++ it.each([+ ['a text tile dialog is open', (): void => logic.actions.openTextTileModal()],+ ['an image tile dialog is open', (): void => logic.actions.openImageTileModal()],+ ['a button tile dialog is open', (): void => logic.actions.openButtonTileModal()],+ ['the add widget dialog is open', (): void => logic.actions.setAddWidgetModalOpen(true)],+ ['a tile is carried', (): void => logic.actions.setCarryingTile(true)],+ ])('turns off layout edit shortcuts while %s', async (_, open) => {+ await expectLogic(logic, open).toMatchValues({ layoutEditShortcutsEnabled: false })})it('exits edit mode immediately when the prompt flag is off, even with unsaved layout changes', async () => {diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex a8333d85106d..bc76fc2b5b00 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -749,6 +749,7 @@ export interface dashboardLogicValues {canRestrictDashboard: booleancanSaveProjectDashboardTemplate: booleancancellingPreview: boolean+ carryingTile: booleanchangedFilterCount: numbercollapsedTileGroupKeys: string[]collapsedTileIds: Set<number>@@ -780,6 +781,7 @@ export interface dashboardLogicValues {dashboardTileSpacingSaving: booleandataColorTheme: DataColorTheme | nulldataColorThemeId: number | null+ discardPromptOpen: booleandraftLayouts: ResponsiveLayouts | nulleffectiveBreakdownColors: BreakdownColorConfig[]effectiveEditBarFilters: DashboardFilter@@ -813,6 +815,7 @@ export interface dashboardLogicValues {lastDashboardRefresh: Dayjs | nulllayout: Layout | undefinedlayoutEditMode: boolean+ layoutEditShortcutsEnabled: booleanlayoutForItem: Record<string, TileLayout>layoutZoom: numberlayouts: ResponsiveLayouts@@ -1390,6 +1393,9 @@ export interface dashboardLogicActions {setButtonTileId: (buttonTileId: DashboardTileIdOrNew) => {buttonTileId: DashboardTileIdOrNew}+ setCarryingTile: (carryingTile: boolean) => {+ carryingTile: boolean+ }setCompareFilter: (compareFilter: CompareFilter | null) => {compareFilter: CompareFilter | null}@@ -1440,6 +1446,9 @@ export interface dashboardLogicActions {dateTo: string | null | undefinedexplicitDate: boolean | undefined}+ setDiscardPromptOpen: (discardPromptOpen: boolean) => {+ discardPromptOpen: boolean+ }setExternalFilters: (filters: DashboardFilter) => {filters: DashboardFilter}@@ -1954,6 +1963,14 @@ export interface dashboardLogicMeta {autoBreakdownColorsEnabled: boolean,dataColorTheme: DataColorTheme | null) => BreakdownColorConfig[]+ layoutEditShortcutsEnabled: (+ carryingTile: boolean,+ discardPromptOpen: boolean,+ showTextTileModal: boolean,+ showImageTileModal: boolean,+ showButtonTileModal: boolean,+ addWidgetModalOpen: boolean+ ) => booleanhasUnsavedColorChanges: (temporaryBreakdownColors: BreakdownColorConfig[],temporaryDataColorThemeId: {@@ -2167,6 +2184,8 @@ export const dashboardLogic = kea<dashboardLogicType>([widgets: { widgetType: string; config: Record<string, unknown> }[]}) => payload,setAddWidgetModalOpen: (open: boolean) => ({ open }),+ setCarryingTile: (carryingTile: boolean) => ({ carryingTile }),+ setDiscardPromptOpen: (discardPromptOpen: boolean) => ({ discardPromptOpen }),toggleAddWidgetSelectedType: (widgetType: string) => ({ widgetType }),clearAddWidgetSelectedTypes: true,toggleAddWidgetCollapsedGroup: (groupId: string) => ({ groupId }),@@ -3567,6 +3586,19 @@ export const dashboardLogic = kea<dashboardLogicType>([setAddWidgetModalOpen: (_, { open }) => open,},],+ carryingTile: [+ false,+ {+ setCarryingTile: (_, { carryingTile }) => carryingTile,+ setDashboardMode: () => false,+ },+ ],+ discardPromptOpen: [+ false,+ {+ setDiscardPromptOpen: (_, { discardPromptOpen }) => discardPromptOpen,+ },+ ],addWidgetSelectedTypes: [[] as string[],{@@ -4519,6 +4551,17 @@ export const dashboardLogic = kea<dashboardLogicType>([return applyAutoBreakdownColors(tileBreakdownValues, kept, paletteSize)},],+ layoutEditShortcutsEnabled: [+ (s) => [+ s.carryingTile,+ s.discardPromptOpen,+ s.showTextTileModal,+ s.showImageTileModal,+ s.showButtonTileModal,+ s.addWidgetModalOpen,+ ],+ (...blockers: boolean[]): boolean => !blockers.some(Boolean),+ ],hasUnsavedColorChanges: [(s) => [s.temporaryBreakdownColors, s.temporaryDataColorThemeId, s.dashboard],(@@ -6264,9 +6307,14 @@ export const dashboardLogic = kea<dashboardLogicType>([discard()return}+ if (values.discardPromptOpen) {+ return+ }reportDashboardEditModeDiscardPrompt(values.dashboard, 'shown')+ actions.setDiscardPromptOpen(true)LemonDialog.open({title: 'Discard unsaved changes?',+ onAfterClose: () => actions.setDiscardPromptOpen(false),description:'You have unsaved layout or color changes. If you discard now, the dashboard will revert to its last saved state.',primaryButton: {diff --git a/products/dashboards/PERFORMANCE.md b/products/dashboards/PERFORMANCE.mdindex a63e288f0110..82493f98dd79 100644--- a/products/dashboards/PERFORMANCE.md+++ b/products/dashboards/PERFORMANCE.md@@ -57,6 +57,7 @@ Dashboard-wide state can make every card render even when only one tile moves.- 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.+- Do not dispatch a Kea action on the first movement of a gesture. Each dispatch reruns the selectors of every subscribed component on the dashboard, even when only a small overlay reads the new value.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.@@ -89,6 +90,7 @@ Check third-party drag and resize code for global style changes. Recheck upstrea- 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.+- Mount transient overlays, such as a move hint, outside the grid through a portal. The grid styles use `:has()` selectors, so a node inserted into the grid wrapper restyles every tile.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.@@ -180,6 +182,9 @@ If checks are paused, identify the unverified behavior and leave the change loca10. Stop traces and detach diagnostic sessions. Repeat timing measurements without profiling overhead.11. Compare the first gesture after a fresh load with a repeat gesture on the same page. Record whether tiles still mount during the gesture.+A hidden or covered browser window throttles animation frames, and the timings it reports are not valid.+Measure in a visible window or a headless browser, and check the frame rate before each run.+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.diff --git a/products/dashboards/frontend/carryTile.test.ts b/products/dashboards/frontend/carryTile.test.tsnew file mode 100644index 000000000000..35b52f7bcf2e--- /dev/null+++ b/products/dashboards/frontend/carryTile.test.ts@@ -0,0 +1,165 @@+import { type TileCarry, type TilePickUp, carryTile, getTilePickUp } from './carryTile'++const HANDLE = '.CardMeta,.drag-handle'+const CANCEL = 'a,table,button,input,.Popover'++function renderGrid(): {+ grid: HTMLElement+ meta: HTMLElement+ button: HTMLElement+ body: HTMLElement+} {+ document.body.innerHTML = `+ <div class="react-grid-layout">+ <div class="react-grid-item">+ <div class="CardMeta">+ <span class="title">Signups</span><button>More</button>+ </div>+ <div class="body">chart</div>+ </div>+ </div>`+ return {+ grid: document.querySelector('.react-grid-layout')!,+ meta: document.querySelector('.title')!,+ button: document.querySelector('button')!,+ body: document.querySelector('.body')!,+ }+}++function clickOn(target: Element, init: MouseEventInit = {}): MouseEvent {+ const event = new MouseEvent('click', { bubbles: true, cancelable: true, clientX: 10, clientY: 10, ...init })+ target.dispatchEvent(event)+ return event+}++describe('carryTile', () => {+ let listeners: AbortController+ let carries: TileCarry[]++ const listen = <K extends keyof DocumentEventMap>(+ target: EventTarget,+ type: K,+ handler: (event: DocumentEventMap[K]) => unknown+ ): void => target.addEventListener(type, handler as EventListener, { signal: listeners.signal })++ const startCarry = (props: Parameters<typeof carryTile>[0]): TileCarry => {+ const carry = carryTile(props)+ carries.push(carry)+ return carry+ }++ beforeEach(() => {+ jest.useFakeTimers()+ listeners = new AbortController()+ carries = []+ })++ afterEach(() => {+ carries.forEach((carry) => carry.cancel())+ listeners.abort()+ jest.runOnlyPendingTimers()+ jest.useRealTimers()+ document.body.innerHTML = ''+ })++ test.each([+ ['an unmoved click on the drag handle', 'meta', { x: 10, y: 10 }, {}, true],+ ['a click on the chart, outside the drag handle', 'body', { x: 10, y: 10 }, {}, false],+ ['a button inside the drag handle', 'button', { x: 10, y: 10 }, {}, false],+ ['the end of a held drag', 'meta', { x: 40, y: 10 }, {}, false],+ ] as const)('decides whether %s picks up the tile', (_, targetKey, press, init, expected) => {+ const elements = renderGrid()+ const result: { pickUp: TilePickUp | null } = { pickUp: null }+ listen(elements[targetKey], 'click', (event) => {+ result.pickUp = getTilePickUp(event, press, HANDLE, CANCEL)+ })+ clickOn(elements[targetKey], init)+ expect(result.pickUp?.target ?? null).toBe(expected ? elements[targetKey] : null)+ })++ it('ends the drag on the next release and swallows the click that follows it', () => {+ const { grid, meta, body } = renderGrid()+ const presses: number[] = []+ listen(meta, 'mousedown', (event) => presses.push(event.buttons))+ const releases: number[] = []+ listen(document, 'mouseup', (event) => releases.push(event.clientX))+ const onDrop = jest.fn()++ startCarry({ target: meta, grid, clientX: 10, clientY: 10, onDrop, onCancel: jest.fn() })+ expect(presses).toEqual([1])++ const dropPress = new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 })+ body.dispatchEvent(dropPress)+ body.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 300 }))+ const dropClick = clickOn(body)++ expect(dropPress.defaultPrevented).toBe(true)+ expect(releases).toEqual([300])+ expect(onDrop).toHaveBeenCalledTimes(1)+ expect(dropClick.defaultPrevented).toBe(true)++ jest.runAllTimers()+ expect(clickOn(body).defaultPrevented).toBe(false)+ })++ it('keeps a held drag going after its release, until the next click', () => {+ const { grid, meta, body } = renderGrid()+ const presses: number[] = []+ listen(meta, 'mousedown', (event) => presses.push(event.buttons))+ const releases: number[] = []+ listen(document, 'mouseup', (event) => releases.push(event.clientX))+ const onDrop = jest.fn()++ startCarry({ target: meta, grid, clientX: 10, clientY: 10, held: true, onDrop, onCancel: jest.fn() })+ body.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 100 }))++ expect(presses).toEqual([])+ expect(releases).toEqual([])+ expect(onDrop).not.toHaveBeenCalled()++ body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 }))+ body.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 300 }))++ expect(releases).toEqual([300])+ expect(onDrop).toHaveBeenCalledTimes(1)+ })++ it('replays the last pointer position on scroll until the tile is dropped', () => {+ const { grid, meta, body } = renderGrid()+ const moves: [number, number][] = []+ listen(document, 'mousemove', (event) => moves.push([event.clientX, event.clientY]))++ startCarry({ target: meta, grid, clientX: 10, clientY: 10, onDrop: jest.fn(), onCancel: jest.fn() })+ body.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 40, clientY: 60 }))+ body.dispatchEvent(new Event('scroll'))+ expect(moves).toEqual([+ [40, 60],+ [40, 60],+ ])++ body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 }))+ body.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0 }))+ body.dispatchEvent(new Event('scroll'))+ expect(moves).toHaveLength(2)+ })++ it('puts the tile back on Esc by releasing at the pick-up point', () => {+ const { grid, meta } = renderGrid()+ const pointer: [string, number, number][] = []+ const record = (event: MouseEvent): number => pointer.push([event.type, event.clientX, event.clientY])+ listen(document, 'mousemove', record)+ listen(document, 'mouseup', record)+ const onCancel = jest.fn()+ const onDrop = jest.fn()++ startCarry({ target: meta, grid, clientX: 25, clientY: 40, onDrop, onCancel })+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }))++ expect(onCancel).toHaveBeenCalledTimes(1)+ expect(onDrop).not.toHaveBeenCalled()+ expect(pointer).toEqual([+ ['mousemove', 25, 40],+ ['mouseup', 25, 40],+ ])+ })+})diff --git a/products/dashboards/frontend/carryTile.ts b/products/dashboards/frontend/carryTile.tsnew file mode 100644index 000000000000..a18b2ba6d3d7--- /dev/null+++ b/products/dashboards/frontend/carryTile.ts@@ -0,0 +1,161 @@+// react-grid-layout's drag threshold, so a press that travels further was a drag.+const CLICK_TRAVEL_LIMIT_PX = 3+const KEEP_CLICK_SELECTOR = [+ 'textarea',+ 'select',+ 'label',+ '[role="button"]',+ '[role="menuitem"]',+ '[role="textbox"]',+ '[contenteditable="true"]',+ '.ProseMirror',+ '.react-resizable-handle',+].join(',')++export interface TilePickUp {+ target: Element+ grid: Element+}++export interface TileCarry {+ cancel: () => void+}++interface CarryTileProps extends TilePickUp {+ clientX: number+ clientY: number+ held?: boolean+ onHeldRelease?: () => void+ onDrop: () => void+ onCancel: () => void+}++function dispatchMouse(target: EventTarget, type: string, clientX: number, clientY: number, buttons: number): void {+ target.dispatchEvent(+ new MouseEvent(type, { bubbles: true, cancelable: true, view: window, clientX, clientY, button: 0, buttons })+ )+}++function swallowEvent(event: Event): void {+ event.preventDefault()+ event.stopPropagation()+}++export function getTilePickUp(+ event: MouseEvent,+ press: { x: number; y: number } | null,+ handleSelector: string,+ cancelSelector: string+): TilePickUp | null {+ if (!press || event.button !== 0 || event.detail > 1) {+ return null+ }+ if (Math.hypot(event.clientX - press.x, event.clientY - press.y) > CLICK_TRAVEL_LIMIT_PX) {+ return null+ }+ const target = event.target instanceof Element ? event.target : null+ const gridItem = target?.closest('.react-grid-item')+ const grid = gridItem?.parentElement+ const handle = target?.closest(handleSelector)+ if (!target || !gridItem || !grid || !handle || !gridItem.contains(handle)) {+ return null+ }+ if (target.closest(cancelSelector) || target.closest(KEEP_CLICK_SELECTOR)) {+ return null+ }+ return { target, grid }+}++export function carryTile({+ target,+ grid,+ clientX,+ clientY,+ held = false,+ onHeldRelease,+ onDrop,+ onCancel,+}: CarryTileProps): TileCarry {+ const gridRect = grid.getBoundingClientRect()+ const offsetX = clientX - gridRect.left+ const offsetY = clientY - gridRect.top+ let carrying = true+ let awaitingHeldRelease = held+ let pointerX = clientX+ let pointerY = clientY++ const stop = (): void => {+ carrying = false+ window.removeEventListener('mousedown', swallowLeftPress, { capture: true })+ window.removeEventListener('mouseup', drop, { capture: true })+ window.removeEventListener('keydown', cancelOnEscape, { capture: true })+ window.removeEventListener('mousemove', trackPointer, { capture: true })+ document.removeEventListener('scroll', followScroll, { capture: true })+ }++ function trackPointer(event: MouseEvent): void {+ pointerX = event.clientX+ pointerY = event.clientY+ }++ function followScroll(): void {+ dispatchMouse(document, 'mousemove', pointerX, pointerY, 1)+ }++ function swallowLeftPress(event: MouseEvent): void {+ if (event.button === 0) {+ swallowEvent(event)+ }+ }++ function drop(event: MouseEvent): void {+ if (event.button !== 0) {+ return+ }+ window.addEventListener('click', swallowEvent, { capture: true, once: true })+ window.setTimeout(() => window.removeEventListener('click', swallowEvent, { capture: true }), 0)+ if (awaitingHeldRelease) {+ // Letting go of the held press keeps the tile moving, so react-grid-layout must not see this release.+ awaitingHeldRelease = false+ swallowEvent(event)+ onHeldRelease?.()+ return+ }+ // This release has to reach react-grid-layout to end the drag. Only the click that follows is swallowed.+ stop()+ onDrop()+ }++ const cancel = (): void => {+ if (!carrying) {+ return+ }+ stop()+ // Called before the release, so the grid's drag stop handler already sees the move as canceled.+ onCancel()+ const rect = grid.getBoundingClientRect()+ const x = rect.left + offsetX+ const y = rect.top + offsetY+ dispatchMouse(document, 'mousemove', x, y, 1)+ dispatchMouse(document, 'mouseup', x, y, 0)+ }++ function cancelOnEscape(event: KeyboardEvent): void {+ if (event.key === 'Escape') {+ swallowEvent(event)+ cancel()+ }+ }++ if (!held) {+ dispatchMouse(target, 'mousedown', clientX, clientY, 1)+ }+ window.addEventListener('mousedown', swallowLeftPress, { capture: true })+ window.addEventListener('mouseup', drop, { capture: true })+ window.addEventListener('keydown', cancelOnEscape, { capture: true })+ window.addEventListener('mousemove', trackPointer, { capture: true, passive: true })+ // Scroll events do not bubble, so capture catches the scene's own scroll container too.+ document.addEventListener('scroll', followScroll, { capture: true, passive: true })++ return { cancel }+}diff --git a/products/dashboards/frontend/components/DashboardGridBackground.tsx b/products/dashboards/frontend/components/DashboardGridBackground.tsxindex 32f6ec946b93..ba05af9ed24a 100644--- a/products/dashboards/frontend/components/DashboardGridBackground.tsx+++ b/products/dashboards/frontend/components/DashboardGridBackground.tsx@@ -6,6 +6,7 @@ interface DashboardGridBackgroundProps {cols: numberrowHeight: numbermargin: [number, number]+ /** Draws whole rows up to this height. Without it, the background fills its positioned parent as the grid grows. */height?: number}@@ -25,7 +26,7 @@ export function DashboardGridBackground({containerPadding: [0, 0],})const rowCount = height ? Math.ceil((height + gapY) / (cellHeight + gapY)) : 10- const totalHeight = rowCount * (cellHeight + gapY) - gapY+ const totalHeight = height === undefined ? '100%' : rowCount * (cellHeight + gapY) - gapYreturn (<svgdiff --git a/products/dashboards/frontend/useClickToMoveTile.test.ts b/products/dashboards/frontend/useClickToMoveTile.test.tsnew file mode 100644index 000000000000..c1d5c34c44f5--- /dev/null+++ b/products/dashboards/frontend/useClickToMoveTile.test.ts@@ -0,0 +1,78 @@+import { renderHook } from '@testing-library/react'++import { useClickToMoveTile } from './useClickToMoveTile'++describe('useClickToMoveTile', () => {+ let container: HTMLElement+ let gridItem: HTMLElement+ let handle: HTMLElement++ beforeEach(() => {+ jest.useFakeTimers()+ document.body.innerHTML = `+ <div class="container">+ <div class="react-grid-layout">+ <div class="react-grid-item"><div class="CardMeta"><span class="title">Signups</span></div></div>+ </div>+ </div>`+ container = document.querySelector('.container')!+ gridItem = document.querySelector('.react-grid-item')!+ handle = document.querySelector('.title')!+ })++ afterEach(() => {+ jest.runOnlyPendingTimers()+ jest.useRealTimers()+ document.body.innerHTML = ''+ })++ const renderMove = (enabled = true): { onCarryingChange: jest.Mock; rerender: (enabled: boolean) => void } => {+ const onCarryingChange = jest.fn()+ const props = (isEnabled: boolean): Parameters<typeof useClickToMoveTile>[0] => ({+ containerRef: { current: container },+ enabled: isEnabled,+ handleSelector: '.CardMeta',+ cancelSelector: 'button',+ onCarryingChange,+ })+ const { result, rerender } = renderHook((isEnabled: boolean) => useClickToMoveTile(props(isEnabled)), {+ initialProps: enabled,+ })+ // react-grid-layout reports a drag start on the first pointer move, not on the press.+ document.addEventListener('mousemove', () => result.current.carryHeldDrag(gridItem), { once: true })+ return { onCarryingChange, rerender }+ }++ const pickUpWithClick = (): void => {+ handle.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 10, clientY: 10 }))+ handle.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }))+ document.body.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 40, clientY: 40 }))+ }++ it('drops a clicked tile on the next click, even though its replayed press starts a drag too', () => {+ const { onCarryingChange } = renderMove()+ pickUpWithClick()+ expect(onCarryingChange).toHaveBeenLastCalledWith(true)++ document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 }))+ document.body.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0 }))+ jest.runOnlyPendingTimers()+ const nextPress = new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 })+ document.body.dispatchEvent(nextPress)++ expect(onCarryingChange).toHaveBeenLastCalledWith(false)+ expect(nextPress.defaultPrevented).toBe(false)+ })++ it('puts a carried tile back and stops swallowing presses when edit mode ends', () => {+ const { onCarryingChange, rerender } = renderMove()+ pickUpWithClick()++ rerender(false)+ const press = new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 })+ document.body.dispatchEvent(press)++ expect(onCarryingChange).toHaveBeenLastCalledWith(false)+ expect(press.defaultPrevented).toBe(false)+ })+})diff --git a/products/dashboards/frontend/useClickToMoveTile.ts b/products/dashboards/frontend/useClickToMoveTile.tsnew file mode 100644index 000000000000..fdd01a0821d5--- /dev/null+++ b/products/dashboards/frontend/useClickToMoveTile.ts@@ -0,0 +1,116 @@+import { useCallback, useEffect, useRef } from 'react'+import type { MutableRefObject, RefObject } from 'react'++import { type TileCarry, type TilePickUp, carryTile, getTilePickUp } from './carryTile'++export type TileMoveInput = 'drag' | 'click' | 'canceled'++interface UseClickToMoveTileProps {+ containerRef: RefObject<HTMLElement>+ enabled: boolean+ handleSelector: string+ cancelSelector: string+ onCarryingChange: (carrying: boolean) => void+}++export interface ClickToMoveTile {+ tileMoveInputRef: MutableRefObject<TileMoveInput>+ carryHeldDrag: (gridItem: HTMLElement | null) => void+}++export function useClickToMoveTile({+ containerRef,+ enabled,+ handleSelector,+ cancelSelector,+ onCarryingChange,+}: UseClickToMoveTileProps): ClickToMoveTile {+ const tileMoveInputRef = useRef<TileMoveInput>('drag')+ const carryRef = useRef<TileCarry | null>(null)+ const pressRef = useRef<{ x: number; y: number } | null>(null)+ const onCarryingChangeRef = useRef(onCarryingChange)+ onCarryingChangeRef.current = onCarryingChange++ const startCarrying = useCallback(+ (pickUp: TilePickUp, clientX: number, clientY: number, input: 'drag' | 'click'): void => {+ // Setting the state re-renders every subscriber, so a held drag only sets it once its button is released.+ let announced = false+ const announce = (): void => {+ announced = true+ onCarryingChangeRef.current(true)+ }+ const finish = (finalInput: TileMoveInput): void => {+ carryRef.current = null+ if (announced) {+ onCarryingChangeRef.current(false)+ }+ tileMoveInputRef.current = finalInput+ // The drag stop handler reads the input once the release reaches react-grid-layout, after this handler.+ window.setTimeout(() => {+ tileMoveInputRef.current = 'drag'+ }, 0)+ }+ tileMoveInputRef.current = input+ if (input === 'click') {+ announce()+ }+ carryRef.current = carryTile({+ ...pickUp,+ clientX,+ clientY,+ held: input === 'drag',+ onHeldRelease: announce,+ onDrop: () => finish(input),+ onCancel: () => finish('canceled'),+ })+ },+ []+ )++ const carryHeldDrag = useCallback(+ (gridItem: HTMLElement | null): void => {+ const press = pressRef.current+ const grid = gridItem?.parentElement+ if (carryRef.current || !press || !gridItem || !grid) {+ return+ }+ startCarrying({ target: gridItem, grid }, press.x, press.y, 'drag')+ },+ [startCarrying]+ )++ useEffect(() => {+ const container = containerRef.current+ if (!enabled || !container) {+ return+ }++ const onMouseDown = (event: MouseEvent): void => {+ pressRef.current = event.button === 0 ? { x: event.clientX, y: event.clientY } : null+ }++ const onClick = (event: MouseEvent): void => {+ if (carryRef.current) {+ return+ }+ const pickUp = getTilePickUp(event, pressRef.current, handleSelector, cancelSelector)+ if (!pickUp) {+ return+ }+ event.preventDefault()+ event.stopPropagation()+ startCarrying(pickUp, event.clientX, event.clientY, 'click')+ }++ container.addEventListener('mousedown', onMouseDown, { capture: true })+ container.addEventListener('click', onClick, { capture: true })+ return () => {+ container.removeEventListener('mousedown', onMouseDown, { capture: true })+ container.removeEventListener('click', onClick, { capture: true })+ carryRef.current?.cancel()+ }+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- containerRef is a stable ref object+ }, [enabled, handleSelector, cancelSelector, startCarrying])++ return { tileMoveInputRef, carryHeldDrag }+}