: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import './PersonsModal.scss'
import { useActions, useValues } from 'kea'
import React, { useCallback, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { IconCollapse, IconExpand } from '@posthog/icons'
import {
LemonBadge,
LemonBanner,
LemonButton,
LemonDivider,
LemonInput,
LemonModal,
LemonModalProps,
LemonSelect,
LemonSkeleton,
Link,
} from '@posthog/lemon-ui'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { PropertiesTable } from 'lib/components/PropertiesTable'
import { PropertiesTimeline } from 'lib/components/PropertiesTimeline'
import { consumePersonsModalClick } from 'lib/components/ResultMenu/personsModalCapture'
import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'
import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'
import { IconPlayCircle } from 'lib/lemon-ui/icons'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { isGroupType, isSessionType } from 'lib/utils/guards'
import { capitalizeFirstLetter, midEllipsis, pluralize } from 'lib/utils/strings'
import { InsightErrorState, InsightValidationError } from 'scenes/insights/EmptyStates'
import { isOtherBreakdown } from 'scenes/insights/utils'
import { teamLogic } from 'scenes/teamLogic'
import { isSharedView } from '~/exporter/exporterViewLogic'
import { Noun } from '~/models/groupsModel'
import { MAX_SELECT_RETURNED_ROWS } from '~/queries/nodes/DataTable/DataTableExport'
import { extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'
import { FunnelsActorsQuery, InsightActorsQuery, NodeKind } from '~/queries/schema/schema-general'
import {
AccessControlLevel,
AccessControlResourceType,
ActorType,
ExporterFormat,
PropertyDefinitionType,
} from '~/types'
import { GroupActorDisplay, groupDisplayId } from 'products/persons/frontend/components/GroupActorDisplay'
import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'
import { asDisplay, pickBestPersonDistinctId } from 'products/persons/frontend/person-utils'
import {
cleanedInsightActorsQueryOptions,
funnelBreakdownSelectValue,
funnelStepBreakdownFromSelectValue,
} from './persons-modal-utils'
import { PersonModalLogicProps, personsModalLogic } from './personsModalLogic'
import { SaveCohortModal } from './SaveCohortModal'
import { SessionActorDisplay } from './SessionActorDisplay'
export interface PersonsModalProps extends PersonModalLogicProps, Pick<LemonModalProps, 'inline'> {
onAfterClose?: () => void
urlsIndex?: number
urls?: {
label: string | JSX.Element
value: string
}[]
title: React.ReactNode | ((actorLabel: string) => React.ReactNode)
}
export function PersonsModal({
url: _url,
urlsIndex,
urls,
query: _query,
title,
onAfterClose,
inline,
additionalSelect,
orderBy,
}: PersonsModalProps): JSX.Element {
const [selectedUrlIndex, setSelectedUrlIndex] = useState(urlsIndex || 0)
const originalUrl = (urls || [])[selectedUrlIndex]?.value || _url || ''
const logic = personsModalLogic({
url: originalUrl,
query: _query,
additionalSelect,
orderBy,
})
const {
query,
actors,
actorsResponseLoading,
actorsResponse,
errorObject,
validationError,
insightActorsQueryOptions,
searchTerm,
actorLabel,
isCohortModalOpen,
isModalOpen,
missingActorsCount,
propertiesTimelineQuery,
insightEventsQueryUrl,
exploreUrl,
actorsQuery,
recordingFilters,
} = useValues(logic)
const { updateActorsQuery, setSearchTerm, saveAsCohort, setIsCohortModalOpen, closeModal, loadNextActors } =
useActions(logic)
const { currentTeam } = useValues(teamLogic)
const { startExport } = useActions(exportsLogic)
// Creating an export requires editor access to the export resource.
const exportAccessControlDisabledReason = getAccessControlDisabledReason(
AccessControlResourceType.Export,
AccessControlLevel.Editor
)
const totalActorsCount = missingActorsCount + actors.length
type ActorsQuery = NonNullable<typeof query>
const asLemonSelectValue = (value: unknown): string | number | boolean | null =>
typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? value : null
const getTitle = useCallback(() => {
if (typeof title === 'function') {
return title(capitalizeFirstLetter(actorLabel.plural))
}
if (isOtherBreakdown(title)) {
return 'Other'
}
return title
}, [title, actorLabel.plural])
const hasGroups = actors.some((actor) => isGroupType(actor))
const hasSessions = actors.some((actor) => isSessionType(actor))
return (
<>
<LemonModal
data-attr="persons-modal"
title={null}
isOpen={isModalOpen}
onClose={closeModal}
onAfterClose={onAfterClose}
simple
width={600}
inline={inline}
>
<LemonModal.Header>
<h3>{getTitle()}</h3>
</LemonModal.Header>
<div className="px-4 py-2">
{actorsResponse && !!missingActorsCount && !hasGroups && (
<MissingPersonsAlert actorLabel={actorLabel} missingActorsCount={missingActorsCount} />
)}
<LemonInput
type="search"
placeholder={
hasGroups
? 'Search for groups by name or ID'
: hasSessions
? 'Search for sessions by person email or name'
: 'Search for persons by email, name, or ID'
}
fullWidth
value={searchTerm}
onChange={setSearchTerm}
className="my-2"
/>
{urls ? (
<LemonSelect
fullWidth
className="mb-2"
value={selectedUrlIndex}
onChange={(v) => {
if (v !== null && v >= 0) {
setSelectedUrlIndex(v)
}
}}
options={(urls || []).map((url, index) => ({
value: index,
label: url.label,
}))}
/>
) : null}
{query &&
cleanedInsightActorsQueryOptions(insightActorsQueryOptions, query).map(([key, options]) => {
if (query.kind === NodeKind.FunnelsActorsQuery) {
// Funnel actor queries use their own field names (funnelStepBreakdown),
// and Baseline maps to "no breakdown filter".
if (key === 'breakdown' && options.length > 1) {
return (
<div key={key}>
<LemonSelect
fullWidth
className="mb-2"
value={funnelBreakdownSelectValue(query.funnelStepBreakdown, options)}
onChange={(v) =>
updateActorsQuery({
funnelStepBreakdown: funnelStepBreakdownFromSelectValue(v),
})
}
options={options}
/>
</div>
)
}
if (key === 'compare' && options.length > 1) {
return (
<div key={key}>
<LemonSelect
fullWidth
className="mb-2"
value={query.compare ?? 'current'}
onChange={(v) =>
v &&
updateActorsQuery({
compare: v as FunnelsActorsQuery['compare'],
})
}
options={options}
/>
</div>
)
}
// The step (and converted/dropped status) is fixed at click time.
return null
}
return key === 'breakdowns'
? options.map(({ values }, index) => (
<div key={`${key}_${index}`}>
<LemonSelect
fullWidth
className="mb-2"
value={Array.isArray(query.breakdown) ? query.breakdown[index] : null}
onChange={(v) => {
if (!v) {
return
}
const breakdown = Array.isArray(query.breakdown)
? [...query.breakdown]
: []
breakdown[index] = v.toString()
updateActorsQuery({ breakdown })
}}
options={values}
/>
</div>
))
: options.length > 1 && (
<div key={key}>
<LemonSelect
fullWidth
className="mb-2"
value={asLemonSelectValue(query[key as keyof ActorsQuery])}
onChange={(v) => updateActorsQuery({ [key]: v })}
options={options}
/>
</div>
)
})}
<div className="flex items-center justify-between gap-2 text-secondary">
<div className="flex items-center gap-2">
{actorsResponseLoading ? (
<>
<Spinner />
<span>Loading {actorLabel.plural}...</span>
</>
) : (
<span>
{actorsResponse?.next || actorsResponse?.offset ? 'More than ' : ''}
<span className="font-semibold text-default">
{totalActorsCount || 'No'} unique{' '}
{pluralize(totalActorsCount, actorLabel.singular, actorLabel.plural, false)}
</span>
</span>
)}
</div>
<ViewRecordingsPlaylistButton
filters={recordingFilters}
size="small"
type="secondary"
tooltip={
<>
View all recordings for <strong>{getTitle()}</strong>
</>
}
onClick={() => {}}
/>
</div>
</div>
<div className="px-4 overflow-hidden flex flex-col">
<div className="relative min-h-20 p-2 deprecated-space-y-2 rounded bg-border-light overflow-y-auto mb-2">
{errorObject ? (
validationError ? (
<InsightValidationError
query={query}
detail={validationError}
validationErrorCode={extractValidationErrorCode(errorObject)}
/>
) : (
<InsightErrorState query={query} />
)
) : actors && actors.length > 0 ? (
<>
{actors.map((actor) => (
<ActorRow
key={actor.id}
actor={actor}
// created_at is null for actors without a PostgreSQL Person record
// (personless mode, merged, or deleted persons) — skip the
// timeline which would 404, and show static properties instead.
propertiesTimelineQuery={
actor.type == 'person' &&
actor.created_at &&
currentTeam?.person_on_events_querying_enabled
? (propertiesTimelineQuery ?? undefined)
: undefined
}
/>
))}
</>
) : actorsResponseLoading ? (
<div className="deprecated-space-y-3">
<LemonSkeleton active={false} className="h-4 w-full" />
<LemonSkeleton active={false} className="h-4 w-3/5" />
</div>
) : (
<div className="text-center p-5" data-attr="persons-modal-no-matches">
We couldn't find any matching {actorLabel.plural} for this data point.
</div>
)}
{(actorsResponse?.next || actorsResponse?.offset) && (
<div className="m-4 flex justify-center">
<LemonButton type="primary" onClick={loadNextActors} loading={actorsResponseLoading}>
Load more {actorLabel.plural}
</LemonButton>
</div>
)}
</div>
</div>
<LemonModal.Footer>
<div className="flex justify-between gap-2 w-full">
<div className="flex gap-2">
{actors.length > 0 && (
<LemonButton
type="secondary"
onClick={() => {
startExport({
export_format: ExporterFormat.CSV,
export_context: query
? {
source: {
...actorsQuery,
select: actorsQuery!.select?.filter(
(c) => c !== 'matched_recordings'
),
source: { ...actorsQuery!.source, includeRecordings: false },
},
}
: { path: originalUrl },
})
}}
tooltip={`Up to ${MAX_SELECT_RETURNED_ROWS} persons will be exported`}
disabledReason={exportAccessControlDisabledReason ?? undefined}
data-attr="person-modal-download-csv"
>
Download CSV
</LemonButton>
)}
{actors.length > 0 && !isGroupType(actors[0]) && !hasSessions && (
<LemonButton
onClick={() => setIsCohortModalOpen(true)}
type="secondary"
data-attr="person-modal-save-as-cohort"
disabled={!actors.length}
>
Save as cohort
</LemonButton>
)}
</div>
<div className="flex gap-2">
{insightEventsQueryUrl && (
<LemonButton
type="secondary"
to={insightEventsQueryUrl}
data-attr="person-modal-view-events"
onClick={() => {
closeModal()
}}
targetBlank
>
View events
</LemonButton>
)}
{exploreUrl && (
<LemonButton
type="primary"
to={exploreUrl}
data-attr="person-modal-new-insight"
onClick={() => {
closeModal()
}}
>
Open as new insight
</LemonButton>
)}
</div>
</div>
</LemonModal.Footer>
</LemonModal>
<SaveCohortModal
onSave={(title) => saveAsCohort(title)}
onCancel={() => setIsCohortModalOpen(false)}
isOpen={isCohortModalOpen}
/>
</>
)
}
interface ActorRowProps {
actor: ActorType
/** The clicked data point's actors query, when the timeline supports it and the actor is a person. */
propertiesTimelineQuery?: InsightActorsQuery
}
export function ActorRow({ actor, propertiesTimelineQuery }: ActorRowProps): JSX.Element {
const [expanded, setExpanded] = useState(false)
const [tab, setTab] = useState('properties')
const isSession = isSessionType(actor)
const name = isGroupType(actor)
? groupDisplayId(actor.group_key, actor.properties)
: isSession && actor.person
? asDisplay(actor.person)
: asDisplay(actor)
// The most human-readable distinct ID, for the person row's copyable subtitle
const bestDistinctId =
!isGroupType(actor) && !isSessionType(actor) ? pickBestPersonDistinctId(actor.distinct_ids) : undefined
const onOpenRecordingClick = (): void => {
if (!actor.matched_recordings) {
return
}
if (actor.matched_recordings?.length > 1) {
setExpanded(true)
setTab('recordings')
}
}
const matchedRecordings = actor.matched_recordings || []
return (
<div className="relative border rounded bg-surface-primary">
<div className="flex items-center gap-2 p-2">
<LemonButton
noPadding
active={expanded}
onClick={() => setExpanded(!expanded)}
icon={expanded ? <IconCollapse /> : <IconExpand />}
title={expanded ? 'Show less' : 'Show more'}
data-attr={`persons-modal-expand-${actor.id}`}
/>
{!isSession && <ProfilePicture name={name} size="md" />}
<div className="flex-1 overflow-hidden">
{isGroupType(actor) ? (
<div className="font-bold">
<GroupActorDisplay actor={actor} />
</div>
) : isSession ? (
<SessionActorDisplay actor={actor} />
) : (
<>
<div className="font-bold flex items-start">
<PersonDisplay person={actor} withIcon={false} />
</div>
{bestDistinctId && (
<CopyToClipboardInline
explicitValue={bestDistinctId}
iconStyle={{ color: 'var(--color-accent)' }}
iconPosition="end"
className="text-xs text-secondary"
>
{midEllipsis(bestDistinctId, 32)}
</CopyToClipboardInline>
)}
</>
)}
</div>
{isSession ? (
<ViewRecordingButton
sessionId={actor.id}
checkIfViewed={true}
type="secondary"
size="small"
openPlayerIn={RecordingPlayerType.Modal}
hasRecording={true}
/>
) : matchedRecordings.length > 1 ? (
<div className="shrink-0">
<LemonButton
onClick={onOpenRecordingClick}
sideIcon={matchedRecordings.length === 1 ? <IconPlayCircle /> : null}
type="secondary"
status={matchedRecordings.length > 1 ? 'alt' : undefined}
size="small"
>
{matchedRecordings.length} recordings
</LemonButton>
</div>
) : (
<ViewRecordingButton
sessionId={matchedRecordings[0]?.session_id}
checkIfViewed={matchedRecordings.length > 0}
matchingEvents={
matchedRecordings[0]
? [
{
events: matchedRecordings[0].events,
session_id: matchedRecordings[0].session_id,
},
]
: undefined
}
type="secondary"
size="small"
openPlayerIn={RecordingPlayerType.Modal}
hasRecording={matchedRecordings.length > 0}
/>
)}
</div>
{expanded ? (
<div className="PersonsModal__tabs bg-primary border-t rounded-b">
<LemonTabs
activeKey={tab}
onChange={setTab}
tabs={[
{
key: 'properties',
label: 'Properties',
content:
propertiesTimelineQuery && actor.type === 'person' ? (
<PropertiesTimeline actor={actor} query={propertiesTimelineQuery} />
) : (
<PropertiesTable
type={actor.type as PropertyDefinitionType}
properties={actor.properties}
/>
),
},
...(isSession && actor.person
? [
{
key: 'person',
label: 'Person',
content: (
<PropertiesTable
type={PropertyDefinitionType.Person}
properties={actor.person.properties}
/>
),
},
]
: [
{
key: 'recordings',
label: 'Recordings',
content: (
<div className="p-2 deprecated-space-y-2 font-medium mt-1">
<div className="flex justify-between items-center px-2">
<span>
{pluralize(matchedRecordings.length, 'matched recording')}
</span>
</div>
<ul className="deprecated-space-y-px">
{matchedRecordings?.length
? matchedRecordings.map((recording, i) => (
<React.Fragment key={i}>
<LemonDivider className="my-0" />
<li>
<ViewRecordingButton
sessionId={recording.session_id}
matchingEvents={[
{
events: recording.events,
session_id: recording.session_id,
},
]}
label={`View recording ${i + 1}`}
checkIfViewed={true}
openPlayerIn={RecordingPlayerType.Modal}
fullWidth={true}
/>
</li>
</React.Fragment>
))
: null}
</ul>
</div>
),
},
]),
]}
/>
</div>
) : null}
{actor.value_at_data_point !== null && (
<Tooltip title={`${name}'s value for this data point.`}>
<LemonBadge.Number
count={actor.value_at_data_point}
maxDigits={Infinity}
position="top-right"
style={{ pointerEvents: 'auto' }}
/>
</Tooltip>
)}
</div>
)
}
export function MissingPersonsAlert({
actorLabel,
missingActorsCount,
}: {
actorLabel: Noun
missingActorsCount: number
}): JSX.Element {
return (
<LemonBanner type="info" className="mb-2">
{missingActorsCount}{' '}
<span>{missingActorsCount > 1 ? `${actorLabel.plural} are` : `${actorLabel.singular} is`}</span> not shown
because they've been merged with those listed, or deleted.{' '}
<Link to="https://posthog.com/docs/how-posthog-works/queries#insights-counting-unique-persons">
Learn more.
</Link>
</LemonBanner>
)
}
export type OpenPersonsModalProps = Omit<PersonsModalProps, 'onClose' | 'onAfterClose'>
export const openPersonsModal = (props: OpenPersonsModalProps): void => {
if (isSharedView()) {
// Shared/exported views authenticate with a sharing token, which can never run the
// person-level queries this modal needs — it would only ever render an error state.
return
}
if (consumePersonsModalClick(props)) {
return
}
const div = document.createElement('div')
const root = createRoot(div)
function destroy(): void {
root.unmount()
if (div.parentNode) {
div.parentNode.removeChild(div)
}
}
document.body.appendChild(div)
root.render(<PersonsModal {...props} onAfterClose={destroy} />)
}