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.9 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { useEffect, useState } from 'react'

import { IconPerson, IconPlusSmall } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonDropdown, LemonInput } from '@posthog/lemon-ui'

import { urls } from 'scenes/urls'

import { clearFilterButtonProps } from '../../clearFilterButtonProps'
import { AssigneeIconDisplay, AssigneeLabelDisplay, AssigneeResolver } from './AssigneeDisplay'
import { assigneeSelectLogic } from './assigneeSelectLogic'
import {
    Assignee,
    AssigneeFilterEntry,
    isSameAssigneeEntry,
    MAX_ASSIGNEE_FILTER_ENTRIES,
    toTicketAssignee,
} from './types'

export function AssigneeMultiSelect({
    value,
    onChange,
    emptyLabel = 'All assignees',
}: {
    value: AssigneeFilterEntry[]
    onChange: (value: AssigneeFilterEntry[]) => void
    emptyLabel?: string
}): JSX.Element {
    const { search, filteredRoles, filteredMembers, currentUserMember, rolesLoading, membersLoading } =
        useValues(assigneeSelectLogic)
    const { setSearch, ensureAssigneeTypesLoaded } = useActions(assigneeSelectLogic)
    const [showPopover, setShowPopover] = useState(false)

    useEffect(() => {
        ensureAssigneeTypesLoaded()
    }, [ensureAssigneeTypesLoaded])

    const isSelected = (entry: AssigneeFilterEntry): boolean =>
        value.some((selected) => isSameAssigneeEntry(selected, entry))
    const toggleEntry = (entry: AssigneeFilterEntry): void => {
        onChange(
            isSelected(entry) ? value.filter((selected) => !isSameAssigneeEntry(selected, entry)) : [...value, entry]
        )
    }
    const selectionCapReason =
        value.length >= MAX_ASSIGNEE_FILTER_ENTRIES
            ? `You can select up to ${MAX_ASSIGNEE_FILTER_ENTRIES} assignees`
            : undefined

    return (
        <LemonDropdown
            closeOnClickInside={false}
            visible={showPopover}
            matchWidth={false}
            onVisibilityChange={(visible) => {
                setShowPopover(visible)
                if (!visible) {
                    setSearch('')
                }
            }}
            overlay={
                <div className="max-w-100 deprecated-space-y-2">
                    <LemonInput
                        type="search"
                        placeholder="Search"
                        autoFocus
                        value={search}
                        onChange={setSearch}
                        fullWidth
                    />
                    <ul className="deprecated-space-y-2">
                        {currentUserMember && (
                            <li>
                                {/* Dynamic "me" entry — resolves to whoever is signed in, so a
                                    saved view scoped to it stays each viewer's own tickets. */}
                                <LemonButton
                                    fullWidth
                                    role="menuitem"
                                    size="small"
                                    icon={<LemonCheckbox checked={isSelected('me')} className="pointer-events-none" />}
                                    disabledReason={isSelected('me') ? undefined : selectionCapReason}
                                    onClick={() => toggleEntry('me')}
                                >
                                    <span className="flex items-center gap-1">
                                        <MeIcon />
                                        Me
                                        <span className="text-secondary">(current user)</span>
                                    </span>
                                </LemonButton>
                            </li>
                        )}
                        <li>
                            <LemonButton
                                fullWidth
                                role="menuitem"
                                size="small"
                                icon={
                                    <LemonCheckbox checked={isSelected('unassigned')} className="pointer-events-none" />
                                }
                                disabledReason={isSelected('unassigned') ? undefined : selectionCapReason}
                                onClick={() => toggleEntry('unassigned')}
                            >
                                <span className="flex items-center gap-1">
                                    <AssigneeIconDisplay assignee={null} size="small" />
                                    Unassigned
                                </span>
                            </LemonButton>
                        </li>
                        <Section
                            title="Roles"
                            loading={rolesLoading}
                            search={!!search}
                            items={filteredRoles.map((role) => ({ id: role.id, type: 'role' as const, role }))}
                            isSelected={isSelected}
                            onToggle={toggleEntry}
                            selectionCapReason={selectionCapReason}
                            emptyState={
                                <LemonButton
                                    fullWidth
                                    size="small"
                                    icon={<IconPlusSmall />}
                                    to={urls.settings('organization-roles')}
                                >
                                    <div className="text-secondary">Create role</div>
                                </LemonButton>
                            }
                        />
                        {(!!search || membersLoading || filteredMembers.length > 0) && (
                            <Section
                                title="Users"
                                loading={membersLoading}
                                search={!!search}
                                // Include the current user here too (as their concrete
                                // user:<id>), so they can filter to their own UUID
                                // specifically — distinct from the dynamic "Me" row above.
                                items={filteredMembers.map((member) => ({
                                    id: member.user.id,
                                    type: 'user' as const,
                                    user: member.user,
                                }))}
                                isSelected={isSelected}
                                onToggle={toggleEntry}
                                selectionCapReason={selectionCapReason}
                            />
                        )}
                    </ul>
                </div>
            }
        >
            <LemonButton
                size="small"
                type="secondary"
                active={showPopover}
                {...clearFilterButtonProps(value.length > 0 ? () => onChange([]) : null, 'Clear assignee filter')}
            >
                <TriggerLabel value={value} emptyLabel={emptyLabel} />
            </LemonButton>
        </LemonDropdown>
    )
}

function TriggerLabel({ value, emptyLabel }: { value: AssigneeFilterEntry[]; emptyLabel: string }): JSX.Element {
    if (value.length === 0) {
        return <>{emptyLabel}</>
    }
    if (value.length > 1) {
        return <>{value.length} assignees</>
    }
    const entry = value[0]
    if (entry === 'unassigned') {
        return (
            <span className="flex items-center gap-1">
                <AssigneeIconDisplay assignee={null} size="small" />
                <AssigneeLabelDisplay assignee={null} size="small" />
            </span>
        )
    }
    if (entry === 'me') {
        return (
            <span className="flex items-center gap-1">
                <MeIcon />
                Me
            </span>
        )
    }
    return (
        <AssigneeResolver assignee={toTicketAssignee(entry)}>
            {({ assignee }) => (
                <span className="flex items-center gap-1">
                    <AssigneeIconDisplay assignee={assignee} size="small" />
                    <AssigneeLabelDisplay assignee={assignee} size="small" placeholder="1 assignee" />
                </span>
            )}
        </AssigneeResolver>
    )
}

// Solid person glyph for the dynamic "me" entry — distinct from the dashed
// "unassigned" icon and from any specific member's avatar.
function MeIcon(): JSX.Element {
    return <IconPerson className="rounded-full bg-accent-highlight text-accent p-0.5 h-4 w-4" />
}

const AssigneeFilterItem = ({
    item,
    isSelected,
    onToggle,
    selectionCapReason,
    labelSuffix,
}: {
    item: NonNullable<Assignee>
    isSelected: (entry: AssigneeFilterEntry) => boolean
    onToggle: (entry: AssigneeFilterEntry) => void
    selectionCapReason?: string
    labelSuffix?: JSX.Element
}): JSX.Element => {
    return (
        <LemonButton
            fullWidth
            role="menuitem"
            size="small"
            icon={<LemonCheckbox checked={isSelected(item)} className="pointer-events-none" />}
            disabledReason={isSelected(item) ? undefined : selectionCapReason}
            onClick={() => onToggle(toTicketAssignee(item))}
        >
            <span className="flex items-center gap-1">
                <AssigneeIconDisplay assignee={item} size="small" />
                <AssigneeLabelDisplay assignee={item} />
                {labelSuffix}
            </span>
        </LemonButton>
    )
}

const Section = ({
    title,
    loading,
    search,
    items,
    isSelected,
    onToggle,
    selectionCapReason,
    emptyState,
}: {
    title: string
    loading: boolean
    search: boolean
    items: NonNullable<Assignee>[]
    isSelected: (entry: AssigneeFilterEntry) => boolean
    onToggle: (entry: AssigneeFilterEntry) => void
    selectionCapReason?: string
    emptyState?: JSX.Element
}): JSX.Element => {
    return (
        <li>
            <section className="deprecated-space-y-px">
                <h5 className="mx-2 my-0.5">{title}</h5>
                {items.map((item) => (
                    <li key={item.id}>
                        <AssigneeFilterItem
                            item={item}
                            isSelected={isSelected}
                            onToggle={onToggle}
                            selectionCapReason={selectionCapReason}
                        />
                    </li>
                ))}

                {loading ? (
                    <div className="p-2 text-secondary italic truncate border-t">Loading...</div>
                ) : items.length === 0 ? (
                    search ? (
                        <div className="p-2 text-secondary italic truncate border-t">
                            <span>No matches</span>
                        </div>
                    ) : (
                        <div className="border-t pt-1">{emptyState}</div>
                    )
                ) : null}
            </section>
        </li>
    )
}