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 { LogicWrapper, MakeLogicType, afterMount, kea, key, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import { performQuery } from '~/queries/query'
import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'

import { ListVariable } from '../../types'
import { getListVariableValues } from './variableUtils'

export interface VariableValuesLogicProps {
    variable: ListVariable
    loadOnMount: boolean
}

export interface VariableOption {
    value: string
    label: string
}

// Identifies which (connection, query) pair a load ran against, so consumers can tell
// whether the loaded options still match the variable being edited. Null means static options.
export const getValuesQueryKey = (variable: ListVariable): string | null => {
    const valuesQuery = variable.values_query?.trim()
    if (!valuesQuery) {
        return null
    }
    return `${variable.values_query_connection_id ?? ''}\n${valuesQuery}`
}

const isScalar = (value: unknown): value is string | number | boolean =>
    ['string', 'number', 'boolean'].includes(typeof value)

export const queryResultsToVariableOptions = (results: unknown): VariableOption[] => {
    if (!Array.isArray(results)) {
        return []
    }

    const options: VariableOption[] = []
    const seenValues = new Set<string>()
    for (const row of results) {
        const rawValue = Array.isArray(row) ? row[0] : row
        if (!isScalar(rawValue)) {
            continue
        }
        const value = String(rawValue)
        if (seenValues.has(value)) {
            continue
        }
        seenValues.add(value)
        const rawLabel = Array.isArray(row) ? row[1] : undefined
        options.push({ value, label: isScalar(rawLabel) ? String(rawLabel) : value })
    }

    return options
}

export const getStaticVariableOptions = (variable: ListVariable): VariableOption[] =>
    getListVariableValues(variable).map((value) => ({ value, label: value }))

export const loadListVariableOptions = async (variable: ListVariable): Promise<VariableOption[]> => {
    const valuesQuery = variable.values_query?.trim()
    if (!valuesQuery) {
        return getStaticVariableOptions(variable)
    }

    const response = await performQuery<HogQLQuery>({
        kind: NodeKind.HogQLQuery,
        query: valuesQuery,
        ...(variable.values_query_connection_id ? { connectionId: variable.values_query_connection_id } : {}),
    })

    return queryResultsToVariableOptions(response.results).slice(0, 1000)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variableValuesLogicValues {
    requestedValuesQueryKey: string | null
    variableOptions: VariableOption[]
    variableOptionsError: string | null
    variableOptionsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variableValuesLogicActions {
    loadVariableOptions: (variable?: ListVariable) => ListVariable
    loadVariableOptionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadVariableOptionsSuccess: (
        variableOptions: VariableOption[],
        payload?: ListVariable
    ) => {
        variableOptions: VariableOption[]
        payload?: ListVariable
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variableValuesLogicMeta {
    key: string
}

export type variableValuesLogicType = MakeLogicType<
    variableValuesLogicValues,
    variableValuesLogicActions,
    VariableValuesLogicProps,
    variableValuesLogicMeta
>

export const variableValuesLogic: LogicWrapper<variableValuesLogicType> = kea<variableValuesLogicType>([
    props({} as VariableValuesLogicProps),
    key((props) => props.variable.id || 'new'),
    path((key) => ['queries', 'nodes', 'DataVisualization', 'Variables', 'variableValuesLogic', key]),
    loaders(({ props }) => ({
        variableOptions: [
            [] as VariableOption[],
            {
                loadVariableOptions: async (variable?: ListVariable) =>
                    loadListVariableOptions(variable ?? props.variable),
            },
        ],
    })),
    reducers(({ props }) => ({
        requestedValuesQueryKey: [
            null as string | null,
            {
                loadVariableOptions: (_, variable) => getValuesQueryKey(variable ?? props.variable),
            },
        ],
        variableOptionsError: [
            null as string | null,
            {
                loadVariableOptions: () => null,
                loadVariableOptionsSuccess: () => null,
                loadVariableOptionsFailure: (_, { error, errorObject }) => errorObject?.detail ?? error,
            },
        ],
    })),
    afterMount(({ actions, props }) => {
        if (props.loadOnMount) {
            actions.loadVariableOptions(props.variable)
        }
    }),
])