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.

21.4 KB
Raw Blame
import { MakeLogicType, actions, connect, 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 { actionsLogic } from '~/toolbar/shared/actions/actionsLogic'
import { toolbarLogic } from '~/toolbar/shared/bar/toolbarLogic'
import { toolbarApi } from '~/toolbar/shared/toolbarApi'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import { toolbarPosthogJS } from '~/toolbar/shared/toolbarPosthogJS'
import { ActionDraftType, ActionForm } from '~/toolbar/shared/types'
import { urls } from '~/toolbar/shared/urls'
import {
    actionStepToActionStepFormItem,
    elementToActionStep,
    joinWithUiHost,
    stepToDatabaseFormat,
} from '~/toolbar/shared/utils'
import { AccessControlLevel, ActionType, ElementType } from '~/types'

import type { ToolbarUserIntent } from '../../../types'
import type { ActionStepPropertyKey } from './ActionStep'

function newAction(
    element: HTMLElement | null,
    dataAttributes: string[] = [],
    name: string | null,
    includedPropertyKeys?: ActionStepPropertyKey[]
): ActionDraftType {
    return {
        name: name || '',
        steps: [
            element
                ? actionStepToActionStepFormItem(
                      elementToActionStep(element, dataAttributes),
                      true,
                      includedPropertyKeys
                  )
                : {},
        ],
        pinned_at: null,
        user_access_level: AccessControlLevel.Editor,
    }
}

function toElementsChain(element: HTMLElement): ElementType[] {
    const chain: HTMLElement[] = []
    let currentElement: HTMLElement | null | undefined = element
    while (currentElement && currentElement !== document.documentElement) {
        chain.push(currentElement)
        currentElement = currentElement.parentElement
    }
    return chain.map(
        (element, index) =>
            ({
                attr_class: element.getAttribute('class')?.split(' '),
                attr_id: element.getAttribute('id') || undefined,

                attributes: Array.from(element.attributes).reduce(
                    (acc, attr) => {
                        if (!acc[attr.name]) {
                            acc[attr.name] = attr.value
                        } else {
                            acc[attr.name] += ` ${attr.value}`
                        }
                        return acc
                    },
                    {} as Record<string, string>
                ),

                href: element.getAttribute('href') || undefined,
                tag_name: element.tagName.toLowerCase(),
                text: index === 0 ? element.innerText : undefined,
            }) as ElementType
    )
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface actionsTabLogicValues {
    allActions: ActionType[] // actionsLogic
    actionId: number | null // toolbarConfigLogic
    buttonVisible: boolean // toolbarConfigLogic
    dataAttributes: string[] // toolbarConfigLogic
    uiHost: string // toolbarConfigLogic
    userIntent: ToolbarUserIntent | null // toolbarConfigLogic
    actionForm: ActionForm
    actionFormAllErrors: Record<string, any>
    actionFormChanged: boolean
    actionFormElementsChains: Record<number, ElementType[]>
    actionFormErrors: DeepPartialMap<ActionForm, ValidationErrorType>
    actionFormHasErrors: boolean
    actionFormManualErrors: Record<string, any>
    actionFormTouched: boolean
    actionFormTouches: Record<string, boolean>
    actionFormValidationErrors: DeepPartialMap<ActionForm, ValidationErrorType>
    automaticActionCreationEnabled: boolean
    automaticCreationIncludedPropertyKeys: ActionStepPropertyKey[]
    buttonActionsVisible: boolean
    counter: number
    editingSelector: number | null
    editingSelectorValue: string | null
    elementsChainBeingEdited: ElementType[]
    inspectingElement: number | null
    isActionFormSubmitting: boolean
    isActionFormValid: boolean
    isReadyForAutomaticSubmit: boolean
    newActionForElement: HTMLElement | null
    newActionName: string | null
    selectedAction: ActionDraftType | ActionType | null
    selectedActionId: number | 'new' | null
    showActionFormErrors: boolean
    showActionsTooltip: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface actionsTabLogicActions {
    actionCreatedSuccess: (action: ActionType) => {
        action: ActionType
    }
    addAutomaticCreationIncludedPropertyKey: (key: ActionStepPropertyKey) => {
        key: ActionStepPropertyKey
    }
    editSelectorWithIndex: (index: number | null) => {
        index: number | null
    }
    hideButtonActions: () => {
        value: true
    }
    incrementCounter: () => {
        value: true
    }
    inspectElementSelected: (
        element: HTMLElement,
        index: number | null
    ) => {
        element: HTMLElement
        index: number | null
    }
    inspectForElementWithIndex: (index: number | null) => {
        index: number | null
    }
    newAction: (element?: HTMLElement) => {
        element: HTMLElement | null
    }
    removeAutomaticCreationIncludedPropertyKey: (key: ActionStepPropertyKey) => {
        key: ActionStepPropertyKey
    }
    resetActionForm: (values?: ActionForm) => {
        values?: ActionForm
    }
    saveAction: (formValues: ActionForm) => {
        formValues: ActionForm
    }
    selectAction: (id: number | null) => {
        id: number | null
    }
    setActionFormManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setActionFormValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setActionFormValues: (values: DeepPartial<ActionForm>) => {
        values: DeepPartial<ActionForm>
    }
    setAutomaticActionCreationEnabled: (
        enabled: boolean,
        name?: string
    ) => {
        enabled: boolean
        name: string | undefined
    }
    setElementSelector: (
        selector: string,
        index: number
    ) => {
        index: number
        selector: string
    }
    setShowActionsTooltip: (showActionsTooltip: boolean) => {
        showActionsTooltip: boolean
    }
    setautomaticCreationIncludedPropertyKeys: (keys: ActionStepPropertyKey[]) => {
        keys: ActionStepPropertyKey[]
    }
    showButtonActions: () => {
        value: true
    }
    submitActionForm: () => {
        value: boolean
    }
    submitActionFormFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitActionFormRequest: (actionForm: ActionForm) => {
        actionForm: ActionForm
    }
    submitActionFormSuccess: (actionForm: ActionForm) => {
        actionForm: ActionForm
    }
    touchActionFormField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface actionsTabLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        editingSelectorValue: (editingSelector: number | null, actionForm: ActionForm) => string | null
        elementsChainBeingEdited: (
            editingSelector: number | null,
            actionFormElementsChains: Record<number, ElementType[]>
        ) => ElementType[]
        selectedAction: (
            selectedActionId: number | 'new' | null,
            newActionForElement: HTMLElement | null,
            allActions: ActionType[],
            dataAttributes: string[],
            newActionName: string | null,
            automaticCreationIncludedPropertyKeys: ActionStepPropertyKey[]
        ) => ActionDraftType | ActionType | null
        isReadyForAutomaticSubmit: (
            automaticActionCreationEnabled: boolean,
            selectedAction: ActionDraftType | ActionType | null,
            actionForm: ActionForm
        ) => boolean
    }
}

export type actionsTabLogicType = MakeLogicType<
    actionsTabLogicValues,
    actionsTabLogicActions,
    Record<string, any>,
    actionsTabLogicMeta
>

export const actionsTabLogic = kea<actionsTabLogicType>([
    path(['toolbar', 'actions', 'actionsTabLogic']),
    actions({
        selectAction: (id: number | null) => ({ id: id || null }),
        newAction: (element?: HTMLElement) => ({
            element: element || null,
        }),
        inspectForElementWithIndex: (index: number | null) => ({ index }),
        editSelectorWithIndex: (index: number | null) => ({ index }),
        inspectElementSelected: (element: HTMLElement, index: number | null) => ({ element, index }),
        incrementCounter: true,
        saveAction: (formValues: ActionForm) => ({ formValues }),
        showButtonActions: true,
        hideButtonActions: true,
        setShowActionsTooltip: (showActionsTooltip: boolean) => ({ showActionsTooltip }),
        setElementSelector: (selector: string, index: number) => ({ selector, index }),
        setAutomaticActionCreationEnabled: (enabled: boolean, name?: string) => ({ enabled, name }),
        actionCreatedSuccess: (action: ActionType) => ({ action }),
        setautomaticCreationIncludedPropertyKeys: (keys: ActionStepPropertyKey[]) => ({ keys }),
        removeAutomaticCreationIncludedPropertyKey: (key: ActionStepPropertyKey) => ({ key }),
        addAutomaticCreationIncludedPropertyKey: (key: ActionStepPropertyKey) => ({ key }),
    }),

    connect(() => ({
        values: [
            toolbarConfigLogic,
            ['dataAttributes', 'uiHost', 'buttonVisible', 'userIntent', 'actionId'],
            actionsLogic,
            ['allActions'],
        ],
    })),

    reducers({
        actionFormElementsChains: [
            {} as Record<number, ElementType[]>,
            {
                inspectElementSelected: (state, { element, index }) =>
                    index === null
                        ? []
                        : {
                              ...state,
                              [index]: toElementsChain(element),
                          },
                newAction: (_, { element }) => ({
                    0: element ? toElementsChain(element) : [],
                }),
            },
        ],
        buttonActionsVisible: [
            false,
            {
                showButtonActions: () => true,
                hideButtonActions: () => false,
            },
        ],
        selectedActionId: [
            null as number | 'new' | null,
            {
                selectAction: (_, { id }) => id,
                newAction: () => 'new',
            },
        ],
        newActionForElement: [
            null as HTMLElement | null,
            {
                newAction: (_, { element }) => element,
                selectAction: () => null,
            },
        ],
        inspectingElement: [
            null as number | null,
            {
                inspectForElementWithIndex: (_, { index }) => index,
                inspectElementSelected: () => null,
                selectAction: () => null,
                newAction: () => null,
            },
        ],
        editingSelector: [
            null as number | null,
            {
                editSelectorWithIndex: (_, { index }) => index,
            },
        ],
        counter: [
            0,
            {
                incrementCounter: (state) => state + 1,
            },
        ],
        showActionsTooltip: [
            false,
            {
                setShowActionsTooltip: (_, { showActionsTooltip }) => showActionsTooltip,
            },
        ],
        // we automatically create actions for people from analytics onboarding. This flag controls that experience.
        automaticActionCreationEnabled: [
            false as boolean,
            {
                setAutomaticActionCreationEnabled: (_, { enabled, name }) => (enabled && !!name) || false,
            },
        ],
        newActionName: [
            null as string | null,
            {
                setAutomaticActionCreationEnabled: (_, { enabled, name }) => (enabled && name ? name : null),
            },
        ],
        automaticCreationIncludedPropertyKeys: [
            [] as ActionStepPropertyKey[],
            {
                setAutomaticActionCreationEnabled: (_, { enabled }) =>
                    enabled ? ['text', 'href', 'name', 'selector', 'url'] : [],
                setautomaticCreationIncludedPropertyKeys: (_, { keys }) => keys || [],
                removeAutomaticCreationIncludedPropertyKey: (state, { key }) => state.filter((k) => k !== key),
                addAutomaticCreationIncludedPropertyKey: (state, { key }) =>
                    !state.includes(key) ? [...state, key] : state,
            },
        ],
    }),

    forms(({ values, actions }) => ({
        actionForm: {
            defaults: { name: null, steps: [{}] } as ActionForm,
            errors: ({ name }) => ({
                name: !name || !name.length ? 'Must name this action' : undefined,
            }),
            submit: async (formValues, breakpoint) => {
                const actionToSave = {
                    ...formValues,
                    steps: formValues.steps?.map(stepToDatabaseFormat) || [],
                    creation_context: values.automaticActionCreationEnabled ? 'onboarding' : null,
                }
                const { selectedActionId } = values

                const findUniqueActionName = (baseName: string, index = 0): string => {
                    const proposedName = index === 0 ? baseName : `${baseName} - ${index}`
                    if (!values.allActions.find((action) => action.name === proposedName)) {
                        return proposedName
                    }
                    return findUniqueActionName(baseName, index + 1)
                }

                if (values.newActionName) {
                    actionToSave.name = findUniqueActionName(values.newActionName)
                }

                const isUpdate = selectedActionId && selectedActionId !== 'new'
                const result = isUpdate
                    ? await toolbarApi.actions.update(selectedActionId, actionToSave, {
                          context: 'save_action',
                          toastOnError: 'Failed to save action',
                      })
                    : await toolbarApi.actions.create(actionToSave, {
                          context: 'save_action',
                          toastOnError: 'Failed to save action',
                      })

                if (!result.ok) {
                    // Throwing makes the form report a failure instead of a successful submit.
                    throw new Error(result.error.detail)
                }
                const response = result.data
                breakpoint() // guard against stale async after unmount

                actions.selectAction(null)
                actionsLogic.actions.updateAction({ action: response })

                if (!values.automaticActionCreationEnabled) {
                    lemonToast.success('Action saved', {
                        button: {
                            label: 'Open in PostHog',
                            action: () =>
                                window.open(joinWithUiHost(values.uiHost, urls.action(response.id)), '_blank'),
                        },
                    })
                }

                actions.actionCreatedSuccess(response)
            },

            // whether we show errors after touch (true) or submit (false)
            showErrorsOnTouch: true,
            // show errors even without submitting first
            alwaysShowErrors: false,
        },
    })),

    selectors({
        editingSelectorValue: [
            (s) => [s.editingSelector, s.actionForm],
            (editingSelector: number | null, actionForm: ActionForm): string | null => {
                if (editingSelector === null) {
                    return null
                }
                const selector = actionForm.steps?.[editingSelector].selector
                return selector || null
            },
        ],
        elementsChainBeingEdited: [
            (s) => [s.editingSelector, s.actionFormElementsChains],
            (editingSelector: number | null, elementChains: Record<number, ElementType[]>): ElementType[] => {
                if (editingSelector === null) {
                    return []
                }
                return elementChains[editingSelector] || []
            },
        ],
        selectedAction: [
            (s) => [
                s.selectedActionId,
                s.newActionForElement,
                s.allActions,
                s.dataAttributes,
                s.newActionName,
                s.automaticCreationIncludedPropertyKeys,
            ],
            (
                selectedActionId: number | 'new' | null,
                newActionForElement: HTMLElement | null,
                allActions: ActionType[],
                dataAttributes: string[],
                newActionName: string | null,
                automaticCreationIncludedPropertyKeys: ActionStepPropertyKey[]
            ): ActionType | ActionDraftType | null => {
                if (selectedActionId === 'new') {
                    return newAction(
                        newActionForElement,
                        dataAttributes,
                        newActionName,
                        automaticCreationIncludedPropertyKeys
                    )
                }
                return allActions.find((a) => a.id === selectedActionId) || null
            },
        ],
        isReadyForAutomaticSubmit: [
            (s) => [s.automaticActionCreationEnabled, s.selectedAction, s.actionForm],
            (
                automaticActionCreationEnabled: boolean,
                selectedAction: ActionDraftType | ActionType | null,
                actionForm: ActionForm
            ): boolean => {
                return (
                    (automaticActionCreationEnabled &&
                        selectedAction?.name &&
                        actionForm.steps?.[0]?.selector_selected) ||
                    false
                )
            },
        ],
    }),

    subscriptions(({ actions, values }) => ({
        selectedAction: (selectedAction: ActionType | ActionDraftType | null) => {
            if (!selectedAction) {
                actions.setActionFormValues({ name: null, steps: [{}] })
            } else {
                actions.setActionFormValues({
                    ...selectedAction,
                    steps: selectedAction.steps
                        ? selectedAction.steps.map((step) => actionStepToActionStepFormItem(step, false))
                        : [{}],
                })
                if (values.isReadyForAutomaticSubmit) {
                    actions.submitActionForm()
                }
            }
        },
    })),

    listeners(({ actions, values }) => ({
        setElementSelector: ({ selector, index }) => {
            if (values.actionForm) {
                const steps = [...(values.actionForm.steps || [])]
                if (steps && steps[index]) {
                    steps[index].selector = selector
                }
                actions.setActionFormValue('steps', steps)
            }
        },
        selectAction: ({ id }) => {
            if (id) {
                if (!values.buttonVisible) {
                    toolbarConfigLogic.actions.showButton()
                }

                if (!values.buttonActionsVisible) {
                    actions.showButtonActions()
                }

                // The browser extension runs this logic without the floating toolbar's bar.
                toolbarLogic.findMounted()?.actions.setVisibleMenu('actions')
            }
        },
        inspectElementSelected: ({ element, index }) => {
            if (values.actionForm) {
                const actionStep = actionStepToActionStepFormItem(
                    elementToActionStep(element, values.dataAttributes),
                    true
                )
                const newSteps = (values.actionForm.steps || []).map((step, i) =>
                    // null index implicitly means "new step front of the list"
                    i === (index ?? 0) ? actionStep : step
                )

                actions.setActionFormValue('steps', newSteps)
                actions.incrementCounter()
            }
        },
        showButtonActions: () => {
            toolbarPosthogJS.capture('toolbar mode triggered', { mode: 'actions', enabled: true })
        },
        hideButtonActions: () => {
            actions.setShowActionsTooltip(false)
            toolbarPosthogJS.capture('toolbar mode triggered', { mode: 'actions', enabled: false })
        },
        [actionsLogic.actionTypes.getActionsSuccess]: () => {
            const { userIntent, actionId } = values
            if (userIntent === 'edit-action') {
                actions.selectAction(actionId)
                toolbarConfigLogic.actions.clearUserIntent()
            } else if (userIntent === 'add-action') {
                actions.newAction()
                toolbarConfigLogic.actions.clearUserIntent()
            } else {
                actions.setShowActionsTooltip(true)
            }
        },
        setShowActionsTooltip: async ({ showActionsTooltip }, breakpoint) => {
            if (showActionsTooltip) {
                await breakpoint(1000)
                actions.setShowActionsTooltip(false)
            }
        },
    })),
])