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.

8.7 KB
Raw Blame
import './PlayerMeta.scss'

import clsx from 'clsx'
import { useActions, useValues } from 'kea'

import { LemonSelect, LemonSelectOption, Link } from '@posthog/lemon-ui'

import { Logo } from 'lib/brand'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { isObject } from 'lib/utils/guards'
import { DraggableToNotebook } from 'scenes/notebooks/AddToNotebook/DraggableToNotebook'
import { IconWindow } from 'scenes/session-recordings/player/icons'
import {
    InsertInNotebookPlaylistButton,
    MenuActions,
    PinToPlaylistButton,
} from 'scenes/session-recordings/player/player-meta/PlayerMetaLinks'
import {
    SessionRecordingPlayerMode,
    sessionRecordingPlayerLogic,
} from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { PlayerShareMenu } from 'scenes/session-recordings/player/share/PlayerShareMenu'
import { urls } from 'scenes/urls'

import { getCurrentExporterData } from '~/exporter/exporterViewLogic'

import { PlayerInspectorButton } from './PlayerInspectorButton'
import { PlayerMetaExperimentTags } from './PlayerMetaExperimentTags'
import { playerMetaLogic } from './playerMetaLogic'
import { InspectDOM, SetPlaybackSpeed, usePlayerChromeMenuItems } from './PlayerMetaTopSettings'
import { PlayerPersonMeta } from './PlayerPersonMeta'

export function parseUrl(lastUrl: unknown): { urlToUse: string | undefined; isValidUrl: boolean; isWebUrl: boolean } {
    let urlToUse: string | undefined = typeof lastUrl === 'string' ? lastUrl : undefined
    if (isObject(lastUrl)) {
        // regression protection, we saw a user whose site was sometimes sending the string-ified location object
        // this is a best-effort attempt to show the href in that case
        // we've also seen lastUrl arrive as the empty object
        const maybeHref = lastUrl?.href
        if (typeof maybeHref === 'string') {
            urlToUse = maybeHref
        }
    }

    if (!urlToUse || urlToUse.trim() === '') {
        return { urlToUse: undefined, isValidUrl: false, isWebUrl: false }
    }

    let isValidUrl = false
    let isWebUrl = false
    try {
        const parsed = new URL(urlToUse)
        isValidUrl = true
        // Only http/https can be opened from an https page. A file:// or other scheme
        // would render a dead link that ejects the user onto a 404, so treat it as plain text.
        isWebUrl = parsed.protocol === 'http:' || parsed.protocol === 'https:'
    } catch {
        // no valid url
    }

    return { urlToUse, isValidUrl, isWebUrl }
}

function URLOrScreen({ url }: { url: unknown }): JSX.Element | null {
    const { urlToUse, isWebUrl } = parseUrl(url)

    if (!urlToUse) {
        return null
    }

    return (
        <span className="flex flex-row items-center gap-x-1 truncate">
            <span className="flex flex-row items-center gap-x-1 truncate">
                <span className="flex items-center">
                    <CopyToClipboardInline
                        description={urlToUse}
                        explicitValue={urlToUse}
                        iconStyle={{ color: 'var(--color-text-secondary)' }}
                        selectable={true}
                        data-attr="player-meta-copy-url"
                    />
                </span>
                {isWebUrl ? (
                    <Tooltip title={`Click to open url: ${urlToUse}`}>
                        <Link data-attr="player-meta-open-url" to={urlToUse} target="_blank" className="truncate">
                            {urlToUse}
                        </Link>
                    </Tooltip>
                ) : (
                    <span className="truncate">{urlToUse}</span>
                )}
            </span>
        </span>
    )
}

export type PlayerMetaBreakpoints = 'small' | 'normal'

function PlayerMetaControls({ size }: { size: PlayerMetaBreakpoints }): JSX.Element {
    const {
        sessionRecordingId,
        logicProps: { withSidebar, mode },
    } = useValues(sessionRecordingPlayerLogic)
    const chromeItems = usePlayerChromeMenuItems()
    const isSharing = mode === SessionRecordingPlayerMode.Sharing

    return (
        <div className="flex items-center gap-0.5">
            {!isSharing && sessionRecordingId && <MenuActions size={size} extraItems={chromeItems} />}
            <SetPlaybackSpeed />
            {withSidebar && <InspectDOM />}
            {!isSharing && (
                <>
                    <InsertInNotebookPlaylistButton size={size} />
                    <PinToPlaylistButton />
                    <PlayerShareMenu />
                </>
            )}
            {withSidebar && <PlayerInspectorButton />}
            {!withSidebar && <PlayerPersonMeta />}
        </div>
    )
}

export function PlayerMeta(): JSX.Element {
    const { logicProps, isFullScreen } = useValues(sessionRecordingPlayerLogic)

    const { windowIds, trackedWindow, lastPageviewEvent, currentURL, currentWindowIndex, loading } = useValues(
        playerMetaLogic(logicProps)
    )

    const { setTrackedWindow } = useActions(playerMetaLogic(logicProps))

    const { ref, size } = useResizeBreakpoints({
        0: 'small',
        600: 'normal',
    })

    const mode = logicProps.mode ?? SessionRecordingPlayerMode.Standard
    const whitelabel = getCurrentExporterData()?.whitelabel ?? false

    if (mode === SessionRecordingPlayerMode.Sharing) {
        if (whitelabel) {
            return <></>
        }
        return (
            <div className="PlayerMeta">
                <div className="flex justify-between items-center m-2">
                    {!whitelabel ? (
                        <Tooltip title="Powered by PostHog" placement="right">
                            <Link to="https://posthog.com" className="flex items-center" target="blank">
                                <Logo size="md" />
                            </Link>
                        </Tooltip>
                    ) : null}
                </div>
            </div>
        )
    }

    const windowOptions: LemonSelectOption<number | null>[] = [
        {
            label: <IconWindow value={currentWindowIndex} className="text-secondary" />,
            value: null,
            labelInMenu: <>Follow the user</>,
        },
    ]
    windowIds.forEach((windowId) => {
        windowOptions.push({
            label: <IconWindow value={windowId} className="text-secondary" />,
            labelInMenu: (
                <div className="flex flex-row gap-x-1 space-between items-center">
                    Follow window:&nbsp;
                    <IconWindow value={windowId} className="text-secondary" />
                </div>
            ),
            value: windowId,
        })
    })

    return (
        <DraggableToNotebook href={urls.replaySingle(logicProps.sessionRecordingId)} onlyWithModifierKey>
            <div
                ref={ref}
                className={clsx('PlayerMeta relative', {
                    'PlayerMeta--fullscreen': isFullScreen,
                })}
            >
                <div className="flex flex-row items-center justify-between gap-x-1 whitespace-nowrap overflow-hidden px-1 py-0.5 text-xs">
                    {loading ? (
                        <LemonSkeleton className="w-1/3 h-4 my-1" />
                    ) : (
                        <>
                            <LemonSelect
                                size="xsmall"
                                options={windowOptions}
                                value={trackedWindow}
                                disabledReason={windowIds.length <= 1 ? "There's only one window" : undefined}
                                onSelect={(value) => setTrackedWindow(value)}
                                data-attr="player-meta-window-select"
                            />

                            <URLOrScreen url={currentURL} />
                            {lastPageviewEvent?.properties?.['$screen_name'] && (
                                <span className="flex flex-row items-center gap-x-1 truncate">
                                    <span>·</span>
                                    <span className="flex flex-row items-center gap-x-1 truncate">
                                        {lastPageviewEvent?.properties['$screen_name']}
                                    </span>
                                </span>
                            )}
                        </>
                    )}
                    <PlayerMetaExperimentTags />
                    <div className={clsx('flex-1', size === 'small' ? 'min-w-[1rem]' : 'min-w-[5rem]')} />
                    <PlayerMetaControls size={size} />
                </div>
            </div>
        </DraggableToNotebook>
    )
}