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.6 KB
Raw Blame
import { CSSProperties, ReactNode, useMemo, useState } from 'react'
import { List } from 'react-window'

import { Spinner, Tooltip } from '@posthog/lemon-ui'

import { AutoSizer } from 'lib/components/AutoSizer'
import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'
import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'
import { cn } from 'lib/utils/css-classes'

import { TableCell } from './components/TableColumns/TableCell'
import { TableHeaderCell } from './components/TableColumns/TableHeaderCell'
import { ResizableColumns, useResizableColumns } from './components/TableColumns/useResizableColumns'

// Config-driven virtualized table: owns react-window virtualization, client-side sort, and the
// header/row layout; callers pass column definitions + data. Extracted from TraceCompareTable so
// the compare view and the operations view share one implementation. The column-def contract
// mirrors logs' `VirtualizedTableColumn` (products/logs/frontend/components/VirtualizedLogsList);
// the two are intended to converge into a single shared lib/ primitive later.

const ROW_HEIGHT = 44
const HEADER_HEIGHT = 32
/** The table frame's `border` class, on the top and the bottom. */
const FRAME_BORDER_WIDTH = 1

/** Height of a table that shows the header and `rowCount` rows with no vertical scroll. */
export function virtualizedTableHeight(rowCount: number): number {
    return HEADER_HEIGHT + rowCount * ROW_HEIGHT + 2 * FRAME_BORDER_WIDTH
}

export type VirtualizedSortOrder = 1 | -1

export interface VirtualizedSort {
    columnKey: string
    order: VirtualizedSortOrder
}

export interface VirtualizedTableColumn<T> {
    key: string
    title: ReactNode
    /** Default column width in px, before anyone resizes it. */
    width: number
    /** Takes the space left over in the viewport, up to a cap. At most one column per table. */
    grow?: boolean
    align?: 'right'
    /** Header tooltip. */
    tooltip?: string
    render: (record: T) => ReactNode
    /** Provide to make the column sortable. */
    sorter?: (a: T, b: T) => number
}

function HeaderCell({
    column,
    width,
    columns,
    sortKey,
    sortOrder,
    onSort,
}: {
    column: VirtualizedTableColumn<any>
    width: number
    columns: ResizableColumns
    sortKey: string | null
    sortOrder: VirtualizedSortOrder
    onSort: (key: string) => void
}): JSX.Element {
    const label = column.tooltip ? <Tooltip title={column.tooltip}>{column.title}</Tooltip> : column.title
    const resize = columns.resizeHandleProps(column.key, typeof column.title === 'string' ? column.title : column.key)
    const active = sortKey === column.key
    return (
        <TableHeaderCell width={width} align={column.align} resize={resize}>
            {column.sorter ? (
                <button
                    type="button"
                    className={cn(
                        'flex items-center cursor-pointer hover:text-default',
                        column.align === 'right' && 'ml-auto',
                        active && 'text-default'
                    )}
                    onClick={() => onSort(column.key)}
                    data-attr={`virtualized-table-sort-${column.key}`}
                >
                    <span>{label}</span>
                    <SortingIndicator order={active ? sortOrder : null} />
                </button>
            ) : (
                label
            )}
        </TableHeaderCell>
    )
}

// The generic T is erased to `any` at the react-window row boundary — type safety lives at the
// column-definition site (`columns: VirtualizedTableColumn<T>[]`), not inside the row renderer.
interface VirtualizedRowProps {
    columns: VirtualizedTableColumn<any>[]
    widths: Record<string, number>
    dataSource: any[]
    rowKey: (record: any) => string
    onRowClick?: (record: any) => void
    rowClassName?: (record: any) => string | undefined
}

function VirtualizedRow({
    ariaAttributes,
    index,
    style,
    columns,
    widths,
    dataSource,
    rowKey,
    onRowClick,
    rowClassName,
}: {
    ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
    index: number
    style: CSSProperties
} & VirtualizedRowProps): JSX.Element {
    const record = dataSource[index]
    return (
        <div
            {...ariaAttributes}
            // eslint-disable-next-line react/forbid-dom-props
            style={style}
            data-index={index}
            data-row-key={rowKey(record)}
        >
            <div
                className={cn(
                    'flex items-center border-b border-border hover:bg-surface-primary-hover',
                    onRowClick && 'cursor-pointer',
                    rowClassName?.(record)
                )}
                // eslint-disable-next-line react/forbid-dom-props
                style={{ height: ROW_HEIGHT }}
                onClick={onRowClick ? () => onRowClick(record) : undefined}
                onKeyDown={
                    onRowClick
                        ? (e) => {
                              if (e.key === 'Enter' || e.key === ' ') {
                                  e.preventDefault()
                                  onRowClick(record)
                              }
                          }
                        : undefined
                }
                role={onRowClick ? 'button' : undefined}
                tabIndex={onRowClick ? 0 : undefined}
            >
                {columns.map((column) => (
                    <TableCell key={column.key} width={widths[column.key]} align={column.align}>
                        {column.render(record)}
                    </TableCell>
                ))}
            </div>
        </div>
    )
}

export interface VirtualizedTableProps<T> {
    /** Identifies the table's stored column widths. Pinned: renaming resets everyone's widths. */
    tableKey: string
    columns: VirtualizedTableColumn<T>[]
    dataSource: T[]
    loading: boolean
    rowKey: (record: T) => string
    onRowClick?: (record: T) => void
    /** Extra classes for one row, such as a highlight. */
    rowClassName?: (record: T) => string | undefined
    defaultSort?: VirtualizedSort
    /**
     * Controlled sort, which replaces `defaultSort` and the table's own sort state. A caller that sorts its
     * full list before it cuts the list down owns the sort, because the table sees only the rows it gets.
     */
    sort?: VirtualizedSort | null
    onSortChange?: (sort: VirtualizedSort | null) => void
    emptyLabel?: string
    'data-attr'?: string
}

export function VirtualizedTable<T>({
    tableKey,
    columns,
    dataSource,
    loading,
    rowKey,
    onRowClick,
    rowClassName,
    defaultSort,
    sort: controlledSort,
    onSortChange,
    emptyLabel = 'No rows',
    'data-attr': dataAttr,
}: VirtualizedTableProps<T>): JSX.Element {
    const [internalSort, setInternalSort] = useState<VirtualizedSort | null>(defaultSort ?? null)
    const sort = controlledSort === undefined ? internalSort : controlledSort
    const sortKey = sort?.columnKey ?? null
    const sortOrder = sort?.order ?? -1
    const resizableColumns = useResizableColumns(tableKey, columns)

    const rows = useMemo(() => {
        const sorter = columns.find((column) => column.key === sortKey)?.sorter
        if (!sorter) {
            return dataSource
        }
        return [...dataSource].sort((a, b) => sorter(a, b) * sortOrder)
    }, [dataSource, columns, sortKey, sortOrder])

    const onSort = (key: string): void => {
        const next: VirtualizedSort = { columnKey: key, order: key === sortKey && sortOrder === -1 ? 1 : -1 }
        if (controlledSort === undefined) {
            setInternalSort(next)
        }
        onSortChange?.(next)
    }

    if (rows.length === 0) {
        return (
            <div className="flex items-center justify-center p-8 text-muted border rounded bg-bg-light">
                {loading ? <Spinner className="text-2xl" /> : emptyLabel}
            </div>
        )
    }

    return (
        <div className="flex flex-col flex-1 min-h-0 bg-bg-light border rounded overflow-hidden" data-attr={dataAttr}>
            <AutoSizer
                renderProp={({ width, height }: SizeProps) => {
                    if (!width || !height) {
                        return null
                    }
                    const { widths, totalWidth } = resizableColumns.resolveWidths(width)
                    const rowWidth = Math.max(width, totalWidth)
                    return (
                        // The viewport is fixed to the available box; inner content can be wider
                        // (totalWidth) so columns scroll horizontally and rows align with the header.
                        // eslint-disable-next-line react/forbid-dom-props
                        <div className="overflow-x-auto" style={{ width, height }}>
                            {/* eslint-disable-next-line react/forbid-dom-props */}
                            <div style={{ width: rowWidth }}>
                                <div
                                    className="flex items-center border-b border-border bg-surface-secondary font-medium text-muted"
                                    // eslint-disable-next-line react/forbid-dom-props
                                    style={{ height: HEADER_HEIGHT }}
                                >
                                    {columns.map((column) => (
                                        <HeaderCell
                                            key={column.key}
                                            column={column}
                                            width={widths[column.key]}
                                            columns={resizableColumns}
                                            sortKey={sortKey}
                                            sortOrder={sortOrder}
                                            onSort={onSort}
                                        />
                                    ))}
                                </div>
                                <List<VirtualizedRowProps>
                                    style={{ height: height - HEADER_HEIGHT, width: rowWidth }}
                                    overscanCount={10}
                                    rowCount={rows.length}
                                    rowHeight={ROW_HEIGHT}
                                    rowComponent={VirtualizedRow}
                                    rowProps={{ columns, widths, dataSource: rows, rowKey, onRowClick, rowClassName }}
                                />
                            </div>
                        </div>
                    )
                }}
            />
        </div>
    )
}