: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
feat(cohorts): collapse the used-in list into a summary line (#101211)
Phil Haack61ca6285bb0e
diff --git a/frontend/src/mocks/jest.ts b/frontend/src/mocks/jest.tsindex ba88b06de7c7..4c088f6f9485 100644--- a/frontend/src/mocks/jest.ts+++ b/frontend/src/mocks/jest.ts@@ -19,7 +19,7 @@ const jestOnlyDefaultHandlers = mocksToHandlers({'/api/projects/:team_id/event_definitions/primary_properties/': { primary_properties: {} },'/api/environments/:team_id/default_release_conditions/': { default_groups: [], enabled: false },// The unhandled-request floor (a paginated `{ results: [] }`) is the wrong shape here and- // would crash UsedInBanner, which reads `feature_flags.results` & co.+ // would crash UsedInSummary, which reads `feature_flags.results` & co.'/api/projects/:team_id/cohorts/:id/used_in/': {feature_flags: { results: [], total: 0, has_more: false },insights: { results: [], total: 0, has_more: false },diff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsxindex 3f31f8ed918e..0b753ca00753 100644--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx@@ -7,12 +7,13 @@ import { expectLogic, partial } from 'kea-test-utils'import { cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'import { NEW_COHORT } from 'scenes/cohorts/CohortFilters/constants'import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'+import { urls } from 'scenes/urls'import { toPaginatedResponse } from '~/mocks/handlers'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { mockCohort } from '~/test/mocks'-import { AnyCohortCriteriaType, BehavioralEventType, FilterLogicalOperator } from '~/types'+import { AnyCohortCriteriaType, BehavioralEventType, FilterLogicalOperator, InsightShortId } from '~/types'import { CohortEdit } from './CohortEdit'@@ -546,6 +547,73 @@ describe('cohortEditLogic', () => {})})+ describe('used-in summary', () => {+ afterEach(() => {+ cleanup()+ })++ const cohortId = 8+ const cohortName = 'Referenced cohort'+ // 42 insights behind a 2-item page, and a cohorts block nothing references.+ const usedInMocks = {+ get: {+ [`/api/projects/:team_id/cohorts/${cohortId}/`]: {+ ...mockCohort,+ id: cohortId,+ name: cohortName,+ },+ [`/api/projects/:team_id/cohorts/${cohortId}/used_in/`]: {+ feature_flags: {+ results: [{ id: 7, key: 'my-flag', name: 'My flag' }],+ total: 1,+ has_more: false,+ },+ insights: {+ results: [+ { id: 1, short_id: 'abc123', name: 'Weekly signups' },+ { id: 2, short_id: 'def456', name: 'Activation funnel' },+ ],+ total: 42,+ has_more: true,+ },+ cohorts: { results: [], total: 0, has_more: false },+ },+ },+ }++ it('counts every use from the total and leaves the list collapsed', async () => {+ useMocks(usedInMocks)++ render(<CohortEdit id={cohortId} />)++ // Anchored: 42 rather than the 2 results the page carried, and no trailing mention of+ // the cohorts block, which nothing references.+ expect(await screen.findByTestId('cohort-used-in-toggle')).toHaveTextContent(+ /^Used in 1 feature flag and 42 insights$/+ )+ expect(screen.queryByText('Weekly signups')).not.toBeInTheDocument()+ })++ it('reveals the grouped links and the truncation note once expanded', async () => {+ useMocks(usedInMocks)++ render(<CohortEdit id={cohortId} />)++ await userEvent.click(await screen.findByTestId('cohort-used-in-toggle'))++ // The rendered href carries the project prefix these helpers leave off.+ expect(screen.getByText('My flag').closest('a')).toHaveAttribute(+ 'href',+ expect.stringContaining(urls.featureFlag(7))+ )+ expect(screen.getByText('Weekly signups').closest('a')).toHaveAttribute(+ 'href',+ expect.stringContaining(urls.insightView('abc123' as InsightShortId))+ )+ expect(screen.getByText(/2 of 42 shown/)).toBeInTheDocument()+ })+ })+describe('criteria row type switching', () => {afterEach(() => {cleanup()diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsxindex 031afdd56360..2dbe56be868e 100644--- a/frontend/src/scenes/cohorts/CohortEdit.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx@@ -4,7 +4,9 @@ import { router } from 'kea-router'import {IconClock,+ IconCollapse,IconCopy,+ IconExpand,IconInfo,IconRefresh,IconSend,@@ -68,10 +70,17 @@ const POPULATE_FROM_OPTIONS: { label: string; value: StaticCohortMode }[] = [{ label: 'Upload or add people', value: 'people' },]-function UsedInBanner({ usedIn }: { usedIn: CohortUsedInResponseApi }): JSX.Element | null {+interface UsedInSummaryProps {+ usedIn: CohortUsedInResponseApi+ isExpanded: boolean+ setIsExpanded: (expanded: boolean) => void+}++function UsedInSummary({ usedIn, isExpanded, setIsExpanded }: UsedInSummaryProps): JSX.Element | null {const sections = [{title: 'Feature flags',+ noun: 'feature flag',block: usedIn.feature_flags,items: usedIn.feature_flags.results.map((flag) => ({key: `flag-${flag.id}`,@@ -81,6 +90,7 @@ function UsedInBanner({ usedIn }: { usedIn: CohortUsedInResponseApi }): JSX.Elem},{title: 'Insights',+ noun: 'insight',block: usedIn.insights,items: usedIn.insights.results.map((insight) => ({key: `insight-${insight.id}`,@@ -90,6 +100,7 @@ function UsedInBanner({ usedIn }: { usedIn: CohortUsedInResponseApi }): JSX.Elem},{title: 'Cohorts',+ noun: 'cohort',block: usedIn.cohorts,items: usedIn.cohorts.results.map((c) => ({key: `cohort-${c.id}`,@@ -103,27 +114,43 @@ function UsedInBanner({ usedIn }: { usedIn: CohortUsedInResponseApi }): JSX.Elemreturn null}+ // `total` counts every use, while `results` stops at the API's truncation cap.+ const counts = sections.map(({ block, noun }) => `${block.total} ${noun}${block.total === 1 ? '' : 's'}`)+ const summary = counts.length > 1 ? `${counts.slice(0, -1).join(', ')} and ${counts[counts.length - 1]}` : counts[0]+return (- <LemonBanner type="info">- <h4 className="font-semibold mb-1">Used in</h4>- <div className="space-y-2">- {sections.map(({ title, block, items }) => (- <div key={title}>- <h5 className="text-xs font-semibold uppercase opacity-60 mb-0">- {title}- {block.has_more && ` (${block.results.length} of ${block.total} shown)`}- </h5>- <ul className="list-disc pl-4 mb-0 space-y-0.5">- {items.map(({ key, url, label }) => (- <li key={key}>- <Link to={url}>{label}</Link>- </li>- ))}- </ul>- </div>- ))}- </div>- </LemonBanner>+ <div className="flex flex-col gap-y-1" data-attr="cohort-used-in">+ <LemonButton+ size="small"+ type="tertiary"+ icon={isExpanded ? <IconCollapse /> : <IconExpand />}+ onClick={() => setIsExpanded(!isExpanded)}+ aria-expanded={isExpanded}+ className="self-start"+ data-attr="cohort-used-in-toggle"+ >+ Used in {summary}+ </LemonButton>+ {isExpanded && (+ <div className="max-h-60 overflow-y-auto flex flex-col gap-y-2 pl-2">+ {sections.map(({ title, block, items }) => (+ <div key={title}>+ <h5 className="text-xs font-semibold uppercase opacity-60 mb-0">+ {title}+ {block.has_more && ` (${block.results.length} of ${block.total} shown)`}+ </h5>+ <ul className="list-disc pl-4 mb-0">+ {items.map(({ key, url, label }) => (+ <li key={key}>+ <Link to={url}>{label}</Link>+ </li>+ ))}+ </ul>+ </div>+ ))}+ </div>+ )}+ </div>)}@@ -178,6 +205,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {setCreationPersonQuery,setStaticCohortMode,setActiveTab,+ setUsedInExpanded,submitCohort,} = useActions(logic)const modalLogic = addPersonToCohortModalLogic(logicProps)@@ -193,6 +221,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {isPendingCalculation,isCalculatingOrPending,usedIn,+ usedInExpanded,staticCohortMode,activeTab,} = useValues(logic)@@ -562,6 +591,14 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {) : null}</div>)}++ {!isNewCohort && usedIn && (+ <UsedInSummary+ usedIn={usedIn}+ isExpanded={usedInExpanded}+ setIsExpanded={setUsedInExpanded}+ />+ )}</div></div></SceneSection>@@ -570,7 +607,6 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {<UnmatchedImportBanner cohort={cohort} /></div>)}- {!isNewCohort && usedIn && <UsedInBanner usedIn={usedIn} />}{cohort.is_static && staticCohortMode === 'criteria' ? (<><SceneDivider />diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.tsindex 7d0aa5aa5dbf..2af0d8e5ed20 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts@@ -130,6 +130,7 @@ export interface cohortEditLogicValues {showCohortErrors: booleanstaticCohortMode: StaticCohortModeusedIn: CohortUsedInResponseApi | null+ usedInExpanded: booleanusedInLoading: boolean}@@ -383,6 +384,9 @@ export interface cohortEditLogicActions {setStaticCohortMode: (mode: StaticCohortMode) => {mode: StaticCohortMode}+ setUsedInExpanded: (expanded: boolean) => {+ expanded: boolean+ }submitCohort: () => {value: boolean}@@ -538,6 +542,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([refreshPersonsData: true,setStaticCohortMode: (mode: StaticCohortMode) => ({ mode }),setActiveTab: (tab: CohortEditTab) => ({ tab }),+ setUsedInExpanded: (expanded: boolean) => ({ expanded }),}),reducers(({ props }) => ({@@ -744,6 +749,12 @@ export const cohortEditLogic = kea<cohortEditLogicType>([setActiveTab: (_, { tab }) => tab,},],+ usedInExpanded: [+ false,+ {+ setUsedInExpanded: (_, { expanded }) => expanded,+ },+ ],})),selectors({