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.

9.2 KB
Raw Blame
import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'

import { objectsEqual } from 'lib/utils/objects'

import { FeatureFlagType } from '~/types'

import { openConfirmationModal } from './ConfirmationModal'
import { openFeatureFlagDisableDialog } from './featureFlagDisableDialog'
import { DependentFlag } from './featureFlagLogic'

/**
 * Detects feature flag changes that warrant confirmation.
 *
 * Detects the following types of changes:
 * - Active status (enabled/disabled)
 * - Rollout percentage changes
 * - Variant changes (adding/removing/modifying variants)
 * - Release condition changes (properties, targeting)
 * - Payload changes
 * - Other filter configuration changes
 *
 * Note: Some changes like name, description, and tags do NOT trigger confirmation
 * as they don't directly impact user experience.
 */
function detectFeatureFlagChanges(
    originalFlag: FeatureFlagType | null,
    updatedFlag: Partial<FeatureFlagType>
): string[] {
    const changes: string[] = []

    // Don't require confirmation for new flags
    if (!originalFlag || !updatedFlag.id) {
        return changes
    }

    // Check for active status changes
    let statusChanged = false
    if (originalFlag.active !== updatedFlag.active) {
        if (updatedFlag.active) {
            changes.push('Enable the feature flag')
        } else {
            changes.push('Disable the feature flag')
        }
        statusChanged = true
    }

    // Check for any filter changes (comprehensive detection).
    // objectsEqual (fast-deep-equal) compares bigint filter values directly instead of
    // serialising them, which JSON.stringify can't do (it throws on bigint).
    if (!objectsEqual(originalFlag.filters || {}, updatedFlag.filters || {})) {
        // Try to detect specific types of changes for better messaging
        const originalGroups = originalFlag.filters?.groups || []
        const updatedGroups = updatedFlag.filters?.groups || []

        // Check for rollout percentage changes
        const rolloutChanged = originalGroups.some((group, index) => {
            const updatedGroup = updatedGroups[index]
            return updatedGroup && group.rollout_percentage !== updatedGroup.rollout_percentage
        })

        // Check for variant changes
        const originalVariants = originalFlag.filters?.multivariate?.variants || []
        const updatedVariants = updatedFlag.filters?.multivariate?.variants || []
        const variantsChanged = !objectsEqual(originalVariants, updatedVariants)

        // Check for release condition changes (properties, etc.)
        const conditionsChanged = originalGroups.some((group, index) => {
            const updatedGroup = updatedGroups[index]
            return updatedGroup && !objectsEqual(group.properties || [], updatedGroup.properties || [])
        })

        // Check for payload changes
        const originalPayloads = originalFlag.filters?.payloads || {}
        const updatedPayloads = updatedFlag.filters?.payloads || {}
        const payloadsChanged = !objectsEqual(originalPayloads, updatedPayloads)

        // Add specific change messages
        if (rolloutChanged) {
            changes.push('Release condition rollout percentage changed')
        }
        if (variantsChanged) {
            if (updatedVariants.length > originalVariants.length) {
                changes.push('Variants added to feature flag')
            } else if (updatedVariants.length < originalVariants.length) {
                changes.push('Variants removed from feature flag')
            } else {
                changes.push('Variant configurations changed')
            }
        }
        if (conditionsChanged) {
            changes.push('Release conditions changed')
        }
        if (payloadsChanged) {
            changes.push('Payloads changed')
        }

        // If we haven't caught the specific change, add a generic message
        if (!rolloutChanged && !variantsChanged && !conditionsChanged && !payloadsChanged && !statusChanged) {
            changes.push('Feature flag configuration changed')
        }
    }

    return changes
}

// Utility function for checking if confirmation is needed and showing modal
export function checkFeatureFlagConfirmation(
    originalFlag: FeatureFlagType | null,
    updatedFlag: FeatureFlagType,
    shouldDisplayConfirmation: boolean,
    customConfirmationMessage: string | undefined,
    featureFlagConfirmationEnabled: boolean,
    onConfirm: () => void,
    dependentFlags?: DependentFlag[],
    isBeingDisabled?: boolean,
    requireStatusConfirmation = false,
    onDisableAndArchive?: () => void,
    releasesToEveryone = false
): boolean {
    // Check if confirmation is needed
    const needsConfirmation = !!updatedFlag.id && (shouldDisplayConfirmation || releasesToEveryone)

    if (needsConfirmation) {
        const changes = detectFeatureFlagChanges(originalFlag, updatedFlag)

        if (changes.length > 0) {
            // Show confirmation modal
            openConfirmationModal({
                featureFlag: updatedFlag,
                type: 'multi-changes',
                changes: changes,
                customConfirmationMessage: customConfirmationMessage,
                dependentFlags: dependentFlags,
                isBeingDisabled: isBeingDisabled,
                featureFlagConfirmationEnabled: featureFlagConfirmationEnabled,
                releasesToEveryone: releasesToEveryone,
                onConfirm: onConfirm,
            })
            return true // Confirmation modal shown, don't proceed with save
        }
    }

    if (requireStatusConfirmation && originalFlag?.active !== updatedFlag.active) {
        const openStatusConfirmationModal = (onConfirmModal?: () => void, onCancelModal?: () => void): void =>
            openConfirmationModal({
                featureFlag: updatedFlag,
                type: 'flag-status',
                activeNewValue: updatedFlag.active,
                onConfirm: onConfirmModal ?? onConfirm,
                onCancel: onCancelModal,
            })

        // Disabling offers "Disable and archive" alongside "Disable only". Deliberately below the
        // confirmation gate: a flag with dependents, or a team that set up its own confirmation,
        // gets that modal instead.
        if (!updatedFlag.active && onDisableAndArchive) {
            openFeatureFlagDisableDialog({
                source: 'feature-flag-detail',
                filters: updatedFlag.filters,
                onDisable: onConfirm,
                onDisableAndArchive,
            })
            return true
        }
        openStatusConfirmationModal()
        return true
    }

    return false // No confirmation needed, proceed with save
}

export interface FeatureFlagConfirmationLogicProps {
    featureFlag: FeatureFlagType
    onConfirm: () => void
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagConfirmationLogicValues {
    flagChanges: string[]
    hasChanges: boolean
    showSaveConfirmModal: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagConfirmationLogicActions {
    confirmChanges: () => {
        value: true
    }
    setFlagChanges: (changes: string[]) => {
        changes: string[]
    }
    showConfirmationModal: (show: boolean) => {
        show: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagConfirmationLogicMeta {
    key: number | 'new'
    __keaTypeGenInternalSelectorTypes: {
        hasChanges: (flagChanges: string[]) => boolean
    }
}

export type featureFlagConfirmationLogicType = MakeLogicType<
    featureFlagConfirmationLogicValues,
    featureFlagConfirmationLogicActions,
    FeatureFlagConfirmationLogicProps,
    featureFlagConfirmationLogicMeta
>

export const featureFlagConfirmationLogic = kea<featureFlagConfirmationLogicType>([
    path(['scenes', 'feature-flags', 'featureFlagConfirmationLogic']),
    props({} as FeatureFlagConfirmationLogicProps),
    key(({ featureFlag }) => featureFlag.id ?? 'new'),
    actions({
        setFlagChanges: (changes: string[]) => ({ changes }),
        showConfirmationModal: (show: boolean) => ({ show }),
        confirmChanges: true,
    }),
    reducers({
        flagChanges: [
            [] as string[],
            {
                setFlagChanges: (_, { changes }: { changes: string[] }) => changes,
            },
        ],
        showSaveConfirmModal: [
            false,
            {
                showConfirmationModal: (_, { show }: { show: boolean }) => show,
            },
        ],
    }),
    selectors({
        hasChanges: [(s) => [s.flagChanges], (changes: string[]) => changes.length > 0],
    }),
    listeners(({ values, props }) => ({
        confirmChanges: () => {
            if (values.hasChanges) {
                openConfirmationModal({
                    featureFlag: props.featureFlag,
                    type: 'multi-changes',
                    changes: values.flagChanges,
                    onConfirm: props.onConfirm,
                })
            } else {
                props.onConfirm()
            }
        },
    })),
])

// Export the function for reuse in tests
export { detectFeatureFlagChanges }