: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
import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { subscriptions } from 'kea-subscriptions'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { EXPERIMENT_TARGET_SELECTOR } from 'lib/utils/actions'
import { toolbarLogic } from '~/toolbar/shared/bar/toolbarLogic'
import { ElementSelectorType } from '~/toolbar/shared/experiments/elementSelectorTypes'
import { experimentsLogic } from '~/toolbar/shared/experiments/experimentsLogic'
import {
sanitizeExperimentHTML,
sanitizeExperimentStyle,
setSanitizedHTML,
setSanitizedStyle,
} from '~/toolbar/shared/experiments/sanitize'
import { toolbarApi } from '~/toolbar/shared/toolbarApi'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import { toolbarPosthogJS } from '~/toolbar/shared/toolbarPosthogJS'
import { WebExperiment, WebExperimentDraftType, WebExperimentForm, WebExperimentVariant } from '~/toolbar/shared/types'
import { urls } from '~/toolbar/shared/urls'
import { elementToQuery, isLaunched, joinWithUiHost, percentageDistribution } from '~/toolbar/shared/utils'
import { Experiment, ExperimentIdType } from '~/types'
import type { ToolbarUserIntent } from '../../../types'
// The element picker finds a selector that is unique on this page, and a shared component renders the same
// selector elsewhere, so a new variant starts scoped to the page the user picked on.
function currentPageCondition(): WebExperimentVariant['conditions'] {
return {
url: window.location.origin + window.location.pathname,
urlMatchType: 'icontains',
}
}
function newExperiment(): WebExperimentForm {
return {
name: '',
variants: {
control: {
transforms: [],
rollout_percentage: 50,
},
test: {
is_new: true,
transforms: [{}],
conditions: currentPageCondition(),
rollout_percentage: 50,
},
},
original_html_state: {},
}
}
const EXPERIMENT_HEADER_TARGETS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
const EXPERIMENT_BUTTON_TARGETS = ['input[type="button"]', 'button']
const ElementSelectorMap: Record<ElementSelectorType, string> = {
'all-elements': EXPERIMENT_TARGET_SELECTOR,
headers: EXPERIMENT_HEADER_TARGETS.join(','),
buttons: EXPERIMENT_BUTTON_TARGETS.join(','),
images: 'img',
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentsTabLogicValues {
allExperiments: WebExperiment[] // experimentsLogic
buttonVisible: boolean // toolbarConfigLogic
dataAttributes: string[] // toolbarConfigLogic
experimentId: ExperimentIdType | null // toolbarConfigLogic
uiHost: string // toolbarConfigLogic
userIntent: ToolbarUserIntent | null // toolbarConfigLogic
addVariantAvailable: boolean | undefined
buttonExperimentsVisible: boolean
elementSelector: string
experimentForm: WebExperimentForm
experimentFormAllErrors: Record<string, any>
experimentFormChanged: boolean
experimentFormErrors: DeepPartialMap<WebExperimentForm, ValidationErrorType>
experimentFormHasErrors: boolean
experimentFormManualErrors: Record<string, any>
experimentFormTouched: boolean
experimentFormTouches: Record<string, boolean>
experimentFormValidationErrors: DeepPartialMap<WebExperimentForm, ValidationErrorType>
inspectingElement: number | null
isExperimentFormSubmitting: boolean
isExperimentFormValid: boolean
newExperimentForElement: HTMLElement | null
removeVariantAvailable: boolean | undefined
selectedElementType: ElementSelectorType
selectedExperiment: Experiment | WebExperimentDraftType | null
selectedExperimentId: number | 'new' | 'web' | null
selectedExperimentKey: string | null
selectedVariant: string
showExperimentFormErrors: boolean
showExperimentsTooltip: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentsTabLogicActions {
getExperiments: (_?: any) => any // experimentsLogic
addNewTransformation: (variant: string) => {
variant: string
}
addNewVariant: () => {}
applyVariant: (newVariantKey: string) => {
newVariantKey: string
}
editSelectorWithIndex: (
variant: string,
index: number | null
) => {
index: number | null
variant: string
}
hideButtonExperiments: () => {
value: true
}
inspectElementSelected: (
element: HTMLElement,
variant: string,
index: number | null,
selector?: string | null
) => {
element: HTMLElement
index: number | null
selector: string | null | undefined
variant: string
}
inspectForElementWithIndex: (
variant: string,
type: ElementSelectorType,
index: number | null
) => {
index: number | null
type: ElementSelectorType
variant: string
}
newExperiment: (element?: HTMLElement) => {
element: HTMLElement | null
}
rebalanceRolloutPercentage: () => {}
removeElement: (
variant: string,
index: number
) => {
index: number
variant: string
}
removeVariant: (variant: string) => {
variant: string
}
resetExperimentForm: (values?: WebExperimentForm) => {
values?: WebExperimentForm
}
saveExperiment: (formValues: WebExperimentForm) => {
formValues: WebExperimentForm
}
selectElementType: (elementType: ElementSelectorType) => {
elementType: ElementSelectorType
}
selectExperiment: (id: ExperimentIdType | null) => {
id: ExperimentIdType | null
}
selectVariant: (variant: string) => {
variant: string
}
setElementSelector: (
selector: string,
index: number
) => {
index: number
selector: string
}
setExperimentFormManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
setExperimentFormValue: (
key: FieldName,
value: any
) => {
name: FieldName
value: any
}
setExperimentFormValues: (values: DeepPartial<WebExperimentForm>) => {
values: DeepPartial<WebExperimentForm>
}
setShowExperimentsTooltip: (showExperimentsTooltip: boolean) => {
showExperimentsTooltip: boolean
}
showButtonExperiments: () => {
value: true
}
submitExperimentForm: () => {
value: boolean
}
submitExperimentFormFailure: (
error: Error,
errors: Record<string, any>
) => {
error: Error
errors: Record<string, any>
}
submitExperimentFormRequest: (experimentForm: WebExperimentForm) => {
experimentForm: WebExperimentForm
}
submitExperimentFormSuccess: (experimentForm: WebExperimentForm) => {
experimentForm: WebExperimentForm
}
touchExperimentFormField: (key: string) => {
key: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentsTabLogicMeta {
__keaTypeGenInternalSelectorTypes: {
removeVariantAvailable: (experimentForm: WebExperimentForm) => boolean | undefined
addVariantAvailable: (experimentForm: WebExperimentForm) => boolean | undefined
selectedExperiment: (
selectedExperimentId: number | 'new' | 'web' | null,
allExperiments: WebExperiment[]
) => Experiment | WebExperimentDraftType | null
selectedExperimentKey: (
selectedExperimentId: number | 'new' | 'web' | null,
selectedExperiment: Experiment | WebExperimentDraftType | null
) => string | null
}
}
export type experimentsTabLogicType = MakeLogicType<
experimentsTabLogicValues,
experimentsTabLogicActions,
Record<string, any>,
experimentsTabLogicMeta
>
/** Puts back the HTML and styles saved before a preview. Sanitizes once per selector and reuses it across matches. */
export function restoreOriginalHtmlState(
originalHtmlState: WebExperimentForm['original_html_state'] | undefined
): void {
Object.entries(originalHtmlState || {}).forEach(([selector, originalState]) => {
const sanitizedHtml = sanitizeExperimentHTML(originalState.html)
const sanitizedCss = sanitizeExperimentStyle(originalState.css)
document.querySelectorAll(selector).forEach((element) => {
const htmlElement = element as HTMLElement
htmlElement.innerHTML = sanitizedHtml
if (sanitizedCss) {
htmlElement.setAttribute('style', sanitizedCss)
} else {
htmlElement.removeAttribute('style')
}
})
})
}
export const experimentsTabLogic = kea<experimentsTabLogicType>([
path(['toolbar', 'experiments', 'experimentsTabLogic']),
actions({
selectExperiment: (id: ExperimentIdType | null) => ({ id: id || null }),
selectVariant: (variant: string) => ({ variant }),
selectElementType: (elementType: ElementSelectorType) => ({ elementType }),
newExperiment: (element?: HTMLElement) => ({
element: element || null,
}),
addNewVariant: () => ({}),
rebalanceRolloutPercentage: () => ({}),
removeVariant: (variant: string) => ({
variant,
}),
applyVariant: (newVariantKey: string) => ({
newVariantKey,
}),
addNewTransformation: (variant: string) => ({ variant }),
removeElement: (variant: string, index: number) => ({ variant, index }),
inspectForElementWithIndex: (variant: string, type: ElementSelectorType, index: number | null) => ({
variant,
type,
index,
}),
editSelectorWithIndex: (variant: string, index: number | null) => ({ variant, index }),
inspectElementSelected: (
element: HTMLElement,
variant: string,
index: number | null,
selector?: string | null
) => ({
element,
variant,
index,
selector,
}),
saveExperiment: (formValues: WebExperimentForm) => ({ formValues }),
showButtonExperiments: true,
hideButtonExperiments: true,
setShowExperimentsTooltip: (showExperimentsTooltip: boolean) => ({ showExperimentsTooltip }),
setElementSelector: (selector: string, index: number) => ({ selector, index }),
}),
connect(() => ({
values: [
toolbarConfigLogic,
['dataAttributes', 'uiHost', 'buttonVisible', 'userIntent', 'dataAttributes', 'experimentId'],
experimentsLogic,
['allExperiments'],
],
actions: [experimentsLogic, ['getExperiments']],
})),
reducers({
buttonExperimentsVisible: [
false,
{
showButtonExperiments: () => true,
hideButtonExperiments: () => false,
},
],
selectedExperimentId: [
null as number | 'new' | 'web' | null,
{
selectExperiment: (_, { id }) => id,
newExperiment: () => 'new',
},
],
selectedVariant: [
'',
{
selectVariant: (_, { variant }) => variant,
},
],
selectedElementType: [
'all-elements' as ElementSelectorType,
{
selectElementType: (_, { elementType }) => elementType,
},
],
newExperimentForElement: [
null as HTMLElement | null,
{
newExperiment: (_, { element }) => element,
selectExperiment: () => null,
},
],
elementSelector: [
'',
{
inspectForElementWithIndex: (_, { type }) => ElementSelectorMap[type] || '',
},
],
inspectingElement: [
null as number | null,
{
inspectForElementWithIndex: (_, { index }) => index,
inspectElementSelected: () => null,
selectExperiment: () => null,
newExperiment: () => null,
},
],
showExperimentsTooltip: [
false,
{
setShowExperimentsTooltip: (_, { showExperimentsTooltip }) => showExperimentsTooltip,
},
],
}),
forms(({ values, actions }) => ({
experimentForm: {
defaults: {
name: '',
variants: {},
original_html_state: {},
} as WebExperimentForm,
errors: ({ name }) => ({
name: !name ? 'Please enter a name for this experiment' : undefined,
}),
submit: async (formValues, breakpoint) => {
const experimentToSave = {
...formValues,
}
// This property is only used in the editor to undo transforms
delete experimentToSave.original_html_state
const { uiHost } = values
const { selectedExperimentId } = values
const isUpdate = selectedExperimentId && selectedExperimentId !== 'new'
const result = isUpdate
? await toolbarApi.webExperiments.update(selectedExperimentId, experimentToSave, {
context: 'save_experiment',
toastOnError: 'Failed to save experiment',
})
: await toolbarApi.webExperiments.create(experimentToSave, {
context: 'save_experiment',
toastOnError: 'Failed to save experiment',
})
if (!result.ok) {
// Throwing makes the form report a failure instead of a successful submit.
throw new Error('Failed to save experiment')
}
const response = result.data
experimentsLogic.actions.updateExperiment({ experiment: response })
actions.selectExperiment(null)
lemonToast.success('Experiment saved', {
button: {
label: 'Open in PostHog',
action: () => window.open(joinWithUiHost(uiHost, urls.experiment(response.id)), '_blank'),
},
})
breakpoint()
},
// whether we show errors after touch (true) or submit (false)
showErrorsOnTouch: true,
// show errors even without submitting first
alwaysShowErrors: false,
},
})),
selectors({
removeVariantAvailable: [
(s) => [s.experimentForm],
(experimentForm: WebExperimentForm): boolean | undefined => {
/*Only show the remove button if all of these conditions are met:
1. The experiment is still in draft form
2. there's more than one test variant, and the variant is not control*/
return (
!isLaunched(experimentForm) &&
experimentForm.variants &&
Object.keys(experimentForm.variants).length > 2
)
},
],
addVariantAvailable: [
(s) => [s.experimentForm],
(experimentForm: WebExperimentForm): boolean | undefined => {
/*Only show the add button if all of these conditions are met:
1. The experiment is still in draft form*/
return !isLaunched(experimentForm)
},
],
selectedExperiment: [
(s) => [s.selectedExperimentId, s.allExperiments],
(
selectedExperimentId: number | 'new' | 'web' | null,
allExperiments: WebExperiment[]
): Experiment | WebExperimentDraftType | null => {
if (selectedExperimentId === 'new') {
return newExperiment()
}
return allExperiments.find((a) => a.id === selectedExperimentId) || null
},
],
// A reloaded experiment list builds new experiment objects, which must not reset the form being edited.
selectedExperimentKey: [
(s) => [s.selectedExperimentId, s.selectedExperiment],
(
selectedExperimentId: number | 'new' | 'web' | null,
selectedExperiment: Experiment | WebExperimentDraftType | null
): string | null => (selectedExperiment ? String(selectedExperimentId) : null),
],
}),
subscriptions(({ actions, values }) => ({
selectedExperimentKey: () => {
// The page still shows the previous experiment's preview, so put its original HTML back first.
restoreOriginalHtmlState(values.experimentForm?.original_html_state)
const { selectedExperiment } = values
if (!selectedExperiment) {
actions.setExperimentFormValues({ name: '', variants: {}, original_html_state: {} })
} else {
// Build original_html_state from existing selectors
const original_html_state: Record<string, { html: string; css?: string }> = {}
if ((selectedExperiment as WebExperiment).variants) {
Object.values((selectedExperiment as WebExperiment).variants).forEach((variant) => {
variant.transforms?.forEach((transform) => {
if (transform.selector) {
const element = document.querySelector(transform.selector) as HTMLElement
if (element) {
const style = element.getAttribute('style')
original_html_state[transform.selector] = {
html: element.innerHTML,
...(style && { css: style }),
}
}
}
})
})
}
actions.setExperimentFormValues({
name: selectedExperiment.name,
variants: (selectedExperiment as WebExperiment).variants
? (selectedExperiment as WebExperiment).variants
: {},
original_html_state,
})
// TODO: refactor into a single actions to select + apply changes
actions.applyVariant('control')
actions.selectVariant('control')
}
},
})),
listeners(({ actions, values }) => ({
selectExperiment: ({ id }) => {
if (id) {
if (!values.buttonVisible) {
toolbarConfigLogic.actions.showButton()
}
if (!values.buttonExperimentsVisible) {
actions.showButtonExperiments()
}
// The browser extension runs this logic without the floating toolbar's bar.
toolbarLogic.findMounted()?.actions.setVisibleMenu('experiments')
}
},
newExperiment: () => {
actions.showButtonExperiments()
toolbarLogic.findMounted()?.actions.setVisibleMenu('experiments')
},
inspectElementSelected: ({ element, variant, index, selector }) => {
if (values.experimentForm?.variants) {
const currentVariant = values.experimentForm.variants[variant]
if (currentVariant && index !== null && currentVariant.transforms.length > index) {
if (!selector) {
selector = element.id ? `#${element.id}` : elementToQuery(element, [])
}
if (!selector) {
return
}
// Restore original html state for previous selector
const previousSelector = currentVariant.transforms[index].selector
if (previousSelector) {
const originalHtmlState = values.experimentForm.original_html_state?.[previousSelector]
if (originalHtmlState) {
const previousElement = document.querySelector(previousSelector) as HTMLElement | null
// Captured from the live DOM, so script/event-handler content the customer
// page legitimately included is not restored — that's the sanitization trade-off.
if (previousElement) {
setSanitizedHTML(previousElement, originalHtmlState.html)
if (originalHtmlState.css) {
setSanitizedStyle(previousElement, originalHtmlState.css)
}
}
}
}
// Update state
const updatedVariants = {
...values.experimentForm.variants,
[variant]: {
...currentVariant,
transforms: currentVariant.transforms.map((t, i) =>
i === index
? {
selector,
html: element.innerHTML,
...(element.getAttribute('style') && { css: element.getAttribute('style') }),
}
: t
),
},
}
actions.setExperimentFormValue('variants', updatedVariants)
// Save the original state to undo transforms on variant change
actions.setExperimentFormValue('original_html_state', {
...values.experimentForm.original_html_state,
[selector]: {
html: element.innerHTML,
...(element.getAttribute('style') && { css: element.getAttribute('style') }),
},
})
}
}
},
removeVariant: ({ variant }) => {
if (values.experimentForm && values.experimentForm.variants) {
delete values.experimentForm.variants[variant]
actions.setExperimentFormValue('variants', values.experimentForm.variants)
actions.rebalanceRolloutPercentage()
actions.selectVariant('control')
}
},
applyVariant: ({ newVariantKey }) => {
if (values.experimentForm && values.experimentForm.variants) {
const selectedVariant = values.experimentForm.variants[newVariantKey]
if (selectedVariant) {
restoreOriginalHtmlState(values.experimentForm.original_html_state)
// Apply variant transforms — sanitize once per transform, reuse across matches.
selectedVariant.transforms?.forEach((transform) => {
if (transform.selector) {
const sanitizedHtml = transform.html ? sanitizeExperimentHTML(transform.html) : null
const sanitizedCss = transform.css ? sanitizeExperimentStyle(transform.css) : null
const elements = document.querySelectorAll(transform.selector)
elements.forEach((element) => {
const htmlElement = element as HTMLElement
if (htmlElement) {
if (sanitizedHtml !== null) {
htmlElement.innerHTML = sanitizedHtml
}
if (sanitizedCss !== null) {
if (sanitizedCss) {
htmlElement.setAttribute('style', sanitizedCss)
} else {
htmlElement.removeAttribute('style')
}
}
}
})
}
})
}
}
},
rebalanceRolloutPercentage: () => {
const perVariantRollout = percentageDistribution(Object.keys(values.experimentForm.variants || {}).length)
let i = 0
for (const existingVariant in values.experimentForm.variants) {
if (values.experimentForm.variants[existingVariant]) {
values.experimentForm.variants[existingVariant].rollout_percentage = Number(perVariantRollout[i])
i++
}
}
actions.setExperimentFormValue('variants', values.experimentForm.variants)
},
addNewVariant: () => {
if (values.experimentForm) {
const nextVariantName = `test-${Object.keys(values.experimentForm.variants || {}).length - 1}`
if (values.experimentForm.variants == undefined) {
values.experimentForm.variants = {}
}
values.experimentForm.variants[nextVariantName] = {
is_new: true,
transforms: [{}],
conditions: currentPageCondition(),
rollout_percentage: 0,
}
actions.setExperimentFormValue('variants', values.experimentForm.variants)
actions.rebalanceRolloutPercentage()
actions.selectVariant(nextVariantName)
}
},
addNewTransformation: ({ variant }) => {
if (values.experimentForm.variants) {
const webVariant = values.experimentForm.variants[variant]
if (webVariant) {
if (webVariant.transforms == undefined) {
webVariant.transforms = []
}
webVariant.transforms.push({})
actions.setExperimentFormValue('variants', values.experimentForm.variants)
actions.selectVariant(variant)
}
}
},
removeElement: ({ index, variant }) => {
if (values.experimentForm.variants) {
const webVariant = values.experimentForm.variants[variant]
if (webVariant) {
webVariant.transforms.splice(index, 1)
actions.setExperimentFormValue('variants', values.experimentForm.variants)
}
}
},
showButtonExperiments: () => {
toolbarPosthogJS.capture('toolbar mode triggered', { mode: 'experiments', enabled: true })
},
hideButtonExperiments: () => {
actions.setShowExperimentsTooltip(false)
toolbarPosthogJS.capture('toolbar mode triggered', { mode: 'experiments', enabled: false })
},
[experimentsLogic.actionTypes.getExperimentsSuccess]: () => {
const { userIntent, experimentId } = values
if (userIntent === 'edit-experiment') {
actions.selectExperiment(experimentId)
toolbarConfigLogic.actions.clearUserIntent()
} else if (userIntent === 'add-experiment') {
actions.newExperiment()
toolbarConfigLogic.actions.clearUserIntent()
} else {
actions.setShowExperimentsTooltip(true)
}
},
setShowExperimentsTooltip: async ({ showExperimentsTooltip }, breakpoint) => {
if (showExperimentsTooltip) {
await breakpoint(1000)
actions.setShowExperimentsTooltip(false)
}
},
selectVariant: ({ variant }) => {
// Deactivate element inspection when switching variant
actions.inspectForElementWithIndex(variant, 'all-elements', null)
},
})),
events(({ actions }) => ({
afterMount: () => {
actions.getExperiments()
},
})),
])