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, defaults, kea, listeners, path, props, reducers, selectors } from 'kea'

import { isWidgetConfigValidationError } from '../../utils'
import {
    widgetEditModalPropSelectors,
    widgetEditModalTileActions,
    buildWidgetTileMetadataPatch,
    getWidgetEditModalTileDefaults,
} from '../editWidgetModalBuilders'
import type { DashboardWidgetEditModalProps } from '../registry'
import {
    parseExperimentResultsWidgetConfig,
    validateExperimentResultsWidgetConfigInput,
    type ExperimentResultsWidgetFieldErrors,
} from './experimentsWidgetConfigValidation'

export type EditExperimentResultsWidgetModalLogicProps = Omit<DashboardWidgetEditModalProps, 'isOpen'>

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface editExperimentResultsWidgetModalLogicValues {
    activeFieldErrors: ExperimentResultsWidgetFieldErrors
    defaultTitle: string
    fieldErrors: ExperimentResultsWidgetFieldErrors
    onClose: () => void
    saveDisabledReason: string | undefined
    saving: boolean
    tileDescription: string
    tileName: string
    validation:
        | {
              fieldErrors: Partial<Record<'experimentId', string>>
              success: false
          }
        | {
              config: {
                  experimentId?: number | null | undefined
              }
              success: true
          }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface editExperimentResultsWidgetModalLogicActions {
    clearFieldError: (field: keyof ExperimentResultsWidgetFieldErrors) => {
        field: 'experimentId'
    }
    setFieldErrors: (fieldErrors: ExperimentResultsWidgetFieldErrors) => {
        fieldErrors: Partial<Record<'experimentId', string>>
    }
    setTileDescription: (tileDescription: string) => {
        tileDescription: string
    }
    setTileName: (tileName: string) => {
        tileName: string
    }
    submit: () => {
        value: true
    }
    submitFailure: () => {
        value: true
    }
    submitSuccess: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface editExperimentResultsWidgetModalLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        validation: (arg: any) =>
            | {
                  fieldErrors: Partial<Record<'experimentId', string>>
                  success: false
              }
            | {
                  config: {
                      experimentId?: number | null | undefined
                  }
                  success: true
              }
        activeFieldErrors: (
            validation:
                | {
                      config: {
                          experimentId?: number | null | undefined
                      }
                      success: true
                  }
                | {
                      fieldErrors: Partial<Record<'experimentId', string>>
                      success: false
                  },
            fieldErrors: Partial<Record<'experimentId', string>>
        ) => ExperimentResultsWidgetFieldErrors
        saveDisabledReason: (
            saving: boolean,
            validation:
                | {
                      config: {
                          experimentId?: number | null | undefined
                      }
                      success: true
                  }
                | {
                      fieldErrors: Partial<Record<'experimentId', string>>
                      success: false
                  }
        ) => string | undefined
    }
}

export type editExperimentResultsWidgetModalLogicType = MakeLogicType<
    editExperimentResultsWidgetModalLogicValues,
    editExperimentResultsWidgetModalLogicActions,
    EditExperimentResultsWidgetModalLogicProps,
    editExperimentResultsWidgetModalLogicMeta
>

export const editExperimentResultsWidgetModalLogic = kea<editExperimentResultsWidgetModalLogicType>([
    path(['products', 'dashboards', 'widgets', 'experiments', 'editExperimentResultsWidgetModalLogic']),

    props({
        config: {},
        onSave: async () => {},
        onClose: () => {},
        name: '',
        defaultTitle: 'Untitled',
        description: '',
    } as EditExperimentResultsWidgetModalLogicProps),

    actions({
        ...widgetEditModalTileActions,
        setFieldErrors: (fieldErrors: ExperimentResultsWidgetFieldErrors) => ({ fieldErrors }),
        clearFieldError: (field: keyof ExperimentResultsWidgetFieldErrors) => ({ field }),
        submit: true,
        submitSuccess: true,
        submitFailure: true,
    }),

    reducers({
        tileName: [
            '',
            {
                setTileName: (_: string, { tileName }: { tileName: string }) => tileName,
            },
        ],
        tileDescription: [
            '',
            {
                setTileDescription: (_: string, { tileDescription }: { tileDescription: string }) => tileDescription,
            },
        ],
        fieldErrors: [
            {} as ExperimentResultsWidgetFieldErrors,
            {
                setFieldErrors: (
                    _: ExperimentResultsWidgetFieldErrors,
                    { fieldErrors }: { fieldErrors: ExperimentResultsWidgetFieldErrors }
                ) => fieldErrors,
                clearFieldError: (
                    state: ExperimentResultsWidgetFieldErrors,
                    { field }: { field: keyof ExperimentResultsWidgetFieldErrors }
                ) => {
                    if (!state[field]) {
                        return state
                    }
                    const next = { ...state }
                    delete next[field]
                    return next
                },
            },
        ],
        saving: [
            false,
            {
                submit: (_state: boolean, _payload: { value: true }) => true,
                submitSuccess: (_state: boolean, _payload: { value: true }) => false,
                submitFailure: (_state: boolean, _payload: { value: true }) => false,
            },
        ],
    }),

    selectors({
        ...widgetEditModalPropSelectors,
        validation: [
            // The experiment is chosen on the tile filter bar; read it from the persisted config so saving
            // the tile name/description preserves the selection.
            () => [(_, props) => props.config],
            (config) =>
                validateExperimentResultsWidgetConfigInput({
                    experimentId: parseExperimentResultsWidgetConfig(config).experimentId ?? null,
                }),
        ],
        activeFieldErrors: [
            (s) => [s.validation, s.fieldErrors],
            (
                validation:
                    | {
                          config: {
                              experimentId?: number | null | undefined
                          }
                          success: true
                      }
                    | {
                          fieldErrors: Partial<Record<'experimentId', string>>
                          success: false
                      },
                fieldErrors: ExperimentResultsWidgetFieldErrors
            ): ExperimentResultsWidgetFieldErrors => {
                if (!validation.success) {
                    return { ...validation.fieldErrors, ...fieldErrors }
                }
                return fieldErrors
            },
        ],
        saveDisabledReason: [
            (s) => [s.saving, s.validation],
            (
                saving: boolean,
                validation:
                    | {
                          config: {
                              experimentId?: number | null | undefined
                          }
                          success: true
                      }
                    | {
                          fieldErrors: Partial<Record<'experimentId', string>>
                          success: false
                      }
            ): string | undefined => {
                if (saving) {
                    return 'Saving…'
                }
                if (!validation.success) {
                    return 'Fix validation errors to save'
                }
                return undefined
            },
        ],
    }),

    defaults(({ props }) => ({
        ...getWidgetEditModalTileDefaults(props),
        fieldErrors: {},
        saving: false,
    })),

    listeners(({ actions, props, values }) => ({
        submit: async () => {
            const result = values.validation

            if (!result.success) {
                actions.setFieldErrors(result.fieldErrors)
                return
            }

            try {
                await props.onSave(
                    result.config,
                    buildWidgetTileMetadataPatch(props, values.tileName, values.tileDescription)
                )
                actions.setFieldErrors({})
                props.onClose()
                actions.submitSuccess()
            } catch (error) {
                actions.submitFailure()
                if (isWidgetConfigValidationError(error)) {
                    actions.setFieldErrors(error.fieldErrors as ExperimentResultsWidgetFieldErrors)
                    return
                }
                throw error
            }
        },
    })),
])