: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
feat(replay): rework filter templates (#107641)
Hayne Ryu048c5e086adb
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 982525c71e3a..4c53efeeff1f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7476,6 +7476,10 @@ snapshots:hash: v1.k794b7964.c27886267fbfa39c64398e447e3cf63d5929fc3c9ede6fc8bf9c30bfaeea87a7.YxiOImD793nydIZ3ort6IyBzGmOcsZQb9RmqCuyx0tkreplay-tabs-home-filters-banner--scanner-cross-sell--light:hash: v1.k794b7964.6cf63eeaf5abe507d73ec12a3ec9f404ce02e3c07e0aab059a3a1ea97ccfeb8d.O72XHqs276ly-AWZdwJvr_leOyBMigsKLK1SWFQ3XBo+ replay-tabs-home-filters-banner--templates-tab--dark:+ hash: v1.k794b7964.d438ddf6f2d9f05b13d8645a296bf3d7f9875d485708c4a921eb9c49f2991f90.sf5NCCDbhBU-m1nTsrn2EWTeYdDkfXwx2h3f8GFRGCo+ replay-tabs-home-filters-banner--templates-tab--light:+ hash: v1.k794b7964.9e447d52b926cb22093f8c73945c9b4aebb3f79781e350a3f5245559c83e54d2.PJue3UTGwQpd6J6F_vyMA__xCKXHvLqyJew3QYep8SIreplay-tabs-home-success--filters-expanded--dark:hash: v1.k794b7964.e85cac90eb14f279e3367d8d2ab0db3011d7bb6c5d85fee2fb5cd2d0095ea956.9KZY5n5cdZIaHcp8HzrLMg-rgB2x7i_uH93bqNN_MzUreplay-tabs-home-success--filters-expanded--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex dbd47bc8cf6a..71de01d722ec 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -487,6 +487,7 @@ export const FEATURE_FLAGS = {REPLAY_NEGATIVE_EVENT_FILTERS: 'replay-negative-event-filters', // owner: @arnohillen #team-replayREPLAY_PLAYLIST_SURFACING_SCORE: 'replay-playlist-surfacing-score', // owner: #team-replayREPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT: 'replay-recommended-recordings-filter-experiment', // owner: @arnohillen #team-replay multivariate=control,test+ REPLAY_TEMPLATES_IN_FILTERS_PANEL_EXPERIMENT: 'replay-templates-in-filters-panel-experiment', // owner: #team-replay multivariate=control,test (gate on === 'test')REPLAY_TRIGGERS_V2: 'replay-triggers-v2', // owner: #team-replayREPLAY_UI_REDESIGN_2026: 'replay-ui-redesign-2026', // owner: #team-replay, New UI layout for replayREPLAY_VISION_ANALYSIS_NUDGE: 'replay-vision-analysis-nudge', // owner: #team-replay, in-player nudge offering an AI-drafted scanner after analyzing several recordingsdiff --git a/frontend/src/scenes/session-recordings/SessionRecordings.tsx b/frontend/src/scenes/session-recordings/SessionRecordings.tsxindex 7b9d537eb3ef..3633f84db2ec 100644--- a/frontend/src/scenes/session-recordings/SessionRecordings.tsx+++ b/frontend/src/scenes/session-recordings/SessionRecordings.tsx@@ -36,6 +36,7 @@ import { sessionReplayEmptyState } from 'products/replay/frontend/emptyState/sesimport { SessionRecordingCollections } from './collections/SessionRecordingCollections'import { SessionRecordingsPlaylistRedesign } from './playlist-redesign/SessionRecordingsPlaylistRedesign'+import { playlistFiltersLogic } from './playlist/playlistFiltersLogic'import { createPlaylist } from './playlist/playlistUtils'import { SessionRecordingsPlaylist } from './playlist/SessionRecordingsPlaylist'import {@@ -243,13 +244,17 @@ const ReplayPageTabs: ReplayTab[] = [export function SessionRecordingsPageTabs(): JSX.Element {const { tab, shouldShowNewBadge } = useValues(sessionReplaySceneLogic)+ const { templatesInFiltersPanel } = useValues(playlistFiltersLogic)+ const visibleTabs = templatesInFiltersPanel+ ? ReplayPageTabs.filter((replayTab) => replayTab.key !== ReplayTabs.Templates)+ : ReplayPageTabsreturn (<LemonTabsactiveKey={tab}onChange={(t) => router.actions.push(urls.replay(t as ReplayTabs))}sceneInsetclassName="-mt-4"- tabs={ReplayPageTabs.map((replayTab): LemonTab<string> => {+ tabs={visibleTabs.map((replayTab): LemonTab<string> => {return {label: (<>diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsxindex a24c3acf4d64..70d2d33c4d28 100644--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx@@ -103,3 +103,10 @@ const withPageFilter = (values: Record<string, any>[]): Record<string, any> => (export const PageFilterNudge: Story = {parameters: withPageFilter([{ type: 'event', key: '$current_url', operator: 'icontains', value: '/pricing' }]),}++export const TemplatesTab: Story = {+ parameters: {+ featureFlags: { [FEATURE_FLAGS.REPLAY_TEMPLATES_IN_FILTERS_PANEL_EXPERIMENT]: 'test' },+ pageUrl: combineUrl(urls.replay(), { showFilters: true, filtersTab: 'templates' }).url,+ },+}diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsxindex 1b2af2491de2..5e991bda0670 100644--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx@@ -81,6 +81,7 @@ import {sessionRecordingsPlaylistLogic,} from '../playlist/sessionRecordingsPlaylistLogic'import { sessionRecordingEventUsageLogic } from '../sessionRecordingEventUsageLogic'+import { FilterTemplates } from '../templates/FilterTemplates'import { CurrentFilterIndicator } from './CurrentFilterIndicator'import { DurationFilter } from './DurationFilter'import { ProductAnalyticsOverLimitBanner } from './ProductAnalyticsOverLimitBanner'@@ -328,7 +329,7 @@ export const RecordingsUniversalFiltersEmbed = ({ ...props }: ReplayUniversalFiluseMountedLogic(actionsModel)useMountedLogic(groupsModel)- const { activeFilterTab } = useValues(playlistFiltersLogic)+ const { activeFilterTab, templatesInFiltersPanel } = useValues(playlistFiltersLogic)const { setIsFiltersExpanded, setActiveFilterTab } = useActions(playlistFiltersLogic)const { savedFilters } = useValues(sessionRecordingSavedFiltersLogic)@@ -355,12 +356,32 @@ export const RecordingsUniversalFiltersEmbed = ({ ...props }: ReplayUniversalFilcontent: <SavedFilters setFilters={props.setFilters} />,'data-attr': 'session-recordings-saved-tab',},+ ...(templatesInFiltersPanel+ ? [+ {+ key: 'templates',+ label: <div className="px-2">Templates</div>,+ content: (+ <div className="p-2">+ <FilterTemplates+ source="filters_panel"+ onApply={(filters) => {+ props.setFilters(filters)+ setActiveFilterTab('filters')+ }}+ />+ </div>+ ),+ 'data-attr': 'session-recordings-templates-tab',+ },+ ]+ : []),]return (<div className="relative"><LemonTabs- activeKey={activeFilterTab}+ activeKey={tabs.some((tab) => tab.key === activeFilterTab) ? activeFilterTab : 'filters'}onChange={(activeKey) => setActiveFilterTab(activeKey)}size="small"tabs={tabs}diff --git a/frontend/src/scenes/session-recordings/playlist/playlistFiltersLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/playlistFiltersLogic.test.tsnew file mode 100644index 000000000000..99841f4bc678--- /dev/null+++ b/frontend/src/scenes/session-recordings/playlist/playlistFiltersLogic.test.ts@@ -0,0 +1,29 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { playlistFiltersLogic } from 'scenes/session-recordings/playlist/playlistFiltersLogic'+import { urls } from 'scenes/urls'++import { initKeaTests } from '~/test/init'+import { ReplayTabs } from '~/types'++describe('playlistFiltersLogic', () => {+ let logic: ReturnType<typeof playlistFiltersLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = playlistFiltersLogic()+ logic.mount()+ })++ it.each([+ ['saved', 'saved'],+ ['templates', 'templates'],+ ['unknown', 'filters'],+ ])('filtersTab=%s in the URL selects the %s tab', async (filtersTab, expected) => {+ router.actions.push(urls.replay(ReplayTabs.Home), { filtersTab })++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.activeFilterTab).toBe(expected)+ })+})diff --git a/frontend/src/scenes/session-recordings/playlist/playlistFiltersLogic.ts b/frontend/src/scenes/session-recordings/playlist/playlistFiltersLogic.tsindex 3f1078498733..c1b07a2e5e5c 100644--- a/frontend/src/scenes/session-recordings/playlist/playlistFiltersLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/playlistFiltersLogic.ts@@ -1,16 +1,20 @@-import { MakeLogicType, actions, kea, path, reducers } from 'kea'+import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'import { actionToUrl, router, urlToAction } from 'kea-router'+import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'import { ReplayTabs } from '~/types'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface playlistFiltersLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicactiveCategory: stringactiveFilterTab: stringisExpanded: booleanisFiltersExpanded: boolean+ templatesInFiltersPanel: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -29,10 +33,25 @@ export interface playlistFiltersLogicActions {}}-export type playlistFiltersLogicType = MakeLogicType<playlistFiltersLogicValues, playlistFiltersLogicActions>+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface playlistFiltersLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ templatesInFiltersPanel: (featureFlags: FeatureFlagsSet) => boolean+ }+}++export type playlistFiltersLogicType = MakeLogicType<+ playlistFiltersLogicValues,+ playlistFiltersLogicActions,+ Record<string, any>,+ playlistFiltersLogicMeta+>export const playlistFiltersLogic = kea<playlistFiltersLogicType>([path(['scenes', 'session-recordings', 'playlist', 'playlistFiltersLogic']),+ connect(() => ({+ values: [featureFlagLogic, ['featureFlags']],+ })),actions({setIsExpanded: (isExpanded: boolean) => ({ isExpanded }), // WIll be removed together with Mix (R.I.P. Mix)setIsFiltersExpanded: (isFiltersExpanded: boolean) => ({ isFiltersExpanded }),@@ -65,9 +84,16 @@ export const playlistFiltersLogic = kea<playlistFiltersLogicType>([},],}),+ selectors({+ templatesInFiltersPanel: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet) =>+ featureFlags[FEATURE_FLAGS.REPLAY_TEMPLATES_IN_FILTERS_PANEL_EXPERIMENT] === 'test',+ ],+ }),urlToAction(({ actions }) => ({[urls.replay(ReplayTabs.Home)]: (_, searchParams) => {- if (searchParams.filtersTab && ['filters', 'saved'].includes(searchParams.filtersTab)) {+ if (searchParams.filtersTab && ['filters', 'saved', 'templates'].includes(searchParams.filtersTab)) {actions.setActiveFilterTab(searchParams.filtersTab)}if (searchParams.showFilters) {diff --git a/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts b/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.tsindex 18fa6217768c..f92e894ba223 100644--- a/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts+++ b/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts@@ -1,6 +1,7 @@-import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'-import { router, urlToAction } from 'kea-router'+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { combineUrl, router, urlToAction } from 'kea-router'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { capitalizeFirstLetter } from 'lib/utils/strings'import { sceneConfigurations } from 'scenes/scenes'@@ -10,6 +11,8 @@ import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { ActivityScope, Breadcrumb, ReplayTabs } from '~/types'+import { playlistFiltersLogic } from './playlist/playlistFiltersLogic'+export const humanFriendlyTabName = (tab: ReplayTabs): string => {switch (tab) {case ReplayTabs.Home:@@ -29,6 +32,7 @@ export const humanFriendlyTabName = (tab: ReplayTabs): string => {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface sessionReplaySceneLogicValues {+ templatesInFiltersPanel: boolean // playlistFiltersLogicbreadcrumbs: Breadcrumb[]shouldShowNewBadge: booleansidePanelContext: SidePanelSceneContext@@ -60,8 +64,18 @@ export type sessionReplaySceneLogicType = MakeLogicType<sessionReplaySceneLogicMeta>+const templatesInPanelUrl = (): string =>+ combineUrl(+ urls.replay(ReplayTabs.Home),+ { ...router.values.searchParams, showFilters: true, filtersTab: 'templates' },+ router.values.hashParams+ ).url+export const sessionReplaySceneLogic = kea<sessionReplaySceneLogicType>([path(() => ['scenes', 'session-recordings', 'sessionReplaySceneLogic']),+ connect(() => ({+ values: [playlistFiltersLogic, ['templatesInFiltersPanel']],+ })),actions({setTab: (tab: ReplayTabs = ReplayTabs.Home) => ({ tab }),hideNewBadge: true,@@ -82,12 +96,17 @@ export const sessionReplaySceneLogic = kea<sessionReplaySceneLogicType>([],})),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({setTab: ({ tab }) => {if (tab === ReplayTabs.Templates) {actions.hideNewBadge()}},+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ if (values.tab === ReplayTabs.Templates && values.templatesInFiltersPanel) {+ router.actions.replace(templatesInPanelUrl())+ }+ },})),trackedActionToUrl(({ values }) => {@@ -140,6 +159,10 @@ export const sessionReplaySceneLogic = kea<sessionReplaySceneLogicType>([// so, we're extra careful that the value being set is a valid tabconst candidateTab = tab as ReplayTabsconst validTab = Object.values(ReplayTabs).includes(candidateTab) ? candidateTab : ReplayTabs.Home+ if (validTab === ReplayTabs.Templates && values.templatesInFiltersPanel) {+ router.actions.replace(templatesInPanelUrl())+ return+ }if (validTab !== values.tab) {actions.setTab(validTab)}diff --git a/frontend/src/scenes/session-recordings/templates/FilterTemplateCard.tsx b/frontend/src/scenes/session-recordings/templates/FilterTemplateCard.tsxnew file mode 100644index 000000000000..b19fab92b170--- /dev/null+++ b/frontend/src/scenes/session-recordings/templates/FilterTemplateCard.tsx@@ -0,0 +1,118 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonCard, LemonTag, Link, Spinner } from '@posthog/lemon-ui'++import { UniversalFilterButton } from 'lib/components/UniversalFilters/UniversalFilterButton'++import { RecordingUniversalFilters, ReplayTemplateCategory, ReplayTemplateType } from '~/types'++import { ReplayTemplateUsedSource, sessionReplayTemplatesLogic } from './sessionRecordingTemplatesLogic'+import { SingleTemplateVariable } from './SingleTemplateVariable'++export function FilterTemplateCard({+ template,+ category,+ source,+ onApply,+}: {+ template: ReplayTemplateType+ category: ReplayTemplateCategory+ source: ReplayTemplateUsedSource+ onApply: (filters: Partial<RecordingUniversalFilters>) => void+}): JSX.Element {+ const logicProps = { template, category }+ const {+ editableVariables,+ filtersToApply,+ previewFilters,+ hasTemplateFilters,+ canApplyFilters,+ variablesVisible,+ matchCount,+ matchCountLoading,+ matchCountError,+ } = useValues(sessionReplayTemplatesLogic(logicProps))+ const { showVariables, hideVariables, reportTemplateUsed } = useActions(sessionReplayTemplatesLogic(logicProps))++ const applyTemplate = (): void => {+ reportTemplateUsed(source)+ onApply(filtersToApply)+ }++ return (+ <LemonCard+ className="w-full"+ onClick={() => showVariables()}+ focused={variablesVisible}+ closeable={variablesVisible}+ onClose={hideVariables}+ data-attr="session-replay-template"+ data-ph-capture-attribute-category={category}+ data-ph-capture-attribute-template={template.key}+ >+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ {template.icon ? (+ <div className="bg-surface-primary rounded p-2 w-8 h-8 flex items-center justify-center">+ {template.icon}+ </div>+ ) : null}+ <h3 className="mb-0">+ <Link onClick={() => showVariables()} className="text-accent">+ {template.name}+ </Link>+ </h3>+ </div>+ <p className="mb-0">{template.description}</p>+ {variablesVisible ? (+ <div className="flex flex-col gap-3 pt-2 border-t">+ {editableVariables.map((variable) => (+ <SingleTemplateVariable key={variable.key} variable={variable} {...logicProps} />+ ))}+ <div className="flex flex-col gap-1">+ <span className="text-xs font-semibold">Filters this will apply</span>+ <div className="flex flex-wrap items-center gap-1">+ {previewFilters.map((filter, index) => (+ <UniversalFilterButton key={index} filter={filter} />+ ))}+ {template.order ? (+ <LemonTag type="muted">Sorted by {template.order.replaceAll('_', ' ')}</LemonTag>+ ) : null}+ {previewFilters.length === 0 && !template.order ? (+ <span className="text-xs text-secondary">Set a value above to see the filters</span>+ ) : null}+ </div>+ </div>+ <span className="text-xs text-secondary flex items-center gap-1">+ {matchCountLoading ? (+ <>+ <Spinner className="text-sm" /> Counting recordings in the last 7 days+ </>+ ) : matchCountError ? (+ 'Could not count recordings. You can still apply the filters.'+ ) : matchCount && hasTemplateFilters ? (+ matchCount.count === 0 ? (+ 'No recordings in the last 7 days. Change the filters.'+ ) : (+ `${matchCount.count}${matchCount.hasMore ? '+' : ''} ${matchCount.count === 1 && !matchCount.hasMore ? 'recording' : 'recordings'} in the last 7 days`+ )+ ) : null}+ </span>+ <div>+ <LemonButton+ type="primary"+ onClick={applyTemplate}+ disabledReason={+ !canApplyFilters ? 'Please set a value for at least one variable' : undefined+ }+ data-attr="session-replay-filter-template-apply"+ >+ Apply filters+ </LemonButton>+ </div>+ </div>+ ) : null}+ </div>+ </LemonCard>+ )+}diff --git a/frontend/src/scenes/session-recordings/templates/FilterTemplates.tsx b/frontend/src/scenes/session-recordings/templates/FilterTemplates.tsxnew file mode 100644index 000000000000..9e7b644c1e54--- /dev/null+++ b/frontend/src/scenes/session-recordings/templates/FilterTemplates.tsx@@ -0,0 +1,40 @@+import { RecordingUniversalFilters, ReplayTemplateCategory } from '~/types'++import { replayTemplates } from './availableTemplates'+import { FilterTemplateCard } from './FilterTemplateCard'+import { ReplayTemplateUsedSource } from './sessionRecordingTemplatesLogic'++const allCategories: ReplayTemplateCategory[] = replayTemplates+ .flatMap((template) => template.categories)+ .filter((category, index, self) => self.indexOf(category) === index)++export function FilterTemplates({+ source,+ onApply,+}: {+ source: ReplayTemplateUsedSource+ onApply: (filters: Partial<RecordingUniversalFilters>) => void+}): JSX.Element {+ return (+ <div className="flex flex-col gap-6">+ {allCategories.map((category) => (+ <div key={category} className="flex flex-col gap-2">+ <h3 className="mb-0">{category}</h3>+ <div className="grid grid-cols-[repeat(auto-fill,minmax(24rem,1fr))] gap-3 items-start">+ {replayTemplates+ .filter((template) => template.categories.includes(category))+ .map((template) => (+ <FilterTemplateCard+ key={template.key}+ template={template}+ category={category}+ source={source}+ onApply={onApply}+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ )+}diff --git a/frontend/src/scenes/session-recordings/templates/SessionRecordingTemplates.tsx b/frontend/src/scenes/session-recordings/templates/SessionRecordingTemplates.tsxindex 69ad4c71d885..e2caef0d14b8 100644--- a/frontend/src/scenes/session-recordings/templates/SessionRecordingTemplates.tsx+++ b/frontend/src/scenes/session-recordings/templates/SessionRecordingTemplates.tsx@@ -1,188 +1,24 @@-import { useActions, useMountedLogic, useValues } from 'kea'+import { router } from 'kea-router'-import { LemonButton, LemonCard, LemonInput, LemonLabel, Link } from '@posthog/lemon-ui'+import { urls } from 'scenes/urls'-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'-import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'-import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'+import { ReplayTabs } from '~/types'-import { actionsModel } from '~/models/actionsModel'-import { FilterLogicalOperator, ReplayTemplateCategory, ReplayTemplateType, ReplayTemplateVariableType } from '~/types'--import { replayTemplates } from './availableTemplates'-import { sessionReplayTemplatesLogic } from './sessionRecordingTemplatesLogic'--interface RecordingTemplateCardProps {- template: ReplayTemplateType- category: ReplayTemplateCategory-}--const allCategories: ReplayTemplateCategory[] = replayTemplates- .flatMap((template) => template.categories)- .filter((category, index, self) => self.indexOf(category) === index)--const NestedFilterGroup = ({ buttonTitle }: { buttonTitle?: string }): JSX.Element => {- const { filterGroup } = useValues(universalFiltersLogic)- const { replaceGroupValue, removeGroupValue } = useActions(universalFiltersLogic)-- return (- <div>- <div className="inline-flex flex-col gap-2">- {filterGroup.values.map((filterOrGroup, index) => {- return isUniversalGroupFilterLike(filterOrGroup) ? (- <UniversalFilters.Group key={index} index={index} group={filterOrGroup}>- <NestedFilterGroup />- </UniversalFilters.Group>- ) : (- <UniversalFilters.Value- key={index}- index={index}- filter={filterOrGroup}- onRemove={() => removeGroupValue(index)}- onChange={(value) => replaceGroupValue(index, value)}- />- )- })}- <div>- <UniversalFilters.AddFilterButton title={buttonTitle} type="secondary" size="xsmall" />- </div>- </div>- </div>- )-}--const SingleTemplateVariable = ({- variable,- ...props-}: RecordingTemplateCardProps & {- variable: ReplayTemplateVariableType-}): JSX.Element | null => {- const { setVariable, resetVariable } = useActions(sessionReplayTemplatesLogic(props))- useMountedLogic(actionsModel)-- return variable.type === 'pageview' ? (- <div>- <LemonLabel info={variable.description}>{variable.name}</LemonLabel>- <LemonInput- placeholder={variable.value}- value={variable.value}- onChange={(e) =>- e ? setVariable({ ...variable, value: e }) : resetVariable({ ...variable, value: undefined })- }- size="small"- />- </div>- ) : ['event', 'person-property'].includes(variable.type) ? (- <div>- <LemonLabel info={variable.description}>{variable.name}</LemonLabel>- <UniversalFilters- rootKey={`session-recordings-${variable.key}`}- group={{- type: FilterLogicalOperator.And,- values: variable.filterGroup ? [variable.filterGroup] : [],- }}- taxonomicGroupTypes={- variable.type === 'event'- ? [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]- : [TaxonomicFilterGroupType.PersonProperties]- }- onChange={(thisFilterGroup) => {- if (thisFilterGroup.values.length === 0) {- resetVariable({ ...variable, filterGroup: undefined })- } else {- setVariable({ ...variable, filterGroup: thisFilterGroup.values[0] })- }- }}- >- <NestedFilterGroup buttonTitle={`Select ${variable.type === 'event' ? 'event' : 'person property'}`} />- </UniversalFilters>- </div>- ) : null-}--const TemplateVariables = (props: RecordingTemplateCardProps): JSX.Element => {- const { navigate } = useActions(sessionReplayTemplatesLogic(props))- const { variables, canApplyFilters } = useValues(sessionReplayTemplatesLogic(props))- return (- <div className="flex flex-col gap-2">- {variables- .filter((v) => !v.noTouch)- .map((variable) => (- <SingleTemplateVariable key={variable.key} variable={variable} {...props} />- ))}- <div>- <LemonButton- onClick={() => navigate()}- type="primary"- className="mt-2"- disabledReason={!canApplyFilters ? 'Please set a value for at least one variable' : undefined}- >- Apply filters- </LemonButton>- </div>- </div>- )-}--const RecordingTemplateCard = (props: RecordingTemplateCardProps): JSX.Element => {- const { showVariables, hideVariables } = useActions(sessionReplayTemplatesLogic(props))- const { variablesVisible } = useValues(sessionReplayTemplatesLogic(props))-- return (- <LemonCard- className="w-80"- onClick={() => {- showVariables()- }}- closeable={variablesVisible}- onClose={hideVariables}- focused={variablesVisible}- data-attr="session-replay-template"- data-ph-capture-attribute-category={props.category}- data-ph-capture-attribute-template={props.template.key}- >- <div className="flex flex-col gap-2">- <div className="flex items-center gap-2">- {props.template.icon && (- <div className="bg-surface-primary rounded p-2 w-8 h-8 flex items-center justify-center">- {props.template.icon}- </div>- )}- <h3 className="mb-0">- <Link onClick={() => showVariables()} className="text-accent">- {props.template.name}- </Link>- </h3>- </div>- <p>{props.template.description}</p>- {variablesVisible ? <TemplateVariables {...props} /> : null}- </div>- </LemonCard>- )-}+import { FilterTemplates } from './FilterTemplates'const SessionRecordingTemplates = (): JSX.Element => {return (- <div>- <p>To get the most out of session replay, you just need to know where to start. </p>- <h2 className="mt-4">Filter templates</h2>- <p>- Use our templates to find a focus area, then watch the filtered replays to see where users struggle,- what could be made more clear, and other ways to improve.+ <div className="flex flex-col gap-4">+ <p className="mb-0">+ Use a template to find a focus area, then watch the filtered replays to see where users struggle and+ what could be made more clear.</p>- {allCategories.map((category) => (- <div key={`replay-template-category-${category}`} className="mb-6">- <h2>{category}</h2>- <div className="flex flex-wrap gap-2">- {replayTemplates- .filter((template) => template.categories.includes(category))- .map((template) => (- <RecordingTemplateCard key={template.key} template={template} category={category} />- ))}- </div>- </div>- ))}+ <FilterTemplates+ source="templates_tab"+ onApply={({ order, ...filters }) =>+ router.actions.push(urls.replay(ReplayTabs.Home, filters, undefined, order))+ }+ /></div>)}diff --git a/frontend/src/scenes/session-recordings/templates/SingleTemplateVariable.tsx b/frontend/src/scenes/session-recordings/templates/SingleTemplateVariable.tsxnew file mode 100644index 000000000000..07518c3ffc8f--- /dev/null+++ b/frontend/src/scenes/session-recordings/templates/SingleTemplateVariable.tsx@@ -0,0 +1,100 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { LemonInput, LemonLabel } from '@posthog/lemon-ui'++import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'+import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'+import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'++import { actionsModel } from '~/models/actionsModel'+import { FilterLogicalOperator, ReplayTemplateVariableType } from '~/types'++import { ReplayTemplateLogicPropsType, sessionReplayTemplatesLogic } from './sessionRecordingTemplatesLogic'++const NestedFilterGroup = ({ buttonTitle }: { buttonTitle?: string }): JSX.Element => {+ const { filterGroup } = useValues(universalFiltersLogic)+ const { replaceGroupValue, removeGroupValue } = useActions(universalFiltersLogic)++ return (+ <div>+ <div className="inline-flex flex-col gap-2">+ {filterGroup.values.map((filterOrGroup, index) => {+ return isUniversalGroupFilterLike(filterOrGroup) ? (+ <UniversalFilters.Group key={index} index={index} group={filterOrGroup}>+ <NestedFilterGroup />+ </UniversalFilters.Group>+ ) : (+ <UniversalFilters.Value+ key={index}+ index={index}+ filter={filterOrGroup}+ onRemove={() => removeGroupValue(index)}+ onChange={(value) => replaceGroupValue(index, value)}+ />+ )+ })}+ <div>+ <UniversalFilters.AddFilterButton title={buttonTitle} type="secondary" size="xsmall" />+ </div>+ </div>+ </div>+ )+}++export const SingleTemplateVariable = ({+ variable,+ ...props+}: ReplayTemplateLogicPropsType & {+ variable: ReplayTemplateVariableType+}): JSX.Element | null => {+ const { setVariable, resetVariable } = useActions(sessionReplayTemplatesLogic(props))+ useMountedLogic(actionsModel)++ return variable.type === 'pageview' ? (+ <div>+ <LemonLabel info={variable.description}>{variable.name}</LemonLabel>+ <LemonInput+ placeholder={variable.value}+ value={variable.value}+ onChange={(e) =>+ e ? setVariable({ ...variable, value: e }) : resetVariable({ ...variable, value: undefined })+ }+ size="small"+ />+ </div>+ ) : ['event', 'person-property'].includes(variable.type) ? (+ <div>+ <LemonLabel info={variable.description}>{variable.name}</LemonLabel>+ <UniversalFilters+ rootKey={`session-recordings-${variable.key}`}+ group={{+ type: FilterLogicalOperator.And,+ values: !variable.filterGroup+ ? []+ : isUniversalGroupFilterLike(variable.filterGroup)+ ? variable.filterGroup.values+ : [variable.filterGroup],+ }}+ taxonomicGroupTypes={+ variable.type === 'event'+ ? [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]+ : [TaxonomicFilterGroupType.PersonProperties]+ }+ onChange={(thisFilterGroup) => {+ if (thisFilterGroup.values.length === 0) {+ resetVariable({ ...variable, filterGroup: undefined })+ } else {+ setVariable({+ ...variable,+ filterGroup:+ thisFilterGroup.values.length === 1 ? thisFilterGroup.values[0] : thisFilterGroup,+ })+ }+ }}+ >+ <NestedFilterGroup buttonTitle={`Select ${variable.type === 'event' ? 'event' : 'person property'}`} />+ </UniversalFilters>+ </div>+ ) : null+}diff --git a/frontend/src/scenes/session-recordings/templates/sessionRecordingTemplatesLogic.test.ts b/frontend/src/scenes/session-recordings/templates/sessionRecordingTemplatesLogic.test.tsnew file mode 100644index 000000000000..f85eb46a75b8--- /dev/null+++ b/frontend/src/scenes/session-recordings/templates/sessionRecordingTemplatesLogic.test.ts@@ -0,0 +1,89 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { ReplayTemplateType } from '~/types'++import { TEMPLATE_BASE_FILTERS, sessionReplayTemplatesLogic } from './sessionRecordingTemplatesLogic'++const template: ReplayTemplateType = {+ key: 'signup-flow',+ name: 'Signup flow',+ description: '',+ categories: ['B2B'],+ variables: [{ type: 'pageview', name: 'Signup page URL', key: 'signup-page-url' }],+}++describe('sessionReplayTemplatesLogic', () => {+ let logic: ReturnType<typeof sessionReplayTemplatesLogic.build>+ let recordingsRequests: string[]++ beforeEach(() => {+ recordingsRequests = []+ localStorage.clear()+ initKeaTests()+ logic = sessionReplayTemplatesLogic({ template, category: 'B2B' })+ logic.mount()+ })++ it.each([+ [3, false],+ [25, true],+ ])('counts %s matching recordings (has more: %s) once a variable is set', async (resultCount, hasNext) => {+ useMocks({+ get: {+ '/api/environments/:team_id/session_recordings': ({ request }) => {+ recordingsRequests.push(new URL(request.url).search)+ return [200, { results: Array(resultCount).fill({ id: 'r' }), has_next: hasNext }]+ },+ },+ })++ logic.actions.showVariables()+ await expectLogic(logic).toFinishAllListeners()+ expect(recordingsRequests).toHaveLength(0)++ logic.actions.setVariable({ ...template.variables![0], value: '/sign-up' })+ await expectLogic(logic).toFinishAllListeners()++ expect(recordingsRequests).toHaveLength(1)+ expect(recordingsRequests[0]).toContain('sign-up')+ expect(recordingsRequests[0]).toContain('filter_test_accounts=false')+ expect(logic.values.matchCount).toEqual({ count: resultCount, hasMore: hasNext })+ })++ it('applies the template with the same base filters the count uses', () => {+ logic.actions.setVariable({ ...template.variables![0], value: '/sign-up' })++ expect(logic.values.filtersToApply).toMatchObject(TEMPLATE_BASE_FILTERS)+ expect(logic.values.filtersToApply.filter_group).toBeTruthy()+ })++ it('counts once when a card opens, not on every click inside it', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/session_recordings': ({ request }) => {+ recordingsRequests.push(new URL(request.url).search)+ return [200, { results: [], has_next: false }]+ },+ },+ })+ logic.actions.setVariable({ ...template.variables![0], value: '/sign-up' })+ logic.actions.showVariables()+ logic.actions.showVariables()+ await expectLogic(logic).toFinishAllListeners()++ expect(recordingsRequests).toHaveLength(1)+ })++ it('marks the count as failed instead of throwing when the request errors', async () => {+ useMocks({ get: { '/api/environments/:team_id/session_recordings': () => [500, { detail: 'boom' }] } })++ logic.actions.showVariables()+ logic.actions.setVariable({ ...template.variables![0], value: '/sign-up' })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.matchCountError).toBe(true)+ expect(logic.values.matchCount).toBeNull()+ })+})diff --git a/frontend/src/scenes/session-recordings/templates/sessionRecordingTemplatesLogic.tsx b/frontend/src/scenes/session-recordings/templates/sessionRecordingTemplatesLogic.tsxindex 2d364b94305c..805c6fd35821 100644--- a/frontend/src/scenes/session-recordings/templates/sessionRecordingTemplatesLogic.tsx+++ b/frontend/src/scenes/session-recordings/templates/sessionRecordingTemplatesLogic.tsx@@ -1,24 +1,44 @@import clsx from 'clsx'import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'-import { router } from 'kea-router'+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 { urls } from 'scenes/urls'+import { RecordingOrder } from '~/queries/schema/schema-general'import {FilterLogicalOperator,PropertyFilterType,PropertyOperator,RecordingUniversalFilters,- ReplayTabs,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 {@@ -29,6 +49,8 @@ const getPageviewFilterValue = (pageview: string): UniversalFiltersGroupValue =>}}+export type ReplayTemplateUsedSource = 'templates_tab' | 'filters_panel'+export interface ReplayTemplateLogicPropsType {template: ReplayTemplateType// one card can be in multiple categories,@@ -43,6 +65,12 @@ export interface sessionReplayTemplatesLogicValues {canApplyFilters: booleaneditableVariables: ReplayTemplateVariableType[]filterGroup: Partial<RecordingUniversalFilters>+ filtersToApply: Partial<RecordingUniversalFilters>+ hasTemplateFilters: boolean+ matchCount: TemplateMatchCount | null+ matchCountError: boolean+ matchCountLoading: boolean+ previewFilters: UniversalFilterValue[]variables: ReplayTemplateVariableType[]variablesVisible: boolean}@@ -52,9 +80,39 @@ export interface sessionReplayTemplatesLogicActions {hideVariables: () => {value: true}- navigate: () => {+ 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: ReplayTemplateUsedSource+ }resetVariable: (variable: ReplayTemplateVariableType) => {variable: ReplayTemplateVariableType}@@ -74,6 +132,13 @@ 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[]) => booleancanApplyFilters: (variables: ReplayTemplateVariableType[], areAnyVariablesTouched: boolean) => booleanareAnyVariablesTouched: (variables: ReplayTemplateVariableType[]) => booleaneditableVariables: (variables: ReplayTemplateVariableType[]) => ReplayTemplateVariableType[]@@ -98,7 +163,9 @@ export const sessionReplayTemplatesLogic = kea<sessionReplayTemplatesLogicType>(setVariables: (variables?: ReplayTemplateVariableType[]) => ({ variables }),setVariable: (variable: ReplayTemplateVariableType) => ({ variable }),resetVariable: (variable: ReplayTemplateVariableType) => ({ variable }),- navigate: true,+ reportTemplateUsed: (source: ReplayTemplateUsedSource) => ({ source }),+ matchCountFailed: true,+ loadMatchCount: true,showVariables: true,hideVariables: true,}),@@ -129,6 +196,47 @@ export const sessionReplayTemplatesLogic = kea<sessionReplayTemplatesLogicType>(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: [@@ -164,6 +272,31 @@ export const sessionReplayTemplatesLogic = kea<sessionReplayTemplatesLogicType>(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.variables, s.areAnyVariablesTouched],(variables: ReplayTemplateVariableType[], areAnyVariablesTouched: boolean) =>@@ -179,14 +312,28 @@ export const sessionReplayTemplatesLogic = kea<sessionReplayTemplatesLogicType>((variables: ReplayTemplateVariableType[]) => variables.filter((v) => !v.noTouch),],}),- listeners(({ values, props }) => ({- navigate: () => {+ 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,})- const filterGroup = values.variables.length > 0 ? values.filterGroup : undefined- router.actions.push(urls.replay(ReplayTabs.Home, filterGroup, undefined, props.template.order))},})),events(({ actions, props, values }) => ({