: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 clsx from 'clsx'
import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
import api from 'lib/api'
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { teamLogic } from 'scenes/teamLogic'
import { RecordingOrder } from '~/queries/schema/schema-general'
import {
FilterLogicalOperator,
PropertyFilterType,
PropertyOperator,
RecordingUniversalFilters,
ReplayTemplateCategory,
ReplayTemplateType,
ReplayTemplateVariableType,
UniversalFilterValue,
UniversalFiltersGroupValue,
} from '~/types'
import type { TeamPublicType, TeamType } from '../../../types'
import { convertUniversalFiltersToRecordingsQuery } from '../filters/recordingsQueryConversions'
import { defaultRecordingDurationFilter } from '../playlist/sessionRecordingsPlaylistLogic'
const MATCH_COUNT_LIMIT = 25
export const TEMPLATE_BASE_FILTERS: Pick<
RecordingUniversalFilters,
'date_from' | 'date_to' | 'duration' | 'filter_test_accounts'
> = {
date_from: '-7d',
date_to: null,
duration: [defaultRecordingDurationFilter],
filter_test_accounts: false,
}
export interface TemplateMatchCount {
count: number
hasMore: boolean
}
const getPageviewFilterValue = (pageview: string): UniversalFiltersGroupValue => {
return {
key: 'visited_page',
value: pageview,
operator: PropertyOperator.IContains,
type: PropertyFilterType.Recording,
}
}
export type ReplayTemplateUsedSource = 'filters_panel'
export interface ReplayTemplateLogicPropsType {
template: ReplayTemplateType
// one card can be in multiple categories,
// key on the category so that multiple instances of the same card are isolated
category: ReplayTemplateCategory
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionReplayTemplatesLogicValues {
currentTeam: TeamPublicType | TeamType | null // teamLogic
canApplyFilters: boolean
editableVariables: ReplayTemplateVariableType[]
filterGroup: Partial<RecordingUniversalFilters>
filtersToApply: Partial<RecordingUniversalFilters>
hasTemplateFilters: boolean
matchCount: TemplateMatchCount | null
matchCountError: boolean
matchCountLoading: boolean
previewFilters: UniversalFilterValue[]
variables: ReplayTemplateVariableType[]
variablesVisible: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionReplayTemplatesLogicActions {
hideVariables: () => {
value: true
}
loadMatchCount: () => {
value: true
}
loadMatchCountFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadMatchCountSuccess: (
matchCount: {
count: number
hasMore: boolean
} | null,
payload?: {
value: true
}
) => {
matchCount: {
count: number
hasMore: boolean
} | null
payload?: {
value: true
}
}
matchCountFailed: () => {
value: true
}
reportTemplateUsed: (source: ReplayTemplateUsedSource) => {
source: 'filters_panel'
}
resetVariable: (variable: ReplayTemplateVariableType) => {
variable: ReplayTemplateVariableType
}
setVariable: (variable: ReplayTemplateVariableType) => {
variable: ReplayTemplateVariableType
}
setVariables: (variables?: ReplayTemplateVariableType[]) => {
variables: ReplayTemplateVariableType[] | undefined
}
showVariables: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionReplayTemplatesLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
filterGroup: (variables: ReplayTemplateVariableType[]) => Partial<RecordingUniversalFilters>
previewFilters: (filterGroup: Partial<RecordingUniversalFilters>) => UniversalFilterValue[]
filtersToApply: (
filterGroup: Partial<RecordingUniversalFilters>,
variables: ReplayTemplateVariableType[],
arg: any
) => Partial<RecordingUniversalFilters>
hasTemplateFilters: (previewFilters: UniversalFilterValue[], variables: ReplayTemplateVariableType[]) => boolean
canApplyFilters: (hasTemplateFilters: boolean) => boolean
editableVariables: (variables: ReplayTemplateVariableType[]) => ReplayTemplateVariableType[]
}
}
export type sessionReplayTemplatesLogicType = MakeLogicType<
sessionReplayTemplatesLogicValues,
sessionReplayTemplatesLogicActions,
ReplayTemplateLogicPropsType,
sessionReplayTemplatesLogicMeta
>
export const sessionReplayTemplatesLogic = kea<sessionReplayTemplatesLogicType>([
path(() => ['scenes', 'session-recordings', 'templates', 'sessionReplayTemplatesLogic']),
props({} as ReplayTemplateLogicPropsType),
key((props) => `${props.category}-${props.template.key}`),
connect(() => ({
values: [teamLogic, ['currentTeam']],
})),
actions({
setVariables: (variables?: ReplayTemplateVariableType[]) => ({ variables }),
setVariable: (variable: ReplayTemplateVariableType) => ({ variable }),
resetVariable: (variable: ReplayTemplateVariableType) => ({ variable }),
reportTemplateUsed: (source: ReplayTemplateUsedSource) => ({ source }),
matchCountFailed: true,
loadMatchCount: true,
showVariables: true,
hideVariables: true,
}),
reducers(({ props, values }) => ({
variables: [
props.template.variables ?? [],
{
persist: true,
storageKey: clsx(
'session-recordings.templates.variables',
values.currentTeam?.id,
props.category,
props.template.key
),
},
{
setVariables: (_, { variables }) => variables ?? [],
setVariable: (state, { variable }) =>
state.map((v) => (v.key === variable.key ? { ...variable, touched: true } : v)),
resetVariable: (state, { variable }) =>
state.map((v) => (v.key === variable.key ? { ...variable, touched: false } : v)),
},
],
variablesVisible: [
false,
{
showVariables: () => true,
hideVariables: () => false,
},
],
matchCountError: [
false,
{
loadMatchCount: () => false,
matchCountFailed: () => true,
},
],
})),
loaders(({ actions, values }) => ({
matchCount: [
null as TemplateMatchCount | null,
{
loadMatchCount: async (_, breakpoint) => {
if (!values.hasTemplateFilters) {
return null
}
await breakpoint(300)
const query = {
...convertUniversalFiltersToRecordingsQuery({
...TEMPLATE_BASE_FILTERS,
filter_group: values.filterGroup.filter_group ?? {
type: FilterLogicalOperator.And,
values: [],
},
}),
limit: MATCH_COUNT_LIMIT,
}
let response
try {
// nosemgrep: prefer-codegen-api-namespaced-replay
response = await api.recordings.list(query)
} catch {
breakpoint()
actions.matchCountFailed()
return null
}
breakpoint()
return { count: response.results.length, hasMore: response.has_next }
},
},
],
})),
selectors({
filterGroup: [
(s) => [s.variables],
(variables: ReplayTemplateVariableType[]) => {
const filters = variables
.map((variable) => {
if (variable.type === 'pageview' && variable.value) {
return getPageviewFilterValue(variable.value)
}
if (
['snapshot_source', 'event', 'person-property'].includes(variable.type) &&
variable.filterGroup
) {
return variable.filterGroup
}
return undefined
})
.filter((filter): filter is UniversalFiltersGroupValue => filter !== undefined)
const filterGroup: Partial<RecordingUniversalFilters> = {
filter_group: {
type: FilterLogicalOperator.And,
values: [
{
type: FilterLogicalOperator.And,
values: filters,
},
],
},
// TODO this should set order on the filter group after https://github.com/PostHog/posthog/pull/25701
}
return filterGroup
},
],
previewFilters: [
(s) => [s.filterGroup],
(filterGroup: Partial<RecordingUniversalFilters>): UniversalFilterValue[] => {
const leaves = (values: UniversalFiltersGroupValue[]): UniversalFilterValue[] =>
values.flatMap((value) => (isUniversalGroupFilterLike(value) ? leaves(value.values) : [value]))
return leaves(filterGroup.filter_group?.values ?? [])
},
],
filtersToApply: [
(s) => [s.filterGroup, s.variables, (_, props) => props.template.order],
(
filterGroup: Partial<RecordingUniversalFilters>,
variables: ReplayTemplateVariableType[],
order: RecordingOrder | undefined
): Partial<RecordingUniversalFilters> => ({
...(variables.length > 0 ? filterGroup : {}),
...(order ? { order } : {}),
...TEMPLATE_BASE_FILTERS,
}),
],
hasTemplateFilters: [
(s) => [s.previewFilters, s.variables],
(previewFilters: UniversalFilterValue[], variables: ReplayTemplateVariableType[]) =>
previewFilters.length > 0 || variables.length === 0,
],
canApplyFilters: [(s) => [s.hasTemplateFilters], (hasTemplateFilters: boolean) => hasTemplateFilters],
editableVariables: [
(s) => [s.variables],
(variables: ReplayTemplateVariableType[]) => variables.filter((v) => !v.noTouch),
],
}),
listeners(({ actions, props, selectors, values }) => ({
showVariables: (_, __, ___, previousState) => {
if (!selectors.variablesVisible(previousState)) {
actions.loadMatchCount()
}
},
setVariable: () => {
if (values.variablesVisible) {
actions.loadMatchCount()
}
},
resetVariable: () => {
if (values.variablesVisible) {
actions.loadMatchCount()
}
},
reportTemplateUsed: ({ source }) => {
posthog.capture('session replay template used', {
template: props.template.key,
category: props.category,
source,
})
},
})),
events(({ actions, props, values }) => ({
afterMount: () => {
if (values.variables.length === 0) {
actions.setVariables(props.template.variables)
}
},
})),
])