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.

5.0 KB
Raw Blame
import { BindLogic, useActions, useValues } from 'kea'
import { MutableRefObject, memo, useEffect, useRef, useState } from 'react'
import { useDebouncedCallback } from 'use-debounce'

import { Dayjs } from 'lib/dayjs'
import useIsHovering from 'lib/hooks/useIsHovering'
import { cn } from 'lib/utils/css-classes'
import { formatLocalizedTime } from 'lib/utils/datetime'
import { colonDelimitedDuration } from 'lib/utils/durations'

import { PlayerFrame } from '../PlayerFrame'
import { TimestampFormat } from '../playerSettingsLogic'
import {
    SessionRecordingPlayerLogicProps,
    SessionRecordingPlayerMode,
    sessionRecordingPlayerLogic,
} from '../sessionRecordingPlayerLogic'

const TWENTY_MINUTES_IN_MS = 20 * 60 * 1000

export type PlayerSeekbarPreviewProps = {
    minMs: number
    maxMs: number
    seekBarRef: MutableRefObject<HTMLDivElement | null>
    activeMs: number | null
    timestampFormat: TimestampFormat
    startTime: Dayjs | null
    showPreviewFrame?: boolean
}

const PlayerSeekbarPreviewFrame = ({
    percentage,
    minMs,
    maxMs,
    isVisible,
}: { percentage: number; isVisible: boolean } & Omit<
    PlayerSeekbarPreviewProps,
    'seekBarRef' | 'activeMs' | 'timestampFormat' | 'startTime'
>): JSX.Element | null => {
    const { sessionRecordingId, logicProps } = useValues(sessionRecordingPlayerLogic)

    const seekPlayerLogicProps: SessionRecordingPlayerLogicProps = {
        sessionRecordingId: sessionRecordingId,
        playerKey: `${logicProps.playerKey}-preview`,
        autoPlay: false,
        mode: SessionRecordingPlayerMode.Preview,
    }

    const { setPause, seekToTime } = useActions(sessionRecordingPlayerLogic(seekPlayerLogicProps))

    const debouncedSeekToTime = useDebouncedCallback(
        (time: number) => {
            setPause()
            seekToTime(time)
        },
        200,
        {
            maxWait: 500,
        }
    )

    useEffect(() => {
        if (isVisible) {
            debouncedSeekToTime(minMs + (maxMs - minMs) * percentage)
        }
    }, [percentage, minMs, maxMs, isVisible]) // oxlint-disable-line react-hooks/exhaustive-deps

    return (
        <BindLogic logic={sessionRecordingPlayerLogic} props={seekPlayerLogicProps}>
            <div className="bg-red w-60 h-40">
                <PlayerFrame />
            </div>
        </BindLogic>
    )
}

export const PlayerSeekbarPreview = memo(function PlayerSeekbarPreview({
    minMs,
    maxMs,
    seekBarRef,
    activeMs,
    timestampFormat,
    startTime,
    showPreviewFrame = false,
}: PlayerSeekbarPreviewProps): JSX.Element {
    const [percentage, setPercentage] = useState<number>(0)
    const ref = useRef<HTMLDivElement>(null)
    const fixedUnits = maxMs / 1000 > 3600 ? 3 : 2

    const progressionSeconds = ((maxMs - minMs) / 1000) * percentage

    const absoluteTime = startTime?.add(progressionSeconds, 'seconds')

    const content =
        timestampFormat === TimestampFormat.Relative
            ? colonDelimitedDuration(minMs / 1000 + progressionSeconds, fixedUnits)
            : absoluteTime
              ? (timestampFormat === TimestampFormat.UTC ? absoluteTime?.tz('UTC') : absoluteTime)?.format(
                    formatLocalizedTime()
                )
              : '00:00:00'

    const isHovering = useIsHovering(seekBarRef)

    const canShowPreview = showPreviewFrame && typeof activeMs === 'number' && activeMs < TWENTY_MINUTES_IN_MS

    useEffect(() => {
        if (!seekBarRef?.current) {
            return
        }

        const handleMouseMove = (e: MouseEvent): void => {
            const rect = ref.current?.getBoundingClientRect()
            if (!rect) {
                return
            }

            const relativeX = e.clientX - rect.x
            const newPercentage = Math.max(Math.min(relativeX / rect.width, 1), 0)
            setPercentage(newPercentage)
        }

        const seekBar = seekBarRef.current
        seekBar.addEventListener('mousemove', handleMouseMove)
        return () => seekBar.removeEventListener('mousemove', handleMouseMove)
    }, [seekBarRef])

    return (
        <div className="PlayerSeekBarPreview" ref={ref}>
            <div
                className="PlayerSeekBarPreview__tooltip"
                // eslint-disable-next-line react/forbid-dom-props
                style={{
                    transform: `translateX(${percentage * 100}%)`,
                }}
            >
                <div
                    className={cn(
                        'PlayerSeekBarPreview__tooltip__content',
                        canShowPreview && 'PlayerSeekBarPreview__tooltip__content--with-preview'
                    )}
                >
                    {canShowPreview && (
                        <PlayerSeekbarPreviewFrame
                            minMs={minMs}
                            maxMs={maxMs}
                            percentage={percentage}
                            isVisible={isHovering}
                        />
                    )}
                    <div className="text-center p-2">{content}</div>
                </div>
            </div>
        </div>
    )
})