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.

9.5 KB
Raw Blame
// Shared scope bar: the in-page trail (list › entity) on the left, dismissible filter chips on
// the right, and the shared date scope (engineeringAnalyticsFiltersLogic) so a window picked on one page
// carries to the next. The run-scope control lives here too, but pages dock it on their scope panel.

import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { Fragment, ReactNode, useState } from 'react'

import { IconChevronDown, IconX } from '@posthog/icons'
import { LemonButton, LemonDropdown, LemonInput, LemonSegmentedButton, Link, Spinner } from '@posthog/lemon-ui'

import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { cn } from 'lib/utils/css-classes'
import { dateMapping } from 'lib/utils/dateFilters'
import { urls } from 'scenes/urls'

import { DateMappingOption } from '~/types'

import { withScope } from '../lib/scope'
import {
    RUN_SCOPE_OPTIONS,
    SHARED_DEFAULT_DATE_FROM,
    engineeringAnalyticsFiltersLogic,
} from '../scenes/engineeringAnalyticsFiltersLogic'
import { workflowSwitcherLogic } from '../scenes/workflowSwitcherLogic'

// The endpoints require a window start (no "all time"), so offer relative windows and Custom only.
export const SCOPE_DATE_OPTIONS = dateMapping.filter(({ key }) =>
    [
        'Custom',
        'Today',
        'Last 24 hours',
        'Last 7 days',
        'Last 14 days',
        'Last 30 days',
        'Last 90 days',
        'Last 180 days',
    ].includes(key)
)

// The delivery reads cap a window at a year, so they offer only presets inside it and no custom range.
export const DELIVERY_DATE_OPTIONS = dateMapping.filter(({ key }) =>
    ['Last 7 days', 'Last 14 days', 'Last 30 days', 'Last 90 days', 'Last 180 days', 'This year'].includes(key)
)

export interface ScopeCrumb {
    label: string
    to?: string
    /** Custom chip rendering (e.g. the workflow switcher); overrides `to`. `label` stays the key. */
    node?: ReactNode
}

export interface LensChip {
    label: string
    /** Where dismissing the chip navigates. */
    to: string
}

const CHIP_CLASS =
    'inline-flex items-center gap-1.5 rounded border border-primary bg-surface-primary px-2.5 py-1 text-xs text-secondary'

/** Workflow crumb that doubles as a switcher: a searchable dropdown of the repo's workflows, loaded
 *  lazily on first open, navigating to the picked workflow's page. */
export function WorkflowScopeChip({
    repoOwner,
    repoName,
    workflowName,
    sourceId,
}: {
    repoOwner: string
    repoName: string
    workflowName: string
    sourceId: string | null
}): JSX.Element {
    const logic = workflowSwitcherLogic({ repoOwner, repoName, sourceId })
    const { workflowNames, workflowNamesLoading } = useValues(logic)
    const { ensureWorkflowsLoaded } = useActions(logic)
    const [visible, setVisible] = useState(false)
    const [search, setSearch] = useState('')

    const searchTerm = search.trim().toLowerCase()
    const options = (workflowNames ?? []).filter((name) => !searchTerm || name.toLowerCase().includes(searchTerm))

    const selectWorkflow = (name: string): void => {
        setVisible(false)
        setSearch('')
        if (name !== workflowName) {
            router.actions.push(
                withScope(
                    urls.engineeringAnalyticsWorkflowRuns(repoOwner, repoName, name),
                    router.values.currentLocation.searchParams,
                    sourceId
                )
            )
        }
    }

    return (
        <LemonDropdown
            visible={visible}
            onVisibilityChange={(next) => {
                setVisible(next)
                if (next) {
                    ensureWorkflowsLoaded()
                } else {
                    setSearch('')
                }
            }}
            closeOnClickInside={false}
            overlay={
                <div className="flex w-72 flex-col gap-1 p-1">
                    <LemonInput
                        type="search"
                        size="small"
                        placeholder="Search workflows…"
                        value={search}
                        onChange={setSearch}
                        autoFocus
                        data-attr="engineering-analytics-workflow-switcher-search"
                    />
                    <div className="max-h-80 overflow-y-auto">
                        {workflowNamesLoading ? (
                            <div className="flex items-center gap-2 px-2 py-1.5 text-xs text-secondary">
                                <Spinner /> Loading workflows…
                            </div>
                        ) : options.length > 0 ? (
                            options.map((name) => (
                                <LemonButton
                                    key={name}
                                    size="small"
                                    fullWidth
                                    active={name === workflowName}
                                    onClick={() => selectWorkflow(name)}
                                >
                                    <span className="truncate">{name}</span>
                                </LemonButton>
                            ))
                        ) : (
                            <div className="px-2 py-1.5 text-xs text-secondary">
                                {searchTerm ? 'No workflows match.' : 'No workflows in the window.'}
                            </div>
                        )}
                    </div>
                </div>
            }
        >
            <LemonButton
                size="small"
                type="secondary"
                sideIcon={<IconChevronDown />}
                title="Switch to another workflow in this repository"
                data-attr="engineering-analytics-workflow-switcher"
            >
                {workflowName}
            </LemonButton>
        </LemonDropdown>
    )
}

const RUN_SCOPE_SEGMENTS = RUN_SCOPE_OPTIONS.map((option) => ({
    ...option,
    'data-attr': `engineering-analytics-run-scope-${option.value}`,
}))

export function RunScopeControl(): JSX.Element {
    const { runScope } = useValues(engineeringAnalyticsFiltersLogic)
    const { setRunScope } = useActions(engineeringAnalyticsFiltersLogic)
    return (
        <LemonSegmentedButton
            size="small"
            value={runScope}
            onChange={(value) => {
                // Re-picking the active group would reload every surface for no change.
                if (value !== runScope) {
                    setRunScope(value)
                }
            }}
            options={RUN_SCOPE_SEGMENTS}
        />
    )
}

/** The shared window picker, wired to the cross-page date scope. Standalone so pages can place it outside
 *  the scope bar (the hub docks it in the repo header). */
export function ScopeDateFilter({
    dateOptions = SCOPE_DATE_OPTIONS,
}: {
    /** Custom and rolling ranges show only when the options include Custom. */
    dateOptions?: DateMappingOption[]
}): JSX.Element {
    const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
    const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
    const allowsCustomRange = dateOptions.some(({ key }) => key === 'Custom')
    return (
        <DateFilter
            dateFrom={dateFrom}
            dateTo={dateTo}
            onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
            dateOptions={dateOptions}
            showCustomRangeOptions={allowsCustomRange}
            showRollingRangePicker={allowsCustomRange}
            size="small"
        />
    )
}

export function WorkflowScopeControls(): JSX.Element {
    return (
        <>
            <RunScopeControl />
            <ScopeDateFilter />
        </>
    )
}

export function ScopeBar({
    crumbs,
    lensFilter,
    showDate = true,
    extra,
}: {
    /** The trail from the list tab to this page (Workflows › workflow › run). The title names the repository. */
    crumbs: ScopeCrumb[]
    /** The active cross-cutting lens (pr: #N). Dismissing it zooms out to `to`. */
    lensFilter?: LensChip
    showDate?: boolean
    extra?: ReactNode
}): JSX.Element {
    return (
        <div className="flex flex-wrap items-center gap-2">
            {crumbs.map((crumb, index) => (
                <Fragment key={crumb.label}>
                    {index > 0 && <span className="text-xs text-tertiary">›</span>}
                    {crumb.node ? (
                        crumb.node
                    ) : crumb.to ? (
                        <Link to={crumb.to} className="text-[13px] font-medium">
                            {crumb.label}
                        </Link>
                    ) : (
                        <span className="text-[13px] font-semibold">{crumb.label}</span>
                    )}
                </Fragment>
            ))}
            <span className="ml-auto flex flex-wrap items-center gap-2">
                {lensFilter && (
                    <span
                        className={cn(CHIP_CLASS, 'border-accent-highlight-secondary bg-fill-highlight-50')}
                        title="A filter is applied to this page. Remove it to see the whole repo."
                    >
                        <strong className="font-semibold text-primary">{lensFilter.label}</strong>
                        <Link to={lensFilter.to} className="px-0.5 text-tertiary hover:text-primary">
                            <IconX />
                        </Link>
                    </span>
                )}
                {showDate && <ScopeDateFilter />}
                {extra}
            </span>
        </div>
    )
}