: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(surveys): add regex URL targeting to guided surveys (#57716)
Lucas Faria2e6917a4e4d9
diff --git a/frontend/src/scenes/surveys/wizard/SurveyWizard.tsx b/frontend/src/scenes/surveys/wizard/SurveyWizard.tsxindex fc9f552bd980..c0345edb0037 100644--- a/frontend/src/scenes/surveys/wizard/SurveyWizard.tsx+++ b/frontend/src/scenes/surveys/wizard/SurveyWizard.tsx@@ -17,7 +17,7 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { themeLogic } from '~/layout/navigation-3000/themeLogic'-import { SurveyQuestionBranchingType } from '~/types'+import { SurveyMatchType, SurveyQuestionBranchingType } from '~/types'import { SdkVersionWarnings } from '../components/SdkVersionWarnings'import { NewSurvey } from '../constants'@@ -168,7 +168,14 @@ function SurveyWizard({ id }: SurveyWizardLogicProps): JSX.Element {const summary: string[] = []if (conditions?.url) {- summary.push(`URL ${conditions.urlMatchType === 'exact' ? 'is exactly' : 'contains'} "${conditions.url}"`)+ const urlMatchLabel =+ conditions.urlMatchType === SurveyMatchType.Exact+ ? 'is exactly'+ : conditions.urlMatchType === SurveyMatchType.Regex+ ? 'matches regex'+ : 'contains'++ summary.push(`URL ${urlMatchLabel} "${conditions.url}"`)}if (conditions?.selector) {diff --git a/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx b/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsxindex effed5990d49..af7df0830af7 100644--- a/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx+++ b/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx@@ -1,45 +1,101 @@import { useActions, useValues } from 'kea'-import { useEffect } from 'react'+import { RE2JS } from 're2js'+import { useEffect, useState } from 'react'import { IconTrash } from '@posthog/icons'-import { LemonButton, LemonInputSelect, LemonSegmentedButton } from '@posthog/lemon-ui'+import { LemonButton, LemonInputSelect, LemonSegmentedButton, Spinner } from '@posthog/lemon-ui'+import api from 'lib/api'import { FlagSelector } from 'lib/components/FlagSelector'import { ANY_VARIANT, variantOptions } from 'lib/components/IngestionControls/triggers/FlagTrigger/VariantSelector'import { LemonRadio } from 'lib/lemon-ui/LemonRadio'+import { humanFriendlyNumber } from 'lib/utils'+import { formatRE2Error } from 'lib/utils/regexp'import { featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'+import { teamLogic } from 'scenes/teamLogic'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'-import { PropertyDefinitionType, SurveyDisplayConditions, SurveyMatchType } from '~/types'+import type { HogQLQueryString } from '~/queries/utils'+import {+ PropertyDefinitionType,+ PropertyFilterType,+ PropertyOperator,+ SurveyDisplayConditions,+ SurveyMatchType,+} from '~/types'import { surveyLogic } from '../../surveyLogic'import { SurveyAudienceFilters } from '../SurveyAudienceFilters'import { WizardSection, WizardStepLayout } from '../WizardLayout'const DEVICE_OPTIONS = ['Desktop', 'Mobile', 'Tablet']+const URL_AUDIENCE_ESTIMATE_DAYS = 30+const URL_AUDIENCE_ESTIMATE_TAGS = {+ scene: 'Survey' as const,+ productKey: 'surveys' as const,+ name: 'survey_url_audience_estimate' as const,+}++type UrlMatchMode = SurveyMatchType.Contains | SurveyMatchType.Exact | SurveyMatchType.Regex+type UrlAudienceEstimate =+ | { status: 'idle' }+ | { status: 'loading' }+ | { status: 'loaded'; count: number }+ | { status: 'error' }++const URL_MATCH_MODE_PROPERTY_OPERATORS: Record<UrlMatchMode, PropertyOperator> = {+ [SurveyMatchType.Contains]: PropertyOperator.IContains,+ [SurveyMatchType.Exact]: PropertyOperator.Exact,+ [SurveyMatchType.Regex]: PropertyOperator.Regex,+}++function getRegexValidationError(pattern: string, matchType: UrlMatchMode): string | null {+ if (matchType !== SurveyMatchType.Regex || !pattern) {+ return null+ }++ try {+ RE2JS.compile(pattern)+ } catch (error) {+ return error instanceof Error ? formatRE2Error(error, pattern) : 'Invalid RE2 regex'+ }++ return null+}export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => void }): JSX.Element {const { survey } = useValues(surveyLogic)const { setSurveyValue } = useActions(surveyLogic)const { featureFlag } = useValues(featureFlagLogic({ id: survey.linked_flag_id || 'link' }))+ const { currentTeamId } = useValues(teamLogic)const { options } = useValues(propertyDefinitionsModel)const { loadPropertyValues } = useActions(propertyDefinitionsModel)const urlOptions = options['$current_url']+ const [urlAudienceEstimate, setUrlAudienceEstimate] = useState<UrlAudienceEstimate>({ status: 'idle' })const conditions: Partial<SurveyDisplayConditions> = survey.conditions || {}const targetingMode = conditions.urlMatchType ? 'specific' : 'all'const urlPattern = conditions.url || ''- const urlMatchMode =- conditions.urlMatchType === SurveyMatchType.Exact ? SurveyMatchType.Exact : SurveyMatchType.Contains+ const urlMatchMode: UrlMatchMode =+ conditions.urlMatchType === SurveyMatchType.Exact || conditions.urlMatchType === SurveyMatchType.Regex+ ? conditions.urlMatchType+ : SurveyMatchType.Containsconst isPathInputInExactMode = urlMatchMode === SurveyMatchType.Exact && urlPattern.trim().startsWith('/')+ const regexValidationError = getRegexValidationError(urlPattern, urlMatchMode)const selectedDevices = conditions.deviceTypes || []const resolvedLinkedFlag = survey.linked_flag || (survey.linked_flag_id ? featureFlag : null)const urlInputPlaceholder =urlMatchMode === SurveyMatchType.Exact? 'Select a page or type the full URL'- : 'Select a page or type a path like /pricing'+ : urlMatchMode === SurveyMatchType.Regex+ ? 'Type a regex like ^https://example.com/docs/.*'+ : 'Select a page or type a path like /pricing'const urlSuggestions = (() => {+ if (urlMatchMode === SurveyMatchType.Regex) {+ return []+ }+const seen = new Set<string>()return (urlOptions?.values || [])@@ -72,7 +128,12 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => void})()useEffect(() => {- if (targetingMode === 'specific' && urlOptions?.status !== 'loading' && urlOptions?.status !== 'loaded') {+ if (+ targetingMode === 'specific' &&+ urlMatchMode !== SurveyMatchType.Regex &&+ urlOptions?.status !== 'loading' &&+ urlOptions?.status !== 'loaded'+ ) {loadPropertyValues({endpoint: undefined,type: PropertyDefinitionType.Event,@@ -82,7 +143,65 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => voidproperties: [],})}- }, [targetingMode, urlOptions?.status, loadPropertyValues])+ }, [targetingMode, urlMatchMode, urlOptions?.status, loadPropertyValues])++ useEffect(() => {+ const trimmedPattern = urlPattern.trim()++ if (+ targetingMode !== 'specific' ||+ !currentTeamId ||+ !trimmedPattern ||+ isPathInputInExactMode ||+ regexValidationError+ ) {+ setUrlAudienceEstimate({ status: 'idle' })+ return+ }++ const abortController = new AbortController()+ const timeout = window.setTimeout(async () => {+ setUrlAudienceEstimate({ status: 'loading' })++ try {+ const query = `+ SELECT uniq(person_id)+ FROM events+ WHERE team_id = ${currentTeamId}+ AND event = '$pageview'+ AND timestamp >= now() - INTERVAL ${URL_AUDIENCE_ESTIMATE_DAYS} DAY+ AND {filters}+ ` as HogQLQueryString++ const response = await api.queryHogQL<[[number]]>(query, URL_AUDIENCE_ESTIMATE_TAGS, {+ requestOptions: { signal: abortController.signal },+ queryParams: {+ filters: {+ properties: [+ {+ key: '$current_url',+ operator: URL_MATCH_MODE_PROPERTY_OPERATORS[urlMatchMode],+ type: PropertyFilterType.Event,+ value: trimmedPattern,+ },+ ],+ },+ },+ })++ setUrlAudienceEstimate({ status: 'loaded', count: response.results?.[0]?.[0] ?? 0 })+ } catch (error) {+ if ((error as { name?: string }).name !== 'AbortError') {+ setUrlAudienceEstimate({ status: 'error' })+ }+ }+ }, 500)++ return () => {+ window.clearTimeout(timeout)+ abortController.abort()+ }+ }, [currentTeamId, isPathInputInExactMode, regexValidationError, targetingMode, urlMatchMode, urlPattern])const setTargetingMode = (mode: 'all' | 'specific'): void => {if (mode === 'all') {@@ -96,7 +215,7 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => voidsetSurveyValue('conditions', { ...conditions, url: pattern, urlMatchType: urlMatchMode })}- const setUrlMatchMode = (matchType: SurveyMatchType.Exact | SurveyMatchType.Contains): void => {+ const setUrlMatchMode = (matchType: UrlMatchMode): void => {setSurveyValue('conditions', {...conditions,urlMatchType: matchType,@@ -147,12 +266,11 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => void<div className="mb-2"><LemonSegmentedButtonvalue={urlMatchMode}- onChange={(value) =>- setUrlMatchMode(value as SurveyMatchType.Exact | SurveyMatchType.Contains)- }+ onChange={(value) => setUrlMatchMode(value as UrlMatchMode)}options={[{ value: SurveyMatchType.Contains, label: 'Contains path' },{ value: SurveyMatchType.Exact, label: 'Exact URL' },+ { value: SurveyMatchType.Regex, label: 'Regex' },]}size="small"/>@@ -162,6 +280,10 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => voidvalue={urlPattern ? [urlPattern] : []}onChange={(val) => setUrlPattern(val[0] || '')}onInputChange={(newInput) => {+ if (urlMatchMode === SurveyMatchType.Regex) {+ return+ }+loadPropertyValues({type: PropertyDefinitionType.Event,endpoint: undefined,@@ -173,11 +295,13 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => void}}placeholder={urlInputPlaceholder}allowCustomValues- status={isPathInputInExactMode ? 'danger' : undefined}- loading={urlOptions?.status === 'loading'}+ status={isPathInputInExactMode || regexValidationError ? 'danger' : undefined}+ loading={urlMatchMode !== SurveyMatchType.Regex && urlOptions?.status === 'loading'}options={urlSuggestions}/>- {isPathInputInExactMode ? (+ {regexValidationError ? (+ <p className="text-xs text-danger mt-1.5">{regexValidationError}</p>+ ) : isPathInputInExactMode ? (<p className="text-xs text-danger mt-1.5">Exact URL requires the full URL, including protocol and host. Use Contains path forentries like /pricing.@@ -186,7 +310,26 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => void<p className="text-xs text-muted mt-1.5">{urlMatchMode === SurveyMatchType.Exact? 'Select from your most visited pages or type the full URL, including protocol and host.'- : 'Select from your most visited pages or type a path like /pricing.'}+ : urlMatchMode === SurveyMatchType.Regex+ ? 'Match against the full current URL using a regular expression.'+ : 'Select from your most visited pages or type a path like /pricing.'}+ </p>+ )}+ {urlAudienceEstimate.status === 'loading' && (+ <p className="text-xs text-muted mt-1.5 flex items-center gap-1">+ <Spinner className="text-xs" /> Estimating matching users...+ </p>+ )}+ {urlAudienceEstimate.status === 'loaded' && (+ <p className="text-xs text-muted mt-1.5">+ About {humanFriendlyNumber(urlAudienceEstimate.count)} unique{' '}+ {urlAudienceEstimate.count === 1 ? 'user' : 'users'} viewed matching URLs in the last{' '}+ {URL_AUDIENCE_ESTIMATE_DAYS} days.+ </p>+ )}+ {urlAudienceEstimate.status === 'error' && (+ <p className="text-xs text-muted mt-1.5">+ Unable to estimate matching users for this URL condition.</p>)}</div>