-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathABTest.tsx
More file actions
81 lines (73 loc) · 2.23 KB
/
Copy pathABTest.tsx
File metadata and controls
81 lines (73 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { IS_PREVIEW_DEPLOY, IS_PROD } from "@/lib/utils/env"
import { ABTestDebugPanel } from "./TestDebugPanel"
import { ABTestTracker } from "./TestTracker"
import type { ABTestVariants } from "@/lib/ab-testing/types"
interface ABTestProps {
/** Unique key for the A/B test (must match Matomo experiment name) */
testKey: string
/** Precomputed variant index from the Flags SDK */
variantIndex: number
/** Array of variant components to render (index 0 = original) */
variants: ABTestVariants
}
/**
* A/B Test component for use with precomputed flag values.
*
* Designed for the Flags SDK precomputation pattern: it receives the variant
* index directly from server-side precomputation, via the proxy-rewritten
* coded route (see docs/ab-testing.md).
*
* @example
* ```tsx
* // In a server component with precomputed flag value
* const [heroVariant] = await getPrecomputed([homepageHeroFlag], abTestFlags, code)
*
* <ABTest
* testKey="HomepageHero"
* variantIndex={heroVariant}
* variants={[
* <OriginalHero key="original" />,
* <VariantAHero key="variant-a" />,
* ]}
* />
* ```
*/
export function ABTest({ testKey, variantIndex, variants }: ABTestProps) {
const safeIndex = Math.max(0, Math.min(variantIndex, variants.length - 1))
// Extract labels from React element keys or fall back to defaults
const availableVariants = variants.map((variant, i) => {
if (
variant &&
typeof variant === "object" &&
"key" in variant &&
variant.key
) {
return String(variant.key)
.replace(/-/g, " ")
.replace(/\b\w/g, (l) => l.toUpperCase())
}
return `Variant ${i}`
})
return (
<>
{/* Track the A/B test assignment with Matomo */}
<ABTestTracker
assignment={{
experimentId: testKey,
experimentName: testKey,
variant: availableVariants[safeIndex],
variantIndex: safeIndex,
}}
/>
{/* Preview panel for development and preview deploys */}
{(!IS_PROD || IS_PREVIEW_DEPLOY) && (
<ABTestDebugPanel
testKey={testKey}
availableVariants={availableVariants}
/>
)}
{/* Render the selected variant */}
{variants[safeIndex]}
</>
)
}