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.

19.9 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
    selectors,
} from 'kea'
import { subscriptions } from 'kea-subscriptions'

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

import {
    getVariablesFromQuery,
    haveVariablesOrFiltersChanged,
    syncSelectedVariablesToQuery,
} from '~/queries/nodes/InsightViz/queryUtils'
import { VisualizationNode, HogQLVariable } from '~/queries/schema/schema-general'
import { DashboardType } from '~/types'

import type { DataNode, RefreshType } from '../../../../schema/schema-general'
import { dataVisualizationLogic } from '../../dataVisualizationLogic'
import { Variable, VariableType } from '../../types'
import { variableDataLogic } from './variableDataLogic'

export interface VariablesLogicProps {
    key: string
    /** Disable any changes to the query */
    readOnly: boolean
    /** Dashboard ID for the current dashboard if we're viewing one */
    dashboardId?: DashboardType['id']

    sourceQuery?: VisualizationNode
    setQuery?: (query: VisualizationNode) => void
    onUpdate?: (query: VisualizationNode) => void
}

const convertValueToCorrectType = (value: unknown, type: VariableType): unknown => {
    if (type === 'List' && Array.isArray(value)) {
        return value.map(String)
    }

    if (type === 'Number') {
        return Number(value)
    }

    if (type === 'Boolean' && typeof value === 'string') {
        return value.toLowerCase() === 'true'
    }

    return typeof value === 'string' ? value : String(value ?? '')
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variablesLogicValues {
    query: VisualizationNode // dataVisualizationLogic
    variables: Variable[] // variableDataLogic
    variablesLoading: boolean // variableDataLogic
    editorQuery: string | null
    filteredVariables: (Variable & {
        selected: boolean
    })[]
    internalSelectedVariables: HogQLVariable[]
    queryVariableCodeNames: string[]
    searchTerm: string
    showVariablesBar: boolean
    variablesForInsight: Variable[]
    variablesNotInQuery: Variable[]
    variablesUsedInQuery: Variable[]
    variablesWithValues: Variable[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variablesLogicActions {
    loadData: (
        refresh?: RefreshType | undefined,
        alreadyRunningQueryId?: string | undefined,
        overrideQuery?: DataNode<Record<string, any>> | undefined
    ) => {
        overrideQuery: DataNode<Record<string, any>> | undefined
        pollOnly: boolean
        queryId: string
        refresh: RefreshType | undefined
    } // dataVisualizationLogic
    setQuery: (setter: (node: VisualizationNode) => VisualizationNode) => {
        setter: (node: VisualizationNode) => VisualizationNode
    } // dataVisualizationLogic
    loadVariables: () => any // variableDataLogic
    _addVariable: (variable: HogQLVariable) => {
        variable: HogQLVariable
    }
    _removeVariable: (variableId: string) => {
        variableId: string
    }
    addVariable: (variable: HogQLVariable) => {
        variable: HogQLVariable
    }
    addVariables: (variables: HogQLVariable[]) => {
        variables: HogQLVariable[]
    }
    clickVariable: (
        variable: Variable & {
            selected: boolean
        }
    ) => {
        variable: Variable & {
            selected: boolean
        }
    }
    removeVariable: (variableId: string) => {
        variableId: string
    }
    resetVariables: () => {
        value: true
    }
    setEditorQuery: (query: string) => {
        query: string
    }
    setSearchTerm: (search: string) => {
        search: string
    }
    updateInternalSelectedVariable: (variable: HogQLVariable) => {
        variable: HogQLVariable
    }
    updateSourceQuery: () => {
        value: true
    }
    updateVariableValue: (
        variableId: string,
        value: any,
        isNull: boolean
    ) => {
        allVariables: Variable[]
        isNull: boolean
        value: any
        variableId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface variablesLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        queryVariableCodeNames: (editorQuery: string | null, arg: any) => string[]
        variablesWithValues: (variables: Variable[], internalSelectedVariables: HogQLVariable[]) => Variable[]
        variablesForInsight: (
            variables: Variable[],
            internalSelectedVariables: HogQLVariable[],
            queryVariableCodeNames: string[]
        ) => Variable[]
        showVariablesBar: (arg: any) => boolean
        filteredVariables: (
            variables: Variable[],
            searchTerm: string,
            internalSelectedVariables: HogQLVariable[]
        ) => (Variable & {
            selected: boolean
        })[]
        variablesUsedInQuery: (
            variablesWithValues: Variable[],
            queryVariableCodeNames: string[],
            searchTerm: string
        ) => Variable[]
        variablesNotInQuery: (
            variablesWithValues: Variable[],
            queryVariableCodeNames: string[],
            searchTerm: string
        ) => Variable[]
    }
}

export type variablesLogicType = MakeLogicType<
    variablesLogicValues,
    variablesLogicActions,
    VariablesLogicProps,
    variablesLogicMeta
>

export const variablesLogic = kea<variablesLogicType>([
    path(['queries', 'nodes', 'DataVisualization', 'Components', 'Variables', 'variablesLogic']),
    props({ key: '' } as VariablesLogicProps),
    key((props) => props.key),
    connect(() => ({
        actions: [dataVisualizationLogic, ['setQuery', 'loadData'], variableDataLogic, ['loadVariables']],
        values: [dataVisualizationLogic, ['query'], variableDataLogic, ['variables', 'variablesLoading']],
    })),
    actions(({ values }) => ({
        addVariable: (variable: HogQLVariable) => ({ variable }),
        _addVariable: (variable: HogQLVariable) => ({ variable }),
        addVariables: (variables: HogQLVariable[]) => ({ variables }),
        removeVariable: (variableId: string) => ({ variableId }),
        _removeVariable: (variableId: string) => ({ variableId }),
        updateVariableValue: (variableId: string, value: any, isNull: boolean) => ({
            variableId,
            value,
            isNull,
            allVariables: values.variables,
        }),
        setEditorQuery: (query: string) => ({ query }),
        updateSourceQuery: true,
        resetVariables: true,
        updateInternalSelectedVariable: (variable: HogQLVariable) => ({ variable }),
        setSearchTerm: (search: string) => ({ search }),
        clickVariable: (variable: Variable & { selected: boolean }) => ({ variable }),
    })),
    propsChanged(({ props, actions, values }) => {
        if (props.sourceQuery) {
            const variables = Object.values(props.sourceQuery?.source?.variables ?? {})

            if (variables.length) {
                variables.forEach((variable) => {
                    actions._addVariable(variable)
                })
            }

            values.internalSelectedVariables.forEach((variable) => {
                if (!variables.map((n) => n.variableId).includes(variable.variableId)) {
                    actions._removeVariable(variable.variableId)
                }
            })
        }
    }),
    reducers({
        internalSelectedVariables: [
            [] as HogQLVariable[],
            {
                addVariable: (state, { variable }) => {
                    if (state.find((n) => variable.variableId === n.variableId)) {
                        return state
                    }

                    return [...state, { ...variable }]
                },
                _addVariable: (state, { variable }) => {
                    if (state.find((n) => variable.variableId === n.variableId)) {
                        return state
                    }

                    return [...state, { ...variable }]
                },
                addVariables: (_state, { variables }) => {
                    return variables.map((n) => ({ ...n }))
                },
                updateVariableValue: (state, { variableId, value, isNull, allVariables }) => {
                    const variableIndex = state.findIndex((n) => n.variableId === variableId)
                    if (variableIndex < 0) {
                        return state
                    }

                    const variableType = allVariables.find((n) => n.id === variableId)?.type
                    const valueWithType = convertValueToCorrectType(value, variableType ?? 'String')
                    const variablesInState = [...state]
                    variablesInState[variableIndex] = {
                        ...variablesInState[variableIndex],
                        value: valueWithType,
                        isNull,
                    }

                    return variablesInState
                },
                removeVariable: (state, { variableId }) => {
                    const stateCopy = [...state]
                    const index = stateCopy.findIndex((n) => n.variableId === variableId)
                    if (index >= 0) {
                        stateCopy.splice(index, 1)
                    }

                    return stateCopy
                },
                _removeVariable: (state, { variableId }) => {
                    const stateCopy = [...state]
                    const index = stateCopy.findIndex((n) => n.variableId === variableId)
                    if (index >= 0) {
                        stateCopy.splice(index, 1)
                    }

                    return stateCopy
                },
                resetVariables: () => {
                    return []
                },
                updateInternalSelectedVariable: (state, { variable }) => {
                    const variableIndex = state.findIndex((n) => n.variableId === variable.variableId)
                    if (variableIndex < 0) {
                        return state
                    }
                    const variablesInState = [...state]
                    variablesInState[variableIndex] = {
                        ...variable,
                    }

                    return variablesInState
                },
            },
        ],
        editorQuery: [
            null as string | null,
            {
                setEditorQuery: (_, { query }) => query,
            },
        ],
        searchTerm: [
            '' as string,
            {
                setSearchTerm: (_, { search }) => search,
            },
        ],
    }),
    selectors({
        queryVariableCodeNames: [
            (s) => [s.editorQuery, (_, props) => props.sourceQuery?.source?.query],
            (editorQuery: string | null, sourceQuery): string[] => {
                const matches = getVariablesFromQuery(editorQuery ?? sourceQuery ?? '')
                return Array.from(new Set(matches.filter((match): match is string => Boolean(match))))
            },
        ],
        variablesWithValues: [
            (s) => [s.variables, s.internalSelectedVariables],
            (variables: Variable[], internalSelectedVariables: HogQLVariable[]): Variable[] => {
                return variables.map((variable) => {
                    const selectedVariable = internalSelectedVariables.find(
                        (selected) => selected.variableId === variable.id
                    )
                    if (!selectedVariable) {
                        return variable
                    }

                    return {
                        ...variable,
                        value: selectedVariable.value,
                        isNull: selectedVariable.isNull,
                    }
                })
            },
        ],
        variablesForInsight: [
            (s) => [s.variables, s.internalSelectedVariables, s.queryVariableCodeNames],
            (
                variables: Variable[],
                internalSelectedVariables: HogQLVariable[],
                queryVariableCodeNames: string[]
            ): Variable[] => {
                if (!variables.length || !internalSelectedVariables.length) {
                    return []
                }

                const queryCodeNames = new Set(queryVariableCodeNames)

                return internalSelectedVariables
                    .map(({ variableId, value, isNull }) => {
                        const v = variables.find((n) => n.id === variableId)
                        if (v) {
                            return { ...v, value, isNull } as Variable
                        }

                        return undefined
                    })
                    .filter((variable): variable is Variable => variable !== undefined)
                    .filter((variable) => queryCodeNames.has(variable.code_name))
            },
        ],
        showVariablesBar: [
            () => [(_, props) => props.dashboardId],
            (dashboardId) => {
                return !dashboardId
            },
        ],
        filteredVariables: [
            (s) => [s.variables, s.searchTerm, s.internalSelectedVariables],
            (
                variables: Variable[],
                searchTerm: string,
                internalSelectedVariables: HogQLVariable[]
            ): (Variable & { selected: boolean })[] => {
                const selectedVariableIds = new Set(internalSelectedVariables.map((variable) => variable.variableId))

                const trimmedSearch = searchTerm.trim().toLowerCase()

                const visibleVariables = trimmedSearch
                    ? variables.filter((variable) => {
                          const nameMatch = variable.name.toLowerCase().includes(trimmedSearch)
                          const codeNameMatch = variable.code_name?.toLowerCase().includes(trimmedSearch)
                          const typeMatch = variable.type.toLowerCase().includes(trimmedSearch)

                          return nameMatch || codeNameMatch || typeMatch
                      })
                    : variables

                return [...visibleVariables]
                    .sort((a, b) => a.name.localeCompare(b.name))
                    .map((variable) => ({
                        ...variable,
                        selected: selectedVariableIds.has(variable.id),
                    }))
            },
        ],
        variablesUsedInQuery: [
            (s) => [s.variablesWithValues, s.queryVariableCodeNames, s.searchTerm],
            (variablesWithValues: Variable[], queryVariableCodeNames: string[], searchTerm: string): Variable[] => {
                const queryCodeNames = new Set(queryVariableCodeNames)
                const trimmedSearch = searchTerm.trim().toLowerCase()

                const visibleVariables = trimmedSearch
                    ? variablesWithValues.filter((variable) => {
                          const nameMatch = variable.name.toLowerCase().includes(trimmedSearch)
                          const codeNameMatch = variable.code_name?.toLowerCase().includes(trimmedSearch)
                          const typeMatch = variable.type.toLowerCase().includes(trimmedSearch)

                          return nameMatch || codeNameMatch || typeMatch
                      })
                    : variablesWithValues

                return visibleVariables
                    .filter((variable) => queryCodeNames.has(variable.code_name))
                    .sort((a, b) => a.name.localeCompare(b.name))
            },
        ],
        variablesNotInQuery: [
            (s) => [s.variablesWithValues, s.queryVariableCodeNames, s.searchTerm],
            (variablesWithValues: Variable[], queryVariableCodeNames: string[], searchTerm: string): Variable[] => {
                const queryCodeNames = new Set(queryVariableCodeNames)
                const trimmedSearch = searchTerm.trim().toLowerCase()

                const visibleVariables = trimmedSearch
                    ? variablesWithValues.filter((variable) => {
                          const nameMatch = variable.name.toLowerCase().includes(trimmedSearch)
                          const codeNameMatch = variable.code_name?.toLowerCase().includes(trimmedSearch)
                          const typeMatch = variable.type.toLowerCase().includes(trimmedSearch)

                          return nameMatch || codeNameMatch || typeMatch
                      })
                    : variablesWithValues

                return visibleVariables
                    .filter((variable) => !queryCodeNames.has(variable.code_name))
                    .sort((a, b) => a.name.localeCompare(b.name))
            },
        ],
    }),
    listeners(({ props, values, actions }) => ({
        clickVariable: ({ variable }) => {
            if (
                variable.id === values.internalSelectedVariables.find((v) => v.variableId === variable.id)?.variableId
            ) {
                actions.removeVariable(variable.id)
            } else {
                actions.addVariable({ variableId: variable.id, code_name: variable.code_name })
            }
        },
        addVariable: () => {
            // dashboard items handle source query separately
            if (!props.readOnly) {
                actions.updateSourceQuery()
            }
        },
        removeVariable: () => {
            actions.updateSourceQuery()
        },
        updateVariableValue: () => {
            actions.updateSourceQuery()
        },
        updateSourceQuery: () => {
            if (!props.sourceQuery?.source) {
                return
            }

            const variables = values.internalSelectedVariables

            const query: VisualizationNode = {
                ...props.sourceQuery,
                source: {
                    ...props.sourceQuery?.source,
                    variables: variables.reduce(
                        (acc, cur) => {
                            if (cur.variableId) {
                                acc[cur.variableId] = {
                                    variableId: cur.variableId,
                                    value: cur.value,
                                    code_name: cur.code_name,
                                    isNull: cur.isNull,
                                }
                            }

                            return acc
                        },
                        {} as Record<string, HogQLVariable>
                    ),
                },
            }
            const queryVarsHaveChanged = haveVariablesOrFiltersChanged(query.source, props.sourceQuery?.source)

            if (!queryVarsHaveChanged) {
                return
            }

            props.setQuery?.(query)

            if (props.readOnly) {
                // Refresh the data manaully via dataNodeLogic when in insight view mode
                // actions.loadData(true, undefined, query.source)
                props.onUpdate?.(query)
            }
        },
    })),
    subscriptions(({ actions, values }) => ({
        editorQuery: (query: string | null) => {
            if (query === null) {
                return
            }

            const syncedVariables = syncSelectedVariablesToQuery(
                query,
                values.variables,
                values.internalSelectedVariables
            )

            if (objectsEqual(syncedVariables, values.internalSelectedVariables)) {
                return
            }

            actions.addVariables(syncedVariables)
            actions.updateSourceQuery()
        },
        variables: (variables: Variable[]) => {
            if (values.editorQuery === null || !variables.length) {
                return
            }

            const syncedVariables = syncSelectedVariablesToQuery(
                values.editorQuery,
                variables,
                values.internalSelectedVariables
            )

            if (objectsEqual(syncedVariables, values.internalSelectedVariables)) {
                return
            }

            actions.addVariables(syncedVariables)
            actions.updateSourceQuery()
        },
    })),
])