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.

7.9 KB
Raw Blame
import posthog from 'posthog-js'

import { IconWarning } from '@posthog/icons'
import { LemonDialog, Link } from '@posthog/lemon-ui'

import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'

import { FeatureFlagType } from '~/types'

import { DependentFlag } from './featureFlagLogic'

type ConfirmationModalType = 'flag-status' | 'rollout' | 'multi-changes'

interface ConfirmationModalProps {
    featureFlag: FeatureFlagType
    type: ConfirmationModalType
    activeNewValue?: boolean // Only for flag-status type
    changes?: string[] // Only for multi-changes type
    customConfirmationMessage?: string // Custom confirmation message to replace default message
    dependentFlags?: DependentFlag[] // Feature flags that depend on this flag (only shown when disabling)
    isBeingDisabled?: boolean // Whether the flag is being disabled (controls dependent flags warning)
    featureFlagConfirmationEnabled?: boolean // Whether the team has feature flag confirmation enabled in settings
    releasesToEveryone?: boolean // Whether saving turns the flag on for everyone (only for multi-changes type)
    onConfirm: () => void
    onCancel?: () => void
}

function WarningCallout({ title, children }: { title: string; children: React.ReactNode }): JSX.Element {
    return (
        <div className="mt-4 p-3 border border-warning bg-warning-highlight rounded">
            <p className="my-0 flex items-center gap-2">
                <IconWarning className="text-warning" />
                <strong>{title}</strong>
            </p>
            <p className="mb-0">{children}</p>
        </div>
    )
}

/**
 * Opens a confirmation dialog for feature flag changes.
 * This is used for confirming status changes, rollout changes, or multiple changes at once.
 */
export function openConfirmationModal({
    featureFlag,
    type,
    activeNewValue,
    changes = [],
    customConfirmationMessage,
    dependentFlags,
    isBeingDisabled = false,
    featureFlagConfirmationEnabled = false,
    releasesToEveryone = false,
    onConfirm,
    onCancel,
}: ConfirmationModalProps): void {
    let title: string
    let description: JSX.Element

    switch (type) {
        case 'flag-status': {
            const action = activeNewValue ? 'enable' : 'disable'
            const actionCapitalized = capitalizeFirstLetter(action)
            const actionEffect = activeNewValue ? 'activate' : 'deactivate'

            title = `${actionCapitalized} feature flag "${featureFlag.key}"?`
            description = (
                <>
                    <p>
                        Are you sure you want to {action} this feature flag? This will {actionEffect} it for all users
                        within the release conditions.
                    </p>
                    <p>
                        Changes to feature flags can significantly impact your application. Please ensure you understand
                        the consequences of this change.
                    </p>
                </>
            )
            break
        }
        case 'rollout': {
            title = `Update rollout conditions for "${featureFlag.key}"?`
            description = (
                <>
                    <p>
                        Are you sure you want to update the rollout conditions for this feature flag? This will change
                        which users the flag is enabled for.
                    </p>
                    <p>
                        Changes to rollout conditions can significantly impact your application's behavior. Please
                        ensure you understand the consequences of this change.
                    </p>
                </>
            )
            break
        }
        case 'multi-changes': {
            title = `Confirm changes to feature flag "${featureFlag.key}"?`
            const defaultMessage =
                '⚠️ These changes will immediately affect users matching the release conditions. Please ensure you understand the consequences before proceeding.'

            const allMessages: React.ReactNode[] = []

            if (customConfirmationMessage) {
                allMessages.push(customConfirmationMessage)
            } else if (featureFlagConfirmationEnabled) {
                allMessages.push(defaultMessage)
            }

            description = (
                <>
                    <p>You are about to save the following changes:</p>
                    <ul className="ml-4 mt-2 list-disc">
                        {changes.map((change, index) => (
                            <li key={index}>{change}</li>
                        ))}
                    </ul>
                    {releasesToEveryone && (
                        <WarningCallout title="This releases the flag to all users">
                            After you save, every user who evaluates <strong>{featureFlag.key}</strong> gets it
                            immediately.
                        </WarningCallout>
                    )}
                    {isBeingDisabled && dependentFlags && dependentFlags.length > 0 && (
                        <WarningCallout title="Cannot disable this feature flag">
                            This flag is referenced by {dependentFlags.length} other feature flag
                            {dependentFlags.length === 1 ? '' : 's'}:{' '}
                            {dependentFlags.map((flag, index) => (
                                <span key={flag.id}>
                                    {index > 0 && (index === dependentFlags.length - 1 ? ' and ' : ', ')}
                                    <Link
                                        to={urls.featureFlag(flag.id)}
                                        target="_blank"
                                        aria-label={`Open ${flag.key}`}
                                    >
                                        <strong>{flag.key}</strong>
                                    </Link>
                                </span>
                            ))}
                            . Please update or disable the dependent flags first.
                        </WarningCallout>
                    )}
                    {allMessages.map((message, index) => (
                        <p key={index} className="mt-4">
                            {message}
                        </p>
                    ))}
                </>
            )
            break
        }
    }

    // Determine if the primary button should be disabled
    const hasBlockingDependentFlags = isBeingDisabled && dependentFlags && dependentFlags.length > 0
    let confirmed = false

    if (releasesToEveryone) {
        // pinned: analytics event names
        posthog.capture('feature flag release to everyone confirmation shown')
    }

    LemonDialog.open({
        title,
        description,
        primaryButton: {
            children:
                type === 'flag-status'
                    ? `${capitalizeFirstLetter(activeNewValue ? 'enable' : 'disable')} flag`
                    : type === 'rollout'
                      ? 'Update conditions'
                      : releasesToEveryone
                        ? 'Release to all users'
                        : 'Save changes',
            status: type === 'flag-status' && !activeNewValue ? 'danger' : 'default',
            onClick: hasBlockingDependentFlags
                ? undefined
                : () => {
                      confirmed = true
                      onConfirm()
                  },
            disabled: hasBlockingDependentFlags,
        },
        secondaryButton: {
            children: 'Cancel',
            onClick: onCancel,
        },
        // Escape, the close icon and the overlay skip the Cancel button, so count every close without a confirm.
        onAfterClose: () => {
            if (releasesToEveryone && !confirmed) {
                posthog.capture('feature flag release to everyone confirmation canceled')
            }
        },
    })
}