Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(experiments): drag to reorder metrics in the table (#77649)

ruby childs64bcdbd98358
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e8b756d13202..6c16fa66e472 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5895,25 +5895,25 @@ snapshots:
scenes-app-experiments--draft-experiment--light:
hash: v1.k794b7964.74192966b20280489fdc67329370f7c5b675e67a8e18512b61ac71e6c982c0f7.NrgEIHQRT87ytfEBzJVtAVuW3Wn06aWA8erEOgDlmpE
scenes-app-experiments--experiment-asymmetric-intervals--dark:
- hash: v1.k794b7964.aa2e1954e34d3bf3bae366e96d1d738a9576eb3535fa5f6b610f187bd8c8644f.NzIUnefqXLRK3LTnOPpL7972hJIwcXXMjSLXPmK9MuE
+ hash: v1.k794b7964.49105844a48e3c23386a1bea3720b6a2e4722f6d49afb4125c38351e132a53eb.ljI08w6HZnct_K7roF_S_nuqQ-MA6ChK2Tca7dh9hsI
scenes-app-experiments--experiment-asymmetric-intervals--light:
hash: v1.k794b7964.b2bc93939d938d962fbd42530c5c06ea637feef8192291232d4726aed5805cb4.Hl0K2n_pRnLrochHVl4MEGZG6PcHg72tGPuBxwQc9J8
scenes-app-experiments--experiment-exposures-expanded--dark:
- hash: v1.k794b7964.56095d76684633d164b2bd7f3e3da2aefefba1272f2818e3c8f2e4d1bff595c7.jIZ5N9SItEnQIRj-axX2BfRM21O5JSz_MSSH3JyLAd4
+ hash: v1.k794b7964.268a400ea2d747cba63eb6270af752f62080036c7cb16b2f7470794ba91d2253.h20Em9fXRb9O71IYCdZV5l5m4fxF8NfPgiMIl2yvkYM
scenes-app-experiments--experiment-exposures-expanded--light:
- hash: v1.k794b7964.724a28250f085bea69008b564ca8266298b8f927f6231d8c3ee40571356c99b5.hX_fvUeWfYI85mX0qLAi3WWzB-bHfef61kIPRKsrw8U
+ hash: v1.k794b7964.ba7d43c183d3d97f0f4056b4293ef15d323c56be131957881cae031d5c654fa9.QfVezRYgy-vWVpeyh5JBZ4B7diInR6UsdbNEMfaB3Ik
scenes-app-experiments--experiment-frequentist-five-variants--dark:
- hash: v1.k794b7964.e8a5b05a1e2fac506182f04dd0fb26649c927ca30a0166fd6dedefc6db83a3e7.bpIufNF51-pPDeWrq6e-Hu3o6Au6R9QlRzAUNeOcYgE
+ hash: v1.k794b7964.64907f2bf773632ae842870dd967079496c161171ca264af1d4e00e4e5c1195f.7yK2Tx9IC-ddtEvHbF__sgBr9ivvBShPMx7VUiyT2H8
scenes-app-experiments--experiment-frequentist-five-variants--light:
- hash: v1.k794b7964.467244e1b3678d7ed48d65486bda0175bf803f3b6b88409ff4fc31cb86a6e4be.CiD-wox9uMHSDNpfzgcY1Nk1r_f0_wDAFAG_12RsRh8
+ hash: v1.k794b7964.f478981f562a501e410ad9dcdcbdd71d073a180997aab12894e41512932b1d2f.h8YEuihISGANeWkHFNbbJMm1TtmMLzXRPRLq3twoCD8
scenes-app-experiments--experiment-frequentist-two-variants--dark:
- hash: v1.k794b7964.aa6f33f30d218a8d77d1f97aa5a650735df960b3859f75d755336d717cc50754._0xzc6w5jbUAOfZxxT9tzHyFGbVgcBfVQZhGtrfNtUI
+ hash: v1.k794b7964.bb18212dddff7df860cbea51f78d888106dcd91d28a43c72942f4377582b2f9e.m9EZYBw6L48FQNPBH9ilA5oAyaXj1uCwARaznfavowk
scenes-app-experiments--experiment-frequentist-two-variants--light:
- hash: v1.k794b7964.78c1d7249257f5c718f08f0891a67457acd2dd9db209f029e07e6b40032bc0f2.1OlEHxGwB9WRLVeWyifax0PiHjsUA46RUx0np37kSjM
+ hash: v1.k794b7964.f92ae3b1acfa8fc4f98babb18e7c944e30b5749400dd382d43fa702b1bc0727b.v7qRnZU8furIdj048Ap7rBb0QbVoNS88_de-FqorlF8
scenes-app-experiments--experiment-with-funnel-metric--dark:
hash: v1.k794b7964.96b1395012157c8db6f8b7c202fde3bc61fe5eac1ffc69e94e6aa7555d7aa761.Li7ufJd8K-fsREg0jONxzGhDJuDnuWcatmvY5cvdJRI
scenes-app-experiments--experiment-with-funnel-metric--light:
- hash: v1.k794b7964.8c14414398b3c6b47e0968adeea6d040b7a48c8f7f72d15bcd33392a005ca439.0tOTaEYTCs0PMiFDlR1l4QI6xLkEBXJE6o_kYkPV1BI
+ hash: v1.k794b7964.251dc04d7466461679393d7cad275a9afb66b3d3b562c86078e25db37349150e.laYWvinsU-fNhfqh4ZAewzsgi6u563HDsMVraFRbXMw
scenes-app-experiments--experiment-with-legacy-funnels-query--dark:
hash: v1.k794b7964.6503cdfd33ae5f9d525d14dc8d43b047e8469beca7e5e489534347904efe1dec.2CtGz-wQvIwr_SQDthwlGJI5bVcJ7bFpetJricY-Lps
scenes-app-experiments--experiment-with-legacy-funnels-query--light:
@@ -5927,13 +5927,13 @@ snapshots:
scenes-app-experiments--experiment-with-mean-metric--light:
hash: v1.k794b7964.2bd044c1fb951cc5280c8befc03b7534774e703e92aa268f228ab20bd2522411.AFij815dd9946fOpsJgW7T2G_FjYM3Njr7LJ87amVrQ
scenes-app-experiments--experiment-with-multiple-metrics--dark:
- hash: v1.k794b7964.1c6ec257ea31fe08adfd5f72270032c58fb9eea0c8a68409fb954152035a41ca.6PcGl1qAelTN8aq72lqgcYZw_sGKGunuXghGOUhkdVk
+ hash: v1.k794b7964.c2b2dfac0dcf77fefa7bfcd55ad0022ee6a8f461f3c03d74448bab270ba7dd7b.DgmRBGi8wUsgVlPWENMllouOKXKtCawcdVWsU6Srd5U
scenes-app-experiments--experiment-with-multiple-metrics--light:
- hash: v1.k794b7964.6b5d896de6354dd8b5f191d4fbb2b87d167a3f3cc93f62c62284a782ec430bc6.7-LXuxxEUV_5ZlG5tUbyAmm4K2yP4rMwOiTDpAZkeTU
+ hash: v1.k794b7964.bd0c9df6ac5649eb99e8fe4b2c4a3ecd5967e86390934fbcaa90d6a98298e62a.CaaUkkkx-ak0cHKyZjYvANiqHcEeRLVUfiYWbGBEGa0
scenes-app-experiments--experiment-with-multiple-metrics-reordered--dark:
- hash: v1.k794b7964.0aa35284172e036a686089dc570689700b128d0f606e100d0c8ae087cb712e93.aN_1UIRF5SlRbAPWl6PYs5zLUdQVQRB4CoKp5FXX0ww
+ hash: v1.k794b7964.bf78a31867b98f4d38802a891ff6806070a45a51f2cab47681dd0dbfd2c520bd.wua8m3TWJX-zNOg4_kEde_UoBl7SZ3qdtnPkIM_yTxk
scenes-app-experiments--experiment-with-multiple-metrics-reordered--light:
- hash: v1.k794b7964.0ca14c6de1840b81c5389bd9b544ec815c845027a909e002090ead17d6d82b45.aqoPvTeNXn14TqXpZO-ZxNgWLw4tzzHYaHrTib8pHbM
+ hash: v1.k794b7964.8a4ba7f6b3940090235189423acb5815d3950a5e7e6c04020d1eef1f90ac74f6.F5ZLNpXgvKczk05Mkzg_cN_KZgfsEZ-fs0Gnv9pYo0M
scenes-app-experiments--experiment-with-ratio-metric--dark:
hash: v1.k794b7964.f7d50e2c065ff1b918c01fae91091f1e6e7ac248a375529d04316a6e5a6ec521.0EZJzXkY1jfkXaoPiKnv3j5o8CNzqI0VBR8Wxs9JC0Y
scenes-app-experiments--experiment-with-ratio-metric--light:
diff --git a/frontend/src/scenes/experiments/MetricsView/MetricsReorderModal.tsx b/frontend/src/scenes/experiments/MetricsView/MetricsReorderModal.tsx
deleted file mode 100644
index 512f108c0e02..000000000000
--- a/frontend/src/scenes/experiments/MetricsView/MetricsReorderModal.tsx
+++ /dev/null
@@ -1,272 +0,0 @@
-import { DndContext, DragEndEvent } from '@dnd-kit/core'
-import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'
-import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'
-import { CSS } from '@dnd-kit/utilities'
-import clsx from 'clsx'
-import { useActions, useValues } from 'kea'
-import { useEffect, useState } from 'react'
-
-import { IconDrag } from '@posthog/icons'
-import { LemonBadge, LemonButton, LemonModal, LemonTag } from '@posthog/lemon-ui'
-
-import { ExperimentMetric } from '~/queries/schema/schema-general'
-
-import { experimentLogic } from '../experimentLogic'
-import { modalsLogic } from '../modalsLogic'
-import { MetricTitle } from './shared/MetricTitle'
-import { getMetricTag } from './shared/utils'
-
-const MetricItem = ({
- metric,
- order,
- isRemoved,
- isMoved,
- canLeave,
- moveTargetLabel,
- onRemove,
- onMove,
- onRestore,
-}: {
- metric: ExperimentMetric & { sharedMetricId?: number; isSharedMetric?: boolean }
- order: number
- isRemoved: boolean
- isMoved: boolean
- canLeave: boolean
- moveTargetLabel: string
- onRemove: () => void
- onMove: () => void
- onRestore: () => void
-}): JSX.Element => {
- const uuid = metric.uuid || (metric as any).query?.uuid
- const isStaged = isRemoved || isMoved
- const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
- id: uuid,
- disabled: isStaged,
- })
-
- return (
- <div
- ref={setNodeRef}
- className={clsx(
- 'relative flex items-center gap-2 p-3 border rounded bg-bg-light',
- isDragging && 'z-[999999]'
- )}
- style={{
- transform: CSS.Transform.toString(transform),
- transition,
- }}
- {...attributes}
- >
- <div
- className={clsx('flex-shrink-0', isStaged ? 'cursor-default' : 'cursor-move')}
- {...(isStaged ? {} : listeners)}
- >
- <IconDrag className={clsx('text-lg', isStaged ? 'text-muted' : 'text-orange-500')} />
- </div>
- <LemonBadge.Number count={order + 1} maxDigits={3} status="muted" />
- <div
- className={clsx(
- 'flex-1 min-w-0 flex flex-col gap-1',
- isRemoved && 'line-through opacity-50',
- isMoved && 'opacity-50'
- )}
- >
- <div className="font-semibold">
- <MetricTitle metric={metric} />
- </div>
- <div className="flex gap-1">
- <LemonTag type="muted" size="small">
- {getMetricTag(metric)}
- </LemonTag>
- {metric.isSharedMetric && (
- <LemonTag type="option" size="small">
- Shared
- </LemonTag>
- )}
- </div>
- </div>
- {isStaged ? (
- <>
- {isMoved && (
- <LemonTag type="highlight" size="small">
- Moving to {moveTargetLabel}
- </LemonTag>
- )}
- <LemonButton size="small" type="secondary" onClick={onRestore}>
- Restore
- </LemonButton>
- </>
- ) : (
- <>
- <LemonButton
- size="small"
- type="secondary"
- onClick={onMove}
- disabledReason={!canLeave ? 'At least one metric is required' : undefined}
- >
- Move to {moveTargetLabel}
- </LemonButton>
- <LemonButton
- size="small"
- status="danger"
- type="secondary"
- onClick={onRemove}
- disabledReason={!canLeave ? 'At least one metric is required' : undefined}
- >
- Remove
- </LemonButton>
- </>
- )}
- </div>
- )
-}
-
-export function MetricsReorderModal({ isSecondary = false }: { isSecondary?: boolean }): JSX.Element {
- const { isPrimaryMetricsReorderModalOpen, isSecondaryMetricsReorderModalOpen } = useValues(modalsLogic)
- const { closePrimaryMetricsReorderModal, closeSecondaryMetricsReorderModal } = useActions(modalsLogic)
-
- const isOpen = isSecondary ? isSecondaryMetricsReorderModalOpen : isPrimaryMetricsReorderModalOpen
- const closeModal = isSecondary ? closeSecondaryMetricsReorderModal : closePrimaryMetricsReorderModal
-
- const { experiment, getOrderedMetricsWithResults, experimentUpdateLoading } = useValues(experimentLogic)
- const { saveMetricsReorder } = useActions(experimentLogic)
-
- const moveTargetLabel = isSecondary ? 'primary' : 'secondary'
-
- const [orderedUuids, setOrderedUuids] = useState<string[]>([])
- const [removedUuids, setRemovedUuids] = useState<Set<string>>(new Set())
- const [movedUuids, setMovedUuids] = useState<Set<string>>(new Set())
-
- useEffect(() => {
- if (isOpen && experiment) {
- const currentOrder = isSecondary
- ? (experiment.secondary_metrics_ordered_uuids ?? [])
- : (experiment.primary_metrics_ordered_uuids ?? [])
- setOrderedUuids([...currentOrder])
- } else {
- setOrderedUuids([])
- }
- setRemovedUuids(new Set())
- setMovedUuids(new Set())
- }, [
- isOpen,
- isSecondary,
- experiment.primary_metrics_ordered_uuids,
- experiment.secondary_metrics_ordered_uuids,
- experiment,
- ])
-
- const displayMetrics = (() => {
- if (!experiment || orderedUuids.length === 0) {
- return []
- }
-
- const metricsWithResults = getOrderedMetricsWithResults(isSecondary)
- const allMetrics = metricsWithResults.map(({ metric }: { metric: any }) => metric)
-
- const metricsMap = new Map()
- allMetrics.forEach((metric: any) => {
- const uuid = metric.uuid || metric.query?.uuid
- if (uuid) {
- metricsMap.set(uuid, metric)
- }
- })
-
- return orderedUuids.map((uuid) => metricsMap.get(uuid)).filter(Boolean)
- })()
-
- // Moved metrics leave the section just like removed ones, so both count
- // against the at-least-one-primary-metric requirement.
- const activeCount = orderedUuids.length - removedUuids.size - movedUuids.size
- const canLeaveMore = isSecondary || activeCount > 1
-
- const handleDragEnd = ({ active, over }: DragEndEvent): void => {
- if (active.id && over && active.id !== over.id) {
- const from = orderedUuids.indexOf(active.id as string)
- const to = orderedUuids.indexOf(over.id as string)
-
- if (from !== -1 && to !== -1) {
- const newOrder = arrayMove(orderedUuids, from, to)
- setOrderedUuids(newOrder)
- }
- }
- }
-
- const handleSave = (): void => {
- // The listener persists everything in one update, realigns results, and
- // closes the modal on completion.
- saveMetricsReorder(isSecondary, orderedUuids, Array.from(removedUuids), Array.from(movedUuids))
- }
-
- return (
- <LemonModal
- onClose={closeModal}
- isOpen={isOpen}
- width={600}
- title={`Reorder ${isSecondary ? 'secondary' : 'primary'} metrics`}
- description={
- <p>
- Drag and drop to reorder, move metrics to the {moveTargetLabel} section, or remove metrics you no
- longer need.
- </p>
- }
- footer={
- <>
- <LemonButton type="secondary" onClick={closeModal}>
- Cancel
- </LemonButton>
- <LemonButton type="primary" onClick={handleSave} loading={experimentUpdateLoading}>
- Save
- </LemonButton>
- </>
- }
- >
- <div className="flex flex-col gap-2">
- <DndContext modifiers={[restrictToVerticalAxis, restrictToParentElement]} onDragEnd={handleDragEnd}>
- <SortableContext items={orderedUuids} strategy={verticalListSortingStrategy}>
- {isOpen && displayMetrics.length === 0 && (
- <div className="p-4 text-center text-muted">
- <p>No metrics available for reordering</p>
- </div>
- )}
- {displayMetrics.map((metric, index) => {
- const uuid = metric.uuid || (metric as any).query?.uuid
- const isRemoved = removedUuids.has(uuid)
- const isMoved = movedUuids.has(uuid)
- const effectiveIndex =
- displayMetrics.slice(0, index + 1).filter((m) => {
- const id = m.uuid || (m as any).query?.uuid
- return !removedUuids.has(id) && !movedUuids.has(id)
- }).length - 1
- return (
- <MetricItem
- key={uuid}
- metric={metric}
- order={isRemoved || isMoved ? index : effectiveIndex}
- isRemoved={isRemoved}
- isMoved={isMoved}
- canLeave={canLeaveMore}
- moveTargetLabel={moveTargetLabel}
- onRemove={() => setRemovedUuids((prev) => new Set([...prev, uuid]))}
- onMove={() => setMovedUuids((prev) => new Set([...prev, uuid]))}
- onRestore={() => {
- setRemovedUuids((prev) => {
- const next = new Set(prev)
- next.delete(uuid)
- return next
- })
- setMovedUuids((prev) => {
- const next = new Set(prev)
- next.delete(uuid)
- return next
- })
- }}
- />
- )
- })}
- </SortableContext>
- </DndContext>
- </div>
- </LemonModal>
- )
-}
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
index e465a8e83327..4e684fb80698 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
@@ -81,7 +81,7 @@ interface BreakdownErrorStateProps {
function BreakdownErrorState({ metric, isAlternatingRow, onRemoveBreakdown }: BreakdownErrorStateProps): JSX.Element {
return (
- <tr data-breakdown-row className="hover:bg-bg-hover group [&:last-child>td]:border-b-0">
+ <tr data-breakdown-row className="hover:bg-bg-hover group">
<td colSpan={7} className={`p-0 border-t border-b ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}>
<div className="p-1">
<div className="flex items-center gap-2">
@@ -181,7 +181,7 @@ function CollapsibleBreakdownSection({
}
return (
- <tr ref={mainTableRef} data-breakdown-row className="hover:bg-bg-hover group [&:last-child>td]:border-b-0">
+ <tr ref={mainTableRef} data-breakdown-row className="hover:bg-bg-hover group">
<td colSpan={7} className={`p-0 border-t border-b ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}>
<LemonCollapse
multiple={false}
@@ -533,6 +533,7 @@ interface MetricRowGroupProps {
isSecondary: boolean
isLastMetric: boolean
isAlternatingRow: boolean
+ dragHandle?: JSX.Element | null
onDuplicateMetric?: () => void
onDuplicateAsSingleUseMetric?: () => void
onDeleteMetric?: () => void
@@ -555,6 +556,7 @@ export function MetricRowGroup({
isSecondary,
isLastMetric,
isAlternatingRow,
+ dragHandle,
onDuplicateMetric,
onDuplicateAsSingleUseMetric,
onDeleteMetric,
@@ -779,7 +781,7 @@ export function MetricRowGroup({
return (
<>
- <tr className="hover:bg-bg-hover group [&:last-child>td]:border-b-0" style={FIXED_HEIGHT_STYLE}>
+ <tr className="hover:bg-bg-hover group" style={FIXED_HEIGHT_STYLE}>
{/* Metric column: real header spanning every variant row, stays interactive while loading */}
<td
className={`w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${
@@ -789,6 +791,7 @@ export function MetricRowGroup({
style={getScaledHeightStyle(skeletonVariantKeys.length)}
>
<MetricHeader
+ dragHandle={dragHandle}
displayOrder={displayOrder}
metric={metric}
metricType={metricType}
@@ -827,11 +830,7 @@ export function MetricRowGroup({
</tr>
{skeletonVariantKeys.slice(1).map((variantKey, index) => (
- <tr
- key={variantKey}
- className="hover:bg-bg-hover group [&:last-child>td]:border-b-0"
- style={FIXED_HEIGHT_STYLE}
- >
+ <tr key={variantKey} className="hover:bg-bg-hover group" style={FIXED_HEIGHT_STYLE}>
<SkeletonResultCells
variantKey={variantKey}
className={clsx(bg, index === skeletonVariantKeys.length - 2 && 'border-b')}
@@ -849,7 +848,7 @@ export function MetricRowGroup({
return (
<>
- <tr className="hover:bg-bg-hover group [&:last-child>td]:border-b-0" style={noResultStateStyle}>
+ <tr className="hover:bg-bg-hover group" style={noResultStateStyle}>
{/* Metric column - always visible */}
<td
className={`w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${
@@ -858,6 +857,7 @@ export function MetricRowGroup({
style={noResultStateStyle}
>
<MetricHeader
+ dragHandle={dragHandle}
displayOrder={displayOrder}
metric={metric}
metricType={metricType}
@@ -956,7 +956,7 @@ export function MetricRowGroup({
)}
{/* Baseline row */}
- <tr className="hover:bg-bg-hover group [&:last-child>td]:border-b-0" style={FIXED_HEIGHT_STYLE}>
+ <tr className="hover:bg-bg-hover group" style={FIXED_HEIGHT_STYLE}>
{/* Metric column - with rowspan */}
<td
className={`w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${!isLastMetric ? 'border-b' : ''} ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
@@ -964,6 +964,7 @@ export function MetricRowGroup({
style={totalRowsHeightStyle}
>
<MetricHeader
+ dragHandle={dragHandle}
displayOrder={displayOrder}
metric={metric}
metricType={metricType}
@@ -1094,7 +1095,7 @@ export function MetricRowGroup({
return (
<tr
key={`${metric.uuid}-${variant.key}`}
- className="hover:bg-bg-hover group [&:last-child>td]:border-b-0"
+ className="hover:bg-bg-hover group"
style={FIXED_HEIGHT_STYLE}
onMouseEnter={(e) => handleTooltipMouseEnter(e, variant)}
onMouseLeave={handleTooltipMouseLeave}
diff --git a/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx b/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx
index 92f698d4df94..db3713e09ca3 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx
@@ -1,7 +1,7 @@
-import { useActions, useValues } from 'kea'
+import { useValues } from 'kea'
-import { IconInfo, IconList } from '@posthog/icons'
-import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+import { IconInfo } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { IconAreaChart } from 'lib/lemon-ui/icons'
@@ -13,8 +13,6 @@ import { experimentLogic } from '~/scenes/experiments/experimentLogic'
import { experimentMetricsLogic } from '~/scenes/experiments/experimentMetricsLogic'
import { AddMetricButton } from '~/scenes/experiments/Metrics/AddMetricButton'
import { METRIC_CONTEXTS } from '~/scenes/experiments/Metrics/experimentMetricModalLogic'
-import { MetricsReorderModal } from '~/scenes/experiments/MetricsView/MetricsReorderModal'
-import { modalsLogic } from '~/scenes/experiments/modalsLogic'
import { getExperimentVariants, isSavedExperiment, metricResults } from '~/scenes/experiments/utils'
import { Experiment } from '~/types'
@@ -50,8 +48,6 @@ function MetricsContent({ experiment, isSecondary }: { experiment: Experiment; i
const { featureFlags } = useValues(featureFlagLogic)
const recalculationFlow = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]
- const { openPrimaryMetricsReorderModal, openSecondaryMetricsReorderModal } = useActions(modalsLogic)
-
const type = isSecondary ? 'secondary' : 'primary'
const metricsWithResults = recalculationFlow
@@ -76,12 +72,6 @@ function MetricsContent({ experiment, isSecondary }: { experiment: Experiment; i
return (
<div className="mb-4 -mt-2" data-attr="experiment-creation-goal-metric">
- {experiment?.id && (
- <>
- <MetricsReorderModal isSecondary={false} />
- <MetricsReorderModal isSecondary={true} />
- </>
- )}
<div className="flex">
<div className="w-1/2 pt-5">
<div className="inline-flex items-center deprecated-space-x-2 mb-0">
@@ -105,17 +95,6 @@ function MetricsContent({ experiment, isSecondary }: { experiment: Experiment; i
<AddMetricButton
metricContext={isSecondary ? METRIC_CONTEXTS.secondary : METRIC_CONTEXTS.primary}
/>
- <LemonButton
- type="secondary"
- size="xsmall"
- onClick={() =>
- isSecondary
- ? openSecondaryMetricsReorderModal()
- : openPrimaryMetricsReorderModal()
- }
- icon={<IconList />}
- tooltip="Reorder, move or remove metrics"
- />
</div>
)}
</div>
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
index 933add0b84f6..12940fe30740 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
@@ -1,5 +1,9 @@
+import { DndContext, DragEndEvent, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
+import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'
+import { SortableContext, arrayMove, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { useActions, useValues } from 'kea'
+import { verticalSortableListCollisionDetection } from 'lib/sortable'
import { experimentsConfigLogic } from 'scenes/settings/environment/experimentsConfigLogic'
import {
@@ -14,11 +18,14 @@ import { experimentLogic } from '../../experimentLogic'
import { experimentMetricsLogic } from '../../experimentMetricsLogic'
import { isLaunched } from '../../experimentsLogic'
import { resolveSequentialEnabled } from '../../ExperimentView/sequential'
-import { type ExperimentVariantResult, getVariantInterval } from '../shared/utils'
+import { type ExperimentVariantResult, getDefaultMetricTitle, getVariantInterval } from '../shared/utils'
import { MAX_AXIS_RANGE } from './constants'
import { MetricRowGroup } from './MetricRowGroup'
+import { SortableMetricRowGroup } from './SortableMetricRowGroup'
import { TableHeader } from './TableHeader'
+const metricName = (metric: ExperimentMetric): string => metric.name || getDefaultMetricTitle(metric)
+
/**
* True when any metric in this section is still being recalculated. Curried by the section's metrics so
* each table judges only its own; exposures loading is the caller's concern.
@@ -63,8 +70,53 @@ export function MetricsTable({
removeMetricBreakdown,
removeMetric,
removeSharedMetricFromExperiment,
+ reorderMetrics,
} = useActions(experimentLogic)
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+ )
+
+ const orderedUuids = metrics.map(({ uuid }) => uuid).filter(Boolean) as string[]
+ // Ordering is keyed by uuid, so a metric without one can't take part.
+ const dragDisabled = orderedUuids.length !== metrics.length || metrics.length < 2
+
+ const handleDragEnd = ({ active, over }: DragEndEvent): void => {
+ if (!over || active.id === over.id) {
+ return
+ }
+
+ const from = orderedUuids.indexOf(active.id as string)
+ const to = orderedUuids.indexOf(over.id as string)
+
+ if (from === -1 || to === -1) {
+ return
+ }
+
+ reorderMetrics(isSecondary, arrayMove(orderedUuids, from, to))
+ }
+
+ const nameByUuid = new Map(metrics.map((metric) => [metric.uuid, metricName(metric)]))
+ const announcements = {
+ onDragStart: ({ active }: { active: { id: string | number } }) =>
+ `Picked up ${nameByUuid.get(String(active.id))}.`,
+ onDragOver: ({ active, over }: { active: { id: string | number }; over: { id: string | number } | null }) =>
+ over
+ ? `${nameByUuid.get(String(active.id))} moved to position ${
+ orderedUuids.indexOf(String(over.id)) + 1
+ } of ${orderedUuids.length}.`
+ : undefined,
+ onDragEnd: ({ active, over }: { active: { id: string | number }; over: { id: string | number } | null }) =>
+ over
+ ? `${nameByUuid.get(String(active.id))} dropped at position ${
+ orderedUuids.indexOf(String(over.id)) + 1
+ } of ${orderedUuids.length}.`
+ : `${nameByUuid.get(String(active.id))} returned to its original position.`,
+ onDragCancel: ({ active }: { active: { id: string | number } }) =>
+ `Reordering cancelled. ${nameByUuid.get(String(active.id))} returned to its original position.`,
+ }
+
// Calculate shared axisRange across all metrics
let hasBreakdowns = false
const allIntervalValues = results.flatMap((result: NewExperimentQueryResponse) => {
@@ -110,111 +162,134 @@ export function MetricsTable({
sectionHasRecalculatingMetric(metrics)(recalculatingMetricUuids) || hasColdMetric || exposuresLoading
return (
- <div className="w-full overflow-x-auto rounded-md border">
- <table className="w-full border-collapse text-sm">
- <colgroup>
- <col className="min-w-[200px]" />
- <col />
- <col />
- <col />
- <col />
- <col />
- <col className="min-w-[400px]" />
- </colgroup>
- <TableHeader
- axisRange={axisRange}
- statsMethod={experiment.stats_config?.method || ExperimentStatsMethod.Bayesian}
- sequentialTestingEnabled={sequentialTestingEnabled}
- loading={sectionLoading}
- />
- <tbody>
- {metrics.map((metric, index) => {
- const result = results[index]
- const error = errors[index]
- const metricIndex = metricIndexes[index]
-
- const isLoading = !result && !error && isLaunched(experiment)
-
- return (
- <MetricRowGroup
- key={metric.uuid || index}
- metric={metric}
- result={result}
- experiment={experiment}
- metricType={getInsightType(metric)}
- metricIndex={metricIndex}
- displayOrder={index}
- axisRange={axisRange}
- isSecondary={isSecondary}
- isLastMetric={index === metrics.length - 1}
- isAlternatingRow={index % 2 === 1}
- onDuplicateMetric={() => {
- if (!metric.uuid || !experiment) {
- return
- }
-
- const newUuid = crypto.randomUUID()
- duplicateMetric({ uuid: metric.uuid, isSecondary, newUuid })
- updateExperimentMetrics()
- }}
- onDuplicateAsSingleUseMetric={() => {
- if (!metric.isSharedMetric || !metric.sharedMetricId || !experiment) {
- return
- }
-
- const newUuid = crypto.randomUUID()
- duplicateSharedMetricAsInlineMetric({
- sharedMetricId: metric.sharedMetricId,
- isSecondary,
- newUuid,
- })
- updateExperimentMetrics()
- }}
- onDeleteMetric={() => {
- if (metric.isSharedMetric && metric.sharedMetricId) {
- removeSharedMetricFromExperiment(metric.sharedMetricId)
- return
- }
- if (!metric.uuid) {
- return
- }
- removeMetric(metric.uuid, isSecondary ? 'secondary' : 'primary')
- }}
- onBreakdownChange={(breakdown) => {
- if (!metric.uuid) {
- return
- }
-
- updateMetricBreakdown(metric.uuid, breakdown)
- }}
- onRemoveBreakdown={(index) => {
- if (!metric.uuid) {
- return
- }
-
- /**
- * we pass the breakdown just for instrumentation purposes
- */
- const breakdown = metric.breakdownFilter?.breakdowns?.[index]
-
- /**
- * throw an error if the breakdown is not found
- */
- if (!breakdown) {
- throw new Error('Breakdown not found')
- }
-
- removeMetricBreakdown(metric.uuid, index, breakdown)
- }}
- error={error}
- isLoading={isLoading}
- exposuresLoading={exposuresLoading}
- showDetailsModal={showDetailsModal}
- />
- )
- })}
- </tbody>
- </table>
- </div>
+ <DndContext
+ sensors={sensors}
+ // Metric groups vary from one row to many, which is exactly where closestCenter misjudges.
+ collisionDetection={verticalSortableListCollisionDetection}
+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}
+ // The wrapper is overflow-x-auto, which makes it a scroll container on both axes. Left to
+ // auto-scroll it chases the dragged group past its own bounds, growing scrollHeight until
+ // the rows scroll out of view. The page still scrolls normally.
+ autoScroll={{ canScroll: (element) => element === document.scrollingElement }}
+ accessibility={{ announcements }}
+ onDragEnd={handleDragEnd}
+ >
+ <div className="w-full overflow-x-auto rounded-md border">
+ <table className="w-full border-collapse text-sm">
+ <colgroup>
+ <col className="min-w-[200px]" />
+ <col />
+ <col />
+ <col />
+ <col />
+ <col />
+ <col className="min-w-[400px]" />
+ </colgroup>
+ <TableHeader
+ axisRange={axisRange}
+ statsMethod={experiment.stats_config?.method || ExperimentStatsMethod.Bayesian}
+ sequentialTestingEnabled={sequentialTestingEnabled}
+ loading={sectionLoading}
+ />
+ <SortableContext items={orderedUuids} strategy={verticalListSortingStrategy}>
+ {metrics.map((metric, index) => {
+ const result = results[index]
+ const error = errors[index]
+ const metricIndex = metricIndexes[index]
+
+ const isLoading = !result && !error && isLaunched(experiment)
+
+ return (
+ <SortableMetricRowGroup
+ key={metric.uuid || index}
+ uuid={metric.uuid || String(index)}
+ metricName={metricName(metric)}
+ disabled={dragDisabled}
+ isLastMetric={index === metrics.length - 1}
+ >
+ {(dragHandle) => (
+ <MetricRowGroup
+ metric={metric}
+ dragHandle={dragHandle}
+ result={result}
+ experiment={experiment}
+ metricType={getInsightType(metric)}
+ metricIndex={metricIndex}
+ displayOrder={index}
+ axisRange={axisRange}
+ isSecondary={isSecondary}
+ isLastMetric={index === metrics.length - 1}
+ isAlternatingRow={index % 2 === 1}
+ onDuplicateMetric={() => {
+ if (!metric.uuid || !experiment) {
+ return
+ }
+
+ const newUuid = crypto.randomUUID()
+ duplicateMetric({ uuid: metric.uuid, isSecondary, newUuid })
+ updateExperimentMetrics()
+ }}
+ onDuplicateAsSingleUseMetric={() => {
+ if (!metric.isSharedMetric || !metric.sharedMetricId || !experiment) {
+ return
+ }
+
+ const newUuid = crypto.randomUUID()
+ duplicateSharedMetricAsInlineMetric({
+ sharedMetricId: metric.sharedMetricId,
+ isSecondary,
+ newUuid,
+ })
+ updateExperimentMetrics()
+ }}
+ onDeleteMetric={() => {
+ if (metric.isSharedMetric && metric.sharedMetricId) {
+ removeSharedMetricFromExperiment(metric.sharedMetricId)
+ return
+ }
+ if (!metric.uuid) {
+ return
+ }
+ removeMetric(metric.uuid, isSecondary ? 'secondary' : 'primary')
+ }}
+ onBreakdownChange={(breakdown) => {
+ if (!metric.uuid) {
+ return
+ }
+
+ updateMetricBreakdown(metric.uuid, breakdown)
+ }}
+ onRemoveBreakdown={(index) => {
+ if (!metric.uuid) {
+ return
+ }
+
+ /**
+ * we pass the breakdown just for instrumentation purposes
+ */
+ const breakdown = metric.breakdownFilter?.breakdowns?.[index]
+
+ /**
+ * throw an error if the breakdown is not found
+ */
+ if (!breakdown) {
+ throw new Error('Breakdown not found')
+ }
+
+ removeMetricBreakdown(metric.uuid, index, breakdown)
+ }}
+ error={error}
+ isLoading={isLoading}
+ exposuresLoading={exposuresLoading}
+ showDetailsModal={showDetailsModal}
+ />
+ )}
+ </SortableMetricRowGroup>
+ )
+ })}
+ </SortableContext>
+ </table>
+ </div>
+ </DndContext>
)
}
diff --git a/frontend/src/scenes/experiments/MetricsView/new/SortableMetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/SortableMetricRowGroup.tsx
new file mode 100644
index 000000000000..2b035f2c38c8
--- /dev/null
+++ b/frontend/src/scenes/experiments/MetricsView/new/SortableMetricRowGroup.tsx
@@ -0,0 +1,86 @@
+import { DraggableSyntheticListeners } from '@dnd-kit/core'
+import { useSortable } from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
+import clsx from 'clsx'
+
+import { IconDrag } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+const MetricDragHandle = ({
+ listeners,
+ attributes,
+ setActivatorNodeRef,
+ metricName,
+}: {
+ listeners: DraggableSyntheticListeners | undefined
+ attributes: Record<string, any>
+ setActivatorNodeRef: (element: HTMLElement | null) => void
+ metricName: string
+}): JSX.Element => (
+ <Tooltip title="Drag to reorder metrics">
+ <button
+ type="button"
+ ref={setActivatorNodeRef}
+ className="touch-none cursor-grab active:cursor-grabbing text-muted hover:text-default transition-colors border-none bg-transparent p-0 flex-shrink-0"
+ aria-label={`Reorder ${metricName}`}
+ {...listeners}
+ {...attributes}
+ data-attr="experiment-metric-drag-handle"
+ >
+ <IconDrag className="text-base" />
+ </button>
+ </Tooltip>
+)
+
+/**
+ * A metric spans several `<tr>`s (baseline, one per variant, optional breakdown rows), so the
+ * sortable unit has to be a `<tbody>` — a table may hold many of them.
+ */
+export function SortableMetricRowGroup({
+ uuid,
+ metricName,
+ disabled,
+ isLastMetric,
+ children,
+}: {
+ uuid: string
+ metricName: string
+ disabled: boolean
+ isLastMetric: boolean
+ children: (dragHandle: JSX.Element | null) => JSX.Element
+}): JSX.Element {
+ const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({
+ id: uuid,
+ disabled,
+ })
+
+ return (
+ <tbody
+ ref={disabled ? undefined : setNodeRef}
+ style={{
+ transform: CSS.Transform.toString(transform),
+ transition: isDragging ? 'none' : transition,
+ position: isDragging ? 'relative' : undefined,
+ // Stays under the sticky header, which sits at z-10.
+ zIndex: isDragging ? 2 : undefined,
+ // The dragged group overlaps its neighbours, so the shadow makes it read as
+ // lifted above them rather than merged into them.
+ boxShadow: isDragging ? 'var(--shadow-elevation-3000)' : undefined,
+ }}
+ // Scoped here rather than on the rows: with one tbody per metric, a row-level
+ // `:last-child` would strip the border between every metric, not just the final one.
+ className={clsx(isLastMetric && '[&>tr:last-child>td]:border-b-0')}
+ >
+ {children(
+ disabled ? null : (
+ <MetricDragHandle
+ listeners={listeners}
+ attributes={attributes}
+ setActivatorNodeRef={setActivatorNodeRef}
+ metricName={metricName}
+ />
+ )
+ )}
+ </tbody>
+ )
+}
diff --git a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx
index eab4f5387a4c..6ae1344829e6 100644
--- a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx
@@ -1,13 +1,14 @@
import { useActions, useValues } from 'kea'
import { useState } from 'react'
-import { IconCopy, IconEllipsis, IconPencil, IconStack, IconTarget, IconTrash } from '@posthog/icons'
+import { IconCopy, IconEllipsis, IconPencil, IconSort, IconStack, IconTarget, IconTrash } from '@posthog/icons'
import { LemonButton, LemonDialog, LemonDropdown, LemonMenu, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { Spinner } from 'lib/lemon-ui/Spinner'
+import { experimentLogic } from 'scenes/experiments/experimentLogic'
import { experimentMetricsLogic } from 'scenes/experiments/experimentMetricsLogic'
import { isMetricThresholdCueVisible } from 'scenes/experiments/ExperimentMetricThreshold'
import {
@@ -80,6 +81,7 @@ const AddBreakdownMenuItem = ({
}
export const MetricHeader = ({
+ dragHandle,
displayOrder,
metric,
metricType,
@@ -91,6 +93,7 @@ export const MetricHeader = ({
onDeleteMetricClick,
readOnly,
}: {
+ dragHandle?: JSX.Element | null
displayOrder?: number
metric: ExperimentMetric
metricType: any
@@ -112,6 +115,7 @@ export const MetricHeader = ({
openSecondarySharedMetricModal,
} = useActions(modalsLogic)
+ const { moveMetricsBetweenSections } = useActions(experimentLogic)
const { openExperimentMetricModal } = useActions(experimentMetricModalLogic)
const { openSharedMetricDetailModal } = useActions(sharedMetricDetailsModalLogic)
@@ -216,17 +220,36 @@ export const MetricHeader = ({
const canAddBreakdown = (metric.breakdownFilter?.breakdowns || []).length < MAX_BREAKDOWNS
+ const metricUuid = metric.uuid
+ const sectionUuids =
+ (isPrimaryMetric ? experiment.primary_metrics_ordered_uuids : experiment.secondary_metrics_ordered_uuids) ?? []
+ // An experiment still has to measure something, so the last primary metric can't leave.
+ const isLastPrimaryMetric = isPrimaryMetric && sectionUuids.length <= 1
+
+ const handleMoveSection = (): void => {
+ // The menu item only renders when the metric has a uuid.
+ if (!metricUuid) {
+ return
+ }
+ // Flips shared-metric links, prunes the ordering arrays and realigns existing
+ // results in one update.
+ moveMetricsBetweenSections(isPrimaryMetric === false, sectionUuids, [], [metricUuid])
+ }
+
const recalculationEnabled = useFeatureFlag('EXPERIMENTS_METRICS_RECALCULATION')
const { isMetricRecalculating, metricRetries } = useValues(experimentMetricsLogic({ experiment }))
const showRecalculatingTag = recalculationEnabled && isMetricRecalculating(metric.uuid)
const metricRetry = recalculationEnabled && metric.uuid ? metricRetries[metric.uuid] : undefined
return (
- <div className="text-xs font-semibold flex flex-col justify-between h-full">
- <div className="deprecated-space-y-1">
+ // The handle and the order number are their own columns, so the title and the tags below it
+ // share one left edge instead of the tags starting back at the cell edge.
+ <div className="text-xs font-semibold flex items-start gap-1">
+ {dragHandle}
+ {displayOrder !== undefined && <span className="flex-shrink-0">{displayOrder + 1}.</span>}
+ <div className="flex flex-col flex-1 min-w-0 deprecated-space-y-1">
<div className="flex items-start justify-between gap-2 min-w-0">
<div className="text-xs font-semibold flex items-start min-w-0 flex-1">
- {displayOrder !== undefined && <span className="mr-1 flex-shrink-0">{displayOrder + 1}.</span>}
<div className="min-w-0 flex-1">
<MetricTitle metric={metric} metricType={metricType} />
</div>
@@ -270,6 +293,19 @@ export const MetricHeader = ({
handleDuplicate()
},
},
+ !!metricUuid && {
+ label: isPrimaryMetric
+ ? 'Make secondary metric'
+ : 'Make primary metric',
+ icon: <IconSort />,
+ disabledReason: isLastPrimaryMetric
+ ? 'An experiment needs at least one primary metric'
+ : undefined,
+ onClick: () => {
+ closeMenu()
+ handleMoveSection()
+ },
+ },
].filter(Boolean) as any,
},
onDeleteMetricClick && {
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 5db782b0fb28..939d0a699a7c 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -605,7 +605,7 @@ describe('experimentLogic', () => {
expect(logic.values.experiment.description).toEqual('stale write')
})
})
- describe('saveMetricsReorder', () => {
+ describe('moveMetricsBetweenSections', () => {
const primaryMetric = {
kind: 'ExperimentMetric',
uuid: 'primary-metric-uuid',
@@ -649,35 +649,6 @@ describe('experimentLogic', () => {
api.update.mockClear()
})
- it('persists a pure reorder without touching metric arrays or results', async () => {
- const testExperiment = {
- ...experiment,
- saved_metrics: [],
- metrics: [primaryMetric, otherPrimaryMetric],
- metrics_secondary: [],
- primary_metrics_ordered_uuids: ['primary-metric-uuid', 'other-primary-uuid'],
- } as unknown as Experiment
-
- logic.actions.setExperiment(testExperiment)
- logic.actions.setPrimaryMetricsResults([primaryMetricResult, otherPrimaryMetricResult])
- api.update.mockResolvedValue({
- ...testExperiment,
- primary_metrics_ordered_uuids: ['other-primary-uuid', 'primary-metric-uuid'],
- })
-
- await expectLogic(logic, () => {
- logic.actions.saveMetricsReorder(false, ['other-primary-uuid', 'primary-metric-uuid'], [], [])
- })
- .toFinishAllListeners()
- .toNotHaveDispatchedActions(['refreshExperimentResults', 'loadPrimaryMetricsResults'])
-
- expect(api.update).toHaveBeenCalledWith(expect.stringContaining('/experiments/'), {
- primary_metrics_ordered_uuids: ['other-primary-uuid', 'primary-metric-uuid'],
- update_feature_flag_params: false,
- })
- expect(logic.values.primaryMetricsResults).toEqual([primaryMetricResult, otherPrimaryMetricResult])
- })
-
it('moves an inline metric to secondary and reuses existing results', async () => {
const testExperiment = {
...experiment,
@@ -698,7 +669,7 @@ describe('experimentLogic', () => {
})
await expectLogic(logic, () => {
- logic.actions.saveMetricsReorder(
+ logic.actions.moveMetricsBetweenSections(
false,
['primary-metric-uuid', 'other-primary-uuid'],
[],
@@ -756,7 +727,7 @@ describe('experimentLogic', () => {
})
await expectLogic(logic, () => {
- logic.actions.saveMetricsReorder(
+ logic.actions.moveMetricsBetweenSections(
false,
['primary-metric-uuid', 'other-primary-uuid', 'third-primary-uuid'],
['other-primary-uuid'],
@@ -815,7 +786,7 @@ describe('experimentLogic', () => {
})
await expectLogic(logic, () => {
- logic.actions.saveMetricsReorder(false, ['shared-metric-uuid'], [], ['shared-metric-uuid'])
+ logic.actions.moveMetricsBetweenSections(false, ['shared-metric-uuid'], [], ['shared-metric-uuid'])
})
.toFinishAllListeners()
.toNotHaveDispatchedActions(['refreshExperimentResults', 'loadExperiment'])
@@ -875,7 +846,7 @@ describe('experimentLogic', () => {
})
await expectLogic(logic, () => {
- logic.actions.saveMetricsReorder(true, ['secondary-metric-uuid'], [], ['secondary-metric-uuid'])
+ logic.actions.moveMetricsBetweenSections(true, ['secondary-metric-uuid'], [], ['secondary-metric-uuid'])
})
.toDispatchActions(['updateExperimentSuccess', 'retryPrimaryMetric'])
.toFinishAllListeners()
@@ -915,12 +886,83 @@ describe('experimentLogic', () => {
})
await expectLogic(logic, () => {
- logic.actions.saveMetricsReorder(false, ['primary-metric-uuid'], [], ['primary-metric-uuid'])
+ logic.actions.moveMetricsBetweenSections(false, ['primary-metric-uuid'], [], ['primary-metric-uuid'])
})
.toDispatchActions(['updateExperiment', 'refreshExperimentResults'])
.toFinishAllListeners()
})
})
+ describe('reorderMetrics', () => {
+ const testExperiment = {
+ ...experiment,
+ saved_metrics: [],
+ metrics: [
+ { kind: 'ExperimentMetric', uuid: 'first-uuid', name: 'First' },
+ { kind: 'ExperimentMetric', uuid: 'second-uuid', name: 'Second' },
+ ],
+ metrics_secondary: [],
+ primary_metrics_ordered_uuids: ['first-uuid', 'second-uuid'],
+ } as unknown as Experiment
+
+ beforeEach(() => {
+ jest.spyOn(api, 'update')
+ api.update.mockClear()
+ logic.actions.setExperiment(testExperiment)
+ })
+
+ it('applies the new order before the request lands, then persists only the ordering', async () => {
+ api.update.mockResolvedValue({
+ ...testExperiment,
+ primary_metrics_ordered_uuids: ['second-uuid', 'first-uuid'],
+ })
+
+ logic.actions.reorderMetrics(false, ['second-uuid', 'first-uuid'])
+
+ // Optimistic: the table must not wait on the round trip to show the new order.
+ expect(logic.values.experiment.primary_metrics_ordered_uuids).toEqual(['second-uuid', 'first-uuid'])
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledWith(
+ expect.stringContaining('/experiments/'),
+ expect.objectContaining({
+ primary_metrics_ordered_uuids: ['second-uuid', 'first-uuid'],
+ update_feature_flag_params: false,
+ })
+ )
+ })
+
+ it('rolls the order back when the update fails', async () => {
+ const errorMock = lemonToast.error as jest.Mock
+ errorMock.mockClear()
+ api.update.mockRejectedValue(new Error('nope'))
+
+ await expectLogic(logic, () => {
+ logic.actions.reorderMetrics(false, ['second-uuid', 'first-uuid'])
+ }).toFinishAllListeners()
+
+ expect(logic.values.experiment.primary_metrics_ordered_uuids).toEqual(['first-uuid', 'second-uuid'])
+ expect(errorMock).toHaveBeenCalledWith('Could not save the new metric order')
+ })
+
+ it('coalesces drops inside the debounce window into one request', async () => {
+ const errorMock = lemonToast.error as jest.Mock
+ errorMock.mockClear()
+ api.update.mockResolvedValue({
+ ...testExperiment,
+ primary_metrics_ordered_uuids: ['first-uuid', 'second-uuid'],
+ })
+
+ logic.actions.reorderMetrics(false, ['second-uuid', 'first-uuid'])
+ logic.actions.reorderMetrics(false, ['first-uuid', 'second-uuid'])
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledTimes(1)
+ // A superseded run must not report its cancellation as a save failure.
+ expect(errorMock).not.toHaveBeenCalled()
+ })
+ })
describe('breakdown management', () => {
it('should add breakdown to inline metric', () => {
const breakdown: Breakdown = { property: '$browser', type: 'event' }
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 5764e1b44ab8..8ffc61a0310f 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -772,18 +772,12 @@ export interface experimentLogicActions {
closePrimaryMetricModal: () => {
value: true
} // modalsLogic
- closePrimaryMetricsReorderModal: () => {
- value: true
- } // modalsLogic
closeResumeExperimentModal: () => {
value: true
} // modalsLogic
closeSecondaryMetricModal: () => {
value: true
} // modalsLogic
- closeSecondaryMetricsReorderModal: () => {
- value: true
- } // modalsLogic
openPrimaryMetricModal: (uuid: string) => {
uuid: string
} // modalsLogic
@@ -976,6 +970,17 @@ export interface experimentLogicActions {
refreshId: string
triggeredBy: ExperimentTriggeredBy
}
+ moveMetricsBetweenSections: (
+ isSecondary: boolean,
+ orderedUuids: string[],
+ removedUuids: string[],
+ movedUuids: string[]
+ ) => {
+ isSecondary: boolean
+ movedUuids: string[]
+ orderedUuids: string[]
+ removedUuids: string[]
+ }
pauseExperiment: () => {
value: true
}
@@ -1010,6 +1015,13 @@ export interface experimentLogicActions {
removeSharedMetricFromExperiment: (sharedMetricId: SharedMetric['id']) => {
sharedMetricId: number
}
+ reorderMetrics: (
+ isSecondary: boolean,
+ orderedUuids: string[]
+ ) => {
+ isSecondary: boolean
+ orderedUuids: string[]
+ }
resetAutoRefreshInterval: () => {
value: true
}
@@ -1031,17 +1043,6 @@ export interface experimentLogicActions {
retrySecondaryMetric: (index: number) => {
index: number
}
- saveMetricsReorder: (
- isSecondary: boolean,
- orderedUuids: string[],
- removedUuids: string[],
- movedUuids: string[]
- ) => {
- isSecondary: boolean
- movedUuids: string[]
- orderedUuids: string[]
- removedUuids: string[]
- }
setAutoRefresh: (
enabled: boolean,
interval: number
@@ -1499,8 +1500,6 @@ export const experimentLogic = kea<experimentLogicType>([
'closeResumeExperimentModal',
'closeFinishExperimentModal',
'openReleaseConditionsModal',
- 'closePrimaryMetricsReorderModal',
- 'closeSecondaryMetricsReorderModal',
],
],
})),
@@ -1699,7 +1698,8 @@ export const experimentLogic = kea<experimentLogicType>([
}),
// Semantic metric actions - each controls its own reload behavior
removeMetric: (uuid: string, context: 'primary' | 'secondary') => ({ uuid, context }),
- saveMetricsReorder: (
+ reorderMetrics: (isSecondary: boolean, orderedUuids: string[]) => ({ isSecondary, orderedUuids }),
+ moveMetricsBetweenSections: (
isSecondary: boolean,
orderedUuids: string[],
removedUuids: string[],
@@ -3328,24 +3328,51 @@ export const experimentLogic = kea<experimentLogicType>([
update_feature_flag_params: false,
})
},
- saveMetricsReorder: async ({ isSecondary, orderedUuids, removedUuids, movedUuids }) => {
- const removed = new Set(removedUuids)
- const moved = new Set(movedUuids)
+ reorderMetrics: async ({ isSecondary, orderedUuids }, breakpoint) => {
const orderingField = isSecondary ? 'secondary_metrics_ordered_uuids' : 'primary_metrics_ordered_uuids'
- const closeModal = isSecondary
- ? actions.closeSecondaryMetricsReorderModal
- : actions.closePrimaryMetricsReorderModal
+ const previousOrder = values.experiment[orderingField] ?? []
- // Pure reorder: only the ordering array changes, so the positional
- // results arrays stay aligned and nothing needs reloading.
- if (removed.size === 0 && moved.size === 0) {
- await asyncActions.updateExperiment({
- [orderingField]: orderedUuids,
- update_feature_flag_params: false,
+ // Only the ordering array changes, so the positional results arrays stay aligned
+ // to the metrics and nothing needs reloading.
+ actions.setExperiment({ [orderingField]: orderedUuids })
+
+ // Coalesce a flurry of drops into one request.
+ await breakpoint(300)
+
+ try {
+ // Deliberately not the updateExperiment loader: kea-loaders swallows the rejection
+ // into a Failure action, and a silent failure here would leave the table showing an
+ // order that never saved.
+ const response: Experiment = await api.update(
+ `api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,
+ {
+ ...toConcurrencyPayload(values.unmodifiedExperiment),
+ [orderingField]: orderedUuids,
+ update_feature_flag_params: false,
+ }
+ )
+ // A newer reorder may have started while this request was in flight.
+ breakpoint()
+ const responseWithMetricsOrdering = initializeMetricOrdering(response)
+ // Refreshing unmodifiedExperiment too, so a later edit-cancel doesn't revert the
+ // order the user just set.
+ actions.setUnmodifiedExperiment(structuredClone(responseWithMetricsOrdering))
+ actions.setExperiment(responseWithMetricsOrdering)
+ } catch (error) {
+ // Swallowing the breakpoint would roll a superseded reorder back over a newer one.
+ if (isBreakpoint(error as Error)) {
+ throw error
+ }
+ actions.setExperiment({
+ [orderingField]: values.unmodifiedExperiment?.[orderingField] ?? previousOrder,
})
- closeModal()
- return
+ lemonToast.error('Could not save the new metric order')
}
+ },
+ moveMetricsBetweenSections: async ({ isSecondary, orderedUuids, removedUuids, movedUuids }) => {
+ const removed = new Set(removedUuids)
+ const moved = new Set(movedUuids)
+ const orderingField = isSecondary ? 'secondary_metrics_ordered_uuids' : 'primary_metrics_ordered_uuids'
// Moves and removals don't change any metric's definition, so existing
// results stay valid — they only need realigning to the new positional
@@ -3405,7 +3432,6 @@ export const experimentLogic = kea<experimentLogicType>([
}
await asyncActions.updateExperiment(update)
- closeModal()
if (!canReuseResults) {
actions.refreshExperimentResults(true, 'config_change')
diff --git a/frontend/src/scenes/experiments/modalsLogic.ts b/frontend/src/scenes/experiments/modalsLogic.ts
index 0d9b1975b50d..d5d10c297c72 100644
--- a/frontend/src/scenes/experiments/modalsLogic.ts
+++ b/frontend/src/scenes/experiments/modalsLogic.ts
@@ -21,14 +21,12 @@ export interface modalsLogicValues {
isPauseExperimentModalOpen: boolean
isPrimaryMetricModalOpen: boolean
isPrimaryMetricSourceModalOpen: boolean
- isPrimaryMetricsReorderModalOpen: boolean
isPrimarySharedMetricModalOpen: boolean
isReleaseConditionsModalOpen: boolean
isResumeExperimentModalOpen: boolean
isRunningTimeConfigModalOpen: boolean
isSecondaryMetricModalOpen: boolean
isSecondaryMetricSourceModalOpen: boolean
- isSecondaryMetricsReorderModalOpen: boolean
isSecondarySharedMetricModalOpen: boolean
isStatsEngineModalOpen: boolean
isVariantDeltaTimeseriesModalOpen: boolean
@@ -69,9 +67,6 @@ export interface modalsLogicActions {
closePrimaryMetricSourceModal: () => {
value: true
}
- closePrimaryMetricsReorderModal: () => {
- value: true
- }
closePrimarySharedMetricModal: () => {
value: true
}
@@ -90,9 +85,6 @@ export interface modalsLogicActions {
closeSecondaryMetricSourceModal: () => {
value: true
}
- closeSecondaryMetricsReorderModal: () => {
- value: true
- }
closeSecondarySharedMetricModal: () => {
value: true
}
@@ -132,9 +124,6 @@ export interface modalsLogicActions {
openPrimaryMetricSourceModal: () => {
value: true
}
- openPrimaryMetricsReorderModal: () => {
- value: true
- }
openPrimarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => {
sharedMetricId: number | null
}
@@ -153,9 +142,6 @@ export interface modalsLogicActions {
openSecondaryMetricSourceModal: () => {
value: true
}
- openSecondaryMetricsReorderModal: () => {
- value: true
- }
openSecondarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => {
sharedMetricId: number | null
}
@@ -212,10 +198,6 @@ export const modalsLogic = kea<modalsLogicType>([
closeSecondarySharedMetricModal: true,
openVariantDeltaTimeseriesModal: true,
closeVariantDeltaTimeseriesModal: true,
- openPrimaryMetricsReorderModal: true,
- closePrimaryMetricsReorderModal: true,
- openSecondaryMetricsReorderModal: true,
- closeSecondaryMetricsReorderModal: true,
openRunningTimeConfigModal: true,
closeRunningTimeConfigModal: true,
}),
@@ -325,20 +307,6 @@ export const modalsLogic = kea<modalsLogicType>([
closeVariantDeltaTimeseriesModal: () => false,
},
],
- isPrimaryMetricsReorderModalOpen: [
- false,
- {
- openPrimaryMetricsReorderModal: () => true,
- closePrimaryMetricsReorderModal: () => false,
- },
- ],
- isSecondaryMetricsReorderModalOpen: [
- false,
- {
- openSecondaryMetricsReorderModal: () => true,
- closeSecondaryMetricsReorderModal: () => false,
- },
- ],
isDescriptionModalOpen: [
false,
{
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index f2ab7ddba5b2..b1ff5334ad8f 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -1058,13 +1058,22 @@ class ExperimentService:
return event_names, action_ids
@classmethod
- def validate_metric_action_ids(cls, metrics: list[dict] | None, team_id: int) -> None:
+ def validate_metric_action_ids(
+ cls, metrics: list[dict] | None, team_id: int, *, known_action_ids: set[int] | None = None
+ ) -> None:
"""Validate that all ActionsNode IDs reference existing, non-deleted actions for the team.
Actions are explicitly created entities with stable IDs, so a reference to a
nonexistent action is almost certainly a mistake, so we raise a hard validation error.
+
+ ``known_action_ids`` exempts ids already persisted on the experiment, so an
+ update is checked for what it introduces rather than for everything it
+ resends. Without it, deleting a referenced action makes every later metric
+ edit fail on the resent arrays. See ``update_experiment``.
"""
_, action_ids = cls._extract_entity_nodes(metrics)
+ if known_action_ids:
+ action_ids -= known_action_ids
if not action_ids:
return
@@ -1083,7 +1092,9 @@ class ExperimentService:
"Each ActionsNode must reference an existing action belonging to this project."
)
- def validate_metric_event_names(self, metrics: list[dict] | None) -> None:
+ def validate_metric_event_names(
+ self, metrics: list[dict] | None, *, known_event_names: set[str] | None = None
+ ) -> None:
"""Validate that all EventsNode event names have been seen by this project.
The frontend event picker already prevents selecting unknown events, so an
@@ -1092,12 +1103,18 @@ class ExperimentService:
an experiment before deploying the emitting code) can pass
``allow_unknown_events=True`` to bypass this check.
+ ``known_event_names`` exempts names the caller has established are already in
+ use, so an update can be checked for what it introduces rather than for
+ everything it resends. See ``update_experiment``.
+
Scope must match the picker: the EventDefinition list endpoint is
project-scoped (see posthog/api/event_definition.py), so a user in a
multi-team project can pick an event ingested by a sibling team. We
mirror that scope here to avoid rejecting legitimate selections.
"""
event_names, _ = self._extract_entity_nodes(metrics)
+ if known_event_names:
+ event_names -= known_event_names
if not event_names:
return
@@ -3358,20 +3375,36 @@ class ExperimentService:
# _sync_ordering_with_metric_changes runs later and appends the new
# regenerated uuids as additions; _sync_ordering_for_saved_metrics_on_update
# handles saved-metric link uuids independently.
+
+ # `metrics`/`metrics_secondary` are whole-array fields, so changing one metric
+ # means resending them all. A metric already on the experiment has been through
+ # this check (or was deliberately allowed past it), so re-validating it lets one
+ # stale event name or deleted action block edits that don't touch it. Both
+ # sections are pooled: moving a metric between them changes which array holds
+ # it, not which entity it references. Read before the update is applied, so
+ # these are the stored references.
+ persisted_event_names, persisted_action_ids = self._extract_entity_nodes(
+ [*(experiment.metrics or []), *(experiment.metrics_secondary or [])]
+ )
+
if "metrics" in update_data:
update_data["metrics"] = self._assign_uuids_to_metrics(update_data["metrics"], seen=seen_metric_uuids)
self.validate_experiment_metrics(update_data["metrics"])
- self.validate_metric_action_ids(update_data["metrics"], self.team.id)
+ self.validate_metric_action_ids(update_data["metrics"], self.team.id, known_action_ids=persisted_action_ids)
if not allow_unknown_events:
- self.validate_metric_event_names(update_data["metrics"])
+ self.validate_metric_event_names(update_data["metrics"], known_event_names=persisted_event_names)
if "metrics_secondary" in update_data:
update_data["metrics_secondary"] = self._assign_uuids_to_metrics(
update_data["metrics_secondary"], seen=seen_metric_uuids
)
self.validate_experiment_metrics(update_data["metrics_secondary"])
- self.validate_metric_action_ids(update_data["metrics_secondary"], self.team.id)
+ self.validate_metric_action_ids(
+ update_data["metrics_secondary"], self.team.id, known_action_ids=persisted_action_ids
+ )
if not allow_unknown_events:
- self.validate_metric_event_names(update_data["metrics_secondary"])
+ self.validate_metric_event_names(
+ update_data["metrics_secondary"], known_event_names=persisted_event_names
+ )
enforce_warehouse_metric_access(
[
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index a8e975ba2cb7..af57ffa8b691 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -6065,6 +6065,52 @@ class TestExperimentService(APIBaseTest):
)
assert experiment.metrics is not None and len(experiment.metrics) == 1
+ def test_update_with_deleted_action_still_referenced_succeeds(self):
+ action = Action.objects.create(team=self.team, name="soon deleted action")
+ stale = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "ActionsNode", "id": action.id},
+ }
+ service = self._service()
+ experiment = service.create_experiment(
+ name="Stale Action Resend",
+ feature_flag_key="stale-action-resend-flag",
+ metrics=[stale],
+ )
+ action.deleted = True
+ action.save()
+
+ updated = service.update_experiment(experiment, {"metrics": [stale], "metrics_secondary": []})
+
+ assert updated.metrics is not None and len(updated.metrics) == 1
+
+ def test_update_rejects_new_unknown_action_alongside_resent_stale_one(self):
+ action = Action.objects.create(team=self.team, name="another soon deleted action")
+ stale = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "ActionsNode", "id": action.id},
+ }
+ service = self._service()
+ experiment = service.create_experiment(
+ name="Unknown Alongside Stale Action",
+ feature_flag_key="unknown-alongside-stale-action-flag",
+ metrics=[stale],
+ )
+ action.deleted = True
+ action.save()
+ fresh = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "ActionsNode", "id": 999999},
+ }
+
+ with self.assertRaises(ValidationError) as ctx:
+ service.update_experiment(experiment, {"metrics": [stale, fresh]})
+
+ assert "999999" in str(ctx.exception.detail)
+
def test_funnel_metric_with_empty_series_raises(self):
# The experiment exposure event is prepended as step_0 at query time, so an
# empty series would produce a degenerate single-step funnel with no conversion event.
@@ -6550,6 +6596,53 @@ class TestExperimentService(APIBaseTest):
# Event/action validation on update_experiment
# ------------------------------------------------------------------
+ def test_update_keeps_metric_whose_event_was_never_ingested(self):
+ service = self._service()
+ metric = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "not_yet_deployed"},
+ }
+ experiment = service.create_experiment(
+ name="Move Stale Event",
+ feature_flag_key="move-stale-event-flag",
+ allow_unknown_events=True,
+ metrics=[metric],
+ )
+
+ # Moving the metric to the other section resends both arrays without the
+ # opt-in flag. The event is already on the experiment, so it must not be
+ # re-validated: a stale name would otherwise block every metric edit.
+ updated = service.update_experiment(experiment, {"metrics": [], "metrics_secondary": [metric]})
+
+ assert updated.metrics == []
+ assert updated.metrics_secondary is not None and len(updated.metrics_secondary) == 1
+ assert updated.metrics_secondary[0]["source"]["event"] == "not_yet_deployed"
+
+ def test_update_rejects_new_unknown_event_alongside_resent_stale_one(self):
+ service = self._service()
+ stale = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "not_yet_deployed"},
+ }
+ experiment = service.create_experiment(
+ name="Add Unknown Alongside Stale",
+ feature_flag_key="add-unknown-alongside-stale-flag",
+ allow_unknown_events=True,
+ metrics=[stale],
+ )
+ fresh = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "also_not_deployed"},
+ }
+
+ with self.assertRaises(ValidationError) as ctx:
+ service.update_experiment(experiment, {"metrics": [stale, fresh]})
+
+ assert "also_not_deployed" in str(ctx.exception.detail)
+
def test_update_experiment_with_unknown_event_raises(self):
EventDefinition.objects.create(team=self.team, name="$pageview")
service = self._service()