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.

chore(dashboards): remove inline tile insertion (#97775)

Matt Pua78cbc5a2539e
diff --git a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx
index 055ba906bac7..09bf4d85c3d0 100644
--- a/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/EditModeEdgeOverlay.tsx
@@ -19,9 +19,7 @@ const edgeOverlayBaseStyle: React.CSSProperties = {
background: 'none',
}
-// Top/bottom zones hug the border and reach mostly *into* the tile: the inline "insert tile" overlay owns the
-// row gap between tiles (see InsertTileOverlay), so keeping these off the gap avoids fighting it for the same
-// pixels. They still win the shared border pixel via a higher z-index. Left/right never touch the insert line.
+// Top/bottom zones hug the tile border. They still win the shared border pixel via a higher z-index.
const TOP_BOTTOM_Z = 7
// Corners sit above edges so a press in the corner resolves to the diagonal handle.
const cornerZoneStyle: React.CSSProperties = { zIndex: TOP_BOTTOM_Z, width: 18, height: 18 }
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index c26271e3ee71..002fe5fad613 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -78,8 +78,6 @@ import {
SurveyQuestionType,
} from '~/types'
-import type { DashboardAddTileType } from 'products/dashboards/frontend/types'
-
import type { ExperimentMetricUnion } from '../../queries/schema/schema-general'
import type { FunnelCorrelationResultsType, Realm, UserType } from '../../types'
@@ -785,11 +783,11 @@ export interface eventUsageLogicActions {
stepCount: number
}
reportDashboardAddMenuOpened: (
- source: 'header' | 'inline',
+ source: 'header',
dashboardId: number
) => {
dashboardId: number
- source: 'header' | 'inline'
+ source: 'header'
}
reportDashboardBreakdownColorsSaved: (
dashboard: DashboardType<QueryBasedInsightModel> | null,
@@ -1023,21 +1021,6 @@ export interface eventUsageLogicActions {
ignored: boolean
insightId: number | null
}
- reportDashboardTileInsertedInline: (
- tileType: DashboardAddTileType,
- dashboardId: number,
- tileId: number,
- column: number,
- row: number,
- fullWidth: boolean
- ) => {
- column: number
- dashboardId: number
- fullWidth: boolean
- row: number
- tileId: number
- tileType: DashboardAddTileType
- }
reportDashboardTileRefreshed: (
dashboardId: number,
tile: DashboardTile<QueryBasedInsightModel>,
@@ -2670,15 +2653,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
reportCustomChannelTypeRulesUpdated: (numRules: number) => ({ numRules }),
reportPropertySelectOpened: true,
reportCreatedDashboardFromModal: true,
- reportDashboardAddMenuOpened: (source: 'header' | 'inline', dashboardId: number) => ({ source, dashboardId }),
- reportDashboardTileInsertedInline: (
- tileType: DashboardAddTileType,
- dashboardId: number,
- tileId: number,
- column: number,
- row: number,
- fullWidth: boolean
- ) => ({ tileType, dashboardId, tileId, column, row, fullWidth }),
+ reportDashboardAddMenuOpened: (source: 'header', dashboardId: number) => ({ source, dashboardId }),
/** Dashboard created via PostHog web app from a template (new dashboard modal / template chooser). */
reportWebDashboardCreatedFromTemplate: (payload: {
dashboard_id: number
@@ -3854,16 +3829,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
reportDashboardAddMenuOpened: async ({ source, dashboardId }) => {
posthog.capture('dashboard add menu opened', { source, dashboard_id: dashboardId })
},
- reportDashboardTileInsertedInline: async ({ tileType, dashboardId, tileId, column, row, fullWidth }) => {
- posthog.capture('dashboard tile inserted inline', {
- tile_type: tileType,
- dashboard_id: dashboardId,
- tile_id: tileId,
- 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.tsx
index bc71448af151..134035c7ff1f 100644
--- a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
@@ -96,7 +96,6 @@ export function DashboardAddTileButton(): JSX.Element | null {
const {
loadDashboard,
setAddWidgetModalOpen,
- setPendingInsertion,
openAddInsightModal,
openTextTileModal,
openImageTileModal,
@@ -143,8 +142,6 @@ export function DashboardAddTileButton(): JSX.Element | null {
onAddButton: openButtonTileModal,
push,
setAddWidgetModalOpen,
- // Adding from the header appends at the bottom; drop any stale inline-insertion target.
- onBeforeSelect: () => setPendingInsertion(null),
})}
onVisibilityChange={(visible) => {
if (visible) {
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index c331efe3b34c..2488e891c549 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -15,11 +15,8 @@ import { ApiError } from 'lib/api'
import { InsightCard } from 'lib/components/Cards/InsightCard'
import { EditModeEdge, useResizeHandleScrollbarPassThrough } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
-import { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
-import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDashboardModalLogic'
-import { getAddTileMenuItems } from 'scenes/dashboard/DashboardHeaderActions'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import {
BREAKPOINTS,
@@ -28,7 +25,6 @@ import {
isWidgetTileVisibleOnPlacement,
} from 'scenes/dashboard/dashboardUtils'
import { continueDragGestureInEditMode, continueResizeGestureInEditMode } from 'scenes/dashboard/editLayoutGesture'
-import { InsertTileOverlay } from 'scenes/dashboard/InsertTileOverlay'
import { useDashboardLayoutInteraction } from 'scenes/dashboard/useDashboardLayoutInteraction'
import { useSurveyLinkedInsights } from 'scenes/surveys/hooks/useSurveyLinkedInsights'
import { getBestSurveyOpportunityFunnel } from 'scenes/surveys/utils/opportunityDetection'
@@ -120,16 +116,10 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
copyToDashboard,
setTileOverride,
setDashboardMode,
- setAddWidgetModalOpen,
- setPendingInsertion,
- openTextTileModal,
- openImageTileModal,
- openButtonTileModal,
} = useActions(dashboardLogic)
- const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
const { updateWidgetTile } = useAsyncActions(dashboardLogic)
const { renameInsight } = useActions(insightsModel)
- const { reportDashboardAddMenuOpened, reportDashboardTileRepositioned } = useActions(eventUsageLogic)
+ const { reportDashboardTileRepositioned } = useActions(eventUsageLogic)
const { push } = useActions(router)
const { data: surveyLinkedInsights, loading: surveyLinkedInsightsLoading } = useSurveyLinkedInsights({})
@@ -264,33 +254,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
[gridGap, spacingFactor]
)
- const getInsertMenuItems = useCallback(
- (targetX: number, targetY: number, targetW?: number): LemonMenuItems =>
- dashboard
- ? getAddTileMenuItems({
- dashboardWidgetsEnabled,
- onAddInsight: showAddInsightToDashboardModal,
- onAddText: openTextTileModal,
- onAddImage: openImageTileModal,
- onAddButton: openButtonTileModal,
- push,
- setAddWidgetModalOpen,
- onBeforeSelect: () => setPendingInsertion({ x: targetX, y: targetY, w: targetW ?? null }),
- })
- : [],
- [
- dashboard,
- dashboardWidgetsEnabled,
- showAddInsightToDashboardModal,
- push,
- setAddWidgetModalOpen,
- setPendingInsertion,
- openTextTileModal,
- openImageTileModal,
- openButtonTileModal,
- ]
- )
-
const showResizeHandles = layoutEditMode && !isMobileView && isEditablePlacement && !isLayoutZoomToggled
const showEditingControls = isEditablePlacement || layoutEditMode
const showDetailsControls =
@@ -730,25 +693,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
}
})}
</ReactGridLayout>
- {isEditablePlacement && (
- <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}
- onMenuOpen={() => {
- if (dashboard?.id) {
- reportDashboardAddMenuOpened('inline', dashboard.id)
- }
- }}
- />
- )}
</div>
)}
{dashboardStreaming && (
diff --git a/frontend/src/scenes/dashboard/InsertTileOverlay.tsx b/frontend/src/scenes/dashboard/InsertTileOverlay.tsx
deleted file mode 100644
index fbc9e956a29c..000000000000
--- a/frontend/src/scenes/dashboard/InsertTileOverlay.tsx
+++ /dev/null
@@ -1,265 +0,0 @@
-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, LemonMenuItems } 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) => LemonMenuItems
- onMenuOpen: () => void
-}
-
-export function InsertTileOverlay({
- layout,
- gridWidth,
- cols,
- rowHeight,
- marginX,
- marginY,
- canEditDashboard,
- isMobileView,
- disabled,
- getMenuItems,
- onMenuOpen,
-}: 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 (
- // Stays below the tiles' edge-resize hover zones (see EditModeEdgeOverlay), so hovering a tile border
- // grabs the resize handle rather than this insert line. Keep this under those zones' z-index if changed.
- // 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}
- onMenuOpen={onMenuOpen}
- />
- ))}
- </div>
- )
-}
-
-// Transparent hover zone centered on the row boundary. Kept within the inter-row gap (12px < the 16px
-// gap) so it doesn't bleed onto the adjacent tile borders, which carry their own resize-on-hover zones.
-const HOVER_HIT_HEIGHT = 12
-// 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,
- onMenuOpen,
-}: {
- lineY: number
- gridRow: number
- gridWidth: number
- cols: number
- segments: LineSegment[]
- zones: InsertZone[]
- getMenuItems: (targetX: number, targetY: number, targetW?: number) => LemonMenuItems
- onMenuOpen: () => void
-}): 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={(visible) => {
- setMenuOpen(visible)
- if (visible) {
- onMenuOpen()
- }
- }}
- >
- <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/__snapshots__/DashboardItems.test.tsx.snap b/frontend/src/scenes/dashboard/__snapshots__/DashboardItems.test.tsx.snap
index bbb4f120f4ff..334a99f63a71 100644
--- a/frontend/src/scenes/dashboard/__snapshots__/DashboardItems.test.tsx.snap
+++ b/frontend/src/scenes/dashboard/__snapshots__/DashboardItems.test.tsx.snap
@@ -26,10 +26,6 @@ exports[`DashboardItems matches snapshot in edit mode with layout zoom enabled 1
data-tile-id="1"
/>
</div>
- <div
- class="absolute inset-0 pointer-events-none"
- style="z-index: 6;"
- />
</div>
</div>
`;
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 6fc2b306e3d5..e067a8e28f35 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -26,10 +26,6 @@ import type { Layout } from 'react-grid-layout'
import { LemonButton, 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,
@@ -40,7 +36,6 @@ import {
import api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'
import { ApiError, isAccessDeniedError } from 'lib/api-error'
import { DataColorTheme } from 'lib/colors'
-import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { OrganizationMembershipLevel } from 'lib/constants'
import { FEATURE_FLAGS } from 'lib/constants'
import { Dayjs, dayjs, now } from 'lib/dayjs'
@@ -55,12 +50,7 @@ import { shouldCancelQuery } from 'lib/utils/requests'
import { toParams } from 'lib/utils/url'
import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDashboardModalLogic'
import { BREAKPOINTS, dashboardToSaveableTemplate, getDashboardTileDisplayName } from 'scenes/dashboard/dashboardUtils'
-import {
- calculateDuplicateLayout,
- calculateInsertionLayout,
- calculateLayouts,
- DEFAULT_INSERTED_TILE_SIZE,
-} from 'scenes/dashboard/tileLayouts'
+import { calculateDuplicateLayout, calculateLayouts } from 'scenes/dashboard/tileLayouts'
import {
chunkTileIds,
fetchRunWidgets,
@@ -117,9 +107,7 @@ import {
TileLayout,
} from '~/types'
-import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'
import { DashboardGridCompaction } from 'products/dashboards/frontend/dashboardCustomization'
-import type { DashboardAddTileType } from 'products/dashboards/frontend/types'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { Node } from '../../queries/schema/schema-general'
@@ -206,13 +194,6 @@ export enum RefreshDashboardItemsAction {
// to stop kea typegen getting confused
export 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
-}
-
function parseDashboardTileId(tileId: string | undefined): DashboardTileIdOrNew {
const parsedTileId = Number(tileId)
return Number.isNaN(parsedTileId) ? null : parsedTileId
@@ -352,7 +333,6 @@ export interface dashboardLogicValues {
nextAllowedDashboardRefresh: Dayjs | null
oldestRefreshed: Dayjs | null
pageVisibility: boolean
- pendingInsertion: PendingInsertion | null
placement: DashboardPlacement
projectTreeRef: ProjectTreeRef
refreshMetrics: {
@@ -431,9 +411,6 @@ export interface dashboardLogicActions {
applyFilters: () => {
value: true
}
- applyPendingInsertion: () => {
- value: true
- }
applyWidgetIssueMetadataChange: (payload: {
context: WidgetIssueMetadataContext
delta: WidgetIssueMetadataDelta
@@ -832,9 +809,6 @@ export interface dashboardLogicActions {
setPageVisibility: (visible: boolean) => {
visible: boolean
}
- setPendingInsertion: (pendingInsertion: PendingInsertion | null) => {
- pendingInsertion: PendingInsertion | null
- }
setProperties: (properties: AnyPropertyFilter[] | null) => {
properties: AnyPropertyFilter[] | null
}
@@ -1395,8 +1369,6 @@ 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 }),
@@ -2255,16 +2227,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
setDashboardMode: () => false,
},
],
- 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,
{
@@ -3284,9 +3246,6 @@ 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 }) => ({
@@ -3433,106 +3392,6 @@ 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 = (() => {
- switch (getDashboardWidgetType(newTile)) {
- case 'text':
- return getImageOnlyTextCardImage(textCardConverter, newTile.text!.body) ? 'image' : 'text_card'
- case 'button_tile':
- return 'button'
- case 'widget':
- return 'widget'
- case 'insight':
- return 'insight'
- }
- })() satisfies DashboardAddTileType
- eventUsageLogic.actions.reportDashboardTileInsertedInline(
- insertedTileType,
- props.id,
- newTile.id,
- 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, 'dashboard_scene')
- 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,
@@ -4279,30 +4138,7 @@ 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 widgetsPayload = widgets.map(({ widgetType, config }) => ({ widget_type: widgetType, config }))
const response = await api.create(
`api/environments/${teamLogic.values.currentTeamId}/dashboards/${dashboardId}/widgets/batch/`,
@@ -4320,10 +4156,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
if (dashboard) {
dashboardsModel.actions.updateDashboardSuccess(dashboard)
- // Only auto-scroll when the new tiles actually went to the bottom.
- if (!insertSlot) {
- actions.requestScrollToBottom()
- }
+ actions.requestScrollToBottom()
}
}
@@ -4588,8 +4421,6 @@ 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.ts
deleted file mode 100644
index e4b411fc179f..000000000000
--- a/frontend/src/scenes/dashboard/insertTileGeometry.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-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.ts
deleted file mode 100644
index 5c4ae2670348..000000000000
--- a/frontend/src/scenes/dashboard/insertTileGeometry.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-// 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/products/dashboards/frontend/types.ts b/products/dashboards/frontend/types.ts
index c6ad97c78716..278d0a379759 100644
--- a/products/dashboards/frontend/types.ts
+++ b/products/dashboards/frontend/types.ts
@@ -1,5 +1,3 @@
-export type DashboardAddTileType = 'insight' | 'text_card' | 'image' | 'button' | 'widget'
-
/**
* Product RBAC for gated widget types. New types: extend union here — see products/dashboards/CONTRIBUTING.md.
*/