: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
fix(workflows): warn before leaving unsaved workflow settings (#125464)
Meikel Ratz116e57bde895
diff --git a/products/workflows/frontend/scenes/settings/WorkflowsDailyLimitsSettings.tsx b/products/workflows/frontend/scenes/settings/WorkflowsDailyLimitsSettings.tsxindex 9ebc9d573a40..99e64048c224 100644--- a/products/workflows/frontend/scenes/settings/WorkflowsDailyLimitsSettings.tsx+++ b/products/workflows/frontend/scenes/settings/WorkflowsDailyLimitsSettings.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { useEffect, useState } from 'react'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'@@ -10,6 +10,8 @@ import { teamLogic } from 'scenes/teamLogic'import { TeamType } from '~/types'+import { unsavedSettingsLogic } from './unsavedSettingsLogic'+type WorkflowsConfig = NonNullable<TeamType['workflows_config']>type LimitField = {[Key in keyof WorkflowsConfig]-?: NonNullable<WorkflowsConfig[Key]> extends number ? Key : never@@ -44,6 +46,13 @@ export function WorkflowsDailyLimitsSettings({}: WorkflowsDailyLimitsSettingsProps): JSX.Element {const { currentTeam, currentTeamLoading } = useValues(teamLogic)const { updateCurrentTeam } = useActions(teamLogic)+ const unsavedGuard = unsavedSettingsLogic({+ sectionId: attrPrefix,+ message: `Leave without saving?\nThe ${unit} limits you entered will be discarded.`,+ })+ // useActions alone does not mount a logic, and the guard arms on mount.+ useMountedLogic(unsavedGuard)+ const { setHasUnsavedChanges } = useActions(unsavedGuard)const restrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,@@ -83,6 +92,10 @@ export function WorkflowsDailyLimitsSettings({const perProjectError = errorFor(perProject, savedPerProject, maxPerProject)const unchanged = perWorkflow === savedPerWorkflow && perProject === savedPerProject+ useEffect(() => {+ setHasUnsavedChanges(!unchanged)+ }, [unchanged, setHasUnsavedChanges])+return (<div className="@container"><div className="flex flex-wrap gap-4">diff --git a/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx b/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsxindex 9a3a92ad8761..b851ea1e56bd 100644--- a/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx+++ b/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { useEffect, useState } from 'react'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'@@ -14,10 +14,18 @@ import {frequencyCapFieldError,toFrequencyCapInputValue,} from './frequencyCap'+import { unsavedSettingsLogic } from './unsavedSettingsLogic'export function WorkflowsFrequencyCapSettings(): JSX.Element {const { currentTeam, currentTeamLoading } = useValues(teamLogic)const { updateCurrentTeam } = useActions(teamLogic)+ const unsavedGuard = unsavedSettingsLogic({+ sectionId: 'workflows-frequency-cap',+ message: 'Leave without saving?\nThe frequency cap you entered will be discarded.',+ })+ // useActions alone does not mount a logic, and the guard arms on mount.+ useMountedLogic(unsavedGuard)+ const { setHasUnsavedChanges } = useActions(unsavedGuard)const restrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,@@ -40,6 +48,10 @@ export function WorkflowsFrequencyCapSettings(): JSX.Element {const windowDaysError = frequencyCapFieldError(windowDays, maxMessages, MAX_FREQUENCY_CAP_WINDOW_DAYS)const unchanged = maxMessages === savedMaxMessages && windowDays === savedWindowDays+ useEffect(() => {+ setHasUnsavedChanges(!unchanged)+ }, [unchanged, setHasUnsavedChanges])+return (<div className="@container"><div className="flex flex-wrap gap-4">diff --git a/products/workflows/frontend/scenes/settings/unsavedSettingsLogic.test.ts b/products/workflows/frontend/scenes/settings/unsavedSettingsLogic.test.tsnew file mode 100644index 000000000000..305a2fa31df6--- /dev/null+++ b/products/workflows/frontend/scenes/settings/unsavedSettingsLogic.test.ts@@ -0,0 +1,69 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { removeProjectIdIfPresent } from 'lib/utils/kea-router'++import { initKeaTests } from '~/test/init'++import { unsavedSettingsLogic } from './unsavedSettingsLogic'++describe('unsavedSettingsLogic', () => {+ let logic: ReturnType<typeof unsavedSettingsLogic.build>+ const confirm = jest.fn()++ beforeEach(() => {+ initKeaTests()+ window.confirm = confirm+ confirm.mockReset()+ logic = unsavedSettingsLogic({ sectionId: 'test-section', message: 'Leave without saving?' })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ async function navigate(): Promise<void> {+ router.actions.push('/elsewhere')+ await expectLogic(router).toFinishAllListeners()+ }++ it('lets navigation through when nothing is unsaved', async () => {+ await navigate()++ expect(confirm).not.toHaveBeenCalled()+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual('/elsewhere')+ })++ it('keeps the person on the page when they cancel the prompt', async () => {+ confirm.mockReturnValue(false)+ logic.actions.setHasUnsavedChanges(true)++ await navigate()++ expect(confirm).toHaveBeenCalledWith('Leave without saving?')+ expect(removeProjectIdIfPresent(router.values.location.pathname)).not.toEqual('/elsewhere')+ expect(logic.values.hasUnsavedChanges).toBe(true)+ })++ it('stays quiet when only the hash changes', async () => {+ confirm.mockReturnValue(false)+ logic.actions.setHasUnsavedChanges(true)++ router.actions.push(`${router.values.location.pathname}#a-heading`)+ await expectLogic(router).toFinishAllListeners()++ expect(confirm).not.toHaveBeenCalled()+ expect(logic.values.hasUnsavedChanges).toBe(true)+ })++ it('navigates and disarms when they confirm', async () => {+ confirm.mockReturnValue(true)+ logic.actions.setHasUnsavedChanges(true)++ await navigate()++ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual('/elsewhere')+ expect(logic.values.hasUnsavedChanges).toBe(false)+ })+})diff --git a/products/workflows/frontend/scenes/settings/unsavedSettingsLogic.ts b/products/workflows/frontend/scenes/settings/unsavedSettingsLogic.tsnew file mode 100644index 000000000000..5a86350fdc22--- /dev/null+++ b/products/workflows/frontend/scenes/settings/unsavedSettingsLogic.ts@@ -0,0 +1,65 @@+import { MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'+import { beforeUnload, router } from 'kea-router'++export interface UnsavedSettingsLogicProps {+ /** Identifies the settings section, so two sections on one page track their edits apart. */+ sectionId: string+ message: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface unsavedSettingsLogicValues {+ hasUnsavedChanges: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface unsavedSettingsLogicActions {+ setHasUnsavedChanges: (hasUnsavedChanges: boolean) => {+ hasUnsavedChanges: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface unsavedSettingsLogicMeta {+ key: string+}++export type unsavedSettingsLogicType = MakeLogicType<+ unsavedSettingsLogicValues,+ unsavedSettingsLogicActions,+ UnsavedSettingsLogicProps,+ unsavedSettingsLogicMeta+>++// Switches and selects on this settings page save themselves on change, so a typed value in a+// Save-button section reads as saved and is lost on navigation unless something asks first.+export const unsavedSettingsLogic = kea<unsavedSettingsLogicType>([+ props({} as UnsavedSettingsLogicProps),+ key((props) => props.sectionId),+ path((key) => ['products', 'workflows', 'scenes', 'settings', 'unsavedSettingsLogic', key]),+ actions({+ setHasUnsavedChanges: (hasUnsavedChanges: boolean) => ({ hasUnsavedChanges }),+ }),+ reducers({+ hasUnsavedChanges: [+ false,+ {+ setHasUnsavedChanges: (_, { hasUnsavedChanges }) => hasUnsavedChanges,+ },+ ],+ }),+ beforeUnload(({ values, props, actions }) => ({+ enabled: (newLocation) => {+ if (!values.hasUnsavedChanges) {+ return false+ }+ // A heading's link icon only sets the hash. The section stays mounted and still+ // dirty, so prompting there would clear the flag while the edits are still at risk.+ return !newLocation || newLocation.pathname !== router.values.location.pathname+ },+ message: props.message,+ onConfirm: () => {+ actions.setHasUnsavedChanges(false)+ },+ })),+])