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.

feat(flags): show release conditions in flag history (#93773)

Sandy Spicerf38bf85d3d78
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6a5797afee62..3be8c64b7c2e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -85,9 +85,9 @@ snapshots:
components-activitylog--data-management-activity--light:
hash: v1.k794b7964.2de1f2b9f7ac1b902c9e2e0c43867770ae703abc07bf397d62f173171f0f3e97.EcZZDXwHHM4LaBsE1yChqI_9TBtDIflrBdz6OTtFjxE
components-activitylog--feature-flag-activity--dark:
- hash: v1.k794b7964.c50aafdb46bf983f33df0daaa56957997bffcbc7a744dd044127c04d88102125.w2ylz_uEGIEYNAdzFm01XLwEb5nSscju_qU8Wk7Zb_E
+ hash: v1.k794b7964.1dac32db25d6d76a6d02953093f1e0a0368ca8ef009faba9b01250b8da223a95.VyKy0x-jtdoLlv3B-3p4xplcbAU6jyk9HbuRDdZG1Fo
components-activitylog--feature-flag-activity--light:
- hash: v1.k794b7964.5a8358a3bb67728abcc71ec423255206af014e13d1d95aaeaf2daba16bc96b45.tMsr51f9bhJSycyXPJYsOjM-kNAGQI2hFI3CbJBoyOk
+ hash: v1.k794b7964.4d0ea9b5e240664f5a1bfd696d07d1a4eea152567cd3ee16af963ecd9ab31cb9.XFh5MPIIt4FV_pf16hgPtmBadov5zGa6jA8s1AOfzrU
components-activitylog--insight-activity--dark:
hash: v1.k794b7964.eeb2e5b54ba0acf05e292aba372702616dc9c6326fd8bcbf4bbf1125fcb7c637.XMwf5MqrlV-FQsYrL-4Db38vN69QQAmBms5tmbFQlSw
components-activitylog--insight-activity--light:
@@ -101,9 +101,9 @@ snapshots:
components-activitylog--team-activity--light:
hash: v1.k794b7964.10d5353835f51b3db0c19a80aa9f457523e6d698389a02b72bdf360a636807bd.2Fjfwjkw22VkdyEm_oYP64jgiEZbtSYUV2P_snheeHU
components-activitylog--with-caption--dark:
- hash: v1.k794b7964.d47109e68a75102903a3c0773b280d888a6f18b25a2ab5521d7cf210231c4098.n9Ph9PHPw6LDyrJ47TifVEyeqocAj-YdQskRnJjleD8
+ hash: v1.k794b7964.9188cd8eecfbe14ff000a4daa237858f90d02667c76ae4e40bf902857fb2f407.USkSSkFqRGXtN-wH8cetAwOqFKH0nFnXKh6tjRx5zOc
components-activitylog--with-caption--light:
- hash: v1.k794b7964.20e59716d386749675ff10e2b6c84b703463050f22196c15e5f326ee44483b25.WjQBpdfxfDuHG4dJ4KrYa1loSG5opyt9wD-rftojrJM
+ hash: v1.k794b7964.38803a04d4ae34e0901aae419866fd1571d06cba43aa585374450efa5dbbb654.EocQNZd4xc-hKDaksq_LzruooC1nBMisuTV5xL0kTCc
components-activitylog--with-no-data--dark:
hash: v1.k794b7964.a639d0f489ca1519634969688cbadae4ebd9e977221b2d85594dfd793e494a57.A1Sl4bZi1PZr56FFNlP4SIy-lCtzRdRgPQOgtyiPdSs
components-activitylog--with-no-data--light:
@@ -7536,6 +7536,14 @@ snapshots:
hash: v1.k794b7964.b21df130430a104352e31173ae34feb16146f03d0688631d35f78052114fd3e7.GA0QgvUydkp96bBYC1RIiHsKN8O6Z_3nX1PXnfaBgeA
scenes-app-feature-flags-new-feature-flag-menu--default--light:
hash: v1.k794b7964.c58d12ddf9499563916bb71f41ff70dce9db471379ef2215c8b57a0ac88aa76c.jl03AgPo8iB46wC9k3xNkQwobb5SLJcSwYnOphJUt8Y
+ scenes-app-feature-flags-release-conditions-change--rollout-changed--dark:
+ hash: v1.k794b7964.1f1d0f0e4e314ca8790886541b58a532cea78a5dbb084cac9c59ee1f95927191._DqpNipdJm-6BYmEuAoL70krke_FnrxMK3bD0NPVN78
+ scenes-app-feature-flags-release-conditions-change--rollout-changed--light:
+ hash: v1.k794b7964.aa56849ff36f2f55c82c04ec678a37afd4d1b3ca20970dcf60b835cd7cb12928.twPzdzqJgb4Xqe1hN2i5xtRhDBoS6qVbgBfiEdsz2K8
+ scenes-app-feature-flags-release-conditions-change--sets-added-changed-and-removed--dark:
+ hash: v1.k794b7964.cd29e02235eef94b7f08eb8051b994244d80717b79920541be8e363240ff3576.ux8ofOEupuUEzUdKeNtQ_wJ4QanPv8O_VbXH5QzCVBo
+ scenes-app-feature-flags-release-conditions-change--sets-added-changed-and-removed--light:
+ hash: v1.k794b7964.48c78c2c3734564b9dbfbc50054091eea724ddfcfe3a8b497da1631d8a49eb5c.f8xu60hg7HwMtKcEHj3IRvx-ATgV7o_gmMQsVpP-wzs
scenes-app-feature-flags-request-usage-summary-card--billing-units--dark:
hash: v1.k794b7964.4bee55e405082cc86dbd6cbaeb89cc1d583174707ba34ebcd95648ad8c32658a.yMqVeg0qnl7x4i2wG3eomTFBZVXVSQCdgHVkoY70t0A
scenes-app-feature-flags-request-usage-summary-card--billing-units--light:
diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsx
new file mode 100644
index 000000000000..eb338de51259
--- /dev/null
+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsx
@@ -0,0 +1,35 @@
+import '@testing-library/jest-dom'
+
+import { fireEvent, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { ActivityLogRow } from 'lib/components/ActivityLog/ActivityLog'
+import { HumanizedActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
+import { dayjs } from 'lib/dayjs'
+
+import { initKeaTests } from '~/test/init'
+
+describe('ActivityLogRow', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ it('opens an item that has an expanded view on that view', () => {
+ const logItem: HumanizedActivityLogItem = {
+ name: 'peter',
+ description: <>changed the rollout</>,
+ created_at: dayjs('2022-02-05T16:28:39.594Z'),
+ expandedView: { label: 'Release conditions', content: <div>the release conditions</div> },
+ }
+
+ render(
+ <Provider>
+ <ActivityLogRow logItem={logItem} />
+ </Provider>
+ )
+ fireEvent.click(screen.getByRole('button'))
+
+ expect(screen.getByText('Release conditions').closest('[role="tab"]')).toHaveAttribute('aria-selected', 'true')
+ expect(screen.getByText('the release conditions')).toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.tsx
index 63c9c50ede1a..88433e8ef73d 100644
--- a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx
+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.tsx
@@ -78,7 +78,7 @@ const Loading = (): JSX.Element => {
)
}
-export type ActivityLogTabs = 'extended description' | 'diff' | 'raw'
+export type ActivityLogTabs = 'details' | 'extended description' | 'diff' | 'raw'
const ActivityLogDiff = ({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element => {
const changes = logItem.unprocessed?.detail.changes
@@ -143,7 +143,7 @@ export const ActivityLogRow = ({
highlighted?: boolean
}): JSX.Element => {
const [isExpanded, setIsExpanded] = useState(false)
- const [activeTab, setActiveTab] = useState<ActivityLogTabs>('diff')
+ const [activeTab, setActiveTab] = useState<ActivityLogTabs>(logItem.expandedView ? 'details' : 'diff')
const rowRef = useRef<HTMLDivElement>(null)
useEffect(() => {
@@ -237,6 +237,13 @@ export const ActivityLogRow = ({
activeKey={activeTab}
onChange={(key) => setActiveTab(key as ActivityLogTabs)}
tabs={[
+ logItem.expandedView
+ ? {
+ key: 'details',
+ label: logItem.expandedView.label,
+ content: logItem.expandedView.content,
+ }
+ : false,
logItem.extendedDescription
? {
key: 'extended description',
diff --git a/frontend/src/lib/components/ActivityLog/activityLogLogic.feature-flag.test.tsx b/frontend/src/lib/components/ActivityLog/activityLogLogic.feature-flag.test.tsx
index d4fffd7ed37f..c20b61e4c480 100644
--- a/frontend/src/lib/components/ActivityLog/activityLogLogic.feature-flag.test.tsx
+++ b/frontend/src/lib/components/ActivityLog/activityLogLogic.feature-flag.test.tsx
@@ -201,7 +201,7 @@ describe('the activity log logic', () => {
const actual = logic.values.humanizedActivity
expect(render(<>{actual[0]?.description}</>).container).toHaveTextContent(
- 'peter removed 2 release conditions on test flag'
+ 'peter removed 2 condition sets on test flag'
)
})
@@ -252,7 +252,7 @@ describe('the activity log logic', () => {
const actual = logic.values.humanizedActivity
expect(render(<>{actual[0]?.description}</>).container).toHaveTextContent(
- 'peter removed 1 release condition on test flag'
+ 'peter removed the condition set for all users on test flag'
)
})
@@ -296,7 +296,7 @@ describe('the activity log logic', () => {
const actual = logic.values.humanizedActivity
expect(render(<>{actual[0]?.description}</>).container).toHaveTextContent(
- 'peter changed the filter conditions to apply to 30% of all users, and removed 1 release condition on test flag'
+ 'peter removed the condition set for User in ID 98 on test flag'
)
})
@@ -336,7 +336,7 @@ describe('the activity log logic', () => {
const actual = logic.values.humanizedActivity
expect(render(<>{actual[0].description}</>).container).toHaveTextContent(
- 'peter changed the filter conditions to apply to 99% of all users on test flag'
+ 'peter added a condition set for all users at 99% on test flag'
)
})
@@ -378,7 +378,7 @@ describe('the activity log logic', () => {
const actual = logic.values.humanizedActivity
expect(render(<>{actual[0].description}</>).container).toHaveTextContent(
- 'peter changed the filter conditions to apply to 100% of User in ID 98, and 100% of User not in ID 411 on with cohort'
+ 'peter added condition sets for User in ID 98 at 100% and User not in ID 411 at 100% on with cohort'
)
})
@@ -411,8 +411,9 @@ describe('the activity log logic', () => {
const actual = logic.values.humanizedActivity
expect(render(<>{actual[0].description}</>).container).toHaveTextContent(
- 'peter changed the filter conditions to apply to 77% of all users on with simple rollout change'
+ 'peter changed the rollout for all users from 75% to 77% on with simple rollout change'
)
+ expect(actual[0].expandedView?.label).toEqual('Release conditions')
})
it('describes a null rollout percentage as 100%', async () => {
@@ -469,7 +470,7 @@ describe('the activity log logic', () => {
const actual = logic.values.humanizedActivity
expect(render(<>{actual[0].description}</>).container).toHaveTextContent(
- 'peter changed the filter conditions to apply to 100% of Email address = …@somewhere.dev on with null rollout change'
+ 'peter added a condition set for Email address = …@somewhere.dev at 100% on with null rollout change'
)
})
@@ -539,55 +540,121 @@ describe('the activity log logic', () => {
const actual = logic.values.humanizedActivity
expect(render(<>{actual[0].description}</>).container).toHaveTextContent(
- 'peter changed the filter conditions to apply to 76% of Initial browser = Chrome , and 99% of Initial browser version = 100 on with two changes'
+ 'peter changed the rollout for Initial browser = Chrome from 77% to 76% and Initial browser version = 100 from 100% to 99% on with two changes'
)
})
- it('does not mention variant rollout when only release conditions changed', async () => {
+ it.each([
+ {
+ name: 'lists every set at the detail limit',
+ initials: ['a', 'b', 'c'],
+ expected:
+ 'peter changed the rollout for Email address = [email protected] from 50% to 100%, Email address = [email protected] from 50% to 100% and Email address = [email protected] from 50% to 100% on test flag',
+ },
+ {
+ name: 'lists counts instead of every set past the detail limit',
+ initials: ['a', 'b', 'c', 'd'],
+ expected: 'peter changed the rollout for 4 condition sets on test flag',
+ },
+ ])('$name', async ({ initials, expected }) => {
+ const emailSet = (email: string, rollout: number): Record<string, unknown> => ({
+ properties: [{ key: 'email', type: 'person', value: [email], operator: 'exact' }],
+ rollout_percentage: rollout,
+ })
+ const emails = initials.map((initial) => `${initial}@example.com`)
+ const logic = await featureFlagsTestSetup('test flag', 'updated', [
+ {
+ type: ActivityScope.FEATURE_FLAG,
+ action: 'changed',
+ field: 'filters',
+ before: { groups: emails.map((email) => emailSet(email, 50)), multivariate: null },
+ after: { groups: emails.map((email) => emailSet(email, 100)), multivariate: null },
+ },
+ ])
+
+ const actual = logic.values.humanizedActivity
+
+ expect(render(<>{actual[0].description}</>).container).toHaveTextContent(expected)
+ })
+
+ it('counts condition sets whose description changed past the detail limit', async () => {
+ const describedSet = (initial: string, description: string): Record<string, unknown> => ({
+ properties: [{ key: 'email', type: 'person', value: [`${initial}@example.com`], operator: 'exact' }],
+ rollout_percentage: 50,
+ description,
+ })
+ const initials = ['a', 'b', 'c', 'd']
+ const logic = await featureFlagsTestSetup('test flag', 'updated', [
+ {
+ type: ActivityScope.FEATURE_FLAG,
+ action: 'changed',
+ field: 'filters',
+ before: { groups: initials.map((initial) => describedSet(initial, 'before')), multivariate: null },
+ after: { groups: initials.map((initial) => describedSet(initial, 'after')), multivariate: null },
+ },
+ ])
+
+ const actual = logic.values.humanizedActivity
+
+ expect(render(<>{actual[0].description}</>).container).toHaveTextContent(
+ 'peter changed the description of 4 condition sets on test flag'
+ )
+ })
+
+ it('names a set once when its criteria and rollout both change', async () => {
+ const emailSet = (email: string, rollout: number): Record<string, unknown> => ({
+ properties: [{ key: 'email', type: 'person', value: [email], operator: 'exact' }],
+ rollout_percentage: rollout,
+ })
+ const logic = await featureFlagsTestSetup('test flag', 'updated', [
+ {
+ type: ActivityScope.FEATURE_FLAG,
+ action: 'changed',
+ field: 'filters',
+ before: { groups: [emailSet('[email protected]', 75)], multivariate: null },
+ after: { groups: [emailSet('[email protected]', 100)], multivariate: null },
+ },
+ ])
+
+ const container = render(<>{logic.values.humanizedActivity[0].description}</>).container
+
+ expect(container).toHaveTextContent(
+ 'peter changed the criteria for Email address = [email protected] and its rollout from 75% to 100% on test flag'
+ )
+ expect(container.textContent?.match(/Email address = b@example\.com/g)).toHaveLength(1)
+ })
+
+ it('names the variant a condition set moved to without mentioning variant rollout', async () => {
+ const multivariate = {
+ variants: [
+ { key: 'control', rollout_percentage: 100 },
+ { key: 'variant', rollout_percentage: 0 },
+ ],
+ }
const logic = await featureFlagsTestSetup('test flag', 'updated', [
{
type: ActivityScope.FEATURE_FLAG,
action: 'changed',
field: 'filters',
before: {
- groups: [{ variant: null, properties: [], rollout_percentage: 0 }],
+ groups: [{ variant: null, properties: [], rollout_percentage: 20 }],
payloads: {},
- multivariate: {
- variants: [
- { key: 'control', rollout_percentage: 100 },
- { key: 'variant', rollout_percentage: 0 },
- ],
- },
+ multivariate,
},
after: {
- groups: [
- {
- variant: 'variant',
- properties: [
- {
- key: 'created_at_timestamp',
- type: 'person',
- value: '1771344031000',
- operator: 'gt',
- },
- ],
- rollout_percentage: 20,
- },
- ],
+ groups: [{ variant: 'variant', properties: [], rollout_percentage: 20 }],
payloads: {},
- multivariate: {
- variants: [
- { key: 'control', rollout_percentage: 100 },
- { key: 'variant', rollout_percentage: 0 },
- ],
- },
+ multivariate,
},
},
])
const actual = logic.values.humanizedActivity
- const text = render(<>{actual[0].description}</>).container.textContent
- expect(text).not.toContain('changed the rollout percentage for the variants')
+ const container = render(<>{actual[0].description}</>).container
+ expect(container).toHaveTextContent(
+ 'peter changed the variant for all users from none to variant on test flag'
+ )
+ expect(container.textContent).not.toContain('changed the rollout percentage for the variants')
})
it('only lists variants whose rollout percentage actually changed', async () => {
@@ -657,6 +724,31 @@ describe('the activity log logic', () => {
expect(text).not.toContain('changed payload')
})
+ it('offers no release conditions view when only a variant payload changed', async () => {
+ const groups = [{ properties: [], rollout_percentage: 50 }]
+ const multivariate = {
+ variants: [
+ { key: 'control', rollout_percentage: 50 },
+ { key: 'test', rollout_percentage: 50 },
+ ],
+ }
+ const logic = await featureFlagsTestSetup('test flag', 'updated', [
+ {
+ type: ActivityScope.FEATURE_FLAG,
+ action: 'changed',
+ field: 'filters',
+ before: { groups, payloads: { control: 'old' }, multivariate },
+ after: { groups, payloads: { control: 'new' }, multivariate },
+ },
+ ])
+
+ const actual = logic.values.humanizedActivity
+ const text = render(<>{actual[0].description}</>).container.textContent ?? ''
+ expect(text.match(/changed payload/g)).toHaveLength(1)
+ expect(text).toContain('variant: control')
+ expect(actual[0].expandedView).toBeUndefined()
+ })
+
it('can handle changing variants from a multivariate flag', async () => {
const logic = await featureFlagsTestSetup('test flag', 'updated', [
{
@@ -840,6 +932,36 @@ describe('the activity log logic', () => {
)
})
+ it('describes the payload change when the same save removes all variants', async () => {
+ const logic = await featureFlagsTestSetup('test flag', 'updated', [
+ {
+ type: ActivityScope.FEATURE_FLAG,
+ action: 'changed',
+ field: 'filters',
+ before: {
+ groups: [{ properties: [], rollout_percentage: 75 }],
+ payloads: { control: 'a' },
+ multivariate: {
+ variants: [
+ { key: 'control', rollout_percentage: 50 },
+ { key: 'test-1', rollout_percentage: 50 },
+ ],
+ },
+ },
+ after: {
+ groups: [{ properties: [], rollout_percentage: 75 }],
+ payloads: { true: 'b' },
+ multivariate: { variants: [] },
+ },
+ },
+ ])
+
+ const container = render(<>{logic.values.humanizedActivity[0].description}</>).container
+
+ expect(container).toHaveTextContent('changed payload to b')
+ expect(container).toHaveTextContent('removed all variants')
+ })
+
it('can handle removing the last variant from a multivariate flag', async () => {
const logic = await featureFlagsTestSetup('test flag', 'updated', [
{
diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
index 8e1fb42dd460..77ff457bba97 100644
--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
@@ -64,12 +64,19 @@ export type ActivityLogItem = {
export type Description = string | JSX.Element | null
// the extended description gives extra context, like the insight details card to describe a change to an insight
export type ExtendedDescription = JSX.Element | undefined
+// content too large to sit inline with the sentence, shown as its own tab once the row is expanded
+export type ExpandedView = { label: string; content: JSX.Element }
export type ChangeMapping = {
description: Description[] | null
extendedDescription?: ExtendedDescription
+ expandedView?: ExpandedView
suffix?: string | JSX.Element | null // to override the default suffix
}
-export type HumanizedChange = { description: Description | null; extendedDescription?: ExtendedDescription }
+export type HumanizedChange = {
+ description: Description | null
+ extendedDescription?: ExtendedDescription
+ expandedView?: ExpandedView
+}
export type HumanizedActivityLogItem = {
id?: string
@@ -83,6 +90,7 @@ export type HumanizedActivityLogItem = {
client?: string | null
description: Description
extendedDescription?: ExtendedDescription // e.g. an insight's filters summary
+ expandedView?: ExpandedView // e.g. a flag's release conditions after the change
created_at: dayjs.Dayjs
unread?: boolean
// used when showing e.g. diff of changes
@@ -116,7 +124,7 @@ export function humanize(
if (!describer) {
continue
}
- const { description, extendedDescription } = describer(logItem, asNotification)
+ const { description, extendedDescription, expandedView } = describer(logItem, asNotification)
if (description !== null) {
const impersonatedUserName = logItem.user ? fullName(logItem.user) : undefined
@@ -132,6 +140,7 @@ export function humanize(
client: logItem.client,
description,
extendedDescription,
+ expandedView,
created_at: dayjs(logItem.created_at),
unread: logItem.unread,
unprocessed: logItem,
diff --git a/frontend/src/scenes/audit-logs/AuditLogTable.tsx b/frontend/src/scenes/audit-logs/AuditLogTable.tsx
index 1c037d5e7227..a0f6b9b94ada 100644
--- a/frontend/src/scenes/audit-logs/AuditLogTable.tsx
+++ b/frontend/src/scenes/audit-logs/AuditLogTable.tsx
@@ -203,10 +203,10 @@ function ExpandedRowContent({ logItem }: { logItem: HumanizedActivityLogItem }):
)
}
-type ActivityLogTabs = 'extended description' | 'diff' | 'raw'
+type ActivityLogTabs = 'details' | 'extended description' | 'diff' | 'raw'
const ActivityDetailsSection = ({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element => {
- const [activeTab, setActiveTab] = useState<ActivityLogTabs>('diff')
+ const [activeTab, setActiveTab] = useState<ActivityLogTabs>(logItem.expandedView ? 'details' : 'diff')
return (
<LemonTabs
@@ -214,6 +214,13 @@ const ActivityDetailsSection = ({ logItem }: { logItem: HumanizedActivityLogItem
onChange={(key) => setActiveTab(key as ActivityLogTabs)}
data-attr="audit-log-details-tabs"
tabs={[
+ logItem.expandedView
+ ? {
+ key: 'details',
+ label: logItem.expandedView.label,
+ content: logItem.expandedView.content,
+ }
+ : false,
logItem.extendedDescription
? {
key: 'extended description',
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx
index 6dab80533112..2d90f5f8c0ab 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx
@@ -1,33 +1,16 @@
import { useValues } from 'kea'
-import { IconFlag } from '@posthog/icons'
-import { LemonButton, LemonLabel, LemonSnack, LemonTag } from '@posthog/lemon-ui'
+import { LemonLabel, LemonTag } from '@posthog/lemon-ui'
-import { allOperatorsToHumanName } from 'lib/components/DefinitionPopover/utils'
-import { isPropertyFilterWithOperator } from 'lib/components/PropertyFilters/utils'
-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { IconOpenInNew, IconSubArrowRight } from 'lib/lemon-ui/icons'
-import { urls } from 'scenes/urls'
-
-import { getFilterLabel } from '~/taxonomy/helpers'
-import {
- AnyPropertyFilter,
- FeatureFlagEvaluationRuntime,
- FeatureFlagFilters,
- FeatureFlagGroupType,
- PropertyFilterType,
-} from '~/types'
+import { FeatureFlagEvaluationRuntime, FeatureFlagFilters } from '~/types'
+import { FeatureFlagConditionSetCard } from 'products/feature_flags/frontend/FeatureFlagConditionSetCard'
import { FractionalRolloutWarning } from 'products/feature_flags/frontend/FractionalRolloutWarning'
import { EarlyExitIndicator } from './EarlyExitIndicator'
import { FeatureFlagConditionWarning } from './FeatureFlagConditionWarning'
import { FeatureFlagNoConditionsWarning } from './FeatureFlagNoConditionsWarning'
-import {
- featureFlagReleaseConditionsLogic,
- isDistinctIdFilter,
- withResolvedFlagLabels,
-} from './featureFlagReleaseConditionsLogic'
+import { featureFlagReleaseConditionsLogic } from './featureFlagReleaseConditionsLogic'
interface FeatureFlagReleaseConditionsReadonlyProps {
id: string
@@ -36,87 +19,6 @@ interface FeatureFlagReleaseConditionsReadonlyProps {
evaluationRuntime?: FeatureFlagEvaluationRuntime
}
-/** Extract server-provided group_key_names from a property, if present. */
-function getGroupKeyNames(property: AnyPropertyFilter): Record<string, string> {
- if (property.type === PropertyFilterType.Group && 'group_key_names' in property) {
- return (property as any).group_key_names ?? {}
- }
- return {}
-}
-
-function PropertyValueDisplay({
- property,
- getDistinctIdName,
-}: {
- property: AnyPropertyFilter
- getDistinctIdName: (distinctId: string) => string
-}): JSX.Element {
- if (property.type === PropertyFilterType.Cohort) {
- return (
- <LemonButton type="secondary" size="xsmall" to={urls.cohort(property.value)} sideIcon={<IconOpenInNew />}>
- {property.cohort_name || `ID ${property.value}`}
- </LemonButton>
- )
- }
-
- const propertyValues = Array.isArray(property.value) ? property.value : [property.value]
- const groupKeyNames = property.key === '$group_key' ? getGroupKeyNames(property) : {}
- const isDistinctId = isDistinctIdFilter(property)
-
- return (
- <>
- {propertyValues.map((val, idx) => {
- const strVal = String(val)
- const display = isDistinctId ? getDistinctIdName(strVal) : groupKeyNames[strVal] || strVal
- return <LemonSnack key={idx}>{display}</LemonSnack>
- })}
- </>
- )
-}
-
-function PropertyFilterRow({
- property,
- isFirst,
- getDistinctIdName,
-}: {
- property: AnyPropertyFilter
- isFirst: boolean
- getDistinctIdName: (distinctId: string) => string
-}): JSX.Element {
- const propertyLabel =
- property.type === PropertyFilterType.Cohort || property.type === PropertyFilterType.Flag
- ? null
- : getFilterLabel(
- property.key,
- property.type === PropertyFilterType.Person
- ? TaxonomicFilterGroupType.PersonProperties
- : TaxonomicFilterGroupType.EventProperties
- )
-
- const operator = isPropertyFilterWithOperator(property) ? allOperatorsToHumanName(property.operator) : 'equals'
-
- return (
- <div className="flex items-center gap-1.5 flex-wrap text-sm">
- {isFirst ? (
- <LemonButton icon={<IconSubArrowRight className="arrow-right" />} size="small" noPadding />
- ) : (
- <LemonButton icon={<span className="text-xs font-medium">&</span>} size="small" noPadding />
- )}
- {propertyLabel && propertyLabel !== property.key && <span className="text-muted">{propertyLabel}</span>}
- {property.type === PropertyFilterType.Flag ? (
- <LemonSnack>
- <IconFlag className="mr-1" />
- {property.label || property.key}
- </LemonSnack>
- ) : (
- <LemonSnack>{property.type === PropertyFilterType.Cohort ? 'Cohort' : property.key}</LemonSnack>
- )}
- <span className="text-muted">{operator}</span>
- <PropertyValueDisplay property={property} getDistinctIdName={getDistinctIdName} />
- </div>
- )
-}
-
export function FeatureFlagReleaseConditionsReadonly({
id,
filters,
@@ -163,7 +65,7 @@ export function FeatureFlagReleaseConditionsReadonly({
OR
</div>
)}
- <ConditionSetCard
+ <FeatureFlagConditionSetCard
group={group}
index={index}
aggregationTargetName={aggregationTargetName(group.aggregation_group_type_index)}
@@ -178,76 +80,3 @@ export function FeatureFlagReleaseConditionsReadonly({
</div>
)
}
-
-interface ConditionSetCardProps {
- group: FeatureFlagGroupType
- index: number
- aggregationTargetName: string
- getDistinctIdName: (distinctId: string) => string
- getFlagKey: (flagId: string) => string
-}
-
-function ConditionSetCard({
- group,
- index,
- aggregationTargetName,
- getDistinctIdName,
- getFlagKey,
-}: ConditionSetCardProps): JSX.Element {
- const properties = withResolvedFlagLabels(group.properties, getFlagKey)
- const rollout = group.rollout_percentage ?? 100
-
- const getSummary = (): JSX.Element => {
- if (properties.length === 0) {
- return (
- <>
- Condition set will match <b>all {aggregationTargetName}</b>
- </>
- )
- }
- return (
- <>
- Match <b>{aggregationTargetName}</b> against <b>all</b> criteria
- </>
- )
- }
-
- return (
- <div className="border rounded p-4 bg-surface-primary">
- <div className="flex items-center gap-2 flex-wrap">
- <LemonSnack>Set {index + 1}</LemonSnack>
- <span className="text-sm">{getSummary()}</span>
- </div>
-
- {group.description && <div className="mt-2 text-sm text-muted">{group.description}</div>}
-
- {properties.length > 0 && (
- <div className="mt-3 flex flex-col gap-1">
- {properties.map((property, idx) => (
- <PropertyFilterRow
- key={idx}
- property={property}
- isFirst={idx === 0}
- getDistinctIdName={getDistinctIdName}
- />
- ))}
- </div>
- )}
-
- <div className="mt-3">
- <LemonTag type={rollout === 100 ? 'highlight' : rollout === 0 ? 'caution' : 'none'}>
- <span className="text-sm">
- Rolled out to <b className="tabular-nums">{rollout}%</b> of <b>{aggregationTargetName}</b> in
- this set.
- </span>
- </LemonTag>
- </div>
-
- {group.variant && (
- <div className="mt-3 text-sm">
- All <b>{aggregationTargetName}</b> in this set will be in variant <b>{group.variant}</b>
- </div>
- )}
- </div>
- )
-}
diff --git a/frontend/src/scenes/feature-flags/activityDescriptions.tsx b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
index 3fef5e0f55ac..b8aa42877c8d 100644
--- a/frontend/src/scenes/feature-flags/activityDescriptions.tsx
+++ b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
@@ -6,6 +6,7 @@ import {
ActivityLogUserName,
ChangeMapping,
Description,
+ ExpandedView,
HumanizedChange,
defaultDescriber,
detectBoolean,
@@ -17,13 +18,16 @@ import { Link } from 'lib/lemon-ui/Link'
import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
+import { FeatureFlagEvaluationRuntime, FeatureFlagFilters, FeatureFlagGroupType, FeatureFlagType } from '~/types'
+
+import { FeatureFlagReleaseConditionsChange } from 'products/feature_flags/frontend/FeatureFlagReleaseConditionsChange'
import {
- AnyPropertyFilter,
- FeatureFlagEvaluationRuntime,
- FeatureFlagFilters,
- FeatureFlagGroupType,
- FeatureFlagType,
-} from '~/types'
+ ConditionSetAspect,
+ ConditionSetChange,
+ changedAspects,
+ diffReleaseConditionSets,
+ rolloutOf,
+} from 'products/feature_flags/frontend/releaseConditionsDiff'
const getChangedPayloadKeys = (
filtersBefore: FeatureFlagFilters | undefined,
@@ -53,6 +57,198 @@ const getRuntimeLabel = (runtime: string): string => {
}
}
+const rolloutLabel = (rollout: number): JSX.Element => <strong className="tabular-nums">{rollout}%</strong>
+
+const conditionSetLabel = (group: FeatureFlagGroupType): JSX.Element => {
+ if (group.description) {
+ return <strong>"{group.description}"</strong>
+ }
+ const properties = group.properties ?? []
+ if (properties.length === 0) {
+ return <strong>{group.aggregation_group_type_index != null ? 'all groups' : 'all users'}</strong>
+ }
+ return (
+ <>
+ <PropertyFilterButton item={properties[0]} />
+ {properties.length > 1 && (
+ <span className="text-muted">
+ {' '}
+ and {properties.length - 1} more{' '}
+ {pluralize(properties.length - 1, 'condition', 'conditions', false)}
+ </span>
+ )}
+ </>
+ )
+}
+
+const joinInline = (parts: JSX.Element[]): JSX.Element => (
+ <>
+ {parts.map((part, index) => (
+ <Fragment key={index}>
+ {index > 0 && (index === parts.length - 1 ? ' and ' : ', ')}
+ {part}
+ </Fragment>
+ ))}
+ </>
+)
+
+const conditionSetsNoun = (count: number): string => pluralize(count, 'condition set', 'condition sets')
+
+const MAX_DETAILED_SET_CHANGES = 3
+
+// Description comes last because it only ever reads as a tail: "... and its description".
+const DESCRIBED_ASPECTS: ConditionSetAspect[] = ['criteria', 'rollout', 'variant', 'description']
+
+const describedAspects = (set: ConditionSetChange): ConditionSetAspect[] => {
+ const aspects = changedAspects(set)
+ return DESCRIBED_ASPECTS.filter((aspect) => aspects.includes(aspect))
+}
+
+const rolloutChangeFragment = (set: ConditionSetChange): JSX.Element => (
+ <>
+ from {rolloutLabel(rolloutOf(set.previous ?? set.group))} to {rolloutLabel(rolloutOf(set.group))}
+ </>
+)
+
+const variantChangeFragment = (set: ConditionSetChange): JSX.Element => (
+ <>
+ from <strong>{set.previous?.variant ?? 'none'}</strong> to <strong>{set.group.variant ?? 'none'}</strong>
+ </>
+)
+
+interface AspectWording {
+ verb: string
+ noun: string
+ subject: (set: ConditionSetChange) => JSX.Element
+ fragment?: (set: ConditionSetChange) => JSX.Element
+}
+
+// A description change names its set by position, because the label of a set is its description.
+const ASPECT_WORDING: Record<ConditionSetAspect, AspectWording> = {
+ criteria: {
+ verb: 'changed the criteria for',
+ noun: 'criteria',
+ subject: (set) => conditionSetLabel(set.group),
+ },
+ rollout: {
+ verb: 'changed the rollout for',
+ noun: 'rollout',
+ subject: (set) => conditionSetLabel(set.group),
+ fragment: rolloutChangeFragment,
+ },
+ variant: {
+ verb: 'changed the variant for',
+ noun: 'variant',
+ subject: (set) => conditionSetLabel(set.group),
+ fragment: variantChangeFragment,
+ },
+ description: {
+ verb: 'changed the description of',
+ noun: 'description',
+ subject: (set) => <>condition set {set.index + 1}</>,
+ },
+}
+
+const aspectDetail = (set: ConditionSetChange, aspect: ConditionSetAspect): JSX.Element => {
+ const { subject, fragment } = ASPECT_WORDING[aspect]
+ return fragment ? (
+ <>
+ {subject(set)} {fragment(set)}
+ </>
+ ) : (
+ subject(set)
+ )
+}
+
+const aspectHeadClause = (set: ConditionSetChange, aspect: ConditionSetAspect): JSX.Element => (
+ <>
+ {ASPECT_WORDING[aspect].verb} {aspectDetail(set, aspect)}
+ </>
+)
+
+const aspectTailClause = (set: ConditionSetChange, aspect: ConditionSetAspect): JSX.Element => {
+ const { noun, fragment } = ASPECT_WORDING[aspect]
+ return fragment ? (
+ <>
+ its {noun} {fragment(set)}
+ </>
+ ) : (
+ <>its {noun}</>
+ )
+}
+
+const conditionSetClause = (set: ConditionSetChange): JSX.Element => {
+ const [head, ...rest] = describedAspects(set)
+ return joinInline([aspectHeadClause(set, head), ...rest.map((aspect) => aspectTailClause(set, aspect))])
+}
+
+const describeConditionSetChanges = (
+ filtersBefore: FeatureFlagFilters | undefined,
+ filtersAfter: FeatureFlagFilters
+): Description[] => {
+ const diff = diffReleaseConditionSets(filtersBefore, filtersAfter)
+ const added = diff.sets.filter((set) => set.status === 'added')
+ const changed = diff.sets.filter((set) => set.status === 'changed')
+ const summarize = added.length + changed.length + diff.removed.length > MAX_DETAILED_SET_CHANGES
+ // A set that changed in more than one way reads better as a single clause than as an entry in
+ // each per-aspect list, where its label would repeat. Counts have no label to repeat.
+ const multiAspect: ConditionSetChange[] = summarize ? [] : changed.filter((set) => describedAspects(set).length > 1)
+ const withAspect = (aspect: ConditionSetAspect): ConditionSetChange[] =>
+ changed.filter((set) => !multiAspect.includes(set) && changedAspects(set).includes(aspect))
+
+ // Past the detail limit every part collapses to "<verb> N condition sets"; the expanded view has the rest.
+ const listOrCount = (
+ sets: ConditionSetChange[],
+ verbs: { detail: string; count?: string },
+ detail: (set: ConditionSetChange) => JSX.Element
+ ): JSX.Element =>
+ summarize ? (
+ <>
+ {verbs.count ?? verbs.detail} {conditionSetsNoun(sets.length)}
+ </>
+ ) : (
+ <>
+ {verbs.detail} {joinInline(sets.map(detail))}
+ </>
+ )
+ const labelOf = (set: ConditionSetChange): JSX.Element => conditionSetLabel(set.group)
+
+ const parts: Description[] = []
+ DESCRIBED_ASPECTS.forEach((aspect) => {
+ const sets = withAspect(aspect)
+ if (sets.length) {
+ parts.push(listOrCount(sets, { detail: ASPECT_WORDING[aspect].verb }, (set) => aspectDetail(set, aspect)))
+ }
+ })
+ parts.push(...multiAspect.map(conditionSetClause))
+ if (added.length) {
+ const verbs = {
+ detail: added.length === 1 ? 'added a condition set for' : 'added condition sets for',
+ count: 'added',
+ }
+ parts.push(
+ listOrCount(added, verbs, (set) => (
+ <>
+ {labelOf(set)} at {rolloutLabel(rolloutOf(set.group))}
+ </>
+ ))
+ )
+ }
+ if (diff.removed.length) {
+ parts.push(
+ diff.removed.length === 1 && !summarize ? (
+ <>removed the condition set for {conditionSetLabel(diff.removed[0].group)}</>
+ ) : (
+ <>removed {conditionSetsNoun(diff.removed.length)}</>
+ )
+ )
+ }
+ if (diff.reordered) {
+ parts.push(<>reordered the condition sets</>)
+ }
+ return parts
+}
+
// Shared handler for fields the feed deliberately never describes. EXCLUDED_FLAG_FIELDS is
// derived by identity from this function, so excluded fields stay distinguishable from
// describable fields whose handler returned null for one particular change.
@@ -79,104 +275,40 @@ const featureFlagActionsMapping: Record<
suffix: <>{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}</>,
}
},
- filters: function onChangedFilter(change) {
- const filtersBefore = change?.before as FeatureFlagFilters
+ filters: function onChangedFilter(change, logItem) {
+ const filtersBefore = change?.before as FeatureFlagFilters | undefined
const filtersAfter = change?.after as FeatureFlagFilters
- const isBooleanValueFlag = Array.isArray(filtersAfter?.groups)
- const isMultivariateFlag = filtersAfter?.multivariate
+ const hasConditionSets = Array.isArray(filtersAfter?.groups)
+ // A flag left with an empty variants list is a boolean flag again, so its payload is the
+ // boolean one. Reading the whole `multivariate` object here would leave that payload undescribed.
+ const isMultivariateFlag = !!filtersAfter?.multivariate?.variants?.length
const changes: Description[] = []
+ let expandedView: ExpandedView | undefined
- if (isBooleanValueFlag) {
- if (
- filtersAfter.groups.length === 0 ||
- !filtersAfter.groups.some((group) => group.rollout_percentage !== 0)
- ) {
- // there are no rollout groups or all are at 0%
- changes.push(<>changed the filter conditions to apply to no users</>)
- } else {
+ if (hasConditionSets) {
+ if (!isMultivariateFlag) {
getChangedPayloadKeys(filtersBefore, filtersAfter).forEach((key) => {
const changedPayload = filtersAfter.payloads?.[key]?.toString() || null
changes.push(<SentenceList listParts={[changedPayload]} prefix="changed payload to" />)
})
-
- const groupAdditions: (string | JSX.Element | null)[] = []
- const groupRemovals: (string | JSX.Element | null)[] = []
-
- filtersAfter.groups
- .filter((groupAfter, index) => {
- const groupBefore = filtersBefore?.groups?.[index]
- // only keep changes with no "before" state, or those where before and after are different
- return !groupBefore || JSON.stringify(groupBefore) !== JSON.stringify(groupAfter)
- })
- .forEach((groupAfter: FeatureFlagGroupType) => {
- const { properties, rollout_percentage = null } = groupAfter
-
- if ((properties?.length || 0) > 0) {
- const nonEmptyProperties = properties as AnyPropertyFilter[] // above check ensures this is not null
- const newButtons =
- nonEmptyProperties.map((property, idx) => {
- return (
- <Fragment key={property.key ?? idx}>
- {' '}
- {idx === 0 && (
- <span>
- <strong className="tabular-nums">
- {rollout_percentage ?? 100}%
- </strong>{' '}
- of{' '}
- </span>
- )}
- <PropertyFilterButton item={property} />
- </Fragment>
- )
- }) || []
- newButtons[0] = (
- <Fragment key={nonEmptyProperties[0].key ?? 0}>
- <span>
- <strong className="tabular-nums">{rollout_percentage ?? 100}%</strong> of{' '}
- </span>
- <PropertyFilterButton
- key={nonEmptyProperties[0].key}
- item={nonEmptyProperties[0]}
- />
- </Fragment>
- )
- groupAdditions.push(...newButtons)
- } else {
- groupAdditions.push(
- <>
- <strong className="tabular-nums">{rollout_percentage ?? 100}%</strong> of{' '}
- <strong>all users</strong>
- </>
- )
- }
- })
-
- if (groupAdditions.length) {
- changes.push(
- <SentenceList listParts={groupAdditions} prefix="changed the filter conditions to apply to" />
- )
- }
-
- const removedGroups = (filtersBefore?.groups || []).filter((_, index) => {
- const groupAfter = filtersAfter?.groups?.[index]
- // only keep changes with no "after" state, they've been removed
- return !groupAfter
- })
-
- if (removedGroups.length) {
- groupRemovals.push(
- <>
- <strong>removed </strong>{' '}
- {pluralize(removedGroups.length, 'release condition', 'release conditions')}
- </>
- )
- }
-
- if (groupRemovals.length) {
- changes.push(<SentenceList listParts={groupRemovals} />)
+ }
+ const setChanges = describeConditionSetChanges(filtersBefore, filtersAfter)
+ changes.push(...setChanges)
+ if (setChanges.length > 0) {
+ // The expanded view tags what moved between the two condition set lists, so it has
+ // nothing to show for a save that left them alone.
+ expandedView = {
+ label: 'Release conditions',
+ content: (
+ <FeatureFlagReleaseConditionsChange
+ flagId={logItem?.item_id ?? ''}
+ activityId={logItem?.id ?? logItem?.created_at ?? ''}
+ before={filtersBefore}
+ after={filtersAfter}
+ />
+ ),
}
}
}
@@ -258,7 +390,7 @@ const featureFlagActionsMapping: Record<
}
if (changes.length > 0) {
- return { description: changes }
+ return { description: changes, expandedView }
}
console.error({ change }, 'could not describe this change')
@@ -507,6 +639,7 @@ export function flagActivityDescriber(logItem: ActivityLogItem, asNotification?:
{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}
</>
)
+ let expandedView: ExpandedView | undefined
for (const change of logItem.detail.changes || []) {
if (!change?.field) {
@@ -519,19 +652,23 @@ export function flagActivityDescriber(logItem: ActivityLogItem, asNotification?:
}
const possibleLogItem = fieldHandler ? fieldHandler(change, logItem) : null
if (possibleLogItem) {
- const { description, suffix } = possibleLogItem
+ const { description, suffix, expandedView: view } = possibleLogItem
if (description) {
changes = changes.concat(description)
}
if (suffix) {
changeSuffix = suffix
}
+ if (view) {
+ expandedView = view
+ }
}
}
if (changes.length) {
return {
description: <SentenceList listParts={changes} prefix={getActorName(logItem)} suffix={changeSuffix} />,
+ expandedView,
}
}
diff --git a/products/feature_flags/frontend/FeatureFlagConditionSetCard.tsx b/products/feature_flags/frontend/FeatureFlagConditionSetCard.tsx
new file mode 100644
index 000000000000..69940860ad8d
--- /dev/null
+++ b/products/feature_flags/frontend/FeatureFlagConditionSetCard.tsx
@@ -0,0 +1,183 @@
+import { IconFlag } from '@posthog/icons'
+import { LemonButton, LemonSnack, LemonTag } from '@posthog/lemon-ui'
+
+import { allOperatorsToHumanName } from 'lib/components/DefinitionPopover/utils'
+import { isPropertyFilterWithOperator } from 'lib/components/PropertyFilters/utils'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { IconOpenInNew, IconSubArrowRight } from 'lib/lemon-ui/icons'
+import { isDistinctIdFilter, withResolvedFlagLabels } from 'scenes/feature-flags/featureFlagReleaseConditionsLogic'
+import { urls } from 'scenes/urls'
+
+import { getFilterLabel } from '~/taxonomy/helpers'
+import { AnyPropertyFilter, FeatureFlagGroupType, PropertyFilterType } from '~/types'
+
+import { rolloutOf } from './releaseConditionsDiff'
+
+export interface FeatureFlagConditionSetCardProps {
+ group: FeatureFlagGroupType
+ index: number
+ aggregationTargetName: string
+ getDistinctIdName: (distinctId: string) => string
+ getFlagKey: (flagId: string) => string
+ tag?: JSX.Element | null
+ previousRolloutPercentage?: number
+ /** Title for the card. Defaults to the set's position. */
+ label?: string
+}
+
+/** Extract server-provided group_key_names from a property, if present. */
+function getGroupKeyNames(property: AnyPropertyFilter): Record<string, string> {
+ if (property.type === PropertyFilterType.Group && 'group_key_names' in property) {
+ return (property as any).group_key_names ?? {}
+ }
+ return {}
+}
+
+function PropertyValueDisplay({
+ property,
+ getDistinctIdName,
+}: {
+ property: AnyPropertyFilter
+ getDistinctIdName: (distinctId: string) => string
+}): JSX.Element {
+ if (property.type === PropertyFilterType.Cohort) {
+ return (
+ <LemonButton type="secondary" size="xsmall" to={urls.cohort(property.value)} sideIcon={<IconOpenInNew />}>
+ {property.cohort_name || `ID ${property.value}`}
+ </LemonButton>
+ )
+ }
+
+ const propertyValues = Array.isArray(property.value) ? property.value : [property.value]
+ const groupKeyNames = property.key === '$group_key' ? getGroupKeyNames(property) : {}
+ const isDistinctId = isDistinctIdFilter(property)
+
+ return (
+ <>
+ {propertyValues.map((val, idx) => {
+ const strVal = String(val)
+ const display = isDistinctId ? getDistinctIdName(strVal) : groupKeyNames[strVal] || strVal
+ return <LemonSnack key={idx}>{display}</LemonSnack>
+ })}
+ </>
+ )
+}
+
+function PropertyFilterRow({
+ property,
+ isFirst,
+ getDistinctIdName,
+}: {
+ property: AnyPropertyFilter
+ isFirst: boolean
+ getDistinctIdName: (distinctId: string) => string
+}): JSX.Element {
+ const propertyLabel =
+ property.type === PropertyFilterType.Cohort || property.type === PropertyFilterType.Flag
+ ? null
+ : getFilterLabel(
+ property.key,
+ property.type === PropertyFilterType.Person
+ ? TaxonomicFilterGroupType.PersonProperties
+ : TaxonomicFilterGroupType.EventProperties
+ )
+
+ const operator = isPropertyFilterWithOperator(property) ? allOperatorsToHumanName(property.operator) : 'equals'
+
+ return (
+ <div className="flex items-center gap-1.5 flex-wrap text-sm">
+ {isFirst ? (
+ <LemonButton icon={<IconSubArrowRight className="arrow-right" />} size="small" noPadding />
+ ) : (
+ <LemonButton icon={<span className="text-xs font-medium">&</span>} size="small" noPadding />
+ )}
+ {propertyLabel && propertyLabel !== property.key && <span className="text-muted">{propertyLabel}</span>}
+ {property.type === PropertyFilterType.Flag ? (
+ <LemonSnack>
+ <IconFlag className="mr-1" />
+ {property.label || property.key}
+ </LemonSnack>
+ ) : (
+ <LemonSnack>{property.type === PropertyFilterType.Cohort ? 'Cohort' : property.key}</LemonSnack>
+ )}
+ <span className="text-muted">{operator}</span>
+ <PropertyValueDisplay property={property} getDistinctIdName={getDistinctIdName} />
+ </div>
+ )
+}
+
+export function FeatureFlagConditionSetCard({
+ group,
+ index,
+ aggregationTargetName,
+ getDistinctIdName,
+ getFlagKey,
+ tag,
+ previousRolloutPercentage,
+ label,
+}: FeatureFlagConditionSetCardProps): JSX.Element {
+ const properties = withResolvedFlagLabels(group.properties, getFlagKey)
+ const rollout = rolloutOf(group)
+ const rolloutChanged = previousRolloutPercentage !== undefined && previousRolloutPercentage !== rollout
+
+ const getSummary = (): JSX.Element => {
+ if (properties.length === 0) {
+ return (
+ <>
+ Condition set will match <b>all {aggregationTargetName}</b>
+ </>
+ )
+ }
+ return (
+ <>
+ Match <b>{aggregationTargetName}</b> against <b>all</b> criteria
+ </>
+ )
+ }
+
+ return (
+ <div className="border rounded p-4 bg-surface-primary">
+ <div className="flex items-center gap-2 flex-wrap">
+ <LemonSnack>{label ?? `Set ${index + 1}`}</LemonSnack>
+ <span className="text-sm">{getSummary()}</span>
+ {tag}
+ </div>
+
+ {group.description && <div className="mt-2 text-sm text-muted">{group.description}</div>}
+
+ {properties.length > 0 && (
+ <div className="mt-3 flex flex-col gap-1">
+ {properties.map((property, idx) => (
+ <PropertyFilterRow
+ key={idx}
+ property={property}
+ isFirst={idx === 0}
+ getDistinctIdName={getDistinctIdName}
+ />
+ ))}
+ </div>
+ )}
+
+ <div className="mt-3">
+ <LemonTag type={rollout === 100 ? 'highlight' : rollout === 0 ? 'caution' : 'none'}>
+ <span className="text-sm">
+ Rolled out to <b className="tabular-nums">{rollout}%</b> of <b>{aggregationTargetName}</b> in
+ this set.
+ {rolloutChanged && (
+ <>
+ {' '}
+ Was <b className="tabular-nums">{previousRolloutPercentage}%</b>.
+ </>
+ )}
+ </span>
+ </LemonTag>
+ </div>
+
+ {group.variant && (
+ <div className="mt-3 text-sm">
+ All <b>{aggregationTargetName}</b> in this set will be in variant <b>{group.variant}</b>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.stories.tsx b/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.stories.tsx
new file mode 100644
index 000000000000..23e2a1259ddc
--- /dev/null
+++ b/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.stories.tsx
@@ -0,0 +1,72 @@
+import { Meta } from '@storybook/react'
+
+import { FeatureFlagFilters, FeatureFlagGroupType, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { FeatureFlagReleaseConditionsChange } from './FeatureFlagReleaseConditionsChange'
+
+const meta: Meta<typeof FeatureFlagReleaseConditionsChange> = {
+ title: 'Scenes-App/Feature Flags/Release Conditions Change',
+ component: FeatureFlagReleaseConditionsChange,
+}
+export default meta
+
+const ORG_A = '00000000-0000-0000-0000-00000000000a'
+const ORG_B = '00000000-0000-0000-0000-00000000000b'
+
+function organizationSet(
+ orgIds: string[],
+ rollout: number,
+ operator: PropertyOperator = PropertyOperator.Exact,
+ description?: string
+): FeatureFlagGroupType {
+ return {
+ properties: [
+ { key: 'organization_id', type: PropertyFilterType.Group, group_type_index: 0, operator, value: orgIds },
+ ],
+ rollout_percentage: rollout,
+ description,
+ aggregation_group_type_index: 0,
+ }
+}
+
+function everyone(rollout: number): FeatureFlagGroupType {
+ return { properties: [], rollout_percentage: rollout }
+}
+
+function filters(groups: FeatureFlagGroupType[]): FeatureFlagFilters {
+ return { groups, multivariate: null }
+}
+
+export function RolloutChanged(): JSX.Element {
+ return (
+ <div className="max-w-3xl">
+ <FeatureFlagReleaseConditionsChange
+ flagId="1234"
+ activityId="rollout"
+ before={filters([everyone(75)])}
+ after={filters([everyone(100)])}
+ />
+ </div>
+ )
+}
+
+export function SetsAddedChangedAndRemoved(): JSX.Element {
+ return (
+ <div className="max-w-3xl">
+ <FeatureFlagReleaseConditionsChange
+ flagId="1234"
+ activityId="restructure"
+ before={filters([
+ organizationSet([ORG_A], 0, PropertyOperator.Exact, 'Disabled for org A'),
+ organizationSet([ORG_B], 100),
+ everyone(100),
+ ])}
+ after={filters([
+ organizationSet([ORG_A], 0, PropertyOperator.Exact, 'Disabled for org A'),
+ organizationSet([ORG_B], 50),
+ organizationSet([ORG_A, ORG_B], 100, PropertyOperator.IsNot),
+ ])}
+ />
+ </div>
+ )
+}
diff --git a/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.test.tsx b/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.test.tsx
new file mode 100644
index 000000000000..257cb543eb28
--- /dev/null
+++ b/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.test.tsx
@@ -0,0 +1,70 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, within } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { FeatureFlagFilters, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { FeatureFlagReleaseConditionsChange } from './FeatureFlagReleaseConditionsChange'
+
+const before: FeatureFlagFilters = {
+ groups: [
+ {
+ properties: [
+ {
+ type: PropertyFilterType.Person,
+ key: 'distinct_id',
+ operator: PropertyOperator.Exact,
+ value: ['user-7'],
+ },
+ {
+ type: PropertyFilterType.Flag,
+ key: '42',
+ operator: PropertyOperator.FlagEvaluatesTo,
+ value: true,
+ },
+ ],
+ rollout_percentage: 100,
+ },
+ ],
+ multivariate: null,
+}
+
+const after: FeatureFlagFilters = {
+ groups: [{ properties: [], rollout_percentage: 100 }],
+ multivariate: null,
+}
+
+describe('FeatureFlagReleaseConditionsChange', () => {
+ beforeEach(() => {
+ initKeaTests()
+ useMocks({
+ post: {
+ '/api/projects/:team/feature_flags/bulk_keys/': [200, { keys: { '42': 'beta-banner' } }],
+ '/api/environments/:team/persons/batch_by_distinct_ids/': [
+ 200,
+ { results: { 'user-7': { name: 'Ada Lovelace' } } },
+ ],
+ },
+ })
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('resolves distinct id and flag names in a removed condition set', async () => {
+ render(
+ <Provider>
+ <FeatureFlagReleaseConditionsChange flagId="1234" activityId="removal" before={before} after={after} />
+ </Provider>
+ )
+
+ await screen.findByText('user-7 (Ada Lovelace)')
+ const removedCard = screen.getByText('Was set 1').closest('div.border') as HTMLElement
+ expect(within(removedCard).getByText('user-7 (Ada Lovelace)')).toBeInTheDocument()
+ expect(within(removedCard).getByText('beta-banner')).toBeInTheDocument()
+ })
+})
diff --git a/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.tsx b/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.tsx
new file mode 100644
index 000000000000..a6d4d17c28e7
--- /dev/null
+++ b/products/feature_flags/frontend/FeatureFlagReleaseConditionsChange.tsx
@@ -0,0 +1,113 @@
+import { useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { featureFlagReleaseConditionsLogic } from 'scenes/feature-flags/featureFlagReleaseConditionsLogic'
+
+import { FeatureFlagFilters } from '~/types'
+
+import { FeatureFlagConditionSetCard } from './FeatureFlagConditionSetCard'
+import { ConditionSetChange, diffReleaseConditionSets, rolloutOf } from './releaseConditionsDiff'
+
+export interface FeatureFlagReleaseConditionsChangeProps {
+ flagId: string
+ activityId: string
+ before?: FeatureFlagFilters | null
+ after: FeatureFlagFilters
+}
+
+function statusTag(set: ConditionSetChange): JSX.Element | null {
+ if (set.status === 'added') {
+ return (
+ <LemonTag type="success" size="small">
+ Added
+ </LemonTag>
+ )
+ }
+ if (set.status === 'changed') {
+ return (
+ <LemonTag type="warning" size="small">
+ Changed
+ </LemonTag>
+ )
+ }
+ return null
+}
+
+export function FeatureFlagReleaseConditionsChange({
+ flagId,
+ activityId,
+ before,
+ after,
+}: FeatureFlagReleaseConditionsChangeProps): JSX.Element {
+ // The logic resolves distinct ids and flag ids to names from the groups it is given, and this view
+ // also renders the sets that the change removed, so it needs both sides.
+ const filtersForNameResolution = useMemo(
+ (): FeatureFlagFilters => ({ ...after, groups: [...(after.groups ?? []), ...(before?.groups ?? [])] }),
+ [after, before]
+ )
+ // The logic is keyed by id, and every history entry for one flag carries different filters,
+ // so each entry needs its own key or they would all share one state.
+ const logic = featureFlagReleaseConditionsLogic({
+ id: `${flagId}-activity-${activityId}`,
+ readOnly: true,
+ filters: filtersForNameResolution,
+ })
+ const { aggregationTargetName, getDistinctIdName, getFlagKey } = useValues(logic)
+ const diff = diffReleaseConditionSets(before, after)
+
+ return (
+ <div className="flex flex-col gap-2 py-2">
+ <p className="text-xs text-muted mb-0">
+ Release conditions after this change. Condition sets are evaluated top to bottom, the first match wins.
+ </p>
+
+ {diff.sets.length === 0 && (
+ <p className="text-sm text-muted mb-0">No condition sets. The flag matches no one.</p>
+ )}
+
+ {diff.sets.map((set) => (
+ <div key={set.index}>
+ {set.index > 0 && (
+ <div className="condition-set-separator my-2 py-0 text-center text-xs font-semibold text-muted">
+ OR
+ </div>
+ )}
+ <FeatureFlagConditionSetCard
+ group={set.group}
+ index={set.index}
+ aggregationTargetName={aggregationTargetName(set.group.aggregation_group_type_index)}
+ getDistinctIdName={getDistinctIdName}
+ getFlagKey={getFlagKey}
+ tag={statusTag(set)}
+ previousRolloutPercentage={set.previous ? rolloutOf(set.previous) : undefined}
+ />
+ </div>
+ ))}
+
+ {diff.removed.length > 0 && (
+ <>
+ <div className="mt-2 text-xs font-semibold text-muted">Removed by this change</div>
+ {diff.removed.map(({ group, index }) => (
+ <div key={index} className="opacity-60">
+ <FeatureFlagConditionSetCard
+ group={group}
+ index={index}
+ label={`Was set ${index + 1}`}
+ aggregationTargetName={aggregationTargetName(group.aggregation_group_type_index)}
+ getDistinctIdName={getDistinctIdName}
+ getFlagKey={getFlagKey}
+ tag={
+ <LemonTag type="danger" size="small">
+ Removed
+ </LemonTag>
+ }
+ />
+ </div>
+ ))}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/feature_flags/frontend/releaseConditionsDiff.test.ts b/products/feature_flags/frontend/releaseConditionsDiff.test.ts
new file mode 100644
index 000000000000..b0fd0d8cf448
--- /dev/null
+++ b/products/feature_flags/frontend/releaseConditionsDiff.test.ts
@@ -0,0 +1,142 @@
+import { FeatureFlagFilters, FeatureFlagGroupType, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { changedAspects, diffReleaseConditionSets } from './releaseConditionsDiff'
+
+const everyone = (rollout: number | null): FeatureFlagGroupType => ({ properties: [], rollout_percentage: rollout })
+
+const email = (
+ value: string,
+ rollout: number | null = 100,
+ extra: Partial<FeatureFlagGroupType> = {}
+): FeatureFlagGroupType => ({
+ properties: [{ key: 'email', type: PropertyFilterType.Person, operator: PropertyOperator.Exact, value: [value] }],
+ rollout_percentage: rollout,
+ ...extra,
+})
+
+const cohort = (id: number, rollout: number | null = 100): FeatureFlagGroupType => ({
+ properties: [{ key: 'id', type: PropertyFilterType.Cohort, value: id, operator: PropertyOperator.In }],
+ rollout_percentage: rollout,
+})
+
+const filters = (groups: FeatureFlagGroupType[]): FeatureFlagFilters => ({ groups, multivariate: null })
+
+describe('diffReleaseConditionSets', () => {
+ it.each([
+ {
+ name: 'rollout change keeps the set matched',
+ before: [everyone(75)],
+ after: [everyone(100)],
+ statuses: ['changed'],
+ aspects: [['rollout']],
+ removed: [],
+ reordered: false,
+ },
+ {
+ name: 'null rollout counts as 100%',
+ before: [email('[email protected]', null)],
+ after: [email('[email protected]', 100)],
+ statuses: ['unchanged'],
+ aspects: [[]],
+ removed: [],
+ reordered: false,
+ },
+ {
+ name: 'removing the first set does not mark the sets that shifted up as changed',
+ before: [cohort(98), everyone(30), email('[email protected]')],
+ after: [everyone(30), email('[email protected]')],
+ statuses: ['unchanged', 'unchanged'],
+ aspects: [[], []],
+ removed: [0],
+ reordered: false,
+ },
+ {
+ name: 'a new set at the end is added',
+ before: [cohort(98)],
+ after: [cohort(98), email('[email protected]')],
+ statuses: ['unchanged', 'added'],
+ aspects: [[], []],
+ removed: [],
+ reordered: false,
+ },
+ {
+ name: 'editing a value in place is a criteria change',
+ before: [email('[email protected]', 50), everyone(10)],
+ after: [email('[email protected]', 50), everyone(10)],
+ statuses: ['changed', 'unchanged'],
+ aspects: [['criteria'], []],
+ removed: [],
+ reordered: false,
+ },
+ {
+ name: 'replacing a set with an unrelated one is a removal plus an addition',
+ before: [cohort(98), everyone(10)],
+ after: [everyone(10), email('[email protected]')],
+ statuses: ['unchanged', 'added'],
+ aspects: [[], []],
+ removed: [0],
+ reordered: false,
+ },
+ {
+ name: 'a variant-only edit keeps the set matched',
+ before: [email('[email protected]', 50, { variant: 'control' })],
+ after: [email('[email protected]', 50, { variant: 'test' })],
+ statuses: ['changed'],
+ aspects: [['variant']],
+ removed: [],
+ reordered: false,
+ },
+ {
+ name: 'a description-only edit is reported as a description change',
+ before: [email('[email protected]', 0)],
+ after: [email('[email protected]', 0, { description: 'Disabled for Example' })],
+ statuses: ['changed'],
+ aspects: [['description']],
+ removed: [],
+ reordered: false,
+ },
+ {
+ name: 'editing a set and moving it in one save is a criteria change plus a reorder',
+ before: [email('[email protected]', 50), cohort(98)],
+ after: [cohort(98), email('[email protected]', 50)],
+ statuses: ['unchanged', 'changed'],
+ aspects: [[], ['criteria']],
+ removed: [],
+ reordered: true,
+ },
+ {
+ name: 'a moved edit with two look-alike candidates stays a removal plus an addition',
+ before: [email('[email protected]', 50), email('[email protected]', 50), cohort(98)],
+ after: [cohort(98), cohort(411), email('[email protected]', 50)],
+ statuses: ['unchanged', 'added', 'added'],
+ aspects: [[], [], []],
+ removed: [0, 1],
+ reordered: false,
+ },
+ {
+ name: 'swapping two sets is a reorder',
+ before: [cohort(98), everyone(10)],
+ after: [everyone(10), cohort(98)],
+ statuses: ['unchanged', 'unchanged'],
+ aspects: [[], []],
+ removed: [],
+ reordered: true,
+ },
+ {
+ name: 'no before state means every set is added',
+ before: undefined,
+ after: [everyone(99)],
+ statuses: ['added'],
+ aspects: [[]],
+ removed: [],
+ reordered: false,
+ },
+ ])('$name', ({ before, after, statuses, aspects, removed, reordered }) => {
+ const diff = diffReleaseConditionSets(before ? filters(before) : undefined, filters(after))
+
+ expect(diff.sets.map((set) => set.status)).toEqual(statuses)
+ expect(diff.sets.map(changedAspects)).toEqual(aspects)
+ expect(diff.removed.map((set) => set.index)).toEqual(removed)
+ expect(diff.reordered).toBe(reordered)
+ })
+})
diff --git a/products/feature_flags/frontend/releaseConditionsDiff.ts b/products/feature_flags/frontend/releaseConditionsDiff.ts
new file mode 100644
index 000000000000..c89e2e5d6a70
--- /dev/null
+++ b/products/feature_flags/frontend/releaseConditionsDiff.ts
@@ -0,0 +1,174 @@
+import { AnyPropertyFilter, FeatureFlagFilters, FeatureFlagGroupType } from '~/types'
+
+export type ConditionSetStatus = 'added' | 'changed' | 'unchanged'
+export type ConditionSetAspect = 'criteria' | 'rollout' | 'variant' | 'description'
+
+export interface ConditionSetChange {
+ group: FeatureFlagGroupType
+ /** Position in the filters after the change. */
+ index: number
+ status: ConditionSetStatus
+ /** The set this one was matched to before the change. Absent for added sets. */
+ previous?: FeatureFlagGroupType
+}
+
+export interface RemovedConditionSet {
+ group: FeatureFlagGroupType
+ /** Position in the filters before the change. */
+ index: number
+}
+
+export interface ReleaseConditionsDiff {
+ sets: ConditionSetChange[]
+ removed: RemovedConditionSet[]
+ /** True when sets that exist on both sides come out in a different order. */
+ reordered: boolean
+}
+
+interface PropertyFilterShape {
+ type?: string
+ key?: string
+ operator?: string | null
+ value?: unknown
+ group_type_index?: number | null
+}
+
+export function rolloutOf(group: FeatureFlagGroupType): number {
+ return group.rollout_percentage ?? 100
+}
+
+function propertySignature(property: AnyPropertyFilter): string {
+ const { type, key, operator, value, group_type_index } = property as PropertyFilterShape
+ return JSON.stringify([type ?? null, key ?? null, operator ?? null, value ?? null, group_type_index ?? null])
+}
+
+function criteriaSignature(group: FeatureFlagGroupType): string {
+ return JSON.stringify([group.aggregation_group_type_index ?? null, (group.properties ?? []).map(propertySignature)])
+}
+
+function setSignature(group: FeatureFlagGroupType): string {
+ return JSON.stringify([
+ criteriaSignature(group),
+ rolloutOf(group),
+ group.variant ?? null,
+ group.description ?? null,
+ ])
+}
+
+function propertyKeys(group: FeatureFlagGroupType): string[] {
+ return (group.properties ?? []).map((property) => {
+ const { type, key } = property as PropertyFilterShape
+ return `${type ?? ''}:${key ?? ''}`
+ })
+}
+
+// Two sets target the same kind of thing when they share an aggregation group type and either share a
+// property key or both have no properties. Without this, an unrelated new set would read as an edit.
+function looksLikeSameSet(a: FeatureFlagGroupType, b: FeatureFlagGroupType): boolean {
+ if ((a.aggregation_group_type_index ?? null) !== (b.aggregation_group_type_index ?? null)) {
+ return false
+ }
+ const keysA = propertyKeys(a)
+ const keysB = propertyKeys(b)
+ if (keysA.length === 0 && keysB.length === 0) {
+ return true
+ }
+ return keysA.some((key) => keysB.includes(key))
+}
+
+export function diffReleaseConditionSets(
+ before: FeatureFlagFilters | null | undefined,
+ after: FeatureFlagFilters
+): ReleaseConditionsDiff {
+ const beforeGroups = before?.groups ?? []
+ const afterGroups = after.groups ?? []
+ const beforeSignatures = beforeGroups.map(setSignature)
+ const afterSignatures = afterGroups.map(setSignature)
+ const beforeCriteria = beforeGroups.map(criteriaSignature)
+ const afterCriteria = afterGroups.map(criteriaSignature)
+
+ const matchedBefore = new Map<number, number>()
+ const usedBefore = new Set<number>()
+ const claim = (afterIndex: number, beforeIndex: number): void => {
+ matchedBefore.set(afterIndex, beforeIndex)
+ usedBefore.add(beforeIndex)
+ }
+ const findUnusedBefore = (predicate: (beforeIndex: number) => boolean): number =>
+ beforeGroups.findIndex((_, beforeIndex) => !usedBefore.has(beforeIndex) && predicate(beforeIndex))
+
+ afterGroups.forEach((_, afterIndex) => {
+ const beforeIndex = findUnusedBefore((j) => beforeSignatures[j] === afterSignatures[afterIndex])
+ if (beforeIndex >= 0) {
+ claim(afterIndex, beforeIndex)
+ }
+ })
+ afterGroups.forEach((_, afterIndex) => {
+ if (matchedBefore.has(afterIndex)) {
+ return
+ }
+ const beforeIndex = findUnusedBefore((j) => beforeCriteria[j] === afterCriteria[afterIndex])
+ if (beforeIndex >= 0) {
+ claim(afterIndex, beforeIndex)
+ }
+ })
+ afterGroups.forEach((group, afterIndex) => {
+ if (matchedBefore.has(afterIndex) || usedBefore.has(afterIndex) || afterIndex >= beforeGroups.length) {
+ return
+ }
+ if (looksLikeSameSet(group, beforeGroups[afterIndex])) {
+ claim(afterIndex, afterIndex)
+ }
+ })
+ // A set edited and moved in the same save has no positional partner. Pair it with the one leftover set
+ // it still resembles; with several look-alikes there is no safe pick, so those stay added and removed.
+ afterGroups.forEach((group, afterIndex) => {
+ if (matchedBefore.has(afterIndex)) {
+ return
+ }
+ const candidates = beforeGroups
+ .map((_, beforeIndex) => beforeIndex)
+ .filter((beforeIndex) => !usedBefore.has(beforeIndex) && looksLikeSameSet(group, beforeGroups[beforeIndex]))
+ if (candidates.length === 1) {
+ claim(afterIndex, candidates[0])
+ }
+ })
+
+ const sets: ConditionSetChange[] = afterGroups.map((group, index) => {
+ const beforeIndex = matchedBefore.get(index)
+ if (beforeIndex === undefined) {
+ return { group, index, status: 'added' }
+ }
+ const status = beforeSignatures[beforeIndex] === afterSignatures[index] ? 'unchanged' : 'changed'
+ return { group, index, status, previous: beforeGroups[beforeIndex] }
+ })
+ const removed = beforeGroups.map((group, index) => ({ group, index })).filter(({ index }) => !usedBefore.has(index))
+ const matchedOrder = sets.flatMap((set) => {
+ const beforeIndex = matchedBefore.get(set.index)
+ return beforeIndex === undefined ? [] : [beforeIndex]
+ })
+ const reordered = matchedOrder.some(
+ (beforeIndex, position) => position > 0 && beforeIndex < matchedOrder[position - 1]
+ )
+
+ return { sets, removed, reordered }
+}
+
+export function changedAspects(set: ConditionSetChange): ConditionSetAspect[] {
+ if (set.status !== 'changed' || !set.previous) {
+ return []
+ }
+ const aspects: ConditionSetAspect[] = []
+ if (criteriaSignature(set.previous) !== criteriaSignature(set.group)) {
+ aspects.push('criteria')
+ }
+ if (rolloutOf(set.previous) !== rolloutOf(set.group)) {
+ aspects.push('rollout')
+ }
+ if ((set.previous.variant ?? null) !== (set.group.variant ?? null)) {
+ aspects.push('variant')
+ }
+ if ((set.previous.description ?? null) !== (set.group.description ?? null)) {
+ aspects.push('description')
+ }
+ return aspects
+}