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.

4.9 KB
Raw Blame
import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { createFuse } from 'lib/utils/fuseSearch'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

import { toolbarApi } from '~/toolbar/shared/toolbarApi'
import { WebExperiment } from '~/toolbar/shared/types'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentsLogicValues {
    allExperiments: WebExperiment[]
    allExperimentsLoading: boolean
    experimentCount: number
    searchTerm: string
    sortedExperiments: WebExperiment[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentsLogicActions {
    deleteExperiment: ({ id }: { id: number }) => {
        id: number
    }
    deleteExperimentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteExperimentSuccess: (
        allExperiments: WebExperiment[],
        payload?: {
            id: number
        }
    ) => {
        allExperiments: WebExperiment[]
        payload?: {
            id: number
        }
    }
    getExperiments: (_?: any) => any
    getExperimentsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    getExperimentsSuccess: (
        allExperiments: WebExperiment[],
        payload?: any
    ) => {
        allExperiments: WebExperiment[]
        payload?: any
    }
    setSearchTerm: (searchTerm: string) => {
        searchTerm: string
    }
    updateExperiment: ({ experiment }: { experiment: WebExperiment }) => {
        experiment: WebExperiment
    }
    updateExperimentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateExperimentSuccess: (
        allExperiments: WebExperiment[],
        payload?: {
            experiment: WebExperiment
        }
    ) => {
        allExperiments: WebExperiment[]
        payload?: {
            experiment: WebExperiment
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        sortedExperiments: (allExperiments: WebExperiment[], searchTerm: string) => WebExperiment[]
        experimentCount: (allExperiments: WebExperiment[]) => number
    }
}

export type experimentsLogicType = MakeLogicType<
    experimentsLogicValues,
    experimentsLogicActions,
    Record<string, any>,
    experimentsLogicMeta
>

export const experimentsLogic = kea<experimentsLogicType>([
    path(['toolbar', 'experiments', 'experimentsLogic']),
    actions({
        setSearchTerm: (searchTerm: string) => ({ searchTerm }),
    }),
    loaders(({ values }) => ({
        allExperiments: [
            [] as WebExperiment[],
            {
                // oxlint-disable-next-line @typescript-eslint/no-unused-vars
                getExperiments: async (_ = null, breakpoint: () => void) => {
                    const result = await toolbarApi.webExperiments.list({
                        context: 'load_experiments',
                        reauthenticateOnForbidden: true,
                    })
                    breakpoint()

                    // Any failure (unauthenticated, server error, malformed body) soft-fails to
                    // the existing list — toolbarApi has already logged/reported it as needed.
                    if (!result.ok || !Array.isArray(result.data.results)) {
                        return values.allExperiments
                    }
                    return result.data.results
                },
                updateExperiment: ({ experiment }: { experiment: WebExperiment }) => {
                    return values.allExperiments.filter((r) => r.id !== experiment.id).concat([experiment])
                },
                deleteExperiment: ({ id }: { id: number }) => {
                    return values.allExperiments.filter((r) => r.id !== id)
                },
            },
        ],
    })),
    reducers({
        searchTerm: [
            '',
            {
                setSearchTerm: (_, { searchTerm }) => searchTerm,
            },
        ],
    }),
    selectors({
        sortedExperiments: [
            (s) => [s.allExperiments, s.searchTerm],
            (allExperiments: WebExperiment[], searchTerm: string) => {
                const filteredExperiments = searchTerm
                    ? createFuse(allExperiments, {
                          keys: ['name'],
                      })
                          .search(searchTerm)
                          .map(({ item }) => item)
                    : allExperiments
                return [...filteredExperiments]
            },
        ],
        experimentCount: [(s) => [s.allExperiments], (allExperiments: WebExperiment[]) => allExperiments.length],
    }),
    permanentlyMount(),
])