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.

9.5 KB
Raw Blame
import { MakeLogicType, actions, afterMount, 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 type { ActionForm } from '~/toolbar/shared/types'

import { capturePageToolUsed } from '../../browser/extensionTelemetry'
import { PageFormSync } from '../../messaging/pageFormSync'
import type { PageToolbarActionsState, PageToolbarState } from '../../messaging/pageToolbarBridge'
import type { PageActionsCommand } from '../page/extensionPageActionsLogic'
import { extensionPageToolbarConnectionLogic } from './extensionPageToolbarConnectionLogic'

const EMPTY_ACTION_FORM = { name: null, steps: [{}] } as ActionForm

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionActionsLogicValues {
    pageToolbarState: PageToolbarState | null // extensionPageToolbarConnectionLogic
    actionForm: ActionForm
    actionFormAllErrors: Record<string, any>
    actionFormChanged: boolean
    actionFormErrors: DeepPartialMap<ActionForm, ValidationErrorType>
    actionFormHasErrors: boolean
    actionFormManualErrors: Record<string, any>
    actionFormTouched: boolean
    actionFormTouches: Record<string, boolean>
    actionFormValidationErrors: DeepPartialMap<ActionForm, ValidationErrorType>
    actionsState: PageToolbarActionsState | null
    editingSelector: number | null
    filteredActions: PageToolbarActionsState['actions']
    isActionFormSubmitting: boolean
    isActionFormValid: boolean
    saveRequested: boolean
    saving: boolean
    searchTerm: string
    showActionFormErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionActionsLogicActions {
    sendCommand: (message: import('../../messaging/pageToolbarBridge').PageToolbarCommand) => {
        message: import('../../messaging/pageToolbarBridge').PageToolbarCommand
    } // extensionPageToolbarConnectionLogic
    applySelector: (
        index: number,
        selector: string
    ) => {
        index: number
        selector: string
    }
    inspectForStep: (index: number | null) => {
        index: number | null
    }
    newAction: (fromSelectedElement: boolean) => {
        fromSelectedElement: boolean
    }
    resetActionForm: (values?: ActionForm) => {
        values?: ActionForm
    }
    selectAction: (id: number | null) => {
        id: number | null
    }
    sendActionsCommand: (command: PageActionsCommand) => {
        command: PageActionsCommand
    }
    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>
    }
    setEditingSelector: (index: number | null) => {
        index: number | null
    }
    setSaveRequested: (saveRequested: boolean) => {
        saveRequested: boolean
    }
    setSearchTerm: (searchTerm: string) => {
        searchTerm: string
    }
    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 extensionActionsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        actionsState: (pageToolbarState: PageToolbarState | null) => PageToolbarActionsState | null
        filteredActions: (
            actionsState: PageToolbarActionsState | null,
            searchTerm: string
        ) => PageToolbarActionsState['actions']
        saving: (actionsState: PageToolbarActionsState | null, saveRequested: boolean) => boolean
    }
}

export type extensionActionsLogicType = MakeLogicType<
    extensionActionsLogicValues,
    extensionActionsLogicActions,
    Record<string, any>,
    extensionActionsLogicMeta
>

/** The panel side of the actions tool. The page runs the toolbar's actions logics, the panel edits its own copy of the form. */
export const extensionActionsLogic = kea<extensionActionsLogicType>([
    path(['toolbar', 'extension', 'extensionActionsLogic']),
    connect(() => ({
        values: [extensionPageToolbarConnectionLogic, ['pageToolbarState']],
        actions: [extensionPageToolbarConnectionLogic, ['sendCommand']],
    })),
    actions({
        setSearchTerm: (searchTerm: string) => ({ searchTerm }),
        sendActionsCommand: (command: PageActionsCommand) => ({ command }),
        selectAction: (id: number | null) => ({ id }),
        newAction: (fromSelectedElement: boolean) => ({ fromSelectedElement }),
        inspectForStep: (index: number | null) => ({ index }),
        setEditingSelector: (index: number | null) => ({ index }),
        applySelector: (index: number, selector: string) => ({ index, selector }),
        setSaveRequested: (saveRequested: boolean) => ({ saveRequested }),
    }),
    forms(({ actions }) => ({
        actionForm: {
            defaults: EMPTY_ACTION_FORM,
            errors: ({ name }) => ({
                name: !name || !name.length ? 'Must name this action' : undefined,
            }),
            submit: () => {
                actions.sendActionsCommand({ type: 'save-action' })
                capturePageToolUsed('save-action')
            },
            showErrorsOnTouch: true,
        },
    })),
    reducers({
        searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],
        editingSelector: [null as number | null, { setEditingSelector: (_, { index }) => index }],
        // The page takes a moment to report that it started saving, so the button waits from the click.
        saveRequested: [
            false,
            {
                submitActionForm: () => true,
                // kea-forms fails the submit without calling submit when validation fails.
                submitActionFormFailure: () => false,
                setSaveRequested: (_, { saveRequested }) => saveRequested,
            },
        ],
    }),
    selectors({
        actionsState: [
            (s) => [s.pageToolbarState],
            (pageToolbarState: PageToolbarState | null): PageToolbarActionsState | null =>
                pageToolbarState?.actions ?? null,
        ],
        filteredActions: [
            (s) => [s.actionsState, s.searchTerm],
            (actionsState: PageToolbarActionsState | null, searchTerm: string): PageToolbarActionsState['actions'] =>
                (actionsState?.actions ?? []).filter(({ name }) =>
                    (name ?? '').toLowerCase().includes(searchTerm.trim().toLowerCase())
                ),
        ],
        saving: [
            (s) => [s.actionsState, s.saveRequested],
            (actionsState: PageToolbarActionsState | null, saveRequested: boolean): boolean =>
                saveRequested || !!actionsState?.saving,
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        sendActionsCommand: ({ command }) => {
            // Every command can make the page change the form, so the page gets the user's edits first.
            if (command.type !== 'set-action-form') {
                cache.formSync.flush()
            }
            actions.sendCommand({ tool: 'actions', command })
        },
        setActionFormValue: () => cache.formSync.schedule(),
        setActionFormValues: () => cache.formSync.schedule(),
        selectAction: ({ id }) => actions.sendActionsCommand({ type: 'select-action', id }),
        newAction: ({ fromSelectedElement }) => {
            actions.sendActionsCommand({ type: 'new-action', fromSelectedElement })
            if (fromSelectedElement) {
                capturePageToolUsed('create-action')
            }
        },
        inspectForStep: ({ index }) => actions.sendActionsCommand({ type: 'inspect-for-action-step', index }),
        applySelector: ({ index, selector }) => {
            actions.setEditingSelector(null)
            const steps = [...(values.actionForm.steps ?? [])]
            if (steps[index]) {
                steps[index] = { ...steps[index], selector }
                actions.setActionFormValue('steps', steps)
            }
        },
    })),
    afterMount(({ actions, values, cache }) => {
        cache.formSync = new PageFormSync(() =>
            actions.sendCommand({ tool: 'actions', command: { type: 'set-action-form', form: values.actionForm } })
        )
        cache.disposables.add(() => () => cache.formSync.cancel(), 'formSync')
    }),
    // Runs after afterMount above, which creates the form sync the first call reads.
    subscriptions(({ actions, values, cache }) => ({
        actionsState: (page: PageToolbarActionsState | null) => {
            if (!page) {
                return
            }
            if (cache.formSync.adopt(page.selectedActionId, page.formRevision)) {
                actions.setEditingSelector(null)
                actions.setSaveRequested(false)
                actions.resetActionForm(page.actionForm)
            } else if (values.saveRequested && !page.saving && page.saveResult) {
                actions.setSaveRequested(false)
            }
        },
    })),
])