:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(dashboards): add inline "+" tile insertion on grid hover (#65867)
Matt Pua9926619af1ca
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 3b5648ce61a5..44eaa78225b4 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -268,6 +268,7 @@ export const FEATURE_FLAGS = {CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analyticsCUSTOMER_PROFILE_CONFIG_BUTTON: 'customer-profile-config-button', // owner: @arthurdedeus #team-customer-analyticsDASHBOARD_AUTO_PREVIEW_LIMIT: 'dashboard-auto-preview-limit', // owner: @pauldambra #team-product-analytics+ DASHBOARD_INLINE_TILE_INSERTION: 'dashboard-inline-tile-insertion', // owner: @MattPua #team-analytics-platformDASHBOARD_LAYOUT_DISCARD_PROMPT: 'dashboard-layout-discard-prompt', // owner: @cory.s #team-analytics-platformDASHBOARD_QUICK_FILTERS_EXPERIMENT: 'dashboard-quick-filters-experiment', // owner: @vdekrijger #team-product-analytics multivariate=control,testDASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,newdiff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 1560b20f4a4b..ce94f5e105f4 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -7,6 +7,7 @@ import { now } from 'lib/dayjs'import { TimeToSeeDataPayload } from 'lib/internalMetrics'import { objectClean } from 'lib/utils/objects'import { BillingUsageInteractionProps } from 'scenes/billing/types'+import type { DashboardAddTileType } from 'scenes/dashboard/dashboardAddTileTypes'import { SharedMetric } from 'scenes/experiments/SharedMetrics/sharedMetricLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { ProductTourEvent } from 'scenes/product-tours/constants'@@ -586,6 +587,12 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportCustomChannelTypeRulesUpdated: (numRules: number) => ({ numRules }),reportPropertySelectOpened: true,reportCreatedDashboardFromModal: true,+ reportDashboardTileInsertedInline: (+ tileType: DashboardAddTileType,+ column: number,+ row: number,+ fullWidth: boolean+ ) => ({ tileType, column, row, fullWidth }),/** Dashboard created via PostHog web app from a template (new dashboard modal / template chooser). */reportWebDashboardCreatedFromTemplate: (payload: {dashboard_id: number@@ -1625,6 +1632,14 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportCreatedDashboardFromModal: async () => {posthog.capture('created new dashboard from modal')},+ reportDashboardTileInsertedInline: async ({ tileType, column, row, fullWidth }) => {+ posthog.capture('dashboard tile inserted inline', {+ tile_type: tileType,+ column,+ row,+ full_width: fullWidth,+ })+ },reportWebDashboardCreatedFromTemplate: async (payload) => {posthog.capture('dashboard created from template', {...payload,diff --git a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsxindex 4ece1bd70098..9a2a7682bd15 100644--- a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx+++ b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx@@ -8,7 +8,7 @@ import { Shortcut } from 'lib/components/Shortcuts/Shortcut'import { keyBinds } from 'lib/components/Shortcuts/shortcuts'import { FEATURE_FLAGS } from 'lib/constants'import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonMenu } from 'lib/lemon-ui/LemonMenu'+import { LemonMenu, LemonMenuItem } from 'lib/lemon-ui/LemonMenu'import { DashboardEventSource } from 'lib/utils/eventUsageLogic'import { MaxTool } from 'scenes/max/MaxTool'import { Scene } from 'scenes/sceneTypes'@@ -20,9 +20,64 @@ import { AccessControlLevel, AccessControlResourceType, DashboardMode } from '~/import { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'import { DashboardLoadAction, dashboardLogic } from './dashboardLogic'+export function getAddTileMenuItems({+ dashboardId,+ dashboardWidgetsEnabled,+ showAddInsightToDashboardModal,+ push,+ setAddWidgetModalOpen,+ onBeforeSelect,+}: {+ dashboardId: number+ dashboardWidgetsEnabled: boolean+ showAddInsightToDashboardModal: () => void+ push: (url: string) => void+ setAddWidgetModalOpen: (open: boolean) => void+ onBeforeSelect?: () => void+}): LemonMenuItem[] {+ const withBeforeSelect =+ (onClick: () => void): (() => void) =>+ () => {+ onBeforeSelect?.()+ onClick()+ }++ return [+ {+ label: 'Insight',+ onClick: withBeforeSelect(showAddInsightToDashboardModal),+ 'data-attr': 'dashboard-add-insight',+ },+ {+ label: 'Text card',+ onClick: withBeforeSelect(() => push(urls.dashboardTextTile(dashboardId, 'new'))),+ 'data-attr': 'dashboard-add-text-tile',+ },+ {+ label: 'Button',+ onClick: withBeforeSelect(() => push(urls.dashboardButtonTile(dashboardId, 'new'))),+ 'data-attr': 'dashboard-add-button-tile',+ },+ dashboardWidgetsEnabled+ ? {+ label: 'Widget',+ tag: 'new' as const,+ onClick: withBeforeSelect(() => setAddWidgetModalOpen(true)),+ 'data-attr': 'dashboard-add-widget',+ }+ : {+ label: 'Widget',+ tag: 'beta' as const,+ tooltip: 'Opens settings to enable the Dashboard widgets beta',+ onClick: withBeforeSelect(() => push(urls.featurePreview(FEATURE_FLAGS.DASHBOARD_WIDGETS))),+ 'data-attr': 'dashboard-add-widget-preview',+ },+ ]+}+export function DashboardAddTileButton(): JSX.Element | null {const { dashboard, dashboardWidgetsEnabled } = useValues(dashboardLogic)- const { loadDashboard, setAddWidgetModalOpen } = useActions(dashboardLogic)+ const { loadDashboard, setAddWidgetModalOpen, setPendingInsertion } = useActions(dashboardLogic)const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)const { push } = useActions(router)@@ -56,37 +111,15 @@ export function DashboardAddTileButton(): JSX.Element | null {userAccessLevel={dashboard.user_access_level}><LemonMenu- items={[- {- label: 'Insight',- onClick: showAddInsightToDashboardModal,- 'data-attr': 'dashboard-add-insight',- },- {- label: 'Text card',- onClick: () => push(urls.dashboardTextTile(dashboard.id, 'new')),- 'data-attr': 'dashboard-add-text-tile',- },- {- label: 'Button',- onClick: () => push(urls.dashboardButtonTile(dashboard.id, 'new')),- 'data-attr': 'dashboard-add-button-tile',- },- dashboardWidgetsEnabled- ? {- label: 'Widget',- tag: 'new' as const,- onClick: () => setAddWidgetModalOpen(true),- 'data-attr': 'dashboard-add-widget',- }- : {- label: 'Widget',- tag: 'beta' as const,- tooltip: 'Opens settings to enable the Dashboard widgets beta',- onClick: () => push(urls.featurePreview(FEATURE_FLAGS.DASHBOARD_WIDGETS)),- 'data-attr': 'dashboard-add-widget-preview',- },- ]}+ items={getAddTileMenuItems({+ dashboardId: dashboard.id,+ dashboardWidgetsEnabled,+ showAddInsightToDashboardModal,+ push,+ setAddWidgetModalOpen,+ // Adding from the header appends at the bottom; drop any stale inline-insertion target.+ onBeforeSelect: () => setPendingInsertion(null),+ })}><LemonButton type="primary" data-attr="dashboard-add-tile" size="small" icon={<IconPlusSmall />}>Adddiff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsxindex cd3c999daaf0..54e7290138b9 100644--- a/frontend/src/scenes/dashboard/DashboardItems.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx@@ -13,10 +13,14 @@ import { getDashboardWidgetFetchDisplayError } from '@posthog/products-dashboardimport { InsightCard } from 'lib/components/Cards/InsightCard'import { EditModeEdge } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonMenuItem } from 'lib/lemon-ui/LemonMenu'import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'+import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDashboardModalLogic'+import { getAddTileMenuItems } from 'scenes/dashboard/DashboardHeaderActions'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { BREAKPOINTS, BREAKPOINT_COLUMN_COUNTS, isWidgetTileVisibleOnPlacement } from 'scenes/dashboard/dashboardUtils'import { continueDragGestureInEditMode, continueResizeGestureInEditMode } from 'scenes/dashboard/editLayoutGesture'+import { InsertTileOverlay } from 'scenes/dashboard/InsertTileOverlay'import { useSurveyLinkedInsights } from 'scenes/surveys/hooks/useSurveyLinkedInsights'import { getBestSurveyOpportunityFunnel } from 'scenes/surveys/utils/opportunityDetection'import { urls } from 'scenes/urls'@@ -54,6 +58,7 @@ export function DashboardItems(): JSX.Element {dataColorThemeId,canEditDashboard,dashboardWidgetsEnabled,+ inlineTileInsertionEnabled,widgetResultsByTileId,widgetRefreshStatus,scrollToBottomSignal,@@ -74,7 +79,10 @@ export function DashboardItems(): JSX.Element {copyToDashboard,setTileOverride,setDashboardMode,+ setAddWidgetModalOpen,+ setPendingInsertion,} = useActions(dashboardLogic)+ const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)const { updateWidgetTile } = useAsyncActions(dashboardLogic)const { renameInsight } = useActions(insightsModel)const { reportDashboardTileRepositioned } = useActions(eventUsageLogic)@@ -200,6 +208,28 @@ export function DashboardItems(): JSX.Element {const spacingFactor = effectiveZoom < 1 ? 0.9 : 1const margin = useMemo(() => BASE_MARGIN.map((m) => m * spacingFactor) as [number, number], [spacingFactor])+ const getInsertMenuItems = useCallback(+ (targetX: number, targetY: number, targetW?: number): LemonMenuItem[] =>+ dashboard+ ? getAddTileMenuItems({+ dashboardId: dashboard.id,+ dashboardWidgetsEnabled,+ showAddInsightToDashboardModal,+ push,+ setAddWidgetModalOpen,+ onBeforeSelect: () => setPendingInsertion({ x: targetX, y: targetY, w: targetW ?? null }),+ })+ : [],+ [+ dashboard,+ dashboardWidgetsEnabled,+ showAddInsightToDashboardModal,+ push,+ setAddWidgetModalOpen,+ setPendingInsertion,+ ]+ )+const showResizeHandles = layoutEditMode && !isMobileView && isEditablePlacement && !isLayoutZoomToggledconst showEditingControls = isEditablePlacement || layoutEditModeconst showDetailsControls =@@ -606,6 +636,20 @@ export function DashboardItems(): JSX.Element {}})}</ReactGridLayout>+ {isEditablePlacement && inlineTileInsertionEnabled && (+ <InsertTileOverlay+ layout={layouts['sm']}+ gridWidth={gridWidth}+ cols={BREAKPOINT_COLUMN_COUNTS.sm}+ rowHeight={rowHeight}+ marginX={margin[0]}+ marginY={margin[1]}+ canEditDashboard={canEditDashboard}+ isMobileView={isMobileView}+ disabled={resizingTileId !== null}+ getMenuItems={getInsertMenuItems}+ />+ )}</div>)}{dashboardStreaming && (diff --git a/frontend/src/scenes/dashboard/InsertTileOverlay.tsx b/frontend/src/scenes/dashboard/InsertTileOverlay.tsxnew file mode 100644index 000000000000..b1c349ed5e62--- /dev/null+++ b/frontend/src/scenes/dashboard/InsertTileOverlay.tsx@@ -0,0 +1,251 @@+import clsx from 'clsx'+import { useLayoutEffect, useMemo, useRef, useState } from 'react'+import { Layout } from 'react-grid-layout'++import { IconPlusSmall } from '@posthog/icons'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonMenu, LemonMenuItem } from 'lib/lemon-ui/LemonMenu'+import { computeBoundaries, InsertZone, LineSegment, TileRect } from 'scenes/dashboard/insertTileGeometry'++interface InsertTileOverlayProps {+ // `layout` is unused at render but its identity change drives re-measuring (effect dep).+ layout: Layout | undefined+ gridWidth: number+ cols: number+ rowHeight: number+ marginX: number+ marginY: number+ canEditDashboard: boolean+ isMobileView: boolean+ disabled?: boolean+ getMenuItems: (targetX: number, targetY: number, targetW?: number) => LemonMenuItem[]+}++export function InsertTileOverlay({+ layout,+ gridWidth,+ cols,+ rowHeight,+ marginX,+ marginY,+ canEditDashboard,+ isMobileView,+ disabled,+ getMenuItems,+}: InsertTileOverlayProps): JSX.Element | null {+ const containerRef = useRef<HTMLDivElement>(null)+ const [tileRects, setTileRects] = useState<TileRect[]>([])++ const active = canEditDashboard && !isMobileView && !disabled++ // Measure the rendered tile boxes; positioning, clipping, and drop zones all work off these so the+ // line lands in the real gaps regardless of zoom, padding, or grid-vs-render drift.+ useLayoutEffect(() => {+ if (!active) {+ return+ }+ const measure = (): void => {+ const container = containerRef.current+ const parent = container?.parentElement+ if (!container || !parent) {+ return+ }+ const base = container.getBoundingClientRect()+ const rects: TileRect[] = []+ parent.querySelectorAll('.react-grid-item').forEach((el) => {+ if (el.classList.contains('react-grid-placeholder')) {+ return+ }+ const r = el.getBoundingClientRect()+ rects.push({+ top: r.top - base.top,+ bottom: r.bottom - base.top,+ left: r.left - base.left,+ right: r.right - base.left,+ })+ })+ setTileRects(rects)+ }+ measure()+ const parent = containerRef.current!.parentElement!+ const resizeObserver = new ResizeObserver(measure)+ resizeObserver.observe(parent)+ // react-grid-layout repositions tiles via CSS transform without changing the container size, so+ // a ResizeObserver alone goes stale. Watch the grid's style/child mutations to re-measure on move.+ const gridEl = parent.querySelector('.react-grid-layout')+ const mutationObserver = new MutationObserver(measure)+ if (gridEl) {+ mutationObserver.observe(gridEl, {+ attributes: true,+ attributeFilter: ['style'],+ subtree: true,+ childList: true,+ })+ }+ window.addEventListener('resize', measure)+ return () => {+ resizeObserver.disconnect()+ mutationObserver.disconnect()+ window.removeEventListener('resize', measure)+ }+ }, [active, layout, gridWidth, rowHeight, marginY])++ const boundaries = useMemo(+ () => computeBoundaries(tileRects, { gridWidth, cols, marginX, marginY, rowHeight }),+ [tileRects, gridWidth, cols, marginX, marginY, rowHeight]+ )++ if (!active) {+ return null+ }++ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div ref={containerRef} className="absolute inset-0 pointer-events-none" style={{ zIndex: 6 }}>+ {boundaries.map((boundary) => (+ <InsertionStrip+ key={Math.round(boundary.lineY)}+ lineY={boundary.lineY}+ gridRow={boundary.gridRow}+ gridWidth={gridWidth}+ cols={cols}+ segments={boundary.segments}+ zones={boundary.zones}+ getMenuItems={getMenuItems}+ />+ ))}+ </div>+ )+}++// Generous transparent hover zone so the thin line/"+" is easy to target (the visible bits stay+// centered on the row boundary). Larger than the inter-row gap, so it bleeds a little into the+// adjacent tiles — that's the intended trade-off for a comfortable hit area.+const HOVER_HIT_HEIGHT = 28+// Keep the "+" fully on the strip when the cursor is near either end.+const BUTTON_EDGE_PADDING = 16++interface InsertTarget {+ targetX: number+ targetY: number+ targetW?: number+}++function InsertionStrip({+ lineY,+ gridRow,+ gridWidth,+ cols,+ segments,+ zones,+ getMenuItems,+}: {+ lineY: number+ gridRow: number+ gridWidth: number+ cols: number+ segments: LineSegment[]+ zones: InsertZone[]+ getMenuItems: (targetX: number, targetY: number, targetW?: number) => LemonMenuItem[]+}): JSX.Element {+ const stripRef = useRef<HTMLDivElement>(null)+ const buttonRef = useRef<HTMLDivElement>(null)+ // Where the insert will land, frozen with the button while the menu is open so it matches the spot+ // the user opened the menu over.+ const targetRef = useRef<InsertTarget | null>(null)+ // Freeze the follow while the pointer is pressed: a click emits tiny mousemoves between mousedown+ // and mouseup, and repositioning the button mid-press moves it out from under the stationary cursor+ // so mouseup lands elsewhere and the browser never fires `click` — that's the lost first click.+ const pointerDownRef = useRef(false)+ const [menuOpen, setMenuOpen] = useState(false)++ const revealClass = menuOpen ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'++ // Move the "+" to follow the cursor by writing to the DOM directly — no setState, so the LemonMenu+ // subtree never re-renders during a hover/move. Frozen while pressed (see pointerDownRef) and while+ // the menu is open so it stays anchored under the popover.+ const followCursor = (clientX: number): void => {+ if (menuOpen || pointerDownRef.current || !buttonRef.current) {+ return+ }+ const rect = stripRef.current?.getBoundingClientRect()+ if (rect) {+ const x = Math.min(Math.max(clientX - rect.left, BUTTON_EDGE_PADDING), gridWidth - BUTTON_EDGE_PADDING)+ // Only show the "+" in a real gap (not on top of a tile). Over a tile bordering the line we+ // insert into that column; over empty gap space we insert full-width so it still lands at the+ // line (compaction would otherwise float a column-width tile up above it).+ const inGap = segments.some((segment) => x >= segment.left && x <= segment.left + segment.width)+ buttonRef.current.style.display = inGap ? '' : 'none'+ if (!inGap) {+ return+ }+ const zone = zones.find((z) => x >= z.left && x <= z.right)+ targetRef.current = zone+ ? { targetX: zone.targetX, targetY: zone.targetY }+ : { targetX: 0, targetY: gridRow, targetW: cols }+ // Our Tailwind config sets `important: true`, so the `left-4` class is `left !important` and+ // would beat a plain inline `left`. Write with priority so the follow position actually wins.+ buttonRef.current.style.setProperty('left', `${x}px`, 'important')+ }+ }++ // Build items when the menu opens, from the frozen target. Stable otherwise so the dropdown overlay+ // isn't rebuilt under the pointer on unrelated re-renders.+ const menuItems = useMemo(+ () => {+ const target = targetRef.current+ return target ? getMenuItems(target.targetX, target.targetY, target.targetW) : []+ },+ // menuOpen forces a rebuild on open so targetRef (frozen there) picks the spot under the cursor.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [getMenuItems, menuOpen]+ )++ return (+ <div+ ref={stripRef}+ className="group absolute pointer-events-auto"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ left: 0, width: gridWidth, top: lineY - HOVER_HIT_HEIGHT / 2, height: HOVER_HIT_HEIGHT }}+ onMouseEnter={(e) => followCursor(e.clientX)}+ onMouseMove={(e) => followCursor(e.clientX)}+ onMouseDown={() => (pointerDownRef.current = true)}+ onMouseUp={() => (pointerDownRef.current = false)}+ onMouseLeave={() => (pointerDownRef.current = false)}+ >+ {segments.map((segment, index) => (+ <div+ key={index}+ className={clsx(+ 'absolute top-1/2 -translate-y-1/2 h-0.5 bg-accent transition-opacity',+ revealClass+ )}+ // eslint-disable-next-line react/forbid-dom-props+ style={{ left: segment.left, width: segment.width }}+ />+ ))}+ <div+ ref={buttonRef}+ // `left` is set imperatively in followCursor (not via the style prop) so the followed+ // position survives the open/close re-render and the menu stays anchored under the cursor.+ className={clsx(+ 'absolute left-4 top-1/2 -translate-x-1/2 -translate-y-1/2 transition-opacity',+ revealClass+ )}+ >+ <LemonMenu items={menuItems} onVisibilityChange={setMenuOpen}>+ <LemonButton+ size="xsmall"+ type="primary"+ icon={<IconPlusSmall />}+ sideIcon={null}+ data-attr="dashboard-inline-add-tile"+ >+ Add+ </LemonButton>+ </LemonMenu>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/dashboard/dashboardAddTileTypes.ts b/frontend/src/scenes/dashboard/dashboardAddTileTypes.tsnew file mode 100644index 000000000000..6bd0e308cfde--- /dev/null+++ b/frontend/src/scenes/dashboard/dashboardAddTileTypes.ts@@ -0,0 +1 @@+export type DashboardAddTileType = 'insight' | 'text_card' | 'button' | 'widget'diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex bd73569bd0f1..5249f76216a8 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -21,6 +21,10 @@ import { ResponsiveLayouts } from 'react-grid-layout'import { LemonDialog, lemonToast } from '@posthog/lemon-ui'import type { DashboardWidgetRunResultApi } from '@posthog/products-dashboards/frontend/generated/api.schemas'import { isWidgetConfigValidationError, updateDashboardWidgetTile } from '@posthog/products-dashboards/frontend/utils'+import {+ DASHBOARD_WIDGET_CATALOG,+ getDashboardWidgetCatalogEntry,+} from '@posthog/products-dashboards/frontend/widget_types/catalog'import { DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE } from '@posthog/products-dashboards/frontend/widgets/constants'import {applyIssueMetadataToWidgetListResult,@@ -43,7 +47,12 @@ import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogicimport { shouldCancelQuery } from 'lib/utils/requests'import { toParams } from 'lib/utils/url'import { BREAKPOINTS, dashboardToSaveableTemplate, getDashboardTileDisplayName } from 'scenes/dashboard/dashboardUtils'-import { calculateDuplicateLayout, calculateLayouts } from 'scenes/dashboard/tileLayouts'+import {+ calculateDuplicateLayout,+ calculateInsertionLayout,+ calculateLayouts,+ DEFAULT_INSERTED_TILE_SIZE,+} from 'scenes/dashboard/tileLayouts'import {chunkTileIds,fetchRunWidgets,@@ -168,6 +177,13 @@ export enum RefreshDashboardItemsAction {// to stop kea typegen getting confusedexport type DashboardTileLayoutUpdatePayload = Pick<DashboardTile, 'id' | 'layouts'>+export interface PendingInsertion {+ x: number+ y: number+ // Width override for the full-width fallback when the hovered column can't anchor the tile; else null.+ w: number | null+}+const tileLayoutsFromDashboard = (dashboard: DashboardType<QueryBasedInsightModel> | null | undefined): Record<number, DashboardTile['layouts']> => {@@ -370,6 +386,8 @@ export const dashboardLogic = kea<dashboardLogicType>([* Dashboard layout & tiles.*/updateLayouts: (layouts: ResponsiveLayouts) => ({ layouts }),+ setPendingInsertion: (pendingInsertion: PendingInsertion | null) => ({ pendingInsertion }),+ applyPendingInsertion: true,updateContainerWidth: (containerWidth: number, columns: number) => ({ containerWidth, columns }),updateTileColor: (tileId: number, color: InsightColor | null) => ({ tileId, color }),toggleTileDescription: (tileId: number) => ({ tileId }),@@ -1096,6 +1114,16 @@ export const dashboardLogic = kea<dashboardLogicType>([},},],+ pendingInsertion: [+ null as PendingInsertion | null,+ {+ setPendingInsertion: (_, { pendingInsertion }) => pendingInsertion,+ // Clear on a real mode switch, but not on mode === null — the text/button add flow routes through it.+ setDashboardMode: (state, { mode }) => (mode != null ? null : state),+ // No hideAddInsightToDashboardModal handler on purpose: it fires as the insight is added, so+ // clearing there would drop the target before the tile lands.+ },+ ],urlSearchParamsAtEditModeEntry: [null as { filters?: unknown; variables?: unknown } | null,{@@ -1650,6 +1678,10 @@ export const dashboardLogic = kea<dashboardLogicType>([return !!featureFlags[FEATURE_FLAGS.DASHBOARD_WIDGETS]},],+ inlineTileInsertionEnabled: [+ (s) => [s.featureFlags],+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.DASHBOARD_INLINE_TILE_INSERTION],+ ],insightTiles: [(s) => [s.tiles],(tiles) => tiles.filter((t) => !!t.insight).filter((i) => !i.insight?.deleted),@@ -1956,6 +1988,9 @@ export const dashboardLogic = kea<dashboardLogicType>([beforeUnmount: () => {cache.widgetTileRefreshScheduler?.cancelAll()actions.abortAnyRunningQuery()+ // Bound the inline-insertion target's lifetime to this mount, so a never-consumed target+ // (e.g. an add flow abandoned by navigating away) can't reposition a tile on a later visit.+ cache.tileIdsBeforeInsertion = undefined},})),sharedListeners(({ values, props, actions }) => ({@@ -2094,6 +2129,94 @@ export const dashboardLogic = kea<dashboardLogicType>([actions.loadDashboard({ action: DashboardLoadAction.Update })}},+ setPendingInsertion: ({ pendingInsertion }) => {+ // Snapshot current tile ids so we can identify the tile the add flow appends afterwards.+ cache.tileIdsBeforeInsertion = pendingInsertion ? new Set((values.tiles || []).map((t) => t.id)) : undefined+ },+ applyPendingInsertion: async () => {+ // Capture before setPendingInsertion(null) below clears it.+ const slot = values.pendingInsertion+ const previousTileIds = cache.tileIdsBeforeInsertion as Set<number> | undefined+ if (!slot || !previousTileIds) {+ return+ }++ // Load-bearing assumption: exactly one unknown tile appeared since the snapshot and it is the+ // one the add flow just created. A concurrent arrival (background refresh, a collaborator's add)+ // in this window could be mis-targeted — blast radius is one tile's layout, which we accept.+ const newTile = (values.tiles || []).find((tile) => !tile.deleted && !previousTileIds.has(tile.id))+ if (!newTile) {+ // The appended tile hasn't reached state yet; a later arrival signal will retry.+ return+ }++ // Clear before persisting so the resulting updateDashboardSuccess doesn't re-enter this listener.+ actions.setPendingInsertion(null)++ const smLayout = values.layouts?.sm+ const newTileLayoutEntry = smLayout?.find((l) => String(l.i) === String(newTile.id))+ const w = slot.w ?? newTileLayoutEntry?.w ?? DEFAULT_INSERTED_TILE_SIZE.w+ const h = newTileLayoutEntry?.h ?? DEFAULT_INSERTED_TILE_SIZE.h++ const { newTileLayout, tilesToUpdate } = calculateInsertionLayout(+ smLayout,+ newTile.id,+ slot.y,+ slot.x,+ w,+ h+ )++ // Apply optimistically so the grid reflows immediately.+ const shiftById = new Map(tilesToUpdate.map((t) => [t.id, t.layouts.sm]))+ const newSmLayout = (smLayout || []).map((l) => {+ if (String(l.i) === String(newTile.id)) {+ return { ...l, ...newTileLayout.sm }+ }+ const shifted = shiftById.get(parseInt(l.i))+ return shifted ? { ...l, ...shifted } : l+ })+ actions.updateLayouts({ ...values.layouts, sm: newSmLayout })++ // The inline insert has now landed at the line — report it (outcome, vs the option-clicked intent).+ const insertedTileType = newTile.text+ ? 'text_card'+ : newTile.button_tile+ ? 'button'+ : newTile.widget+ ? 'widget'+ : 'insight'+ eventUsageLogic.actions.reportDashboardTileInsertedInline(insertedTileType, slot.x, slot.y, slot.w != null)++ // In edit mode the change is saved with the rest of the edit session.+ if (values.layoutEditMode) {+ return+ }++ // Persist the repositioning (same raw-PATCH shape as duplicateTile / saveEditModeChanges).+ // TODO: drop this follow-up request once the tile-create endpoints can insert at a position+ // (and reflow the displaced tiles) server-side, so an inline insert is a single round trip.+ try {+ const response: DashboardType<InsightModel> = await api.update(+ `api/environments/${values.currentTeamId}/dashboards/${props.id}`,+ {+ tiles: [...tilesToUpdate, { id: newTile.id, layouts: newTileLayout }],+ }+ )+ const updated = getQueryBasedDashboard(response)+ if (updated) {+ dashboardsModel.actions.updateDashboardSuccess(updated)+ }+ } catch (e) {+ lemonToast.error('Could not position the new tile: ' + String(e))+ }+ },+ [dashboardsModel.actionTypes.updateDashboardSuccess]: ({ dashboard }) => {+ // Text/button (via updateDashboard) and widget (client-merged) tiles arrive through here.+ if (dashboard?.id === props.id) {+ actions.applyPendingInsertion()+ }+ },[dashboardsModel.actionTypes.updateDashboardInsight]: ({ insight, extraDashboardIds, sourceDashboardId }) => {if (sourceDashboardId != null && sourceDashboardId !== props.id) {// Same rationale as the reducer: ignore refresh payloads scoped to another dashboard.@@ -2600,14 +2723,34 @@ export const dashboardLogic = kea<dashboardLogicType>([try {const previousWidgetTileIds = new Set(values.widgetTiles.map((tile) => tile.id))+ // Inline insertion: create the widget at the chosen slot instead of the backend's+ // default bottom placement, and let applyPendingInsertion shift existing tiles down.+ // Only single-widget adds insert positionally — applyPendingInsertion repositions one+ // tile, so a multi-select add can't be cleanly inserted at a single slot; it appends.+ if (values.pendingInsertion && widgets.length !== 1) {+ actions.setPendingInsertion(null)+ }+ const insertSlot = widgets.length === 1 ? values.pendingInsertion : null+ const widgetsPayload = widgets.map(({ widgetType, config }) => {+ if (!insertSlot) {+ return { widget_type: widgetType, config }+ }+ const defaultLayout =+ widgetType in DASHBOARD_WIDGET_CATALOG+ ? getDashboardWidgetCatalogEntry(widgetType).defaultLayout+ : undefined+ const w = insertSlot.w ?? defaultLayout?.w ?? DEFAULT_INSERTED_TILE_SIZE.w+ const h = defaultLayout?.h ?? DEFAULT_INSERTED_TILE_SIZE.h+ return {+ widget_type: widgetType,+ config,+ layouts: { sm: { x: insertSlot.x, y: insertSlot.y, w, h } },+ }+ })+const response = await api.create(`api/environments/${teamLogic.values.currentTeamId}/dashboards/${dashboardId}/widgets/batch/`,- {- widgets: widgets.map(({ widgetType, config }) => ({- widget_type: widgetType,- config,- })),- }+ { widgets: widgetsPayload })const createdTiles = findNewlyAddedWidgetTiles(previousWidgetTileIds, response.tiles)if (createdTiles.length > 0 && values.dashboard?.id === dashboardId) {@@ -2618,9 +2761,10 @@ export const dashboardLogic = kea<dashboardLogicType>([if (dashboard) {dashboardsModel.actions.updateDashboardSuccess(dashboard)- // New tiles are stacked at the bottom (backend), so ask the view to scroll- // down once they've rendered to reveal what was just added.- actions.requestScrollToBottom()+ // Only auto-scroll when the new tiles actually went to the bottom.+ if (!insertSlot) {+ actions.requestScrollToBottom()+ }}}@@ -2826,6 +2970,8 @@ export const dashboardLogic = kea<dashboardLogicType>([actions.dashboardNotFound()return // We hit a 404}+ // Insight tiles arrive via a dashboard reload; reposition to the pending insertion row.+ actions.applyPendingInsertion()},sharedListeners.handleDashboardLoadComplete,],diff --git a/frontend/src/scenes/dashboard/insertTileGeometry.test.ts b/frontend/src/scenes/dashboard/insertTileGeometry.test.tsnew file mode 100644index 000000000000..e4b411fc179f--- /dev/null+++ b/frontend/src/scenes/dashboard/insertTileGeometry.test.ts@@ -0,0 +1,106 @@+import { computeBoundaries, computeSegments, computeZones, GridGeometry, TileRect } from './insertTileGeometry'++describe('insertTileGeometry', () => {+ const rect = (top: number, bottom: number, left: number, right: number): TileRect => ({ top, bottom, left, right })++ describe('computeSegments', () => {+ // A clean gap (no tile crosses the line) must draw the line full width — the "line stopped short of+ // empty space" regression. A tile the line passes through must be cut out, padded into the gutter —+ // the "line slices across the card" regression.+ it.each([+ {+ name: 'no tile on the line → full-width segment',+ lineY: 100,+ tiles: [rect(0, 90, 0, 600), rect(110, 200, 0, 600)],+ expected: [{ left: 0, width: 600 }],+ },+ {+ name: 'a straddling tile is cut out (padded by half the margin)',+ lineY: 100,+ tiles: [rect(50, 150, 300, 600)],+ expected: [{ left: 0, width: 292 }],+ },+ {+ name: 'tile straddling the left leaves only the right run',+ lineY: 100,+ tiles: [rect(50, 150, 0, 300)],+ expected: [{ left: 308, width: 292 }],+ },+ {+ name: 'two straddling columns leave the middle gutter',+ lineY: 100,+ tiles: [rect(50, 150, 0, 290), rect(50, 150, 310, 600)],+ expected: [{ left: 298, width: 4 }],+ },+ ])('$name', ({ lineY, tiles, expected }) => {+ expect(computeSegments(lineY, tiles, 600, 16)).toEqual(expected)+ })+ })++ describe('computeZones', () => {+ const unit = 96 // rowHeight 80 + marginY 16+ const colUnit = 50++ it('a tile whose top is on the line yields a drop zone at that row', () => {+ // tile at grid row 5 (top 5*96 = 480), line sits in the gap just above it+ expect(computeZones(472, [rect(480, 700, 0, 300)], unit, colUnit, 16)).toEqual([+ { left: 0, right: 300, targetX: 0, targetY: 5 },+ ])+ })++ it('a tile whose bottom is on the line yields an append-below zone', () => {+ // tile occupies rows 0..4, bottom at 5*96 - 16 = 464; appending lands at row 5+ expect(computeZones(472, [rect(0, 464, 0, 300)], unit, colUnit, 16)).toEqual([+ { left: 0, right: 300, targetX: 0, targetY: 5 },+ ])+ })++ it('targetX comes from the tile column, so right-column tiles insert right', () => {+ expect(computeZones(472, [rect(480, 700, 300, 600)], unit, colUnit, 16)).toEqual([+ { left: 300, right: 600, targetX: 6, targetY: 5 },+ ])+ })++ it('a tile not bordering the line yields no zone (empty column above the line)', () => {+ expect(computeZones(472, [rect(0, 100, 0, 300)], unit, colUnit, 16)).toEqual([])+ })++ it('a stacked tile-above and tile-below at the same boundary dedupe to one zone', () => {+ // above ends at 464 (row 5), below starts at 480 (row 5) — both map to column 0, row 5+ expect(computeZones(472, [rect(0, 464, 0, 300), rect(480, 700, 0, 300)], unit, colUnit, 16)).toEqual([+ { left: 0, right: 300, targetX: 0, targetY: 5 },+ ])+ })+ })++ describe('computeBoundaries', () => {+ const geometry: GridGeometry = { gridWidth: 600, cols: 12, marginX: 16, marginY: 16, rowHeight: 80 }++ it('offers no line above the first row, a line between rows, and an append line below', () => {+ // two stacked full-width tiles: rows 0..4 (top 0, bottom 464) and rows 5..9 (top 480, bottom 944)+ const boundaries = computeBoundaries([rect(0, 464, 0, 600), rect(480, 944, 0, 600)], geometry)++ // one line in the gap (above the second tile) + one append line below the lowest tile — never above row 0+ expect(boundaries.map((b) => b.gridRow)).toEqual([5, 10])+ expect(boundaries[0].lineY).toEqual(472) // 480 - marginY/2+ expect(boundaries[1].lineY).toEqual(952) // 944 + marginY/2+ })++ it('returns nothing for an empty board', () => {+ expect(computeBoundaries([], geometry)).toEqual([])+ })++ it('a tile starting partway down a taller neighbour still gets its own line', () => {+ // left tile spans rows 0..9; right tile starts at row 5 — the line above the right tile must exist,+ // clipped behind the left tile (so it only shows in the right column's gutter onward)+ const boundaries = computeBoundaries([rect(0, 944, 0, 290), rect(480, 944, 310, 600)], geometry)+ const line = boundaries.find((b) => b.gridRow === 5)++ expect(line).not.toBeUndefined()+ // the left tile straddles this line, so the segment starts past it (into the gutter)+ expect(line!.segments[0].left).toBeGreaterThan(290)+ // the drop zone is the right column+ expect(line!.zones).toEqual([{ left: 310, right: 600, targetX: 6, targetY: 5 }])+ })+ })+})diff --git a/frontend/src/scenes/dashboard/insertTileGeometry.ts b/frontend/src/scenes/dashboard/insertTileGeometry.tsnew file mode 100644index 000000000000..5c4ae2670348--- /dev/null+++ b/frontend/src/scenes/dashboard/insertTileGeometry.ts@@ -0,0 +1,158 @@+// Pure geometry for the inline tile-insert overlay. Kept free of React so it can be unit-tested:+// the line clipping and drop-zone rules here are exactly where the visual bugs lived, and they're+// cheap to pin down with a table of cases.++export interface LineSegment {+ left: number+ width: number+}++export interface TileRect {+ top: number+ bottom: number+ left: number+ right: number+}++/**+ * A column span where dropping a tile lands it at the line: above a tile whose top is on the line+ * (push that tile down) or below a tile whose bottom is on the line (append under it). Over these,+ * insertion stays column-aware; elsewhere in the gap it falls back to a full-width tile at the line.+ */+export interface InsertZone {+ left: number+ right: number+ targetX: number+ targetY: number+}++export interface InsertBoundary {+ lineY: number+ gridRow: number+ segments: LineSegment[]+ zones: InsertZone[]+}++export interface GridGeometry {+ gridWidth: number+ cols: number+ marginX: number+ marginY: number+ rowHeight: number+}++// Tile tops within this many px are treated as the same row (sub-pixel rounding from getBoundingClientRect).+const EDGE_MERGE_PX = 4++// The full width minus any rendered tile the line's pixel passes through, so the line reads as passing+// behind the cards instead of slicing across them. Covered spans are padded into the column gutter so+// the line doesn't peek through the margin right next to a covered tile.+export function computeSegments(+ lineY: number,+ tileRects: TileRect[],+ gridWidth: number,+ marginX: number+): LineSegment[] {+ const covered = tileRects+ .filter((rect) => rect.top < lineY && rect.bottom > lineY)+ .map(+ (rect) =>+ [Math.max(0, rect.left - marginX / 2), Math.min(gridWidth, rect.right + marginX / 2)] as [+ number,+ number,+ ]+ )+ .sort((a, b) => a[0] - b[0])++ const merged: Array<[number, number]> = []+ for (const interval of covered) {+ const last = merged[merged.length - 1]+ if (last && interval[0] <= last[1]) {+ last[1] = Math.max(last[1], interval[1])+ } else {+ merged.push([...interval])+ }+ }++ const segments: LineSegment[] = []+ let cursor = 0+ for (const [start, end] of merged) {+ if (start > cursor) {+ segments.push({ left: cursor, width: start - cursor })+ }+ cursor = Math.max(cursor, end)+ }+ if (cursor < gridWidth) {+ segments.push({ left: cursor, width: gridWidth - cursor })+ }+ return segments+}++// Column drop zones for a line: a tile whose top sits on the line (insert above it, pushing it down)+// or whose bottom sits on the line (append directly below). targetY comes from the measured px / row+// unit, exact since react-grid-layout positions tiles at row*unit. Deduped per column + row.+export function computeZones(+ lineY: number,+ tileRects: TileRect[],+ unit: number,+ colUnit: number,+ marginY: number+): InsertZone[] {+ const seen = new Set<string>()+ const zones: InsertZone[] = []+ for (const rect of tileRects) {+ let targetY: number | null = null+ if (Math.abs(rect.top - lineY) <= marginY) {+ targetY = Math.round(rect.top / unit)+ } else if (Math.abs(rect.bottom - lineY) <= marginY) {+ targetY = Math.round(rect.bottom / unit)+ }+ if (targetY === null) {+ continue+ }+ const targetX = Math.round(rect.left / colUnit)+ const key = `${targetX}:${targetY}`+ if (seen.has(key)) {+ continue+ }+ seen.add(key)+ zones.push({ left: rect.left, right: rect.right, targetX, targetY })+ }+ return zones+}++// Insert boundaries derived from the rendered tiles: a line above each distinct tile-top (the gap+// before it) plus one below the lowest tile. The very top edge is skipped — no inserting above the+// board. Each line's grid row is recovered from its pixel position for the actual insert.+export function computeBoundaries(tileRects: TileRect[], geometry: GridGeometry): InsertBoundary[] {+ if (!tileRects.length) {+ return []+ }+ const { gridWidth, cols, marginX, marginY, rowHeight } = geometry+ const unit = rowHeight + marginY+ const colUnit = (gridWidth - marginX * (cols - 1)) / cols + marginX+ const minTop = Math.min(...tileRects.map((r) => r.top))+ const maxBottom = Math.max(...tileRects.map((r) => r.bottom))++ // Distinct tile-top edges (rounded to merge tiles that share a row), excluding the first row.+ const edges = new Map<number, number>()+ for (const rect of tileRects) {+ if (rect.top - minTop < marginY) {+ continue+ }+ edges.set(Math.round(rect.top / EDGE_MERGE_PX) * EDGE_MERGE_PX, rect.top)+ }++ const build = (lineY: number, gridRow: number): InsertBoundary => ({+ lineY,+ gridRow,+ segments: computeSegments(lineY, tileRects, gridWidth, marginX),+ zones: computeZones(lineY, tileRects, unit, colUnit, marginY),+ })++ const result = Array.from(edges.values())+ .sort((a, b) => a - b)+ .map((edge) => build(edge - marginY / 2, Math.round(edge / unit)))+ result.push(build(maxBottom + marginY / 2, Math.round(maxBottom / unit)))+ return result+}diff --git a/frontend/src/scenes/dashboard/tileLayouts.test.ts b/frontend/src/scenes/dashboard/tileLayouts.test.tsindex e340fcdb8107..d285c5dddc3f 100644--- a/frontend/src/scenes/dashboard/tileLayouts.test.ts+++ b/frontend/src/scenes/dashboard/tileLayouts.test.ts@@ -1,6 +1,6 @@import { Layout, LayoutItem } from 'react-grid-layout'-import { calculateDuplicateLayout, calculateLayouts } from 'scenes/dashboard/tileLayouts'+import { calculateDuplicateLayout, calculateInsertionLayout, calculateLayouts } from 'scenes/dashboard/tileLayouts'import { DashboardLayoutSize, DashboardTile, QueryBasedInsightModel, TileLayout } from '~/types'@@ -239,3 +239,106 @@ describe('calculateDuplicateLayout', () => {expect((result.duplicateLayouts as any).xs).toBeUndefined()})})++describe('calculateInsertionLayout', () => {+ const smLayout = (i: string, x: number, y: number, w: number, h: number): LayoutItem => ({ i, x, y, w, h })++ it.each([+ {+ name: 'inserting into the left column leaves the right column untouched',+ layout: [smLayout('1', 0, 0, 6, 5), smLayout('2', 6, 0, 6, 5)],+ newTileId: 9,+ targetX: 0,+ targetY: 0,+ w: 6,+ h: 2,+ expected: {+ newTileLayout: { sm: { x: 0, y: 0, w: 6, h: 2 } },+ tilesToUpdate: [{ id: 1, layouts: { sm: { x: 0, y: 2, w: 6, h: 5 } } }],+ },+ },+ {+ name: 'inserting into the right column pushes only the right column',+ layout: [smLayout('1', 0, 0, 6, 5), smLayout('2', 6, 0, 6, 5)],+ newTileId: 9,+ targetX: 6,+ targetY: 0,+ w: 6,+ h: 2,+ expected: {+ newTileLayout: { sm: { x: 6, y: 0, w: 6, h: 2 } },+ tilesToUpdate: [{ id: 2, layouts: { sm: { x: 6, y: 2, w: 6, h: 5 } } }],+ },+ },+ {+ name: 'a full-width insert pushes both columns down',+ layout: [smLayout('1', 0, 0, 6, 5), smLayout('2', 6, 0, 6, 5)],+ newTileId: 9,+ targetX: 0,+ targetY: 0,+ w: 12,+ h: 2,+ expected: {+ newTileLayout: { sm: { x: 0, y: 0, w: 12, h: 2 } },+ tilesToUpdate: [+ { id: 1, layouts: { sm: { x: 0, y: 2, w: 6, h: 5 } } },+ { id: 2, layouts: { sm: { x: 6, y: 2, w: 6, h: 5 } } },+ ],+ },+ },+ {+ name: 'insert in the middle only pushes same-column tiles at or below the row',+ layout: [smLayout('1', 0, 0, 6, 5), smLayout('2', 0, 5, 6, 5), smLayout('3', 0, 10, 6, 5)],+ newTileId: 9,+ targetX: 0,+ targetY: 5,+ w: 6,+ h: 3,+ expected: {+ newTileLayout: { sm: { x: 0, y: 5, w: 6, h: 3 } },+ tilesToUpdate: [+ { id: 2, layouts: { sm: { x: 0, y: 8, w: 6, h: 5 } } },+ { id: 3, layouts: { sm: { x: 0, y: 13, w: 6, h: 5 } } },+ ],+ },+ },+ {+ name: 'insert at the bottom shifts nothing',+ layout: [smLayout('1', 0, 0, 6, 5)],+ newTileId: 9,+ targetX: 0,+ targetY: 5,+ w: 2,+ h: 2,+ expected: {+ newTileLayout: { sm: { x: 0, y: 5, w: 2, h: 2 } },+ tilesToUpdate: [],+ },+ },+ {+ name: 'ignores the newly-added tile already present in the layout',+ layout: [smLayout('1', 0, 0, 6, 5), smLayout('9', 0, 5, 6, 5)],+ newTileId: 9,+ targetX: 0,+ targetY: 0,+ w: 6,+ h: 5,+ expected: {+ newTileLayout: { sm: { x: 0, y: 0, w: 6, h: 5 } },+ tilesToUpdate: [{ id: 1, layouts: { sm: { x: 0, y: 5, w: 6, h: 5 } } }],+ },+ },+ ])('$name', ({ layout, newTileId, targetX, targetY, w, h, expected }) => {+ const result = calculateInsertionLayout(layout, newTileId, targetY, targetX, w, h)++ expect(result.newTileLayout).toEqual(expected.newTileLayout)+ expect(result.tilesToUpdate).toEqual(expected.tilesToUpdate)+ })++ it('handles an undefined layout (first tile on an empty dashboard)', () => {+ const result = calculateInsertionLayout(undefined, 1, 0, 0, 6, 5)++ expect(result.newTileLayout).toEqual({ sm: { x: 0, y: 0, w: 6, h: 5 } })+ expect(result.tilesToUpdate).toEqual([])+ })+})diff --git a/frontend/src/scenes/dashboard/tileLayouts.ts b/frontend/src/scenes/dashboard/tileLayouts.tsindex 54068f8f8f4f..2bcd8dd58212 100644--- a/frontend/src/scenes/dashboard/tileLayouts.ts+++ b/frontend/src/scenes/dashboard/tileLayouts.ts@@ -24,6 +24,9 @@ const MIN_TEXT_TILE_HEIGHT_ROWS = 1const MIN_WIDGET_TILE_WIDTH_COLS = 3const MIN_WIDGET_TILE_HEIGHT_ROWS = 4+/** Fallback tile dimensions (half-width, standard height) when a tile has no known layout yet. */+export const DEFAULT_INSERTED_TILE_SIZE = { w: 6, h: 5 } as const+type WidgetCatalogLayout = DashboardWidgetCatalogEntry['defaultLayout']/**@@ -72,7 +75,7 @@ export function calculateDuplicateLayout(): DuplicateLayoutResult {const result: DuplicateLayoutResult = { duplicateLayouts: {}, tilesToUpdate: [] }- const originalSmLayout = currentLayouts?.sm?.find((l) => String(l.i) === String(tileId))+ const originalSmLayout = currentLayouts?.sm?.find((l) => l.i === `${tileId}`)if (!originalSmLayout) {return result@@ -98,12 +101,59 @@ export function calculateDuplicateLayout(// shift down any tiles that would overlap with the new placementfor (const smLayout of currentLayouts?.sm || []) {// ignore the duplicated tile and tiles above the insertion point- if (String(smLayout.i) === String(tileId) || smLayout.y < insertY) {+ if (smLayout.i === `${tileId}` || smLayout.y < insertY) {+ continue+ }++ result.tilesToUpdate.push({+ id: Number(smLayout.i),+ layouts: {+ sm: { x: smLayout.x, y: smLayout.y + h, w: smLayout.w, h: smLayout.h },+ },+ })+ }++ return result+}++export interface InsertionLayoutResult {+ newTileLayout: { sm: TileLayout }+ tilesToUpdate: Array<{ id: number; layouts: { sm?: TileLayout } }>+}++/**+ * Layout for inserting a tile at a given grid slot: the new tile lands at (`targetX`, `targetY`) and+ * only tiles sharing its column span (those horizontally overlapping the new tile) that sit at or+ * below `targetY` are pushed down by `h` rows. Tiles in other columns stay put, so inserting into the+ * right column doesn't shove the left one. Mirrors `calculateDuplicateLayout`'s `tilesToUpdate` shape+ * so persistence is shared.+ */+export function calculateInsertionLayout(+ currentSmLayout: Layout | undefined,+ newTileId: number,+ targetY: number,+ targetX: number,+ w: number,+ h: number+): InsertionLayoutResult {+ const result: InsertionLayoutResult = {+ newTileLayout: { sm: { x: targetX, y: targetY, w, h } },+ tilesToUpdate: [],+ }++ for (const smLayout of currentSmLayout || []) {+ // leave the new tile and anything above the insertion point untouched+ if (smLayout.i === `${newTileId}` || smLayout.y < targetY) {+ continue+ }+ // only push tiles that share horizontal space with the inserted tile's column span+ const overlapsColumn = smLayout.x < targetX + w && smLayout.x + smLayout.w > targetX+ if (!overlapsColumn) {continue}result.tilesToUpdate.push({- id: parseInt(smLayout.i),+ id: Number(smLayout.i),layouts: {sm: { x: smLayout.x, y: smLayout.y + h, w: smLayout.w, h: smLayout.h },},@@ -128,7 +178,7 @@ function canPlaceToRight(}return !layouts.some((l) => {- if (String(l.i) === String(excludeTileId)) {+ if (l.i === `${excludeTileId}`) {return false}const overlapsX = l.x < rightX + w && l.x + l.w > rightX@@ -303,7 +353,7 @@ export const calculateLayouts = (if (breakpoint === 'sm') {referenceOrder = [...cleanLayouts].sort((a, b) => (a.y === b.y ? a.x - b.x : a.y - b.y))- .map((l) => parseInt(l.i))+ .map((l) => Number(l.i))}allLayouts[breakpoint] = cleanLayouts