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.

10.9 KB
Raw Blame
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
import React, { MutableRefObject, memo, useEffect, useMemo } from 'react'
import useResizeObserver from 'use-resize-observer'

import { IconComment } from '@posthog/icons'

import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { LazyRichContentPreview, LazyTextContent } from 'lib/components/RichContentEditor/LazyRichContent'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { autoCaptureEventToDescription } from 'lib/utils/events'
import { getPrimaryPropertyForEvent } from 'lib/utils/events'
import {
    InspectorListItem,
    InspectorListItemComment,
    InspectorListItemEvent,
    InspectorListItemExperimentVariant,
    InspectorListItemMetricEvent,
    InspectorListItemNotebookComment,
} from 'scenes/session-recordings/player/inspector/playerInspectorLogic'
import { isSingleEmoji } from 'scenes/session-recordings/utils'

import { primaryEventPropertiesModel } from '~/models/primaryEventPropertiesModel'

import { SeekbarGlyph, resolveOverlappingGlyphs } from './seekbarTickOffsets'
import { UserActivity } from './UserActivity'

// keep in sync with --emoji-width / --comment-width in Seekbar.scss
const EMOJI_TICK_WIDTH_PX = 16
const COMMENT_TICK_WIDTH_PX = 12

function isEventItem(x: InspectorListItem): x is InspectorListItemEvent {
    return 'data' in x && !!x.data && 'event' in x.data
}

function isExperimentVariantItem(x: InspectorListItem): x is InspectorListItemExperimentVariant {
    return x.type === 'experiment-variant'
}

function isMetricEventItem(x: InspectorListItem): x is InspectorListItemMetricEvent {
    return x.type === 'metric-event'
}

function isNotebookComment(x: InspectorListItem): x is InspectorListItemNotebookComment {
    if (x.type !== 'comment') {
        return false
    }
    return 'source' in x && x.source === 'notebook'
}

function isComment(x: InspectorListItem): x is InspectorListItemComment {
    if (x.type !== 'comment') {
        return false
    }
    return 'source' in x && x.source === 'comment'
}

function isAnyComment(x: InspectorListItem): x is InspectorListItemComment | InspectorListItemNotebookComment {
    return x.type === 'comment'
}

function isEmojiComment(x: InspectorListItem): x is InspectorListItemComment {
    return isComment(x) && !!x.data.item_context?.is_emoji && !!x.data.content && isSingleEmoji(x.data.content)
}

function PlayerSeekbarTick({
    item,
    endTimeMs,
    zIndex,
    onClick,
    primaryProperties,
    offsetPx = 0,
}: {
    item:
        | InspectorListItemComment
        | InspectorListItemNotebookComment
        | InspectorListItemEvent
        | InspectorListItemExperimentVariant
        | InspectorListItemMetricEvent
    endTimeMs: number
    zIndex: number
    onClick: (e: React.MouseEvent) => void
    primaryProperties: Record<string, string>
    offsetPx?: number
}): JSX.Element | null {
    const position = (item.timeInRecording / endTimeMs) * 100

    if (position < 0 || position > 100) {
        return null
    }

    const primaryPropertyKey = isEventItem(item) ? getPrimaryPropertyForEvent(item.data.event, primaryProperties) : null
    const primaryValue = primaryPropertyKey && isEventItem(item) ? item.data.properties?.[primaryPropertyKey] : null

    return (
        <div
            className={clsx('PlayerSeekbarTick', item.highlightColor && `PlayerSeekbarTick--${item.highlightColor}`)}
            // eslint-disable-next-line react/forbid-dom-props
            style={{
                left: offsetPx ? `calc(${position}% + ${offsetPx}px)` : `${position}%`,
                zIndex: zIndex,
            }}
            onClick={onClick}
        >
            <Tooltip
                placement="top-start"
                delayMs={10}
                onOpen={() => {
                    posthog.capture('player seekbar tick tooltip shown', {
                        item_type: item.type,
                        ...(isEventItem(item) && { event: item.data.event }),
                    })
                }}
                title={
                    isExperimentVariantItem(item) ? (
                        <>
                            Saw variant "{item.data.variant}" of {item.data.experimentName}
                        </>
                    ) : isMetricEventItem(item) ? (
                        <>
                            Fired a {item.data.metricName} event ({item.data.experimentName})
                        </>
                    ) : isEventItem(item) ? (
                        <>
                            {item.data.event === '$autocapture' ? (
                                <>{autoCaptureEventToDescription(item.data)}</>
                            ) : (
                                <PropertyKeyInfo
                                    className="font-medium"
                                    disableIcon
                                    disablePopover
                                    ellipsis={true}
                                    type={TaxonomicFilterGroupType.Events}
                                    value={item.data.event}
                                />
                            )}
                            {primaryValue != null && primaryValue !== '' ? (
                                <span className="ml-2 opacity-75">{String(primaryValue)}</span>
                            ) : null}
                        </>
                    ) : isNotebookComment(item) ? (
                        item.data.comment
                    ) : (
                        <div className="flex flex-col px-4 py-2 gap-y-2">
                            {item.data.rich_content ? (
                                <LazyRichContentPreview content={item.data.rich_content} className="rounded-none" />
                            ) : (
                                <LazyTextContent
                                    text={item.data.content ?? ''}
                                    data-attr="PlayerSeekbarTicks--text-content"
                                />
                            )}
                            <ProfilePicture user={item.data.created_by} showName size="md" type="person" />{' '}
                        </div>
                    )
                }
            >
                {isEmojiComment(item) ? (
                    <div className="PlayerSeekbarTick__emoji">{item.data.content}</div>
                ) : isAnyComment(item) ? (
                    <div className="PlayerSeekbarTick__comment">
                        <IconComment />
                    </div>
                ) : (
                    <div className="PlayerSeekbarTick__line" />
                )}
            </Tooltip>
        </div>
    )
}

const MemoisedPlayerSeekbarTicks = memo(
    function PlayerSeekbarTicksInner({
        seekbarItems,
        endTimeMs,
        seekToTime,
        hoverRef,
        primaryProperties,
        ticksRef,
        containerWidth,
    }: {
        seekbarItems: (
            | InspectorListItemEvent
            | InspectorListItemComment
            | InspectorListItemNotebookComment
            | InspectorListItemExperimentVariant
            | InspectorListItemMetricEvent
        )[]
        endTimeMs: number
        seekToTime: (timeInMilliseconds: number) => void
        hoverRef: MutableRefObject<HTMLDivElement | null>
        primaryProperties: Record<string, string>
        ticksRef: (node: HTMLDivElement | null) => void
        containerWidth: number
    }): JSX.Element {
        const glyphOffsets = useMemo(() => {
            const glyphs: SeekbarGlyph[] = []
            seekbarItems.forEach((item, index) => {
                if (!isAnyComment(item)) {
                    return
                }
                const position = (item.timeInRecording / endTimeMs) * 100
                if (position < 0 || position > 100) {
                    return
                }
                glyphs.push({
                    index,
                    position,
                    widthPx: isEmojiComment(item) ? EMOJI_TICK_WIDTH_PX : COMMENT_TICK_WIDTH_PX,
                })
            })
            return resolveOverlappingGlyphs(glyphs, containerWidth)
        }, [seekbarItems, endTimeMs, containerWidth])

        return (
            <div className="PlayerSeekbarTicks" ref={ticksRef}>
                <UserActivity hoverRef={hoverRef} />
                {seekbarItems.map((item, i) => {
                    return (
                        <PlayerSeekbarTick
                            key={item.data.id}
                            item={item}
                            endTimeMs={endTimeMs}
                            zIndex={i + (item.highlightColor ? 1000 : 0)}
                            onClick={(e) => {
                                e.stopPropagation()
                                seekToTime(item.timeInRecording)
                            }}
                            primaryProperties={primaryProperties}
                            offsetPx={glyphOffsets.get(i)}
                        />
                    )
                })}
            </div>
        )
    },
    (prev, next) => {
        const seekbarItemsAreEqual =
            prev.seekbarItems.length === next.seekbarItems.length &&
            prev.seekbarItems.every((item, i) => item.data.id === next.seekbarItems[i].data.id)

        return (
            seekbarItemsAreEqual &&
            prev.endTimeMs === next.endTimeMs &&
            prev.seekToTime === next.seekToTime &&
            prev.primaryProperties === next.primaryProperties &&
            prev.containerWidth === next.containerWidth
        )
    }
)

export function PlayerSeekbarTicks({
    seekbarItems,
    endTimeMs,
    seekToTime,
    hoverRef,
}: {
    seekbarItems: (
        | InspectorListItemEvent
        | InspectorListItemComment
        | InspectorListItemNotebookComment
        | InspectorListItemExperimentVariant
        | InspectorListItemMetricEvent
    )[]
    endTimeMs: number
    seekToTime: (timeInMilliseconds: number) => void
    hoverRef: MutableRefObject<HTMLDivElement | null>
}): JSX.Element {
    const { primaryProperties } = useValues(primaryEventPropertiesModel)
    const { ensureLoadedForEvents } = useActions(primaryEventPropertiesModel)
    const { ref: ticksRef, width: containerWidth } = useResizeObserver<HTMLDivElement>({})
    const distinctEventNames = useMemo(
        () => Array.from(new Set(seekbarItems.filter(isEventItem).map((i) => i.data.event))),
        [seekbarItems]
    )
    useEffect(() => {
        ensureLoadedForEvents(distinctEventNames)
    }, [distinctEventNames, ensureLoadedForEvents])

    return (
        <MemoisedPlayerSeekbarTicks
            seekbarItems={seekbarItems}
            endTimeMs={endTimeMs}
            seekToTime={seekToTime}
            hoverRef={hoverRef}
            primaryProperties={primaryProperties}
            ticksRef={ticksRef}
            containerWidth={containerWidth ?? 0}
        />
    )
}