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.

18.9 KB
Raw Blame
import { deepEqual as equal } from 'fast-equals'
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { lazyLoaders } from 'kea-loaders'
import posthog from 'posthog-js'

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { userLogic } from 'scenes/userLogic'

import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'
import { ActorsQuery, EventsQuery, GroupsQuery, NodeKind } from '~/queries/schema/schema-general'
import { isEventsQuery } from '~/queries/utils'
import { AnyPropertyFilter, PropertyOperator } from '~/types'

import { GROUPS_LIST_DEFAULT_QUERY } from 'products/groups/frontend/logics/groupsListLogic'
import { PERSON_EVENTS_CONTEXT_KEY } from 'products/persons/frontend/logics/personsLogic'
import { PEOPLE_LIST_CONTEXT_KEY, isPeopleListDefaultQuery } from 'products/persons/frontend/logics/personsSceneLogic'
import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'

import type { UserType } from '../../../../types'

export type TableViewSupportedQueryType = ActorsQuery | GroupsQuery | EventsQuery

export interface TableViewLogicProps {
    contextKey: string
    query: TableViewSupportedQueryType
    setQuery: (query: TableViewSupportedQueryType) => void
}

interface EventSyntheticMarker {
    key: 'event'
    value: EventsQuery['event']
    operator: PropertyOperator.Exact
    type: undefined
}

interface EventsSyntheticMarker {
    key: 'events'
    value: EventsQuery['events']
    operator: PropertyOperator.In
    type: undefined
}

type TableViewSavedFilter = AnyPropertyFilter | EventSyntheticMarker | EventsSyntheticMarker

function getViewData(
    props: TableViewLogicProps,
    name?: string,
    visibility?: 'private' | 'shared'
): Partial<ColumnConfigurationApi> {
    if (!isEventsQuery(props.query)) {
        return {
            context_key: props.contextKey,
            ...(name && { name }),
            ...(visibility && { visibility }),
            columns: props.query.select,
            filters: props.query.properties,
            order_by: props.query.orderBy ?? [],
        }
    }
    const event: EventSyntheticMarker = {
        key: 'event',
        value: props.query.event,
        operator: PropertyOperator.Exact,
        type: undefined,
    }
    const events: EventsSyntheticMarker = {
        key: 'events',
        value: props.query.events,
        operator: PropertyOperator.In,
        type: undefined,
    }
    return {
        context_key: props.contextKey,
        ...(name && { name }),
        ...(visibility && { visibility }),
        columns: props.query.select,
        filters: [...(props.query.properties || []), event, events],
        order_by: props.query.orderBy ?? [],
    }
}

function isInitialPersonEventsQuery(query: TableViewSupportedQueryType): boolean {
    if (!isEventsQuery(query)) {
        return false
    }
    const defaultColumns = defaultDataTableColumns(NodeKind.EventsQuery)
    return equal(query.select, defaultColumns) && !query.properties?.length && !query.event && !query.events?.length
}

// Applying a remembered view is only safe while the table still shows its default query.
// Anywhere else it would overwrite columns the user picked, or a query that arrived in the URL.
function isUntouchedDefaultQuery(contextKey: string, query: TableViewSupportedQueryType): boolean {
    switch (contextKey) {
        case PEOPLE_LIST_CONTEXT_KEY:
            return isPeopleListDefaultQuery(query)
        case 'group-0-list':
        case 'group-1-list':
        case 'group-2-list':
        case 'group-3-list':
        case 'group-4-list': {
            const groupTypeIndex = parseInt(contextKey.split('-')[1])
            return equal(query, GROUPS_LIST_DEFAULT_QUERY(groupTypeIndex).source)
        }
        case PERSON_EVENTS_CONTEXT_KEY:
            return isInitialPersonEventsQuery(query)
        default:
            return false
    }
}

function getQueryFromView(
    query: TableViewSupportedQueryType,
    view: ColumnConfigurationApi
): TableViewSupportedQueryType {
    const orderByOverride = view.order_by != null ? { orderBy: view.order_by } : {}

    if (!isEventsQuery(query)) {
        return {
            ...query,
            select: view.columns || [],
            properties: view.filters || [],
            ...orderByOverride,
        } as TableViewSupportedQueryType
    }

    const rawFilters = (view.filters || []) as TableViewSavedFilter[]
    const isEventMarker = (f: TableViewSavedFilter): f is EventSyntheticMarker =>
        f.key === 'event' && f.type === undefined
    const isEventsMarker = (f: TableViewSavedFilter): f is EventsSyntheticMarker =>
        f.key === 'events' && f.type === undefined
    const properties = rawFilters.filter((f): f is AnyPropertyFilter => !isEventMarker(f) && !isEventsMarker(f))
    const event = rawFilters.find(isEventMarker)?.value
    const events = rawFilters.find(isEventsMarker)?.value
    return {
        ...query,
        select: view.columns || [],
        properties,
        event,
        events,
        ...orderByOverride,
    } as EventsQuery
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tableViewLogicValues {
    user: UserType | null // userLogic
    canEditCurrentView: boolean
    currentView: ColumnConfigurationApi | null
    hasUnsavedChanges: boolean
    isCreating: boolean
    isNewViewFormSubmitting: boolean
    isNewViewFormValid: boolean
    newViewForm: {
        name: string
        visibility: 'private' | 'shared'
    }
    newViewFormAllErrors: Record<string, any>
    newViewFormChanged: boolean
    newViewFormErrors: DeepPartialMap<
        {
            name: string
            visibility: 'private' | 'shared'
        },
        ValidationErrorType
    >
    newViewFormHasErrors: boolean
    newViewFormManualErrors: Record<string, any>
    newViewFormTouched: boolean
    newViewFormTouches: Record<string, boolean>
    newViewFormValidationErrors: DeepPartialMap<
        {
            name: string
            visibility: 'private' | 'shared'
        },
        ValidationErrorType
    >
    showDeleteConfirm: string | null
    showNewViewFormErrors: boolean
    views: ColumnConfigurationApi[]
    viewsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tableViewLogicActions {
    applyView: (view: ColumnConfigurationApi) => {
        view: ColumnConfigurationApi
    }
    deleteView: (id: string) => {
        id: string
    }
    deleteViewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteViewSuccess: (
        views: ColumnConfigurationApi[],
        payload?: {
            id: string
        }
    ) => {
        views: ColumnConfigurationApi[]
        payload?: {
            id: string
        }
    }
    loadViews: () => {
        value: true
    }
    loadViewsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadViewsSuccess: (
        views: ColumnConfigurationApi[],
        payload?: {
            value: true
        }
    ) => {
        views: ColumnConfigurationApi[]
        payload?: {
            value: true
        }
    }
    resetNewViewForm: (values?: { name: string; visibility: 'private' | 'shared' }) => {
        values?: {
            name: string
            visibility: 'private' | 'shared'
        }
    }
    saveCurrentAsView: (
        name: string,
        visibility: 'private' | 'shared'
    ) => {
        name: string
        visibility: 'private' | 'shared'
    }
    saveCurrentAsViewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveCurrentAsViewSuccess: (
        views: ColumnConfigurationApi[],
        payload?: {
            name: string
            visibility: 'private' | 'shared'
        }
    ) => {
        views: ColumnConfigurationApi[]
        payload?: {
            name: string
            visibility: 'private' | 'shared'
        }
    }
    setCurrentView: (view: ColumnConfigurationApi | null) => {
        view: ColumnConfigurationApi | null
    }
    setIsCreating: (isCreating: boolean) => {
        isCreating: boolean
    }
    setNewViewFormManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setNewViewFormValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setNewViewFormValues: (
        values: DeepPartial<{
            name: string
            visibility: 'private' | 'shared'
        }>
    ) => {
        values: DeepPartial<{
            name: string
            visibility: 'private' | 'shared'
        }>
    }
    setShowDeleteConfirm: (viewId: string | null) => {
        viewId: string | null
    }
    submitNewViewForm: () => {
        value: boolean
    }
    submitNewViewFormFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitNewViewFormRequest: (newViewForm: { name: string; visibility: 'private' | 'shared' }) => {
        newViewForm: {
            name: string
            visibility: 'private' | 'shared'
        }
    }
    submitNewViewFormSuccess: (newViewForm: { name: string; visibility: 'private' | 'shared' }) => {
        newViewForm: {
            name: string
            visibility: 'private' | 'shared'
        }
    }
    touchNewViewFormField: (key: string) => {
        key: string
    }
    updateView: (
        id: string,
        updates: Partial<ColumnConfigurationApi>
    ) => {
        id: string
        updates: Partial<ColumnConfigurationApi>
    }
    updateViewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateViewSuccess: (
        views: ColumnConfigurationApi[],
        payload?: {
            id: string
            updates: Partial<ColumnConfigurationApi>
        }
    ) => {
        views: ColumnConfigurationApi[]
        payload?: {
            id: string
            updates: Partial<ColumnConfigurationApi>
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tableViewLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        hasUnsavedChanges: (currentView: ColumnConfigurationApi | null, arg: any) => boolean
        canEditCurrentView: (currentView: ColumnConfigurationApi | null, user: UserType | null) => boolean
    }
}

export type tableViewLogicType = MakeLogicType<
    tableViewLogicValues,
    tableViewLogicActions,
    TableViewLogicProps,
    tableViewLogicMeta
>

export const tableViewLogic = kea<tableViewLogicType>([
    props({} as TableViewLogicProps),
    // Include the team id so a team switch yields a fresh logic instance
    // rather than reusing one whose storageKey is frozen to the old team.
    key((props) => `${getCurrentTeamId()}.${props.contextKey}`),
    path(['queries', 'nodes', 'DataTable', 'TableView', 'tableViewLogic']),
    connect({
        values: [userLogic, ['user']],
    }),

    actions({
        loadViews: true,
        saveCurrentAsView: (name: string, visibility: 'private' | 'shared') => ({ name, visibility }),
        updateView: (id: string, updates: Partial<ColumnConfigurationApi>) => ({ id, updates }),
        deleteView: (id: string) => ({ id }),
        applyView: (view: ColumnConfigurationApi) => ({ view }),
        setCurrentView: (view: ColumnConfigurationApi | null) => ({ view }),
        setShowDeleteConfirm: (viewId: string | null) => ({ viewId }),
        setIsCreating: (isCreating: boolean) => ({ isCreating }),
    }),

    lazyLoaders(({ props, values }) => ({
        views: [
            [] as ColumnConfigurationApi[],
            {
                loadViews: async () => {
                    const response = await api.columnConfigurations.list({
                        context_key: props.contextKey,
                    })
                    return response.results
                },

                saveCurrentAsView: async ({ name, visibility }) => {
                    const response = await api.columnConfigurations.create({
                        data: getViewData(props, name, visibility),
                    })
                    return [...values.views, response]
                },

                updateView: async ({ id, updates }) => {
                    // If updating with current query state (no explicit updates provided)
                    if (!updates.name && !updates.visibility) {
                        updates = getViewData(props)
                    }

                    const response = await api.columnConfigurations.update({
                        id,
                        data: updates,
                    })

                    return values.views.map((v) => (v.id === id ? response : v))
                },

                deleteView: async ({ id }) => {
                    await api.columnConfigurations.delete({ id })
                    return values.views.filter((v) => v.id !== id)
                },
            },
        ],
    })),

    reducers(({ props }) => ({
        currentView: [
            null as ColumnConfigurationApi | null,
            {
                persist: true,
                // Scope by team so views don't leak across projects (e.g. after impersonation).
                storageKey: `queries.nodes.DataTable.TableView.tableViewLogic.${getCurrentTeamId()}.${props.contextKey}.currentView`,
            },
            {
                setCurrentView: (_, { view }) => view,
                applyView: (_, { view }) => view,
                // Keep only a view this user picked, and only while the list still has it. Falling
                // back to the first view would select the shared view a teammate created most
                // recently, because the API lists shared views newest first.
                loadViewsSuccess: (state, { views }) =>
                    state && views.some((view) => view.id === state.id) ? state : null,
                deleteViewSuccess: (state, { views }) => {
                    if (state && !views.find((v) => v.id === state.id)) {
                        return null
                    }
                    return state
                },
            },
        ],
        showDeleteConfirm: [
            null as string | null,
            {
                setShowDeleteConfirm: (_, { viewId }) => viewId,
            },
        ],
        isCreating: [
            false,
            {
                setIsCreating: (_, { isCreating }) => isCreating,
                saveCurrentAsViewSuccess: () => false,
            },
        ],
    })),

    selectors(() => ({
        hasUnsavedChanges: [
            (s) => [s.currentView, (_, props) => props.query],
            (currentView: ColumnConfigurationApi | null, query): boolean => {
                if (!currentView) {
                    return false
                }
                const queryFromView = getQueryFromView(query, currentView)
                return !equal(queryFromView, query)
            },
        ],
        canEditCurrentView: [
            (s) => [s.currentView, s.user],
            (currentView: ColumnConfigurationApi | null, user: null | import('~/types').UserType): boolean => {
                if (!currentView || !user) {
                    return false
                }
                return currentView.created_by === user.id
            },
        ],
    })),

    forms(({ props, actions }) => ({
        newViewForm: {
            defaults: {
                name: '',
                visibility: 'private' as 'private' | 'shared',
            },
            errors: ({ name }) => ({
                name: !name?.trim() ? 'Name is required' : undefined,
            }),
            submit: async ({ name, visibility }) => {
                const response = await api.columnConfigurations.create({
                    data: getViewData(props, name, visibility),
                })

                actions.loadViews()
                actions.applyView(response)
                actions.resetNewViewForm()
                actions.setIsCreating(false)
            },
        },
    })),

    listeners(({ props, actions, values, cache }) => ({
        applyView: ({ view }) => {
            props.setQuery(getQueryFromView(props.query, view))
        },

        saveCurrentAsViewSuccess: () => {
            actions.setIsCreating(false)
        },

        saveCurrentAsViewFailure: (error) => {
            posthog.captureException(error)
            lemonToast.error('Error saving view')
        },

        updateViewSuccess: ({ payload }) => {
            const updatedView = values.views.find((view) => view.id === payload?.id)
            if (updatedView) {
                actions.applyView(updatedView)
            }
            lemonToast.success(`View "${updatedView?.name || ''}" updated`)
        },

        updateViewFailure: (error) => {
            posthog.captureException(error)
            lemonToast.error('Error updating view')
        },

        deleteViewSuccess: () => {
            lemonToast.success('View deleted')
        },

        deleteViewFailure: (error) => {
            posthog.captureException(error)
            lemonToast.error('Error deleting view')
        },

        loadViewsSuccess: () => {
            // Restoring on mount would apply the columns of a view its creator has since deleted,
            // because the pick lives in this browser's storage, and clearing the pick afterwards
            // does not take those columns back off the table. The reducer runs before this, so
            // currentView is already null when the list dropped the view. Restore on the first
            // list only, so the refresh after saving a view does not apply the pick again.
            if (cache.restoredStoredView) {
                return
            }
            cache.restoredStoredView = true

            if (values.currentView && isUntouchedDefaultQuery(props.contextKey, props.query)) {
                actions.applyView(values.currentView)
            }
        },

        loadViewsFailure: (error) => {
            posthog.captureException(error)
            lemonToast.error('Error loading views')
        },

        submitNewViewFormSuccess: ({ newViewForm }) => {
            lemonToast.success(`View "${newViewForm.name}" saved`)
        },

        submitNewViewFormFailure: ({ error }) => {
            // Kea-forms emits this when client validation fails; fields already show errors.
            if (error instanceof Error && error.message === 'Validation Failed') {
                return
            }
            posthog.captureException(error)
            lemonToast.error('Error creating view')
        },
    })),
])