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.

refactor(replay-vision): adopt shared guided wizard stepper (#81453)

Arno Hillen8aff13893c14
diff --git a/frontend/src/lib/components/GuidedWizard/GuidedWizardStepper.test.tsx b/frontend/src/lib/components/GuidedWizard/GuidedWizardStepper.test.tsx
index 92c0ff4e2a8c..a9158967e44d 100644
--- a/frontend/src/lib/components/GuidedWizard/GuidedWizardStepper.test.tsx
+++ b/frontend/src/lib/components/GuidedWizard/GuidedWizardStepper.test.tsx
@@ -33,6 +33,17 @@ describe('GuidedWizardStepper', () => {
expect(screen.getByText('Third').closest('button')).toHaveAttribute('aria-disabled', 'true')
})
+ it('renders each step dataAttr as a data-attr on its button', () => {
+ render(
+ <GuidedWizardStepper
+ steps={STEPS.map((step) => ({ ...step, dataAttr: `wizard-step-${step.step}` }))}
+ currentStep="first"
+ />
+ )
+
+ expect(screen.getByText('Second').closest('button')).toHaveAttribute('data-attr', 'wizard-step-second')
+ })
+
it.each([
['before the steps (e.g. a template picker)', 'intro', 'start', ['1', '2', '3']],
['after the steps (e.g. a success screen)', 'done', 'end', []],
@@ -66,6 +77,45 @@ describe('GuidedWizardStepper', () => {
expect(onStepClick).toHaveBeenCalledWith('third')
})
+ it('shows the error messages as a tooltip on the errored current step', async () => {
+ render(
+ <GuidedWizardStepper steps={STEPS} currentStep="second" stepErrors={{ second: ['Something is wrong'] }} />
+ )
+
+ const warningIcon = screen.getByText('Second').closest('button')!.querySelector('svg')!
+ fireEvent.pointerEnter(warningIcon, { pointerType: 'mouse' })
+ fireEvent.mouseEnter(warningIcon)
+ // The tooltip's hover-intent detection needs pointer movement, not just enter
+ fireEvent.pointerMove(warningIcon, { pointerType: 'mouse' })
+ fireEvent.mouseMove(warningIcon)
+
+ expect(await screen.findByText('Something is wrong')).toBeInTheDocument()
+ })
+
+ it('ignores clicks on a disabled step and explains why in a tooltip', async () => {
+ const onStepClick = jest.fn()
+ render(
+ <GuidedWizardStepper
+ steps={STEPS}
+ currentStep="second"
+ onStepClick={onStepClick}
+ disabledSteps={{ first: 'This step is locked' }}
+ />
+ )
+
+ const disabledButton = screen.getByText('First').closest('button')!
+ expect(disabledButton).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(disabledButton)
+ expect(onStepClick).not.toHaveBeenCalled()
+
+ // aria-disabled (not disabled) keeps the button hoverable so the tooltip can explain the lock
+ fireEvent.pointerEnter(disabledButton, { pointerType: 'mouse' })
+ fireEvent.mouseEnter(disabledButton)
+ fireEvent.pointerMove(disabledButton, { pointerType: 'mouse' })
+ fireEvent.mouseMove(disabledButton)
+ expect(await screen.findByText('This step is locked')).toBeInTheDocument()
+ })
+
it('blocks forward navigation but allows going back when the current step has errors', () => {
const onStepClick = jest.fn()
render(
diff --git a/frontend/src/lib/components/GuidedWizard/GuidedWizardStepper.tsx b/frontend/src/lib/components/GuidedWizard/GuidedWizardStepper.tsx
index cc5a391faf83..43d1ec76eff6 100644
--- a/frontend/src/lib/components/GuidedWizard/GuidedWizardStepper.tsx
+++ b/frontend/src/lib/components/GuidedWizard/GuidedWizardStepper.tsx
@@ -7,6 +7,8 @@ export interface GuidedWizardStep<Step extends string = string> {
step: Step
label: string
optional?: boolean
+ /** Rendered as data-attr on the step button, for autocapture analytics. */
+ dataAttr?: string
}
export interface GuidedWizardStepperProps<Step extends string> {
@@ -20,6 +22,9 @@ export interface GuidedWizardStepperProps<Step extends string> {
unlistedStepPosition?: 'start' | 'end'
onStepClick?: (step: Step) => void
stepErrors?: Partial<Record<Step, string[]>>
+ /** Steps that stay in the sequence for consistent numbering but can't be navigated to, keyed to the reason why. */
+ disabledSteps?: Partial<Record<Step, string>>
+ className?: string
'aria-label'?: string
}
@@ -29,6 +34,8 @@ export function GuidedWizardStepper<Step extends string>({
unlistedStepPosition = 'start',
onStepClick,
stepErrors = {},
+ disabledSteps = {},
+ className,
'aria-label': ariaLabel = 'Wizard progress',
}: GuidedWizardStepperProps<Step>): JSX.Element {
const currentStepIndex = steps.findIndex(({ step }) => step === currentStep)
@@ -45,32 +52,44 @@ export function GuidedWizardStepper<Step extends string>({
}
return (
- <nav className="flex items-center" aria-label={ariaLabel}>
+ <nav className={cn('flex items-center', className)} aria-label={ariaLabel}>
{steps.map((step, index) => {
const isCompleted = currentOrder > index
const isCurrent = currentStep === step.step
const hasErrors = (stepErrors[step.step]?.length ?? 0) > 0
const isBlocked = isInteractive && currentStepHasErrors && index > currentOrder
+ const disabledReason = disabledSteps[step.step]
const button = (
<button
type="button"
- onClick={() => handleStepClick(step.step, index)}
- // aria-disabled instead of disabled so the button keeps pointer events (the blocked tooltip needs hover) and its tab-order slot
- aria-disabled={isBlocked || !isInteractive}
+ onClick={() => !disabledReason && handleStepClick(step.step, index)}
+ // aria-disabled instead of disabled so the button keeps pointer events (the tooltips need hover) and its tab-order slot
+ aria-disabled={isBlocked || !!disabledReason || !isInteractive}
+ data-attr={step.dataAttr}
className={cn(
'group flex items-center gap-1.5 px-2 py-1 rounded',
'transition-all duration-150',
'focus:outline-none focus-visible:ring-1 focus-visible:ring-accent',
isBlocked && 'opacity-50 cursor-not-allowed',
- !isBlocked && isInteractive && 'hover:bg-fill-button-tertiary-hover active:scale-[0.98]',
+ !isBlocked && disabledReason && 'opacity-50 cursor-default',
+ !isBlocked &&
+ !disabledReason &&
+ isInteractive &&
+ 'hover:bg-fill-button-tertiary-hover active:scale-[0.98]',
!isInteractive && 'cursor-default'
)}
aria-current={isCurrent ? 'step' : undefined}
>
{/* Indicator: errors outrank the completed checkmark, current or not */}
{hasErrors ? (
- <IconWarning className="size-5 text-warning" />
+ <Tooltip
+ title={stepErrors[step.step]?.map((error) => (
+ <div key={error}>{error}</div>
+ ))}
+ >
+ <IconWarning className="size-5 text-warning" />
+ </Tooltip>
) : isCompleted ? (
<IconCheckCircle className="size-5 text-success" />
) : (
@@ -119,7 +138,13 @@ export function GuidedWizardStepper<Step extends string>({
)}
{/* Step */}
- {isBlocked ? <Tooltip title="Fix errors before proceeding">{button}</Tooltip> : button}
+ {isBlocked ? (
+ <Tooltip title="Fix errors before proceeding">{button}</Tooltip>
+ ) : disabledReason ? (
+ <Tooltip title={disabledReason}>{button}</Tooltip>
+ ) : (
+ button
+ )}
</div>
)
})}
diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
index 10cc091f50c3..8fa8fdf46513 100644
--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
@@ -23,6 +23,7 @@ import {
} from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
+import { GuidedWizardStepper } from 'lib/components/GuidedWizard/GuidedWizardStepper'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
@@ -55,14 +56,13 @@ import { replayScannerLogic } from './replayScannerLogic'
import {
SCANNER_EDITOR_STEPS,
SCANNER_EDITOR_STEP_ORDER,
+ SCANNER_STEPPER_STEPS,
STEP_LABELS,
ScannerEditorStep,
UNVALIDATED_SCANNER_STEPS,
- scannerStepErrors,
scannerEditorSceneLogic,
scannerStepUrlWithParams,
} from './scannerEditorSceneLogic'
-import { ScannerEditorStepper } from './ScannerEditorStepper'
import { scannerSelfDrivingStatsLogic } from './scannerSelfDrivingStatsLogic'
import { SCANNER_TYPE_OPTIONS, getModelOptions, modelNamingVariant } from './types'
@@ -121,15 +121,7 @@ export function ScannerEditorSceneComponent(): JSX.Element {
const scannerLogic = replayScannerLogic({ id: scannerId })
useAttachedLogic(scannerLogic, scannerEditorSceneLogic)
- const {
- scanner,
- scannerLoading,
- isScannerSubmitting,
- scannerValidationErrors,
- showScannerErrors,
- durationValidationError,
- experimentContext,
- } = useValues(scannerLogic)
+ const { scanner, scannerLoading, isScannerSubmitting, stepErrors, experimentContext } = useValues(scannerLogic)
const { submitScanner } = useActions(scannerLogic)
// An experiment cross-sell entry point has already said what to watch and deep-linked the
@@ -149,10 +141,6 @@ export function ScannerEditorSceneComponent(): JSX.Element {
const title = isNew ? scanner?.name || 'New scanner' : scanner?.name || 'Scanner'
- const stepErrors = showScannerErrors
- ? scannerStepErrors({ ...scannerValidationErrors, duration: durationValidationError })
- : undefined
-
// Validate the current step and move on: submit routes to the next step on success. A step with
// nothing to validate navigates straight on, so it can't fail on fields the user hasn't reached.
const advance = (): void => {
@@ -191,9 +179,9 @@ export function ScannerEditorSceneComponent(): JSX.Element {
actions={<ReplayVisionFeedbackButton />}
/>
{showGoalEntry || step === 'overview' || fromOverview ? null : (
- <ScannerEditorStepper
+ <GuidedWizardStepper
+ steps={SCANNER_STEPPER_STEPS}
currentStep={step}
- steps={SCANNER_EDITOR_STEPS}
onStepClick={goToStep}
stepErrors={stepErrors}
disabledSteps={
@@ -201,6 +189,8 @@ export function ScannerEditorSceneComponent(): JSX.Element {
? undefined
: { template: 'A saved scanner keeps the template it was created from' }
}
+ className="flex-wrap justify-center gap-y-1"
+ aria-label="Scanner editor progress"
/>
)}
{step === 'template' ? (
diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorStepper.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorStepper.tsx
deleted file mode 100644
index 420a33d66232..000000000000
--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorStepper.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import { IconCheckCircle, IconWarning } from '@posthog/icons'
-
-import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { cn } from 'lib/utils/css-classes'
-
-import { SCANNER_EDITOR_STEP_ORDER, STEP_LABELS, ScannerEditorStep } from './scannerEditorSceneLogic'
-
-interface ScannerEditorStepperProps {
- currentStep: ScannerEditorStep
- steps: readonly ScannerEditorStep[]
- onStepClick: (step: ScannerEditorStep) => void
- stepErrors?: Partial<Record<ScannerEditorStep, boolean>>
- /** Steps that stay in the sequence for consistent numbering but can't be navigated to. */
- disabledSteps?: Partial<Record<ScannerEditorStep, string>>
-}
-
-export function ScannerEditorStepper({
- currentStep,
- steps,
- onStepClick,
- stepErrors = {},
- disabledSteps = {},
-}: ScannerEditorStepperProps): JSX.Element {
- const currentOrder = SCANNER_EDITOR_STEP_ORDER[currentStep]
-
- return (
- <nav className="flex flex-wrap items-center justify-center gap-y-1" aria-label="Scanner editor progress">
- {steps.map((stepKey, index) => {
- const step = { key: stepKey, label: STEP_LABELS[stepKey] }
- const stepOrder = SCANNER_EDITOR_STEP_ORDER[step.key]
- const isCompleted = currentOrder > stepOrder
- const isCurrent = currentStep === step.key
- const hasErrors = !!stepErrors[step.key]
- const disabledReason = disabledSteps[step.key]
-
- return (
- <div key={step.key} className="flex items-center">
- {index > 0 && (
- <div
- className={cn(
- 'w-6 h-px transition-colors duration-150',
- hasErrors
- ? 'bg-warning'
- : isCompleted || isCurrent
- ? 'bg-success'
- : 'bg-border-primary'
- )}
- />
- )}
- <Tooltip title={disabledReason}>
- <button
- type="button"
- onClick={() => !disabledReason && onStepClick(step.key)}
- aria-disabled={!!disabledReason}
- data-attr={`vision-editor-step-${step.key}`}
- className={cn(
- 'group flex items-center gap-1.5 px-2 py-1 rounded transition-all duration-150',
- 'focus:outline-none focus-visible:ring-1 focus-visible:ring-accent',
- disabledReason
- ? 'opacity-50 cursor-default'
- : 'hover:bg-fill-button-tertiary-hover active:scale-[0.98]'
- )}
- aria-current={isCurrent ? 'step' : undefined}
- >
- {/* Errors outrank the completed checkmark. */}
- {hasErrors ? (
- <Tooltip title="This step has errors to fix">
- <IconWarning className="size-5 text-warning" />
- </Tooltip>
- ) : isCompleted ? (
- <IconCheckCircle className="size-5 text-success" />
- ) : (
- <span
- className={cn(
- 'flex items-center justify-center size-5 rounded-full text-xs font-semibold',
- 'transition-all duration-150',
- isCurrent && 'bg-accent text-primary-inverse ring-2 ring-accent/25',
- !isCurrent && 'bg-surface-secondary text-secondary border border-primary'
- )}
- >
- {index + 1}
- </span>
- )}
- <span
- className={cn(
- 'text-sm transition-colors duration-150',
- isCurrent && 'font-semibold text-primary',
- isCompleted && 'font-medium text-primary',
- !isCompleted && !isCurrent && 'text-secondary'
- )}
- >
- {step.label}
- </span>
- </button>
- </Tooltip>
- </div>
- )
- })}
- </nav>
- )
-}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index c8cbe43f35de..221a85a9fdd3 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -80,8 +80,10 @@ import { ReplayScannerTab } from './replayScannerSceneLogic'
import { clearScannerDraft, readScannerDraft, writeScannerDraft } from './scannerDraft'
import {
SCANNER_EDITOR_STEPS,
+ ScannerEditorStep,
firstErroredScannerStep,
scannerEditorSceneLogic,
+ scannerStepErrors,
scannerStepUrl,
scannerStepUrlWithParams,
UNVALIDATED_SCANNER_STEPS,
@@ -417,6 +419,7 @@ export interface replayScannerLogicValues {
scannerValidationErrors: DeepPartialMap<ScannerFormValues, ValidationErrorType>
showScannerErrors: boolean
sidePanelContext: SidePanelSceneContext | null
+ stepErrors: Partial<Record<ScannerEditorStep, string[]>>
tagSuggestions: TagSuggestionApi[]
tagSuggestionsLoading: boolean
togglingEnabled: boolean
@@ -747,6 +750,11 @@ export interface replayScannerLogicMeta {
__keaTypeGenInternalSelectorTypes: {
isNew: (id: string) => boolean
durationValidationError: (scanner: ScannerFormValues) => string | null
+ stepErrors: (
+ showScannerErrors: boolean,
+ scannerValidationErrors: DeepPartialMap<ScannerFormValues, ValidationErrorType>,
+ durationValidationError: string | null
+ ) => Partial<Record<ScannerEditorStep, string[]>>
hasUnsavedChanges: (scanner: ScannerFormValues, originalScanner: ScannerFormValues | null) => boolean
hasObservationsInFlight: (observationStatsApi: ObservationStatsApi | null) => boolean
hasActiveObservationFilters: (
@@ -1399,6 +1407,18 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
return durationFilter ? durationFilterError(clampDurationFilter(durationFilter)) : null
},
],
+ // Stepper badges show errors only after a failed submit; until then every step reads clean.
+ stepErrors: [
+ (s) => [s.showScannerErrors, s.scannerValidationErrors, s.durationValidationError],
+ (
+ showScannerErrors: boolean,
+ scannerValidationErrors: DeepPartialMap<ScannerFormValues, ValidationErrorType>,
+ durationValidationError: string | null
+ ): Partial<Record<ScannerEditorStep, string[]>> =>
+ showScannerErrors
+ ? scannerStepErrors({ ...scannerValidationErrors, duration: durationValidationError })
+ : {},
+ ],
hasUnsavedChanges: [
(s) => [s.scanner, s.originalScanner],
(scanner: ReplayScanner | null, original: ReplayScanner | null): boolean => {
diff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts
index ccddb3d33e09..421c3f1b9771 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts
@@ -5,7 +5,7 @@ import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
-import { firstErroredScannerStep, scannerEditorSceneLogic } from './scannerEditorSceneLogic'
+import { firstErroredScannerStep, scannerEditorSceneLogic, scannerStepErrors } from './scannerEditorSceneLogic'
describe('firstErroredScannerStep', () => {
it.each([
@@ -18,6 +18,25 @@ describe('firstErroredScannerStep', () => {
})
})
+describe('scannerStepErrors', () => {
+ it('carries the field-level messages through to each step', () => {
+ expect(
+ scannerStepErrors({
+ scanner_config: { prompt: 'Prompt is required' },
+ sampling_rate: 'Sampling rate must be between 0% and 100%',
+ duration: 'Duration filters above 1 hour match nothing',
+ })
+ ).toEqual({
+ template: [],
+ overview: [],
+ details: [],
+ configure: ['Prompt is required'],
+ triggers: ['Duration filters above 1 hour match nothing'],
+ budget: ['Sampling rate must be between 0% and 100%'],
+ })
+ })
+})
+
describe('scannerEditorSceneLogic', () => {
let logic: ReturnType<typeof scannerEditorSceneLogic.build>
diff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts
index cd93985dfa1c..646b9a7cab84 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts
@@ -1,6 +1,7 @@
import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'
import { combineUrl, router, urlToAction } from 'kea-router'
+import { GuidedWizardStep } from 'lib/components/GuidedWizard/GuidedWizardStepper'
import { urls } from 'scenes/urls'
import { tagsModel } from '~/models/tagsModel'
@@ -34,6 +35,13 @@ export const STEP_LABELS: Record<ScannerEditorStep, string> = {
budget: 'Budget',
}
+export const SCANNER_STEPPER_STEPS: GuidedWizardStep<ScannerEditorStep>[] = SCANNER_EDITOR_STEPS.map((step) => ({
+ step,
+ label: STEP_LABELS[step],
+ // pinned: data-attr for autocapture, renaming breaks dashboards
+ dataAttr: `vision-editor-step-${step}`,
+}))
+
export interface ScannerFieldErrors {
scanner_config?: unknown
sampling_rate?: unknown
@@ -44,22 +52,39 @@ export interface ScannerFieldErrors {
/** Steps that mount no validated field, so leaving them must not run whole-form validation. */
export const UNVALIDATED_SCANNER_STEPS: readonly ScannerEditorStep[] = ['template', 'details']
+// Fallback for error shapes that carry no message, so an errored step is never silently clean
+function fieldErrorMessages(error: unknown): string[] {
+ if (!error) {
+ return []
+ }
+ if (typeof error === 'string') {
+ return [error]
+ }
+ if (typeof error === 'object') {
+ const nested = Object.values(error).flatMap((value) => fieldErrorMessages(value))
+ if (nested.length > 0) {
+ return nested
+ }
+ }
+ return ['This step has errors to fix']
+}
+
/** Which step mounts each validated field. The stepper badges and the post-submit jump both read this. */
-export function scannerStepErrors(errors: ScannerFieldErrors): Record<ScannerEditorStep, boolean> {
+export function scannerStepErrors(errors: ScannerFieldErrors): Record<ScannerEditorStep, string[]> {
return {
- template: false,
- overview: false,
- details: false,
- configure: !!errors.scanner_config,
- triggers: !!errors.duration,
- budget: !!(errors.sampling_rate || errors.credit_limit),
+ template: [],
+ overview: [],
+ details: [],
+ configure: fieldErrorMessages(errors.scanner_config),
+ triggers: fieldErrorMessages(errors.duration),
+ budget: [...fieldErrorMessages(errors.sampling_rate), ...fieldErrorMessages(errors.credit_limit)],
}
}
/** Earliest step rendering an errored field, so a failed submit lands where the user can fix it. */
export function firstErroredScannerStep(errors: ScannerFieldErrors): ScannerEditorStep | null {
const stepErrors = scannerStepErrors(errors)
- return SCANNER_EDITOR_STEPS.find((step) => stepErrors[step]) ?? null
+ return SCANNER_EDITOR_STEPS.find((step) => stepErrors[step].length > 0) ?? null
}
/**