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.

4.7 KB
Raw Blame
import type { ReactNode } from 'react'

// Pure column-layout helpers used by LemonTable internals. Kept separate from
// columnUtils.tsx, whose column factories render TZLabel/ProfilePicture and would
// otherwise drag that graph (including eventUsageLogic and the taxonomy JSON) into
// every bundle that renders a LemonTable.
import { LemonTableColumn } from './types'

export const DEFAULT_COLUMN_WIDTH = 120

interface PinnedColumnInfo {
    isSticky: boolean
    leftPosition: number
}

/**
 * Get the pinned column info
 * @param columnKey - The key of the column
 * @param stickyColumns - The pinned columns
 * @param stickyColumnWidths - The widths of the pinned columns
 * @param allColumns - All the columns
 * @returns The pinned column info
 * example:
 * getStickyColumnInfo(
 *     'source',
 *     ['source', 'campaign'],
 *     [100, 200],
 *     [
 *         { key: 'campaign', dataIndex: 'campaign' },
 *         { key: 'source', dataIndex: 'source' },
 *     ]
 * ) -> {
 *     isSticky: true,
 *     leftPosition: 100
 * }
 */
export function getStickyColumnInfo<T extends Record<string, any>>(
    columnKey: string,
    stickyColumns: string[] | undefined,
    stickyColumnWidths: number[] | undefined,
    allColumns: LemonTableColumn<T, any>[] | undefined
): PinnedColumnInfo {
    if (!stickyColumns?.length) {
        return { isSticky: false, leftPosition: 0 }
    }

    const isSticky = stickyColumns.includes(columnKey)

    if (!isSticky || !allColumns) {
        return { isSticky, leftPosition: 0 }
    }

    const columnPositionMap = new Map<string, number>()
    allColumns.forEach((col, index) => {
        const key = col.key ?? col.dataIndex
        if (key) {
            columnPositionMap.set(key, index)
        }
    })

    const columnIndex = columnPositionMap.get(columnKey) ?? -1

    // Calculate left position for pinned column
    let leftPosition = 0
    if (stickyColumnWidths) {
        for (let i = 0; i < stickyColumns.length; i++) {
            const key = stickyColumns[i]
            const keyIndex = columnPositionMap.get(key) ?? -1
            if (keyIndex >= 0 && keyIndex < columnIndex) {
                const width = stickyColumnWidths[i]
                leftPosition += width && width > 0 ? width : DEFAULT_COLUMN_WIDTH
            }
        }
    }

    return { isSticky, leftPosition }
}

/**
 * The maximum width for the cells of a resizable column. A `<col>` width is only a hint: when the
 * table sizes itself intrinsically, the widest cell can make the column wider than that hint. The
 * cap holds the column at the width a person drags it to, and the content crops instead.
 */
export function getColumnWidthCap<T extends Record<string, any>>(
    column: LemonTableColumn<T, any>
): string | number | undefined {
    return column.resizable && column.width ? column.width : undefined
}

/**
 * Determine the column's key, using `dataIndex` as fallback.
 * If `obligationReason` is specified, will throw an error if the key can't be determined.
 */
export function determineColumnKey(column: LemonTableColumn<any, any>, obligationReason: string): string
export function determineColumnKey(column: LemonTableColumn<any, any>, obligationReason?: undefined): string | null
export function determineColumnKey(column: LemonTableColumn<any, any>, obligationReason?: string): string | null {
    const columnKey = column.key || column.dataIndex
    if (obligationReason && columnKey == null) {
        // == is intentional to catch undefined too
        throw new Error(`Column \`key\` or \`dataIndex\` must be defined for ${obligationReason}`)
    }
    return columnKey
}

export interface VirtualColumnWindow {
    startIndex: number
    endIndex: number
    paddingLeft: number
    paddingRight: number
    stickyFirstColumn: boolean
}

export function virtualColumnIndex(index: number, window: VirtualColumnWindow): number {
    return window.stickyFirstColumn && index === 0 ? 0 : window.startIndex + index - Number(window.stickyFirstColumn)
}

export function windowHeaderRow(
    row: { title: ReactNode; colSpan: number }[],
    window?: VirtualColumnWindow
): { title: ReactNode; colSpan: number; columnIndex: number }[] {
    let columnIndex = 0
    return row.flatMap((cell) => {
        const start = columnIndex
        columnIndex += cell.colSpan
        if (!window) {
            return [{ ...cell, columnIndex: start }]
        }
        const visibleStart = Math.max(start, window.startIndex)
        const visibleEnd = Math.min(columnIndex, window.endIndex)
        return [
            ...(window.stickyFirstColumn && start === 0 ? [{ ...cell, colSpan: 1, columnIndex: 0 }] : []),
            ...(visibleEnd > visibleStart
                ? [{ ...cell, colSpan: visibleEnd - visibleStart, columnIndex: visibleStart }]
                : []),
        ]
    })
}