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.

18.4 KB
Raw Blame
import { Combobox } from '@base-ui/react/combobox'
import { useActions, useValues } from 'kea'
import { useCallback, useMemo, useRef, useState } from 'react'

import { IconCheck, IconPlusSmall, IconSearch, IconX } from '@posthog/icons'

import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'
import { IconBlank } from 'lib/lemon-ui/icons'
import { KeyboardShortcut } from 'lib/lemon-ui/KeyboardShortcut/KeyboardShortcut'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { ScrollableShadows } from 'lib/lemon-ui/ScrollableShadows/ScrollableShadows'
import { UploadedLogo } from 'lib/lemon-ui/UploadedLogo'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { MenuSeparator } from 'lib/ui/Menus/Menus'
import { cn } from 'lib/utils/css-classes'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { globalModalsLogic } from '~/layout/globalModalsLogic'
import { AccessLevelIndicator } from '~/layout/navigation/AccessLevelIndicator'
import { AvailableFeature, OrganizationBasicType } from '~/types'

import { newAccountMenuLogic } from './newAccountMenuLogic'
import { pendingInvitesLogic, PendingInviteForCurrentUser } from './pendingInvitesLogic'

interface OrgListItem {
    type: 'org'
    id: string
    org: OrganizationBasicType
    isCurrent: boolean
    isDisabled: boolean
    disabledReason?: string
}

interface PendingInviteListItem {
    type: 'pending-invite'
    id: string
    invite: PendingInviteForCurrentUser
}

interface CreateOrgItem {
    type: 'create'
    id: 'create-new-org'
    label: string
}

type ListItem = OrgListItem | PendingInviteListItem | CreateOrgItem

export function OrgSwitcher({ dialog = true }: { dialog?: boolean }): JSX.Element {
    const { preflight } = useValues(preflightLogic)
    const { guardAvailableFeature } = useValues(upgradeModalLogic)
    const { showCreateOrganizationModal } = useActions(globalModalsLogic)
    const { currentOrganization } = useValues(organizationLogic)
    const { otherOrganizations } = useValues(userLogic)
    const { pendingInvites } = useValues(pendingInvitesLogic)
    const { updateCurrentOrganization } = useActions(userLogic)
    const { closeOrgSwitcher, setAccountMenuOpen } = useActions(newAccountMenuLogic)
    const [searchValue, setSearchValue] = useState('')
    const inputRef = useRef<HTMLInputElement>(null!)

    const allOrgItems: OrgListItem[] = useMemo(() => {
        const items: OrgListItem[] = []

        if (currentOrganization) {
            items.push({
                type: 'org',
                id: currentOrganization.id,
                org: currentOrganization,
                isCurrent: true,
                isDisabled: false,
            })
        }

        for (const org of otherOrganizations) {
            items.push({
                type: 'org',
                id: org.id,
                org,
                isCurrent: false,
                isDisabled: org.is_active === false,
                disabledReason: org.is_not_active_reason || 'Organization is disabled',
            })
        }

        return items
    }, [currentOrganization, otherOrganizations])

    const allPendingInviteItems: PendingInviteListItem[] = useMemo(
        () =>
            pendingInvites.map((invite) => ({
                type: 'pending-invite' as const,
                id: invite.id,
                invite,
            })),
        [pendingInvites]
    )

    const filteredItems = useMemo(() => {
        const searchLower = searchValue.trim().toLowerCase()

        // Filter org items
        const filteredOrgs = searchLower
            ? allOrgItems.filter((item) => item.org.name.toLowerCase().includes(searchLower))
            : allOrgItems

        const filteredInvites = searchLower
            ? allPendingInviteItems.filter((item) => item.invite.organization_name.toLowerCase().includes(searchLower))
            : allPendingInviteItems

        // Create the "create" item - show different label based on search
        const createItem: CreateOrgItem = {
            type: 'create',
            id: 'create-new-org',
            label: 'New organization',
            // TODO: Uncomment this when we have a way to create organizations with a name
            // label: searchValue.trim() ? `Create '${searchValue.trim()}'` : 'New organization',
        }

        return [...filteredOrgs, ...filteredInvites, createItem] as ListItem[]
    }, [allOrgItems, allPendingInviteItems, searchValue])

    const currentOrgItem = filteredItems.find((o): o is OrgListItem => o.type === 'org' && o.isCurrent)
    const otherOrgItems = filteredItems
        .filter((o): o is OrgListItem => o.type === 'org' && !o.isCurrent)
        .sort((a, b) => a.org.name.localeCompare(b.org.name))
    const pendingInviteItems = filteredItems
        .filter((o): o is PendingInviteListItem => o.type === 'pending-invite')
        .sort((a, b) => a.invite.organization_name.localeCompare(b.invite.organization_name))
    const createItem = filteredItems.find((o): o is CreateOrgItem => o.type === 'create')

    const handleItemClick = useCallback(
        (item: ListItem) => {
            if (item.type === 'create') {
                guardAvailableFeature(
                    AvailableFeature.ORGANIZATIONS_PROJECTS,
                    () => {
                        showCreateOrganizationModal()
                        setAccountMenuOpen(false)
                    },
                    { guardOnCloud: false }
                )
                closeOrgSwitcher()
            } else if (item.type === 'pending-invite') {
                closeOrgSwitcher()
                window.location.href = urls.inviteSignup(item.invite.id)
            } else if (!item.isCurrent && !item.isDisabled) {
                closeOrgSwitcher()
                updateCurrentOrganization(item.org.id)
            }
        },
        [
            closeOrgSwitcher,
            updateCurrentOrganization,
            guardAvailableFeature,
            showCreateOrganizationModal,
            setAccountMenuOpen,
        ]
    )

    const getItemString = useCallback((item: ListItem | null): string => {
        if (!item) {
            return ''
        }
        if (item.type === 'create') {
            return item.label
        }
        if (item.type === 'pending-invite') {
            return item.invite.organization_name
        }
        return item.org.name
    }, [])

    const canCreateOrg = preflight?.can_create_org !== false

    const spacingClass = dialog ? 'p-2' : 'p-1'

    return (
        <Combobox.Root
            items={filteredItems}
            filter={null}
            itemToStringValue={getItemString}
            inline
            defaultOpen
            autoHighlight
        >
            <div className="flex flex-col overflow-hidden">
                {/* Search Input */}
                <div className={`${spacingClass} ${dialog && 'border-b border-primary'}`}>
                    <label
                        className={cn(
                            'group input-like flex gap-1 items-center relative w-full bg-fill-input border border-primary focus-within:ring-primary py-1 px-2',
                            {
                                'h-[30px]': !dialog,
                            }
                        )}
                    >
                        <Combobox.Icon
                            className="size-5"
                            render={<IconSearch className="text-tertiary group-focus-within:text-primary" />}
                        />
                        <Combobox.Input
                            ref={inputRef}
                            value={searchValue}
                            onChange={(e) => setSearchValue(e.target.value)}
                            aria-label="Search organizations"
                            placeholder="Search organizations..."
                            className="w-full px-1 py-1 text-sm focus:outline-none border-transparent"
                            autoFocus
                        />
                        {searchValue && (
                            <Combobox.Clear
                                render={
                                    <ButtonPrimitive
                                        iconOnly
                                        size="sm"
                                        onClick={() => setSearchValue('')}
                                        aria-label="Clear search"
                                        className="-mr-1"
                                    >
                                        <IconX className="size-4 text-tertiary" />
                                    </ButtonPrimitive>
                                }
                            />
                        )}
                    </label>
                </div>

                {/* Results */}
                <ScrollableShadows
                    direction="vertical"
                    styledScrollbars
                    className="flex-1 overflow-y-auto max-h-[400px]"
                >
                    <Combobox.List
                        className={`flex flex-col gap-px ${spacingClass} bg-surface-primary ${!dialog && 'pt-0.5'}`}
                        tabIndex={-1}
                    >
                        {/* Current Organization */}
                        {currentOrgItem && (
                            <Combobox.Group items={[currentOrgItem]}>
                                <Combobox.Collection>
                                    {(item: OrgListItem) => (
                                        <Combobox.Item
                                            key={item.id}
                                            value={item}
                                            onClick={() => handleItemClick(item)}
                                            render={(props) => (
                                                <ButtonPrimitive {...props} menuItem active fullWidth>
                                                    <IconCheck className="text-tertiary" />
                                                    <UploadedLogo
                                                        size="xsmall"
                                                        name={item.org.name}
                                                        entityId={item.org.id}
                                                        mediaId={item.org.logo_media_id}
                                                    />
                                                    <span className="truncate">{item.org.name}</span>
                                                    <div className="ml-auto">
                                                        <AccessLevelIndicator organization={item.org} />
                                                    </div>
                                                </ButtonPrimitive>
                                            )}
                                        />
                                    )}
                                </Combobox.Collection>
                            </Combobox.Group>
                        )}

                        {/* Other Organizations */}
                        {otherOrgItems.length > 0 && (
                            <Combobox.Group items={otherOrgItems}>
                                <Combobox.Collection>
                                    {(item: OrgListItem) => (
                                        <Combobox.Item
                                            key={item.id}
                                            value={item}
                                            onClick={() => handleItemClick(item)}
                                            render={(props) => (
                                                <ButtonPrimitive
                                                    {...props}
                                                    menuItem
                                                    fullWidth
                                                    disabled={item.isDisabled}
                                                    tooltip={item.isDisabled ? item.disabledReason : undefined}
                                                    tooltipPlacement="right"
                                                >
                                                    <IconBlank />
                                                    <UploadedLogo
                                                        size="xsmall"
                                                        name={item.org.name}
                                                        entityId={item.org.id}
                                                        mediaId={item.org.logo_media_id}
                                                    />
                                                    <span className="truncate">{item.org.name}</span>
                                                    <div className="ml-auto">
                                                        <AccessLevelIndicator organization={item.org} />
                                                    </div>
                                                </ButtonPrimitive>
                                            )}
                                        />
                                    )}
                                </Combobox.Collection>
                            </Combobox.Group>
                        )}

                        {/* Pending Invitations */}
                        {pendingInviteItems.length > 0 && (
                            <Combobox.Group items={pendingInviteItems}>
                                <Combobox.Collection>
                                    {(item: PendingInviteListItem) => (
                                        <Combobox.Item
                                            key={item.id}
                                            value={item}
                                            onClick={() => handleItemClick(item)}
                                            render={(props) => (
                                                <ButtonPrimitive
                                                    {...props}
                                                    menuItem
                                                    fullWidth
                                                    tooltip={`Accept pending invitation to ${item.invite.organization_name}`}
                                                    tooltipPlacement="right"
                                                >
                                                    <IconBlank />
                                                    <UploadedLogo
                                                        size="xsmall"
                                                        name={item.invite.organization_name}
                                                        entityId={item.invite.organization_id}
                                                    />
                                                    <span className="truncate">{item.invite.organization_name}</span>
                                                    <div className="ml-auto">
                                                        <LemonTag>pending invite</LemonTag>
                                                    </div>
                                                </ButtonPrimitive>
                                            )}
                                        />
                                    )}
                                </Combobox.Collection>
                            </Combobox.Group>
                        )}

                        <MenuSeparator />

                        {/* Create New Organization */}
                        {createItem && (
                            <Combobox.Group items={[createItem]}>
                                <Combobox.Collection>
                                    {(item: CreateOrgItem) => (
                                        <Combobox.Item
                                            key={item.id}
                                            value={item}
                                            onClick={() => handleItemClick(item)}
                                            render={(props) => (
                                                <ButtonPrimitive
                                                    {...props}
                                                    menuItem
                                                    fullWidth
                                                    disabled={!canCreateOrg}
                                                    tooltip={
                                                        !canCreateOrg
                                                            ? 'You do not have permission to create an organization'
                                                            : undefined
                                                    }
                                                    tooltipPlacement="right"
                                                >
                                                    <IconPlusSmall className="text-tertiary" />
                                                    <span className="truncate">{item.label}</span>
                                                </ButtonPrimitive>
                                            )}
                                        />
                                    )}
                                </Combobox.Collection>
                            </Combobox.Group>
                        )}
                    </Combobox.List>
                </ScrollableShadows>

                {/* Footer */}
                {dialog && (
                    <div className="menu-legend border-t border-primary p-1">
                        <div className="px-2 py-1 text-xxs text-tertiary font-medium flex items-center gap-2">
                            <span>
                                <KeyboardShortcut arrowup arrowdown preserveOrder /> navigate
                            </span>
                            <span>
                                <KeyboardShortcut enter /> select
                            </span>
                            <span>
                                <KeyboardShortcut escape /> close
                            </span>
                        </div>
                    </div>
                )}
            </div>
        </Combobox.Root>
    )
}