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(insights): show the unsaved insight draft as a table row (#72971)

Thomas Obermüllerc16c7062d453
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 283cdc35177e..3a7f5a12a77b 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -1325,6 +1325,16 @@ export interface eventUsageLogicActions {
reportInsightDateRangeChanged: (queryKind: string | undefined) => {
queryKind: string | undefined
}
+ reportInsightDraftDiscarded: (draftAgeSeconds: number) => {
+ draftAgeSeconds: number
+ }
+ reportInsightDraftRestored: (
+ surface: 'insight_editor' | 'saved_insights',
+ draftAgeSeconds: number
+ ) => {
+ draftAgeSeconds: number
+ surface: 'insight_editor' | 'saved_insights'
+ }
reportInsightDragToZoomed: (queryKind: string | undefined) => {
queryKind: string | undefined
}
@@ -2278,6 +2288,11 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
insightType,
presetKey,
}),
+ reportInsightDraftRestored: (surface: 'saved_insights' | 'insight_editor', draftAgeSeconds: number) => ({
+ surface,
+ draftAgeSeconds,
+ }),
+ reportInsightDraftDiscarded: (draftAgeSeconds: number) => ({ draftAgeSeconds }),
reportPersonSplit: (merge_count: number) => ({ merge_count }),
reportHelpButtonViewed: true,
reportHelpButtonUsed: (help_type: HelpType) => ({ help_type }),
@@ -3328,6 +3343,12 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
reportSavedInsightTabChanged: ({ tab }) => {
posthog.capture('saved insights list page tab changed', { tab })
},
+ reportInsightDraftRestored: ({ surface, draftAgeSeconds }) => {
+ posthog.capture('insight draft restored', { surface, draft_age_seconds: draftAgeSeconds })
+ },
+ reportInsightDraftDiscarded: ({ draftAgeSeconds }) => {
+ posthog.capture('insight draft discarded', { draft_age_seconds: draftAgeSeconds })
+ },
reportSavedInsightNewInsightClicked: ({ insightType, presetKey }) => {
posthog.capture('saved insights new insight clicked', {
insight_type: insightType,
diff --git a/frontend/src/scenes/saved-insights/DraftInsightRow.tsx b/frontend/src/scenes/saved-insights/DraftInsightRow.tsx
new file mode 100644
index 000000000000..c65b5d50984f
--- /dev/null
+++ b/frontend/src/scenes/saved-insights/DraftInsightRow.tsx
@@ -0,0 +1,67 @@
+import { useActions } from 'kea'
+
+import { dayjs } from 'lib/dayjs'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { More } from 'lib/lemon-ui/LemonButton/More'
+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { useSummarizeInsight } from 'scenes/insights/summarizeInsight'
+import { urls } from 'scenes/urls'
+
+import { SavedInsightListItem, savedInsightsLogic } from './savedInsightsLogic'
+
+function draftAgeSeconds(item: SavedInsightListItem): number {
+ return Math.max(0, dayjs().diff(dayjs(item.created_at), 'second'))
+}
+
+export function DraftInsightNameCell({ item }: { item: SavedInsightListItem }): JSX.Element {
+ const summarizeInsight = useSummarizeInsight()
+ const { reportInsightDraftRestored } = useActions(eventUsageLogic)
+ return (
+ <LemonTableLink
+ to={urls.insightNew({ query: item.query ?? undefined })}
+ onClick={() => reportInsightDraftRestored('saved_insights', draftAgeSeconds(item))}
+ title={
+ <span className="flex items-center gap-2">
+ <i>{summarizeInsight(item.query) || 'Unsaved insight'}</i>
+ <LemonTag type="warning" size="small">
+ Draft
+ </LemonTag>
+ </span>
+ }
+ description="Unsaved changes, only stored in this browser"
+ />
+ )
+}
+
+export function DraftInsightMoreMenu({ item }: { item: SavedInsightListItem }): JSX.Element {
+ const { discardDraftQuery } = useActions(savedInsightsLogic)
+ const { reportInsightDraftRestored } = useActions(eventUsageLogic)
+ return (
+ <More
+ overlay={
+ <>
+ <LemonButton
+ to={urls.insightNew({ query: item.query ?? undefined })}
+ onClick={() => reportInsightDraftRestored('saved_insights', draftAgeSeconds(item))}
+ data-attr="draft-insight-continue-editing"
+ fullWidth
+ >
+ Continue editing
+ </LemonButton>
+ <LemonDivider />
+ <LemonButton
+ status="danger"
+ onClick={discardDraftQuery}
+ data-attr="draft-insight-discard"
+ fullWidth
+ >
+ Discard draft
+ </LemonButton>
+ </>
+ }
+ />
+ )
+}
diff --git a/frontend/src/scenes/saved-insights/ReloadInsight.tsx b/frontend/src/scenes/saved-insights/ReloadInsight.tsx
index 9c79229eb6cf..7ffd2222a7c2 100644
--- a/frontend/src/scenes/saved-insights/ReloadInsight.tsx
+++ b/frontend/src/scenes/saved-insights/ReloadInsight.tsx
@@ -1,7 +1,8 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { Link } from '@posthog/lemon-ui'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { parseDraftQueryFromLocalStorage } from 'scenes/insights/utils'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -10,6 +11,7 @@ import { Node } from '~/queries/schema/schema-general'
export function ReloadInsight(): JSX.Element {
const { currentTeamId } = useValues(teamLogic)
+ const { reportInsightDraftRestored } = useActions(eventUsageLogic)
const draftQueryLocalStorage = localStorage.getItem(`draft-query-${currentTeamId}`)
let draftQuery: { query: Node<Record<string, any>>; timestamp: number } | null = null
if (draftQueryLocalStorage) {
@@ -24,10 +26,22 @@ export function ReloadInsight(): JSX.Element {
if (!draftQuery?.query) {
return <> </>
}
+ const draftTimestamp = draftQuery.timestamp
return (
<div className="text-secondary">
- You have an unsaved insight from {new Date(draftQuery.timestamp).toLocaleString()}.{' '}
- <Link to={urls.insightNew({ query: draftQuery.query })}>Click here</Link> to view it.
+ You have an unsaved insight from {new Date(draftTimestamp).toLocaleString()}.{' '}
+ <Link
+ to={urls.insightNew({ query: draftQuery.query })}
+ onClick={() =>
+ reportInsightDraftRestored(
+ 'insight_editor',
+ Math.max(0, Math.round((Date.now() - draftTimestamp) / 1000))
+ )
+ }
+ >
+ Click here
+ </Link>{' '}
+ to view it.
</div>
)
}
diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsx
index 510adfb5d4f2..46c651ac5f3b 100644
--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx
@@ -49,9 +49,10 @@ import {
export * from './insightTypesMetadata'
+import { isDraftInsightRow } from './draftInsight'
+import { DraftInsightMoreMenu, DraftInsightNameCell } from './DraftInsightRow'
import { QUERY_TYPES_METADATA } from './insightTypesMetadata'
import { NewInsightButton } from './NewInsightMenu'
-import { ReloadInsight } from './ReloadInsight'
import { SavedInsightListItem, savedInsightsLogic } from './savedInsightsLogic'
export const scene: SceneExport = {
@@ -88,8 +89,16 @@ export function SavedInsights(): JSX.Element {
setSavedInsightsFilters,
bulkDeleteInsights,
} = useActions(savedInsightsLogic)
- const { insights, insightsLoading, filters, sorting, pagination, usingFilters, bulkDeleteResponseLoading } =
- useValues(savedInsightsLogic)
+ const {
+ insights,
+ insightsLoading,
+ filters,
+ sorting,
+ pagination,
+ usingFilters,
+ bulkDeleteResponseLoading,
+ draftInsightRow,
+ } = useValues(savedInsightsLogic)
const { currentProjectId } = useValues(projectLogic)
const summarizeInsight = useSummarizeInsight()
@@ -109,6 +118,9 @@ export function SavedInsights(): JSX.Element {
dataIndex: 'name',
key: 'name',
render: function renderName(name: string, insight) {
+ if (isDraftInsightRow(insight)) {
+ return <DraftInsightNameCell item={insight} />
+ }
return (
<div className="flex items-center gap-1">
<LemonTableLink
@@ -215,6 +227,9 @@ export function SavedInsights(): JSX.Element {
{
width: 0,
render: function Render(_, insight) {
+ if (isDraftInsightRow(insight)) {
+ return <DraftInsightMoreMenu item={insight} />
+ }
return (
<More
overlay={
@@ -342,11 +357,11 @@ export function SavedInsights(): JSX.Element {
: undefined
}
/>
- <ReloadInsight />
<LemonTable
loading={insightsLoading}
columns={columns}
- dataSource={insights.results}
+ dataSource={draftInsightRow ? [draftInsightRow, ...insights.results] : insights.results}
+ rowClassName={(record) => (isDraftInsightRow(record) ? 'bg-warning-highlight' : null)}
pagination={pagination}
noSortingCancellation
sorting={sorting}
@@ -371,13 +386,15 @@ export function SavedInsights(): JSX.Element {
bulkSelection={{
getKey: (insight: SavedInsightListItem): number => insight.id,
isRowSelectable: (insight: SavedInsightListItem) =>
- accessLevelSatisfied(
- AccessControlResourceType.Insight,
- insight.user_access_level,
- AccessControlLevel.Editor
- )
- ? true
- : { disabledReason: "You don't have permission to edit this insight." },
+ isDraftInsightRow(insight)
+ ? { disabledReason: 'This draft only exists in your browser.' }
+ : accessLevelSatisfied(
+ AccessControlResourceType.Insight,
+ insight.user_access_level,
+ AccessControlLevel.Editor
+ )
+ ? true
+ : { disabledReason: "You don't have permission to edit this insight." },
rowAriaLabel: (insight: SavedInsightListItem) =>
`Select insight ${insight.name || 'Untitled'}`,
headerAriaLabel: 'Select all insights on this page',
diff --git a/frontend/src/scenes/saved-insights/draftInsight.ts b/frontend/src/scenes/saved-insights/draftInsight.ts
new file mode 100644
index 000000000000..edaf131e2b17
--- /dev/null
+++ b/frontend/src/scenes/saved-insights/draftInsight.ts
@@ -0,0 +1,73 @@
+import { dayjs } from 'lib/dayjs'
+
+import { Node } from '~/queries/schema/schema-general'
+import { AccessControlLevel, InsightShortId, UserBasicType, UserType } from '~/types'
+
+import type { SavedInsightListItem } from './savedInsightsLogic'
+
+/** An insight draft persisted by the insight editor in localStorage under `draft-query-${teamId}`. */
+export interface DraftInsightQuery {
+ query: Node<Record<string, any>>
+ timestamp: number
+}
+
+/** Sentinel id for the local draft row in the saved insights table. Real insight ids are positive. */
+export const DRAFT_INSIGHT_ROW_ID = -1
+
+/** Storage can hold anything — a non-numeric timestamp would throw in draftInsightListItem and crash the list. */
+export function isValidDraftInsightQuery(value: unknown): value is DraftInsightQuery {
+ const draft = value as DraftInsightQuery | null
+ return (
+ !!draft &&
+ typeof draft === 'object' &&
+ !!draft.query &&
+ typeof draft.query === 'object' &&
+ typeof draft.query.kind === 'string' &&
+ typeof draft.timestamp === 'number' &&
+ Number.isFinite(draft.timestamp)
+ )
+}
+
+export function isDraftInsightRow(item: SavedInsightListItem): boolean {
+ return item.id === DRAFT_INSIGHT_ROW_ID
+}
+
+/** Shapes the local draft like a saved insight so it can sit in the saved insights table. */
+export function draftInsightListItem(draft: DraftInsightQuery, currentUser: UserType | null): SavedInsightListItem {
+ const timestamp = dayjs(draft.timestamp).toISOString()
+ // UserType is not assignable to UserBasicType (hedgehog_config shapes differ), so pick the basic fields
+ const user: UserBasicType | null = currentUser
+ ? {
+ id: currentUser.id,
+ uuid: currentUser.uuid,
+ distinct_id: currentUser.distinct_id,
+ first_name: currentUser.first_name,
+ last_name: currentUser.last_name,
+ email: currentUser.email,
+ }
+ : null
+ return {
+ id: DRAFT_INSIGHT_ROW_ID,
+ // Never used for API calls or links: render paths guard via isDraftInsightRow
+ short_id: 'draft' as InsightShortId,
+ name: '',
+ query: draft.query,
+ order: null,
+ result: null,
+ deleted: false,
+ saved: false,
+ is_sample: false,
+ dashboards: null,
+ dashboard_tiles: null,
+ last_refresh: null,
+ created_at: timestamp,
+ created_by: user,
+ updated_at: timestamp,
+ last_modified_at: timestamp,
+ last_modified_by: user,
+ last_viewed_at: null,
+ tags: [],
+ favorited: false,
+ user_access_level: AccessControlLevel.Viewer,
+ }
+}
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
index 196447b90eb8..b53d147071c6 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
@@ -4,6 +4,7 @@ import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
import api from 'lib/api'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { DeleteDashboardForm, deleteDashboardLogic } from 'scenes/dashboard/deleteDashboardLogic'
import { DuplicateDashboardForm, duplicateDashboardLogic } from 'scenes/dashboard/duplicateDashboardLogic'
import { sceneLogic } from 'scenes/sceneLogic'
@@ -324,4 +325,45 @@ describe('savedInsightsLogic', () => {
}).toDispatchActions(['addInsight'])
})
})
+
+ describe('draft insight row', () => {
+ const draftKey = `draft-query-${MOCK_TEAM_ID}`
+ const draft = {
+ query: { kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] } },
+ timestamp: 1721000000000,
+ }
+
+ afterEach(() => {
+ localStorage.removeItem(draftKey)
+ })
+
+ it('loads a stored draft into the draft row', async () => {
+ localStorage.setItem(draftKey, JSON.stringify(draft))
+ logic.actions.loadDraftQuery()
+ await expectLogic(logic).toMatchValues({
+ draftQuery: draft,
+ draftInsightRow: partial({ id: -1, query: draft.query }),
+ })
+ })
+
+ it.each([
+ ['unparseable JSON', 'not json'],
+ ['a non-numeric timestamp', JSON.stringify({ query: { kind: 'TrendsQuery' }, timestamp: 'yesterday' })],
+ ['a query without a kind', JSON.stringify({ query: {}, timestamp: 1721000000000 })],
+ ])('drops a malformed draft (%s) instead of surfacing it', async (_label, storedValue) => {
+ localStorage.setItem(draftKey, storedValue)
+ logic.actions.loadDraftQuery()
+ await expectLogic(logic).toMatchValues({ draftQuery: null, draftInsightRow: null })
+ expect(localStorage.getItem(draftKey)).toBeNull()
+ })
+
+ it('discarding a draft clears localStorage so it does not come back', async () => {
+ localStorage.setItem(draftKey, JSON.stringify(draft))
+ logic.actions.loadDraftQuery()
+ logic.actions.discardDraftQuery()
+ await expectLogic(logic).toMatchValues({ draftQuery: null, draftInsightRow: null })
+ await expectLogic(eventUsageLogic).toDispatchActions(['reportInsightDraftDiscarded'])
+ expect(localStorage.getItem(draftKey)).toBeNull()
+ })
+ })
})
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
index 2a42fe739b9a..2c3c2c28f45e 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
@@ -13,16 +13,18 @@ import { objectDiffShallow, objectsEqual } from 'lib/utils/objects'
import { toParams } from 'lib/utils/url'
import { deleteDashboardLogic } from 'scenes/dashboard/deleteDashboardLogic'
import { duplicateDashboardLogic } from 'scenes/dashboard/duplicateDashboardLogic'
+import { crushDraftQueryForLocalStorage, parseDraftQueryFromLocalStorage } from 'scenes/insights/utils'
import { insightsApi } from 'scenes/insights/utils/api'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'
-import { Breadcrumb, InsightModel, QueryBasedInsightModel, SavedInsightsTabs } from '~/types'
+import { Breadcrumb, InsightModel, QueryBasedInsightModel, SavedInsightsTabs, UserType } from '~/types'
import {
InsightBulkDeleteResponseApi,
@@ -33,6 +35,7 @@ import type { Node } from '../../queries/schema/schema-general'
import type { DeleteDashboardForm } from '../dashboard/deleteDashboardLogic'
import type { DuplicateDashboardForm } from '../dashboard/duplicateDashboardLogic'
import { teamLogic } from '../teamLogic'
+import { DraftInsightQuery, draftInsightListItem, isValidDraftInsightQuery } from './draftInsight'
export const INSIGHTS_PER_PAGE = 30
@@ -93,6 +96,7 @@ export function cleanFilters(values: Partial<SavedInsightFilters>): SavedInsight
export interface savedInsightsLogicValues {
activeSceneId: string | null // sceneLogic
currentTeamId: number | null // teamLogic
+ user: UserType | null // userLogic
breadcrumbs: Breadcrumb[]
bulkDeleteResponse: InsightBulkDeleteResponseApi | null
bulkDeleteResponseLoading: boolean
@@ -100,6 +104,8 @@ export interface savedInsightsLogicValues {
bulkRestoreResponseLoading: boolean
count: number
dashboardUpdatesInProgress: Record<number, boolean>
+ draftInsightRow: SavedInsightListItem | null
+ draftQuery: DraftInsightQuery | null
filters: SavedInsightFilters
insights: InsightsResult
insightsLoading: boolean
@@ -177,6 +183,9 @@ export interface savedInsightsLogicActions {
ids: number[]
}
}
+ discardDraftQuery: () => {
+ value: true
+ }
duplicateInsight: (
insight: QueryBasedInsightModel,
redirectToInsight?: any
@@ -184,6 +193,9 @@ export interface savedInsightsLogicActions {
insight: QueryBasedInsightModel<Node<Record<string, any>>>
redirectToInsight: any
}
+ loadDraftQuery: () => {
+ value: true
+ }
loadInsights: (debounce?: boolean) => {
debounce: boolean
}
@@ -215,6 +227,9 @@ export interface savedInsightsLogicActions {
insightId: number
loading: boolean
}
+ setDraftQuery: (draftQuery: DraftInsightQuery | null) => {
+ draftQuery: DraftInsightQuery | null
+ }
setSavedInsightsFilters: (
filters: Partial<SavedInsightFilters>,
merge?: boolean,
@@ -298,6 +313,11 @@ export interface savedInsightsLogicMeta {
user?: true | undefined
}
pagination: (filters: SavedInsightFilters, count: number) => PaginationManual
+ draftInsightRow: (
+ draftQuery: DraftInsightQuery | null,
+ user: UserType | null,
+ filters: SavedInsightFilters
+ ) => SavedInsightListItem | null
}
}
@@ -311,7 +331,7 @@ export type savedInsightsLogicType = MakeLogicType<
export const savedInsightsLogic = kea<savedInsightsLogicType>([
path(['scenes', 'saved-insights', 'savedInsightsLogic']),
connect(() => ({
- values: [teamLogic, ['currentTeamId'], sceneLogic, ['activeSceneId']],
+ values: [teamLogic, ['currentTeamId'], sceneLogic, ['activeSceneId'], userLogic, ['user']],
logic: [eventUsageLogic],
})),
actions({
@@ -330,6 +350,9 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
updateInsight: (insight: QueryBasedInsightModel) => ({ insight }),
addInsight: (insight: QueryBasedInsightModel) => ({ insight }),
setDashboardUpdateLoading: (insightId: number, loading: boolean) => ({ insightId, loading }),
+ loadDraftQuery: true,
+ setDraftQuery: (draftQuery: DraftInsightQuery | null) => ({ draftQuery }),
+ discardDraftQuery: true,
}),
loaders(({ values }) => ({
insights: {
@@ -451,6 +474,12 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
},
},
],
+ draftQuery: [
+ null as DraftInsightQuery | null,
+ {
+ setDraftQuery: (_, { draftQuery }) => draftQuery,
+ },
+ ],
}),
selectors({
filters: [
@@ -534,6 +563,16 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
}
},
],
+ draftInsightRow: [
+ (s) => [s.draftQuery, s.user, s.filters],
+ (
+ draftQuery: DraftInsightQuery | null,
+ user: UserType | null,
+ filters: SavedInsightFilters
+ ): SavedInsightListItem | null =>
+ // The draft is pinned to the top of the list, so it only belongs on the first page
+ draftQuery && filters.page === 1 ? draftInsightListItem(draftQuery, user) : null,
+ ],
[SIDE_PANEL_CONTEXT_KEY]: [
() => [],
(): SidePanelSceneContext => {
@@ -673,6 +712,48 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
bulkRestoreInsightsFailure: () => {
lemonToast.error('Failed to restore insights')
},
+ loadDraftQuery: () => {
+ if (!values.currentTeamId) {
+ actions.setDraftQuery(null)
+ return
+ }
+ const storageKey = `draft-query-${values.currentTeamId}`
+ const stored = localStorage.getItem(storageKey)
+ const parsed = stored ? parseDraftQueryFromLocalStorage(stored) : null
+ const draft = isValidDraftInsightQuery(parsed) ? parsed : null
+ if (stored && !draft) {
+ // A malformed draft would resurface (or crash the row) on every visit, so drop it for good
+ localStorage.removeItem(storageKey)
+ }
+ actions.setDraftQuery(draft)
+ },
+ discardDraftQuery: () => {
+ const draft = values.draftQuery
+ if (!draft) {
+ return
+ }
+ const storageKey = `draft-query-${values.currentTeamId}`
+ localStorage.removeItem(storageKey)
+ actions.setDraftQuery(null)
+ eventUsageLogic.actions.reportInsightDraftDiscarded(
+ Math.max(0, Math.round((Date.now() - draft.timestamp) / 1000))
+ )
+ lemonToast.info('Draft discarded', {
+ button: {
+ label: 'Undo',
+ action: () => {
+ // The editor may have written a newer draft since the discard — don't clobber it
+ if (localStorage.getItem(storageKey) === null) {
+ localStorage.setItem(
+ storageKey,
+ crushDraftQueryForLocalStorage(draft.query, draft.timestamp)
+ )
+ }
+ actions.loadDraftQuery()
+ },
+ },
+ })
+ },
})),
trackedActionToUrl(({ values }) => {
const changeUrl = ():
@@ -730,6 +811,9 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
return
}
+ // The insight editor may have written or cleared a draft since this logic mounted
+ actions.loadDraftQuery()
+
const currentFilters = cleanFilters(values.filters)
const nextFilters = cleanFilters(searchParams)
if (values.rawFilters === null || !objectsEqual(currentFilters, nextFilters)) {
@@ -737,4 +821,7 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
}
},
})),
+ afterMount(({ actions }) => {
+ actions.loadDraftQuery()
+ }),
])