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.

7.9 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { useEffect, useMemo, useRef, useState } from 'react'

import { LemonSkeleton } from '@posthog/lemon-ui'

import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { SceneSection } from '~/layout/scenes/components/SceneSection'
import { OrganizationFeatureFlag, OrganizationFeatureFlagRow } from '~/types'

import { BulkCopyFlagsModal, BulkCopyToProjectsButton } from '../BulkCopyFlagsModal'
import { flagSelectionLogic } from '../flagSelectionLogic'
import { confirmFlagActiveToggleInProject, flagToggleKey } from '../updateFlagActiveInProject'
import { CellState, ProjectsGridCell } from './ProjectsGridCell'
import { projectsGridLogic } from './projectsGridLogic'
import { ProjectsGridToolbar } from './ProjectsGridToolbar'

export function cellStateFor(
    flag: OrganizationFeatureFlagRow,
    teamId: number,
    currentTeamId: number,
    accessibleTeamIds: Set<number>,
    siblings: OrganizationFeatureFlag[] | undefined,
    siblingsLoading: boolean
): CellState {
    const siblingForTeam = siblings?.find((s) => s.team_id === teamId)
    if (siblingForTeam) {
        return { kind: 'present', sibling: siblingForTeam }
    }

    // Before siblings load, render the current team's cell directly from the row's representative
    // flag, but only when that representative actually belongs to the current team (eval count
    // unavailable until siblings arrive).
    if (teamId === currentTeamId && flag.team_id === currentTeamId) {
        return {
            kind: 'present',
            sibling: {
                flag_id: flag.id,
                team_id: teamId,
                filters: flag.filters,
                active: flag.active,
                // Not rendered by ProjectsGridCell; the row doesn't carry them to avoid a per-row join.
                created_by: null,
                created_at: '',
            },
        }
    }

    if (siblingsLoading || siblings === undefined) {
        return { kind: 'loading' }
    }
    if (!accessibleTeamIds.has(teamId)) {
        return { kind: 'no-access' }
    }
    return { kind: 'missing' }
}

export function ProjectsGrid(): JSX.Element {
    const {
        flags,
        flagsPageLoading,
        flagsHasMore,
        visibleColumns,
        accessibleTeamIds,
        siblingsByFlagKey,
        siblingsLoadingKeys,
        togglingFlagIds,
    } = useValues(projectsGridLogic)
    const { loadMoreFlags, toggleFlagActive } = useActions(projectsGridLogic)
    const { currentOrganization } = useValues(organizationLogic)
    const { currentTeamId } = useValues(teamLogic)
    const { openBulkCopyModal } = useActions(flagSelectionLogic)

    const sentinelRef = useRef<HTMLDivElement>(null)
    // State (not a ref) so the table re-renders once the toolbar slot mounts and the bar can portal into it
    const [bulkBarTarget, setBulkBarTarget] = useState<HTMLDivElement | null>(null)

    useEffect(() => {
        const el = sentinelRef.current
        if (!el) {
            return
        }
        const io = new IntersectionObserver(
            (entries) => {
                if (entries[0]?.isIntersecting && flagsHasMore && !flagsPageLoading) {
                    loadMoreFlags()
                }
            },
            { rootMargin: '400px' }
        )
        io.observe(el)
        return () => io.disconnect()
    }, [flagsHasMore, flagsPageLoading, loadMoreFlags])

    const teamsById = useMemo(
        () => new Map((currentOrganization?.teams ?? []).map((t) => [t.id, t])),
        [currentOrganization?.teams]
    )

    if (!currentTeamId) {
        return <LemonSkeleton className="h-40" />
    }

    const columnWidth = `${100 / (visibleColumns.length + 1)}%`

    const columns: LemonTableColumns<OrganizationFeatureFlagRow> = [
        {
            title: 'Flag',
            key: 'flag',
            width: columnWidth,
            render: (_, flag) => (
                <LemonTableLink
                    to={urls.project(flag.team_id, urls.featureFlag(flag.id))}
                    title={flag.name || flag.key}
                    description={flag.key}
                />
            ),
        },
        ...visibleColumns.map((teamId) => ({
            title: (
                <span>
                    {teamsById.get(teamId)?.name ?? `Project ${teamId}`}
                    {teamId === currentTeamId && (
                        <span className="ml-1 text-tertiary font-normal normal-case">(current)</span>
                    )}
                </span>
            ),
            key: `project-${teamId}`,
            width: columnWidth,
            render: (_: unknown, flag: OrganizationFeatureFlagRow) => {
                const state = cellStateFor(
                    flag,
                    teamId,
                    currentTeamId,
                    accessibleTeamIds,
                    siblingsByFlagKey[flag.key],
                    siblingsLoadingKeys.includes(flag.key)
                )
                const flagId = state.kind === 'present' ? state.sibling.flag_id : null
                return (
                    <ProjectsGridCell
                        state={state}
                        toggling={flagId !== null ? togglingFlagIds[flagToggleKey(teamId, flagId)] : false}
                        onToggle={
                            flagId !== null
                                ? (active) =>
                                      confirmFlagActiveToggleInProject({
                                          teamName: teamsById.get(teamId)?.name ?? `Project ${teamId}`,
                                          active,
                                          onConfirm: () => toggleFlagActive(flag.key, teamId, flagId, active),
                                      })
                                : undefined
                        }
                    />
                )
            },
        })),
    ]

    return (
        <SceneSection
            title="Feature flags across projects"
            description="Compare each flag's status, rollout, and recent usage across your organization's projects."
        >
            <ProjectsGridToolbar bulkSelectionBarRef={setBulkBarTarget} />
            <BulkCopyFlagsModal />
            <LemonTable
                columns={columns}
                dataSource={flags}
                rowKey="id"
                loading={flagsPageLoading && flags.length === 0}
                emptyState="No flags match your search."
                data-attr="projects-grid-table"
                className="[&_table]:table-fixed"
                bulkSelection={{
                    getKey: (flag: OrganizationFeatureFlagRow): string => flag.key,
                    rowAriaLabel: (flag: OrganizationFeatureFlagRow) => `Select feature flag ${flag.key}`,
                    headerAriaLabel: 'Select all loaded feature flags',
                    noun: ['flag', 'flags'],
                    barPortalTarget: bulkBarTarget,
                    renderActions: (ctx) => (
                        <BulkCopyToProjectsButton
                            dataAttr="projects-grid-bulk-copy-button"
                            selectedCount={ctx.selectedCount}
                            onOpen={() =>
                                openBulkCopyModal({
                                    sourceProjectId: currentTeamId,
                                    flagKeys: ctx.selectedKeys.map(String),
                                    sourceSelectable: true,
                                })
                            }
                        />
                    ),
                }}
            />
            {flagsPageLoading && flags.length > 0 && <LemonSkeleton className="h-8 my-2" />}
            <div ref={sentinelRef} className="h-1" />
        </SceneSection>
    )
}

export default ProjectsGrid