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.

11.2 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'

import { Dayjs, dayjs } from 'lib/dayjs'
import { humanFriendlyMilliseconds } from 'lib/utils/durations'
import { performanceEventDataLogic } from 'scenes/session-recordings/apm/performanceEventDataLogic'
import { percentagesWithinEventRange } from 'scenes/session-recordings/apm/waterfall/TimingBar'
import {
    SessionRecordingDataCoordinatorLogicProps,
    sessionRecordingDataCoordinatorLogic,
} from 'scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic'

import { PerformanceEvent } from '~/types'

import type { SessionPlayerData, SessionRecordingType } from '../../../types'
import type { AssetSizeInfo } from './performanceEventDataLogic'

export interface NetworkViewLogicProps extends SessionRecordingDataCoordinatorLogicProps {}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface networkViewLogicValues {
    allPerformanceEvents: PerformanceEvent[] // performanceEventDataLogic
    sizeBreakdown: Record<string, AssetSizeInfo> // performanceEventDataLogic
    sessionPlayerData: SessionPlayerData // sessionRecordingDataCoordinatorLogic
    sessionPlayerMetaData: SessionRecordingType | null // sessionRecordingDataCoordinatorLogic
    sessionPlayerMetaDataLoading: boolean // sessionRecordingDataCoordinatorLogic
    snapshotsLoading: boolean // sessionRecordingDataCoordinatorLogic
    start: Dayjs | null // sessionRecordingDataCoordinatorLogic
    currentPage: (PerformanceEvent & {
        timeInRecording: number
    })[]
    finalItem:
        | (PerformanceEvent & {
              timeInRecording: number
          })
        | null
    formattedDurationFor: (item: PerformanceEvent) => string | undefined
    hasPageViews: boolean
    isLoading: boolean
    navigationItem:
        | (PerformanceEvent & {
              timeInRecording: number
          })
        | null
    page: number
    pageCount: number
    pageViews: (PerformanceEvent & {
        timeInRecording: number
    })[][]
    positionPercentagesFor: (item: PerformanceEvent) =>
        | {
              startPercentage: string
              widthPercentage: string
          }
        | null
        | undefined
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface networkViewLogicActions {
    loadSnapshots: () => {
        value: true
    } // sessionRecordingDataCoordinatorLogic
    maybeLoadRecordingMeta: () => {
        value: true
    } // sessionRecordingDataCoordinatorLogic
    nextPage: () => boolean
    prevPage: () => boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface networkViewLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        isLoading: (snapshotsLoading: boolean, sessionPlayerMetaDataLoading: boolean) => boolean
        pageViews: (
            allPerformanceEvents: PerformanceEvent[],
            start: Dayjs | null
        ) => (PerformanceEvent & {
            timeInRecording: number
        })[][]
        pageCount: (
            pageViews: (PerformanceEvent & {
                timeInRecording: number
            })[][]
        ) => number
        currentPage: (
            pageViews: (PerformanceEvent & {
                timeInRecording: number
            })[][],
            page: number
        ) => (PerformanceEvent & {
            timeInRecording: number
        })[]
        navigationItem: (
            currentPage: (PerformanceEvent & {
                timeInRecording: number
            })[]
        ) =>
            | (PerformanceEvent & {
                  timeInRecording: number
              })
            | null
        finalItem: (
            currentPage: (PerformanceEvent & {
                timeInRecording: number
            })[]
        ) =>
            | (PerformanceEvent & {
                  timeInRecording: number
              })
            | null
        positionPercentagesFor: (
            navigationItem:
                | (PerformanceEvent & {
                      timeInRecording: number
                  })
                | null,
            finalItem:
                | (PerformanceEvent & {
                      timeInRecording: number
                  })
                | null
        ) => (item: PerformanceEvent) =>
            | {
                  startPercentage: string
                  widthPercentage: string
              }
            | null
            | undefined
        hasPageViews: (pageCount: number) => boolean
    }
}

export type networkViewLogicType = MakeLogicType<
    networkViewLogicValues,
    networkViewLogicActions,
    NetworkViewLogicProps,
    networkViewLogicMeta
>

export const networkViewLogic = kea<networkViewLogicType>([
    path(['scenes', 'session-recordings', 'apm', 'networkViewLogic']),
    key((props) => `network-view-${props.sessionRecordingId}`),
    props({} as NetworkViewLogicProps),
    connect((props: NetworkViewLogicProps) => ({
        values: [
            sessionRecordingDataCoordinatorLogic(props),
            ['sessionPlayerData', 'sessionPlayerMetaData', 'snapshotsLoading', 'sessionPlayerMetaDataLoading', 'start'],
            performanceEventDataLogic({ key: props.sessionRecordingId, sessionRecordingId: props.sessionRecordingId }),
            ['allPerformanceEvents', 'sizeBreakdown'],
        ],
        actions: [sessionRecordingDataCoordinatorLogic(props), ['loadSnapshots', 'maybeLoadRecordingMeta']],
    })),
    actions({
        nextPage: () => true,
        prevPage: () => true,
    }),
    reducers({
        page: [
            0,
            {
                nextPage: (state) => state + 1,
                prevPage: (state) => Math.max(0, state - 1),
            },
        ],
    }),
    afterMount(({ actions }) => {
        actions.maybeLoadRecordingMeta()
        actions.loadSnapshots()
    }),
    selectors({
        isLoading: [
            (s) => [s.snapshotsLoading, s.sessionPlayerMetaDataLoading],
            (snapshotsLoading: boolean, sessionPlayerMetaDataLoading: boolean) =>
                snapshotsLoading || sessionPlayerMetaDataLoading,
        ],
        pageViews: [
            (s) => [s.allPerformanceEvents, s.start],
            (
                allPerformanceEvents: PerformanceEvent[],
                start: Dayjs
            ): (PerformanceEvent & { timeInRecording: number })[][] => {
                // ignore events before the first navigation event
                // then we create an array of performance events for each page
                // and store them in an array
                const pages: (PerformanceEvent & { timeInRecording: number })[][] = []

                for (const perfEvent of allPerformanceEvents) {
                    const hasAnyNavigation = Object.keys(pages).length
                    const eventType = perfEvent.entry_type
                    if (!hasAnyNavigation && eventType !== 'navigation') {
                        continue
                    }
                    const timedEvent = {
                        ...perfEvent,
                        timeInRecording: dayjs(perfEvent.timestamp).valueOf() - start?.valueOf(),
                    }
                    if (eventType === 'navigation') {
                        pages.push([timedEvent])
                    } else {
                        pages[pages.length - 1].push(timedEvent)
                    }
                }

                return pages
            },
        ],
        pageCount: [
            (s) => [s.pageViews],
            (
                pageViews: (PerformanceEvent & {
                    timeInRecording: number
                })[][]
            ) => pageViews.length,
        ],
        currentPage: [
            (s) => [s.pageViews, s.page],
            (
                pageViews: (PerformanceEvent & {
                    timeInRecording: number
                })[][],
                page: number
            ) => {
                return pageViews[page] || []
            },
        ],
        navigationItem: [
            (s) => [s.currentPage],
            (
                currentPage: (PerformanceEvent & {
                    timeInRecording: number
                })[]
            ) => {
                if (currentPage.length) {
                    return currentPage[0]
                }
                return null
            },
        ],
        finalItem: [
            (s) => [s.currentPage],
            (
                currentPage: (PerformanceEvent & {
                    timeInRecording: number
                })[]
            ) => {
                if (currentPage.length) {
                    return currentPage[currentPage.length - 1]
                }
                return null
            },
        ],
        formattedDurationFor: [
            () => [],
            () => {
                return (item: PerformanceEvent) => {
                    let formattedDuration: string | undefined
                    const itemStart = item.start_time
                    const itemEnd = item.load_event_end ? item.load_event_end : item.response_end
                    if (itemStart !== undefined && itemEnd !== undefined) {
                        const itemDuration = itemEnd - itemStart
                        formattedDuration = humanFriendlyMilliseconds(itemDuration)
                    } else {
                        formattedDuration = ''
                    }

                    return formattedDuration
                }
            },
        ],
        positionPercentagesFor: [
            (s) => [s.navigationItem, s.finalItem],
            (
                navigationItem:
                    | (PerformanceEvent & {
                          timeInRecording: number
                      })
                    | null,
                finalItem:
                    | (PerformanceEvent & {
                          timeInRecording: number
                      })
                    | null
            ) => {
                return (item: PerformanceEvent) => {
                    if (!navigationItem || !finalItem) {
                        return
                    }

                    const rangeStart = navigationItem.start_time
                    const rangeEnd = finalItem.load_event_end ? finalItem.load_event_end : finalItem.response_end

                    const itemStart = item.start_time
                    const itemEnd = item.load_event_end ? item.load_event_end : item.response_end

                    if (
                        itemStart === undefined ||
                        itemEnd === undefined ||
                        rangeStart === undefined ||
                        rangeEnd === undefined
                    ) {
                        return null
                    }

                    const percentages = percentagesWithinEventRange({
                        rangeStart,
                        rangeEnd,
                        partStart: itemStart,
                        partEnd: itemEnd,
                    })
                    const startPercentage = percentages.startPercentage
                    const widthPercentage = percentages.widthPercentage
                    return { startPercentage, widthPercentage }
                }
            },
        ],
        hasPageViews: [(s) => [s.pageCount], (pageCount: number) => pageCount > 0],
    }),
])