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.

34.5 KB
Raw Blame
import { hide } from '@floating-ui/react'
import { useActions, useValues } from 'kea'
import { Fragment, useEffect, useMemo } from 'react'

import { IconBadge, IconEye, IconHide, IconInfo } from '@posthog/icons'
import { LemonButton, LemonDivider, LemonInputSelect, LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'

import { ActionPopoverInfo } from 'lib/components/DefinitionPopover/ActionPopoverInfo'
import { CohortPopoverInfo } from 'lib/components/DefinitionPopover/CohortPopoverInfo'
import { DefinitionPopover } from 'lib/components/DefinitionPopover/DefinitionPopover'
import { DefinitionPopoverState, definitionPopoverLogic } from 'lib/components/DefinitionPopover/definitionPopoverLogic'
import { LazyFeatureFlagPopoverInfo } from 'lib/components/DefinitionPopover/LazyFeatureFlagPopoverInfo'
import { featureFlagKeyFromProperty } from 'lib/components/DefinitionPopover/utils'
import { FlagCalledMoveNotice } from 'lib/components/FlagCalledMoveNotice/FlagCalledMoveNotice'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import {
    DataWarehousePopoverField,
    DefinitionPopoverRenderer,
    SimpleOption,
    TaxonomicDefinitionTypes,
    TaxonomicFilterGroup,
    TaxonomicFilterGroupType,
} from 'lib/components/TaxonomicFilter/types'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea/LemonTextArea'
import { Popover } from 'lib/lemon-ui/Popover'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { cn } from 'lib/utils/css-classes'
import { isKeyOf } from 'lib/utils/guards'

import { getCoreFilterDefinition, getFilterLabel, isCoreFilter } from '~/taxonomy/helpers'
import {
    ActionType,
    CohortType,
    EventDefinition,
    PropertyDefinition,
    PropertyDefinitionVerificationStatus,
} from '~/types'

import { DataWarehouseTableForInsight } from 'products/data_warehouse/frontend/types'

import { HogQLDropdown } from '../HogQLDropdown/HogQLDropdown'
import { taxonomicFilterLogic } from '../TaxonomicFilter/taxonomicFilterLogic'
import { TZLabel } from '../TZLabel'

export function PropertyStatusControl({
    verified,
    hidden,
    showHiddenOption,
    allowVerification,
    onChange,
    compact = false,
    isProperty,
}: {
    verified: boolean
    hidden: boolean
    showHiddenOption: boolean
    allowVerification: boolean
    onChange: (status: { verified: boolean; hidden: boolean }) => void
    compact?: boolean
    isProperty: boolean
}): JSX.Element {
    const definitionType = isProperty ? 'property' : 'event'
    const copy = {
        verified: `Prioritize this ${definitionType} in filters and other selection components to signal to collaborators that this ${definitionType} should be used in favor of similar ${
            definitionType === 'property' ? 'properties' : `${definitionType}s`
        }.`,
        visible: `${
            definitionType.charAt(0).toUpperCase() + definitionType.slice(1)
        } is available for use but has not been verified by the team.`,
        hidden: `Hide this ${definitionType} from filters and other selection components by default. Use this for deprecated or irrelevant ${definitionType}s.`,
    }

    const verifiedDisabledCorePropCopy = `Core PostHog ${definitionType}s are inherently treated as if verified, but they can still be hidden.`

    const currentStatus: PropertyDefinitionVerificationStatus = hidden ? 'hidden' : verified ? 'verified' : 'visible'

    return (
        <>
            <LemonSegmentedButton
                value={currentStatus}
                onChange={(value) => {
                    const status = value as PropertyDefinitionVerificationStatus
                    onChange({
                        verified: status === 'verified',
                        hidden: status === 'hidden',
                    })
                }}
                options={[
                    {
                        value: 'verified',
                        label: 'Verified',
                        tooltip: allowVerification ? copy.verified : undefined,
                        icon: <IconBadge />,
                        disabledReason: !allowVerification ? verifiedDisabledCorePropCopy : undefined,
                    },
                    {
                        value: 'visible',
                        label: 'Visible',
                        tooltip: copy.visible,
                        icon: <IconEye />,
                    },
                    ...(showHiddenOption
                        ? [
                              {
                                  value: 'hidden',
                                  label: 'Hidden',
                                  tooltip: copy.hidden,
                                  icon: <IconHide />,
                              },
                          ]
                        : []),
                ]}
            />
            {!compact && <p className="italic">{copy[currentStatus]}</p>}
        </>
    )
}

export function DefinitionView({
    group,
    description: descriptionOverride,
}: {
    group: TaxonomicFilterGroup
    /** Wins over both the definition's own description and the core one. */
    description?: string
}): JSX.Element {
    const {
        definition,
        localDefinition,
        type,
        isAction,
        isEvent,
        isCohort,
        isDataWarehouse,
        isDataWarehousePersonProperty,
        isProperty,
        hasSentAs,
        isVirtual,
    } = useValues(definitionPopoverLogic)

    const { setLocalDefinition } = useActions(definitionPopoverLogic)
    const { selectedItemMeta, dataWarehousePopoverFields } = useValues(taxonomicFilterLogic)
    const { selectItem } = useActions(taxonomicFilterLogic)

    // Pre-populate field mappings from the insight filter.
    // Only apply to data warehouse - for events/properties, selectedItemMeta.id is the
    // event name which would incorrectly overwrite the event definition's UUID.
    useEffect(() => {
        if (isDataWarehouse && selectedItemMeta && definition.name === selectedItemMeta.id) {
            setLocalDefinition(selectedItemMeta)
        }
    }, [definition, isDataWarehouse]) // eslint-disable-line react-hooks/exhaustive-deps

    const hasSentAsLabel = useMemo(() => {
        const _definition = definition as PropertyDefinition

        if (!_definition) {
            return null
        }

        if (isDataWarehousePersonProperty) {
            return _definition.id
        }

        if (_definition.name !== '') {
            return _definition.name
        }

        return <i>(empty string)</i>
    }, [isDataWarehousePersonProperty, definition, isProperty])

    if (!definition) {
        return <></>
    }

    const description =
        descriptionOverride ||
        (definition && 'description' in definition && definition?.description) ||
        (definition?.name ? getCoreFilterDefinition(definition.name, group.type)?.description : undefined)

    const sharedComponents = (
        <>
            {description ? (
                <DefinitionPopover.Description description={description} />
            ) : (
                <DefinitionPopover.DescriptionEmpty />
            )}
            <FlagCalledMoveNotice name={definition.name} groupType={group.type} className="mb-2" />
            <DefinitionPopover.Example value={group?.getValue?.(definition)?.toString()} />
            {definition && 'tags' in definition && !!definition.tags?.length && (
                <ObjectTags
                    className="definition-popover-tags"
                    tags={definition.tags}
                    style={{ marginBottom: 4 }}
                    staticOnly
                />
            )}
            <DefinitionPopover.TimeMeta
                createdAt={(definition && 'created_at' in definition && definition.created_at) || undefined}
                createdBy={(definition && 'created_by' in definition && definition.created_by) || undefined}
                updatedAt={(definition && 'updated_at' in definition && definition.updated_at) || undefined}
                updatedBy={(definition && 'updated_by' in definition && definition.updated_by) || undefined}
            />
            <LemonDivider className="DefinitionPopover my-4" />
        </>
    )

    // Things start to get different here
    if (isEvent) {
        const _definition = definition as EventDefinition
        return (
            <>
                {sharedComponents}
                <DefinitionPopover.Grid cols={2}>
                    <DefinitionPopover.Card
                        title="First seen"
                        value={_definition.created_at && <TZLabel time={_definition.created_at} />}
                    />
                    <DefinitionPopover.Card
                        title="Last seen"
                        value={_definition.last_seen_at && <TZLabel time={_definition.last_seen_at} />}
                    />
                </DefinitionPopover.Grid>

                {hasSentAs ? (
                    <>
                        <DefinitionPopover.HorizontalLine />
                        <DefinitionPopover.Section>
                            <DefinitionPopover.Card
                                title="Sent as"
                                value={<span className="font-mono text-xs">{_definition.name}</span>}
                            />
                        </DefinitionPopover.Section>
                    </>
                ) : null}
            </>
        )
    }
    if (isAction) {
        const _definition = definition as ActionType
        return (
            <>
                {sharedComponents}
                <ActionPopoverInfo entity={_definition} />
            </>
        )
    }

    if (isProperty) {
        const _definition = definition as PropertyDefinition
        const flagKey =
            type === TaxonomicFilterGroupType.EventFeatureFlags ? featureFlagKeyFromProperty(_definition.name) : null

        return (
            <>
                {sharedComponents}
                {_definition.verified && (
                    <div className="mb-4">
                        <Tooltip title="This property is verified by the team. It is prioritized in filters and other selection components.">
                            <LemonTag type="success">
                                <IconBadge /> Verified
                            </LemonTag>
                        </Tooltip>
                    </div>
                )}
                {flagKey ? (
                    <LazyFeatureFlagPopoverInfo flagKey={flagKey} />
                ) : (
                    <DefinitionPopover.Grid cols={2}>
                        <DefinitionPopover.Card title="Property Type" value={_definition.property_type ?? '-'} />
                    </DefinitionPopover.Grid>
                )}
                {hasSentAs ? (
                    <>
                        <DefinitionPopover.HorizontalLine />
                        <DefinitionPopover.Grid cols={2}>
                            <DefinitionPopover.Card
                                title={isDataWarehousePersonProperty ? 'Table' : 'Sent as'}
                                value={
                                    <span
                                        className="truncate text-mono text-xs"
                                        title={
                                            isDataWarehousePersonProperty
                                                ? _definition.id
                                                : (_definition.name ?? undefined)
                                        }
                                    >
                                        {hasSentAsLabel}
                                    </span>
                                }
                            />
                        </DefinitionPopover.Grid>
                    </>
                ) : null}
                {isVirtual ? (
                    <>
                        <DefinitionPopover.HorizontalLine />
                        <DefinitionPopover.Grid cols={2}>
                            <DefinitionPopover.Card
                                title="Virtual"
                                value={
                                    <span className="text-xs">
                                        Virtual properties are computed from other properties, and are not sent
                                        directly.
                                    </span>
                                }
                            />
                        </DefinitionPopover.Grid>
                    </>
                ) : null}
            </>
        )
    }
    if (isCohort) {
        const _definition = definition as CohortType
        if (type === TaxonomicFilterGroupType.CohortsWithAllUsers) {
            return (
                <>
                    {sharedComponents}
                    <DefinitionPopover.Grid cols={2}>
                        <DefinitionPopover.Card title="Persons" value={_definition.count ?? 0} />
                        <DefinitionPopover.Card
                            title="Last calculated"
                            value={_definition.last_calculation && <TZLabel time={_definition.last_calculation} />}
                        />
                    </DefinitionPopover.Grid>
                </>
            )
        }
        if (!_definition.is_static) {
            return (
                <>
                    {sharedComponents}
                    <DefinitionPopover.Grid cols={2}>
                        <DefinitionPopover.Card title="Persons" value={_definition.count ?? 0} />
                        <DefinitionPopover.Card
                            title="Last calculated"
                            value={_definition.last_calculation && <TZLabel time={_definition.last_calculation} />}
                        />
                    </DefinitionPopover.Grid>
                    <CohortPopoverInfo cohort={_definition} />
                </>
            )
        }
        return (
            <>
                {sharedComponents}
                <DefinitionPopover.Grid cols={2}>
                    <DefinitionPopover.Card title="Persons" value={_definition.count ?? 0} />
                    <DefinitionPopover.Card
                        title="Last calculated"
                        value={_definition.last_calculation && <TZLabel time={_definition.last_calculation} />}
                    />
                </DefinitionPopover.Grid>
            </>
        )
    }
    if (
        group.type === TaxonomicFilterGroupType.PageviewEvents ||
        group.type === TaxonomicFilterGroupType.ScreenEvents ||
        group.type === TaxonomicFilterGroupType.AutocaptureEvents ||
        group.type === TaxonomicFilterGroupType.PageviewUrls ||
        group.type === TaxonomicFilterGroupType.Screens ||
        group.type === TaxonomicFilterGroupType.EmailAddresses
    ) {
        const _definition = definition as SimpleOption
        const isEventMode =
            group.type === TaxonomicFilterGroupType.PageviewEvents ||
            group.type === TaxonomicFilterGroupType.ScreenEvents ||
            group.type === TaxonomicFilterGroupType.AutocaptureEvents

        const groupConfig: Record<
            string,
            {
                propertyName: string
                propertyGroupType: TaxonomicFilterGroupType
                eventName?: string
                eventDescription?: string
            }
        > = {
            [TaxonomicFilterGroupType.PageviewEvents]: {
                propertyName: '$current_url',
                propertyGroupType: TaxonomicFilterGroupType.EventProperties,
                eventName: '$pageview',
                eventDescription: 'Pageview filtered by current URL.',
            },
            [TaxonomicFilterGroupType.PageviewUrls]: {
                propertyName: '$current_url',
                propertyGroupType: TaxonomicFilterGroupType.EventProperties,
            },
            [TaxonomicFilterGroupType.ScreenEvents]: {
                propertyName: '$screen_name',
                propertyGroupType: TaxonomicFilterGroupType.EventProperties,
                eventName: '$screen',
                eventDescription: 'Screen event filtered by screen name.',
            },
            [TaxonomicFilterGroupType.Screens]: {
                propertyName: '$screen_name',
                propertyGroupType: TaxonomicFilterGroupType.EventProperties,
            },
            [TaxonomicFilterGroupType.AutocaptureEvents]: {
                propertyName: '$el_text',
                propertyGroupType: TaxonomicFilterGroupType.EventProperties,
                eventName: '$autocapture',
                eventDescription: 'Autocapture filtered by element text.',
            },
            [TaxonomicFilterGroupType.EmailAddresses]: {
                propertyName: 'email',
                propertyGroupType: TaxonomicFilterGroupType.PersonProperties,
            },
        }

        const config = groupConfig[group.type]
        const propertyLabel = getFilterLabel(config.propertyName, config.propertyGroupType)

        if (isEventMode && config.eventName && config.eventDescription) {
            const eventLabel = getFilterLabel(config.eventName, TaxonomicFilterGroupType.Events)

            return (
                <>
                    <DefinitionPopover.Description
                        description={
                            <>
                                {config.eventDescription}
                                <br />
                                <br />
                                Selecting this will add a <span className="font-semibold">{eventLabel}</span> event
                                filtered by <span className="font-semibold">{propertyLabel}</span> matching{' '}
                                <span className="font-semibold break-all">{_definition.name}</span>.
                            </>
                        }
                    />
                    <DefinitionPopover.Example value={_definition.name} />
                </>
            )
        }

        return (
            <>
                <DefinitionPopover.Description
                    description={
                        <>
                            Selecting this will filter by <span className="font-semibold">{propertyLabel}</span>{' '}
                            matching <span className="font-semibold break-all">{_definition.name}</span>.
                        </>
                    }
                />
                <DefinitionPopover.Example value={_definition.name} />
            </>
        )
    }
    if (group.type === TaxonomicFilterGroupType.Elements) {
        const _definition = definition as SimpleOption
        return (
            <>
                {sharedComponents}
                <DefinitionPopover.Section>
                    <DefinitionPopover.Card
                        title="Sent as"
                        value={<span className="text-xs font-mono">{_definition.name}</span>}
                    />
                </DefinitionPopover.Section>
            </>
        )
    }
    if (group.type === TaxonomicFilterGroupType.EventMetadata) {
        const _definition = definition as PropertyDefinition
        return (
            <>
                {sharedComponents}
                <DefinitionPopover.Grid cols={2}>
                    <DefinitionPopover.Card title="Type" value={_definition.property_type ?? '-'} />
                </DefinitionPopover.Grid>
                <LemonDivider className="DefinitionPopover my-4" />
                <DefinitionPopover.Section>
                    <DefinitionPopover.Card
                        title="Sent as"
                        value={<span className="text-xs font-mono">{_definition.id}</span>}
                    />
                </DefinitionPopover.Section>
            </>
        )
    }
    if (isDataWarehouse && dataWarehousePopoverFields.length > 0) {
        const _definition = definition as DataWarehouseTableForInsight
        const columnOptions = Object.values(_definition.fields ?? {}).map((column) => ({
            label: column.name + ' (' + column.type + ')',
            value: column.name,
            type: column.type,
        }))
        const hogqlOption = { label: 'SQL Expression', value: '' }
        const itemValue = localDefinition ? group?.getValue?.(localDefinition) : null

        const isUsingHogQLExpression = (value: string | undefined): boolean => {
            if (value === undefined) {
                return false
            }
            const column = Object.values(_definition.fields ?? {}).find((n) => n.name == value)
            return !column
        }

        return (
            <form className="definition-popover-data-warehouse-schema-form">
                <div className="flex flex-col justify-between gap-4">
                    <DefinitionPopover.Section>
                        {dataWarehousePopoverFields.map(
                            ({
                                key,
                                label,
                                description,
                                allowHogQL,
                                hogQLOnly,
                                tableName,
                                optional,
                                type,
                            }: DataWarehousePopoverField) => {
                                const fieldValue = isKeyOf(key, localDefinition) ? localDefinition[key] : undefined
                                const isHogQL = isUsingHogQLExpression(fieldValue ?? undefined)

                                return (
                                    <Fragment key={key}>
                                        <label className="definition-popover-edit-form-label" htmlFor={key}>
                                            <span
                                                className={cn('label-text', {
                                                    'font-semibold': !optional,
                                                })}
                                            >
                                                {label}
                                                {!optional && <span className="text-muted">&nbsp;*</span>}
                                            </span>
                                            {description && (
                                                <Tooltip title={description}>
                                                    &nbsp;
                                                    <IconInfo className="ml-1" />
                                                </Tooltip>
                                            )}
                                        </label>
                                        {!hogQLOnly && (
                                            <LemonInputSelect
                                                mode="single"
                                                fullWidth
                                                placeholder="Select a column"
                                                value={isHogQL ? [''] : fieldValue != null ? [fieldValue] : null}
                                                options={[
                                                    ...columnOptions
                                                        .filter((col) => !type || col.type === type)
                                                        .map((col) => ({
                                                            key: col.value,
                                                            label: col.label,
                                                            value: col.value,
                                                        })),
                                                    ...(allowHogQL
                                                        ? [
                                                              {
                                                                  key: hogqlOption.value,
                                                                  label: hogqlOption.label,
                                                                  value: hogqlOption.value,
                                                              },
                                                          ]
                                                        : []),
                                                ]}
                                                onChange={(value) =>
                                                    setLocalDefinition({ [key]: value.length > 0 ? value[0] : null })
                                                }
                                            />
                                        )}
                                        {((allowHogQL && isHogQL) || hogQLOnly) && (
                                            <HogQLDropdown
                                                hogQLValue={fieldValue || ''}
                                                tableName={tableName || _definition.name}
                                                onHogQLValueChange={(value) => setLocalDefinition({ [key]: value })}
                                            />
                                        )}
                                    </Fragment>
                                )
                            }
                        )}
                    </DefinitionPopover.Section>
                    <div className="flex justify-end">
                        <LemonButton
                            onClick={() => {
                                selectItem(group, itemValue ?? null, localDefinition)
                            }}
                            disabledReason={
                                dataWarehousePopoverFields.every(
                                    ({ key, optional }: DataWarehousePopoverField) =>
                                        optional || (isKeyOf(key, localDefinition) && localDefinition[key])
                                )
                                    ? null
                                    : 'All required field mappings must be specified'
                            }
                            type="primary"
                        >
                            Select
                        </LemonButton>
                    </div>
                </div>
            </form>
        )
    }
    return <></>
}

function DefinitionEdit(): JSX.Element {
    const {
        definition,
        localDefinition,
        definitionLoading,
        singularType,
        isViewable,
        hideView,
        type,
        dirty,
        viewFullDetailUrl,
        isProperty,
    } = useValues(definitionPopoverLogic)
    const { setLocalDefinition, handleCancel, handleSave } = useActions(definitionPopoverLogic)

    if (!definition) {
        return <></>
    }

    const showHiddenOption = 'hidden' in localDefinition
    const allowVerification = !isCoreFilter(definition.name || '') && 'verified' in localDefinition

    return (
        <>
            <LemonDivider className="DefinitionPopover my-4" />
            <form className="definition-popover-edit-form">
                {definition && 'description' in localDefinition && (
                    <>
                        <label className="definition-popover-edit-form-label" htmlFor="description">
                            <span className="label-text">Description</span>
                            <span className="text-secondary">(optional)</span>
                        </label>
                        <LemonTextArea
                            id="description"
                            className="definition-popover-edit-form-value"
                            autoFocus
                            placeholder={`Add a description for this ${singularType}.`}
                            value={localDefinition.description || ''}
                            onChange={(value) => setLocalDefinition({ description: value })}
                            minRows={3}
                            maxRows={4}
                            data-attr="definition-popover-edit-description"
                        />
                    </>
                )}
                {definition && 'tags' in localDefinition && (
                    <>
                        <label className="definition-popover-edit-form-label" htmlFor="description">
                            <span className="label-text">Tags</span>
                            <span className="text-secondary">(optional)</span>
                        </label>
                        <div className="definition-popover-tags">
                            <ObjectTags
                                className="definition-popover-edit-form-value"
                                tags={localDefinition.tags || []}
                                onChange={(tags) => setLocalDefinition({ tags })}
                                saving={false}
                            />
                        </div>
                    </>
                )}
                {definition && definition.name && (showHiddenOption || allowVerification) && (
                    <div className="mb-4">
                        <PropertyStatusControl
                            isProperty={isProperty}
                            verified={!!localDefinition.verified}
                            hidden={!!(localDefinition as Partial<PropertyDefinition>).hidden}
                            onChange={({ verified, hidden }) => {
                                setLocalDefinition({ verified, hidden } as Partial<PropertyDefinition>)
                            }}
                            compact
                            showHiddenOption={showHiddenOption}
                            allowVerification={allowVerification}
                        />
                    </div>
                )}
                <LemonDivider className="DefinitionPopover mt-0" />
                <div className="flex items-center justify-between gap-2 click-outside-block">
                    {!hideView && isViewable && viewFullDetailUrl && type !== TaxonomicFilterGroupType.Events ? (
                        <LemonButton
                            sideIcon={<IconOpenInNew style={{ marginLeft: 4, fontSize: '1rem' }} />}
                            disabledReason={definitionLoading ? 'Loading…' : undefined}
                            type="secondary"
                            size="small"
                            to={viewFullDetailUrl}
                            targetBlank
                        >
                            More options
                        </LemonButton>
                    ) : (
                        <div className="flex-1" />
                    )}
                    <div className="flex items-center">
                        <LemonButton
                            onClick={handleCancel}
                            className=" mr-2"
                            disabledReason={definitionLoading ? 'Loading…' : undefined}
                            type="secondary"
                            size="small"
                        >
                            Cancel
                        </LemonButton>
                        <LemonButton
                            type="primary"
                            onClick={handleSave}
                            disabledReason={!dirty ? 'No changes to save' : undefined}
                            loading={definitionLoading}
                            size="small"
                        >
                            Save
                        </LemonButton>
                    </div>
                </div>
            </form>
        </>
    )
}

interface ControlledDefinitionPopoverContentsProps {
    visible: boolean
    item: TaxonomicDefinitionTypes
    group: TaxonomicFilterGroup
    highlightedItemElement: HTMLDivElement | null
    definitionPopoverRenderer?: DefinitionPopoverRenderer
}

export function ControlledDefinitionPopover({
    visible,
    item,
    group,
    highlightedItemElement,
    definitionPopoverRenderer,
}: ControlledDefinitionPopoverContentsProps): JSX.Element | null {
    const { state, singularType } = useValues(definitionPopoverLogic)
    const { setDefinition } = useActions(definitionPopoverLogic)

    // Not definition: the effect below syncs it after render, so for one render it can hold another group's
    // row, and a getIcon that reads its own row shape ("On this page" reads option.icon) then crashes.
    const icon = group.getIcon?.(item)

    // Supports all types specified in selectedItemHasPopover
    // Pinned items store minimal data ({ name }) so the source group's getValue may not
    // work (e.g. EventMetadata uses option.id). Fall back to item.name for pinned items.
    const value = group.getValue?.(item) ?? ('name' in item ? item.name : null)

    // Hydrate popover card with the newest item. Compare by value identity (not reference)
    // to avoid cascading re-renders when taxonomicGroups re-evaluates and creates new item
    // objects with the same logical identity.
    useEffect(() => {
        setDefinition(item)
    }, [value, setDefinition]) // eslint-disable-line react-hooks/exhaustive-deps

    if (!value || !item) {
        return null
    }

    const defaultView = <DefinitionView group={group} />
    const customView = definitionPopoverRenderer?.({ item, group, defaultView }) ?? defaultView
    const isDataWarehouseFunnelWidePopover =
        group.type === TaxonomicFilterGroupType.DataWarehouse && customView !== defaultView

    return (
        <Popover
            visible={visible}
            referenceElement={highlightedItemElement}
            className={cn('click-outside-block hotkey-block', {
                'definition-popover--data-warehouse-funnel-wide': isDataWarehouseFunnelWidePopover,
            })}
            overlay={
                <DefinitionPopover.Wrapper>
                    <DefinitionPopover.Header
                        title={
                            <PropertyKeyInfo
                                value={item.name ?? ''}
                                type={group.type}
                                disablePopover
                                disableIcon={!!icon}
                                ellipsis={false}
                            />
                        }
                        headerTitle={group.getPopoverHeader?.(item)}
                        editHeaderTitle={`Edit ${singularType}`}
                        icon={icon}
                    />
                    {state === DefinitionPopoverState.Edit ? <DefinitionEdit /> : customView}
                </DefinitionPopover.Wrapper>
            }
            placement="right"
            fallbackPlacements={['left']}
            middleware={[hide()]} // Hide the definition popover when the reference is off-screen
        />
    )
}