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): offer insight deletion after removal (#81450)

Matt Puab22662dbe233
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 69630abd5234..bb7e620ef576 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -743,6 +743,12 @@ export interface eventUsageLogicActions {
insightId: number
source: DashboardEventSource
}
+ reportDashboardInsightDeleteAfterRemovalClicked: (otherDashboardCount: number) => {
+ otherDashboardCount: number
+ }
+ reportDashboardInsightDeleteAfterRemovalConfirmed: (otherDashboardCount: number) => {
+ otherDashboardCount: number
+ }
reportDashboardInsightLegendToggled: (
dashboardId: number | undefined,
insightId: number,
@@ -2429,6 +2435,8 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
originalLength: number,
newLength: number
) => ({ dashboardId, attribute, originalLength, newLength }),
+ reportDashboardInsightDeleteAfterRemovalClicked: (otherDashboardCount: number) => ({ otherDashboardCount }),
+ reportDashboardInsightDeleteAfterRemovalConfirmed: (otherDashboardCount: number) => ({ otherDashboardCount }),
reportDashboardShareToggled: (dashboardId: number | undefined, isShared: boolean) => ({
dashboardId,
isShared,
@@ -3524,6 +3532,16 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
attribute,
})
},
+ reportDashboardInsightDeleteAfterRemovalClicked: async ({ otherDashboardCount }) => {
+ posthog.capture('dashboard insight delete after removal clicked', {
+ other_dashboard_count: otherDashboardCount,
+ })
+ },
+ reportDashboardInsightDeleteAfterRemovalConfirmed: async ({ otherDashboardCount }) => {
+ posthog.capture('dashboard insight delete after removal confirmed', {
+ other_dashboard_count: otherDashboardCount,
+ })
+ },
reportDashboardInsightValuesOnSeriesToggled: async ({ dashboardId, insightId, source }) => {
posthog.capture('dashboard insight values on series toggled', {
dashboard_id: dashboardId,
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index 9e6f4214b098..e8925bf9ef4a 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -2601,6 +2601,73 @@ describe('dashboardLogic', () => {
})
})
+ describe('insight tiles', () => {
+ let lemonToastInfoSpy: jest.SpiedFunction<typeof lemonToast.info>
+ let lemonToastDismissSpy: jest.SpiedFunction<typeof lemonToast.dismiss>
+ let lemonDialogOpenSpy: jest.SpiedFunction<typeof LemonDialog.open>
+
+ beforeEach(async () => {
+ lemonToastInfoSpy = jest.spyOn(lemonToast, 'info').mockImplementation(() => 'toast-id')
+ lemonToastDismissSpy = jest.spyOn(lemonToast, 'dismiss').mockImplementation(() => undefined)
+ lemonDialogOpenSpy = jest.spyOn(LemonDialog, 'open').mockImplementation(() => undefined)
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ lemonToastInfoSpy.mockRestore()
+ lemonToastDismissSpy.mockRestore()
+ lemonDialogOpenSpy.mockRestore()
+ })
+
+ it('offers to delete a removed insight and explains its other dashboard usage', async () => {
+ const { fireEvent, render } = await import('@testing-library/react')
+ const reportDeleteClicked = jest.spyOn(
+ eventUsageLogic.actions,
+ 'reportDashboardInsightDeleteAfterRemovalClicked'
+ )
+ const insightTile = logic.values.insightTiles[0]
+ const insight = insightTile.insight!
+
+ await expectLogic(logic, () => {
+ logic.actions.removeTile({
+ ...insightTile,
+ insight: {
+ ...insight,
+ dashboard_tiles: [
+ ...(insight.dashboard_tiles || []),
+ { id: 999, dashboard_id: 8, deleted: true },
+ ],
+ },
+ })
+ }).toFinishAllListeners()
+
+ const toastContent = lemonToastInfoSpy.mock.calls.at(-1)?.[0]
+ const { getByText } = render(toastContent)
+ fireEvent.click(getByText('Delete insight everywhere'))
+ expect(reportDeleteClicked).toHaveBeenCalledWith(1)
+ expect(lemonToastDismissSpy).not.toHaveBeenCalled()
+
+ const dialogProps = lemonDialogOpenSpy.mock.calls.at(-1)?.[0]
+ expect(dialogProps).toEqual(
+ expect.objectContaining({ title: 'Delete insight everywhere?', shouldAwaitSubmit: true })
+ )
+ if (!dialogProps) {
+ throw new Error('Delete dialog did not open')
+ }
+
+ const { container, getByText: getDialogText } = render(dialogProps.description)
+ expect(getDialogText('This insight is also used on:')).not.toBeNull()
+ expect(container.querySelector('a')?.getAttribute('href')).toMatch(/\/dashboard\/6$/)
+ expect(
+ getDialogText('This deletes the insight and removes it from every dashboard. You can undo this action.')
+ ).not.toBeNull()
+
+ reportDeleteClicked.mockRestore()
+ })
+ })
+
describe('widget tiles', () => {
let lemonToastInfoSpy: jest.SpiedFunction<typeof lemonToast.info>
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 9878e69e43da..5bbd6baef35e 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -22,7 +22,7 @@ import uniqBy from 'lodash.uniqby'
import { ResponsiveLayouts } from 'react-grid-layout'
import type { Layout } from 'react-grid-layout'
-import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
+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 {
@@ -45,6 +45,7 @@ import { Dayjs, dayjs, now } from 'lib/dayjs'
import { Link } from 'lib/lemon-ui/Link'
import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
+import { deleteInsightWithUndo } from 'lib/utils/deleteWithUndo'
import { clearDOMTextSelection, getJSHeapMemory, uuid } from 'lib/utils/dom'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
@@ -3422,47 +3423,166 @@ export const dashboardLogic = kea<dashboardLogicType>([
const isWidgetTile = !!tile.widget
const removedMessage = isWidgetTile ? 'widget removed' : 'has been removed from the dashboard'
const toastId = `remove-tile-${tile.id}`
+ const otherDashboardIds = new Set(
+ (
+ tile.insight?.dashboard_tiles
+ ?.filter((dashboardTile) => !dashboardTile.deleted)
+ .map((dashboardTile) => dashboardTile.dashboard_id) ??
+ tile.insight?.dashboards ??
+ []
+ ).filter((dashboardId) => dashboardId !== props.id)
+ )
+ const canDeleteInsight =
+ tile.insight?.user_access_level !== AccessControlLevel.Viewer &&
+ (!tile.insight?.user_access_level ||
+ accessLevelSatisfied(
+ AccessControlResourceType.Insight,
+ tile.insight.user_access_level,
+ AccessControlLevel.Editor
+ ))
+ const deleteInsight = (): void => {
+ if (!tile.insight) {
+ return
+ }
- lemonToast.info(
- <>
- <b>{tileName}</b> {removedMessage}
- </>,
- {
- toastId,
- button: {
- label: 'Undo',
- dataAttr: 'undo-remove-tile-from-dashboard',
- action: async () => {
- try {
- await api.update(`api/environments/${values.currentTeamId}/dashboards/${props.id}`, {
- tiles: [{ id: tile.id, deleted: false }],
- })
-
- if (tile.insight) {
- const insight = tile.insight
- const nextDashboards = insight.dashboards?.includes(props.id)
- ? insight.dashboards
- : [...(insight.dashboards || []), props.id]
- dashboardsModel.actions.updateDashboardInsight(
- { ...insight, dashboards: nextDashboards },
- [props.id]
- )
- }
-
- actions.loadDashboard({ action: DashboardLoadAction.Update })
-
- lemonToast.success(
- <>
- <b>{tileName}</b> {isWidgetTile ? 'widget restored' : 'has been restored'}
- </>,
- { toastId }
- )
- } catch (e) {
- lemonToast.error('Could not restore tile: ' + String(e))
- }
+ const otherDashboards = Array.from(otherDashboardIds).map((dashboardId) => ({
+ id: dashboardId,
+ name: dashboardsModel.values.rawDashboards[dashboardId]?.name || `Dashboard ${dashboardId}`,
+ }))
+ const dashboardIds = [props.id, ...otherDashboardIds]
+ const otherDashboardCount = otherDashboards.length
+
+ LemonDialog.open({
+ title: 'Delete insight everywhere?',
+ shouldAwaitSubmit: true,
+ description: (
+ <div className="pt-2 space-y-4">
+ {otherDashboards.length > 0 && (
+ <div>
+ <div>This insight is also used on:</div>
+ <ul className="list-inside list-disc">
+ {otherDashboards.map((dashboard) => (
+ <li key={dashboard.id}>
+ <Link to={urls.dashboard(dashboard.id)}>{dashboard.name}</Link>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ <div>
+ This deletes the insight and removes it from every dashboard. You can undo this action.
+ </div>
+ </div>
+ ),
+ primaryButton: {
+ children: 'Delete insight everywhere',
+ status: 'danger',
+ onClick: () => {
+ eventUsageLogic.actions.reportDashboardInsightDeleteAfterRemovalConfirmed(
+ otherDashboardCount
+ )
+ return deleteInsightWithUndo({
+ object: { ...tile.insight!, dashboards: dashboardIds },
+ endpoint: `projects/${values.currentTeamId}/insights`,
+ callback: (undo, insight) => {
+ const updatedInsight = {
+ ...insight,
+ deleted: !undo,
+ dashboards: undo ? insight.dashboards : [],
+ }
+ dashboardsModel.actions.updateDashboardInsight(updatedInsight, dashboardIds)
+ if (!undo) {
+ lemonToast.dismiss(toastId)
+ }
+ },
+ })
},
},
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ const undoTileRemoval = async (): Promise<void> => {
+ try {
+ await api.update(`api/environments/${values.currentTeamId}/dashboards/${props.id}`, {
+ tiles: [{ id: tile.id, deleted: false }],
+ })
+
+ if (tile.insight) {
+ const insight = tile.insight
+ const nextDashboards = insight.dashboards?.includes(props.id)
+ ? insight.dashboards
+ : [...(insight.dashboards || []), props.id]
+ dashboardsModel.actions.updateDashboardInsight({ ...insight, dashboards: nextDashboards }, [
+ props.id,
+ ])
+ }
+
+ actions.loadDashboard({ action: DashboardLoadAction.Update })
+
+ lemonToast.success(
+ <>
+ <b>{tileName}</b> {isWidgetTile ? 'widget restored' : 'has been restored'}
+ </>,
+ { toastId }
+ )
+ } catch (e) {
+ lemonToast.error('Could not restore tile: ' + String(e))
}
+ }
+
+ lemonToast.info(
+ tile.insight ? (
+ <span className="flex flex-col gap-2">
+ <span>
+ <b>{tileName}</b> {removedMessage}
+ </span>
+ <span className="flex items-center gap-2">
+ {canDeleteInsight && (
+ <LemonButton
+ type="primary"
+ status="danger"
+ size="small"
+ data-attr="delete-removed-insight"
+ className="!m-0"
+ onClick={() => {
+ eventUsageLogic.actions.reportDashboardInsightDeleteAfterRemovalClicked(
+ otherDashboardIds.size
+ )
+ deleteInsight()
+ }}
+ >
+ Delete insight everywhere
+ </LemonButton>
+ )}
+ <LemonButton
+ type="secondary"
+ size="small"
+ data-attr="undo-remove-tile-from-dashboard"
+ className="!m-0"
+ onClick={() => {
+ void undoTileRemoval()
+ lemonToast.dismiss(toastId)
+ }}
+ >
+ Undo
+ </LemonButton>
+ </span>
+ </span>
+ ) : (
+ <>
+ <b>{tileName}</b> {removedMessage}
+ </>
+ ),
+ tile.insight
+ ? { toastId }
+ : {
+ toastId,
+ button: {
+ label: 'Undo',
+ dataAttr: 'undo-remove-tile-from-dashboard',
+ action: undoTileRemoval,
+ },
+ }
)
},
moveToDashboardSuccess: ({ payload }) => {