: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, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
import api, { PaginatedResponse } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { uuid } from 'lib/utils/dom'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { addProductIntent } from 'lib/utils/product-intents'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { deleteFromTree } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import {
Breadcrumb,
ProductTour,
ProductTourButtonAction,
ProductTourContent,
ProductTourDisplayFrequency,
ProductTourStepButton,
ProductTourStepButtons,
ProgressStatus,
SurveyPosition,
} from '~/types'
import { getExplainerStepContent } from './stepUtils'
export const BUTTON_ACTION_OPTIONS: { value: ProductTourButtonAction; label: string }[] = [
{ value: 'dismiss', label: 'Dismiss' },
{ value: 'link', label: 'Open link' },
{ value: 'trigger_tour', label: 'Start tour' },
]
export const TOUR_BUTTON_ACTION_OPTIONS: { value: ProductTourButtonAction; label: string }[] = [
{ value: 'next_step', label: 'Next step' },
{ value: 'previous_step', label: 'Previous step' },
...BUTTON_ACTION_OPTIONS,
]
export const DEFAULT_PRIMARY_BUTTON: ProductTourStepButton = {
text: 'Got it',
action: 'dismiss',
}
export const DEFAULT_SECONDARY_BUTTON: ProductTourStepButton = {
text: 'Learn more',
action: 'link',
link: '',
}
interface ProductTourDisplayFrequencyOption {
value: ProductTourDisplayFrequency
label: string
tooltip?: string
}
export const BANNER_DISPLAY_FREQUENCY_OPTIONS: ProductTourDisplayFrequencyOption[] = [
{
value: 'until_interacted',
label: 'Until interacted',
tooltip: 'Shows until user dismisses or interacts',
},
{
value: 'always',
label: 'Always',
tooltip: 'Always shows when the rest of your conditions are met. Hides dismiss button.',
},
]
export const ANNOUNCEMENT_DISPLAY_FREQUENCY_OPTIONS: ProductTourDisplayFrequencyOption[] = [
{ value: 'show_once', label: 'Once', tooltip: "Shows once per user, even if they don't interact" },
{
value: 'until_interacted',
label: 'Until interacted',
tooltip: 'Shows repeatedly until user clicks a button or dismisses',
},
]
export function getDisplayFrequencyOptions(tour: Pick<ProductTour, 'content'>): ProductTourDisplayFrequencyOption[] {
if (isBannerAnnouncement(tour)) {
return BANNER_DISPLAY_FREQUENCY_OPTIONS
}
if (isAnnouncement(tour)) {
return ANNOUNCEMENT_DISPLAY_FREQUENCY_OPTIONS
}
return []
}
export function getDefaultDisplayFrequency(tour: Pick<ProductTour, 'content'>): ProductTourDisplayFrequencyOption {
const options = getDisplayFrequencyOptions(tour)
if (options.length === 0) {
throw new Error(`No defaults found for tour type ${tour.content?.type}`)
}
return options[0]
}
export function getDefaultTourStepButtons(stepIndex: number, totalSteps: number): ProductTourStepButtons {
const isFirstStep = stepIndex === 0
const isLastStep = stepIndex === totalSteps - 1
return {
primary: {
text: isLastStep ? 'Done' : 'Next',
action: 'next_step',
},
...(isFirstStep
? {}
: {
secondary: {
text: 'Back',
action: 'previous_step',
},
}),
}
}
function createDefaultAnnouncementContent(): ProductTourContent {
return {
type: 'announcement',
steps: [
{
id: uuid(),
type: 'modal',
content: {
type: 'doc',
content: [
{
type: 'heading',
attrs: { level: 2 },
content: [{ type: 'text', text: 'Your announcement title' }],
},
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Add your message here. You can use rich text formatting, images, and more.',
},
],
},
],
},
buttons: {
primary: DEFAULT_PRIMARY_BUTTON,
},
modalPosition: SurveyPosition.MiddleCenter,
},
],
appearance: {
showOverlay: false,
dismissOnClickOutside: false,
},
displayFrequency: 'show_once',
}
}
function createDefaultBannerContent(): ProductTourContent {
return {
type: 'announcement',
steps: [
{
id: uuid(),
type: 'banner',
content: {
type: 'doc',
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Your banner message here. Keep it short and actionable.',
},
],
},
],
},
bannerConfig: {
behavior: 'sticky',
action: {
type: 'none',
},
animation: {
duration: 300,
},
},
},
],
appearance: {
showOverlay: false,
dismissOnClickOutside: false,
whiteLabel: true, // banners simply have no branding
},
displayFrequency: 'until_interacted',
}
}
export function createDefaultTourContent(): ProductTourContent {
return {
type: 'tour',
steps: [
{
id: uuid(),
type: 'modal',
content: getExplainerStepContent(),
},
],
appearance: {
showOverlay: true,
dismissOnClickOutside: true,
},
}
}
export enum ProductToursTabs {
Active = 'active',
Archived = 'archived',
}
export function getProductTourStatus(tour: Pick<ProductTour, 'start_date' | 'end_date'>): ProgressStatus {
if (!tour.start_date) {
return ProgressStatus.Draft
} else if (!tour.end_date) {
return ProgressStatus.Running
}
return ProgressStatus.Complete
}
export function isProductTourRunning(tour: Pick<ProductTour, 'start_date' | 'end_date'>): boolean {
return getProductTourStatus(tour) === ProgressStatus.Running
}
export function isAnnouncement(tour: Pick<ProductTour, 'content'>): boolean {
return tour.content?.type === 'announcement'
}
export function isBannerAnnouncement(tour: Pick<ProductTour, 'content'>): boolean {
return isAnnouncement(tour) && tour.content?.steps?.[0]?.type === 'banner'
}
export interface ProductToursFilters {
archived: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productToursLogicValues {
breadcrumbs: Breadcrumb[]
creating: boolean
duplicatedProductTour: ProductTour | null
duplicatedProductTourLoading: boolean
filteredProductTours: ProductTour[]
filters: ProductToursFilters
productTours: ProductTour[]
productToursLoading: boolean
searchTerm: string
tab: ProductToursTabs
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productToursLogicActions {
reportProductTourCreated: (
tour: ProductTour,
creationSource?: 'app' | 'toolbar' | undefined
) => {
creationSource: 'app' | 'toolbar' | undefined
tour: ProductTour
} // eventUsageLogic
reportProductTourListViewed: () => {
value: true
} // eventUsageLogic
createAnnouncement: (name: string) => {
name: string
}
createBanner: (name: string) => {
name: string
}
createTour: (name: string) => {
name: string
}
deleteProductTour: (id: string) => string
deleteProductTourFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
deleteProductTourSuccess: (
productTours: ProductTour[],
payload?: string
) => {
productTours: ProductTour[]
payload?: string
}
duplicateProductTour: (tour: ProductTour) => ProductTour
duplicateProductTourFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
duplicateProductTourSuccess: (
duplicatedProductTour: ProductTour | null,
payload?: ProductTour
) => {
duplicatedProductTour: ProductTour | null
payload?: ProductTour
}
loadProductTours: () => any
loadProductToursFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadProductToursSuccess: (
productTours: ProductTour[],
payload?: any
) => {
productTours: ProductTour[]
payload?: any
}
setCreating: (creating: boolean) => {
creating: boolean
}
setFilters: (filters: Partial<ProductToursFilters>) => {
filters: Partial<ProductToursFilters>
}
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
setTab: (tab: ProductToursTabs) => {
tab: ProductToursTabs
}
updateProductTour: ({ id, updatePayload }: { id: string; updatePayload: Partial<ProductTour> }) => {
id: string
updatePayload: Partial<ProductTour>
}
updateProductTourFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
updateProductTourSuccess: (
productTours: ProductTour[],
payload?: {
id: string
updatePayload: Partial<ProductTour>
}
) => {
productTours: ProductTour[]
payload?: {
id: string
updatePayload: Partial<ProductTour>
}
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productToursLogicMeta {
__keaTypeGenInternalSelectorTypes: {
filteredProductTours: (productTours: ProductTour[], filters: ProductToursFilters) => ProductTour[]
}
}
export type productToursLogicType = MakeLogicType<
productToursLogicValues,
productToursLogicActions,
Record<string, any>,
productToursLogicMeta
>
export const productToursLogic = kea<productToursLogicType>([
path(['scenes', 'product-tours', 'productToursLogic']),
connect(() => ({
actions: [eventUsageLogic, ['reportProductTourCreated', 'reportProductTourListViewed']],
})),
actions({
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setFilters: (filters: Partial<ProductToursFilters>) => ({ filters }),
setTab: (tab: ProductToursTabs) => ({ tab }),
createAnnouncement: (name: string) => ({ name }),
createBanner: (name: string) => ({ name }),
createTour: (name: string) => ({ name }),
setCreating: (creating: boolean) => ({ creating }),
}),
loaders(({ values, actions }) => ({
productTours: {
__default: [] as ProductTour[],
loadProductTours: async () => {
const search = values.searchTerm?.trim() || undefined
const response: PaginatedResponse<ProductTour> = await api.productTours.list({ search })
return response.results
},
deleteProductTour: async (id: string) => {
await api.productTours.delete(id)
deleteFromTree('product_tour', id)
lemonToast.success('Product tour deleted')
return values.productTours.filter((t: ProductTour) => t.id !== id)
},
updateProductTour: async ({ id, updatePayload }: { id: string; updatePayload: Partial<ProductTour> }) => {
const updatedTour = await api.productTours.update(id, updatePayload)
lemonToast.success('Product tour updated')
return values.productTours.map((t: ProductTour) => (t.id === id ? updatedTour : t))
},
},
duplicatedProductTour: {
__default: null as ProductTour | null,
duplicateProductTour: async (tour: ProductTour) => {
const duplicatedContent: ProductTourContent = {
...tour.content,
steps: (tour.content?.steps ?? []).map((step) => ({
...step,
id: uuid(),
})),
}
try {
const createdTour = await api.productTours.create({
name: `${tour.name} (copy ${dayjs().format('YYYY-MM-DD HH:mm:ss')})`,
description: tour.description,
content: duplicatedContent,
targeting_flag_filters: tour.targeting_flag_filters,
linked_flag_id: tour.linked_flag_id,
auto_launch: tour.auto_launch,
})
lemonToast.success('Product tour duplicated', {
toastId: `product-tour-duplicated-${createdTour.id}`,
button: {
label: 'View tour',
action: () => {
router.actions.push(urls.productTour(createdTour.id))
},
},
})
actions.loadProductTours()
return createdTour
} catch {
lemonToast.error('Error duplicating Product tour')
return null
}
},
},
})),
reducers({
tab: [
ProductToursTabs.Active as ProductToursTabs,
{
setTab: (_, { tab }) => tab,
},
],
searchTerm: [
'' as string,
{
setSearchTerm: (_, { searchTerm }) => searchTerm,
},
],
filters: [
{ archived: false } as ProductToursFilters,
{
setFilters: (state, { filters }) => ({ ...state, ...filters }),
},
],
// Every create route lands on the editor, so a second click before the first
// response would leave a stray tour behind.
creating: [
false,
{
setCreating: (_, { creating }) => creating,
},
],
}),
listeners(({ actions, values }) => ({
setSearchTerm: async (_, breakpoint) => {
await breakpoint(250)
actions.loadProductTours()
},
setTab: ({ tab }) => {
actions.setFilters({ archived: tab === ProductToursTabs.Archived })
},
deleteProductTourSuccess: () => {
router.actions.push(urls.productTours())
},
createAnnouncement: async ({ name }) => {
if (values.creating) {
return
}
actions.setCreating(true)
try {
const announcement = await api.productTours.create({
name,
content: createDefaultAnnouncementContent(),
})
void addProductIntent({
product_type: ProductKey.PRODUCT_TOURS,
intent_context: ProductIntentContext.PRODUCT_TOUR_CREATED,
})
actions.reportProductTourCreated(announcement, 'app')
actions.loadProductTours()
router.actions.push(urls.productTour(announcement.id, 'edit=true'))
} catch {
lemonToast.error('Failed to create announcement')
} finally {
actions.setCreating(false)
}
},
createBanner: async ({ name }) => {
if (values.creating) {
return
}
actions.setCreating(true)
try {
const banner = await api.productTours.create({
name,
content: createDefaultBannerContent(),
})
void addProductIntent({
product_type: ProductKey.PRODUCT_TOURS,
intent_context: ProductIntentContext.PRODUCT_TOUR_CREATED,
})
actions.reportProductTourCreated(banner, 'app')
actions.loadProductTours()
router.actions.push(urls.productTour(banner.id, 'edit=true'))
} catch {
lemonToast.error('Failed to create banner')
} finally {
actions.setCreating(false)
}
},
createTour: async ({ name }) => {
if (values.creating) {
return
}
actions.setCreating(true)
try {
const tour = await api.productTours.create({
name,
content: createDefaultTourContent(),
})
void addProductIntent({
product_type: ProductKey.PRODUCT_TOURS,
intent_context: ProductIntentContext.PRODUCT_TOUR_CREATED,
})
actions.reportProductTourCreated(tour, 'app')
actions.loadProductTours()
router.actions.push(urls.productTour(tour.id, 'edit=true'))
} catch {
lemonToast.error('Failed to create tour')
} finally {
actions.setCreating(false)
}
},
loadProductToursSuccess: () => {
actions.reportProductTourListViewed()
},
})),
selectors({
filteredProductTours: [
(s) => [s.productTours, s.filters],
(productTours: ProductTour[], filters: ProductToursFilters) => {
if (filters.archived) {
return productTours.filter((tour: ProductTour) => tour.archived)
}
return productTours.filter((tour: ProductTour) => !tour.archived)
},
],
breadcrumbs: [
() => [],
(): Breadcrumb[] => [
{
key: Scene.ProductTours,
name: sceneConfigurations[Scene.ProductTours].name || 'Product tours',
path: urls.productTours(),
},
],
],
}),
actionToUrl(({ values }) => ({
setTab: () => {
return [router.values.location.pathname, { ...router.values.searchParams, tab: values.tab }]
},
})),
urlToAction(({ actions }) => ({
[urls.productTours()]: (_, { tab }) => {
if (tab) {
actions.setTab(tab as ProductToursTabs)
}
},
})),
afterMount(({ actions }) => {
actions.loadProductTours()
}),
])