: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import api from 'lib/api'
import { EVENT_PROPERTY_DEFINITIONS_PER_PAGE } from 'lib/constants'
import { LemonSelectOption } from 'lib/lemon-ui/LemonSelect'
import { objectsEqual } from 'lib/utils/objects'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import {
PropertyDefinitionsPaginatedResponse,
normalizePropertyDefinitionEndpointUrl,
} from 'scenes/data-management/events/eventDefinitionsTableLogic'
import { urls } from 'scenes/urls'
import { PropertyDefinition } from '~/types'
import { groupsModel } from '../../../models/groupsModel'
import type { Noun } from '../../../models/groupsModel'
import type { GroupType, GroupTypeIndex } from '../../../types'
export interface Filters {
property: string
type: string
group_type_index: number | null
verified?: boolean
}
function cleanFilters(filter: Partial<Filters>): Filters {
return {
property: '',
type: 'event',
group_type_index: null,
verified: undefined,
...filter,
}
}
function removeDefaults(filter: Filters): Partial<Filters> {
return {
property: filter.property !== '' ? filter.property : undefined,
type: filter.type !== 'event' ? filter.type : undefined,
group_type_index: filter.group_type_index !== null ? filter.group_type_index : undefined,
verified: filter.verified,
}
}
export interface PropertyDefinitionsTableLogicProps {
key: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface propertyDefinitionsTableLogicValues {
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel
filters: Filters
hoveredDefinition: string | null
propertyDefinitions: PropertyDefinitionsPaginatedResponse
propertyDefinitionsLoading: boolean
propertyTypeOptions: LemonSelectOption<string>[]
showVerifiedFilter: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface propertyDefinitionsTableLogicActions {
loadPropertyDefinitions: (url?: string | null) => {
url: string | null
}
loadPropertyDefinitionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadPropertyDefinitionsSuccess: (
propertyDefinitions: PropertyDefinitionsPaginatedResponse,
payload?: {
url: string | null
}
) => {
propertyDefinitions: PropertyDefinitionsPaginatedResponse
payload?: {
url: string | null
}
}
setFilters: (
filters: Partial<Filters>,
debounce?: boolean
) => {
debounce: boolean
filters: Partial<Filters>
}
setHoveredDefinition: (definitionKey: string | null) => {
definitionKey: string | null
}
setLocalPropertyDefinition: (definition: PropertyDefinition) => {
definition: PropertyDefinition
}
setLocalPropertyDefinitionFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
setLocalPropertyDefinitionSuccess: (
propertyDefinitions: PropertyDefinitionsPaginatedResponse,
payload?: {
definition: PropertyDefinition
}
) => {
propertyDefinitions: PropertyDefinitionsPaginatedResponse
payload?: {
definition: PropertyDefinition
}
}
setOpenedDefinition: (id: string | null) => {
id: string | null
}
setPropertyType: (propertyType: string) => {
propertyType: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface propertyDefinitionsTableLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
propertyTypeOptions: (
groupTypes: Map<GroupTypeIndex, GroupType>,
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
) => LemonSelectOption<string>[]
showVerifiedFilter: (propertyDefinitions: PropertyDefinitionsPaginatedResponse) => boolean
}
}
export type propertyDefinitionsTableLogicType = MakeLogicType<
propertyDefinitionsTableLogicValues,
propertyDefinitionsTableLogicActions,
PropertyDefinitionsTableLogicProps,
propertyDefinitionsTableLogicMeta
>
export const propertyDefinitionsTableLogic = kea<propertyDefinitionsTableLogicType>([
path(['scenes', 'data-management', 'properties', 'propertyDefinitionsTableLogic']),
props({} as PropertyDefinitionsTableLogicProps),
key((props) => props.key || 'scene'),
connect(() => ({
values: [groupsModel, ['groupTypes', 'aggregationLabel']],
})),
actions({
loadPropertyDefinitions: (url: string | null = '') => ({
url,
}),
setFilters: (filters: Partial<Filters>, debounce: boolean = true) => ({ filters, debounce }),
setHoveredDefinition: (definitionKey: string | null) => ({ definitionKey }),
setOpenedDefinition: (id: string | null) => ({ id }),
setLocalPropertyDefinition: (definition: PropertyDefinition) => ({ definition }),
setPropertyType: (propertyType: string) => ({ propertyType }),
}),
reducers({
filters: [
{
property: '',
type: 'event',
} as Filters,
{
setFilters: (state, { filters }) => ({
...state,
...filters,
}),
},
],
hoveredDefinition: [
null as string | null,
{
setHoveredDefinition: (_, { definitionKey }) => definitionKey,
},
],
}),
selectors({
propertyTypeOptions: [
(s) => [s.groupTypes, s.aggregationLabel],
(
groupTypes: Map<import('~/types').GroupTypeIndex, import('~/types').GroupType>,
aggregationLabel: (
groupTypeIndex: number | null | undefined,
deferToUserWording?: boolean
) => import('../../../models/groupsModel').Noun
) => {
const groupChoices: Array<LemonSelectOption<string>> = Array.from(groupTypes.values()).map((type) => ({
label: `${capitalizeFirstLetter(aggregationLabel(type.group_type_index).singular)} properties`,
value: `group::${type.group_type_index}`,
}))
return [
{ label: 'Event properties', value: 'event::' } as LemonSelectOption<string>,
{ label: 'Person properties', value: 'person::' } as LemonSelectOption<string>,
].concat(groupChoices)
},
],
}),
loaders(({ values, cache }) => ({
propertyDefinitions: [
{
count: 0,
next: undefined,
current: undefined,
previous: undefined,
results: [],
} as PropertyDefinitionsPaginatedResponse,
{
loadPropertyDefinitions: async ({ url }, breakpoint) => {
if (url && url in (cache.apiCache ?? {})) {
return cache.apiCache[url]
}
if (!url) {
url = api.propertyDefinitions.determineListEndpoint({})
}
cache.propertiesStartTime = performance.now()
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
const response = await api.get(url)
breakpoint()
const currentUrl = `${normalizePropertyDefinitionEndpointUrl(url)}`
cache.apiCache = {
...cache.apiCache,
[currentUrl]: {
...response,
previous: normalizePropertyDefinitionEndpointUrl(response.previous),
next: normalizePropertyDefinitionEndpointUrl(response.next),
current: currentUrl,
page:
Math.floor(
(combineUrl(url).searchParams.offset ?? 0) / EVENT_PROPERTY_DEFINITIONS_PER_PAGE
) + 1,
},
}
return cache.apiCache[url]
},
setLocalPropertyDefinition: ({ definition }) => {
if (!values.propertyDefinitions.current) {
return values.propertyDefinitions
}
// Update cache as well
cache.apiCache = {
...cache.apiCache,
[values.propertyDefinitions.current]: {
...values.propertyDefinitions,
results: values.propertyDefinitions.results.map((d) =>
d.id === definition.id ? definition : d
),
},
}
return cache.apiCache[values.propertyDefinitions.current]
},
},
],
})),
selectors(() => ({
showVerifiedFilter: [
(s) => [s.propertyDefinitions],
(propertyDefinitions: PropertyDefinitionsPaginatedResponse): boolean =>
propertyDefinitions.results.length > 0 && 'verified' in propertyDefinitions.results[0],
],
})),
listeners(({ actions, values, cache }) => ({
setFilters: async ({ debounce }, breakpoint) => {
if (debounce) {
cache.filtersLoadPending = true
await breakpoint(500)
}
cache.filtersLoadPending = false
const params: Record<string, any> = {
offset: 0,
search: values.filters.property,
type: values.filters.type,
group_type_index: values.filters.group_type_index,
verified: values.filters.verified,
}
actions.loadPropertyDefinitions(
normalizePropertyDefinitionEndpointUrl(values.propertyDefinitions.current, params, true)
)
},
loadPropertyDefinitionsSuccess: () => {
if (cache.propertiesStartTime !== undefined) {
posthog.capture('event property definitions page load succeeded', {
load_time: performance.now() - cache.propertiesStartTime,
num_results: values.propertyDefinitions.results.length,
})
cache.propertiesStartTime = undefined
}
},
loadPropertyDefinitionsFailure: ({ error }) => {
if (cache.propertiesStartTime !== undefined) {
posthog.capture('event property definitions page load failed', {
load_time: performance.now() - cache.propertiesStartTime,
error: error ?? 'There was an unknown error fetching property definitions.',
})
cache.propertiesStartTime = undefined
}
},
setPropertyType: ({ propertyType }) => {
const [type, index] = propertyType.split('::')
actions.setFilters({
type: type,
group_type_index: index ? +index : null,
})
},
})),
urlToAction(({ actions, values, cache }) => ({
[urls.propertyDefinitions()]: (_, searchParams) => {
if (values.propertyDefinitionsLoading) {
return
}
// Parse verified as boolean if present
const parsedParams = {
...searchParams,
verified:
searchParams.verified !== undefined
? searchParams.verified === 'true' || searchParams.verified === true
: undefined,
}
if (!objectsEqual(cleanFilters(values.filters), cleanFilters(parsedParams))) {
actions.setFilters(parsedParams as Filters, false)
} else if (
// A debounced filter change already writes this URL, so loading here would skip the debounce
!cache.filtersLoadPending &&
!values.propertyDefinitions.results.length
) {
actions.loadPropertyDefinitions()
}
},
})),
actionToUrl(({ values }) => ({
setFilters: () => {
const nextValues = cleanFilters(values.filters)
const urlValues = cleanFilters(router.values.searchParams)
if (!objectsEqual(nextValues, urlValues)) {
return [router.values.location.pathname, removeDefaults(nextValues)]
}
},
})),
])