: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(flags): show rules v2 flags as an ordered rule flow (#127839)
Andersc9a18ed2f0f5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 04c3722d140c..4de258289210 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11751,9 +11751,9 @@ snapshots:scenes-app-feature-flags--deleted-feature-flag--light:hash: v1.k794b7964.5371c20ecb5f9a0fb7398bbd1af8f5ec93a224195fc16b2f8d131044510e97cf.0vXp3Gzf_WyyYE_ZKMn8KwRN3B96Js3qaEefDUgAFmsscenes-app-feature-flags--deleted-rules-v-2-feature-flag--dark:- hash: v1.k794b7964.e04929cae93f23935399e4e54e7fb0658112b83c9cad626a5f1cf09368bffd85.U2yqL_Ggv_CSSzRo6F8M_i0yGtkWpJ-Cr29Th2SftIQ+ hash: v1.k794b7964.4b5d6bcf07236ca3039fbd1ea122a01016a8efffc6d60f6923d6f07c01099cb8.urrqMGmc5Bs4Tap7GhzdxOf6Ul1rYuTns_FHkkJ6ORwscenes-app-feature-flags--deleted-rules-v-2-feature-flag--light:- hash: v1.k794b7964.bed8de01c0601540fc620e1f235885cddb48ebb25238ea2b449a942ab3631ae4.78Gc8NQcOx8K0JKzCHLBowQs5R9hLwUDf-Y4CgZegSI+ hash: v1.k794b7964.d10c58a3f4fc99a4d0b173c9310fe5c27bd8db3353f3f919b7bde7e17836a130.s84lAD89U2ud_1Kk-ZvM5c-ZPA0diKQXlaMQ4EhhqcUscenes-app-feature-flags--edit-encrypted-remote-config-feature-flag--dark:hash: v1.k794b7964.ca3adaf66d56f978e7924cca42d415cce3f214e4feeba4296e4ed5029b5bb627.uSlf_lOJRxROJ2e0W-zT7zgpYMFIucXAkv6YWmpZE84scenes-app-feature-flags--edit-encrypted-remote-config-feature-flag--light:@@ -11779,13 +11779,13 @@ snapshots:scenes-app-feature-flags--edit-remote-config-feature-flag--light:hash: v1.k794b7964.dbab943a395dc36445e158e397997326eaa0ae0fc5b1ca3f85aa2eb319f2cd02.9S_fWHyuUH9YG17onNRM1cR7N2CDLT_zjZSLPgCmMW4scenes-app-feature-flags--edit-rules-v-2-feature-flag--dark:- hash: v1.k794b7964.7c1812f3bae81f2ec5f88bdd8981269c9ab1db8de052f62261b6a526078e1db1.lLPRMvHcm3J30ZNs_Uv27aiYvPrYiEkQ9v9jzeGl4Rw+ hash: v1.k794b7964.0984b246b0ac7aa0255a5665ead285328c1238db56b76625c3f5dc03fc6d8167.PHh4QWq59D6dPeKBoS2cGnOEeuKzaodQfimA4B8sNHkscenes-app-feature-flags--edit-rules-v-2-feature-flag--light:- hash: v1.k794b7964.6d2f9704f59bf6e3d61b811d92c7ecfc3d4a5263096d0e57181c2bce6dc4dc97.RTb3YQ69UQA3cySea7dGUkkZhOnIDrzoqgk7t0HpMXI+ hash: v1.k794b7964.f95bdd9d1ee561984aa2090a26b6361cd1d92f482986c24d9fe293f76e16610e.wkNjBCSWQLWKLyIEXWmAbce3ZGNCCRvQhzp-1N8FHIoscenes-app-feature-flags--edit-rules-v-2-feature-flag-with-experiment-rules--dark:- hash: v1.k794b7964.d8ab86503937e19dfdaecce1b33a43543301dbc9ea7ec044fa86dc1be4dc78f4.l5piKSXuRQfvFZYzzw-EaBJx3ITJV4JXTiYhSMxmryo+ hash: v1.k794b7964.c41d9ece7a6571cdb500909cf9dbb1fefba7c9554e7fd1842cfb8ad65dec88fd.qW3aYitFdsu8t2KrhIo6lMjwe9lwfVDSnYwwTE_HCh4scenes-app-feature-flags--edit-rules-v-2-feature-flag-with-experiment-rules--light:- hash: v1.k794b7964.6ef70a4f20b39736ec4f22678be78ae849f75361623b492c55736a460f79ac54.TZ9q073SpyMeRfUo-w_opEUXWXwk7oYjJq9D8ixrJMY+ hash: v1.k794b7964.d01cb1e4a42ba99099bf1b55456146ee271a7b24640380e87f3d7bc2c097177b.bi_X-t83cXZ5SNmSQOc4JfwGnnVuPuBugjuMlTo3B3Uscenes-app-feature-flags--feature-flag-load-failed--dark:hash: v1.k794b7964.78c0cc612dbea90f7040fdc919c91d37255bd3c1a5d149a26a7968e86bcd1649.ZSqbZArI-ot3gRLxJErCln6BkMjyS8my3F7ILlT9qX0scenes-app-feature-flags--feature-flag-load-failed--light:@@ -11823,21 +11823,21 @@ snapshots:scenes-app-feature-flags--new-remote-config-flag-payload-error--light:hash: v1.k794b7964.bbbbecef36aa418ff943f76d2006e75aec34f4ed6b26c4303ad005cbc95771ce.t6SkxtqE_6K7m6nlXwksQYnWs2s91AkmcYNUBy5ao-8scenes-app-feature-flags--new-rules-v-2-feature-flag--dark:- hash: v1.k794b7964.1a8f4e9d348c8be23625ab231962fc9c2ce44233e6d699b52ad397f1c9acbc5d.TsUGKIvznQ4mzFHDJGhHd6kdTG6MN0vawhALQYuQHug+ hash: v1.k794b7964.c67d85f567bbdfbd2ef832c52157ca35e77e108ea8a302d6fa40d4ca40abaf25.ZZzhHEwXTMfrunKYH-2W_bQJQaS8-ZTXmGVoZK8totYscenes-app-feature-flags--new-rules-v-2-feature-flag--light:- hash: v1.k794b7964.75a2d3403cf21fc78b4da29dd83c5f47d30ef487b5c34a97bbbb8164265ed506.Fb5E6agVEfrf6Zf-9T-eyjBYxFcG3UFmjnfqVQzh-Ro+ hash: v1.k794b7964.e55189e8225135bd857f79be2396ae7ec0c48d955953aa42a93d853fb486fd25.idqXZZgohOvGdYOO_qNlkZEx_UfOgHQ5UsjtwA3PLyEscenes-app-feature-flags--rules-v-2-feature-flag--dark:- hash: v1.k794b7964.2e595e65c1e4494c71c07b2772015cbcaf64fb4120d32192163e26ae95ca5231.aGTUL2hQW0He1Ia68rgMjgp-KslX-HAyApsF3Uwj5YI+ hash: v1.k794b7964.ae97acf9bd7208b07100a087b90b92b77135a39978753e5a0f0454f8953d5c24.wgNIhSGIA6dAO3refE_yz1b75Xl7w-lm_Joi2kRqDUMscenes-app-feature-flags--rules-v-2-feature-flag--light:- hash: v1.k794b7964.9be1f7a27ef9df90e456212676e6f3bd01f590ac47c07b6e0db76e34eccc0075.FtbgBPtQq1lleQ32jk0zd6EUz8Vdex3ciHhheCbh0i0+ hash: v1.k794b7964.b476d9ddee05c387f8776daccb5424ffa91eb3f0cc25f5cbee0f49972f77d70c.RfD2EJsyqs6DhOsmnUd72z5va1AOWtvuH1oZNpjYFx4scenes-app-feature-flags--rules-v-2-feature-flag-edit-deep-link--dark:- hash: v1.k794b7964.2e595e65c1e4494c71c07b2772015cbcaf64fb4120d32192163e26ae95ca5231.fNaTKRMtH9HwMByvOc77CzVjKpmDG-1hStBUXueEMLk+ hash: v1.k794b7964.ae97acf9bd7208b07100a087b90b92b77135a39978753e5a0f0454f8953d5c24.yCnZG3cepDWmfv_Uhw1du-s2vTCVBEauSwRKtJN1YzYscenes-app-feature-flags--rules-v-2-feature-flag-edit-deep-link--light:- hash: v1.k794b7964.8cbffc977bea22684cf73144ab837a5acabffac33eac687ba2c29e6858ebb3a6.OCNkBGO_Dioqet3YCVFl028n_2oOoNgl2foc1d7VzSk+ hash: v1.k794b7964.b476d9ddee05c387f8776daccb5424ffa91eb3f0cc25f5cbee0f49972f77d70c.f36TDx7gPvrEDnR3tFG2n4LFCH21Er-zUb_86LDqW98scenes-app-feature-flags--rules-v-2-feature-flag-with-experiment-rules--dark:- hash: v1.k794b7964.0c8bc0db31efeffe72e342874f4b2e80f702567638d63aee27e2964facdbde64.nFTGZCL9UCQiUc1f4XqDT8rYoy5W7uhjzi6PAfqj14o+ hash: v1.k794b7964.f9573a7ee83241f13e36811429407c01335c3348872a6ce6fbe45c17880f0394.kwczoT6Q5BOUCO7YAnd3rnKoYoJuIZEQ92JJ9VA9s0gscenes-app-feature-flags--rules-v-2-feature-flag-with-experiment-rules--light:- hash: v1.k794b7964.d2ae1d0fa3a6b10cc03c475fc223daa39b6c17041e5d1e3c05431663073b5062.ZUyX38oS8pRfFpTHCjYMSIF2Wg3EmitLCUmmE8ikdV0+ hash: v1.k794b7964.ca50b2e33695bc79ab6585aa201f9f9bf4dac5996e7ba26b7d23c7231c0b281b.iwyFx3QPotns6ct1AEgpqrzIpzhQ5-6vlXRNnh-0v7Qscenes-app-feature-flags--stale-feature-flag--dark:hash: v1.k794b7964.ecc3094457c572688677f873b9471bfc52054f54e6f7e2f9b93e848c4a886ab0.oYbwUl5hPBLBQbBKSlV7njwwZdWDuiBUq4Cp5XqaGeUscenes-app-feature-flags--stale-feature-flag--light:diff --git a/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx b/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsxindex 59be8bdde604..8d65f77b2065 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx@@ -2,8 +2,8 @@ import './FeatureFlag.scss'import { useActions, useValues } from 'kea'-import { IconCode, IconFlag, IconGlobe, IconLaptop, IconList, IconServer } from '@posthog/icons'-import { LemonSwitch, LemonTag } from '@posthog/lemon-ui'+import { IconCode, IconFlag, IconGlobe, IconLaptop, IconList, IconPencil, IconServer } from '@posthog/icons'+import { LemonButton, LemonSwitch, LemonTag } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'@@ -68,7 +68,7 @@ function TagsDisplay({ tags, evaluationContexts, flagId, hasEvaluationContexts }export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps): JSX.Element {const { featureFlags } = useValues(enabledFeaturesLogic)const { recordingFilterForFlag, featureFlagActiveUpdateLoading, deletedCohortFilters } = useValues(featureFlagLogic)- const { toggleFeatureFlagActive } = useActions(featureFlagLogic)+ const { toggleFeatureFlagActive, editFeatureFlag } = useActions(featureFlagLogic)const hasEvaluationContexts = !!featureFlags[FEATURE_FLAGS.FLAG_EVALUATION_TAGS] // NB: the tag was named "flag-evaluation-tags" before we renamed the concept – i.e. this powers evaluation contexts even though the name implies tags@@ -236,7 +236,32 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):{!v1Filters ? (<div className="rounded border p-4 bg-bg-light">{isRulesV2FeatureFlagConfig(featureFlag.filters) ? (- <FeatureFlagRulesV2Readonly config={featureFlag.filters} />+ <FeatureFlagRulesV2Readonly+ config={featureFlag.filters}+ active={featureFlag.active}+ editButton={+ featureFlag.deleted ? null : (+ <AccessControlAction+ resourceType={AccessControlResourceType.FeatureFlag}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={featureFlag.user_access_level}+ >+ {({ disabledReason }) => (+ <LemonButton+ icon={<IconPencil />}+ size="small"+ type="secondary"+ disabledReason={disabledReason}+ onClick={() => editFeatureFlag(true)}+ data-attr="edit-rules-v2-rules"+ >+ Edit rules+ </LemonButton>+ )}+ </AccessControlAction>+ )+ }+ />) : (<FeatureFlagConfigReadonlyNotice filters={featureFlag.filters} />)}diff --git a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsxindex 20f059b1fb7b..59c7ed2432bc 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx@@ -1,13 +1,13 @@import '@testing-library/jest-dom'-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import { Provider } from 'kea'import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'-import { FeatureFlagRulesV2DraftExperimentRule } from '~/types'+import { FeatureFlagRulesV2DraftExperimentRule, FeatureFlagRulesV2DraftRule } from '~/types'import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'import { FeatureFlagRulesV2Editor } from './FeatureFlagRulesV2Editor'@@ -18,6 +18,12 @@ jest.mock('lib/components/AutoSizer', () => ({renderProp({ height: 400, width: 400 }),}))+jest.mock('./JSONEditorInput', () => ({+ JSONEditorInput: ({ value, onChange }: { value: string; onChange: (value: string) => void }): JSX.Element => (+ <textarea value={value} onChange={(event) => onChange(event.target.value)} />+ ),+}))+const V2_FLAG = {...NEW_FLAG,id: 7,@@ -81,6 +87,38 @@ const STRING_EXPERIMENT_FLAG = {},}+const OBJECT_FLAG = {+ ...NEW_FLAG,+ id: 11,+ key: 'checkout-config',+ version: 2,+ filters: {+ version: 2,+ return_type: 'object',+ default_value: { columns: 1 },+ rules: [+ {+ id: 'rule-beta',+ rule_type: 'targeted_release',+ targeting: { properties: [] },+ value: { columns: 2 },+ },+ ],+ },+}++const NUMBER_FLAG = {+ ...OBJECT_FLAG,+ id: 12,+ key: 'checkout-limit',+ filters: {+ version: 2,+ return_type: 'number',+ default_value: 10,+ rules: [{ id: 'rule-beta', rule_type: 'targeted_release', targeting: { properties: [] }, value: 25 }],+ },+}+async function renderEditor(id: number): Promise<void> {const pageLogic = featureFlagLogic({ id })pageLogic.mount()@@ -100,8 +138,13 @@ describe('FeatureFlagRulesV2Editor', () => {'/api/projects/:team/property_definitions': mockGetPropertyDefinitions,'/api/projects/:team/feature_flags/7/': V2_FLAG,'/api/projects/:team/feature_flags/9/': STRING_EXPERIMENT_FLAG,+ '/api/projects/:team/feature_flags/11/': OBJECT_FLAG,+ '/api/projects/:team/feature_flags/12/': NUMBER_FLAG,'/api/projects/:team/feature_flags/:id/status': { status: 'active', reason: 'mock reason' },},+ post: {+ '/api/projects/:team/feature_flags/user_blast_radius': () => [200, { affected: 120, total: 2000 }],+ },})initKeaTests()})@@ -113,29 +156,118 @@ describe('FeatureFlagRulesV2Editor', () => {await renderEditor(7)})+ const rules = (): FeatureFlagRulesV2DraftRule[] =>+ featureFlagRulesV2EditorLogic({ id: 7 }).values.draft.config.rules+ const openRuleMenu = (index: number): void => {+ fireEvent.click(screen.getByLabelText(`Rule ${index + 1} actions`))+ }+it('names each text input by its label', () => {expect(screen.getByLabelText('Flag key')).toHaveValue('new-checkout')- expect(screen.getAllByLabelText(/^Description/).map((input) => input.tagName)).toEqual([- 'TEXTAREA',- 'INPUT',- 'INPUT',- ])+ expect(screen.getByLabelText(/^Description/).tagName).toBe('TEXTAREA')+ expect(screen.getByLabelText('Rule 1 description')).toHaveValue('Beta users')+ expect(screen.getByLabelText('Rule 2 description')).toHaveValue('Everyone else')expect(screen.getByLabelText('Rollout percentage')).toHaveValue('20')+ const secondRule = screen.getByLabelText('Rule 2')+ expect(secondRule).toHaveAttribute('role', 'group')+ expect(within(secondRule).getByLabelText('Rollout percentage')).toHaveValue('20')+ })++ it('offers only true and false as the default value', () => {+ const defaultValue = within(screen.getByLabelText('Default value'))+ expect(defaultValue.getAllByRole('button').map((button) => button.textContent)).toEqual(['true', 'false'])+ })++ it('does not count a click on the selected default as an edit', () => {+ fireEvent.click(within(screen.getByLabelText('Default value')).getByText('false'))+ expect(featureFlagRulesV2EditorLogic({ id: 7 }).values.hasUnsavedChanges).toBe(false)+ })++ it("keeps a saved flag's value type on a click or an arrow key", () => {+ fireEvent.click(document.querySelector<HTMLElement>('[data-attr="rules-v2-return-type-string"]')!)+ fireEvent.keyDown(screen.getByLabelText('Value type'), { key: 'ArrowRight' })+ expect(featureFlagRulesV2EditorLogic({ id: 7 }).values.draft.config).toMatchObject({+ return_type: 'boolean',+ default_value: false,+ })+ })++ it('estimates how many users each rule matches and its rollout reaches', async () => {+ const [, rolloutRule] = document.querySelectorAll('[data-attr="rules-v2-rule"]')+ await waitFor(() => expect(rolloutRule).toHaveTextContent('≈ 120 users'))+ expect(rolloutRule).toHaveTextContent('≈ 24 users')+ })++ it('warns that a rule after a rule claiming everyone is never reached, until it moves up', async () => {+ const [beta, rollout] = document.querySelectorAll('[data-attr="rules-v2-rule"]')+ expect(beta.querySelector('[data-attr="rules-v2-rule-unreachable"]')).toBeNull()+ expect(rollout.querySelector('[data-attr="rules-v2-rule-unreachable"]')).toHaveTextContent(+ 'rule 1 already decides the value'+ )++ openRuleMenu(1)+ fireEvent.click(await screen.findByText('Move up'))++ await waitFor(() => expect(rules().map((rule) => rule.id)).toEqual(['rule-rollout', 'rule-beta']))+ expect(document.querySelector('[data-attr="rules-v2-rule-unreachable"]')).toBeNull()+ await waitFor(() => expect(document.activeElement).toBe(screen.getByLabelText('Rule 1 actions')))})- // Moving the card re-inserts it, which drops focus. React's commit then refocuses the button,- // because it is still mounted.- it('keeps focus on the rule a keyboard user moved down', async () => {- const [moveDown] = document.querySelectorAll<HTMLElement>('[data-attr="rules-v2-move-rule-down"]')- moveDown.focus()- fireEvent.click(moveDown)+ it('moves focus to Add rule after deleting a rule, since its card is gone', async () => {+ openRuleMenu(1)+ fireEvent.click(await screen.findByText('Delete rule'))+ expect(rules().map((rule) => rule.id)).toEqual(['rule-beta'])await waitFor(() =>- expect(document.querySelector('[data-attr="rules-v2-rule"] input')).toHaveValue('Everyone else')+ expect(document.activeElement).toBe(+ document.querySelector<HTMLElement>('[data-attr="rules-v2-add-rule"]')+ ))- const focusedRule = document.activeElement?.closest('[data-attr="rules-v2-rule"]')- expect(focusedRule).toHaveTextContent('Rule 2')- expect(focusedRule?.querySelector('input')).toHaveValue('Beta users')+ })++ it('leaves a clean draft on Cancel without asking', async () => {+ featureFlagLogic({ id: 7 }).actions.editFeatureFlag(true)+ fireEvent.click(screen.getByText('Cancel'))++ await waitFor(() => expect(featureFlagLogic({ id: 7 }).values.isEditingFlag).toBe(false))+ expect(screen.queryByText('Discard your changes?')).toBeNull()+ })++ it('asks before Cancel discards unsaved edits', async () => {+ featureFlagLogic({ id: 7 }).actions.editFeatureFlag(true)+ fireEvent.change(screen.getByLabelText('Rule 1 description'), { target: { value: 'Beta testers' } })+ fireEvent.click(screen.getByText('Cancel'))++ expect(await screen.findByText('Discard your changes?')).toBeInTheDocument()+ expect(featureFlagLogic({ id: 7 }).values.isEditingFlag).toBe(true)+ fireEvent.click(screen.getByText('Discard changes'))+ await waitFor(() => expect(featureFlagLogic({ id: 7 }).values.isEditingFlag).toBe(false))+ })++ it('adds a rule of the type picked from the add menu', async () => {+ fireEvent.click(document.querySelector<HTMLElement>('[data-attr="rules-v2-add-rule"]')!)+ fireEvent.click(await screen.findByText('Percentage rollout', { selector: '.font-semibold' }))++ expect(rules()).toHaveLength(3)+ expect(rules()[2]).toEqual({+ rule_type: 'percentage_rollout',+ targeting: { properties: [] },+ value: true,+ rollout_percentage: 0,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ assign_by: 'person',+ })+ })++ it('duplicates a rule below itself without its id or seed', async () => {+ openRuleMenu(1)+ fireEvent.click(await screen.findByText('Duplicate'))++ const { id: _id, seed: _seed, ...copy } = V2_FLAG.filters.rules[1]+ expect(rules().map((rule) => rule.id)).toEqual(['rule-beta', 'rule-rollout', undefined])+ expect(rules()[2]).toEqual(copy)+ await waitFor(() => expect(screen.getByLabelText('Rule 3 description')).toHaveValue('Everyone else'))})})@@ -151,6 +283,12 @@ describe('FeatureFlagRulesV2Editor', () => {await renderEditor(9)})+ it('estimates the reach of an experiment rule net of its holdout', async () => {+ const [rule] = document.querySelectorAll('[data-attr="rules-v2-rule"]')+ await waitFor(() => expect(rule).toHaveTextContent('≈ 120 users'))+ expect(rule).toHaveTextContent('≈ 57 users')+ })+it('keeps a variant value that differs from its key when the key is renamed', () => {fireEvent.change(screen.getByLabelText('Variant 1 key'), { target: { value: 'baseline' } })expect(screen.getByLabelText('Variant 1 value')).toHaveValue('standard')@@ -201,4 +339,77 @@ describe('FeatureFlagRulesV2Editor', () => {await waitFor(() => expect(screen.getByLabelText('Holdout excludes')).toHaveValue('10'))})})++ describe('an object flag', () => {+ const logic = (): ReturnType<typeof featureFlagRulesV2EditorLogic> => featureFlagRulesV2EditorLogic({ id: 11 })+ const json = (label: string): HTMLElement => within(screen.getByLabelText(label)).getByRole('textbox')++ beforeEach(async () => {+ await renderEditor(11)+ })++ it('shows each stored object as formatted JSON', () => {+ expect(json('Value')).toHaveValue('{\n "columns": 2\n}')+ expect(json('Default value')).toHaveValue('{\n "columns": 1\n}')+ })++ it('keeps text that is not an object yet as typed and flags it, then stores the object it becomes', () => {+ fireEvent.change(json('Value'), { target: { value: '{"columns": ' } })+ expect(logic().values.draft.config.rules[0]).toMatchObject({ value: '{"columns": ' })+ expect(screen.getByText('Enter a valid JSON object.')).toBeInTheDocument()++ fireEvent.change(json('Value'), { target: { value: '{"columns": 3}' } })+ expect(logic().values.draft.config.rules[0]).toMatchObject({ value: { columns: 3 } })+ expect(json('Value')).toHaveValue('{"columns": 3}')+ expect(screen.queryByText('Enter a valid JSON object.')).not.toBeInTheDocument()+ })++ it('stores a cleared default as null and shows a value set elsewhere', async () => {+ fireEvent.change(json('Default value'), { target: { value: '' } })+ expect(logic().values.draft.config.default_value).toBeNull()++ logic().actions.setConfig({ default_value: { columns: 4 } })+ await waitFor(() => expect(json('Default value')).toHaveValue('{\n "columns": 4\n}'))+ })+ })++ describe('a number flag', () => {+ const draftConfig = (): Record<string, any> => featureFlagRulesV2EditorLogic({ id: 12 }).values.draft.config++ beforeEach(async () => {+ await renderEditor(12)+ })++ it('stores typed numbers, and an empty input as no number', () => {+ expect(screen.getByLabelText('Value')).toHaveValue(25)+ fireEvent.change(screen.getByLabelText('Value'), { target: { value: '-0.5' } })+ expect(draftConfig().rules[0].value).toBe(-0.5)++ fireEvent.change(screen.getByLabelText('Value'), { target: { value: '' } })+ expect(draftConfig().rules[0].value).toBeNull()+ expect(screen.getByText('Enter a number.')).toBeInTheDocument()++ fireEvent.change(screen.getByLabelText('Default value'), { target: { value: '' } })+ expect(draftConfig().default_value).toBeNull()+ })++ it('empties an input whose number is cleared elsewhere', async () => {+ expect(screen.getByLabelText('Default value')).toHaveValue(10)++ featureFlagRulesV2EditorLogic({ id: 12 }).actions.setConfig({ default_value: null })++ await waitFor(() => expect(screen.getByLabelText('Default value')).toHaveValue(null))+ })++ it('moves focus to the first rule type after deleting the last rule', async () => {+ fireEvent.click(screen.getByLabelText('Rule 1 actions'))+ fireEvent.click(await screen.findByText('Delete rule'))++ await waitFor(() =>+ expect(document.activeElement).toBe(+ document.querySelector('[data-attr="rules-v2-add-rule-targeted_release"]')+ )+ )+ })+ })})diff --git a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsxindex 9d6927310094..f68b1f302f68 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx@@ -1,61 +1,294 @@+import {+ Announcements,+ DndContext,+ DragEndEvent,+ KeyboardSensor,+ PointerSensor,+ UniqueIdentifier,+ closestCenter,+ useSensor,+ useSensors,+} from '@dnd-kit/core'+import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'+import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable'+import clsx from 'clsx'import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { useId } from 'react'+import { Fragment, Ref, useCallback, useId, useMemo, useRef } from 'react'-import { IconPlusSmall } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonInput, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'+import { IconCalculator, IconCheckCircle, IconCode, IconLetter, IconPlusSmall, IconToggle } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonDialog, LemonInput, LemonMenu, LemonTextArea, Tooltip } from '@posthog/lemon-ui'import { Button } from '@posthog/quill'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonField } from 'lib/lemon-ui/LemonField'-import { capitalizeFirstLetter } from 'lib/utils/strings'+import { objectsEqual } from 'lib/utils/objects'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { Noun, groupsModel } from '~/models/groupsModel'import { tagsModel } from '~/models/tagsModel'+import { FeatureFlagRulesV2ReturnType } from '~/types'import { RULES_V2_EDITABLE_RETURN_TYPES } from 'products/feature_flags/frontend/featureFlagConfigFormat'+import {+ RULES_V2_RULE_TYPES,+ RULES_V2_RULE_TYPE_META,+ RulesV2Connector,+ RulesV2DefaultStep,+ RulesV2FieldError,+ RulesV2RuleType,+ RulesV2RulesHeading,+ rulesV2RuleTypeMenuLabel,+} from 'products/feature_flags/frontend/RulesV2Flow'import { FeatureFlagLogicProps, slugifyFeatureFlagKey } from './featureFlagLogic'import { featureFlagRulesV2EditorLogic } from './featureFlagRulesV2EditorLogic'import { RulesV2RuleEditor } from './RulesV2RuleEditor'import { RulesV2ValueInput } from './RulesV2ValueInput'-const RETURN_TYPE_OPTIONS = RULES_V2_EDITABLE_RETURN_TYPES.map((value) => ({+const RETURN_TYPE_META: Record<+ FeatureFlagRulesV2ReturnType,+ { label: string; description: string; icon: JSX.Element }+> = {+ boolean: {+ label: 'Boolean',+ description: 'Serves true or false. For releases, kill switches and simple tests.',+ icon: <IconToggle />,+ },+ string: {+ label: 'String',+ description: 'Serves a text value, such as a variant name or a config key.',+ icon: <IconLetter />,+ },+ number: {+ label: 'Number',+ description: 'Serves a number, such as a limit, a timeout or a price.',+ icon: <IconCalculator />,+ },+ object: {+ label: 'JSON object',+ description: 'Serves a JSON object, such as remote config or settings for a variant.',+ icon: <IconCode />,+ },+}++function ReturnTypePicker({value,- label: capitalizeFirstLetter(value),-}))+ onChange,+ disabledReason,+}: {+ value: FeatureFlagRulesV2ReturnType+ onChange: (returnType: FeatureFlagRulesV2ReturnType) => void+ disabledReason?: string+}): JSX.Element {+ const types = RULES_V2_EDITABLE_RETURN_TYPES+ // Arrow keys move the selection, as in any radio group.+ const onKeyDown = (event: React.KeyboardEvent): void => {+ const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]+ if (!step || disabledReason) {+ return+ }+ event.preventDefault()+ const next = types[(types.indexOf(value) + step + types.length) % types.length]+ onChange(next)+ event.currentTarget.querySelector<HTMLElement>(`[data-return-type="${next}"]`)?.focus()+ }+ return (+ <div+ className="grid grid-cols-1 sm:grid-cols-2 gap-2"+ role="radiogroup"+ aria-label="Value type"+ onKeyDown={onKeyDown}+ data-attr="rules-v2-return-type"+ >+ {types.map((returnType) => {+ const meta = RETURN_TYPE_META[returnType]+ const selected = value === returnType+ const disabled = !!disabledReason && !selected+ return (+ <Tooltip key={returnType} title={disabled ? disabledReason : undefined}>+ <button+ type="button"+ role="radio"+ aria-checked={selected}+ // aria-disabled rather than disabled, so the tooltip with the reason still shows.+ aria-disabled={disabled}+ tabIndex={selected ? 0 : -1}+ data-return-type={returnType}+ onClick={() => !disabledReason && onChange(returnType)}+ className={clsx(+ 'text-left rounded border p-2.5 flex flex-col gap-1 transition-colors bg-surface-primary',+ selected+ ? 'border-accent ring-1 ring-accent'+ : disabledReason+ ? 'opacity-50 cursor-not-allowed'+ : 'hover:border-secondary cursor-pointer'+ )}+ data-attr={`rules-v2-return-type-${returnType}`}+ >+ <span className="flex items-center gap-1.5 font-semibold">+ <span className="text-base flex">{meta.icon}</span>+ {meta.label}+ {selected && <IconCheckCircle className="ml-auto text-accent text-base" />}+ </span>+ <span className="text-xs text-secondary">{meta.description}</span>+ </button>+ </Tooltip>+ )+ })}+ </div>+ )+}++function AddRule({+ onAdd,+ empty,+ subjects,+ buttonRef,+}: {+ onAdd: (ruleType: RulesV2RuleType) => void+ empty: boolean+ subjects: Noun+ buttonRef: Ref<HTMLButtonElement>+}): JSX.Element {+ if (empty) {+ return (+ <div className="rounded border border-dashed p-4 flex flex-col gap-3" data-attr="rules-v2-empty-rules">+ <div className="flex flex-col">+ <span className="font-semibold">Add your first rule</span>+ <span className="text-xs text-secondary">+ Until you add a rule, all {subjects.plural} get the default value below.+ </span>+ </div>+ <div className="grid grid-cols-1 md:grid-cols-3 gap-2">+ {RULES_V2_RULE_TYPES.map((ruleType, index) => {+ const meta = RULES_V2_RULE_TYPE_META[ruleType]+ return (+ <button+ key={ruleType}+ ref={index === 0 ? buttonRef : undefined}+ type="button"+ onClick={() => onAdd(ruleType)}+ className="text-left rounded border bg-surface-primary p-3 flex flex-col gap-1 cursor-pointer hover:border-accent transition-colors"+ data-attr={`rules-v2-add-rule-${ruleType}`}+ >+ <span className="flex items-center gap-1.5 font-semibold">+ <span className="text-base flex text-secondary">{meta.icon}</span>+ {meta.label}+ </span>+ <span className="text-xs text-secondary">{meta.description}</span>+ </button>+ )+ })}+ </div>+ </div>+ )+ }+ return (+ <LemonMenu+ placement="bottom-start"+ items={RULES_V2_RULE_TYPES.map((ruleType) => ({+ label: rulesV2RuleTypeMenuLabel(ruleType),+ icon: RULES_V2_RULE_TYPE_META[ruleType].icon,+ onClick: () => onAdd(ruleType),+ 'data-attr': `rules-v2-add-rule-${ruleType}`,+ }))}+ >+ <LemonButton+ ref={buttonRef}+ type="secondary"+ icon={<IconPlusSmall />}+ fullWidth+ center+ className="border-dashed"+ data-attr="rules-v2-add-rule"+ >+ Add rule+ </LemonButton>+ </LemonMenu>+ )+}export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.Element {const logic = featureFlagRulesV2EditorLogic({ id })- const { draft, ruleKeys, featureFlag, saving, saveError, saveDisabledReason, fieldError } = useValues(logic)- const { setDraft, setConfig, setReturnType, addRule, saveRulesV2Flag, editFeatureFlag } = useActions(logic)+ const {+ draft,+ rules,+ ruleKeys,+ shadowingRules,+ featureFlag,+ saving,+ saveError,+ saveDisabledReason,+ fieldError,+ hasUnsavedChanges,+ } = useValues(logic)+ const { setDraft, setConfig, setReturnType, addRule, moveRule, saveRulesV2Flag, editFeatureFlag } =+ useActions(logic)const { tags } = useValues(tagsModel)const { loadTagsIfNeeded } = useActions(tagsModel)+ const { aggregationLabel } = useValues(groupsModel)const isNew = id === 'new'const keyInputId = useId()const descriptionInputId = useId()- const defaultValueInputId = useId()const returnType = draft.config.return_type+ const groupTypeIndex = draft.config.aggregation_group_type_index+ const subjects = useMemo(() => aggregationLabel(groupTypeIndex, true), [aggregationLabel, groupTypeIndex])const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')+ const addRuleRef = useRef<HTMLButtonElement | null>(null)+ // A deleted rule's card and its focused menu button unmount, so focus moves to adding a rule.+ const focusAddRule = useCallback((): void => {+ setTimeout(() => addRuleRef.current?.focus())+ }, [])+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })+ )+ // dnd-kit would read out its internal ids; users know rules by their number.+ const ruleNumber = (id: UniqueIdentifier | undefined): number => ruleKeys.indexOf(Number(id)) + 1+ const dragAnnouncements: Announcements = {+ onDragStart: ({ active }) => `Picked up rule ${ruleNumber(active.id)}.`,+ onDragOver: ({ active, over }) =>+ over ? `Rule ${ruleNumber(active.id)} is over position ${ruleNumber(over.id)}.` : undefined,+ onDragEnd: ({ active, over }) =>+ over+ ? `Rule ${ruleNumber(active.id)} moved to position ${ruleNumber(over.id)}.`+ : `Rule ${ruleNumber(active.id)} dropped.`,+ onDragCancel: ({ active }) => `Moving rule ${ruleNumber(active.id)} was cancelled.`,+ }+ const onDragEnd = ({ active, over }: DragEndEvent): void => {+ if (over && active.id !== over.id) {+ moveRule(ruleKeys.indexOf(Number(active.id)), ruleKeys.indexOf(Number(over.id)))+ }+ }+ const cancel = (): void => {+ if (isNew) {+ // Leaving the page asks before it discards a dirty draft.+ router.actions.push(urls.featureFlags())+ } else if (hasUnsavedChanges) {+ LemonDialog.open({+ title: 'Discard your changes?',+ description: 'Your edits to this flag will be lost.',+ primaryButton: { children: 'Discard changes', status: 'danger', onClick: () => editFeatureFlag(false) },+ secondaryButton: { children: 'Keep editing' },+ })+ } else {+ editFeatureFlag(false)+ }+ }return (- <div className="flex flex-col gap-4" data-attr="feature-flag-rules-v2-editor">+ <div className="flex flex-col gap-4 pb-16" data-attr="feature-flag-rules-v2-editor"><SceneTitleSection- name={draft.key || 'New rules v2 flag'}+ name={draft.key || (isNew ? 'New rules v2 flag' : featureFlag.key)}resourceType={{ type: !isNew && featureFlag.active ? 'feature_flag' : 'feature_flag_off' }}actions={todayRailNav ? (<>- <Button- variant="outline"- data-attr="cancel-rules-v2-flag"- onClick={() =>- isNew ? router.actions.push(urls.featureFlags()) : editFeatureFlag(false)- }- >+ <Button variant="outline" data-attr="cancel-rules-v2-flag" onClick={cancel}>Cancel</Button><Button@@ -65,7 +298,7 @@ export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.EledisabledReason={saveDisabledReason}onClick={saveRulesV2Flag}>- Save+ {isNew ? 'Create flag' : 'Save'}</Button></>) : (@@ -74,9 +307,7 @@ export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.Eletype="secondary"size="small"data-attr="cancel-rules-v2-flag"- onClick={() =>- isNew ? router.actions.push(urls.featureFlags()) : editFeatureFlag(false)- }+ onClick={cancel}>Cancel</LemonButton>@@ -88,7 +319,7 @@ export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.EledisabledReason={saveDisabledReason}onClick={saveRulesV2Flag}>- Save+ {isNew ? 'Create flag' : 'Save'}</LemonButton></>)@@ -100,115 +331,150 @@ export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.Ele{saveError.message}</LemonBanner>)}- <div className="rounded border p-3 bg-surface-primary flex flex-col gap-3 max-w-200">- <LemonField.Pure- label="Flag key"- htmlFor={keyInputId}- error={fieldError('key')}- help={- !isNew && draft.key !== featureFlag.key- ? 'Changing the key breaks every SDK call that uses the old one.'- : undefined- }- >- <LemonInput- id={keyInputId}- value={draft.key}- onChange={(key) => setDraft({ key: slugifyFeatureFlagKey(key) })}- data-attr="rules-v2-flag-key"- className="ph-ignore-input"- autoComplete="off"- spellCheck={false}- placeholder="e.g. new-checkout"- />- </LemonField.Pure>- <LemonField.Pure- label="Description"- htmlFor={descriptionInputId}- showOptional- error={fieldError('name')}- >- <LemonTextArea- id={descriptionInputId}- value={draft.name}- onChange={(name) => setDraft({ name })}- className="ph-ignore-input"- />- </LemonField.Pure>- <LemonField.Pure label="Tags" showOptional error={fieldError('tags')}>- <ObjectTags- tags={draft.tags}- onChange={(tags) => setDraft({ tags })}- onEdit={loadTagsIfNeeded}- saving={saving}- tagsAvailable={tags.filter((tag: string) => !draft.tags.includes(tag))}- data-attr="rules-v2-flag-tags"- />- </LemonField.Pure>- <div className="flex flex-wrap gap-4">- <LemonField.Pure label="Return type" error={fieldError('filters.return_type')}>- <LemonSelect+ <div className="flex gap-4 flex-wrap items-start">+ <div className="flex-1 min-w-[20rem] max-w-[32rem] flex flex-col gap-4">+ <div className="rounded border p-3 bg-surface-primary flex flex-col gap-3">+ <LemonField.Pure+ label="Flag key"+ htmlFor={keyInputId}+ error={fieldError('key')}+ help={+ !isNew && draft.key !== featureFlag.key+ ? 'Changing the key breaks every SDK call that uses the old one.'+ : 'The key your code passes to the SDK. Letters, numbers, hyphens and underscores.'+ }+ >+ <LemonInput+ id={keyInputId}+ value={draft.key}+ onChange={(key) => setDraft({ key: slugifyFeatureFlagKey(key) })}+ data-attr="rules-v2-flag-key"+ className="ph-ignore-input font-mono"+ autoComplete="off"+ autoFocus={isNew}+ spellCheck={false}+ placeholder="e.g. new-checkout"+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="Description"+ htmlFor={descriptionInputId}+ showOptional+ error={fieldError('name')}+ >+ <LemonTextArea+ id={descriptionInputId}+ value={draft.name}+ onChange={(name) => setDraft({ name })}+ placeholder="What does this flag control?"+ minRows={2}+ className="ph-ignore-input"+ />+ </LemonField.Pure>+ <LemonField.Pure label="Tags" showOptional error={fieldError('tags')}>+ <ObjectTags+ tags={draft.tags}+ onChange={(tags) => setDraft({ tags })}+ onEdit={loadTagsIfNeeded}+ saving={saving}+ tagsAvailable={tags.filter((tag: string) => !draft.tags.includes(tag))}+ data-attr="rules-v2-flag-tags"+ />+ </LemonField.Pure>+ </div>+ <div className="rounded border p-3 bg-surface-primary flex flex-col gap-2">+ <div className="flex flex-col">+ <span className="font-semibold">Value type</span>+ <span className="text-xs text-secondary">+ {isNew+ ? 'What the flag returns. You cannot change it after the flag is created.'+ : 'What the flag returns. It is fixed once the flag exists.'}+ </span>+ </div>+ <ReturnTypePickervalue={returnType}onChange={setReturnType}- options={RETURN_TYPE_OPTIONS}disabledReason={- isNew ? undefined : 'The return type cannot be changed after the flag is created.'+ isNew ? undefined : 'The value type cannot be changed after the flag is created.'}- data-attr="rules-v2-return-type"- />- </LemonField.Pure>- <LemonField.Pure- label="Default value"- htmlFor={defaultValueInputId}- help={- returnType === 'boolean'- ? "Returned when no rule matches. Null returns no value, so the SDK uses the caller's default."- : "Returned when no rule matches. Leave it empty to return no value, so the SDK uses the caller's default."- }- error={fieldError('filters.default_value')}- >- <RulesV2ValueInput- id={defaultValueInputId}- returnType={returnType}- value={draft.config.default_value}- onChange={(default_value) => setConfig({ default_value })}- nullable- data-attr="rules-v2-default-value"/>- </LemonField.Pure>+ <RulesV2FieldError error={fieldError('filters.return_type')} />+ </div>+ <div className="rounded border border-dashed p-3 flex flex-col gap-2 text-xs text-secondary">+ <span className="font-semibold text-default text-sm">How rules work</span>+ <ol className="m-0 pl-4 flex flex-col gap-1 list-decimal">+ <li>Rules are checked from the top. Drag a rule to change its place.</li>+ <li>+ A rule first checks its conditions. A {subjects.singular} who doesn't match moves on+ to the next rule.+ </li>+ <li>+ A rollout or experiment then picks a share of the matching {subjects.plural}. You+ choose whether the rest move on or get the default value.+ </li>+ <li>The first rule that serves a value wins. Nobody is served twice.</li>+ </ol>+ {isNew && <span>New flags are created disabled. Enable the flag on its page.</span>}+ </div></div>- {isNew && (- <p className="text-xs text-muted m-0">- New flags are created disabled. Enable the flag from its page after saving.- </p>- )}- </div>- <div className="flex flex-col gap-2 max-w-200">- <span className="font-semibold">Rules</span>- <p className="text-xs text-muted m-0">- Rules are evaluated top to bottom; the first match decides.- </p>- {draft.config.rules.map((rule, index) => (- <RulesV2RuleEditor- key={ruleKeys[index]}- ruleKey={ruleKeys[index]}- id={id}- index={index}- rule={rule}- ruleCount={draft.config.rules.length}- returnType={returnType}- />- ))}- <div>- <LemonButton- type="secondary"- size="small"- icon={<IconPlusSmall />}- onClick={addRule}- data-attr="rules-v2-add-rule"+ <div className="flex-[2] min-w-[30rem] flex flex-col" data-attr="rules-v2-rules">+ <RulesV2RulesHeading subjects={subjects} className="mb-2" />+ <DndContext+ accessibility={{ announcements: dragAnnouncements }}+ sensors={sensors}+ collisionDetection={closestCenter}+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}+ onDragEnd={onDragEnd}>- Add rule- </LemonButton>+ <SortableContext items={ruleKeys} strategy={verticalListSortingStrategy}>+ <div className="flex flex-col">+ {rules.map((rule, index) => (+ <Fragment key={ruleKeys[index]}>+ <RulesV2RuleEditor+ ruleKey={ruleKeys[index]}+ id={id}+ index={index}+ rule={rule}+ ruleCount={rules.length}+ returnType={returnType}+ defaultValue={draft.config.default_value}+ subjects={subjects}+ groupTypeIndex={groupTypeIndex ?? null}+ shadowedBy={shadowingRules[index]}+ onRemoved={focusAddRule}+ />+ <RulesV2Connector />+ </Fragment>+ ))}+ </div>+ </SortableContext>+ </DndContext>+ <AddRule+ onAdd={addRule}+ empty={rules.length === 0}+ subjects={subjects}+ buttonRef={addRuleRef}+ />+ <RulesV2Connector />+ <RulesV2DefaultStep subjects={subjects} rules={rules}>+ <div className="flex flex-col gap-1">+ <RulesV2ValueInput+ aria-label="Default value"+ returnType={returnType}+ value={draft.config.default_value}+ onChange={(default_value) => {+ // A click on the selected true or false reports it again, which is not an edit.+ if (!objectsEqual(default_value, draft.config.default_value)) {+ setConfig({ default_value })+ }+ }}+ nullable+ className="w-56"+ data-attr="rules-v2-default-value"+ />+ <RulesV2FieldError error={fieldError('filters.default_value')} />+ </div>+ </RulesV2DefaultStep></div></div></SceneContent>diff --git a/frontend/src/scenes/feature-flags/QuillFeatureFlagsActions.tsx b/frontend/src/scenes/feature-flags/QuillFeatureFlagsActions.tsxindex 646cb986e217..65dfa9946977 100644--- a/frontend/src/scenes/feature-flags/QuillFeatureFlagsActions.tsx+++ b/frontend/src/scenes/feature-flags/QuillFeatureFlagsActions.tsx@@ -1,14 +1,12 @@import { IconPlus } from '@posthog/icons'import { Button, ButtonGroup } from '@posthog/quill'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { FeedbackSurveyButton } from 'lib/components/FeedbackSurveyButton/FeedbackSurveyButton'import { Shortcut } from 'lib/components/Shortcuts/Shortcut'import { keyBinds } from 'lib/components/Shortcuts/shortcuts'import { LinkPrimitive } from 'lib/lemon-ui/Link'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { Scene } from 'scenes/sceneTypes'-import { urls } from 'scenes/urls'import { AccessControlLevel, AccessControlResourceType } from '~/types'@@ -35,21 +33,6 @@ export function QuillFeatureFlagsActions({return (<><FeedbackSurveyButton surveyId={feedbackSurveyId} data-attr="feature-flags-feedback-button" />- {showRulesV2Editor && (- <AccessControlAction- resourceType={AccessControlResourceType.FeatureFlag}- minAccessLevel={AccessControlLevel.Editor}- >- <Button- variant="outline"- render={<LinkPrimitive to={urls.featureFlagNew({ format: 'rules_v2' })} />}- disabledReason={rulesV2DisabledReason}- data-attr="new-rules-v2-feature-flag"- >- New rules v2 flag- </Button>- </AccessControlAction>- )}<ButtonGroup><Shortcutname="NewFeatureFlag"@@ -70,7 +53,11 @@ export function QuillFeatureFlagsActions({New</Button></Shortcut>- <QuillNewFeatureFlagMenu disabledReason={createDisabledReason} />+ <QuillNewFeatureFlagMenu+ disabledReason={createDisabledReason}+ showRulesV2Editor={showRulesV2Editor}+ rulesV2DisabledReason={rulesV2DisabledReason}+ /></ButtonGroup></>)diff --git a/frontend/src/scenes/feature-flags/QuillNewFeatureFlagMenu.tsx b/frontend/src/scenes/feature-flags/QuillNewFeatureFlagMenu.tsxindex 051c1b8369cf..46ebee816213 100644--- a/frontend/src/scenes/feature-flags/QuillNewFeatureFlagMenu.tsx+++ b/frontend/src/scenes/feature-flags/QuillNewFeatureFlagMenu.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import React from 'react'-import { IconChevronDown, IconCode, IconFlask, IconSparkles, IconWrench } from '@posthog/icons'+import { IconChevronDown, IconCode, IconFlag, IconFlask, IconSparkles, IconWrench } from '@posthog/icons'import {Button,DropdownMenu,@@ -31,7 +31,15 @@ import { INTENT_KEYS, INTENT_METADATA } from 'products/feature_flags/frontend/feimport { AI_SUGGESTIONS, AI_TOOL_DEFINITION, TEMPLATES, TEMPLATE_METADATA } from './NewFeatureFlagMenu'-export function QuillNewFeatureFlagMenu({ disabledReason }: { disabledReason?: string | null }): JSX.Element {+export function QuillNewFeatureFlagMenu({+ disabledReason,+ showRulesV2Editor,+ rulesV2DisabledReason,+}: {+ disabledReason?: string | null+ showRulesV2Editor?: boolean+ rulesV2DisabledReason?: string | null+}): JSX.Element {const { featureFlags } = useValues(enabledFeaturesLogic)const { setActiveGroup } = useActions(maxLogic({ panelId: SIDE_PANEL_PANEL_ID }))const { openSidePanel } = useActions(sidePanelLogic)@@ -55,6 +63,26 @@ export function QuillNewFeatureFlagMenu({ disabledReason }: { disabledReason?: s<IconChevronDown /></DropdownMenuTrigger><DropdownMenuContent align="end" className="min-w-64">+ {showRulesV2Editor && (+ <>+ <DropdownMenuItem+ data-attr="new-rules-v2-feature-flag"+ disabledReason={disabledReason || rulesV2DisabledReason}+ render={+ <Button+ size="row"+ left+ render={<LinkPrimitive to={urls.featureFlagNew({ format: 'rules_v2' })} />}+ />+ }+ description="Ordered rules, rollouts and experiments"+ >+ <IconFlag />+ New rules v2 flag+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}{TEMPLATES.map((template) => {const metadata = TEMPLATE_METADATA[template]if (intentsEnabled) {diff --git a/frontend/src/scenes/feature-flags/RulesV2ExperimentFields.tsx b/frontend/src/scenes/feature-flags/RulesV2ExperimentFields.tsxindex 1c049f80b02a..16999d46b797 100644--- a/frontend/src/scenes/feature-flags/RulesV2ExperimentFields.tsx+++ b/frontend/src/scenes/feature-flags/RulesV2ExperimentFields.tsx@@ -1,14 +1,22 @@import { useActions, useValues } from 'kea'-import { useId } from 'react'-import { IconBalance, IconPlusSmall, IconTrash } from '@posthog/icons'+import { IconBalance, IconCheckCircle, IconPlusSmall, IconTrash, IconWarning } from '@posthog/icons'import { LemonButton, LemonInput, LemonSwitch } from '@posthog/lemon-ui'import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'import { LemonField } from 'lib/lemon-ui/LemonField'+import { Noun } from '~/models/groupsModel'import { FeatureFlagRulesV2DraftExperimentRule, FeatureFlagRulesV2ReturnType, FeatureFlagRulesV2Variant } from '~/types'+import {+ RulesV2AllocationBar,+ RulesV2FieldError,+ RulesV2RuleRow,+ rulesV2ExperimentSegments,+ rulesV2VariantColor,+} from 'products/feature_flags/frontend/RulesV2Flow'+import { FeatureFlagLogicProps } from './featureFlagLogic'import {MAX_VARIANTS,@@ -16,6 +24,7 @@ import {NEW_HOLDOUT,moved,newVariant,+ rulesV2VariantWeightTotal,withEqualWeights,withVariantKey,} from './featureFlagRulesV2Draft'@@ -28,66 +37,78 @@ interface ExperimentFieldsProps extends FeatureFlagLogicProps {rule: FeatureFlagRulesV2DraftExperimentRule}-/** Pause and holdout, which an experiment rule checks before its rollout. Seeds are server-owned and never shown. */-export function RulesV2PauseAndHoldoutFields({ id, index, rule }: ExperimentFieldsProps): JSX.Element {+/** The holdout, which an experiment rule checks before its rollout. Seeds are server-owned and never shown. */+export function RulesV2HoldoutRow({+ id,+ index,+ rule,+ subjects,+}: ExperimentFieldsProps & { subjects: Noun }): JSX.Element {const { fieldError } = useValues(featureFlagRulesV2EditorLogic({ id }))const { updateRule } = useActions(featureFlagRulesV2EditorLogic({ id }))const path = `filters.rules[${index}]`- const holdoutInputId = useId()const { holdout, ...withoutHoldout } = ruleconst holdoutSeedError = fieldError(`${path}.holdout.seed`)+ const error =+ fieldError(`${path}.holdout`) ??+ fieldError(`${path}.holdout.exclusion_percentage`) ??+ (holdoutSeedError && `Holdout seed: ${holdoutSeedError}`)return (- <div className="flex flex-wrap gap-4">- <LemonField.Pure- help="Matching persons get the default value while the experiment is paused."- error={fieldError(`${path}.paused`)}- >+ <RulesV2RuleRow label="Holdout">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 min-h-7"><LemonSwitch- label="Paused"- checked={rule.paused}- onChange={(paused) => updateRule(index, { ...rule, paused })}- bordered- data-attr="rules-v2-experiment-paused"+ aria-label="Hold out users"+ checked={!!holdout}+ // Removing the holdout drops its stored seed; the server keeps it if the holdout is added back before saving.+ onChange={(on) => updateRule(index, on ? { ...rule, holdout: NEW_HOLDOUT } : withoutHoldout)}+ data-attr="rules-v2-experiment-holdout"/>- </LemonField.Pure>- <div className="flex flex-col gap-2">- <LemonField.Pure- help="Held-out persons get the default value and no variant."- error={fieldError(`${path}.holdout`) ?? (holdoutSeedError && `Holdout seed: ${holdoutSeedError}`)}- >- <LemonSwitch- label="Hold out persons"- checked={!!holdout}- // Removing the holdout drops its stored seed; the server keeps it if the holdout is added back before saving.- onChange={(on) => updateRule(index, on ? { ...rule, holdout: NEW_HOLDOUT } : withoutHoldout)}- bordered- data-attr="rules-v2-experiment-holdout"- />- </LemonField.Pure>- {holdout && (- <LemonField.Pure- label="Holdout excludes"- htmlFor={holdoutInputId}- className="w-40"- error={fieldError(`${path}.holdout.exclusion_percentage`)}- >- <PercentageInput- id={holdoutInputId}- value={holdout.exclusion_percentage}- onChange={(exclusion_percentage) =>- updateRule(index, { ...rule, holdout: { ...holdout, exclusion_percentage } })- }- data-attr="rules-v2-experiment-holdout-percentage"- />- </LemonField.Pure>+ {holdout ? (+ <>+ <span>Hold out</span>+ <div className="w-24">+ <PercentageInput+ aria-label="Holdout excludes"+ value={holdout.exclusion_percentage}+ onChange={(exclusion_percentage) =>+ updateRule(index, { ...rule, holdout: { ...holdout, exclusion_percentage } })+ }+ data-attr="rules-v2-experiment-holdout-percentage"+ />+ </div>+ <span className="text-secondary">+ of matching {subjects.plural}. They get the default value and no variant.+ </span>+ </>+ ) : (+ <span className="text-secondary">+ No holdout. Turn it on to keep a share of {subjects.plural} out of every variant.+ </span>)}</div>- </div>+ <RulesV2FieldError error={error} />+ </RulesV2RuleRow>+ )+}++function WeightTotal({ variants }: { variants: FeatureFlagRulesV2Variant[] }): JSX.Element {+ const total = rulesV2VariantWeightTotal(variants)+ const ok = total === 100+ return (+ <span+ className={`inline-flex items-center gap-1 text-xs tabular-nums ${ok ? 'text-success' : 'text-danger'}`}+ data-attr="rules-v2-weight-total"+ >+ {ok ? <IconCheckCircle /> : <IconWarning />}+ Total {total}%+ </span>)}-export function RulesV2VariantsField({+const VARIANT_GRID = 'grid grid-cols-[0.625rem_minmax(0,1fr)_minmax(0,1fr)_6rem_auto] gap-x-2 items-start'++export function RulesV2VariantsRow({id,index,rule,@@ -104,25 +125,18 @@ export function RulesV2VariantsField({const variantsError = fieldError(`${path}.variants`)return (- <LemonField.Pure- label="Variants"- help="Each enrolled person gets one variant, picked by weight. Changing the weights or their order moves some persons to another variant."- >- <div className="flex flex-col gap-2" data-attr="rules-v2-variants">- <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_7rem_6.5rem] gap-2 items-center text-xs font-semibold text-secondary">- <span>Key</span>- <span>Value</span>- <span className="flex items-center gap-1">- Weight- <LemonButton- size="xsmall"- icon={<IconBalance />}- tooltip="Distribute weights equally"- onClick={() => setVariants(withEqualWeights(variants))}- data-attr="rules-v2-distribute-weights"- />- </span>+ <RulesV2RuleRow label="Variants">+ <div className="flex flex-col gap-2 pt-1" data-attr="rules-v2-variants">+ <div className="flex items-center gap-3">+ <RulesV2AllocationBar segments={rulesV2ExperimentSegments(rule)} className="flex-1" />+ <WeightTotal variants={variants} />+ </div>+ <div className={`${VARIANT_GRID} text-xxs font-semibold uppercase tracking-wide text-muted`}><span />+ <span>Key</span>+ <span>Serves</span>+ <span>Share</span>+ <span className="w-[5.25rem]" /></div>{variants.map((variant, variantIndex) => {const variantPath = `${path}.variants[${variantIndex}]`@@ -131,9 +145,14 @@ export function RulesV2VariantsField({<div// Rows hold no state of their own; with index keys, focus stays put when a row moves.key={variantIndex}- className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_7rem_6.5rem] gap-2 items-start"+ className={VARIANT_GRID}data-attr="rules-v2-variant">+ <span+ className="size-2.5 rounded-full mt-2.5"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ background: rulesV2VariantColor(variantIndex) }}+ /><LemonField.Pure error={fieldError(`${variantPath}.key`) ?? fieldError(variantPath)}><LemonInputaria-label={`${label} key`}@@ -142,7 +161,8 @@ export function RulesV2VariantsField({setVariant(variantIndex, withVariantKey(variant, key, returnType))}placeholder="e.g. test"- className="ph-ignore-input"+ size="small"+ className="ph-ignore-input font-mono"autoComplete="off"spellCheck={false}data-attr="rules-v2-variant-key"@@ -187,7 +207,6 @@ export function RulesV2VariantsField({<LemonButtonicon={<IconTrash />}size="small"- status="danger"tooltip="Remove variant"disabledReason={variants.length <= MIN_VARIANTS@@ -201,8 +220,8 @@ export function RulesV2VariantsField({</div>)})}- {variantsError && <LemonField.Error error={variantsError} />}- <div>+ <RulesV2FieldError error={variantsError} />+ <div className="flex flex-wrap items-center gap-2"><LemonButtontype="secondary"size="small"@@ -217,8 +236,20 @@ export function RulesV2VariantsField({>Add variant</LemonButton>+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconBalance />}+ onClick={() => setVariants(withEqualWeights(variants))}+ data-attr="rules-v2-distribute-weights"+ >+ Split equally+ </LemonButton>+ <span className="text-xs text-secondary">+ Changing weights or their order moves some enrolled users to another variant.+ </span></div></div>- </LemonField.Pure>+ </RulesV2RuleRow>)}diff --git a/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx b/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsxindex 50876133b2fd..9f105a25a15a 100644--- a/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx+++ b/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx@@ -1,158 +1,348 @@+import { useSortable } from '@dnd-kit/sortable'+import { CSS } from '@dnd-kit/utilities'+import clsx from 'clsx'import { useActions, useValues } from 'kea'-import { useId } from 'react'+import { memo, useRef } from 'react'-import { IconTrash } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'+import { IconCopy, IconEllipsis, IconPause, IconPlay, IconTrash } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonInput, LemonMenu, LemonSelect } from '@posthog/lemon-ui'import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'-import { LemonField } from 'lib/lemon-ui/LemonField'+import { IconArrowDown, IconArrowUp, SortableDragIcon } from 'lib/lemon-ui/icons'+import { LemonSlider } from 'lib/lemon-ui/LemonSlider'+import { capitalizeFirstLetter } from 'lib/utils/strings'-import { FeatureFlagRulesV2DraftRule, FeatureFlagRulesV2ReturnType } from '~/types'+import { Noun } from '~/models/groupsModel'+import { FeatureFlagRulesV2DraftRule, FeatureFlagRulesV2ReturnType, JsonType } from '~/types'++import { formatPercentage } from 'products/feature_flags/frontend/FractionalRolloutWarning'+import {+ RULES_V2_RULE_TYPES,+ RULES_V2_RULE_TYPE_META,+ RulesV2FieldError,+ RulesV2MatchCountText,+ RulesV2PausedRow,+ RulesV2PausedTag,+ RulesV2RuleNumber,+ RulesV2RuleRow,+ RulesV2ShadowedWarning,+ rulesV2ReachedPercentage,+ rulesV2RolloutMissText,+ rulesV2RuleTypeMenuLabel,+ useRulesV2MatchCount,+} from 'products/feature_flags/frontend/RulesV2Flow'import { FeatureFlagLogicProps } from './featureFlagLogic'import { withRuleType } from './featureFlagRulesV2Draft'import { featureFlagRulesV2EditorLogic } from './featureFlagRulesV2EditorLogic'import { PercentageInput } from './PercentageInput'-import { RulesV2PauseAndHoldoutFields, RulesV2VariantsField } from './RulesV2ExperimentFields'+import { RulesV2HoldoutRow, RulesV2VariantsRow } from './RulesV2ExperimentFields'import { RulesV2ValueInput } from './RulesV2ValueInput'-export function RulesV2RuleEditor({+const RULE_TYPE_OPTIONS = RULES_V2_RULE_TYPES.map((ruleType) => ({+ value: ruleType,+ label: RULES_V2_RULE_TYPE_META[ruleType].label,+ icon: RULES_V2_RULE_TYPE_META[ruleType].icon,+ labelInMenu: rulesV2RuleTypeMenuLabel(ruleType),+}))++const ROLLOUT_MISS_OPTIONS = [+ { value: 'continue' as const, description: 'Later rules, or the default value, decide.' },+ { value: 'return_default' as const, description: 'Later rules never see them.' },+].map(({ value, description }) => ({+ value,+ label: rulesV2RolloutMissText(value),+ labelInMenu: (+ <div className="flex flex-col py-0.5">+ <span>{capitalizeFirstLetter(rulesV2RolloutMissText(value))}</span>+ <span className="text-xs text-secondary">{description}</span>+ </div>+ ),+}))++function RolloutRow({+ id,+ index,+ rule,+ subjects,+ count,+}: FeatureFlagLogicProps & {+ index: number+ rule: Extract<FeatureFlagRulesV2DraftRule, { rollout_percentage: number }>+ subjects: Noun+ count: ReturnType<typeof useRulesV2MatchCount>+}): JSX.Element {+ const { fieldError } = useValues(featureFlagRulesV2EditorLogic({ id }))+ const { updateRule } = useActions(featureFlagRulesV2EditorLogic({ id }))+ const path = `filters.rules[${index}]`+ const heldOut = rule.rule_type === 'experiment' ? (rule.holdout?.exclusion_percentage ?? 0) : 0+ const reached = rulesV2ReachedPercentage(rule)+ const error = fieldError(`${path}.rollout_percentage`) ?? fieldError(`${path}.on_rollout_miss`)++ return (+ <RulesV2RuleRow+ label="Rollout"+ aside={+ reached === null ? null : (+ <RulesV2MatchCountText count={count} subjects={subjects} rolloutPercentage={reached} />+ )+ }+ >+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 min-h-7">+ <LemonSlider+ className="w-40 m-0"+ min={0}+ max={100}+ step={1}+ value={rule.rollout_percentage}+ onChange={(rollout_percentage) => updateRule(index, { ...rule, rollout_percentage })}+ />+ <div className="w-24">+ <PercentageInput+ aria-label="Rollout percentage"+ value={rule.rollout_percentage}+ onChange={(rollout_percentage) => updateRule(index, { ...rule, rollout_percentage })}+ data-attr="rules-v2-rollout-percentage"+ />+ </div>+ <span className="text-secondary">+ of matching {subjects.plural}+ {heldOut > 0 ? ' not held out' : ''}+ {rule.rule_type === 'experiment' ? ' are enrolled' : ''}+ </span>+ </div>+ {rule.rollout_percentage < 100 && (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-secondary">The other {formatPercentage(100 - rule.rollout_percentage)}</span>+ <LemonSelect+ size="small"+ value={rule.on_rollout_miss}+ onChange={(on_rollout_miss) => updateRule(index, { ...rule, on_rollout_miss })}+ options={ROLLOUT_MISS_OPTIONS}+ data-attr="rules-v2-rollout-miss"+ />+ </div>+ )}+ <RulesV2FieldError error={error} />+ </RulesV2RuleRow>+ )+}++export const RulesV2RuleEditor = memo(function RulesV2RuleEditor({id,index,rule,ruleCount,ruleKey,returnType,+ defaultValue,+ subjects,+ groupTypeIndex,+ shadowedBy,+ onRemoved,}: FeatureFlagLogicProps & {index: numberrule: FeatureFlagRulesV2DraftRuleruleCount: numberruleKey: numberreturnType: FeatureFlagRulesV2ReturnType+ defaultValue: JsonType | null+ subjects: Noun+ groupTypeIndex: number | null+ shadowedBy: number | null+ onRemoved: () => void}): JSX.Element {const { fieldError } = useValues(featureFlagRulesV2EditorLogic({ id }))- const { updateRule, removeRule, moveRule } = useActions(featureFlagRulesV2EditorLogic({ id }))+ const { updateRule, removeRule, moveRule, duplicateRule } = useActions(featureFlagRulesV2EditorLogic({ id }))+ const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({+ id: ruleKey,+ })const path = `filters.rules[${index}]`- const descriptionInputId = useId()- const rolloutInputId = useId()- const valueInputId = useId()const seedError = fieldError(`${path}.seed`)+ const properties = rule.targeting.properties+ const count = useRulesV2MatchCount(properties, groupTypeIndex)+ const paused = rule.rule_type === 'experiment' && rule.paused+ const ruleError = fieldError(path)+ const menuButtonRef = useRef<HTMLButtonElement | null>(null)+ // The menu closes without restoring focus, and a move re-inserts the card, so focus goes back to its menu button.+ const refocusMenu = (): void => {+ setTimeout(() => menuButtonRef.current?.focus())+ }return (- <div className="rounded border p-3 bg-surface-primary flex flex-col gap-3" data-attr="rules-v2-rule">- <div className="flex items-center gap-2">- <span className="font-semibold">Rule {index + 1}</span>+ <div+ ref={setNodeRef}+ // eslint-disable-next-line react/forbid-dom-props+ style={{ transform: CSS.Translate.toString(transform), transition }}+ className={clsx(+ 'rounded border bg-surface-primary relative',+ isDragging && 'z-10 shadow-lg ring-1 ring-accent',+ (ruleError || seedError) && 'border-danger'+ )}+ role="group"+ aria-label={`Rule ${index + 1}`}+ data-attr="rules-v2-rule"+ >+ <div className="flex items-center gap-1.5 pl-1 pr-2 py-1.5 border-b">+ <button+ type="button"+ ref={setActivatorNodeRef}+ className="cursor-grab active:cursor-grabbing text-muted hover:text-default border-none bg-transparent p-1 rounded hover:bg-fill-button-tertiary-hover flex"+ aria-label={`Reorder rule ${index + 1}`}+ {...attributes}+ {...listeners}+ data-attr="rules-v2-rule-drag-handle"+ >+ <SortableDragIcon />+ </button>+ <RulesV2RuleNumber index={index} muted={shadowedBy !== null} /><LemonSelectsize="small"value={rule.rule_type}onChange={(ruleType) => updateRule(index, withRuleType(rule, ruleType, returnType))}- options={[- { value: 'targeted_release', label: 'Targeted release' },- { value: 'percentage_rollout', label: 'Percentage rollout' },- { value: 'experiment', label: 'Experiment' },- ]}+ options={RULE_TYPE_OPTIONS}+ dropdownMatchSelectWidth={false}data-attr="rules-v2-rule-type"/>- <div className="flex-1" />- <LemonButton- icon={<IconArrowUp />}- size="small"- tooltip="Move up"- data-attr="rules-v2-move-rule-up"- disabledReason={index === 0 ? 'This rule is evaluated first.' : undefined}- onClick={() => moveRule(index, index - 1)}- />- <LemonButton- icon={<IconArrowDown />}- size="small"- tooltip="Move down"- data-attr="rules-v2-move-rule-down"- disabledReason={index === ruleCount - 1 ? 'This rule is evaluated last.' : undefined}- onClick={() => moveRule(index, index + 1)}- />- <LemonButton- icon={<IconTrash />}- size="small"- status="danger"- tooltip="Remove rule"- data-attr="rules-v2-remove-rule"- onClick={() => removeRule(index)}- />- </div>- {fieldError(path) && <LemonBanner type="error">{fieldError(path)}</LemonBanner>}- {seedError && <LemonBanner type="error">Assignment seed: {seedError}</LemonBanner>}- <LemonField.Pure- label="Description"- htmlFor={descriptionInputId}- showOptional- error={fieldError(`${path}.description`)}- ><LemonInput- id={descriptionInputId}+ size="small"+ className="flex-1 min-w-24 border-transparent bg-transparent hover:border-primary focus-within:border-primary"+ aria-label={`Rule ${index + 1} description`}+ placeholder="Add a description"value={rule.description ?? ''}onChange={(description) => updateRule(index, { ...rule, description: description || undefined })}+ data-attr="rules-v2-rule-description"/>- </LemonField.Pure>- <LemonField.Pure- label="Match persons where"- help={rule.targeting.properties.length === 0 ? 'No conditions: every person matches.' : undefined}- error={fieldError(`${path}.targeting`)}- >- <PropertyFilters- pageKey={`rules-v2-${id}-${ruleKey}`}- propertyFilters={rule.targeting.properties}- onChange={(properties) => updateRule(index, { ...rule, targeting: { properties } })}- taxonomicGroupTypes={[TaxonomicFilterGroupType.PersonProperties]}- hasRowOperator={false}- logicalRowDivider- sendAllKeyUpdates- addText="Add condition"- />- </LemonField.Pure>- {rule.rule_type === 'experiment' && <RulesV2PauseAndHoldoutFields id={id} index={index} rule={rule} />}- {rule.rule_type !== 'targeted_release' && (- <div className="flex flex-wrap gap-4">- <LemonField.Pure- label="Rollout percentage"- htmlFor={rolloutInputId}- className="w-40"- error={fieldError(`${path}.rollout_percentage`)}+ {paused && <RulesV2PausedTag />}+ {rule.rule_type === 'experiment' && (+ <LemonButton+ size="small"+ type="secondary"+ icon={rule.paused ? <IconPlay /> : <IconPause />}+ tooltip={+ rule.paused+ ? 'Matching users get variants again.'+ : 'Matching users get the default value until you resume. Nobody is enrolled meanwhile.'+ }+ onClick={() => updateRule(index, { ...rule, paused: !rule.paused })}+ data-attr="rules-v2-experiment-paused">- <PercentageInput- id={rolloutInputId}- value={rule.rollout_percentage}- onChange={(rollout_percentage) => updateRule(index, { ...rule, rollout_percentage })}- data-attr="rules-v2-rollout-percentage"- />- </LemonField.Pure>- <LemonField.Pure label="Persons outside the rollout" error={fieldError(`${path}.on_rollout_miss`)}>- <LemonSelect- value={rule.on_rollout_miss}- onChange={(on_rollout_miss) => updateRule(index, { ...rule, on_rollout_miss })}- options={[- { value: 'continue', label: 'Continue to the next rule' },- { value: 'return_default', label: 'Get the default value' },- ]}- data-attr="rules-v2-rollout-miss"+ {rule.paused ? 'Resume' : 'Pause'}+ </LemonButton>+ )}+ <LemonMenu+ items={[+ {+ label: 'Move up',+ icon: <IconArrowUp />,+ disabledReason: index === 0 ? 'This rule is checked first.' : undefined,+ onClick: () => {+ moveRule(index, index - 1)+ refocusMenu()+ },+ 'data-attr': 'rules-v2-move-rule-up',+ },+ {+ label: 'Move down',+ icon: <IconArrowDown />,+ disabledReason: index === ruleCount - 1 ? 'This rule is checked last.' : undefined,+ onClick: () => {+ moveRule(index, index + 1)+ refocusMenu()+ },+ 'data-attr': 'rules-v2-move-rule-down',+ },+ {+ label: 'Duplicate',+ icon: <IconCopy />,+ onClick: () => {+ duplicateRule(index)+ refocusMenu()+ },+ 'data-attr': 'rules-v2-duplicate-rule',+ },+ {+ label: 'Delete rule',+ icon: <IconTrash />,+ status: 'danger',+ onClick: () => {+ removeRule(index)+ onRemoved()+ },+ 'data-attr': 'rules-v2-remove-rule',+ },+ ]}+ >+ <LemonButton+ ref={menuButtonRef}+ size="small"+ icon={<IconEllipsis />}+ aria-label={`Rule ${index + 1} actions`}+ data-attr="rules-v2-rule-menu"+ />+ </LemonMenu>+ </div>+ <div className="px-3 py-2.5 flex flex-col gap-2">+ {ruleError && (+ <LemonBanner type="error" className="text-sm">+ {ruleError}+ </LemonBanner>+ )}+ {seedError && (+ <LemonBanner type="error" className="text-sm">+ Assignment seed: {seedError}+ </LemonBanner>+ )}+ <RulesV2ShadowedWarning shadowedBy={shadowedBy} subjects={subjects} />+ <RulesV2RuleRow label="If" aside={<RulesV2MatchCountText count={count} subjects={subjects} />}>+ <div className="flex flex-wrap items-center gap-2">+ {properties.length === 0 && <span className="leading-7">All {subjects.plural}</span>}+ <PropertyFilters+ pageKey={`rules-v2-${id}-${ruleKey}`}+ propertyFilters={properties}+ onChange={(next) => updateRule(index, { ...rule, targeting: { properties: next } })}+ taxonomicGroupTypes={[TaxonomicFilterGroupType.PersonProperties]}+ hasRowOperator={false}+ logicalRowDivider+ sendAllKeyUpdates+ buttonText="Add condition"+ buttonSize="small"/>- </LemonField.Pure>- </div>- )}- {rule.rule_type === 'experiment' ? (- <RulesV2VariantsField id={id} index={index} rule={rule} returnType={returnType} />- ) : (- <LemonField.Pure label="Value" htmlFor={valueInputId} error={fieldError(`${path}.value`)}>- <RulesV2ValueInput- id={valueInputId}- returnType={returnType}- value={rule.value}- onChange={(value) => updateRule(index, { ...rule, value })}- data-attr="rules-v2-rule-value"+ </div>+ <RulesV2FieldError error={fieldError(`${path}.targeting`)} />+ </RulesV2RuleRow>+ {paused && (+ <RulesV2PausedRow+ subjects={subjects}+ defaultValue={defaultValue}+ until="you resume"+ className="text-warning-dark"/>- </LemonField.Pure>- )}+ )}+ {rule.rule_type === 'experiment' && (+ <RulesV2HoldoutRow id={id} index={index} rule={rule} subjects={subjects} />+ )}+ {rule.rule_type !== 'targeted_release' && (+ <RolloutRow id={id} index={index} rule={rule} subjects={subjects} count={count} />+ )}+ {rule.rule_type === 'experiment' ? (+ <RulesV2VariantsRow id={id} index={index} rule={rule} returnType={returnType} />+ ) : (+ <RulesV2RuleRow label="Serve">+ <div className="flex flex-col gap-1 max-w-80">+ <RulesV2ValueInput+ aria-label="Value"+ returnType={returnType}+ value={rule.value}+ onChange={(value) => updateRule(index, { ...rule, value })}+ data-attr="rules-v2-rule-value"+ />+ <RulesV2FieldError error={fieldError(`${path}.value`)} />+ </div>+ </RulesV2RuleRow>+ )}+ </div></div>)-}+})diff --git a/frontend/src/scenes/feature-flags/RulesV2ValueInput.tsx b/frontend/src/scenes/feature-flags/RulesV2ValueInput.tsxindex aee74fa3abc1..4a312a6e98ef 100644--- a/frontend/src/scenes/feature-flags/RulesV2ValueInput.tsx+++ b/frontend/src/scenes/feature-flags/RulesV2ValueInput.tsx@@ -1,19 +1,97 @@+import { useEffect, useRef, useState } from 'react'+import { LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'+import { isObject } from 'lib/utils/guards'+import { objectsEqual } from 'lib/utils/objects'+import { FeatureFlagRulesV2ReturnType, JsonType } from '~/types'+import { JSONEditorInput } from './JSONEditorInput'+const BOOLEAN_OPTIONS = [{ value: 'true', label: 'true' },{ value: 'false', label: 'false' },]-/** A value of the flag's return type. A nullable string value is null while its input is empty. */+function objectInputText(value: JsonType | null): string {+ if (value === null) {+ return ''+ }+ return typeof value === 'string' ? value : JSON.stringify(value, null, 2)+}++/** The object the text holds, or the text itself while it holds none, so the draft's validation flags it. */+function objectInputValue(text: string, nullable: boolean): JsonType | null {+ if (nullable && text.trim() === '') {+ return null+ }+ try {+ const parsed: unknown = JSON.parse(text)+ if (isObject(parsed)) {+ return parsed as JsonType+ }+ } catch {+ // Not JSON yet.+ }+ return text+}++function RulesV2ObjectInput({+ value,+ onChange,+ nullable,+ id,+ className,+ ariaLabel,+ dataAttr,+}: {+ value: JsonType | null+ onChange: (value: JsonType | null) => void+ nullable: boolean+ id?: string+ className?: string+ ariaLabel?: string+ dataAttr?: string+}): JSX.Element {+ // The text keeps the user's formatting; only a value set from outside, such as a discard, replaces it.+ const [text, setText] = useState(() => objectInputText(value))+ const emitted = useRef(value)+ useEffect(() => {+ if (!objectsEqual(value, emitted.current)) {+ emitted.current = value+ setText(objectInputText(value))+ }+ }, [value])++ return (+ <div role="group" id={id} aria-label={ariaLabel} data-attr={dataAttr} className={`min-w-0 ${className ?? ''}`}>+ <JSONEditorInput+ value={text}+ placeholder={nullable ? 'No value' : 'A JSON object'}+ onChange={(next = '') => {+ const parsed = objectInputValue(next, nullable)+ emitted.current = parsed+ setText(next)+ onChange(parsed)+ }}+ />+ </div>+ )+}++/**+ * A value of the flag's return type. A boolean is always true or false. A nullable string, number or object value is+ * null while its input is empty. An+ * object input holds its text until it parses to an object, so the draft shows the error rather than dropping the edit.+ */export function RulesV2ValueInput({returnType,value,onChange,nullable = false,id,+ className,'aria-label': ariaLabel,'data-attr': dataAttr,}: {@@ -22,9 +100,41 @@ export function RulesV2ValueInput({onChange: (value: JsonType | null) => voidnullable?: booleanid?: string+ className?: string'aria-label'?: string'data-attr'?: string}): JSX.Element {+ if (returnType === 'object') {+ return (+ <RulesV2ObjectInput+ value={value}+ onChange={onChange}+ nullable={nullable}+ id={id}+ className={className}+ ariaLabel={ariaLabel}+ dataAttr={dataAttr}+ />+ )+ }+ if (returnType === 'number') {+ return (+ <LemonInput+ type="number"+ id={id}+ aria-label={ariaLabel}+ // NaN shows an empty field and, unlike undefined, keeps the input controlled.+ value={typeof value === 'number' ? value : NaN}+ // An empty or half-typed number reads as NaN.+ onChange={(number) => onChange(number === undefined || Number.isNaN(number) ? null : number)}+ placeholder={nullable ? 'No value' : 'Value to serve'}+ step="any"+ className={`ph-ignore-input font-mono ${className ?? ''}`}+ size="small"+ data-attr={dataAttr}+ />+ )+ }if (returnType === 'string') {return (<LemonInput@@ -32,8 +142,9 @@ export function RulesV2ValueInput({aria-label={ariaLabel}value={typeof value === 'string' ? value : ''}onChange={(text) => onChange(nullable && text === '' ? null : text)}- placeholder={nullable ? 'Leave empty for null' : undefined}- className="ph-ignore-input"+ placeholder={nullable ? 'No value' : 'Value to serve'}+ className={`ph-ignore-input font-mono ${className ?? ''}`}+ size="small"autoComplete="off"spellCheck={false}data-attr={dataAttr}@@ -42,12 +153,12 @@ export function RulesV2ValueInput({}// LemonSegmentedButton drops these props, so a labelled group carries them.return (- <div role="group" id={id} aria-label={ariaLabel} data-attr={dataAttr}>+ <div role="group" id={id} aria-label={ariaLabel} data-attr={dataAttr} className={className}><LemonSegmentedButtonsize="small"value={String(value)}- onChange={(option) => onChange(option === 'null' ? null : option === 'true')}- options={nullable ? [...BOOLEAN_OPTIONS, { value: 'null', label: 'null' }] : BOOLEAN_OPTIONS}+ onChange={(option) => onChange(option === 'true')}+ options={BOOLEAN_OPTIONS}/></div>)diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex d516d56e4f03..8a530d8a08d0 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -6004,6 +6004,22 @@ describe('the editor a flag opens in', () => {it.each([['a string return type', { return_type: 'string', default_value: 'control' }],+ [+ 'a number return type',+ {+ return_type: 'number',+ default_value: 1,+ rules: [+ {+ ...EXPERIMENT_RULE,+ variants: [+ { key: 'control', weight: 50, value: 1 },+ { key: 'test', weight: 50, value: 2 },+ ],+ },+ ],+ },+ ],['an experiment rule', { rules: [EXPERIMENT_RULE] }],['an experiment rule with a holdout',@@ -6016,7 +6032,7 @@ describe('the editor a flag opens in', () => {// The editor would drop, or rewrite on save, what it cannot represent.it.each([- ['a number return type', { return_type: 'number', default_value: 1 }],+ ['an unknown return type', { return_type: 'date', default_value: null }],['group assignment', { aggregation_group_type_index: 0 }],])('a v2 flag with %s opens no editor, even with the editor on', async (_label, filters) => {useMocks({ get: { [V2_FLAG_URL]: () => [200, { ...V2_FLAG, filters: { ...V2_FLAG.filters, ...filters } }] } })diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.test.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.test.tsnew file mode 100644index 000000000000..5fa9e92fd99e--- /dev/null+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.test.ts@@ -0,0 +1,104 @@+import { FeatureFlagRulesV2DraftRule, PropertyFilterType, PropertyOperator } from '~/types'++import { duplicatedRule, rulesV2CatchAllRule, rulesV2ShadowingRules } from './featureFlagRulesV2Draft'++const EMAIL = {+ key: 'email',+ type: PropertyFilterType.Person,+ value: '@example.com',+ operator: PropertyOperator.IContains,+}+const COUNTRY = { key: 'country', type: PropertyFilterType.Person, value: ['NO'], operator: PropertyOperator.Exact }+const INCOMPLETE = { key: 'plan', type: PropertyFilterType.Person, value: null, operator: PropertyOperator.Exact }+const PLAN_IS_SET = { key: 'plan', type: PropertyFilterType.Person, value: null, operator: PropertyOperator.IsSet }++const release = (properties: any[] = []): FeatureFlagRulesV2DraftRule => ({+ rule_type: 'targeted_release',+ targeting: { properties },+ value: true,+})+const rollout = (+ rolloutPercentage: number,+ onRolloutMiss: 'continue' | 'return_default',+ properties: any[] = []+): FeatureFlagRulesV2DraftRule => ({+ rule_type: 'percentage_rollout',+ targeting: { properties },+ value: true,+ rollout_percentage: rolloutPercentage,+ on_rollout_miss: onRolloutMiss,+ assignment_algorithm: 'sha1_60_v1',+})+const experiment = (paused: boolean, rolloutPercentage: number): FeatureFlagRulesV2DraftRule => ({+ rule_type: 'experiment',+ targeting: { properties: [] },+ paused,+ rollout_percentage: rolloutPercentage,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ variants: [+ { key: 'control', weight: 50, value: false },+ { key: 'test', weight: 50, value: true },+ ],+})++describe('rulesV2ShadowingRules', () => {+ it.each([+ ['a release to everyone hides any later rule', [release(), release([EMAIL])], [null, 0]],+ ['a narrower earlier rule hides nothing', [release([EMAIL]), release()], [null, null]],+ [+ 'an earlier rule with a subset of the conditions hides',+ [release([EMAIL]), release([EMAIL, COUNTRY])],+ [null, 0],+ ],+ ['unrelated conditions are not compared', [release([EMAIL]), release([COUNTRY])], [null, null]],+ ['a partial rollout that continues hides nothing', [rollout(50, 'continue'), release()], [null, null]],+ ['a partial rollout that returns the default hides', [rollout(50, 'return_default'), release()], [null, 0]],+ ['a full rollout hides', [rollout(100, 'continue'), release()], [null, 0]],+ ['a paused experiment hides', [experiment(true, 50), release()], [null, 0]],+ ['a running partial experiment that continues hides nothing', [experiment(false, 50), release()], [null, null]],+ [+ 'an incomplete condition matches no one, so it hides nothing',+ [release([INCOMPLETE]), release()],+ [null, null],+ ],+ [+ 'a set check takes no value, so it is complete and hides',+ [release([PLAN_IS_SET]), release([PLAN_IS_SET, EMAIL])],+ [null, 0],+ ],+ ['the first hiding rule is named', [release(), release(), release()], [null, 0, 0]],+ ])('%s', (_, rules, expected) => {+ expect(rulesV2ShadowingRules(rules)).toEqual(expected)+ })+})++describe('rulesV2CatchAllRule', () => {+ it('finds the first rule that decides the value for everyone', () => {+ expect(rulesV2CatchAllRule([release([EMAIL]), rollout(25, 'return_default'), release()])).toBe(1)+ })++ it('finds none when every rule lets someone through', () => {+ expect(rulesV2CatchAllRule([])).toBeNull()+ expect(rulesV2CatchAllRule([release([EMAIL]), rollout(25, 'continue')])).toBeNull()+ })+})++describe('duplicatedRule', () => {+ it('drops the id of a targeted release', () => {+ expect(duplicatedRule({ ...release([EMAIL]), id: 'rule-1', description: 'Staff' })).toEqual({+ ...release([EMAIL]),+ description: 'Staff',+ })+ })++ it('drops the id and both seeds of an experiment rule, keeping its holdout share', () => {+ const stored = { ...experiment(false, 50), id: 'rule-2', seed: 'rule-seed' } as FeatureFlagRulesV2DraftRule+ expect(+ duplicatedRule({ ...stored, holdout: { seed: 'holdout-seed', exclusion_percentage: 5 } } as any)+ ).toEqual({+ ...experiment(false, 50),+ holdout: { exclusion_percentage: 5 },+ })+ })+})diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.tsindex 98dd3ad75a43..3f09a15fef49 100644--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.ts+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.ts@@ -1,4 +1,8 @@+import { isEmptyProperty, isPropertyFilterWithOperator } from 'lib/components/PropertyFilters/utils'+import { objectsEqual } from 'lib/utils/objects'+import {+ AnyPropertyFilter,FeatureFlagRulesV2DraftConfig,FeatureFlagRulesV2DraftExperimentRule,FeatureFlagRulesV2DraftHoldout,@@ -6,6 +10,7 @@ import {FeatureFlagRulesV2ReturnType,FeatureFlagRulesV2Variant,JsonType,+ PropertyOperator,} from '~/types'import { isRulesV2Value } from 'products/feature_flags/frontend/featureFlagConfigFormat'@@ -22,21 +27,58 @@ export function moved<T>(items: T[], from: number, to: number): T[] {return result}-/** The value a new rule starts with. A string has no sensible default, so the user must enter one. */+export function insertedAfter<T>(items: T[], index: number, item: T): T[] {+ return [...items.slice(0, index + 1), item, ...items.slice(index + 1)]+}++/**+ * A condition with no value: the server accepts it, but it never matches. Set and not-set conditions take no value,+ * so they are complete.+ */+export function isIncompleteRulesV2Condition(property: AnyPropertyFilter): boolean {+ return (+ isEmptyProperty(property) &&+ !(+ isPropertyFilterWithOperator(property) &&+ [PropertyOperator.IsSet, PropertyOperator.IsNotSet].includes(property.operator)+ )+ )+}++/** The value a new rule starts with. A string or number has no sensible default, so the user must enter one. */export function rulesV2InitialValue(returnType: FeatureFlagRulesV2ReturnType): JsonType {- return returnType === 'boolean' ? true : ''+ switch (returnType) {+ case 'boolean':+ return true+ case 'number':+ return null+ case 'object':+ return {}+ default:+ return ''+ }}export function rulesV2InitialDefault(returnType: FeatureFlagRulesV2ReturnType): JsonType | null {return returnType === 'boolean' ? false : null}-// A boolean experiment rule starts as control false and test true; a string variant serves its own key.+// A boolean experiment rule starts as control false and test true, a number one as 0 and 1; a string variant+// serves its own key.function initialVariantValue(returnType: FeatureFlagRulesV2ReturnType, key: string, index: number): JsonType {- return returnType === 'boolean' ? index > 0 : key+ switch (returnType) {+ case 'boolean':+ return index > 0+ case 'number':+ return index+ case 'string':+ return key+ default:+ return rulesV2InitialValue(returnType)+ }}-export const NEW_TARGETED_RELEASE_RULE: FeatureFlagRulesV2DraftRule = {+export const NEW_TARGETED_RELEASE_RULE: Extract<FeatureFlagRulesV2DraftRule, { rule_type: 'targeted_release' }> = {rule_type: 'targeted_release',targeting: { properties: [] },value: true,@@ -52,6 +94,13 @@ const NEW_ROLLOUT_FIELDS = {const NEW_EXPERIMENT_ROLLOUT_FIELDS = { ...NEW_ROLLOUT_FIELDS, rollout_percentage: 100 } as const+export function newRulesV2Rule(+ ruleType: FeatureFlagRulesV2DraftRule['rule_type'],+ returnType: FeatureFlagRulesV2ReturnType+): FeatureFlagRulesV2DraftRule {+ return withRuleType({ ...NEW_TARGETED_RELEASE_RULE, value: rulesV2InitialValue(returnType) }, ruleType, returnType)+}+/*** Keeps the rule's identity and shared fields; type-specific fields come and go with the type. A rollout keeps its* percentage and miss behaviour between the two randomized types. The seed is dropped, and the server keeps the@@ -97,6 +146,22 @@ export function withRuleType(}}+/**+ * A copy to insert after the original. It has no id, so the server treats it as a new rule, and no seeds, so its users+ * are assigned independently of the original's.+ */+export function duplicatedRule(rule: FeatureFlagRulesV2DraftRule): FeatureFlagRulesV2DraftRule {+ const { id: _id, ...copy } = rule+ if (copy.rule_type === 'targeted_release') {+ return copy+ }+ const { seed: _seed, ...withoutSeed } = copy+ if (withoutSeed.rule_type === 'experiment' && withoutSeed.holdout) {+ return { ...withoutSeed, holdout: { exclusion_percentage: withoutSeed.holdout.exclusion_percentage } }+ }+ return withoutSeed+}+export const NEW_HOLDOUT: FeatureFlagRulesV2DraftHoldout = { exclusion_percentage: 10 }export function newVariant(returnType: FeatureFlagRulesV2ReturnType, index: number): FeatureFlagRulesV2Variant {@@ -113,6 +178,11 @@ export function withVariantKey(return { ...variant, key, ...(followsKey ? { value: key } : {}) }}+/** The variants' total weight. Two decimals each, so a total in hundredths is exact where a float sum is not. */+export function rulesV2VariantWeightTotal(variants: FeatureFlagRulesV2Variant[]): number {+ return variants.reduce((sum, variant) => sum + Math.round(variant.weight * 100), 0) / 100+}+/** Equal weights in hundredths; the first variants absorb the remainder, so the total is exactly 100. */export function withEqualWeights(variants: FeatureFlagRulesV2Variant[]): FeatureFlagRulesV2Variant[] {const base = Math.floor(10000 / variants.length)@@ -160,7 +230,18 @@ function valueError(value: unknown, returnType: FeatureFlagRulesV2ReturnType): sif (isRulesV2Value(value, returnType)) {return null}- return returnType === 'boolean' ? 'Must be true or false.' : 'Enter a value.'+ switch (returnType) {+ case 'boolean':+ return 'Must be true or false.'+ case 'number':+ return typeof value === 'number' && Number.isFinite(value)+ ? `Must be between -${Number.MAX_SAFE_INTEGER} and ${Number.MAX_SAFE_INTEGER}.`+ : 'Enter a number.'+ case 'object':+ return 'Enter a valid JSON object.'+ default:+ return 'Enter a value.'+ }}function variantKeyError(key: string, seen: Set<string>): string | null {@@ -190,8 +271,7 @@ function experimentErrors(addError(errors, `${variantPath}.weight`, weightError)addError(errors, `${variantPath}.value`, valueError(variant.value, returnType))})- // Two decimals each, so a total in hundredths is exact where a float sum is not.- const total = rule.variants.reduce((sum, variant) => sum + Math.round(variant.weight * 100), 0)+ const total = rulesV2VariantWeightTotal(rule.variants)addError(errors,`${path}.variants`,@@ -199,8 +279,8 @@ function experimentErrors(? `Add at least ${MIN_VARIANTS} variants.`: rule.variants.length > MAX_VARIANTS? `At most ${MAX_VARIANTS} variants are allowed.`- : weightsValid && total !== 10000- ? `Variant weights must total 100% (now ${total / 100}%).`+ : weightsValid && total !== 100+ ? `Variant weights must total 100% (now ${total}%).`: null)if (rule.holdout) {@@ -232,5 +312,48 @@ export function rulesV2DraftErrors(config: FeatureFlagRulesV2DraftConfig): RecorexperimentErrors(rule, path, config.return_type, errors)}})+ if (config.default_value !== null || config.return_type === 'boolean') {+ addError(errors, 'filters.default_value', valueError(config.default_value, config.return_type))+ }return errors}++type RulesV2ReachabilityRule = Pick<FeatureFlagRulesV2DraftRule, 'rule_type' | 'targeting'> &+ Partial<{ rollout_percentage: number; on_rollout_miss: 'continue' | 'return_default'; paused: boolean }>++/** Whether every user a rule matches leaves it with a value, so later rules never see them. */+function claimsEveryMatch(rule: RulesV2ReachabilityRule): boolean {+ if (rule.rule_type === 'targeted_release' || (rule.rule_type === 'experiment' && rule.paused)) {+ return true+ }+ return (rule.rollout_percentage ?? 0) >= 100 || rule.on_rollout_miss === 'return_default'+}++/** Whether `earlier` matches every user `later` matches: its conditions are a subset of the later rule's. */+function matchesEveryoneOf(earlier: RulesV2ReachabilityRule, later: RulesV2ReachabilityRule): boolean {+ return earlier.targeting.properties.every((property) =>+ later.targeting.properties.some((candidate) => objectsEqual(property, candidate))+ )+}++/**+ * For each rule, the index of an earlier rule that claims every user it matches, or null when the rule can serve+ * someone. It only spots shadowing it can prove from the conditions; overlapping conditions are not compared.+ */+export function rulesV2ShadowingRules(rules: RulesV2ReachabilityRule[]): (number | null)[] {+ const claims = rules.map(+ (rule) => claimsEveryMatch(rule) && !rule.targeting.properties.some(isIncompleteRulesV2Condition)+ )+ return rules.map((rule, index) => {+ const shadowing = rules.findIndex(+ (earlier, earlierIndex) => earlierIndex < index && claims[earlierIndex] && matchesEveryoneOf(earlier, rule)+ )+ return shadowing >= 0 ? shadowing : null+ })+}++/** The first rule that claims every user, after which no one falls through to the default step; null if none does. */+export function rulesV2CatchAllRule(rules: RulesV2ReachabilityRule[]): number | null {+ const index = rules.findIndex((rule) => claimsEveryMatch(rule) && rule.targeting.properties.length === 0)+ return index >= 0 ? index : null+}diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.tsindex db4d5b077816..52d597e5f14e 100644--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts@@ -20,6 +20,7 @@ import {FeatureFlagRulesV2DraftExperimentRule,FeatureFlagRulesV2DraftRule,FeatureFlagType,+ JsonType,PropertyFilterType,PropertyOperator,} from '~/types'@@ -291,6 +292,14 @@ describe('featureFlagRulesV2EditorLogic', () => {).toEqual({})})+ it('requires a boolean default, which the editor offers no empty choice for', () => {+ const config = V2_FLAG.filters as FeatureFlagRulesV2Config+ expect(rulesV2DraftErrors({ ...config, default_value: null })).toEqual({+ 'filters.default_value': 'Must be true or false.',+ })+ expect(rulesV2DraftErrors({ ...config, default_value: true })).toEqual({})+ })+it('adds, moves and removes variants, and distributes their weights to exactly 100', () => {const variants = [...EXPERIMENT_RULE.variants, newVariant('string', 3)]expect(variants[3]).toEqual({ key: '', weight: 0, value: '' })@@ -507,6 +516,90 @@ describe('featureFlagRulesV2EditorLogic', () => {expect(JSON.stringify(body)).not.toContain('seed')})+ it('creates a number flag once every rule has a number in range', async () => {+ const create = jest.spyOn(api, 'create').mockResolvedValue({ ...STRING_FLAG, id: 12 })+ const logic = featureFlagRulesV2EditorLogic({ id: 'new' })+ logic.mount()+ const setValue = (value: JsonType): void =>+ logic.actions.updateRule(0, { ...logic.values.draft.config.rules[0], value } as FeatureFlagRulesV2DraftRule)++ logic.actions.setDraft({ key: 'checkout-limit' })+ logic.actions.setReturnType('number')+ logic.actions.addRule()+ logic.actions.addRule('experiment')+ expect(logic.values.draft.config).toMatchObject({ return_type: 'number', default_value: null })+ expect(logic.values.saveDisabledReason).toBe('Rule 1: Enter a number.')+ setValue(2 ** 53)+ expect(logic.values.saveDisabledReason).toBe(+ `Rule 1: Must be between -${Number.MAX_SAFE_INTEGER} and ${Number.MAX_SAFE_INTEGER}.`+ )+ setValue(2.5)+ logic.actions.setConfig({ default_value: 0 })+ expect(logic.values.saveDisabledReason).toBeNull()+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())+ .toDispatchActions(['saveRulesV2FlagSuccess'])+ .toFinishAllListeners()++ const body = create.mock.calls[0][1] as Record<string, any>+ expect(body.filters).toMatchObject({+ return_type: 'number',+ default_value: 0,+ rules: [+ { rule_type: 'targeted_release', value: 2.5 },+ {+ rule_type: 'experiment',+ variants: [+ { key: 'control', weight: 50, value: 0 },+ { key: 'test', weight: 50, value: 1 },+ ],+ },+ ],+ })+ })++ it('creates an object flag and blocks the save while a value is not a JSON object', async () => {+ const create = jest.spyOn(api, 'create').mockResolvedValue({ ...STRING_FLAG, id: 11 })+ const logic = featureFlagRulesV2EditorLogic({ id: 'new' })+ logic.mount()+ const setTestValue = (value: JsonType): void => {+ const rule = logic.values.draft.config.rules[0] as FeatureFlagRulesV2DraftExperimentRule+ logic.actions.updateRule(0, { ...rule, variants: [rule.variants[0], { ...rule.variants[1], value }] })+ }++ logic.actions.setDraft({ key: 'checkout-config' })+ logic.actions.setReturnType('object')+ logic.actions.addRule('experiment')+ expect(logic.values.draft.config).toMatchObject({ return_type: 'object', default_value: null })+ expect(logic.values.saveDisabledReason).toBeNull()++ logic.actions.setConfig({ default_value: '{"columns": ' })+ expect(logic.values.saveDisabledReason).toBe('Default value: Enter a valid JSON object.')+ logic.actions.setConfig({ default_value: { columns: 1 } })+ setTestValue(['compact'])+ expect(logic.values.fieldError('filters.rules[0].variants[1].value')).toBe('Enter a valid JSON object.')+ expect(logic.values.saveDisabledReason).toBe('Rule 1: Enter a valid JSON object.')+ setTestValue({ columns: 2, labels: { cta: 'Buy' } })+ expect(logic.values.saveDisabledReason).toBeNull()+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())+ .toDispatchActions(['saveRulesV2FlagSuccess'])+ .toFinishAllListeners()++ const body = create.mock.calls[0][1] as Record<string, any>+ expect(body.filters).toMatchObject({+ return_type: 'object',+ default_value: { columns: 1 },+ rules: [+ {+ rule_type: 'experiment',+ variants: [+ { key: 'control', weight: 50, value: {} },+ { key: 'test', weight: 50, value: { columns: 2, labels: { cta: 'Buy' } } },+ ],+ },+ ],+ })+ })+it.each([['a valid key', urls.featureFlagNew({ format: 'rules_v2', key: 'checkout-layout' }), 'checkout-layout'],['an invalid key', urls.featureFlagNew({ format: 'rules_v2', key: "x' + 1 + '" }), ''],@@ -633,7 +726,7 @@ describe('featureFlagRulesV2EditorLogic', () => {const confirm = jest.spyOn(window, 'confirm').mockReturnValue(false)expect(logic.values.hasUnsavedChanges).toBe(false)- logic.actions.setConfig({ default_value: null })+ logic.actions.setConfig({ default_value: true })router.actions.push(urls.featureFlags())expect(confirm).toHaveBeenCalledTimes(1)@@ -649,12 +742,12 @@ describe('featureFlagRulesV2EditorLogic', () => {await expectLogic(pageLogic).toDispatchActions(['loadFeatureFlagSuccess']).toFinishAllListeners()pageLogic.actions.editFeatureFlag(true)- logic.actions.setConfig({ default_value: null })+ logic.actions.setConfig({ default_value: true })// The project-prefixed path passes the editor's unload prompt, so only featureFlagLogic's guard keeps the draft.await expectLogic(pageLogic, () => router.actions.push(router.values.location.pathname)).toFinishAllListeners().toMatchValues({ isEditingFlag: true })- expect(logic.values.draft.config.default_value).toBeNull()+ expect(logic.values.draft.config.default_value).toBe(true)// Cancel leaves the draft dirty, so closing the editor is what lets later pushes reach the page.expect(pageLogic.values.rulesV2DraftDirty).toBe(true)@@ -730,7 +823,7 @@ describe('featureFlagRulesV2EditorLogic', () => {saveError: { message: 'Must be at most 100.' },})- logic.actions.setConfig({ default_value: null })+ logic.actions.setConfig({ default_value: true })expect(logic.values.saveError).toBeNull()})@@ -779,6 +872,55 @@ describe('featureFlagRulesV2EditorLogic', () => {logic.mount()})+ it('adds a rule of the chosen type with the starting values of the flag type', () => {+ logic.actions.addRule('experiment')++ expect(logic.values.draft.config.rules[2]).toEqual({+ rule_type: 'experiment',+ targeting: { properties: [] },+ paused: false,+ rollout_percentage: 100,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ assign_by: 'person',+ variants: [+ { key: 'control', weight: 50, value: 'control' },+ { key: 'test', weight: 50, value: 'test' },+ ],+ })+ expect(new Set(logic.values.ruleKeys).size).toBe(3)+ expect(logic.values.hasUnsavedChanges).toBe(true)+ })++ it('duplicates a rule below itself without its id or seeds, so the server assigns new ones', async () => {+ const update = jest.spyOn(api, 'update').mockResolvedValue({ ...STRING_FLAG, version: 6 })++ logic.actions.duplicateRule(1)+ expect(new Set(logic.values.ruleKeys).size).toBe(3)+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())+ .toDispatchActions(['saveRulesV2FlagSuccess'])+ .toFinishAllListeners()++ const { id: _id, seed: _seed, holdout, ...copy } = EXPERIMENT_RULE+ expect((update.mock.calls[0][1] as Record<string, any>).filters.rules).toEqual([+ STRING_FLAG_RULES[0],+ EXPERIMENT_RULE,+ { ...copy, holdout: { exclusion_percentage: holdout.exclusion_percentage } },+ ])+ })++ it('inserts a duplicate of the first rule right after it, and the other rules keep their keys', () => {+ const [firstKey, secondKey] = logic.values.ruleKeys++ logic.actions.duplicateRule(0)++ const { id: _id, ...copy } = STRING_FLAG_RULES[0]+ expect(logic.values.draft.config.rules).toEqual([STRING_FLAG_RULES[0], copy, EXPERIMENT_RULE])+ expect(logic.values.ruleKeys[0]).toBe(firstKey)+ expect(logic.values.ruleKeys[2]).toBe(secondKey)+ expect(new Set(logic.values.ruleKeys).size).toBe(3)+ })+it('changes another rule and moves the experiment rule without touching any of its fields', async () => {const update = jest.spyOn(api, 'update').mockResolvedValue({ ...STRING_FLAG, version: 6 })@@ -889,7 +1031,7 @@ describe('featureFlagRulesV2EditorLogic', () => {error: 'Must be between 0 and 100.',},])('flags $check against its field and blocks the save', ({ edit, field, error }) => {- expect(logic.values.saveDisabledReason).toBeNull()+ expect(logic.values.saveDisabledReason).toBe('Nothing to save yet.')edit()expect(logic.values.fieldError(field)).toBe(error)expect(logic.values.saveDisabledReason).toBe(`Rule 2: ${error}`)diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.tsindex 80dbc1de3c79..fdf9ee95ab78 100644--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts@@ -17,7 +17,6 @@ import { CombinedLocation } from 'kea-router/lib/utils'import { subscriptions } from 'kea-subscriptions'import { readableErrorMessage } from 'lib/api-error'-import { isEmptyProperty, isPropertyFilterWithOperator } from 'lib/components/PropertyFilters/utils'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { objectsEqual } from 'lib/utils/objects'@@ -32,7 +31,6 @@ import {FeatureFlagRulesV2DraftRule,FeatureFlagRulesV2ReturnType,FeatureFlagType,- PropertyOperator,TeamPublicType,TeamType,} from '~/types'@@ -58,10 +56,13 @@ import {variantKeyToIndexFeatureFlagPayloads,} from './featureFlagLogic'import {- NEW_TARGETED_RELEASE_RULE,+ duplicatedRule,+ insertedAfter,+ isIncompleteRulesV2Condition,moved,+ newRulesV2Rule,rulesV2DraftErrors,- rulesV2InitialValue,+ rulesV2ShadowingRules,withReturnType,} from './featureFlagRulesV2Draft'@@ -191,9 +192,11 @@ export interface featureFlagRulesV2EditorLogicValues {fieldError: (field: string) => string | nullhasUnsavedChanges: booleanruleKeys: number[]+ rules: FeatureFlagRulesV2DraftRule[]saveDisabledReason: string | nullsaveError: RulesV2SaveError | nullsaving: boolean+ shadowingRules: (number | null)[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -228,8 +231,11 @@ export interface featureFlagRulesV2EditorLogicActions {setRulesV2DraftDirty: (dirty: boolean) => {dirty: boolean} // featureFlagLogic- addRule: () => {- value: true+ addRule: (ruleType?: FeatureFlagRulesV2DraftRule['rule_type']) => {+ ruleType: 'experiment' | 'percentage_rollout' | 'targeted_release'+ }+ duplicateRule: (index: number) => {+ index: number}loadDraft: (draft: FeatureFlagRulesV2Draft) => {draft: FeatureFlagRulesV2Draft@@ -286,6 +292,8 @@ export interface featureFlagRulesV2EditorLogicMeta {key: number | 'link' | 'new'__keaTypeGenInternalSelectorTypes: {draftErrors: (draft: FeatureFlagRulesV2Draft) => Record<string, string>+ rules: (draft: FeatureFlagRulesV2Draft) => FeatureFlagRulesV2DraftRule[]+ shadowingRules: (rules: FeatureFlagRulesV2DraftRule[]) => (number | null)[]fieldError: (saveError: RulesV2SaveError | null,draftErrors: Record<string, string>@@ -295,6 +303,7 @@ export interface featureFlagRulesV2EditorLogicMeta {draftErrors: Record<string, string>,currentTeam: TeamPublicType | TeamType | null,enabledFeatures: FeatureFlagsSet,+ hasUnsavedChanges: boolean,id: number | 'link' | 'new') => string | null}@@ -330,7 +339,8 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTysetDraft: (draft: Partial<FeatureFlagRulesV2Draft>) => ({ draft }),setConfig: (config: Partial<FeatureFlagRulesV2DraftConfig>) => ({ config }),setReturnType: (returnType: FeatureFlagRulesV2ReturnType) => ({ returnType }),- addRule: true,+ addRule: (ruleType: FeatureFlagRulesV2DraftRule['rule_type'] = 'targeted_release') => ({ ruleType }),+ duplicateRule: (index: number) => ({ index }),updateRule: (index: number, rule: FeatureFlagRulesV2DraftRule) => ({ index, rule }),setRule: (index: number, rule: FeatureFlagRulesV2DraftRule) => ({ index, rule }),removeRule: (index: number) => ({ index }),@@ -351,14 +361,18 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy...state,config: withReturnType(state.config, returnType),}),- addRule: (state) => ({+ addRule: (state, { ruleType }) => ({...state,config: {...state.config,- rules: [- ...state.config.rules,- { ...NEW_TARGETED_RELEASE_RULE, value: rulesV2InitialValue(state.config.return_type) },- ],+ rules: [...state.config.rules, newRulesV2Rule(ruleType, state.config.return_type)],+ },+ }),+ duplicateRule: (state, { index }) => ({+ ...state,+ config: {+ ...state.config,+ rules: insertedAfter(state.config.rules, index, duplicatedRule(state.config.rules[index])),},}),setRule: (state, { index, rule }) => ({@@ -382,6 +396,7 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTysetDraft: (state, { draft }) => (draft.config ? draft.config.rules.map(nextRuleKey) : state),setConfig: (state, { config }) => (config.rules ? config.rules.map(nextRuleKey) : state),addRule: (state) => [...state, nextRuleKey()],+ duplicateRule: (state, { index }) => insertedAfter(state, index, nextRuleKey()),removeRule: (state, { index }) => state.filter((_, i) => i !== index),moveRule: (state, { from, to }) => moved(state, from, to),},@@ -396,6 +411,7 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTysetConfig: () => null,setReturnType: () => null,addRule: () => null,+ duplicateRule: () => null,setRule: () => null,removeRule: () => null,moveRule: () => null,@@ -410,6 +426,7 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTysetConfig: () => true,setReturnType: () => true,addRule: () => true,+ duplicateRule: () => true,setRule: () => true,removeRule: () => true,moveRule: () => true,@@ -428,6 +445,15 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTydraftErrors: [(s) => [s.draft],(draft: FeatureFlagRulesV2Draft): Record<string, string> => rulesV2DraftErrors(draft.config),+ { resultEqualityCheck: objectsEqual },+ ],+ rules: [+ (s) => [s.draft],+ (draft: FeatureFlagRulesV2Draft): FeatureFlagRulesV2DraftRule[] => draft.config.rules,+ ],+ shadowingRules: [+ (s) => [s.rules],+ (rules: FeatureFlagRulesV2DraftRule[]): (number | null)[] => rulesV2ShadowingRules(rules),],// The server's error wins: it is about the document as it was sent.fieldError: [@@ -437,12 +463,13 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTysaveError?.field === field ? saveError.message : (draftErrors[field] ?? null),],saveDisabledReason: [- (s, p) => [s.draft, s.draftErrors, s.currentTeam, s.enabledFeatures, p.id],+ (s, p) => [s.draft, s.draftErrors, s.currentTeam, s.enabledFeatures, s.hasUnsavedChanges, p.id],(draft: FeatureFlagRulesV2Draft,draftErrors: Record<string, string>,currentTeam: TeamPublicType | TeamType | null,enabledFeatures: FeatureFlagsSet,+ hasUnsavedChanges: boolean,id: FeatureFlagLogicProps['id']): string | null => {// The list disables this entry point, but a direct link still opens the editor.@@ -457,24 +484,18 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy}const [firstErrorField, firstError] = Object.entries(draftErrors)[0] ?? []if (firstErrorField) {- const ruleIndex = Number(/^filters\.rules\[(\d+)\]/.exec(firstErrorField)?.[1])- return `Rule ${ruleIndex + 1}: ${firstError}`+ const ruleIndex = /^filters\.rules\[(\d+)\]/.exec(firstErrorField)?.[1]+ return ruleIndex === undefined+ ? `Default value: ${firstError}`+ : `Rule ${Number(ruleIndex) + 1}: ${firstError}`}- // The server accepts a condition with no value, but the condition never matches.- // Set and not-set conditions take no value, so they are not incomplete.const emptyConditionIndex = draft.config.rules.findIndex((rule) =>- rule.targeting.properties.some(- (property) =>- isEmptyProperty(property) &&- !(- isPropertyFilterWithOperator(property) &&- [PropertyOperator.IsSet, PropertyOperator.IsNotSet].includes(property.operator)- )- )+ rule.targeting.properties.some(isIncompleteRulesV2Condition))- return emptyConditionIndex >= 0- ? `Choose a value for every condition in rule ${emptyConditionIndex + 1}.`- : null+ if (emptyConditionIndex >= 0) {+ return `Choose a value for every condition in rule ${emptyConditionIndex + 1}.`+ }+ return id !== 'new' && !hasUnsavedChanges ? 'Nothing to save yet.' : null},],}),@@ -540,7 +561,7 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy}},saveRulesV2FlagSuccess: ({ flag }) => {- lemonToast.success('Flag saved')+ lemonToast.success(props.id === 'new' ? 'Flag created' : 'Flag saved')if (flag.id) {refreshTreeItem('feature_flag', String(flag.id))}diff --git a/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsx b/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsxindex 0fc5d635e87a..60125dec9c1a 100644--- a/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsx+++ b/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsx@@ -12,13 +12,7 @@ import {isRulesV2EditableConfig,} from './featureFlagConfigFormat'-export function FeatureFlagConfigReadonlyNotice({- filters,- hasEditButton = false,-}: {- filters: FeatureFlagConfig- hasEditButton?: boolean-}): JSX.Element {+export function FeatureFlagConfigReadonlyNotice({ filters }: { filters: FeatureFlagConfig }): JSX.Element {const { featureFlags } = useValues(enabledFeaturesLogic)const label = featureFlagConfigFormatLabel(filters)const editable = isRulesV2EditableConfig(filters, featureFlags)@@ -28,11 +22,6 @@ export function FeatureFlagConfigReadonlyNotice({<>This flag is stored as <strong>{label}</strong>, which this page cannot display or change.</>- ) : editable && hasEditButton ? (- <>- This flag is stored as <strong>{label}</strong>. Use Edit to change its rules; archiving is not- available yet.- </>) : editable ? (<>This flag is stored as <strong>{label}</strong> and is shown read-only here. Open the flag page todiff --git a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsxindex 953f5947dab0..8b89c05c9216 100644--- a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx+++ b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx@@ -1,10 +1,11 @@import '@testing-library/jest-dom'-import { cleanup, render } from '@testing-library/react'+import { act, cleanup, fireEvent, render, waitFor, within } from '@testing-library/react'import { Provider } from 'kea'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { FeatureFlagRulesV2Config } from '~/types'+import { AnyPropertyFilter, FeatureFlagRulesV2Config, PropertyFilterType, PropertyOperator } from '~/types'import { FeatureFlagRulesV2Readonly } from './FeatureFlagRulesV2Readonly'@@ -27,8 +28,19 @@ const CONFIG: FeatureFlagRulesV2Config = {],}+/** The base config with one rule targeting `property`. */+const withTargeting = (property: AnyPropertyFilter): FeatureFlagRulesV2Config => ({+ ...CONFIG,+ rules: [{ ...CONFIG.rules[0], targeting: { properties: [property] } }],+})+describe('FeatureFlagRulesV2Readonly', () => {beforeEach(() => {+ useMocks({+ post: {+ '/api/projects/:team/feature_flags/user_blast_radius': () => [200, { affected: 200, total: 2000 }],+ },+ })initKeaTests()})@@ -113,16 +125,193 @@ describe('FeatureFlagRulesV2Readonly', () => {</Provider>)- const [pausedRow, runningRow] = Array.from(container.querySelectorAll('tbody tr'))- expect(pausedRow).toHaveTextContent('Experiment')- expect(pausedRow).toHaveTextContent('Paused')- expect(pausedRow).toHaveTextContent('control33.34%"standard"')- expect(pausedRow).toHaveTextContent('compact66.66%"compact-layout"')- expect(pausedRow).toHaveTextContent('50%Miss: next rule')- expect(pausedRow).toHaveTextContent('Holdout excludes 5%')- expect(runningRow).toHaveTextContent('Experiment')- expect(runningRow).not.toHaveTextContent('Paused')- expect(runningRow).not.toHaveTextContent('Holdout')+ const [pausedRule, runningRule] = Array.from(container.querySelectorAll('[data-attr="rules-v2-rule-readonly"]'))+ expect(pausedRule).toHaveTextContent('Experiment')+ expect(pausedRule).toHaveTextContent('Paused')+ expect(pausedRule).toHaveTextContent('Matching users get the default value')+ const variants = Array.from(pausedRule.querySelectorAll('[data-attr="rules-v2-variant-readonly"]'))+ expect(variants.map((variant) => variant.textContent)).toEqual([+ 'control33.34%standard',+ 'compact66.66%compact-layout',+ ])+ expect(pausedRule).toHaveTextContent('50% of the rest are enrolled. The others continue to the next rule.')+ expect(pausedRule).toHaveTextContent('Holdout excludes 5%')+ expect(runningRule).toHaveTextContent('Experiment')+ expect(runningRule).not.toHaveTextContent('Paused')+ expect(runningRule).not.toHaveTextContent('Holdout')expect(container).not.toHaveTextContent('must-not-render')})++ it('ends the rules with the default value, and estimates who each rule matches and reaches', async () => {+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly config={CONFIG} />+ </Provider>+ )++ const rule = container.querySelector('[data-attr="rules-v2-rule-readonly"]')+ await waitFor(() => expect(rule).toHaveTextContent('≈ 200 users'))+ expect(rule).toHaveTextContent('≈ 100 users')+ expect(container.querySelector('[data-attr="rules-v2-default-step"]')).toHaveTextContent(+ 'Rule 1 decides the value for every user'+ )+ expect(container.querySelector('[data-attr="rules-v2-default-step"]')).toHaveTextContent('false')+ })++ it('warns about a rule that an earlier rule hides', () => {+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly+ config={{+ ...CONFIG,+ rules: [+ CONFIG.rules[0],+ {+ id: 'rule-2',+ rule_type: 'targeted_release',+ targeting: { properties: [] },+ value: true,+ },+ ],+ }}+ />+ </Provider>+ )++ const [first, second] = Array.from(container.querySelectorAll('[data-attr="rules-v2-rule-readonly"]'))+ expect(first.querySelector('[data-attr="rules-v2-rule-unreachable"]')).toBeNull()+ expect(second.querySelector('[data-attr="rules-v2-rule-unreachable"]')).toHaveTextContent(+ 'This rule is never reached: rule 1 already decides the value'+ )+ })++ it('shows a paused experiment without an enrolled estimate, since it enrolls no one', async () => {+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly+ config={{+ ...CONFIG,+ rules: [+ {+ id: 'rule-paused',+ rule_type: 'experiment',+ targeting: { properties: [] },+ paused: true,+ rollout_percentage: 50,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ seed: 'seed',+ variants: [+ { key: 'control', weight: 50, value: false },+ { key: 'test', weight: 50, value: true },+ ],+ },+ ],+ }}+ />+ </Provider>+ )++ const rule = container.querySelector('[data-attr="rules-v2-rule-readonly"]')+ await waitFor(() => expect(rule).toHaveTextContent('≈ 200 users'))+ expect(rule).not.toHaveTextContent('≈ 100 users')+ })++ it.each([+ { status: 500, retry: true },+ { status: 400, retry: false },+ ])('offers a retry after a failed estimate only when one can help (status $status)', async ({ status, retry }) => {+ useMocks({+ post: { '/api/projects/:team/feature_flags/user_blast_radius': () => [status, { detail: 'Failed.' }] },+ })+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly config={CONFIG} />+ </Provider>+ )++ const rule = container.querySelector('[data-attr="rules-v2-rule-readonly"]')+ await waitFor(() => expect(rule).toHaveTextContent("Couldn't estimate"))+ expect(rule?.textContent?.includes('Retry')).toBe(retry)+ })++ it('estimates again on Retry, since a failed estimate is not kept', async () => {+ useMocks({+ post: { '/api/projects/:team/feature_flags/user_blast_radius': () => [500, { detail: 'Failed.' }] },+ })+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly config={CONFIG} />+ </Provider>+ )+ const rule = container.querySelector<HTMLElement>('[data-attr="rules-v2-rule-readonly"]')!+ await waitFor(() => expect(rule).toHaveTextContent('Retry'))++ useMocks({+ post: {+ '/api/projects/:team/feature_flags/user_blast_radius': () => [200, { affected: 200, total: 2000 }],+ },+ })+ fireEvent.click(within(rule).getAllByText('Retry')[0])++ await waitFor(() => expect(rule).toHaveTextContent('≈ 200 users'))+ })++ it('does not estimate a rule while one of its conditions has no value', async () => {+ const estimate = jest.fn(() => [200, { affected: 200, total: 2000 }])+ useMocks({ post: { '/api/projects/:team/feature_flags/user_blast_radius': estimate } })+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly+ config={withTargeting({+ key: 'email',+ type: PropertyFilterType.Person,+ operator: PropertyOperator.Exact,+ value: [],+ })}+ />+ </Provider>+ )++ await act(async () => {})+ expect(estimate).not.toHaveBeenCalled()+ expect(container.querySelector('[data-attr="rules-v2-rule-readonly"]')).not.toHaveTextContent('≈')+ expect(container.querySelector('[data-attr="rules-v2-rule-readonly"]')).not.toHaveTextContent('Estimating')+ })++ it('estimates a group flag over its group type and links to the matching groups', async () => {+ const groupTypeIndexes: unknown[] = []+ useMocks({+ post: {+ '/api/projects/:team/feature_flags/user_blast_radius': async ({ request }) => {+ groupTypeIndexes.push(((await request.json()) as Record<string, unknown>).group_type_index)+ return [200, { affected: 30, total: 90 }]+ },+ },+ })+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly config={{ ...CONFIG, aggregation_group_type_index: 0 }} />+ </Provider>+ )++ await waitFor(() => expect(container).toHaveTextContent('≈ 30'))+ expect(groupTypeIndexes).toEqual([0])+ expect(container.querySelector('a[href*="/groups/0"]')).toHaveTextContent('≈ 30')+ })++ it('shows a rule type it does not know instead of failing', () => {+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly+ config={{+ ...CONFIG,+ rules: [{ id: 'rule-old', rule_type: 'variant_rollout', targeting: { properties: [] } } as any],+ }}+ />+ </Provider>+ )++ expect(container.querySelector('[data-attr="rules-v2-rule-readonly"]')).toHaveTextContent('variant_rollout')+ })})diff --git a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsxindex 50f1ed090a53..996602251149 100644--- a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx+++ b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx@@ -1,143 +1,265 @@import { useValues } from 'kea'+import { Fragment } from 'react'-import { LemonTable, LemonTag } from '@posthog/lemon-ui'+import { LemonTag } from '@posthog/lemon-ui'-import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'-import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'-import { capitalizeFirstLetter } from 'lib/utils/strings'+import 'lib/components/PropertyFilters/PropertyFilters.scss'+import { PropertyFilterButton } from 'lib/components/PropertyFilters/components/PropertyFilterButton'+import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'+import { rulesV2ShadowingRules } from 'scenes/feature-flags/featureFlagRulesV2Draft'-import { groupsModel } from '~/models/groupsModel'-import { FeatureFlagRulesV2Config, FeatureFlagRulesV2Rule } from '~/types'+import { Noun, groupsModel } from '~/models/groupsModel'+import { FeatureFlagRulesV2Config, FeatureFlagRulesV2ExperimentRule, FeatureFlagRulesV2Rule } from '~/types'+import { isRulesV2EditableConfig } from './featureFlagConfigFormat'import { FeatureFlagConfigReadonlyNotice } from './FeatureFlagConfigReadonlyNotice'import { formatPercentage } from './FractionalRolloutWarning'+import {+ RulesV2AllocationBar,+ RulesV2Connector,+ RulesV2DefaultStep,+ RulesV2MatchCountText,+ RulesV2PausedRow,+ RulesV2PausedTag,+ RulesV2RuleNumber,+ RulesV2RuleRow,+ RulesV2RuleTypeLabel,+ RulesV2RulesHeading,+ RulesV2ShadowedWarning,+ RulesV2Value,+ rulesV2ExperimentSegments,+ rulesV2ReachedPercentage,+ rulesV2RolloutMissText,+ rulesV2VariantColor,+ useRulesV2MatchCount,+} from './RulesV2Flow'-const RULE_TYPE_LABELS: Record<FeatureFlagRulesV2Rule['rule_type'], string> = {- targeted_release: 'Targeted release',- percentage_rollout: 'Percentage rollout',- experiment: 'Experiment',-}--function JsonValue({ value }: { value: unknown }): JSX.Element {- return <code className="text-xs break-all">{JSON.stringify(value)}</code>-}--function RolloutCell({ rule }: { rule: FeatureFlagRulesV2Rule }): JSX.Element {- if (rule.rule_type === 'targeted_release') {- return <span>Everyone matching</span>- }+function ExperimentRows({+ rule,+ subjects,+ count,+}: {+ rule: FeatureFlagRulesV2ExperimentRule+ subjects: Noun+ count: ReturnType<typeof useRulesV2MatchCount>+}): JSX.Element {+ const rolloutPercentage = rule.rollout_percentage+ const heldOut = rule.holdout?.exclusion_percentage ?? 0+ const reached = rulesV2ReachedPercentage(rule)return (- <div className="flex flex-col gap-1">- <span className="tabular-nums">{formatPercentage(rule.rollout_percentage)}</span>- <span className="text-xs text-muted">- {rule.on_rollout_miss === 'continue' ? 'Miss: next rule' : 'Miss: default value'}- </span>- </div>+ <>+ {rule.holdout && (+ <RulesV2RuleRow label="Holdout">+ <span className="leading-7">+ Holdout excludes <b className="tabular-nums">{formatPercentage(heldOut)}</b> of matching{' '}+ {subjects.plural}. They get the default value.+ </span>+ </RulesV2RuleRow>+ )}+ <RulesV2RuleRow+ label="Rollout"+ aside={+ reached === null ? null : (+ <RulesV2MatchCountText count={count} subjects={subjects} rolloutPercentage={reached} />+ )+ }+ >+ <span className="leading-7">+ {rolloutPercentage >= 100 ? (+ <>+ Every matching {subjects.singular}+ {rule.holdout ? ' not held out' : ''} is enrolled.+ </>+ ) : (+ <>+ <b className="tabular-nums">{formatPercentage(rolloutPercentage)}</b>+ {rule.holdout ? ' of the rest' : ''} are enrolled. The others{' '}+ {rulesV2RolloutMissText(rule.on_rollout_miss)}.+ </>+ )}+ </span>+ </RulesV2RuleRow>+ <RulesV2RuleRow label="Variants">+ <div className="flex flex-col gap-2 pt-2.5 max-w-120">+ <RulesV2AllocationBar segments={rulesV2ExperimentSegments(rule)} />+ <div className="flex flex-col gap-1">+ {rule.variants.map((variant, index) => (+ <div+ key={variant.key}+ className="grid grid-cols-[auto_minmax(0,12rem)_3.5rem_minmax(0,1fr)] items-center gap-x-3 text-sm"+ data-attr="rules-v2-variant-readonly"+ >+ <span+ className="size-2.5 rounded-full"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ background: rulesV2VariantColor(index) }}+ />+ <span className="font-mono truncate">{variant.key}</span>+ <span className="tabular-nums text-secondary text-right">+ {formatPercentage(variant.weight)}+ </span>+ <span className="flex min-w-0">+ <RulesV2Value value={variant.value} />+ </span>+ </div>+ ))}+ </div>+ </div>+ </RulesV2RuleRow>+ </>)}-function ValueCell({ rule }: { rule: FeatureFlagRulesV2Rule }): JSX.Element {- if (rule.rule_type !== 'experiment') {- return <JsonValue value={rule.value} />- }+function RuleCardReadonly({+ rule,+ index,+ config,+ subjects,+ shadowedBy,+}: {+ rule: FeatureFlagRulesV2Rule+ index: number+ config: FeatureFlagRulesV2Config+ subjects: Noun+ shadowedBy: number | null+}): JSX.Element {+ const properties = rule.targeting.properties+ const count = useRulesV2MatchCount(properties, config.aggregation_group_type_index ?? null)+ const paused = rule.rule_type === 'experiment' && rule.paused+return (- <div className="flex flex-col gap-1">- {rule.paused && (- <LemonTag- type="warning"- size="small"- className="self-start"- title="Persons this rule targets get the default value while it is paused."- >- Paused- </LemonTag>- )}- {rule.variants.map((variant) => (- <div key={variant.key} className="flex items-center gap-2 text-xs">- <span className="font-mono">{variant.key}</span>- <span className="tabular-nums text-muted">{formatPercentage(variant.weight)}</span>- <JsonValue value={variant.value} />- </div>- ))}- {rule.holdout && (- <span className="text-xs text-muted">- Holdout excludes {formatPercentage(rule.holdout.exclusion_percentage)}- </span>- )}+ <div className="rounded border bg-surface-primary" data-attr="rules-v2-rule-readonly">+ <div className="flex items-center gap-2 px-3 py-2 border-b min-h-11">+ <RulesV2RuleNumber index={index} muted={shadowedBy !== null} />+ <RulesV2RuleTypeLabel ruleType={rule.rule_type} />+ {rule.description && <span className="text-secondary truncate min-w-0">{rule.description}</span>}+ <div className="flex-1" />+ {paused && <RulesV2PausedTag />}+ </div>+ <div className="px-3 py-2.5 flex flex-col gap-1.5">+ <RulesV2ShadowedWarning shadowedBy={shadowedBy} subjects={subjects} />+ <RulesV2RuleRow label="If" aside={<RulesV2MatchCountText count={count} subjects={subjects} />}>+ {properties.length > 0 ? (+ <div className="PropertyFilters py-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-1">+ {properties.map((property, propertyIndex) => (+ <Fragment key={propertyIndex}>+ {propertyIndex > 0 && (+ <span className="text-xxs font-semibold uppercase text-muted">and</span>+ )}+ {/* The chip grows to fill a flex row; its own box keeps it to its content. */}+ <span className="flex min-w-0 max-w-full">+ <PropertyFilterButton item={property} compact />+ </span>+ </Fragment>+ ))}+ </div>+ ) : (+ <span className="leading-7">All {subjects.plural}</span>+ )}+ </RulesV2RuleRow>+ {paused && (+ <RulesV2PausedRow+ subjects={subjects}+ defaultValue={config.default_value}+ until="the experiment resumes"+ />+ )}+ {rule.rule_type === 'percentage_rollout' && (+ <RulesV2RuleRow+ label="Rollout"+ aside={+ <RulesV2MatchCountText+ count={count}+ subjects={subjects}+ rolloutPercentage={rule.rollout_percentage}+ />+ }+ >+ <div className="flex flex-col gap-1.5 pt-1.5">+ <span>+ <b className="tabular-nums">{formatPercentage(rule.rollout_percentage)}</b> of matching{' '}+ {subjects.plural}+ {rule.rollout_percentage < 100 && (+ <span className="text-secondary">+ {' '}+ · the others {rulesV2RolloutMissText(rule.on_rollout_miss)}+ </span>+ )}+ </span>+ <RulesV2AllocationBar+ className="max-w-80"+ segments={[+ { key: 'rollout', label: 'Rolled out', percentage: rule.rollout_percentage },+ ]}+ />+ </div>+ </RulesV2RuleRow>+ )}+ {rule.rule_type === 'experiment' ? (+ <div className={paused ? 'opacity-50 flex flex-col gap-1.5' : 'flex flex-col gap-1.5'}>+ <ExperimentRows rule={rule} subjects={subjects} count={count} />+ </div>+ ) : (+ <RulesV2RuleRow label="Serve">+ <span className="leading-7">+ <RulesV2Value value={rule.value} />+ </span>+ </RulesV2RuleRow>+ )}+ </div></div>)}-export function FeatureFlagRulesV2Readonly({ config }: { config: FeatureFlagRulesV2Config }): JSX.Element {+export function FeatureFlagRulesV2Readonly({+ config,+ active = true,+ editButton,+}: {+ config: FeatureFlagRulesV2Config+ active?: boolean+ /** Shown beside the heading when the page can open the editor. */+ editButton?: JSX.Element | null+}): JSX.Element {const { aggregationLabel } = useValues(groupsModel)- const subjects = aggregationLabel(config.aggregation_group_type_index, true).plural-- const columns: LemonTableColumns<FeatureFlagRulesV2Rule> = [- {- title: '#',- width: 0,- render: (_, __, index) => <span className="tabular-nums">{index + 1}</span>,- },- {- title: 'Type',- width: 0,- render: (_, rule) => (- <LemonTag type="default" className="whitespace-nowrap">- {RULE_TYPE_LABELS[rule.rule_type]}- </LemonTag>- ),- },- {- title: 'Description',- render: (_, rule) => rule.description || <span className="text-muted">—</span>,- },- {- title: 'Targeting',- render: (_, rule) =>- rule.targeting.properties.length > 0 ? (- <PropertyFiltersDisplay filters={rule.targeting.properties} compact />- ) : (- <span className="text-muted">All {subjects}</span>- ),- },- {- title: 'Rollout',- width: 0,- render: (_, rule) => <RolloutCell rule={rule} />,- },- {- title: 'Value',- render: (_, rule) => <ValueCell rule={rule} />,- },- ]+ const { featureFlags } = useValues(enabledFeaturesLogic)+ const subjects = aggregationLabel(config.aggregation_group_type_index, true)+ const editable = isRulesV2EditableConfig(config, featureFlags)+ const shadowingRules = rulesV2ShadowingRules(config.rules)return (- <div className="flex flex-col gap-4" data-attr="feature-flag-rules-v2-readonly">- <FeatureFlagConfigReadonlyNotice filters={config} hasEditButton />- <div className="flex flex-wrap gap-6 text-sm">- <div className="flex flex-col gap-1">- <span className="font-semibold">Return type</span>- <LemonTag type="default">{capitalizeFirstLetter(config.return_type)}</LemonTag>- </div>- <div className="flex flex-col gap-1">- <span className="font-semibold">Default value</span>- <JsonValue value={config.default_value} />- </div>- <div className="flex flex-col gap-1">- <span className="font-semibold">Evaluated per</span>- <span>{capitalizeFirstLetter(subjects)}</span>+ <div className="flex flex-col gap-3" data-attr="feature-flag-rules-v2-readonly">+ {!editable && <FeatureFlagConfigReadonlyNotice filters={config} />}+ <div className="flex flex-wrap items-start justify-between gap-2">+ <RulesV2RulesHeading subjects={subjects} />+ <div className="flex items-center gap-2">+ <LemonTag type="default" data-attr="rules-v2-return-type">+ Returns {config.return_type}+ </LemonTag>+ {editable && editButton}</div></div>- <div className="flex flex-col gap-2">- <span className="font-semibold">Rules</span>- <p className="text-xs text-muted m-0">Rules are evaluated top to bottom; the first match decides.</p>- <LemonTable- dataSource={config.rules}- columns={columns}- rowKey="id"- size="small"- emptyState="No rules: every evaluation returns the default value."- />+ {!active && (+ <div className="text-xs text-secondary">+ The flag is disabled, so these rules are not evaluated until you enable it.+ </div>+ )}+ <div className="flex flex-col">+ {config.rules.map((rule, index) => (+ <Fragment key={rule.id ?? index}>+ <RuleCardReadonly+ rule={rule}+ index={index}+ config={config}+ subjects={subjects}+ shadowedBy={shadowingRules[index]}+ />+ <RulesV2Connector />+ </Fragment>+ ))}+ <RulesV2DefaultStep subjects={subjects} rules={config.rules}>+ <RulesV2Value value={config.default_value} />+ </RulesV2DefaultStep></div></div>)diff --git a/products/feature_flags/frontend/RulesV2Flow.tsx b/products/feature_flags/frontend/RulesV2Flow.tsxnew file mode 100644index 000000000000..c01d5b8cd832--- /dev/null+++ b/products/feature_flags/frontend/RulesV2Flow.tsx@@ -0,0 +1,409 @@+import clsx from 'clsx'+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { IconCornerDownRight, IconFlask, IconPause, IconPieChart, IconTarget } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { getSeriesColor } from 'lib/colors'+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { Link } from 'lib/lemon-ui/Link'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'+import { BlastRadiusErrorMessage } from 'scenes/feature-flags/BlastRadiusErrorMessage'+import { BlastRadiusError, isBlastRadiusErrorRetryable } from 'scenes/feature-flags/featureFlagReleaseConditionsLogic'+import { rulesV2CatchAllRule } from 'scenes/feature-flags/featureFlagRulesV2Draft'+import { matchingActorsUrl } from 'scenes/feature-flags/matchingActorsUrl'++import { Noun } from '~/models/groupsModel'+import { AnyPropertyFilter, FeatureFlagRulesV2DraftRule, FeatureFlagRulesV2Variant, JsonType } from '~/types'++import { formatPercentage } from './FractionalRolloutWarning'+import { rulesV2MatchCountLogic } from './rulesV2MatchCountLogic'++export type RulesV2RuleType = FeatureFlagRulesV2DraftRule['rule_type']++export const RULES_V2_RULE_TYPES: RulesV2RuleType[] = ['targeted_release', 'percentage_rollout', 'experiment']++export const RULES_V2_RULE_TYPE_META: Record<+ RulesV2RuleType,+ { label: string; description: string; icon: JSX.Element }+> = {+ targeted_release: {+ label: 'Targeted release',+ description: 'Serve one value to every user who matches.',+ icon: <IconTarget />,+ },+ percentage_rollout: {+ label: 'Percentage rollout',+ description: 'Serve one value to a share of the users who match.',+ icon: <IconPieChart />,+ },+ experiment: {+ label: 'Experiment',+ description: 'Split the users who match between variants.',+ icon: <IconFlask />,+ },+}++export function rulesV2RuleTypeMenuLabel(ruleType: RulesV2RuleType): JSX.Element {+ const meta = RULES_V2_RULE_TYPE_META[ruleType]+ return (+ <div className="flex flex-col py-0.5">+ <span className="font-semibold">{meta.label}</span>+ <span className="text-xs text-secondary font-normal">{meta.description}</span>+ </div>+ )+}++export const RULES_V2_NO_VALUE_TOOLTIP = 'The flag returns no value, so the SDK uses the fallback passed in code.'++/** A value a flag can serve, styled by kind so true, false and strings read apart at a glance. */+export function RulesV2Value({ value, className }: { value: JsonType | null; className?: string }): JSX.Element {+ if (value === null) {+ return (+ <Tooltip title={RULES_V2_NO_VALUE_TOOLTIP}>+ <span className={clsx('italic text-secondary whitespace-nowrap', className)}>no value</span>+ </Tooltip>+ )+ }+ if (typeof value === 'boolean') {+ return (+ <LemonTag type={value ? 'success' : 'muted'} className={clsx('font-mono', className)}>+ {String(value)}+ </LemonTag>+ )+ }+ return (+ <LemonTag type="default" className={clsx('font-mono max-w-full', className)} title={JSON.stringify(value)}>+ <span className="truncate">{typeof value === 'string' ? value : JSON.stringify(value)}</span>+ </LemonTag>+ )+}++/** A stored document can hold a rule type this page does not know, such as one from an older pilot. */+export function RulesV2RuleTypeLabel({ ruleType }: { ruleType: string }): JSX.Element {+ const meta: { label: string; icon: JSX.Element } | undefined = RULES_V2_RULE_TYPE_META[ruleType as RulesV2RuleType]+ return (+ <span className="inline-flex items-center gap-1 font-semibold whitespace-nowrap">+ <span className="text-base text-secondary flex">{meta?.icon ?? <IconTarget />}</span>+ {meta?.label ?? ruleType}+ </span>+ )+}++export function RulesV2RuleNumber({ index, muted }: { index: number; muted?: boolean }): JSX.Element {+ return (+ <span+ className={clsx(+ 'inline-flex items-center justify-center shrink-0 size-6 rounded-full text-xs font-semibold tabular-nums border bg-surface-secondary',+ muted && 'text-muted'+ )}+ >+ <span className="sr-only">Rule </span>+ {index + 1}+ </span>+ )+}++/** One labelled line of a rule card. The labels line up into a column, so a card reads as "if … serve …". */+export function RulesV2RuleRow({+ label,+ children,+ aside,+ className,+}: {+ label: string+ children: React.ReactNode+ aside?: React.ReactNode+ className?: string+}): JSX.Element {+ return (+ <div className={clsx('grid grid-cols-[4.5rem_minmax(0,1fr)] gap-x-3 items-start', className)}>+ <span className="text-xxs font-semibold uppercase tracking-wide text-muted leading-7">{label}</span>+ <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-1 min-h-7">+ <div className="flex flex-col gap-1 min-w-0 flex-1">{children}</div>+ {aside && <div className="shrink-0 text-xs text-secondary leading-7">{aside}</div>}+ </div>+ </div>+ )+}++/** The line between two steps of the flow: a user who is not claimed by the step above moves on to the next one. */+export function RulesV2Connector(): JSX.Element {+ return (+ <div className="flex h-4 pl-[1.4rem]" aria-hidden>+ <div className="w-px h-full bg-border-primary" />+ </div>+ )+}++export interface RulesV2AllocationSegment {+ key: string+ label: string+ percentage: number+ color?: string+ /** Hatched, for users who leave the rule with the default value. */+ hatched?: boolean+}++const HATCHED = 'repeating-linear-gradient(135deg, var(--color-text-tertiary) 0 1.5px, transparent 1.5px 5px)'++/** Where the users a rule matches end up, as one bar. Segments are percentages of those users and total at most 100. */+export function RulesV2AllocationBar({+ segments,+ className,+}: {+ segments: RulesV2AllocationSegment[]+ className?: string+}): JSX.Element {+ const total = segments.reduce((sum, segment) => sum + segment.percentage, 0)+ return (+ <div+ className={clsx('flex h-2 w-full rounded-full overflow-hidden bg-fill-secondary', className)}+ role="img"+ aria-label={segments+ .map((segment) => `${segment.label} ${formatPercentage(segment.percentage)}`)+ .join(', ')}+ >+ {segments+ .filter((segment) => segment.percentage > 0)+ .map((segment) => (+ <Tooltip key={segment.key} title={`${segment.label}: ${formatPercentage(segment.percentage)}`}>+ <div+ className="h-full first:rounded-l-full transition-[width] duration-200 ease-out border-r border-surface-primary last:border-r-0"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ width: `${(segment.percentage / Math.max(total, 100)) * 100}%`,+ background: segment.hatched ? HATCHED : (segment.color ?? 'var(--color-accent)'),+ }}+ />+ </Tooltip>+ ))}+ </div>+ )+}++export function rulesV2VariantColor(index: number): string {+ return getSeriesColor(index)+}++interface RulesV2RolloutShape {+ rollout_percentage: number+ holdout?: { exclusion_percentage: number }+ paused?: boolean+}++function enrolledPercentage(rule: RulesV2RolloutShape): number {+ return ((100 - (rule.holdout?.exclusion_percentage ?? 0)) * rule.rollout_percentage) / 100+}++export function rulesV2ReachedPercentage(rule: RulesV2RolloutShape): number | null {+ return rule.paused ? null : enrolledPercentage(rule)+}++export function rulesV2ExperimentSegments(+ rule: RulesV2RolloutShape & { variants: FeatureFlagRulesV2Variant[] }+): RulesV2AllocationSegment[] {+ const heldOut = rule.holdout?.exclusion_percentage ?? 0+ const enrolled = enrolledPercentage(rule)+ return [+ ...(heldOut > 0 ? [{ key: 'holdout', label: 'Holdout', percentage: heldOut, hatched: true }] : []),+ ...rule.variants.map((variant, index) => ({+ key: `variant-${index}`,+ label: variant.key || `Variant ${index + 1}`,+ percentage: (enrolled * variant.weight) / 100,+ color: rulesV2VariantColor(index),+ })),+ ]+}++export function rulesV2RolloutMissText(onRolloutMiss: 'continue' | 'return_default'): string {+ return onRolloutMiss === 'continue' ? 'continue to the next rule' : 'get the default value'+}++/** The targeting count for a rule: a debounced estimate that ignores incomplete conditions. */+export function useRulesV2MatchCount(+ properties: AnyPropertyFilter[],+ groupTypeIndex: number | null+): {+ countable: boolean+ affected: number | null+ total: number | null+ error: BlastRadiusError | null+ retry: () => void+ matchingActorsUrl: string+} {+ const propertiesKey = useDebouncedValue(+ useMemo(() => JSON.stringify(properties), [properties]),+ 400+ )+ const logic = rulesV2MatchCountLogic({ propertiesKey, groupTypeIndex })+ const { matchCount, matchCountError, countable } = useValues(logic)+ const { loadMatchCount } = useActions(logic)+ return {+ countable,+ affected: matchCount?.affected ?? null,+ total: matchCount?.total ?? null,+ error: matchCountError,+ retry: loadMatchCount,+ matchingActorsUrl: matchingActorsUrl(properties, groupTypeIndex),+ }+}++export function RulesV2MatchCountText({+ count,+ subjects,+ rolloutPercentage,+}: {+ count: ReturnType<typeof useRulesV2MatchCount>+ subjects: Noun+ /** Shows the share the rollout reaches instead of the targeting match. */+ rolloutPercentage?: number+}): JSX.Element | null {+ if (!count.countable) {+ return null+ }+ if (count.error) {+ return (+ <span className="inline-flex items-center gap-1">+ <Tooltip title={<BlastRadiusErrorMessage error={count.error} pluralName={subjects.plural} />}>+ <span tabIndex={0} className="cursor-help">+ Couldn't estimate+ </span>+ </Tooltip>+ {isBlastRadiusErrorRetryable(count.error) && (+ <LemonButton size="xsmall" type="tertiary" onClick={count.retry}>+ Retry+ </LemonButton>+ )}+ </span>+ )+ }+ if (count.affected === null) {+ return <span className="text-muted">Estimating…</span>+ }+ const reached =+ rolloutPercentage === undefined ? count.affected : Math.floor((count.affected * rolloutPercentage) / 100)+ const reachedText = `≈ ${pluralize(reached, subjects.singular, subjects.plural)}`+ if (rolloutPercentage !== undefined) {+ return <span className="tabular-nums">{reachedText}</span>+ }+ return (+ <Tooltip+ title={`About ${humanFriendlyNumber(reached)} of ${humanFriendlyNumber(count.total ?? 0)} ${subjects.plural} match these conditions. Earlier rules may claim some of them first. Opens the matching ${subjects.plural}.`}+ >+ <Link to={count.matchingActorsUrl} target="_blank" className="tabular-nums">+ {reachedText}+ </Link>+ </Tooltip>+ )+}++/** The last step of every flow: what users get when no rule claims them. */+export function RulesV2DefaultStep({+ children,+ subjects,+ rules,+}: {+ children: React.ReactNode+ subjects: Noun+ rules: Parameters<typeof rulesV2CatchAllRule>[0]+}): JSX.Element {+ const hasRules = rules.length > 0+ const catchAllRule = rulesV2CatchAllRule(rules)+ return (+ <div+ className="rounded border border-dashed bg-surface-secondary px-3 py-2.5 flex flex-wrap items-center gap-x-3 gap-y-2"+ data-attr="rules-v2-default-step"+ >+ <span className="inline-flex items-center justify-center shrink-0 size-6 rounded-full text-secondary">+ <IconCornerDownRight className="text-base" />+ </span>+ <div className="flex flex-col min-w-0 flex-1">+ <span className="font-semibold">+ {hasRules ? `All other ${subjects.plural}` : `All ${subjects.plural}`}+ </span>+ <span className="text-xs text-secondary">+ {catchAllRule !== null+ ? `Rule ${catchAllRule + 1} decides the value for every ${subjects.singular}, so nobody reaches this step. Holdouts, paused experiments and rollouts that send the rest to the default still serve this value.`+ : hasRules+ ? `${capitalizeFirstLetter(subjects.plural)} that no rule serves get the default value.`+ : `With no rules, all ${subjects.plural} get the default value.`}+ </span>+ </div>+ <div className="flex items-center gap-2">+ <span className="text-xxs font-semibold uppercase tracking-wide text-muted">Default</span>+ {children}+ </div>+ </div>+ )+}++/** A field error under an input that has no field of its own, rendered only while there is an error. */+export function RulesV2FieldError({ error }: { error: string | null | undefined }): JSX.Element | null {+ return error ? <LemonField.Error error={error} /> : null+}++/** Shown in a rule that an earlier rule makes unreachable. */+export function RulesV2ShadowedWarning({+ shadowedBy,+ subjects,+}: {+ shadowedBy: number | null+ subjects: Noun+}): JSX.Element | null {+ if (shadowedBy === null) {+ return null+ }+ return (+ <div data-attr="rules-v2-rule-unreachable">+ <LemonBanner type="warning" className="text-sm">+ This rule is never reached: rule {shadowedBy + 1} already decides the value for every{' '}+ {subjects.singular} this rule matches. Move this rule above rule {shadowedBy + 1}, or narrow rule{' '}+ {shadowedBy + 1}'s conditions.+ </LemonBanner>+ </div>+ )+}++export function RulesV2RulesHeading({ subjects, className }: { subjects: Noun; className?: string }): JSX.Element {+ return (+ <div className={clsx('flex flex-col', className)}>+ <span className="font-semibold">Rules</span>+ <span className="text-xs text-secondary">+ Checked from top to bottom. The first rule that serves a {subjects.singular} decides the value.+ </span>+ </div>+ )+}++export function RulesV2PausedTag(): JSX.Element {+ return (+ <LemonTag type="warning" icon={<IconPause />}>+ Paused+ </LemonTag>+ )+}++export function RulesV2PausedRow({+ subjects,+ defaultValue,+ until,+ className,+}: {+ subjects: Noun+ defaultValue: JsonType | null+ until: string+ className?: string+}): JSX.Element {+ return (+ <RulesV2RuleRow label="Paused" className={className}>+ <span className="leading-7">+ Matching {subjects.plural} get the default value <RulesV2Value value={defaultValue} /> until {until}.+ Nobody is enrolled meanwhile.+ </span>+ </RulesV2RuleRow>+ )+}diff --git a/products/feature_flags/frontend/featureFlagConfigFormat.test.ts b/products/feature_flags/frontend/featureFlagConfigFormat.test.tsindex 05a8233276f0..0b992c13397d 100644--- a/products/feature_flags/frontend/featureFlagConfigFormat.test.ts+++ b/products/feature_flags/frontend/featureFlagConfigFormat.test.ts@@ -77,16 +77,61 @@ describe('featureFlagConfigFormat', () => {),true,],+ [+ 'a boolean flag without a default',+ stringFlag(+ { variants: [{ key: 'a', weight: 100, value: true }] },+ { return_type: 'boolean', default_value: null }+ ),+ false,+ ],+ [+ 'an object experiment rule',+ stringFlag(+ { variants: [{ key: 'a', weight: 100, value: { columns: 2 } }] },+ { return_type: 'object', default_value: null }+ ),+ true,+ ],+ [+ 'an array where an object belongs',+ stringFlag(+ { variants: [{ key: 'a', weight: 100, value: ['compact'] }] },+ { return_type: 'object', default_value: null }+ ),+ false,+ ],['group assignment', stringFlag({}, { aggregation_group_type_index: 0 }), false],['a variant value of another type', stringFlag({ variants: [{ key: 'a', weight: 100, value: 1 }] }), false],['a number return type',stringFlag(- { variants: [{ key: 'a', weight: 100, value: 1 }] },+ { variants: [{ key: 'a', weight: 100, value: 1.5 }] },+ { return_type: 'number', default_value: 1 }+ ),+ true,+ ],+ [+ 'a number past the safe integer range',+ stringFlag(+ { variants: [{ key: 'a', weight: 100, value: 2 ** 53 }] },{ return_type: 'number', default_value: 1 }),false,],+ [+ 'numbers at both ends of the safe integer range',+ stringFlag(+ {+ variants: [+ { key: 'a', weight: 50, value: Number.MAX_SAFE_INTEGER },+ { key: 'b', weight: 50, value: -Number.MAX_SAFE_INTEGER },+ ],+ },+ { return_type: 'number', default_value: 1 }+ ),+ true,+ ],['an unknown rule type', stringFlag({ rule_type: 'future_rule' }), false],])('decides whether a flag with %s opens the editor', (_, filters, editable) => {expect(isRulesV2EditableConfig(filters, EDITOR_ON)).toBe(editable)diff --git a/products/feature_flags/frontend/featureFlagConfigFormat.ts b/products/feature_flags/frontend/featureFlagConfigFormat.tsindex eb9925026f48..e863535d47d6 100644--- a/products/feature_flags/frontend/featureFlagConfigFormat.ts+++ b/products/feature_flags/frontend/featureFlagConfigFormat.ts@@ -2,6 +2,7 @@ import { isApprovalRequiredError } from 'lib/api-error'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { isObject } from 'lib/utils/guards'import {FeatureFlagConfig,@@ -115,7 +116,7 @@ export function rulesV2CreateDisabledReason(: null}-export const RULES_V2_EDITABLE_RETURN_TYPES: FeatureFlagRulesV2ReturnType[] = ['boolean', 'string']+export const RULES_V2_EDITABLE_RETURN_TYPES: FeatureFlagRulesV2ReturnType[] = ['boolean', 'string', 'number', 'object']export function isRulesV2Value(value: unknown, returnType: FeatureFlagRulesV2ReturnType): boolean {switch (returnType) {@@ -123,6 +124,10 @@ export function isRulesV2Value(value: unknown, returnType: FeatureFlagRulesV2Retreturn typeof value === 'boolean'case 'string':return typeof value === 'string' && value !== ''+ case 'number':+ return typeof value === 'number' && Math.abs(value) <= Number.MAX_SAFE_INTEGER+ case 'object':+ return isObject(value)default:return false}@@ -150,6 +155,8 @@ export function isRulesV2EditableConfig(filters: FeatureFlagConfig, enabledFeatuisRulesV2FeatureFlagConfig(filters) &&RULES_V2_EDITABLE_RETURN_TYPES.includes(filters.return_type) &&filters.aggregation_group_type_index == null &&+ // The editor offers only true and false as a boolean default, so it can't keep a stored null one.+ !(filters.return_type === 'boolean' && filters.default_value === null) &&filters.rules.every((rule) => isRulesV2EditableRule(rule, filters.return_type)))}diff --git a/products/feature_flags/frontend/rulesV2MatchCountLogic.ts b/products/feature_flags/frontend/rulesV2MatchCountLogic.tsnew file mode 100644index 000000000000..ebdd78cae664--- /dev/null+++ b/products/feature_flags/frontend/rulesV2MatchCountLogic.ts@@ -0,0 +1,151 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { RetainedValues } from 'lib/utils/retainedValues'+import { BlastRadiusError, toBlastRadiusError } from 'scenes/feature-flags/featureFlagReleaseConditionsLogic'+import { isIncompleteRulesV2Condition } from 'scenes/feature-flags/featureFlagRulesV2Draft'+import { projectLogic } from 'scenes/projectLogic'++import { AnyPropertyFilter } from '~/types'++import { featureFlagsUserBlastRadiusCreate } from './generated/api'++export interface RulesV2MatchCount {+ affected: number+ total: number+}++export interface RulesV2MatchCountLogicProps {+ /** The rule's targeting properties, serialized, so equal targeting shares one request. */+ propertiesKey: string+ groupTypeIndex: number | null+}++// The estimate is a slow query, and the view and the editor ask for the same targeting, so a pending or recent+// request is shared.+const recentMatchCounts = new RetainedValues<Promise<RulesV2MatchCount>>({+ maxEntries: 200,+ ttlMs: 5 * 60 * 1000,+ scopeToProject: false, // the key already names the project+})++function sharedMatchCount(+ projectId: number | null,+ { propertiesKey, groupTypeIndex }: RulesV2MatchCountLogicProps,+ properties: AnyPropertyFilter[]+): Promise<RulesV2MatchCount> {+ const cacheKey = `${projectId}:${groupTypeIndex}:${propertiesKey}`+ const cached = recentMatchCounts.get(cacheKey)+ if (cached) {+ return cached+ }+ const promise = featureFlagsUserBlastRadiusCreate(String(projectId), {+ condition: { properties },+ group_type_index: groupTypeIndex,+ }).then(({ affected, total }) => ({ affected, total }))+ recentMatchCounts.set(cacheKey, promise)+ promise.catch(() => {+ if (recentMatchCounts.get(cacheKey) === promise) {+ recentMatchCounts.delete(cacheKey)+ }+ })+ return promise+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface rulesV2MatchCountLogicValues {+ currentProjectId: number | null // projectLogic+ countable: boolean+ matchCount: RulesV2MatchCount | null+ matchCountError: BlastRadiusError | null+ properties: AnyPropertyFilter[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface rulesV2MatchCountLogicActions {+ loadMatchCount: () => {+ value: true+ }+ loadMatchCountFailure: (error: BlastRadiusError) => {+ error: BlastRadiusError+ }+ loadMatchCountSuccess: (matchCount: RulesV2MatchCount) => {+ matchCount: RulesV2MatchCount+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface rulesV2MatchCountLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ properties: (arg: any) => AnyPropertyFilter[]+ countable: (properties: AnyPropertyFilter[]) => boolean+ }+}++export type rulesV2MatchCountLogicType = MakeLogicType<+ rulesV2MatchCountLogicValues,+ rulesV2MatchCountLogicActions,+ RulesV2MatchCountLogicProps,+ rulesV2MatchCountLogicMeta+>++/**+ * How many persons or groups a rule's targeting matches, from the estimate the v1 release conditions show. An estimate is a+ * hint, so a failure shows inline with a retry instead of a toast.+ */+export const rulesV2MatchCountLogic = kea<rulesV2MatchCountLogicType>([+ props({} as RulesV2MatchCountLogicProps),+ key(({ propertiesKey, groupTypeIndex }) => `${groupTypeIndex ?? 'persons'}:${propertiesKey}`),+ path((key) => ['products', 'feature_flags', 'frontend', 'rulesV2MatchCountLogic', key]),+ connect(() => ({ values: [projectLogic, ['currentProjectId']] })),+ actions({+ loadMatchCount: true,+ loadMatchCountSuccess: (matchCount: RulesV2MatchCount) => ({ matchCount }),+ loadMatchCountFailure: (error: BlastRadiusError) => ({ error }),+ }),+ reducers({+ matchCount: [+ null as RulesV2MatchCount | null,+ {+ loadMatchCount: () => null,+ loadMatchCountSuccess: (_, { matchCount }) => matchCount,+ },+ ],+ matchCountError: [+ null as BlastRadiusError | null,+ {+ loadMatchCount: () => null,+ loadMatchCountFailure: (_, { error }) => error,+ },+ ],+ }),+ selectors({+ properties: [+ () => [(_, props) => props.propertiesKey],+ (propertiesKey: string): AnyPropertyFilter[] => JSON.parse(propertiesKey),+ ],+ countable: [+ (s) => [s.properties],+ (properties: AnyPropertyFilter[]): boolean => !properties.some(isIncompleteRulesV2Condition),+ ],+ }),+ listeners(({ actions, props, values }) => ({+ loadMatchCount: async (_, breakpoint) => {+ let matchCount: RulesV2MatchCount+ try {+ matchCount = await sharedMatchCount(values.currentProjectId, props, values.properties)+ } catch (error) {+ breakpoint()+ actions.loadMatchCountFailure(toBlastRadiusError(error))+ return+ }+ breakpoint()+ actions.loadMatchCountSuccess(matchCount)+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.countable) {+ actions.loadMatchCount()+ }+ }),+])