Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(dashboards): move tiles between tile groups (#117070)

Paul D'Ambrabcc66b169f2f
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
index 1141a7bc4288..74af4ee5ca51 100644
--- a/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
@@ -5,7 +5,7 @@ import { IconChevronRight } from '@posthog/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
-import { LemonMenu, LemonMenuItem, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
+import { LemonMenu, LemonMenuItem, LemonMenuItems, LemonMenuSection } from 'lib/lemon-ui/LemonMenu'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { dashboardsModel } from '~/models/dashboardsModel'
@@ -24,6 +24,7 @@ interface DashboardWidgetPlacementMenuProps {
label?: string
/** When there are no destinations, the trigger stays visible but disabled (avoids hiding the action). */
emptyDisabledReason?: string
+ leadingSections?: LemonMenuSection[]
}
export function DashboardWidgetPlacementMenu({
@@ -31,6 +32,7 @@ export function DashboardWidgetPlacementMenu({
onSelect,
label = 'Move to',
emptyDisabledReason = 'No other dashboards',
+ leadingSections = [],
}: DashboardWidgetPlacementMenuProps): JSX.Element {
const [searchTerm, setSearchTermState] = useState('')
const { dashboardsLoading } = useValues(dashboardsModel)
@@ -70,7 +72,7 @@ export function DashboardWidgetPlacementMenu({
label: SearchInputLabel,
}
- const items: LemonMenuItems = dashboardsLoading
+ const dashboardItems: LemonMenuItems = dashboardsLoading
? [{ custom: true, label: () => <LemonSkeleton.Row className="m-2 h-8" repeat={5} fade /> }]
: filteredDestinations.length > 0
? [
@@ -108,7 +110,10 @@ export function DashboardWidgetPlacementMenu({
},
]
- if (!destinations.length && !dashboardsLoading) {
+ const hasDashboardItems = destinations.length > 0 || dashboardsLoading
+ const items: LemonMenuItems = [...leadingSections, ...(hasDashboardItems ? dashboardItems : [])]
+
+ if (!items.length) {
return (
<LemonButton fullWidth disabledReason={emptyDisabledReason}>
{label}
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus.tsx
index 380b8f571eda..f2542bfc2f74 100644
--- a/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus.tsx
@@ -2,14 +2,42 @@ import {
DashboardWidgetPlacementMenu,
type DashboardWidgetPlacementDestination,
} from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'
+import type { LemonMenuSection } from 'lib/lemon-ui/LemonMenu'
import type { DashboardBasicType, DashboardType } from '~/types'
+import type { TileGroupMoveOptions } from 'products/dashboards/frontend/dashboardTileSections'
+
export interface DashboardWidgetPlacementMenusProps {
/** Same list for Copy and Move (includes disabled rows with reasons, e.g. already on dashboard). */
placementDestinations: DashboardWidgetPlacementDestination[]
onMoveToDashboard?: (target: Pick<DashboardType, 'id' | 'name'>) => void
onCopyToDashboard?: (dashboard: DashboardBasicType) => void
+ tileGroupMoveOptions?: TileGroupMoveOptions
+ onMoveToTileGroup?: (sectionKey: string | null) => void
+}
+
+function tileGroupSection(
+ { targets, canTakeOut }: TileGroupMoveOptions,
+ onMoveToTileGroup: (sectionKey: string | null) => void
+): LemonMenuSection {
+ return {
+ title: 'Tile groups',
+ items: [
+ ...targets.map(({ sectionKey, label }) => ({
+ label,
+ key: sectionKey,
+ onClick: () => onMoveToTileGroup(sectionKey),
+ 'data-attr': 'dashboard-tile-move-to-group',
+ })),
+ canTakeOut && {
+ label: 'Take out of group',
+ key: 'take-out-of-group',
+ onClick: () => onMoveToTileGroup(null),
+ 'data-attr': 'dashboard-tile-take-out-of-group',
+ },
+ ],
+ }
}
/**
@@ -19,6 +47,8 @@ export function DashboardWidgetPlacementMenus({
placementDestinations,
onMoveToDashboard,
onCopyToDashboard,
+ tileGroupMoveOptions,
+ onMoveToTileGroup,
}: DashboardWidgetPlacementMenusProps): JSX.Element {
return (
<>
@@ -28,6 +58,11 @@ export function DashboardWidgetPlacementMenus({
destinations={placementDestinations}
onSelect={(d) => onMoveToDashboard({ id: d.id, name: d.name })}
emptyDisabledReason="No dashboards you can move to"
+ leadingSections={
+ tileGroupMoveOptions && onMoveToTileGroup
+ ? [tileGroupSection(tileGroupMoveOptions, onMoveToTileGroup)]
+ : undefined
+ }
/>
)}
{onCopyToDashboard && (
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 7274be4fae5d..6f493b188f75 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -47,6 +47,7 @@ import {
} from '~/types'
import type { AlertType } from 'products/alerts/frontend/types'
+import type { TileGroupMoveOptions } from 'products/dashboards/frontend/dashboardTileSections'
import { DashboardResizeHandles } from '../handles'
import { EditModeEdge, EditModeEdgeOverlay } from './EditModeEdgeOverlay'
@@ -126,6 +127,8 @@ export interface InsightCardProps extends Resizeable {
duplicate?: () => void
setOverride?: () => void
moveToDashboard?: (target: Pick<DashboardType, 'id' | 'name'>) => void
+ tileGroupMoveOptions?: TileGroupMoveOptions
+ moveToTileGroup?: (sectionKey: string | null) => void
/** Copy this insight tile to another dashboard (same insight; requires editor on destination). */
copyToDashboard?: (dashboard: DashboardBasicType) => void
/** buttons to add to the "more" menu on the card**/
@@ -194,6 +197,8 @@ function InsightCardInternal(
duplicate,
setOverride,
moveToDashboard,
+ tileGroupMoveOptions,
+ moveToTileGroup,
copyToDashboard,
className,
moreButtons,
@@ -461,6 +466,8 @@ function InsightCardInternal(
duplicate={duplicate}
setOverride={setOverride}
moveToDashboard={moveToDashboard}
+ tileGroupMoveOptions={tileGroupMoveOptions}
+ moveToTileGroup={moveToTileGroup}
copyToDashboard={copyToDashboard}
areDetailsShown={areDetailsShown}
setAreDetailsShown={setAreDetailsShown}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index fd611c41ced8..98f9370559f6 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -113,6 +113,8 @@ interface InsightMetaProps extends Pick<
| 'dashboardId'
| 'canEditDashboard'
| 'moveToDashboard'
+ | 'tileGroupMoveOptions'
+ | 'moveToTileGroup'
| 'copyToDashboard'
| 'showEditingControls'
| 'showDetailsControls'
@@ -160,6 +162,8 @@ export function InsightMeta({
duplicate,
setOverride,
moveToDashboard,
+ tileGroupMoveOptions,
+ moveToTileGroup,
copyToDashboard,
areDetailsShown,
setAreDetailsShown,
@@ -682,6 +686,8 @@ export function InsightMeta({
<DashboardWidgetPlacementMenus
placementDestinations={copyToDestinations}
onMoveToDashboard={moveToDashboard}
+ tileGroupMoveOptions={tileGroupMoveOptions}
+ onMoveToTileGroup={moveToTileGroup}
onCopyToDashboard={canShowCopyToDashboardTile ? copyToDashboard : undefined}
/>
{removeFromDashboard && (
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index b208780531eb..4ae390823ab1 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -1,8 +1,9 @@
import '@testing-library/jest-dom'
-import { fireEvent, render } from '@testing-library/react'
+import { fireEvent, render, within } from '@testing-library/react'
import { useActions, useAsyncActions, useValues } from 'kea'
import { router } from 'kea-router'
+import type { PositionStrategy } from 'react-grid-layout/core'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
@@ -25,6 +26,10 @@ jest.mock('scenes/dashboard/dashboardLogic', () => ({
DashboardLoadAction: { Update: 'update' },
}))
+jest.mock('lib/components/Cards/InsightCard/dashboardWidgetMenusLogic', () => ({
+ dashboardWidgetMenusLogic: () => ({ __mock: 'dashboardWidgetMenusLogic' }),
+}))
+
jest.mock('~/models/dashboardsModel', () => ({
dashboardsModel: { __mock: 'dashboardsModel' },
}))
@@ -159,6 +164,7 @@ jest.mock('react-grid-layout', () => {
margin,
resizeConfig,
dragConfig,
+ positionStrategy,
children,
}: {
className: string
@@ -167,6 +173,7 @@ jest.mock('react-grid-layout', () => {
margin: [number, number]
resizeConfig: { enabled: boolean }
dragConfig: { enabled: boolean }
+ positionStrategy?: unknown
children: any
}) => {
jest.requireActual('react').useEffect(() => {
@@ -174,6 +181,11 @@ jest.mock('react-grid-layout', () => {
}, [])
return (
<div
+ ref={(element) => {
+ if (element) {
+ mockPositionStrategies.set(element, positionStrategy)
+ }
+ }}
data-attr="react-grid-layout"
data-style-width={style?.width}
data-class-name={className}
@@ -206,6 +218,8 @@ const mockRemoveTile = jest.fn()
const mockTriggerDashboardRefresh = jest.fn()
const mockInsightCard = jest.fn()
const mockUpdateContainerWidth = jest.fn()
+const mockMoveTileToSection = jest.fn()
+const mockPositionStrategies = new Map<Element, unknown>()
let mockGridWidth = 1200
let mockGridMounts = 0
let canEditDashboard = true
@@ -275,6 +289,7 @@ describe('DashboardItems', () => {
copyToDashboard: jest.fn(),
setTileOverride: jest.fn(),
setDashboardMode: jest.fn(),
+ moveTileToSection: mockMoveTileToSection,
}
}
@@ -662,10 +677,10 @@ describe('DashboardItems', () => {
})
describe('tile group bands', () => {
- const showBands = (streamedTileIds: number[] = []): void => {
+ const showBands = (overrides: Record<string, unknown> = {}, streamedTileIds: number[] = []): void => {
const defaultValues = mockedUseValues.getMockImplementation()!
mockedUseValues.mockImplementation((logic) => {
- const values = defaultValues(logic)
+ const values = { ...defaultValues(logic), ...(logic === dashboardLogic ? overrides : {}) }
const tiles = [
...values.tiles,
...streamedTileIds.map((id) => ({ id, insight: { id: 100 + id, short_id: `tile${id}` } })),
@@ -692,6 +707,8 @@ describe('DashboardItems', () => {
],
tileGroupSectionLayouts: [layouts],
collapsedTileGroupKeys: [],
+ tileGroupMoveOptions: {},
+ ...overrides,
}
: values
})
@@ -726,10 +743,51 @@ describe('DashboardItems', () => {
const { rerender } = render(<DashboardItems />)
mockedUseValues.mockImplementation(defaultValues)
- showBands([2])
+ showBands({}, [2])
rerender(<DashboardItems />)
expect(mockGridMounts).toBe(1)
})
+
+ it('keeps a dragged tile inside the sides of its band grid', () => {
+ showBands()
+
+ const { container } = render(<DashboardItems />)
+ const grid = container.querySelector('[data-attr="react-grid-layout"]')!
+ const strategy = mockPositionStrategies.get(grid) as PositionStrategy
+ const transform = (left: number): React.CSSProperties['transform'] =>
+ strategy.calcStyle({ left, top: 0, width: 300, height: 100 }).transform
+
+ expect(transform(-200)).toBe(transform(0))
+ expect(transform(5000)).toBe(transform(1200 - 300))
+ })
+
+ it('moves a tile to another group from its menu, with no other dashboard to move to', async () => {
+ const buttonTile = { id: 3, button_tile: { id: 30, text: 'Open docs', url: 'https://example.com' } }
+ showBands({
+ tiles: [buttonTile],
+ layouts: { sm: [{ i: '3', x: 0, y: 0, w: 2, h: 1 }] },
+ tileGroupMoveOptions: { 3: { targets: [{ sectionKey: 'group-ops', label: 'Ops' }], canTakeOut: true } },
+ })
+ const bandValues = mockedUseValues.getMockImplementation()!
+ mockedUseValues.mockImplementation((logic) =>
+ logic === dashboardLogic
+ ? bandValues(logic)
+ : logic === dashboardsModel
+ ? { dashboardsLoading: false }
+ : { copyToDestinations: [] }
+ )
+ const defaultActions = mockedUseActions.getMockImplementation()!
+ mockedUseActions.mockImplementation((logic) =>
+ logic === dashboardsModel ? { loadDashboardsIfNeeded: jest.fn() } : defaultActions(logic)
+ )
+
+ const { container, findByText } = render(<DashboardItems />)
+ fireEvent.click(within(container).getByTestId('more-button'))
+ fireEvent.click(await findByText('Move to'))
+ fireEvent.click(await findByText('Ops'))
+
+ expect(mockMoveTileToSection).toHaveBeenCalledWith(3, 'group-ops', null, 'menu')
+ })
})
})
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index dc563dc9a6ad..d62ac182fcb7 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -6,6 +6,7 @@ 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 { type PositionStrategy, setTransform } from 'react-grid-layout/core'
import { DashboardWidgetItem } from '@posthog/products-dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem'
import { getDashboardWidgetFetchDisplayError } from '@posthog/products-dashboards/frontend/widgets/constants'
@@ -14,7 +15,6 @@ import { ApiError } from 'lib/api'
import { EditModeEdge, useResizeHandleScrollbarPassThrough } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
import { TileDecorations } from 'lib/components/TileDecorations/TileDecorations'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
-import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
@@ -41,11 +41,13 @@ import { DashboardLayoutSize, DashboardPlacement, DashboardTile, DashboardType }
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 { DashboardTileGroup } from 'products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup'
+import { DashboardTileSectionBand } from 'products/dashboards/frontend/components/DashboardTileSectionBand'
+import { TileGroupTakeOutDropZone } from 'products/dashboards/frontend/components/TileGroupTakeOutDropZone'
import { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'
import { getGroupTitlesByTileId, hasTileDecorations } from 'products/dashboards/frontend/dashboardTileGroups'
import type { DashboardSection } from 'products/dashboards/frontend/dashboardTileSections'
import { useDashboardContainerWidth } from 'products/dashboards/frontend/useDashboardContainerWidth'
+import { TAKE_OUT_DROP_ZONE_KEY, useTileGroupDrag } from 'products/dashboards/frontend/useTileGroupDrag'
import { DashboardButtonTileItem } from './items/DashboardButtonTileItem'
import { DashboardErrorTileItem } from './items/DashboardErrorTileItem'
@@ -83,6 +85,16 @@ const MemoizedDashboardButtonTileItem = memo(
const MemoizedDashboardErrorTileItem = memo(DashboardErrorTileItem, gridTilePropsEqual) as typeof DashboardErrorTileItem
const MemoizedDashboardWidgetItem = memo(DashboardWidgetItem, gridTilePropsEqual) as typeof DashboardWidgetItem
+/** Lets a dragged tile leave its band up or down, but not past the sides of its grid. */
+function sidewaysBoundedStrategy(gridWidth: number): PositionStrategy {
+ return {
+ type: 'transform',
+ scale: 1,
+ calcStyle: (position) =>
+ setTransform({ ...position, left: Math.min(Math.max(position.left, 0), gridWidth - position.width) }),
+ }
+}
+
export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsProps = {}): JSX.Element {
const {
dashboard,
@@ -110,6 +122,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
tileGroupSections,
tileGroupSectionLayouts,
collapsedTileGroupKeys,
+ tileGroupMoveOptions,
} = useValues(dashboardLogic)
const { layoutZoom = 1 } = useValues(dashboardLogic)
const {
@@ -127,6 +140,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
setDashboardEditing,
toggleTileGroup,
updateTileGroupSectionLayout,
+ moveTileToSection,
} = useActions(dashboardLogic)
const { updateWidgetTile } = useAsyncActions(dashboardLogic)
const { reportDashboardTileRepositioned } = useActions(eventUsageLogic)
@@ -296,10 +310,28 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
enabled: canEditDashboard && layoutEditMode && !isMobileView,
handle: '.CardMeta,.DashboardTileCard__body,.WidgetCard__header,.drag-handle',
cancel: 'a,table,button,input,.Popover',
- bounded: true,
+ bounded: !showBands,
}),
- [canEditDashboard, layoutEditMode, isMobileView]
+ [canEditDashboard, layoutEditMode, isMobileView, showBands]
)
+ const {
+ draggingTileId,
+ dropTargetKey,
+ frozenSourceGrid,
+ showTakeOutDropZone,
+ startTileDrag,
+ trackTileDrag,
+ finishTileDrag,
+ } = useTileGroupDrag({
+ enabled: dragConfig.enabled && showBands,
+ sections: tileGroupSections,
+ rowHeight,
+ margin,
+ layout: layouts.sm,
+ moveTileToSection: (tileId, sectionKey, cell) => moveTileToSection(tileId, sectionKey, cell, 'drag'),
+ restoreLayout: (layout) => stageLayouts({ sm: layout }),
+ })
+ const boundedStrategy = useMemo(() => sidewaysBoundedStrategy(gridWidth), [gridWidth])
const resizeConfig = useMemo(
() => ({
@@ -401,6 +433,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
await updateWidgetTile({ tile, ...patch })
},
toggleDescription: (): void => toggleTileDescription(tile.id),
+ moveToTileGroup: (sectionKey: string | null): void =>
+ moveTileToSection(tile.id, sectionKey, null, 'menu'),
},
])
),
@@ -416,6 +450,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
refreshDashboardWidgets,
updateWidgetTile,
toggleTileDescription,
+ moveTileToSection,
]
)
@@ -470,40 +505,67 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
}, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom, flushPendingLayouts])
const handleDragStart = useCallback(
- (layout: Layout, _oldItem: LayoutItem | null, newItem: LayoutItem | null) => {
+ (
+ layout: Layout,
+ _oldItem: LayoutItem | null,
+ newItem: LayoutItem | null,
+ _placeholder: LayoutItem | null,
+ _event: Event,
+ element: HTMLElement | null
+ ) => {
if (!newItem) {
return
}
startInteraction(layout, newItem, 'drag')
+ startTileDrag(newItem, element)
startAutoScroll()
},
- [startInteraction, startAutoScroll]
+ [startInteraction, startTileDrag, startAutoScroll]
)
const handleDrag = useCallback(
(_layout: unknown, _oldItem: unknown, _newItem: unknown, _placeholder: unknown, e: Event) => {
isDragging.current = true
+ trackTileDrag(e as Event)
if (dragEndTimeout.current) {
window.clearTimeout(dragEndTimeout.current)
}
autoScrollOnDrag(e)
},
- [autoScrollOnDrag]
+ [autoScrollOnDrag, trackTileDrag]
)
- const handleDragStop = useCallback(() => {
- stopAutoScroll()
- if (dragEndTimeout.current) {
- window.clearTimeout(dragEndTimeout.current)
- }
- dragEndTimeout.current = window.setTimeout(() => {
- isDragging.current = false
- }, 250)
- flushPendingLayouts()
- if (dashboard?.id) {
- reportDashboardTileRepositioned(dashboard.id, 'moved', effectiveZoom)
- }
- }, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom, flushPendingLayouts, stopAutoScroll])
+ const handleDragStop = useCallback(
+ (
+ _layout: Layout,
+ _oldItem: LayoutItem | null,
+ newItem: LayoutItem | null,
+ _placeholder: LayoutItem | null,
+ event: Event,
+ element: HTMLElement | null
+ ) => {
+ stopAutoScroll()
+ if (dragEndTimeout.current) {
+ window.clearTimeout(dragEndTimeout.current)
+ }
+ dragEndTimeout.current = window.setTimeout(() => {
+ isDragging.current = false
+ }, 250)
+ flushPendingLayouts()
+ finishTileDrag(newItem, element, event)
+ if (dashboard?.id) {
+ reportDashboardTileRepositioned(dashboard.id, 'moved', effectiveZoom)
+ }
+ },
+ [
+ dashboard?.id,
+ reportDashboardTileRepositioned,
+ effectiveZoom,
+ flushPendingLayouts,
+ finishTileDrag,
+ stopAutoScroll,
+ ]
+ )
const renderTile = (tile: DashboardTile): JSX.Element | undefined => {
const { insight, text, button_tile, widget } = tile
@@ -525,6 +587,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
moveToDashboard: tileActions.moveToDashboard,
copyToDashboard: tileActions.copyToDashboard,
removeFromDashboard: tileActions.removeFromDashboard,
+ tileGroupMoveOptions: showBands ? tileGroupMoveOptions[tile.id] : undefined,
+ moveToTileGroup: tileActions.moveToTileGroup,
}
if (tile.error && !insight) {
@@ -599,6 +663,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
dashboardId={dashboard?.id}
onEdit={tileActions.edit}
onMoveToDashboard={commonTileProps.moveToDashboard}
+ tileGroupMoveOptions={commonTileProps.tileGroupMoveOptions}
+ onMoveToTileGroup={commonTileProps.moveToTileGroup}
onCopyToDashboard={commonTileProps.copyToDashboard}
onDuplicate={tileActions.duplicate}
onRemove={commonTileProps.removeFromDashboard}
@@ -623,6 +689,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
isDraggingRef={isDragging}
onEdit={tileActions.edit}
onMoveToDashboard={commonTileProps.moveToDashboard}
+ tileGroupMoveOptions={commonTileProps.tileGroupMoveOptions}
+ onMoveToTileGroup={commonTileProps.moveToTileGroup}
onDuplicate={tileActions.duplicate}
onRemove={commonTileProps.removeFromDashboard}
showResizeHandles={commonTileProps.showResizeHandles}
@@ -661,6 +729,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
onDuplicate={tileActions.duplicate}
onRemove={commonTileProps.removeFromDashboard}
onMoveToDashboard={commonTileProps.moveToDashboard}
+ tileGroupMoveOptions={commonTileProps.tileGroupMoveOptions}
+ onMoveToTileGroup={commonTileProps.moveToTileGroup}
onCopyToDashboard={commonTileProps.copyToDashboard}
showResizeHandles={commonTileProps.showResizeHandles}
showEditingControls={commonTileProps.showEditingControls}
@@ -693,10 +763,17 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
const renderSection = (section: DashboardSection, index: number): JSX.Element => {
const sectionLayouts = tileGroupSectionLayouts[index]
+ const isLastSection = 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)) + 1
const grid = (
- <div className="relative">
+ <div
+ className="relative"
+ data-dashboard-section-grid={section.key}
+ style={frozenSourceGrid?.key === section.key ? { height: frozenSourceGrid.height } : undefined}
+ >
{layoutEditMode && !isMobileView && (
<DashboardGridBackground
width={gridWidth}
@@ -712,9 +789,11 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
// into a band without a remount that resets every chart already in it.
key={section.key}
width={gridWidth}
+ positionStrategy={boundedStrategy}
className={clsx(
layoutEditMode ? 'dashboard-edit-mode box-content' : 'dashboard-view-mode',
- layoutEditMode && (index === tileGroupSections.length - 1 ? 'pb-[40vh]' : 'pb-24')
+ layoutEditMode && (isLastSection ? 'pb-[40vh]' : 'pb-24'),
+ isDraggingOutOfSection && '[&_.react-grid-placeholder]:hidden'
)}
breakpoint={bandBreakpoint}
layouts={sectionLayouts}
@@ -724,25 +803,17 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
</div>
)
- if (section.kind === 'tiles') {
- return (
- <div key={section.key}>
- {/* Without a line, viewers read loose tiles under a closed group as part of that group. */}
- {index > 0 && <LemonDivider className="mb-4" />}
- {grid}
- </div>
- )
- }
return (
- <DashboardTileGroup
+ <DashboardTileSectionBand
key={section.key}
- group={section.group}
- tileCount={section.tiles.length}
- collapsed={collapsedTileGroupKeys.includes(section.groupKey)}
- onToggle={() => toggleTileGroup(section.groupKey)}
+ section={section}
+ isFirst={index === 0}
+ isDropTarget={dropTargetKey === section.key}
+ collapsedTileGroupKeys={collapsedTileGroupKeys}
+ onToggleTileGroup={toggleTileGroup}
>
{grid}
- </DashboardTileGroup>
+ </DashboardTileSectionBand>
)
}
@@ -757,6 +828,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
{gridWidth > 0 && showBands && (
<div className={clsx('flex flex-col gap-4', showDecorationSpace && 'mt-10', !layoutEditMode && 'mb-8')}>
{tileGroupSections.map(renderSection)}
+ {showTakeOutDropZone && (
+ <TileGroupTakeOutDropZone isDropTarget={dropTargetKey === TAKE_OUT_DROP_ZONE_KEY} />
+ )}
</div>
)}
{gridWidth > 0 && !showBands && (
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index 890223acb284..e2ca9c1c22ea 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -1,6 +1,7 @@
// let tiles assert an insight is present in tests i.e. `tile!.insight` when it must be present for tests to pass
import { MOCK_TEAM_ID } from 'lib/api.mock'
+import { waitFor } from '@testing-library/react'
import { router } from 'kea-router'
import { expectLogic, truth } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -17,6 +18,7 @@ import { dayjs, now } from 'lib/dayjs'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { pluralize } from 'lib/utils/strings'
import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDashboardModalLogic'
import { parseDashboardId } from 'scenes/dashboard/Dashboard'
import { dashboardInsightColorsModalLogic } from 'scenes/dashboard/dashboardInsightColorsModalLogic'
@@ -491,6 +493,314 @@ describe('dashboardLogic', () => {
expect(logic.values.hasUnsavedLayoutChanges).toBe(false)
})
+ describe('moving a tile between tile groups', () => {
+ interface PendingSave {
+ tileIds: number[]
+ resolve: () => void
+ reject: () => void
+ }
+ let pendingSaves: PendingSave[]
+ let tileIds: number[]
+
+ const groupOf = (tileId: number): string | null =>
+ logic.values.tiles.find((tile) => tile.id === tileId)?.group_key ?? null
+ const enterEditMode = (): void =>
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+
+ beforeEach(async () => {
+ const groupKeys = ['plans', 'ops', null]
+ dashboards[5] = {
+ ...dashboards[5],
+ customization: { groups: { plans: { title: 'Pricing plans' }, ops: { collapsed: true } } },
+ tiles: dashboards[5].tiles.map((tile, index) => ({
+ ...tile,
+ group_key: groupKeys[index],
+ layouts: { sm: { x: 0, y: index * 2, w: 12, h: 2 } } as DashboardTile['layouts'],
+ })),
+ }
+ tileIds = dashboards[5].tiles.map((tile) => tile.id)
+ pendingSaves = []
+ // Like the server, a save answers with the saved dashboard, which lacks moves still on their way.
+ jest.spyOn(api, 'update').mockImplementation((_url, data) => {
+ const payload = data as { tiles: Partial<DashboardTile>[] }
+ return new Promise((resolve, reject) =>
+ pendingSaves.push({
+ tileIds: payload.tiles.filter((entry) => 'group_key' in entry).map((entry) => entry.id!),
+ resolve: () =>
+ resolve({
+ ...dashboards[5],
+ tiles: dashboards[5].tiles.map((tile) => ({
+ ...tile,
+ ...payload.tiles.find((entry) => entry.id === tile.id),
+ })),
+ }),
+ reject: () => reject(new Error('network down')),
+ })
+ )
+ })
+ await mountDashboard()
+ })
+
+ afterEach(() => {
+ ;(api.update as jest.Mock).mockRestore()
+ })
+
+ const settleSaves = async (): Promise<void> => {
+ pendingSaves.forEach((save) => save.resolve())
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ it.each([
+ {
+ name: 'into a titled group',
+ tileIndex: 2,
+ sectionKey: 'group-plans',
+ groupKey: 'plans',
+ toast: 'Moved to the "Pricing plans" group',
+ },
+ // An untitled group is named by its tile count, which the move changes.
+ {
+ name: 'into a closed untitled group',
+ tileIndex: 0,
+ sectionKey: 'group-ops',
+ groupKey: 'ops',
+ toast: `Moved to the "${pluralize(2, 'tile')}" group`,
+ },
+ {
+ name: 'out of its group',
+ tileIndex: 0,
+ sectionKey: null,
+ groupKey: null,
+ toast: 'Tile taken out of its group',
+ },
+ ])('in view mode saves a tile moved $name at once', async ({ tileIndex, sectionKey, groupKey, toast }) => {
+ const tileId = tileIds[tileIndex]
+ const successToast = jest.spyOn(lemonToast, 'success')
+ const capture = jest.spyOn(posthog, 'capture')
+
+ logic.actions.moveTileToSection(tileId, sectionKey, null, 'menu')
+ await waitFor(() => expect(pendingSaves).toHaveLength(1))
+ await settleSaves()
+
+ expect(pendingSaves.map((save) => save.tileIds)).toEqual([[tileId]])
+ expect(groupOf(tileId)).toBe(groupKey)
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(false)
+ expect(logic.values.collapsedTileGroupKeys).toEqual(['ops'])
+ expect(successToast).toHaveBeenCalledWith(toast)
+ expect(capture).toHaveBeenCalledWith(
+ 'dashboard tile moved between groups',
+ expect.objectContaining({ method: 'menu', to_group: groupKey !== null })
+ )
+ })
+
+ it.each([
+ {
+ name: 'two quick moves both save',
+ firstSaves: true,
+ secondMove: { tile: 'other', target: 'group-ops', inEditMode: false },
+ expected: { first: 'ops', firstAtSavedCell: true, second: 'ops', unsaved: false, captures: 2 },
+ },
+ {
+ name: 'a failed first move puts back only its own tile',
+ firstSaves: false,
+ secondMove: { tile: 'other', target: 'group-ops', inEditMode: false },
+ expected: { first: 'plans', firstAtSavedCell: true, second: 'ops', unsaved: false, captures: 1 },
+ },
+ {
+ name: 'a failed move keeps an edit-mode move of another tile',
+ firstSaves: false,
+ secondMove: { tile: 'other', target: 'group-ops', inEditMode: true },
+ expected: { first: 'plans', firstAtSavedCell: true, second: 'ops', unsaved: true, captures: 1 },
+ },
+ {
+ name: 'a failed move keeps a later edit-mode move of the same tile',
+ firstSaves: false,
+ secondMove: { tile: 'same', target: null, inEditMode: true },
+ expected: { first: null, firstAtSavedCell: false, second: null, unsaved: true, captures: 1 },
+ },
+ ])('in view mode, $name', async ({ firstSaves, secondMove, expected }) => {
+ const first = tileIds[0]
+ const second = secondMove.tile === 'same' ? first : tileIds[2]
+ const capture = jest.spyOn(posthog, 'capture')
+
+ logic.actions.moveTileToSection(first, 'group-ops', null, 'menu')
+ await waitFor(() => expect(pendingSaves).toHaveLength(1))
+ if (secondMove.inEditMode) {
+ enterEditMode()
+ }
+ logic.actions.moveTileToSection(second, secondMove.target, null, 'menu')
+ if (firstSaves) {
+ pendingSaves[0].resolve()
+ } else {
+ pendingSaves[0].reject()
+ }
+ if (!secondMove.inEditMode) {
+ await waitFor(() => expect(pendingSaves).toHaveLength(2))
+ }
+ await settleSaves()
+
+ const firstCell = logic.values.layouts.sm?.find((item) => item.i === String(first))
+ const savedFirstCell = logic.values.savedTilePlacements[first]?.layouts?.sm
+ expect(pendingSaves.map((save) => save.tileIds)).toEqual(
+ secondMove.inEditMode ? [[first]] : [[first], [second]]
+ )
+ expect({
+ first: groupOf(first),
+ firstAtSavedCell: firstCell?.y === savedFirstCell?.y,
+ second: groupOf(second),
+ unsaved: logic.values.hasUnsavedLayoutChanges,
+ captures: capture.mock.calls.filter(([event]) => event === 'dashboard tile moved between groups')
+ .length,
+ }).toEqual(expected)
+ })
+
+ it('keeps a view-mode move made while a layout save is on its way', async () => {
+ const [plansTile, , looseTile] = tileIds
+ enterEditMode()
+ logic.actions.moveTileToSection(looseTile, 'group-plans', { x: 0, y: 0 }, 'drag')
+ logic.actions.saveLayoutChanges()
+ await waitFor(() => expect(pendingSaves).toHaveLength(1))
+
+ logic.actions.moveTileToSection(plansTile, 'group-ops', null, 'menu')
+ pendingSaves[0].resolve()
+ await waitFor(() => expect(pendingSaves).toHaveLength(2))
+ await settleSaves()
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(false)
+
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ expect({ moved: groupOf(plansTile), saved: groupOf(looseTile) }).toEqual({
+ moved: 'ops',
+ saved: 'plans',
+ })
+ })
+
+ it.each([
+ { name: 'shows the move', afterDiscard: 'nothing', expectedGroup: 'ops', groupSaves: 1 },
+ {
+ name: 'shows the move in a new edit session',
+ afterDiscard: 'edit',
+ expectedGroup: 'ops',
+ groupSaves: 1,
+ },
+ {
+ name: 'keeps a newer saved drag of the tile',
+ afterDiscard: 'drag and save',
+ expectedGroup: 'plans',
+ groupSaves: 2,
+ },
+ ])(
+ 'when a view-mode move saves after a discard put the tile back, $name',
+ async ({ afterDiscard, expectedGroup, groupSaves }) => {
+ const plansTile = tileIds[0]
+ logic.actions.moveTileToSection(plansTile, 'group-ops', null, 'menu')
+ await waitFor(() => expect(pendingSaves).toHaveLength(1))
+ enterEditMode()
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ expect(groupOf(plansTile)).toBe('plans')
+
+ if (afterDiscard !== 'nothing') {
+ enterEditMode()
+ }
+ if (afterDiscard === 'drag and save') {
+ logic.actions.stageLayouts({
+ sm: (logic.values.layouts.sm ?? []).map((item) =>
+ item.i === String(plansTile) ? { ...item, y: 1 } : item
+ ),
+ })
+ logic.actions.saveLayoutChanges()
+ pendingSaves[0].resolve()
+ await waitFor(() => expect(pendingSaves).toHaveLength(2))
+ }
+ await settleSaves()
+
+ expect({
+ group: groupOf(plansTile),
+ unsaved: logic.values.hasUnsavedLayoutChanges,
+ groupSaves: pendingSaves.filter((save) => save.tileIds.includes(plansTile)).length,
+ }).toEqual({ group: expectedGroup, unsaved: false, groupSaves })
+ }
+ )
+
+ it('runs a layout save queued behind a newer one without an error', async () => {
+ const [, opsTile, looseTile] = tileIds
+ const errorToast = jest.spyOn(lemonToast, 'error')
+ logic.actions.moveTileToSection(opsTile, null, null, 'menu')
+ await waitFor(() => expect(pendingSaves).toHaveLength(1))
+ enterEditMode()
+ logic.actions.moveTileToSection(looseTile, 'group-plans', { x: 0, y: 0 }, 'drag')
+
+ logic.actions.saveEditModeChanges('layout')
+ logic.actions.saveEditModeChanges('layout')
+ pendingSaves[0].resolve()
+ await waitFor(() => expect(pendingSaves).toHaveLength(2))
+ await settleSaves()
+
+ expect(errorToast).not.toHaveBeenCalled()
+ expect(pendingSaves.map((save) => save.tileIds)).toEqual([[opsTile], [looseTile]])
+ expect(groupOf(looseTile)).toBe('plans')
+ })
+
+ it('sends a queued layout save after the dashboard closes', async () => {
+ const [, opsTile, looseTile] = tileIds
+ logic.actions.moveTileToSection(opsTile, null, null, 'menu')
+ await waitFor(() => expect(pendingSaves).toHaveLength(1))
+ enterEditMode()
+ logic.actions.moveTileToSection(looseTile, 'group-plans', { x: 0, y: 0 }, 'drag')
+
+ logic.actions.saveEditModeChanges('layout')
+ logic.unmount()
+ pendingSaves[0].resolve()
+
+ await waitFor(() => expect(pendingSaves).toHaveLength(2))
+ expect(pendingSaves.map((save) => save.tileIds)).toEqual([[opsTile], [looseTile]])
+ pendingSaves[1].resolve()
+ await waitFor(() => expect(logic.isMounted()).toBe(false))
+ })
+
+ it.each([
+ { finish: 'save', saveFails: false, expectedGroup: 'plans', unsaved: false },
+ { finish: 'save', saveFails: true, expectedGroup: 'plans', unsaved: true },
+ { finish: 'cancel', saveFails: false, expectedGroup: null, unsaved: false },
+ ])(
+ 'in edit mode keeps a dragged tile unsaved until $finish (save fails: $saveFails)',
+ async ({ finish, saveFails, expectedGroup, unsaved }) => {
+ const looseTile = tileIds[2]
+ const capture = jest.spyOn(posthog, 'capture')
+ enterEditMode()
+
+ logic.actions.moveTileToSection(looseTile, 'group-plans', { x: 0, y: 0 }, 'drag')
+
+ expect(pendingSaves).toHaveLength(0)
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
+ expect(logic.values.tileGroupSectionLayouts[0].sm).toContainEqual(
+ expect.objectContaining({ i: String(looseTile), y: 0 })
+ )
+ expect(capture).toHaveBeenCalledWith(
+ 'dashboard tile moved between groups',
+ expect.objectContaining({ method: 'drag', from_group: false, to_group: true })
+ )
+
+ if (finish === 'save') {
+ logic.actions.saveLayoutChanges()
+ await waitFor(() => expect(pendingSaves).toHaveLength(1))
+ if (saveFails) {
+ pendingSaves[0].reject()
+ }
+ } else {
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ }
+ await settleSaves()
+
+ expect(pendingSaves.map((save) => save.tileIds)).toEqual(finish === 'save' ? [[looseTile]] : [])
+ expect(groupOf(looseTile)).toBe(expectedGroup)
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(unsaved)
+ }
+ )
+ })
+
it('keeps the changes of two bands that report in the same tick', async () => {
groupTiles({})
await mountDashboard()
@@ -1483,7 +1793,7 @@ describe('dashboardLogic', () => {
const payload = (api.update as jest.Mock).mock.calls.at(-1)[1]
expect(payload).not.toHaveProperty('tiles')
expect(logic.values.dashboard!.tiles[0].layouts?.sm?.x).toBe(modifiedLayouts.sm[0].x)
- expect(logic.values.dashboardLayouts[firstTile.id]).toEqual(firstTile.layouts)
+ expect(logic.values.savedTilePlacements[firstTile.id]?.layouts).toEqual(firstTile.layouts)
expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
})
@@ -1779,6 +2089,46 @@ describe('dashboardLogic', () => {
expect(successToast).toHaveBeenCalledWith('Dashboard saved')
})
+ it.each([
+ {
+ name: 'a failed layout save',
+ act: async (): Promise<void> => {
+ const firstTile = logic.values.dashboard!.tiles[0]
+ logic.actions.stageLayouts({
+ sm: logic.values.layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: layout.x + 1 } : layout
+ ),
+ })
+ jest.spyOn(api, 'update').mockRejectedValueOnce(new Error('network down'))
+ logic.actions.saveLayoutChanges()
+ },
+ unsaved: true,
+ },
+ {
+ name: 'a duplicated tile',
+ act: async (): Promise<void> => {
+ const sourceTile = logic.values.dashboard!.tiles[0]
+ jest.spyOn(api, 'update').mockResolvedValueOnce({
+ ...logic.values.dashboard!,
+ tiles: [
+ ...logic.values.dashboard!.tiles,
+ { ...sourceTile, id: 999, layouts: { sm: { x: 0, y: 99, w: 6, h: 5 } } },
+ ],
+ })
+ logic.actions.duplicateTile(sourceTile)
+ },
+ unsaved: false,
+ },
+ ])('counts $name as saved only when the server has it', async ({ act, unsaved }) => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, act)
+ .toFinishAllListeners()
+ .toNotHaveDispatchedActions([dashboardsModel.actionTypes.updateDashboardSuccess])
+
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(unsaved)
+ })
+
it('does not show a success toast when exiting edit mode with no changes', async () => {
await expectLogic(logic).toFinishAllListeners()
@@ -1798,7 +2148,7 @@ describe('dashboardLogic', () => {
expect(initialDashboard).not.toBeNull()
const firstTile = initialDashboard!.tiles[0]
- const originalLayouts = logic.values.dashboardLayouts[firstTile.id]
+ const originalLayouts = logic.values.savedTilePlacements[firstTile.id]?.layouts
expect(originalLayouts).not.toBeUndefined()
@@ -2548,7 +2898,7 @@ describe('dashboardLogic', () => {
await expectLogic(logic).toFinishAllListeners()
moveFirstTile()
const draftTile = logic.values.dashboard!.tiles[0]
- const savedLayouts = logic.values.dashboardLayouts[draftTile.id]
+ const savedLayouts = logic.values.savedTilePlacements[draftTile.id]?.layouts
const addedTile = { ...WIDGET_TILE, id: 999 }
const updatedDashboard = {
...logic.values.dashboard!,
@@ -2558,8 +2908,8 @@ describe('dashboardLogic', () => {
dashboardsModel.actions.updateDashboardSuccess(updatedDashboard)
expect(logic.values.dashboard!.tiles[0].layouts).toEqual(draftTile.layouts)
- expect(logic.values.dashboardLayouts[draftTile.id]).toEqual(savedLayouts)
- expect(logic.values.dashboardLayouts[addedTile.id]).toEqual(addedTile.layouts)
+ expect(logic.values.savedTilePlacements[draftTile.id]?.layouts).toEqual(savedLayouts)
+ expect(logic.values.savedTilePlacements[addedTile.id]?.layouts).toEqual(addedTile.layouts)
expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
})
@@ -2584,7 +2934,7 @@ describe('dashboardLogic', () => {
.toFinishAllListeners()
expect(logic.values.dashboard!.tiles[1].layouts).toEqual(serverLayouts)
- expect(logic.values.dashboardLayouts[firstTile.id]).toEqual(serverLayouts)
+ expect(logic.values.savedTilePlacements[firstTile.id]?.layouts).toEqual(serverLayouts)
expect(logic.values.hasUnsavedLayoutChanges).toBe(false)
})
@@ -2616,10 +2966,30 @@ describe('dashboardLogic', () => {
expect(logic.values.dashboard!.tiles[0].layouts).toEqual(draftTile.layouts)
expect(logic.values.dashboard!.tiles[1].layouts).toEqual(serverLayouts)
- expect(logic.values.dashboardLayouts[unchangedTile.id]).toEqual(serverLayouts)
+ expect(logic.values.savedTilePlacements[unchangedTile.id]?.layouts).toEqual(serverLayouts)
expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
})
+ it.each([{ layoutsPersisted: false }, { layoutsPersisted: true }])(
+ 'keeps an unsaved group move when an update echoes the saved group (layouts persisted: $layoutsPersisted)',
+ async ({ layoutsPersisted }) => {
+ await expectLogic(logic).toFinishAllListeners()
+ const draftTile = logic.values.dashboard!.tiles[0]
+ logic.actions.setTileProperty(draftTile.id, { group_key: 'plans' })
+ const echo = {
+ ...logic.values.dashboard!,
+ tiles: logic.values.dashboard!.tiles.map((tile) =>
+ tile.id === draftTile.id ? { ...tile, group_key: null } : tile
+ ),
+ }
+
+ dashboardsModel.actions.updateDashboardSuccess(echo, { layoutsPersisted })
+
+ expect(logic.values.dashboard!.tiles[0].group_key).toBe('plans')
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
+ }
+ )
+
it('uses the returned saved layout as the snapshot when the same tile has a draft', async () => {
await expectLogic(logic).toFinishAllListeners()
moveFirstTile()
@@ -2641,7 +3011,7 @@ describe('dashboardLogic', () => {
.toFinishAllListeners()
expect(logic.values.dashboard!.tiles[0].layouts).toEqual(draftTile.layouts)
- expect(logic.values.dashboardLayouts[draftTile.id]).toEqual(savedLayouts)
+ expect(logic.values.savedTilePlacements[draftTile.id]?.layouts).toEqual(savedLayouts)
expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
})
@@ -2657,7 +3027,7 @@ describe('dashboardLogic', () => {
.toDispatchActions(['applyDashboardUpdate'])
.toFinishAllListeners()
- expect(logic.values.dashboardLayouts[draftTile.id]).toEqual(draftTile.layouts)
+ expect(logic.values.savedTilePlacements[draftTile.id]?.layouts).toEqual(draftTile.layouts)
expect(logic.values.hasUnsavedLayoutChanges).toBe(false)
})
@@ -5353,7 +5723,7 @@ describe('dashboardLogic', () => {
await expectLogic(logic).toFinishAllListeners()
const firstTile = logic.values.dashboard!.tiles[0]
- const savedLayouts = logic.values.dashboardLayouts[firstTile.id]
+ const savedLayouts = logic.values.savedTilePlacements[firstTile.id]?.layouts
logic.actions.updateLayouts({
...logic.values.layouts,
sm: logic.values.layouts.sm?.map((layout) =>
@@ -5371,8 +5741,8 @@ describe('dashboardLogic', () => {
}).toFinishAllListeners()
expect(logic.values.dashboard!.tiles[0].layouts).toEqual(draftLayouts)
- expect(logic.values.dashboardLayouts[firstTile.id]).toEqual(savedLayouts)
- expect(logic.values.dashboardLayouts[addedTile.id]).toEqual(addedTile.layouts)
+ expect(logic.values.savedTilePlacements[firstTile.id]?.layouts).toEqual(savedLayouts)
+ expect(logic.values.savedTilePlacements[addedTile.id]?.layouts).toEqual(addedTile.layouts)
expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
})
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 77b63b8f4ce0..c05c219d9bc0 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -136,10 +136,14 @@ import {
import {
type DashboardSection,
type SectionLayouts,
+ type TileGroupMoveOptions,
getCollapsedTileGroupKeys,
getDashboardSections,
getLayoutAfterSectionChange,
+ getLayoutAfterTileMove,
getSectionLayouts,
+ getTileGroupLabel,
+ getTileGroupMoveOptions,
} from 'products/dashboards/frontend/dashboardTileSections'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
@@ -305,20 +309,119 @@ function parseDashboardTileId(tileId: string | undefined): DashboardTileIdOrNew
return Number.isNaN(parsedTileId) ? null : parsedTileId
}
-const tileLayoutsFromDashboard = (
- dashboard: DashboardType | null | undefined
-): Record<number, DashboardTile['layouts']> => {
- const tileIdToLayouts: Record<number, DashboardTile['layouts']> = {}
- dashboard?.tiles.forEach((tile: DashboardTile) => {
- tileIdToLayouts[tile.id] = tile.layouts
+// pinned: `method` property values of the "dashboard tile moved between groups" event
+export type TileGroupMoveMethod = 'menu' | 'drag'
+
+/** Where a tile sits. Its layout and its group save together, so one never goes back without the other. */
+export interface TilePlacement {
+ layouts: DashboardTile['layouts']
+ group_key: string | null
+}
+
+const NO_SAVED_PLACEMENT: TilePlacement = { layouts: undefined, group_key: null }
+
+const savedTilePlacement = (placements: Record<number, TilePlacement>, tileId: number): TilePlacement =>
+ placements[tileId] ?? NO_SAVED_PLACEMENT
+
+const tilePlacement = (tile: DashboardTile): TilePlacement => ({
+ layouts: tile.layouts,
+ group_key: tile.group_key ?? null,
+})
+
+type GridCell = Pick<Layout[number], 'x' | 'y' | 'w' | 'h'>
+
+const sameGridCell = (a: GridCell, b: GridCell): boolean => a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h
+
+const withStagedCellReverted = (
+ layout: Layout,
+ tileId: number,
+ moved: GridCell,
+ saved: GridCell | undefined
+): Layout => {
+ const staged = layout.find((item) => item.i === String(tileId))
+ if (!staged || !sameGridCell(staged, moved)) {
+ return layout
+ }
+ return saved
+ ? layout.map((item) => (item === staged ? { ...item, x: saved.x, y: saved.y, w: saved.w, h: saved.h } : item))
+ : layout.filter((item) => item !== staged)
+}
+
+const tilePlacementsFromDashboard = (dashboard: DashboardType | null | undefined): Record<number, TilePlacement> =>
+ Object.fromEntries((dashboard?.tiles ?? []).map((tile) => [tile.id, tilePlacement(tile)]))
+
+const tileGroupChanged = (tile: DashboardTile, saved: TilePlacement | undefined): boolean =>
+ (tile.group_key ?? null) !== (saved?.group_key ?? null)
+
+const withTilePlacement = (tile: DashboardTile, placement: TilePlacement | undefined): DashboardTile => ({
+ ...tile,
+ layouts: placement?.layouts,
+ group_key: placement?.group_key ?? null,
+})
+
+const withSavedTilePlacements = (
+ dashboard: DashboardType,
+ savedPlacements: Record<number, TilePlacement>
+): DashboardType => ({
+ ...dashboard,
+ tiles: dashboard.tiles.map((tile) => withTilePlacement(tile, savedPlacements[tile.id])),
+})
+
+/**
+ * Runs layout saves one after another. The server then applies them in the order they were made, and each one
+ * starts from the dashboard that the save before it left, so a save response cannot undo a later move.
+ * A loader writes its result after `save` returns, so it passes `applied` to hold the next save until then.
+ */
+interface TileSaveQueueOwner {
+ cache: Record<string, any>
+ mount: () => () => void
+}
+
+function enqueueTileSave<T>(
+ { cache, mount }: TileSaveQueueOwner,
+ save: () => Promise<T>,
+ applied: Promise<void> = Promise.resolve()
+): Promise<T> {
+ const previous = cache.tileSaves as Promise<unknown> | undefined
+ // A queued save reads the store when it starts, so the logic stays mounted until the queue is empty.
+ if (!previous) {
+ cache.releaseTileSaveMount = mount()
+ }
+ // With nothing queued the save starts at once, so its request goes out in the same tick as the action.
+ const result = previous ? previous.then(save) : save()
+ const queued = result.then(
+ () => applied,
+ () => undefined
+ )
+ cache.tileSaves = queued
+ void queued.then(() => {
+ if (cache.tileSaves === queued) {
+ cache.tileSaves = undefined
+ cache.releaseTileSaveMount()
+ }
})
- return tileIdToLayouts
+ return result
+}
+
+function enqueueEditSave<T>(owner: TileSaveQueueOwner, save: () => Promise<T>): Promise<T> {
+ let markApplied = (): void => {}
+ const applied = new Promise<void>((resolve) => {
+ markApplied = resolve
+ })
+ const start = (): Promise<T> => {
+ owner.cache.resolveEditSaveApplied = markApplied
+ return save()
+ }
+ return enqueueTileSave(owner, start, applied)
}
+const groupKeyUpdate = (tile: DashboardTile, saved: TilePlacement | undefined): { group_key?: string | null } =>
+ tileGroupChanged(tile, saved) ? { group_key: tile.group_key ?? null } : {}
+
function calculateDraftLayouts(
tiles: DashboardTile[],
draftLayouts: ResponsiveLayouts | null,
- dashboardLayouts?: Record<DashboardTile['id'], DashboardTile['layouts']>
+ savedPlacements?: Record<DashboardTile['id'], TilePlacement>
): ResponsiveLayouts {
if (!draftLayouts) {
return calculateLayouts(tiles)
@@ -326,7 +429,7 @@ function calculateDraftLayouts(
const draftSmByTile = new Map(draftLayouts.sm?.map((layout) => [layout.i, layout]))
const tilesWithDraft = tiles.map((tile) => {
- const savedSm = dashboardLayouts?.[tile.id]?.sm
+ const savedSm = savedPlacements?.[tile.id]?.layouts?.sm
const serverSm = tile.layouts?.sm
const serverChangedSm = savedSm && serverSm && !equal(savedSm, serverSm)
const sm = serverChangedSm ? serverSm : (draftSmByTile.get(String(tile.id)) ?? serverSm)
@@ -409,7 +512,6 @@ export interface dashboardLogicValues {
dashboardEditing: DashboardEditing | null
dashboardFailedToLoad: boolean
dashboardFiltersSaving: boolean
- dashboardLayouts: Record<DashboardTile['id'], DashboardTile['layouts']>
dashboardLoadData: {
action: DashboardLoadAction | undefined
dashboardQueryId: string
@@ -483,6 +585,7 @@ export interface dashboardLogicValues {
refreshTilesTotal: number | null
revealedTileGroup: RevealedTileGroup | null
savedDashboardSettings: DashboardSettings
+ savedTilePlacements: Record<DashboardTile['id'], TilePlacement>
scrollToBottomSignal: number
settingsForRefresh: DashboardSettings
shouldReportOnAPILoad: boolean
@@ -504,6 +607,7 @@ export interface dashboardLogicValues {
terraformModalOpen: boolean
textTileId: DashboardTileIdOrNew
textTiles: DashboardTile[]
+ tileGroupMoveOptions: Record<number, TileGroupMoveOptions>
tileGroupSectionLayouts: SectionLayouts[]
tileGroupSections: DashboardSection[]
tileGroupSectionsEnabled: boolean
@@ -557,10 +661,10 @@ export interface dashboardLogicActions {
}
applyDashboardUpdate: (
dashboard: DashboardType,
- layouts: Record<number, DashboardTile['layouts']>
+ savedPlacements: Record<number, TilePlacement>
) => {
dashboard: DashboardType
- layouts: Record<number, Record<string, never> | Record<DashboardLayoutSize, TileLayout> | undefined>
+ savedPlacements: Record<number, TilePlacement>
}
applyWidgetIssueMetadataChange: (payload: {
context: WidgetIssueMetadataContext
@@ -724,6 +828,23 @@ export interface dashboardLogicActions {
loadingDashboardItemsStarted: (action: DashboardLoadAction) => {
action: DashboardLoadAction
}
+ moveTileToSection: (
+ tileId: number,
+ sectionKey: string | null,
+ cell: {
+ x: number
+ y: number
+ } | null,
+ method: TileGroupMoveMethod
+ ) => {
+ cell: {
+ x: number
+ y: number
+ } | null
+ method: TileGroupMoveMethod
+ sectionKey: string | null
+ tileId: number
+ }
moveToDashboard: (
tile: DashboardTile,
fromDashboard: number,
@@ -1092,9 +1213,9 @@ export interface dashboardLogicActions {
}
setTileProperty: (
tileId: number,
- properties: Partial<Pick<DashboardTile, 'color' | 'show_description'>>
+ properties: Partial<Pick<DashboardTile, 'color' | 'group_key' | 'layouts' | 'show_description'>>
) => {
- properties: Partial<Pick<DashboardTile, 'color' | 'show_description'>>
+ properties: Partial<Pick<DashboardTile, 'color' | 'group_key' | 'layouts' | 'show_description'>>
tileId: number
}
setWidgetRefreshStatuses: (
@@ -1112,6 +1233,9 @@ export interface dashboardLogicActions {
stageLayouts: (layouts: ResponsiveLayouts) => {
layouts: Partial<Record<string, Layout>>
}
+ tilePlacementsSaved: (placements: Record<number, TilePlacement>) => {
+ placements: Record<number, TilePlacement>
+ }
tileStreamingComplete: () => {
value: true
}
@@ -1319,10 +1443,7 @@ export interface dashboardLogicMeta {
currentDashboardVariables: (currentDashboardSettings: DashboardSettings) => Record<string, HogQLVariable>
hasUnsavedLayoutChanges: (
dashboard: DashboardType | null,
- dashboardLayouts: Record<
- number,
- Record<string, never> | Record<DashboardLayoutSize, TileLayout> | undefined
- >,
+ savedTilePlacements: Record<number, TilePlacement>,
draftLayouts: Partial<Record<string, Layout>> | null
) => boolean
effectiveVariablesAndAssociatedInsights: (
@@ -1439,6 +1560,10 @@ export interface dashboardLogicMeta {
layouts: Partial<Record<string, Layout>>,
dashboard: DashboardType | null
) => SectionLayouts[]
+ tileGroupMoveOptions: (
+ tileGroupSections: DashboardSection[],
+ canEditDashboard: boolean
+ ) => Record<number, TileGroupMoveOptions>
refreshMetrics: (
refreshStatus: Record<string, RefreshStatus>,
refreshTilesTotal: number | null
@@ -1506,6 +1631,59 @@ function exitFilterEditModeWhenSaved(
let dashboardViewedTimeout: ReturnType<typeof setTimeout> | undefined
+interface TileMove {
+ layout: Layout
+ sourceGroupKey: string | null
+ groupKey: string | null
+ message: string
+}
+
+const sectionGroupKey = (section: DashboardSection | null): string | null =>
+ section?.kind === 'group' ? section.groupKey : null
+
+const tileMoveMessage = (target: DashboardSection | null): string =>
+ target?.kind === 'group'
+ ? // The target gains this tile, and an untitled group is named by its tile count.
+ `Moved to the "${getTileGroupLabel(target.group, target.tiles.length + 1)}" group`
+ : 'Tile taken out of its group'
+
+function placementAfterMove(
+ move: TileMove,
+ tileId: number
+): { sm: Layout[number] | undefined; placement: TilePlacement } {
+ const sm = move.layout.find((item) => item.i === tileId.toString())
+ return { sm, placement: { layouts: sm ? ({ sm } as DashboardTile['layouts']) : {}, group_key: move.groupKey } }
+}
+
+function planTileMove(
+ values: dashboardLogicValues,
+ tileId: number,
+ sectionKey: string | null,
+ cell: { x: number; y: number } | null
+): TileMove | null {
+ const sections = values.tileGroupSections
+ const source = sections.find((section) => section.tiles.some((tile) => tile.id === tileId))
+ const target = sectionKey === null ? null : sections.find((section) => section.key === sectionKey)
+ if (!source || target === undefined || target === source || (!target && source.kind !== 'group')) {
+ return null
+ }
+ const layout = getLayoutAfterTileMove({
+ layout: values.layouts.sm ?? [],
+ sections,
+ sectionLayouts: values.tileGroupSectionLayouts.map((sectionLayouts) => sectionLayouts.sm ?? []),
+ tileId,
+ target,
+ cell,
+ compactor: getDashboardGridCompactor(values.dashboard?.customization?.layout_compaction),
+ })
+ return {
+ layout,
+ sourceGroupKey: sectionGroupKey(source),
+ groupKey: sectionGroupKey(target),
+ message: tileMoveMessage(target),
+ }
+}
+
export const dashboardLogic = kea<dashboardLogicType>([
path(['scenes', 'dashboard', 'dashboardLogic']),
connect(() => ({
@@ -1586,6 +1764,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
setRevealedTileGroup: (revealedTileGroup: RevealedTileGroup | null) => ({ revealedTileGroup }),
/** A band grid reports its own layout, which joins the other bands into one dashboard layout. */
updateTileGroupSectionLayout: (layouts: ResponsiveLayouts) => ({ layouts }),
+ /** A null section takes the tile out of its group, and a null cell puts it below the target's tiles. */
+ moveTileToSection: (
+ tileId: number,
+ sectionKey: string | null,
+ cell: { x: number; y: number } | null,
+ method: TileGroupMoveMethod
+ ) => ({ tileId, sectionKey, cell, method }),
+ tilePlacementsSaved: (placements: Record<number, TilePlacement>) => ({ placements }),
/** Debounced run_widgets refresh for a single tile (tile filters). */
scheduleRefreshDashboardWidgets: (tileId: number) => ({ tileId }),
applyWidgetIssueMetadataChange: (payload: {
@@ -1715,14 +1901,17 @@ export const dashboardLogic = kea<dashboardLogicType>([
updateLayouts: (layouts: ResponsiveLayouts) => ({ layouts }),
stageLayouts: (layouts: ResponsiveLayouts) => ({ layouts }),
clearDraftLayouts: () => true,
- applyDashboardUpdate: (dashboard: DashboardType, layouts: Record<number, DashboardTile['layouts']>) => ({
+ applyDashboardUpdate: (dashboard: DashboardType, savedPlacements: Record<number, TilePlacement>) => ({
dashboard,
- layouts,
+ savedPlacements,
}),
updateContainerWidth: (containerWidth: number, columns: number) => ({ containerWidth, columns }),
updateTileColor: (tileId: number, color: InsightColor | null) => ({ tileId, color }),
toggleTileDescription: (tileId: number) => ({ tileId }),
- setTileProperty: (tileId: number, properties: Partial<Pick<DashboardTile, 'color' | 'show_description'>>) => ({
+ setTileProperty: (
+ tileId: number,
+ properties: Partial<Pick<DashboardTile, 'color' | 'group_key' | 'layouts' | 'show_description'>>
+ ) => ({
tileId,
properties,
}),
@@ -1900,114 +2089,124 @@ export const dashboardLogic = kea<dashboardLogicType>([
return preserveTiles ? values.dashboard : null
},
- saveEditModeChanges: async ({ scope }, breakpoint) => {
- cache.dashboardChangesPersisted = false
- cache.draftLayoutsAtSave = values.draftLayouts
- try {
- // Only persist sm layouts; xs layouts are derived on the fly
- const draftByTile = values.draftLayouts ? layoutsByTile(values.layouts) : null
- const layoutsToUpdate = (values.dashboard?.tiles || []).map((tile) => {
- const sm = draftByTile?.[tile.id]?.sm ?? tile.layouts?.sm
- return { id: tile.id, layouts: sm ? { sm } : {} }
- })
-
- const currentDashboard = values.dashboard
- if (!currentDashboard) {
- return null
- }
+ saveEditModeChanges: ({ scope }) =>
+ enqueueEditSave({ cache, mount: (): (() => void) => dashboardLogic(props).mount() }, async () => {
+ cache.dashboardChangesPersisted = false
+ cache.draftLayoutsAtSave = values.draftLayouts
+ try {
+ // Only persist sm layouts; xs layouts are derived on the fly
+ const draftByTile = values.draftLayouts ? layoutsByTile(values.layouts) : null
+ const layoutsToUpdate = (values.dashboard?.tiles || []).map((tile) => {
+ const sm = draftByTile?.[tile.id]?.sm ?? tile.layouts?.sm
+ return {
+ id: tile.id,
+ layouts: sm ? { sm } : {},
+ ...groupKeyUpdate(tile, values.savedTilePlacements[tile.id]),
+ }
+ })
- const persistedBreakdownColors = currentDashboard.breakdown_colors || []
- const persistedThemeId = currentDashboard.data_color_theme_id ?? null
-
- // While tiles are still loading, or an errored/aborted tile is missing its
- // results, the visible breakdown values are incomplete, so fresh auto
- // assignments and stale-entry pruning would both act on partial data.
- // Persist only the saved colors with unsaved edits merged over them, and
- // leave materializing auto entries to a save with every tile's values known.
- const breakdownColorsToSave = values.breakdownValuesIncomplete
- ? mergeBreakdownColorConfigs(
- values.temporaryBreakdownColors,
- persistedBreakdownColors
- ).filter((config) => !!config.colorToken)
- : values.effectiveBreakdownColors
- const breakdownColorsChanged = !equal(persistedBreakdownColors, breakdownColorsToSave)
- const themeChanged = (values.dataColorThemeId ?? null) !== persistedThemeId
-
- const layoutsChanged = (currentDashboard.tiles || []).some((tile) => {
- const originalLayouts = values.dashboardLayouts?.[tile.id]?.sm
- const updatedLayouts = layoutsToUpdate.find((t) => t.id === tile.id)?.layouts?.sm
- return !equal(originalLayouts || {}, updatedLayouts || {})
- })
+ const currentDashboard = values.dashboard
+ if (!currentDashboard) {
+ return null
+ }
- const colorsChanged = breakdownColorsChanged || themeChanged
- const hasChanges = scope === 'colors' ? colorsChanged : layoutsChanged
- if (!hasChanges) {
- return currentDashboard
- }
+ const persistedBreakdownColors = currentDashboard.breakdown_colors || []
+ const persistedThemeId = currentDashboard.data_color_theme_id ?? null
+
+ // While tiles are still loading, or an errored/aborted tile is missing its
+ // results, the visible breakdown values are incomplete, so fresh auto
+ // assignments and stale-entry pruning would both act on partial data.
+ // Persist only the saved colors with unsaved edits merged over them, and
+ // leave materializing auto entries to a save with every tile's values known.
+ const breakdownColorsToSave = values.breakdownValuesIncomplete
+ ? mergeBreakdownColorConfigs(
+ values.temporaryBreakdownColors,
+ persistedBreakdownColors
+ ).filter((config) => !!config.colorToken)
+ : values.effectiveBreakdownColors
+ const breakdownColorsChanged = !equal(persistedBreakdownColors, breakdownColorsToSave)
+ const themeChanged = (values.dataColorThemeId ?? null) !== persistedThemeId
+
+ const layoutsChanged = (currentDashboard.tiles || []).some((tile) => {
+ const originalLayouts = values.savedTilePlacements[tile.id]?.layouts?.sm
+ const updatedLayouts = layoutsToUpdate.find((t) => t.id === tile.id)?.layouts?.sm
+ return (
+ !equal(originalLayouts || {}, updatedLayouts || {}) ||
+ tileGroupChanged(tile, values.savedTilePlacements[tile.id])
+ )
+ })
- breakpoint()
+ const colorsChanged = breakdownColorsChanged || themeChanged
+ const hasChanges = scope === 'colors' ? colorsChanged : layoutsChanged
+ if (!hasChanges) {
+ return currentDashboard
+ }
- const payload =
- scope === 'colors'
- ? {
- breakdown_colors: breakdownColorsToSave,
- data_color_theme_id: values.dataColorThemeId,
- }
- : {
- tiles: layoutsToUpdate,
- }
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
- const persistedDashboard: DashboardType = await api.update(
- `api/projects/${values.currentTeamId}/dashboards/${props.id}`,
- payload
- )
- const latestDashboard = values.dashboard ?? currentDashboard
- const updatedDashboard =
- scope === 'colors'
- ? { ...persistedDashboard, tiles: latestDashboard.tiles }
- : {
- ...persistedDashboard,
- breakdown_colors: latestDashboard.breakdown_colors,
- data_color_theme_id: latestDashboard.data_color_theme_id,
- }
- updatedDashboard.persisted_filters = latestDashboard.persisted_filters
- updatedDashboard.persisted_variables = latestDashboard.persisted_variables
- if (scope === 'colors') {
- dashboardsModel.actions.updateDashboardSuccess(
- {
- ...persistedDashboard,
- persisted_filters: latestDashboard.persisted_filters,
- persisted_variables: latestDashboard.persisted_variables,
- },
- { layoutsPersisted: true }
+ const payload =
+ scope === 'colors'
+ ? {
+ breakdown_colors: breakdownColorsToSave,
+ data_color_theme_id: values.dataColorThemeId,
+ }
+ : {
+ tiles: layoutsToUpdate,
+ }
+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
+ const persistedDashboard: DashboardType = await api.update(
+ `api/projects/${values.currentTeamId}/dashboards/${props.id}`,
+ payload
)
+ const latestDashboard = values.dashboard ?? currentDashboard
+ const updatedDashboard =
+ scope === 'colors'
+ ? { ...persistedDashboard, tiles: latestDashboard.tiles }
+ : {
+ ...persistedDashboard,
+ breakdown_colors: latestDashboard.breakdown_colors,
+ data_color_theme_id: latestDashboard.data_color_theme_id,
+ }
+ updatedDashboard.persisted_filters = latestDashboard.persisted_filters
+ updatedDashboard.persisted_variables = latestDashboard.persisted_variables
+ if (scope === 'colors') {
+ dashboardsModel.actions.updateDashboardSuccess(
+ {
+ ...persistedDashboard,
+ persisted_filters: latestDashboard.persisted_filters,
+ persisted_variables: latestDashboard.persisted_variables,
+ },
+ { layoutsPersisted: true }
+ )
+ } else {
+ actions.tilePlacementsSaved(tilePlacementsFromDashboard(updatedDashboard))
+ }
+ if (scope === 'colors' && breakdownColorsChanged) {
+ const autoCount = breakdownColorsToSave.filter(
+ (color) => color.source === 'auto'
+ ).length
+ posthog.capture('dashboard breakdown colors saved', {
+ dashboard_id: values.dashboard?.id,
+ dashboard: sanitizeDashboard(values.dashboard),
+ manual_count: breakdownColorsToSave.length - autoCount,
+ auto_count: autoCount,
+ breakdown_types: Array.from(
+ new Set(breakdownColorsToSave.map((c) => String(c.breakdownType)))
+ ),
+ })
+ }
+ if (scope === 'colors' && themeChanged) {
+ posthog.capture('dashboard color theme set', {
+ dashboard_id: values.dashboard?.id,
+ dashboard: sanitizeDashboard(values.dashboard),
+ theme_id: values.dataColorThemeId,
+ })
+ }
+ cache.dashboardChangesPersisted = true
+ return updatedDashboard
+ } catch (e) {
+ lemonToast.error('Could not update dashboard: ' + String(e))
+ return values.dashboard
}
- if (scope === 'colors' && breakdownColorsChanged) {
- const autoCount = breakdownColorsToSave.filter((color) => color.source === 'auto').length
- posthog.capture('dashboard breakdown colors saved', {
- dashboard_id: values.dashboard?.id,
- dashboard: sanitizeDashboard(values.dashboard),
- manual_count: breakdownColorsToSave.length - autoCount,
- auto_count: autoCount,
- breakdown_types: Array.from(
- new Set(breakdownColorsToSave.map((c) => String(c.breakdownType)))
- ),
- })
- }
- if (scope === 'colors' && themeChanged) {
- posthog.capture('dashboard color theme set', {
- dashboard_id: values.dashboard?.id,
- dashboard: sanitizeDashboard(values.dashboard),
- theme_id: values.dataColorThemeId,
- })
- }
- cache.dashboardChangesPersisted = true
- return updatedDashboard
- } catch (e) {
- lemonToast.error('Could not update dashboard: ' + String(e))
- return values.dashboard
- }
- },
+ }),
removeTile: async ({ tile }) => {
// The reducer drops the tile optimistically; here we only persist and roll back on failure.
try {
@@ -2031,7 +2230,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
} as DashboardType
}
},
- duplicateTile: async ({ tile }) => {
+ duplicateTile: async ({ tile }): Promise<DashboardType> => {
try {
const newTile = { ...tile } as Partial<DashboardTile>
if (newTile.text) {
@@ -2051,7 +2250,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
tiles: tilesToUpdate.length > 0 ? tilesToUpdate : undefined,
}
)
- return dashboard
+ // The server copy lacks unsaved group moves, so keep each tile's group from before.
+ const groupKeys = new Map(values.tiles.map((tile) => [tile.id, tile.group_key ?? null]))
+ return {
+ ...dashboard,
+ tiles: dashboard.tiles.map((tile) =>
+ groupKeys.has(tile.id) ? { ...tile, group_key: groupKeys.get(tile.id) } : tile
+ ),
+ }
} catch (e) {
// Re-throw so duplicateTileFailure fires. Swallowing the error resolved it as a
// success, so the tile refreshed with no copy and the user kept clicking.
@@ -2299,18 +2505,17 @@ export const dashboardLogic = kea<dashboardLogicType>([
setDashboardStreamFailed: () => true,
},
],
- dashboardLayouts: [
- {} as Record<DashboardTile['id'], DashboardTile['layouts']>,
+ savedTilePlacements: [
+ {} as Record<DashboardTile['id'], TilePlacement>,
{
- loadDashboardSuccess: (_, { dashboard }) => tileLayoutsFromDashboard(dashboard),
- loadDashboardMetadataSuccess: (_, { dashboard }) => tileLayoutsFromDashboard(dashboard),
- applyDashboardUpdate: (_, { layouts }) => layouts,
- saveEditModeChangesSuccess: (state, { dashboard, payload }) =>
- payload?.scope === 'layout' ? tileLayoutsFromDashboard(dashboard) : state,
- receiveTileFromStream: (state, { tile }) => ({
- ...state,
- [tile.id]: tile.layouts,
- }),
+ loadDashboardSuccess: (_, { dashboard }) => tilePlacementsFromDashboard(dashboard),
+ loadDashboardMetadataSuccess: (_, { dashboard }) => tilePlacementsFromDashboard(dashboard),
+ applyDashboardUpdate: (_, { savedPlacements }) => savedPlacements,
+ // Not saveEditModeChangesSuccess, because a failed save also fires it and the moves must stay unsaved.
+ tilePlacementsSaved: (state, { placements }) => ({ ...state, ...placements }),
+ receiveTileFromStream: (state, { tile }) => ({ ...state, [tile.id]: tilePlacement(tile) }),
+ duplicateTileSuccess: (state, { dashboard }) =>
+ dashboard ? { ...tilePlacementsFromDashboard(dashboard), ...state } : state,
},
],
draftLayouts: [
@@ -3170,10 +3375,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
(settings: DashboardSettings) => settings.variables,
],
hasUnsavedLayoutChanges: [
- (s) => [s.dashboard, s.dashboardLayouts, s.draftLayouts],
+ (s) => [s.dashboard, s.savedTilePlacements, s.draftLayouts],
(
dashboard: DashboardType | null,
- dashboardLayouts: Record<DashboardTile['id'], DashboardTile['layouts']>,
+ savedTilePlacements: Record<DashboardTile['id'], TilePlacement>,
draftLayouts: ResponsiveLayouts | null
): boolean => {
if (!dashboard) {
@@ -3181,9 +3386,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
const draftByTile = draftLayouts ? layoutsByTile(draftLayouts) : null
return (dashboard.tiles || []).some((tile: DashboardTile) => {
- const originalSm = dashboardLayouts?.[tile.id]?.sm
+ const saved = savedTilePlacements[tile.id]
const currentSm = draftByTile?.[tile.id]?.sm ?? tile.layouts?.sm
- return !equal(originalSm || {}, currentSm || {})
+ return !equal(saved?.layouts?.sm || {}, currentSm || {}) || tileGroupChanged(tile, saved)
})
},
],
@@ -3604,6 +3809,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
{ resultEqualityCheck: objectsEqual },
],
+ tileGroupMoveOptions: [
+ (s) => [s.tileGroupSections, s.canEditDashboard],
+ (tileGroupSections: DashboardSection[], canEditDashboard: boolean): Record<number, TileGroupMoveOptions> =>
+ canEditDashboard ? getTileGroupMoveOptions(tileGroupSections) : {},
+ { resultEqualityCheck: objectsEqual },
+ ],
refreshMetrics: [
(s) => [s.refreshStatus, s.refreshTilesTotal],
(refreshStatus: Record<string, RefreshStatus>, refreshTilesTotal: number | null) => {
@@ -3938,6 +4149,72 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.stageLayouts({ sm: dashboardLayout })
}
},
+ moveTileToSection: async ({ tileId, sectionKey, cell, method }) => {
+ const capture = ({ sourceGroupKey, groupKey }: TileMove): void => {
+ if (sourceGroupKey !== groupKey) {
+ posthog.capture('dashboard tile moved between groups', {
+ dashboard_id: props.id,
+ from_group: sourceGroupKey !== null,
+ to_group: groupKey !== null,
+ method,
+ })
+ }
+ }
+ if (values.layoutEditMode) {
+ const move = planTileMove(values, tileId, sectionKey, cell)
+ if (!move) {
+ return
+ }
+ actions.stageLayouts({ sm: move.layout })
+ actions.setTileProperty(tileId, { group_key: move.groupKey })
+ capture(move)
+ if (move.groupKey && values.collapsedTileGroupKeys.includes(move.groupKey)) {
+ lemonToast.info(move.message)
+ }
+ return
+ }
+ await enqueueTileSave({ cache, mount: (): (() => void) => dashboardLogic(props).mount() }, async () => {
+ const move = planTileMove(values, tileId, sectionKey, cell)
+ if (!move) {
+ return
+ }
+ const { sm, placement } = placementAfterMove(move, tileId)
+ const savedBefore = savedTilePlacement(values.savedTilePlacements, tileId)
+ actions.setTileProperty(tileId, placement)
+ const currentPlacement = (): TilePlacement | null => {
+ const tile = values.tiles.find((candidate) => candidate.id === tileId)
+ return tile ? tilePlacement(tile) : null
+ }
+ try {
+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
+ await api.update(`api/projects/${values.currentTeamId}/dashboards/${props.id}`, {
+ tiles: [{ id: tileId, ...placement }],
+ })
+ actions.tilePlacementsSaved({ [tileId]: placement })
+ // A discard while the request was out put the tile back, but an edit staged since then is newer.
+ if (values.draftLayouts === null && equal(currentPlacement(), savedBefore)) {
+ actions.setTileProperty(tileId, placement)
+ }
+ capture(move)
+ lemonToast.success(move.message)
+ } catch {
+ lemonToast.error('Could not move the tile, so it is back where it was. Try again.')
+ // A move of this tile in edit mode is newer than this one, so it stays.
+ if (equal(currentPlacement(), placement)) {
+ const saved = savedTilePlacement(values.savedTilePlacements, tileId)
+ actions.setTileProperty(tileId, saved)
+ // A layout staged in edit mode since the move holds the moved cell, so it goes back too.
+ const draft = values.draftLayouts
+ if (draft?.sm && sm) {
+ const draftSm = withStagedCellReverted(draft.sm, tileId, sm, saved.layouts?.sm)
+ if (draftSm !== draft.sm) {
+ actions.stageLayouts({ ...draft, sm: draftSm })
+ }
+ }
+ }
+ }
+ })
+ },
[dashboardsModel.actionTypes.updateDashboardSuccess]: ({
dashboard,
payload,
@@ -3951,45 +4228,41 @@ export const dashboardLogic = kea<dashboardLogicType>([
const layoutsPersisted = payload?.layoutsPersisted === true
const previousTiles = new Map(values.dashboard.tiles.map((tile) => [tile.id, tile]))
+ const savedBefore = values.savedTilePlacements
const originalLayouts = layoutsPersisted
? layoutsByTile(
calculateLayouts(
- values.dashboard.tiles.map((tile) => ({
- ...tile,
- layouts: values.dashboardLayouts[tile.id],
- }))
+ values.dashboard.tiles.map((tile) => withTilePlacement(tile, savedBefore[tile.id]))
)
)
: null
- const layouts = tileLayoutsFromDashboard(dashboard)
- if (!layoutsPersisted) {
- values.dashboard.tiles.forEach((tile) => {
- if (tile.id in layouts) {
- layouts[tile.id] = values.dashboardLayouts[tile.id]
- }
- })
- }
+ const savedPlacements = Object.fromEntries(
+ dashboard.tiles.map((tile) => [
+ tile.id,
+ !layoutsPersisted && previousTiles.has(tile.id)
+ ? (savedBefore[tile.id] ?? tilePlacement(tile))
+ : tilePlacement(tile),
+ ])
+ )
const tiles = dashboard.tiles.map((tile) => {
const previousTile = previousTiles.get(tile.id)
- if (previousTile && !layoutsPersisted) {
- return { ...tile, layouts: previousTile.layouts }
+ if (!previousTile) {
+ return tile
}
- const draftSm = previousTile?.layouts?.sm
- const originalSm = originalLayouts?.[tile.id]?.sm
- if (
- draftSm &&
- originalSm &&
- (draftSm.x !== originalSm.x ||
- draftSm.y !== originalSm.y ||
- draftSm.w !== originalSm.w ||
- draftSm.h !== originalSm.h)
- ) {
- return { ...tile, layouts: previousTile.layouts }
+ if (!layoutsPersisted) {
+ return withTilePlacement(tile, tilePlacement(previousTile))
}
- return tile
+ const draftSm = previousTile.layouts?.sm
+ const originalSm = originalLayouts?.[tile.id]?.sm
+ const layoutMoved = !!draftSm && !!originalSm && !sameGridCell(draftSm, originalSm)
+ const groupMoved = tileGroupChanged(previousTile, savedBefore[tile.id])
+ return withTilePlacement(tile, {
+ layouts: layoutMoved ? previousTile.layouts : tile.layouts,
+ group_key: groupMoved ? (previousTile.group_key ?? null) : (tile.group_key ?? null),
+ })
})
- actions.applyDashboardUpdate({ ...dashboard, tiles }, layouts)
+ actions.applyDashboardUpdate({ ...dashboard, tiles }, savedPlacements)
},
scheduleRefreshDashboardWidgets: ({ tileId }: { tileId: number }) => {
if (!cache.widgetTileRefreshScheduler) {
@@ -4206,7 +4479,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
calculateDraftLayouts(
dashboard.tiles.filter((tile) => !tile.deleted),
values.draftLayouts,
- values.dashboardLayouts
+ values.savedTilePlacements
)
)
}
@@ -5069,8 +5342,13 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.setDashboardEditing(null, DashboardEventSource.DashboardFilters)
}
},
+ saveEditModeChangesFailure: () => {
+ cache.resolveEditSaveApplied?.()
+ },
saveEditModeChangesSuccess: ({ dashboard, payload }) => {
- if (dashboard && payload?.scope !== 'colors') {
+ cache.resolveEditSaveApplied?.()
+ // A failed or no-op save resolves with the dashboard from before the save, which holds unsaved moves.
+ if (dashboard && payload?.scope !== 'colors' && cache.dashboardChangesPersisted) {
// Sync the saved dashboard (including any name/description changes) to
// dashboardsModel so the sidebar and other global views stay up to date
dashboardsModel.actions.updateDashboardSuccess(dashboard, { layoutsPersisted: true })
@@ -5159,11 +5437,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
return
}
const changeCompaction = (discardUnsavedLayoutChanges = false): void => {
- if (discardUnsavedLayoutChanges) {
- const savedSmLayout = Object.entries(values.dashboardLayouts).flatMap(([tileId, layouts]) =>
- layouts?.sm ? [{ ...layouts.sm, i: tileId }] : []
+ if (discardUnsavedLayoutChanges && values.dashboard) {
+ actions.applyDashboardUpdate(
+ withSavedTilePlacements(values.dashboard, values.savedTilePlacements),
+ values.savedTilePlacements
)
- actions.updateLayouts({ sm: savedSmLayout })
+ actions.clearDraftLayouts()
}
actions.setDashboardGridCompaction(layoutCompaction)
actions.saveDashboardGridCompaction(layoutCompaction)
@@ -5194,14 +5473,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
values.dashboard?.tiles
) {
actions.applyDashboardUpdate(
- {
- ...values.dashboard,
- tiles: values.dashboard.tiles.map((tile) => ({
- ...tile,
- layouts: values.dashboardLayouts[tile.id],
- })),
- },
- values.dashboardLayouts
+ withSavedTilePlacements(values.dashboard, values.savedTilePlacements),
+ values.savedTilePlacements
)
}
if (editing?.layout && source !== DashboardEventSource.DashboardHeaderDiscardChanges) {
diff --git a/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx b/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx
index 688f80ef7dad..927d63490f5a 100644
--- a/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx
+++ b/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx
@@ -3,7 +3,10 @@ import React from 'react'
import { ButtonTileCard } from 'lib/components/Cards/ButtonTileCard/ButtonTileCard'
import { dashboardWidgetMenusLogic } from 'lib/components/Cards/InsightCard/dashboardWidgetMenusLogic'
-import { DashboardWidgetPlacementMenus } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'
+import {
+ DashboardWidgetPlacementMenus,
+ type DashboardWidgetPlacementMenusProps,
+} from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
@@ -11,10 +14,10 @@ import type { DashboardPlacement, DashboardTile, DashboardType } from '~/types'
type BaseButtonTileCardProps = React.ComponentProps<typeof ButtonTileCard>
-interface DashboardButtonTileItemProps extends Omit<
- BaseButtonTileCardProps,
- 'buttonTile' | 'placement' | 'moreButtonOverlay'
-> {
+interface DashboardButtonTileItemProps
+ extends
+ Omit<BaseButtonTileCardProps, 'buttonTile' | 'placement' | 'moreButtonOverlay'>,
+ Pick<DashboardWidgetPlacementMenusProps, 'tileGroupMoveOptions' | 'onMoveToTileGroup'> {
tile: DashboardTile
placement: DashboardPlacement
dashboardId?: number | null
@@ -31,6 +34,8 @@ function DashboardButtonTileItemInternal(
dashboardId,
onEdit,
onMoveToDashboard,
+ tileGroupMoveOptions,
+ onMoveToTileGroup,
onDuplicate,
onRemove,
...buttonTileCardProps
@@ -59,6 +64,8 @@ function DashboardButtonTileItemInternal(
<DashboardWidgetPlacementMenus
placementDestinations={copyToDestinations}
onMoveToDashboard={onMoveToDashboard}
+ tileGroupMoveOptions={tileGroupMoveOptions}
+ onMoveToTileGroup={onMoveToTileGroup}
/>
<LemonButton onClick={onDuplicate} fullWidth data-attr="duplicate-button-tile-from-dashboard">
diff --git a/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx
index de3cf4229a7d..eebb4bf77f28 100644
--- a/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx
+++ b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx
@@ -2,7 +2,10 @@ import { useValues } from 'kea'
import React from 'react'
import { dashboardWidgetMenusLogic } from 'lib/components/Cards/InsightCard/dashboardWidgetMenusLogic'
-import { DashboardWidgetPlacementMenus } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'
+import {
+ DashboardWidgetPlacementMenus,
+ type DashboardWidgetPlacementMenusProps,
+} from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'
import { TextCard } from 'lib/components/Cards/TextCard/TextCard'
import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -15,7 +18,10 @@ import { getImageOnlyTextCardImage } from '../ImageTile/imageTileUtils'
type BaseTextCardProps = React.ComponentProps<typeof TextCard>
-interface DashboardTextItemProps extends Omit<BaseTextCardProps, 'textTile' | 'placement' | 'moreButtonOverlay'> {
+interface DashboardTextItemProps
+ extends
+ Omit<BaseTextCardProps, 'textTile' | 'placement' | 'moreButtonOverlay'>,
+ Pick<DashboardWidgetPlacementMenusProps, 'tileGroupMoveOptions' | 'onMoveToTileGroup'> {
tile: DashboardTile
placement: DashboardPlacement
dashboardId?: number | null
@@ -34,6 +40,8 @@ function DashboardTextItemInternal(
onEdit,
onMoveToDashboard,
onCopyToDashboard,
+ tileGroupMoveOptions,
+ onMoveToTileGroup,
onDuplicate,
onRemove,
...textCardProps
@@ -61,6 +69,8 @@ function DashboardTextItemInternal(
placementDestinations={copyToDestinations}
onMoveToDashboard={onMoveToDashboard}
onCopyToDashboard={onCopyToDashboard}
+ tileGroupMoveOptions={tileGroupMoveOptions}
+ onMoveToTileGroup={onMoveToTileGroup}
/>
<LemonButton onClick={onDuplicate} fullWidth data-attr={`duplicate-${tileType}-from-dashboard`}>
diff --git a/products/dashboards/frontend/components/DashboardTileSectionBand.tsx b/products/dashboards/frontend/components/DashboardTileSectionBand.tsx
new file mode 100644
index 000000000000..971d985f88b7
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileSectionBand.tsx
@@ -0,0 +1,45 @@
+import clsx from 'clsx'
+
+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
+
+import type { DashboardSection } from '../dashboardTileSections'
+import { DashboardTileGroup } from './DashboardTileGroup/DashboardTileGroup'
+
+interface DashboardTileSectionBandProps {
+ section: DashboardSection
+ isFirst: boolean
+ isDropTarget: boolean
+ collapsedTileGroupKeys: string[]
+ onToggleTileGroup: (groupKey: string) => void
+ children: React.ReactNode
+}
+
+export function DashboardTileSectionBand({
+ section,
+ isFirst,
+ isDropTarget,
+ collapsedTileGroupKeys,
+ onToggleTileGroup,
+ children,
+}: DashboardTileSectionBandProps): JSX.Element {
+ return (
+ <div data-dashboard-section={section.key} className={clsx('rounded-lg', isDropTarget && 'ring-2 ring-accent')}>
+ {section.kind === 'tiles' ? (
+ <>
+ {/* Without a line, viewers read loose tiles under a closed group as part of that group. */}
+ {!isFirst && <LemonDivider className="mb-4" />}
+ {children}
+ </>
+ ) : (
+ <DashboardTileGroup
+ group={section.group}
+ tileCount={section.tiles.length}
+ collapsed={collapsedTileGroupKeys.includes(section.groupKey)}
+ onToggle={() => onToggleTileGroup(section.groupKey)}
+ >
+ {children}
+ </DashboardTileGroup>
+ )}
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
index 2c0aa0f86109..1ae3373f53da 100644
--- a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
@@ -7,7 +7,10 @@ import { useInView } from 'react-intersection-observer'
import { CardMetaRefreshButton } from 'lib/components/Cards/CardMetaRefreshButton'
import { DashboardTileRefreshDataButton } from 'lib/components/Cards/InsightCard/DashboardTileRefreshDataButton'
import { dashboardWidgetMenusLogic } from 'lib/components/Cards/InsightCard/dashboardWidgetMenusLogic'
-import { DashboardWidgetPlacementMenus } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'
+import {
+ DashboardWidgetPlacementMenus,
+ type DashboardWidgetPlacementMenusProps,
+} from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'
import { EditModeEdge } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
@@ -81,7 +84,8 @@ type DashboardWidgetItemProps = {
onCopyToDashboard?: (target: Pick<DashboardType, 'id' | 'name'>) => void
/** Injected by react-grid-layout / react-resizable — must render inside the card root. */
children?: React.ReactNode
-} & Omit<React.HTMLAttributes<HTMLDivElement>, 'children'>
+} & Pick<DashboardWidgetPlacementMenusProps, 'tileGroupMoveOptions' | 'onMoveToTileGroup'> &
+ Omit<React.HTMLAttributes<HTMLDivElement>, 'children'>
type DashboardWidgetItemContentProps = Omit<
DashboardWidgetItemProps,
@@ -159,6 +163,8 @@ function DashboardWidgetItemContent({
onRemove,
onMoveToDashboard,
onCopyToDashboard,
+ tileGroupMoveOptions,
+ onMoveToTileGroup,
copyToDestinations,
editOpen,
setEditOpen,
@@ -291,6 +297,8 @@ function DashboardWidgetItemContent({
placementDestinations={copyToDestinations ?? []}
onMoveToDashboard={onMoveToDashboard}
onCopyToDashboard={onCopyToDashboard}
+ tileGroupMoveOptions={tileGroupMoveOptions}
+ onMoveToTileGroup={onMoveToTileGroup}
/>
)}
{onRemove && (
@@ -409,6 +417,8 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWid
onRemove,
onMoveToDashboard,
onCopyToDashboard,
+ tileGroupMoveOptions,
+ onMoveToTileGroup,
children,
className,
style,
@@ -500,6 +510,8 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWid
onRemove={onRemove}
onMoveToDashboard={onMoveToDashboard}
onCopyToDashboard={onCopyToDashboard}
+ tileGroupMoveOptions={tileGroupMoveOptions}
+ onMoveToTileGroup={onMoveToTileGroup}
copyToDestinations={copyToDestinations}
editOpen={editOpen}
setEditOpen={setEditOpen}
diff --git a/products/dashboards/frontend/components/TileGroupTakeOutDropZone.tsx b/products/dashboards/frontend/components/TileGroupTakeOutDropZone.tsx
new file mode 100644
index 000000000000..37d9d8f26e74
--- /dev/null
+++ b/products/dashboards/frontend/components/TileGroupTakeOutDropZone.tsx
@@ -0,0 +1,17 @@
+import clsx from 'clsx'
+
+import { TAKE_OUT_DROP_ZONE_KEY } from '../useTileGroupDrag'
+
+export function TileGroupTakeOutDropZone({ isDropTarget }: { isDropTarget: boolean }): JSX.Element {
+ return (
+ <div
+ data-dashboard-section={TAKE_OUT_DROP_ZONE_KEY}
+ className={clsx(
+ 'mb-[40vh] flex h-24 items-center justify-center rounded-lg border border-dashed text-secondary',
+ isDropTarget && 'ring-2 ring-accent'
+ )}
+ >
+ Drag a tile here to take it out of its group
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/dashboardTileSections.test.ts b/products/dashboards/frontend/dashboardTileSections.test.ts
index d84c8d6b0345..33f7ca6508c6 100644
--- a/products/dashboards/frontend/dashboardTileSections.test.ts
+++ b/products/dashboards/frontend/dashboardTileSections.test.ts
@@ -1,5 +1,7 @@
import type { Layout } from 'react-grid-layout'
+import { pluralize } from 'lib/utils/strings'
+
import type { DashboardTile } from '~/types'
import { DashboardGridCompaction, getDashboardGridCompactor } from './dashboardCustomization'
@@ -7,7 +9,9 @@ import {
getCollapsedTileGroupKeys,
getDashboardSections,
getLayoutAfterSectionChange,
+ getLayoutAfterTileMove,
getSectionLayouts,
+ getTileGroupMoveOptions,
hasSectionLayoutChanged,
stackSectionLayouts,
} from './dashboardTileSections'
@@ -37,6 +41,15 @@ interface SectionsCase {
expected: string[]
}
+interface TileMoveCase {
+ name: string
+ tiles: DashboardTile[]
+ targetKey: string | null
+ cell: { x: number; y: number } | null
+ expectedSections: string[]
+ expectedTile?: Partial<Layout[number]>
+}
+
interface CollapsedCase {
name: string
tiles: DashboardTile[]
@@ -199,4 +212,76 @@ describe('dashboardTileSections', () => {
])('getCollapsedTileGroupKeys finds $name', ({ tiles, groups, choices, expected }) => {
expect(getCollapsedTileGroupKeys({ tiles, groups, choices })).toEqual(expected)
})
+
+ it.each<TileMoveCase>([
+ {
+ name: 'into a closed group goes below its tiles',
+ tiles: [tile(1, 'plans'), tile(2, 'ops'), tile(3)],
+ targetKey: 'group-ops',
+ cell: null,
+ expectedSections: ['ops(): 2,1', 'tiles: 3'],
+ },
+ {
+ name: 'out of its group joins the last band when that band has no group',
+ tiles: [tile(1, 'plans'), tile(2, 'ops'), tile(3)],
+ targetKey: null,
+ cell: null,
+ expectedSections: ['ops(): 2', 'tiles: 3,1'],
+ },
+ {
+ name: 'out of its group starts a band after the last group',
+ tiles: [tile(1, 'plans'), tile(2, 'ops'), tile(3, 'ops')],
+ targetKey: null,
+ cell: null,
+ expectedSections: ['ops(): 2,3', 'tiles: 1'],
+ },
+ {
+ name: 'into another band lands at the drop cell',
+ tiles: [tile(1, 'plans'), tile(2, 'ops'), tile(3)],
+ targetKey: 'group-ops',
+ cell: { x: 6, y: 0 },
+ expectedSections: ['ops(): 2,1', 'tiles: 3'],
+ expectedTile: { x: 6, y: 0 },
+ },
+ ])('getLayoutAfterTileMove: a tile moved $name', ({ tiles, targetKey, cell, expectedSections, expectedTile }) => {
+ const layout = [box(1, 0, 0), box(2, 0, 2), box(3, 0, 4)]
+ const sections = getDashboardSections({ tiles, layout, groups: undefined })
+ const compactor = getDashboardGridCompactor(DashboardGridCompaction.Vertical)
+
+ const moved = getLayoutAfterTileMove({
+ layout,
+ sections,
+ sectionLayouts: sections.map((section) => getSectionLayouts({ sm: layout }, section.tiles, compactor).sm!),
+ tileId: 1,
+ target: sections.find((section) => section.key === targetKey) ?? null,
+ cell,
+ compactor,
+ })
+ const targetSection = sections.find((section) => section.key === targetKey)
+ const movedTiles = tiles.map((t) =>
+ t.id === 1 ? { ...t, group_key: targetSection?.kind === 'group' ? targetSection.groupKey : null } : t
+ )
+
+ expect(sectionSummary(movedTiles, moved)).toEqual(expectedSections)
+ if (expectedTile) {
+ expect(moved.find((item) => item.i === '1')).toMatchObject(expectedTile)
+ }
+ })
+
+ it('getTileGroupMoveOptions offers the other groups by their band labels, and taking a grouped tile out', () => {
+ const sections = getDashboardSections({
+ tiles: [tile(1, 'plans'), tile(2, 'ops'), tile(3, 'ops'), tile(4)],
+ layout: [box(1, 0, 0), box(2, 0, 2), box(3, 0, 4), box(4, 0, 6)],
+ groups: { plans: { title: 'Pricing plans' } },
+ })
+ const plans = { sectionKey: 'group-plans', label: 'Pricing plans' }
+ const ops = { sectionKey: 'group-ops', label: pluralize(2, 'tile') }
+
+ expect(getTileGroupMoveOptions(sections)).toEqual({
+ 1: { targets: [ops], canTakeOut: true },
+ 2: { targets: [plans], canTakeOut: true },
+ 3: { targets: [plans], canTakeOut: true },
+ 4: { targets: [plans, ops], canTakeOut: false },
+ })
+ })
})
diff --git a/products/dashboards/frontend/dashboardTileSections.ts b/products/dashboards/frontend/dashboardTileSections.ts
index 026aa46a271b..98a419e2df2b 100644
--- a/products/dashboards/frontend/dashboardTileSections.ts
+++ b/products/dashboards/frontend/dashboardTileSections.ts
@@ -1,10 +1,14 @@
+import { cloneLayout } from 'react-grid-layout'
import type { Compactor, Layout } from 'react-grid-layout'
+import { moveElement } from 'react-grid-layout/core'
import { objectsEqual } from 'lib/utils/objects'
+import { pluralize } from 'lib/utils/strings'
import { BREAKPOINT_COLUMN_COUNTS } from 'scenes/dashboard/dashboardUtils'
import type { DashboardLayoutSize, DashboardTile } from '~/types'
+import type { DashboardGridCompactor } from './dashboardCustomization'
import type { DashboardTileGroupApi } from './generated/api.schemas'
export type DashboardSection =
@@ -13,6 +17,21 @@ export type DashboardSection =
export type SectionLayouts = Partial<Record<DashboardLayoutSize, Layout>>
+export interface TileGroupMoveOptions {
+ targets: { sectionKey: string; label: string }[]
+ canTakeOut: boolean
+}
+
+export function getTileGroupLabel(group: DashboardTileGroupApi, tileCount: number): string {
+ return group.title || pluralize(tileCount, 'tile')
+}
+
+const TILE_GROUP_SECTION_KEY_PREFIX = 'group-'
+
+export function isTileGroupSectionKey(sectionKey: string): boolean {
+ return sectionKey.startsWith(TILE_GROUP_SECTION_KEY_PREFIX)
+}
+
function tilesInLayoutOrder(tiles: DashboardTile[], layout: Layout | undefined): DashboardTile[] {
const positions = new Map((layout ?? []).map((item) => [item.i, item]))
const position = (tile: DashboardTile): [number, number] => {
@@ -50,7 +69,7 @@ export function getDashboardSections({
const group = groups && Object.hasOwn(groups, groupKey) ? groups[groupKey] : {}
const section: DashboardSection = {
kind: 'group',
- key: `group-${groupKey}`,
+ key: `${TILE_GROUP_SECTION_KEY_PREFIX}${groupKey}`,
groupKey,
group,
tiles: [tile],
@@ -164,3 +183,112 @@ export function getCollapsedTileGroupKeys({
return !!(groups && Object.hasOwn(groups, groupKey) && groups[groupKey].collapsed)
})
}
+
+export function getTileGroupMoveOptions(sections: DashboardSection[]): Record<number, TileGroupMoveOptions> {
+ const targets = sections.flatMap((section) =>
+ section.kind === 'group'
+ ? [{ sectionKey: section.key, label: getTileGroupLabel(section.group, section.tiles.length) }]
+ : []
+ )
+ return Object.fromEntries(
+ sections.flatMap((section) => {
+ const options: TileGroupMoveOptions = {
+ targets: targets.filter((target) => target.sectionKey !== section.key),
+ canTakeOut: section.kind === 'group',
+ }
+ return section.tiles.map((tile) => [tile.id, options])
+ })
+ )
+}
+
+export function getDropCell({
+ tileRect,
+ gridRect,
+ cols,
+ rowHeight,
+ margin: [marginX, marginY],
+ tileWidth,
+}: {
+ tileRect: { left: number; top: number }
+ gridRect: { left: number; top: number; width: number }
+ cols: number
+ rowHeight: number
+ margin: [number, number]
+ tileWidth: number
+}): { x: number; y: number } {
+ const columnStep = (gridRect.width - marginX * (cols - 1)) / cols + marginX
+ const x = Math.round((tileRect.left - gridRect.left) / columnStep)
+ const y = Math.round((tileRect.top - gridRect.top) / (rowHeight + marginY))
+ return { x: Math.min(Math.max(x, 0), cols - tileWidth), y: Math.max(y, 0) }
+}
+
+/**
+ * The dashboard layout after a tile moves to the `target` section, or out of its group when `target` is null.
+ * Without a drop cell the tile goes below the target's tiles and only its own layout item changes, so a save of
+ * that one tile matches what the dashboard shows. A tile out of its group goes below every tile, which puts it in
+ * the last band when that band has no group, and in a new band after the last group otherwise.
+ */
+export function getLayoutAfterTileMove({
+ layout,
+ sections,
+ sectionLayouts,
+ tileId,
+ target,
+ cell,
+ compactor,
+}: {
+ layout: Layout
+ sections: DashboardSection[]
+ sectionLayouts: Layout[]
+ tileId: number
+ target: DashboardSection | null
+ cell: { x: number; y: number } | null
+ compactor: DashboardGridCompactor
+}): Layout {
+ const tileKey = tileId.toString()
+ if (!cell || !target) {
+ const targetTileIds = new Set(
+ (target ? target.tiles : sections.flatMap((section) => section.tiles)).map((tile) => tile.id.toString())
+ )
+ targetTileIds.delete(tileKey)
+ const bottom = Math.max(0, ...layout.filter((item) => targetTileIds.has(item.i)).map((item) => item.y + item.h))
+ return layout.map((item) => (item.i === tileKey ? { ...item, y: bottom } : item))
+ }
+
+ const cols = BREAKPOINT_COLUMN_COUNTS.sm
+ const sourceIndex = sections.findIndex((section) => section.tiles.some((tile) => tile.id === tileId))
+ const targetIndex = sections.indexOf(target)
+ const item = sectionLayouts[sourceIndex]?.find((layoutItem) => layoutItem.i === tileKey)
+ if (!item) {
+ return layout
+ }
+ const targetLayout = sectionLayouts[targetIndex] ?? []
+ const bottom = Math.max(0, ...targetLayout.map((layoutItem) => layoutItem.y + layoutItem.h))
+ // Enter at the bottom, then move to the drop cell the way a drag does, so the tile under the drop moves aside.
+ const withTile = cloneLayout([...targetLayout, { ...item, y: bottom }])
+ const moved = moveElement(
+ withTile,
+ withTile[withTile.length - 1],
+ cell.x,
+ cell.y,
+ true,
+ false,
+ compactor.type,
+ cols,
+ compactor.allowOverlap
+ )
+ return stackSectionLayouts(
+ sectionLayouts.map((sectionLayout, index) => {
+ if (index === sourceIndex) {
+ return compactor.compact(
+ sectionLayout.filter((layoutItem) => layoutItem.i !== tileKey),
+ cols
+ )
+ }
+ if (index === targetIndex) {
+ return compactor.compactInteraction(cols, tileKey, moved, moved, true)
+ }
+ return sectionLayout
+ })
+ )
+}
diff --git a/products/dashboards/frontend/useTileGroupDrag.test.ts b/products/dashboards/frontend/useTileGroupDrag.test.ts
new file mode 100644
index 000000000000..6bda38088a38
--- /dev/null
+++ b/products/dashboards/frontend/useTileGroupDrag.test.ts
@@ -0,0 +1,205 @@
+import { act, renderHook } from '@testing-library/react'
+import type { Layout, LayoutItem } from 'react-grid-layout'
+
+import { TAKE_OUT_DROP_ZONE_KEY, useTileGroupDrag } from './useTileGroupDrag'
+
+const box = (id: number, y: number): LayoutItem => ({ i: String(id), x: 0, y, w: 6, h: 2 })
+
+const band = (key: string, withGrid = true): HTMLElement => {
+ const element = document.createElement('div')
+ element.setAttribute('data-dashboard-section', key)
+ if (withGrid) {
+ const grid = document.createElement('div')
+ grid.setAttribute('data-dashboard-section-grid', key)
+ grid.getBoundingClientRect = () => ({ left: 0, top: 0, width: 1200 }) as DOMRect
+ element.append(grid)
+ }
+ return element
+}
+
+const dashboardRoot = (...bands: HTMLElement[]): HTMLElement => {
+ const root = document.createElement('div')
+ root.className = 'dashboard-items-wrapper'
+ root.append(...bands)
+ document.body.append(root)
+ return root
+}
+
+const pointerAt = (...elements: Element[]): void => {
+ Object.defineProperty(document, 'elementsFromPoint', { configurable: true, value: () => elements })
+}
+
+interface Dashboard {
+ root: HTMLElement
+ sourceBand: HTMLElement
+ placeholder: HTMLElement
+ openBand: HTMLElement
+ closedBand: HTMLElement
+ dropZone: HTMLElement
+}
+
+interface DropCase {
+ name: string
+ passOver?: (dashboard: Dashboard) => Element
+ dropOn: (dashboard: Dashboard) => Element[]
+ sourceKey?: string
+ moved: [number, string | null, { x: number; y: number } | null] | null
+ restored: boolean
+}
+
+describe('useTileGroupDrag', () => {
+ const layout: Layout = [box(1, 0), box(2, 2)]
+ const draggedItem = box(1, 40)
+
+ const setUp = (
+ sourceKey = 'group-plans'
+ ): {
+ dashboard: Dashboard
+ tileElement: HTMLElement
+ moveTileToSection: jest.Mock
+ restoreLayout: jest.Mock
+ result: { current: ReturnType<typeof useTileGroupDrag> }
+ rerender: (props: { enabled: boolean }) => void
+ } => {
+ const dashboard = {
+ sourceBand: band(sourceKey),
+ openBand: band('group-ops'),
+ closedBand: band('group-closed', false),
+ dropZone: band(TAKE_OUT_DROP_ZONE_KEY, false),
+ }
+ const root = dashboardRoot(dashboard.sourceBand, dashboard.openBand, dashboard.closedBand, dashboard.dropZone)
+ const tileElement = document.createElement('div')
+ // A column is 100 pixels and a row 80, so this tile sits at column 3, row 2 of the band under it.
+ tileElement.getBoundingClientRect = () => ({ left: 300, top: 160 }) as DOMRect
+ dashboard.sourceBand.append(tileElement)
+ const placeholder = document.createElement('div')
+ placeholder.className = 'react-grid-placeholder'
+ dashboard.sourceBand.append(placeholder)
+ const moveTileToSection = jest.fn()
+ const restoreLayout = jest.fn()
+ const { result, rerender } = renderHook(
+ ({ enabled }: { enabled: boolean }) =>
+ useTileGroupDrag({
+ enabled,
+ sections: [],
+ rowHeight: 80,
+ margin: [0, 0],
+ layout,
+ moveTileToSection,
+ restoreLayout,
+ }),
+ { initialProps: { enabled: true } }
+ )
+ act(() => result.current.startTileDrag(draggedItem, tileElement))
+ return {
+ dashboard: { root, placeholder, ...dashboard },
+ tileElement,
+ moveTileToSection,
+ restoreLayout,
+ result,
+ rerender,
+ }
+ }
+
+ const drop = async (
+ result: { current: ReturnType<typeof useTileGroupDrag> },
+ tileElement: HTMLElement
+ ): Promise<void> => {
+ act(() =>
+ result.current.finishTileDrag(
+ draggedItem,
+ tileElement,
+ new MouseEvent('mouseup', { clientX: 10, clientY: 10 })
+ )
+ )
+ await Promise.resolve()
+ }
+
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ it.each<DropCase>([
+ {
+ name: 'on another band at the cell under the tile',
+ dropOn: (dashboard) => [dashboard.openBand],
+ moved: [1, 'group-ops', { x: 3, y: 2 }],
+ restored: false,
+ },
+ {
+ name: 'on a closed group, which has no cell',
+ dropOn: (dashboard) => [dashboard.closedBand],
+ moved: [1, 'group-closed', null],
+ restored: false,
+ },
+ {
+ name: 'on a closed group under the placeholder that followed it',
+ dropOn: (dashboard) => [dashboard.placeholder, dashboard.closedBand],
+ moved: [1, 'group-closed', null],
+ restored: false,
+ },
+ {
+ name: 'on the drop zone without a group to leave',
+ sourceKey: 'tiles-start',
+ dropOn: (dashboard) => [dashboard.dropZone],
+ moved: null,
+ restored: true,
+ },
+ {
+ name: 'on the drop zone, out of its group',
+ dropOn: (dashboard) => [dashboard.dropZone],
+ moved: [1, null, null],
+ restored: false,
+ },
+ {
+ name: 'inside its own band',
+ dropOn: (dashboard) => [dashboard.sourceBand],
+ moved: null,
+ restored: false,
+ },
+ {
+ name: 'in a gap after passing over another band',
+ passOver: (dashboard) => dashboard.openBand,
+ dropOn: (dashboard) => [dashboard.root],
+ moved: [1, 'group-ops', { x: 3, y: 2 }],
+ restored: false,
+ },
+ {
+ name: 'outside its dashboard',
+ dropOn: () => [document.body],
+ moved: null,
+ restored: true,
+ },
+ {
+ name: 'on a band of another dashboard',
+ dropOn: () => [dashboardRoot(band('group-ops')).firstElementChild!],
+ moved: null,
+ restored: true,
+ },
+ ])('a tile dropped $name', async ({ passOver, dropOn, sourceKey, moved, restored }) => {
+ const { dashboard, tileElement, moveTileToSection, restoreLayout, result } = setUp(sourceKey)
+
+ if (passOver) {
+ pointerAt(passOver(dashboard))
+ act(() => result.current.trackTileDrag(new MouseEvent('mousemove', { clientX: 10, clientY: 10 })))
+ expect(result.current.dropTargetKey).toBe('group-ops')
+ }
+ pointerAt(...dropOn(dashboard))
+ await drop(result, tileElement)
+
+ expect(moveTileToSection.mock.calls).toEqual(moved ? [moved] : [])
+ expect(restoreLayout.mock.calls).toEqual(restored ? [[layout]] : [])
+ })
+
+ it('ignores a drop once edit mode turns off mid-drag', async () => {
+ const { dashboard, tileElement, moveTileToSection, restoreLayout, result, rerender } = setUp()
+
+ rerender({ enabled: false })
+ expect(result.current.frozenSourceGrid).toBeNull()
+ pointerAt(dashboard.openBand)
+ await drop(result, tileElement)
+
+ expect(moveTileToSection).not.toHaveBeenCalled()
+ expect(restoreLayout).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/dashboards/frontend/useTileGroupDrag.ts b/products/dashboards/frontend/useTileGroupDrag.ts
new file mode 100644
index 000000000000..f090f169ced8
--- /dev/null
+++ b/products/dashboards/frontend/useTileGroupDrag.ts
@@ -0,0 +1,168 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import type { Layout, LayoutItem } from 'react-grid-layout'
+
+import { BREAKPOINT_COLUMN_COUNTS } from 'scenes/dashboard/dashboardUtils'
+
+import { type DashboardSection, getDropCell, isTileGroupSectionKey } from './dashboardTileSections'
+
+export const TAKE_OUT_DROP_ZONE_KEY = 'take-out-of-group'
+
+interface TileGroupDragProps {
+ enabled: boolean
+ sections: DashboardSection[]
+ rowHeight: number
+ margin: [number, number]
+ layout: Layout | undefined
+ moveTileToSection: (tileId: number, sectionKey: string | null, cell: { x: number; y: number } | null) => void
+ restoreLayout: (layout: Layout) => void
+}
+
+interface TileGroupDrag {
+ draggingTileId: string | null
+ dropTargetKey: string | null
+ frozenSourceGrid: { key: string; height: number } | null
+ showTakeOutDropZone: boolean
+ startTileDrag: (item: LayoutItem, element: HTMLElement | null) => void
+ trackTileDrag: (event: Event) => void
+ finishTileDrag: (item: LayoutItem | null, element: HTMLElement | null, event: Event) => void
+}
+
+/**
+ * The band of `dashboardRoot` under the pointer, or null when the pointer has left that dashboard.
+ * Undefined means the caller keeps the last band, because the pointer is in a gap between bands.
+ */
+function sectionKeyUnderPointer(event: Event, dashboardRoot: Element): string | null | undefined {
+ const { clientX, clientY } = event as MouseEvent
+ if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) {
+ return undefined
+ }
+ const elements = document
+ .elementsFromPoint(clientX, clientY)
+ // The source grid's placeholder follows the pointer out of its band, so it must not count as that band.
+ .filter((element) => !element.closest('.react-draggable-dragging, .react-grid-placeholder'))
+ for (const element of elements) {
+ const section = element.closest('[data-dashboard-section]')
+ if (section) {
+ // A page can show several dashboards, and their bands share keys like `tiles-start`.
+ return dashboardRoot.contains(section) ? section.getAttribute('data-dashboard-section') : null
+ }
+ }
+ return elements.some((element) => dashboardRoot.contains(element)) ? undefined : null
+}
+
+function dropKeyUnderPointer(
+ event: Event,
+ { dashboardRoot, sourceKey }: { dashboardRoot: Element; sourceKey: string }
+): string | null | undefined {
+ const key = sectionKeyUnderPointer(event, dashboardRoot)
+ return key === TAKE_OUT_DROP_ZONE_KEY && !isTileGroupSectionKey(sourceKey) ? null : key
+}
+
+export function useTileGroupDrag(props: TileGroupDragProps): TileGroupDrag {
+ const latest = useRef(props)
+ latest.current = props
+ const [draggingTileId, setDraggingTileId] = useState<string | null>(null)
+ const [dropTargetKey, setDropTargetKey] = useState<string | null>(null)
+ // A dragged tile grows its own grid, which would push the bands below away from the pointer.
+ const [frozenSourceGrid, setFrozenSourceGrid] = useState<{ key: string; height: number } | null>(null)
+ const drag = useRef<{
+ sourceKey: string
+ keyUnderPointer: string | null
+ dashboardRoot: Element
+ layoutAtStart: Layout
+ } | null>(null)
+
+ const stopTracking = useCallback((): void => {
+ drag.current = null
+ setDropTargetKey(null)
+ setDraggingTileId(null)
+ setFrozenSourceGrid(null)
+ }, [])
+
+ // Escape leaves edit mode without react-grid-layout ending its drag, so a late drop must not move a tile.
+ useEffect(() => {
+ if (!props.enabled) {
+ stopTracking()
+ }
+ }, [props.enabled, stopTracking])
+
+ const startTileDrag = useCallback((item: LayoutItem, element: HTMLElement | null): void => {
+ const section = element?.closest<HTMLElement>('[data-dashboard-section]')
+ const dashboardRoot = element?.closest('.dashboard-items-wrapper')
+ const sourceKey = section?.getAttribute('data-dashboard-section')
+ if (!section || !dashboardRoot || !sourceKey) {
+ return
+ }
+ drag.current = {
+ sourceKey,
+ keyUnderPointer: sourceKey,
+ dashboardRoot,
+ layoutAtStart: latest.current.layout ?? [],
+ }
+ const sourceGrid = section.querySelector<HTMLElement>('[data-dashboard-section-grid]')
+ setFrozenSourceGrid(sourceGrid ? { key: sourceKey, height: sourceGrid.offsetHeight } : null)
+ setDraggingTileId(item.i)
+ }, [])
+
+ const trackTileDrag = useCallback((event: Event): void => {
+ const current = drag.current
+ if (!current) {
+ return
+ }
+ const keyUnderPointer = dropKeyUnderPointer(event, current)
+ if (keyUnderPointer !== undefined) {
+ current.keyUnderPointer = keyUnderPointer
+ setDropTargetKey(keyUnderPointer === current.sourceKey ? null : keyUnderPointer)
+ }
+ }, [])
+
+ const finishTileDrag = useCallback(
+ (item: LayoutItem | null, element: HTMLElement | null, event: Event): void => {
+ const current = drag.current
+ stopTracking()
+ if (!current || !item || !latest.current.enabled) {
+ return
+ }
+ // Autoscroll moves bands under a still pointer, so read the band at the drop point.
+ const keyAtDrop = dropKeyUnderPointer(event, current)
+ const dropKey = keyAtDrop === undefined ? current.keyUnderPointer : keyAtDrop
+ // The source grid reports its own layout right after drag stop, with the tile still in it.
+ // Each change below waits for that report, so the report does not overwrite it.
+ if (dropKey === null) {
+ // The source grid has no lower edge, so it kept the tile at whatever row the drag reached.
+ queueMicrotask(() => latest.current.restoreLayout(current.layoutAtStart))
+ return
+ }
+ if (dropKey === current.sourceKey) {
+ return
+ }
+ // A closed group shows no grid, so a drop there has no cell and goes to the bottom of the group.
+ const grid = current.dashboardRoot.querySelector(`[data-dashboard-section-grid="${CSS.escape(dropKey)}"]`)
+ const { rowHeight, margin } = latest.current
+ const cell =
+ grid && element
+ ? getDropCell({
+ tileRect: element.getBoundingClientRect(),
+ gridRect: grid.getBoundingClientRect(),
+ cols: BREAKPOINT_COLUMN_COUNTS.sm,
+ rowHeight,
+ margin,
+ tileWidth: item.w,
+ })
+ : null
+ const sectionKey = dropKey === TAKE_OUT_DROP_ZONE_KEY ? null : dropKey
+ queueMicrotask(() => latest.current.moveTileToSection(Number(item.i), sectionKey, cell))
+ },
+ [stopTracking]
+ )
+
+ return {
+ draggingTileId,
+ dropTargetKey,
+ frozenSourceGrid,
+ showTakeOutDropZone: props.enabled && props.sections.at(-1)?.kind === 'group',
+ startTileDrag,
+ trackTileDrag,
+ finishTileDrag,
+ }
+}