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.

15.2 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectClean, objectsEqual } from 'lib/utils/objects'
import { toParams } from 'lib/utils/url'
import { urls } from 'scenes/urls'

import {
    ReplayTabs,
    SavedSessionRecordingPlaylistsFilters,
    SavedSessionRecordingPlaylistsResult,
    SessionRecordingPlaylistType,
} from '~/types'

import { createPlaylist, deletePlaylist } from '../playlist/playlistUtils'

export const PLAYLISTS_PER_PAGE = 30

export const DEFAULT_PLAYLIST_FILTERS = {
    createdBy: 'All users',
    page: 1,
    dateFrom: 'all',
    order: '-last_modified_at',
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionRecordingCollectionsLogicValues {
    builtInPlaylists: SessionRecordingPlaylistType[]
    builtInPlaylistsLoading: boolean
    filters: Record<string, any> | SavedSessionRecordingPlaylistsFilters
    loadPlaylistsFailed: boolean
    pagination: PaginationManual
    playlists: SavedSessionRecordingPlaylistsResult
    playlistsLoading: boolean
    sorting: Sorting | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionRecordingCollectionsLogicActions {
    deletePlaylist: (playlist: SessionRecordingPlaylistType) => {
        playlist: SessionRecordingPlaylistType
    }
    deletePlaylistFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deletePlaylistSuccess: (
        playlists: {
            count: number
            filters?: SavedSessionRecordingPlaylistsFilters | null | undefined
            next?: string | null | undefined
            previous?: string | null | undefined
            results: SessionRecordingPlaylistType[]
        },
        payload?: {
            playlist: SessionRecordingPlaylistType
        }
    ) => {
        playlists: {
            count: number
            filters?: SavedSessionRecordingPlaylistsFilters | null | undefined
            next?: string | null | undefined
            previous?: string | null | undefined
            results: SessionRecordingPlaylistType[]
        }
        payload?: {
            playlist: SessionRecordingPlaylistType
        }
    }
    duplicatePlaylist: (playlist: SessionRecordingPlaylistType) => {
        playlist: SessionRecordingPlaylistType
    }
    duplicatePlaylistFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    duplicatePlaylistSuccess: (
        playlists: SavedSessionRecordingPlaylistsResult,
        payload?: {
            playlist: SessionRecordingPlaylistType
        }
    ) => {
        playlists: SavedSessionRecordingPlaylistsResult
        payload?: {
            playlist: SessionRecordingPlaylistType
        }
    }
    loadBuiltInPlaylists: () => {
        value: true
    }
    loadBuiltInPlaylistsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadBuiltInPlaylistsSuccess: (
        builtInPlaylists: SessionRecordingPlaylistType[],
        payload?: {
            value: true
        }
    ) => {
        builtInPlaylists: SessionRecordingPlaylistType[]
        payload?: {
            value: true
        }
    }
    loadPlaylists: () => {
        value: true
    }
    loadPlaylistsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPlaylistsSuccess: (
        playlists: SavedSessionRecordingPlaylistsResult,
        payload?: {
            value: true
        }
    ) => {
        playlists: SavedSessionRecordingPlaylistsResult
        payload?: {
            value: true
        }
    }
    setSavedPlaylistsFilters: (filters: Partial<SavedSessionRecordingPlaylistsFilters>) => {
        filters: Partial<SavedSessionRecordingPlaylistsFilters>
    }
    updatePlaylist: (
        shortId: SessionRecordingPlaylistType['short_id'],
        properties: Partial<SessionRecordingPlaylistType>
    ) => {
        properties: Partial<SessionRecordingPlaylistType>
        shortId: string
    }
    updatePlaylistFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updatePlaylistSuccess: (
        playlists: {
            count: number
            filters?: SavedSessionRecordingPlaylistsFilters | null | undefined
            next?: string | null | undefined
            previous?: string | null | undefined
            results: SessionRecordingPlaylistType[]
        },
        payload?: {
            properties: Partial<SessionRecordingPlaylistType>
            shortId: string
        }
    ) => {
        playlists: {
            count: number
            filters?: SavedSessionRecordingPlaylistsFilters | null | undefined
            next?: string | null | undefined
            previous?: string | null | undefined
            results: SessionRecordingPlaylistType[]
        }
        payload?: {
            properties: Partial<SessionRecordingPlaylistType>
            shortId: string
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionRecordingCollectionsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        sorting: (filters: Record<string, any> | SavedSessionRecordingPlaylistsFilters) => Sorting | null
        pagination: (
            filters: Record<string, any> | SavedSessionRecordingPlaylistsFilters,
            playlists: SavedSessionRecordingPlaylistsResult
        ) => PaginationManual
    }
}

export type sessionRecordingCollectionsLogicType = MakeLogicType<
    sessionRecordingCollectionsLogicValues,
    sessionRecordingCollectionsLogicActions,
    Record<string, any>,
    sessionRecordingCollectionsLogicMeta
>

export const sessionRecordingCollectionsLogic = kea<sessionRecordingCollectionsLogicType>([
    path(() => ['scenes', 'session-recordings', 'collections', 'sessionRecordingCollectionsLogic']),

    actions(() => ({
        setSavedPlaylistsFilters: (filters: Partial<SavedSessionRecordingPlaylistsFilters>) => ({
            filters,
        }),
        loadPlaylists: true,
        loadBuiltInPlaylists: true,
        updatePlaylist: (
            shortId: SessionRecordingPlaylistType['short_id'],
            properties: Partial<SessionRecordingPlaylistType>
        ) => ({ shortId, properties }),
        deletePlaylist: (playlist: SessionRecordingPlaylistType) => ({ playlist }),
        duplicatePlaylist: (playlist: SessionRecordingPlaylistType) => ({ playlist }),
    })),
    reducers(() => ({
        filters: [
            DEFAULT_PLAYLIST_FILTERS as SavedSessionRecordingPlaylistsFilters | Record<string, any>,
            {
                setSavedPlaylistsFilters: (state, { filters }) => {
                    const merged = {
                        ...state,
                        ...filters,
                        ...('page' in filters ? {} : { page: 1 }),
                    }

                    const cleaned = Object.fromEntries(
                        Object.entries(merged).filter(
                            ([key, value]) =>
                                key === 'page' ||
                                DEFAULT_PLAYLIST_FILTERS[key as keyof typeof DEFAULT_PLAYLIST_FILTERS] !== value
                        )
                    )

                    return objectClean(cleaned)
                },
            },
        ],
        loadPlaylistsFailed: [
            false,
            {
                loadPlaylists: () => false,
                loadPlaylistsSuccess: () => false,
                loadPlaylistsFailure: () => true,
            },
        ],
    })),
    loaders(({ values, actions }) => ({
        builtInPlaylists: {
            __default: [] as SessionRecordingPlaylistType[],
            loadBuiltInPlaylists: async () => {
                // nosemgrep: prefer-codegen-api-namespaced-replay
                const response = await api.recordings.listPlaylists(
                    toParams({ type: 'collection', collection_type: 'synthetic', limit: 100 })
                )
                return response.results.filter((playlist) => playlist.is_synthetic)
            },
        },
        playlists: {
            __default: { results: [], count: 0, filters: null } as SavedSessionRecordingPlaylistsResult,
            loadPlaylists: async (_, breakpoint) => {
                if (values.playlists.filters !== null) {
                    await breakpoint(300)
                }

                const filters = { ...values.filters }
                const createdBy = filters.createdBy === 'All users' ? undefined : filters.createdBy

                const params = {
                    limit: PLAYLISTS_PER_PAGE,
                    offset: Math.max(0, (filters.page - 1) * PLAYLISTS_PER_PAGE),
                    order: filters.order ?? '-last_modified_at',
                    created_by: createdBy ?? undefined,
                    search: filters.search || undefined,
                    date_from: filters.dateFrom && filters.dateFrom != 'all' ? filters.dateFrom : undefined,
                    date_to: filters.dateTo ?? undefined,
                    pinned: filters.pinned ? true : undefined,
                    type: 'collection',
                    collection_type: 'custom',
                }

                const response = await api.recordings.listPlaylists(toParams(params))
                breakpoint()

                return response
            },
            updatePlaylist: async ({ shortId, properties }, breakpoint) => {
                await breakpoint(100)
                const updatedPlaylist = await api.recordings.updatePlaylist(shortId, properties)
                breakpoint()

                const index = values.playlists.results.findIndex((x) => x.short_id === updatedPlaylist.short_id)
                if (index > -1) {
                    values.playlists.results[index] = updatedPlaylist
                }

                return { ...values.playlists, results: [...values.playlists.results] }
            },
            deletePlaylist: async ({ playlist }) => {
                await deletePlaylist(playlist, () => actions.loadPlaylists())
                return {
                    ...values.playlists,
                    results: values.playlists.results.filter((x) => x.short_id !== playlist.short_id),
                }
            },

            duplicatePlaylist: async ({ playlist }, breakpoint) => {
                await breakpoint(100)

                const { id, short_id, ...partialPlaylist } = playlist
                partialPlaylist.name = partialPlaylist.name ? partialPlaylist.name + ' (copy)' : ''
                partialPlaylist.creation_method = 'duplicate'

                const newPlaylist = await createPlaylist(partialPlaylist)

                breakpoint()
                if (!newPlaylist) {
                    return values.playlists
                }

                lemonToast.success('Playlist duplicated successfully')

                return { ...values.playlists, results: [newPlaylist, ...values.playlists.results] }
            },
        },
    })),
    listeners(({ actions }) => ({
        setSavedPlaylistsFilters: () => {
            actions.loadPlaylists()
        },
    })),

    selectors(({ actions }) => ({
        sorting: [
            (s) => [s.filters],
            (filters: Record<string, any> | SavedSessionRecordingPlaylistsFilters): Sorting | null => {
                if (!filters.order) {
                    return {
                        columnKey: 'last_modified_at',
                        order: -1,
                    }
                }
                return filters.order.startsWith('-')
                    ? {
                          columnKey: filters.order.slice(1),
                          order: -1,
                      }
                    : {
                          columnKey: filters.order,
                          order: 1,
                      }
            },
        ],
        pagination: [
            (s) => [s.filters, s.playlists],
            (
                filters: Record<string, any> | SavedSessionRecordingPlaylistsFilters,
                playlists: SavedSessionRecordingPlaylistsResult
            ): PaginationManual => {
                return {
                    controlled: true,
                    pageSize: PLAYLISTS_PER_PAGE,
                    currentPage: filters.page,
                    entryCount: playlists.count,
                    onBackward: playlists.previous
                        ? () =>
                              actions.setSavedPlaylistsFilters({
                                  page: filters.page - 1,
                              })
                        : undefined,
                    onForward: playlists.next
                        ? () =>
                              actions.setSavedPlaylistsFilters({
                                  page: filters.page + 1,
                              })
                        : undefined,
                }
            },
        ],
    })),
    actionToUrl(({ values }) => {
        const changeUrl = ():
            | [
                  string,
                  Record<string, any>,
                  Record<string, any>,
                  {
                      replace: boolean
                  },
              ]
            | void => {
            if (removeProjectIdIfPresent(router.values.location.pathname) === urls.replay(ReplayTabs.Playlists)) {
                const nextValues = values.filters
                const urlValues = objectClean(router.values.searchParams)

                // Only include non-default values in URL
                // We always include the page number in the URL
                const nonDefaultValues = objectClean(
                    Object.fromEntries(
                        Object.entries(nextValues).filter(
                            ([key, value]) =>
                                key === 'page' ||
                                DEFAULT_PLAYLIST_FILTERS[key as keyof typeof DEFAULT_PLAYLIST_FILTERS] !== value
                        )
                    )
                )

                if (!objectsEqual(nonDefaultValues, urlValues)) {
                    return [urls.replay(ReplayTabs.Playlists), nonDefaultValues, {}, { replace: false }]
                }
            }
        }
        return {
            loadPlaylists: changeUrl,
            setSavedPlaylistsFilters: changeUrl,
        }
    }),
    urlToAction(({ actions, values }) => ({
        [urls.replay(ReplayTabs.Playlists)]: (_, searchParams) => {
            const currentFilters = values.filters
            const nextFilters = objectClean(searchParams)
            if (!objectsEqual(currentFilters, nextFilters)) {
                actions.setSavedPlaylistsFilters(nextFilters)
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadPlaylists()
        actions.loadBuiltInPlaylists()
    }),
])