: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, kea, key, listeners, path, props, reducers } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { lemonToast } from '@posthog/lemon-ui'
import { ensureAnchored } from 'lib/components/IngestionControls/triggers/urlConfigLogic'
import { uuid } from 'lib/utils/dom'
import {
EventTriggerConfig,
SessionRecordingTriggerGroup,
TriggerPropertyFilter,
UrlTriggerConfig,
} from '~/lib/components/IngestionControls/types'
function isValidRegex(pattern: string): boolean {
try {
new RegExp(pattern)
return true
} catch {
return false
}
}
type UrlPatternResult = { url: string } | { error: 'empty' | 'invalid' | 'duplicate' }
function prepareUrlPattern(raw: string, existing: UrlTriggerConfig[]): UrlPatternResult {
const trimmedUrl = raw.trim()
if (!trimmedUrl) {
return { error: 'empty' }
}
if (!isValidRegex(trimmedUrl)) {
return { error: 'invalid' }
}
const anchoredUrl = ensureAnchored(trimmedUrl)
if (existing.some((u) => u.url === anchoredUrl)) {
return { error: 'duplicate' }
}
return { url: anchoredUrl }
}
const INVALID_REGEX_MESSAGE = 'Invalid regex pattern. Please check your syntax.'
/** Normalize stored events to the object format for the form */
function normalizeEvents(events: (string | EventTriggerConfig)[] | undefined): EventTriggerConfig[] {
return (events || []).map((e) => (typeof e === 'string' ? { name: e } : e))
}
export interface TriggerGroupFormLogicProps {
group?: SessionRecordingTriggerGroup
onSave: (group: SessionRecordingTriggerGroup) => void
onCancel: () => void
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface triggerGroupFormLogicValues {
expandedEvent: string | null
isAddingUrl: boolean
isTriggerGroupSubmitting: boolean
isTriggerGroupValid: boolean
newUrl: string
showTriggerGroupErrors: boolean
testUrl: string
triggerGroup: {
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}
triggerGroupAllErrors: Record<string, any>
triggerGroupChanged: boolean
triggerGroupErrors: DeepPartialMap<
{
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
},
ValidationErrorType
>
triggerGroupHasErrors: boolean
triggerGroupManualErrors: Record<string, any>
triggerGroupTouched: boolean
triggerGroupTouches: Record<string, boolean>
triggerGroupValidationErrors: DeepPartialMap<
{
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
},
ValidationErrorType
>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface triggerGroupFormLogicActions {
addFlag: (
_id: number,
key: string
) => {
key: string
}
addUrl: (url: string) => {
url: string
}
removeEvent: (eventName: string) => {
eventName: string
}
removeFlag: () => {
value: true
}
removeUrl: (url: string) => {
url: string
}
resetTriggerGroup: (values?: {
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}) => {
values?: {
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}
}
setEventProperties: (
eventName: string,
properties: TriggerPropertyFilter[]
) => {
eventName: string
properties: TriggerPropertyFilter[]
}
setExpandedEvent: (eventName: string | null) => {
eventName: string | null
}
setIsAddingUrl: (isAdding: boolean) => {
isAdding: boolean
}
setNewUrl: (url: string) => {
url: string
}
setTestUrl: (url: string) => {
url: string
}
setTriggerGroupManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
setTriggerGroupValue: (
key: FieldName,
value: any
) => {
name: FieldName
value: any
}
setTriggerGroupValues: (
values: DeepPartial<{
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}>
) => {
values: DeepPartial<{
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}>
}
submitTriggerGroup: () => {
value: boolean
}
submitTriggerGroupFailure: (
error: Error,
errors: Record<string, any>
) => {
error: Error
errors: Record<string, any>
}
submitTriggerGroupRequest: (triggerGroup: {
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}) => {
triggerGroup: {
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}
}
submitTriggerGroupSuccess: (triggerGroup: {
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}) => {
triggerGroup: {
events: EventTriggerConfig[]
flag: string | null
matchType: 'all' | 'any'
minDurationMs: number | null
name: string
properties: TriggerPropertyFilter[]
sampleRate: number
urls: UrlTriggerConfig[]
}
}
touchTriggerGroupField: (key: string) => {
key: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface triggerGroupFormLogicMeta {
key: string
}
export type triggerGroupFormLogicType = MakeLogicType<
triggerGroupFormLogicValues,
triggerGroupFormLogicActions,
TriggerGroupFormLogicProps,
triggerGroupFormLogicMeta
>
export const triggerGroupFormLogic = kea<triggerGroupFormLogicType>([
path(['lib', 'components', 'IngestionControls', 'triggers', 'triggerGroups', 'triggerGroupFormLogic']),
props({} as TriggerGroupFormLogicProps),
key((props) => props.group?.id || 'new'),
actions({
setIsAddingUrl: (isAdding: boolean) => ({ isAdding }),
setNewUrl: (url: string) => ({ url }),
setTestUrl: (url: string) => ({ url }),
addUrl: (url: string) => ({ url }),
removeUrl: (url: string) => ({ url }),
removeEvent: (eventName: string) => ({ eventName }),
addFlag: (_id: number, key: string) => ({ key }),
removeFlag: true,
setEventProperties: (eventName: string, properties: TriggerPropertyFilter[]) => ({ eventName, properties }),
setExpandedEvent: (eventName: string | null) => ({ eventName }),
}),
reducers({
isAddingUrl: [
false,
{
setIsAddingUrl: (_, { isAdding }) => isAdding,
addUrl: () => false,
},
],
newUrl: [
'',
{
setNewUrl: (_, { url }) => url,
setIsAddingUrl: (state, { isAdding }) => (isAdding ? state : ''),
addUrl: () => '',
},
],
testUrl: [
'',
{
setTestUrl: (_, { url }) => url,
},
],
expandedEvent: [
null as string | null,
{
setExpandedEvent: (_, { eventName }) => eventName,
},
],
}),
forms(({ props, values }) => ({
triggerGroup: {
defaults: {
name: props.group?.name || '',
sampleRate: Math.round((props.group?.sampleRate || 1) * 100),
minDurationMs: props.group?.minDurationMs ?? null,
matchType: props.group?.conditions.matchType || ('any' as const),
events: normalizeEvents(props.group?.conditions.events),
urls: props.group?.conditions.urls || [],
flag: props.group?.conditions.flag
? typeof props.group.conditions.flag === 'string'
? props.group.conditions.flag
: props.group.conditions.flag.key
: null,
properties: props.group?.conditions.properties || [],
} as {
name: string
sampleRate: number
minDurationMs: number | null
matchType: 'any' | 'all'
events: EventTriggerConfig[]
urls: UrlTriggerConfig[]
flag: string | null
properties: TriggerPropertyFilter[]
},
errors: ({ name }) => ({
name: !name?.trim() ? 'Group name is required' : undefined,
}),
submit: async (formValues) => {
// A pattern still in the input counts as added, so one Save is enough
const pendingUrl = prepareUrlPattern(values.newUrl, formValues.urls)
if ('error' in pendingUrl && pendingUrl.error === 'invalid') {
lemonToast.error(INVALID_REGEX_MESSAGE, { hideButton: true })
return
}
const urls =
'url' in pendingUrl
? [...formValues.urls, { url: pendingUrl.url, matching: 'regex' as const }]
: formValues.urls
const savedGroup: SessionRecordingTriggerGroup = {
id: props.group?.id || uuid(),
name: formValues.name.trim(),
sampleRate: formValues.sampleRate / 100,
minDurationMs: formValues.minDurationMs ?? undefined,
conditions: {
matchType: formValues.matchType,
events: formValues.events.length > 0 ? formValues.events : undefined,
urls: urls.length > 0 ? urls : undefined,
flag: formValues.flag || undefined,
properties: formValues.properties.length > 0 ? formValues.properties : undefined,
},
}
props.onSave(savedGroup)
},
},
})),
listeners(({ actions, values }) => ({
addUrl: ({ url }) => {
const result = prepareUrlPattern(url, values.triggerGroup.urls)
if ('error' in result) {
if (result.error === 'invalid') {
lemonToast.error(INVALID_REGEX_MESSAGE, { hideButton: true })
} else if (result.error === 'duplicate') {
lemonToast.warning('This URL pattern has already been added')
}
return
}
actions.setTriggerGroupValue('urls', [
...values.triggerGroup.urls,
{ url: result.url, matching: 'regex' as const },
])
},
removeUrl: ({ url }) => {
actions.setTriggerGroupValue(
'urls',
values.triggerGroup.urls.filter((u) => u.url !== url)
)
},
removeEvent: ({ eventName }) => {
actions.setTriggerGroupValue(
'events',
values.triggerGroup.events.filter((e) => e.name !== eventName)
)
if (values.expandedEvent === eventName) {
actions.setExpandedEvent(null)
}
},
addFlag: ({ key }) => {
actions.setTriggerGroupValue('flag', key)
},
removeFlag: () => {
actions.setTriggerGroupValue('flag', null)
},
setEventProperties: ({ eventName, properties }) => {
actions.setTriggerGroupValue(
'events',
values.triggerGroup.events.map((e) => (e.name === eventName ? { ...e, properties } : e))
)
},
})),
])