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.

6.3 KB
Raw Blame
import FuseClass from 'fuse.js'
import { MakeLogicType, actions, kea, key, path, props, reducers, selectors } from 'kea'

import { STL as HOG_STL } from '@posthog/hogvm'

import { createFuse } from 'lib/utils/fuseSearch'

export type CyclotronJobTemplateOption = {
    key: string
    description: string
    example: string
}

export type CyclotronJobTemplateOptionCategory = {
    category: string
    options: CyclotronJobTemplateOption[]
}

export type CyclotronJobTemplateSuggestionsLogicProps = {
    templating: 'hog' | 'liquid'
}

// Helping kea-typegen navigate the exported default class for Fuse
export interface Fuse extends FuseClass<CyclotronJobTemplateOption> {}

const HOG_USAGE_EXAMPLES: CyclotronJobTemplateOption[] = [
    {
        key: 'ternary',
        example: `$1 = true ? 'Yes' : 'No'`,
        description: 'Ternary operation (if this then that else other)',
    },
    {
        key: 'default',
        example: `$1 ?? 'Default value'`,
        description: 'Default value (if this is null or undefined, use this)',
    },
]

const HOG_STL_EXAMPLES: CyclotronJobTemplateOption[] = Object.entries(HOG_STL).map(([key, value]) => ({
    key,
    example: value.example,
    description: value.description,
}))

const LIQUID_USAGE_EXAMPLES: CyclotronJobTemplateOption[] = [
    {
        key: 'property',
        example: `{{ person.properties.email }}`,
        description: 'Access a property of an event or person',
    },
    {
        key: 'workflow variable',
        example: `{{ variables.MY_VARIABLE_KEY }}`,
        description: 'Access a workflow variable set earlier in the workflow',
    },
    {
        key: 'if',
        example: `{% if condition %} Yes {% else %} No {% endif %}`,
        description: 'Conditional (if this then that else other)',
    },
    {
        key: 'date',
        example: `{{ person.properties.signed_up_at | date: '%Y-%m-%d' }}`,
        description: 'Format a timestamp',
    },
    {
        key: 'join',
        example: `{{ 'John, Paul, George, Ringo' | split: ', ' | join: ' and ' }}`,
        description: 'Join an array of values into a string',
    },
    {
        key: 'default',
        example: `{{ person.properties.created_at | default: 'Default value' }}`,
        description: 'Default value (if value is null or undefined, use this)',
    },
]

/**
 * The text a picked suggestion inserts into a field. Hog examples are bare expressions that need
 * delimiters, while liquid examples carry their own, so wrapping every example would produce
 * `{{{ ... }}}`. Every call site goes through here so the two engines can't drift apart again.
 */
export function templateReferenceForOption(option: CyclotronJobTemplateOption, templating: 'hog' | 'liquid'): string {
    const example = option.example.trim()
    const alreadyDelimited = example.startsWith('{') && example.endsWith('}')
    if (alreadyDelimited) {
        return example
    }
    return templating === 'liquid' ? `{{ ${example} }}` : `{${example}}`
}

/**
 * Puts `reference` where the caret last sat. Both a null `cursorOffset` (the caret was never placed
 * in this field) and an offset past the end (the value changed underneath it) fall back to
 * appending.
 */
export function insertTemplateReference(value: string, reference: string, cursorOffset: number | null): string {
    if (cursorOffset === null || cursorOffset < 0 || cursorOffset > value.length) {
        return `${value}${reference}`
    }
    return `${value.slice(0, cursorOffset)}${reference}${value.slice(cursorOffset)}`
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cyclotronJobTemplateSuggestionsLogicValues {
    allOptions: CyclotronJobTemplateOption[]
    optionsFiltered: CyclotronJobTemplateOption[]
    optionsFuse: Fuse
    search: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cyclotronJobTemplateSuggestionsLogicActions {
    setSearch: (search: string) => {
        search: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cyclotronJobTemplateSuggestionsLogicMeta {
    key: 'hog' | 'liquid'
    __keaTypeGenInternalSelectorTypes: {
        allOptions: (templating: 'hog' | 'liquid') => CyclotronJobTemplateOption[]
        optionsFuse: (allOptions: CyclotronJobTemplateOption[]) => Fuse
        optionsFiltered: (
            allOptions: CyclotronJobTemplateOption[],
            optionsFuse: Fuse,
            search: string
        ) => CyclotronJobTemplateOption[]
    }
}

export type cyclotronJobTemplateSuggestionsLogicType = MakeLogicType<
    cyclotronJobTemplateSuggestionsLogicValues,
    cyclotronJobTemplateSuggestionsLogicActions,
    CyclotronJobTemplateSuggestionsLogicProps,
    cyclotronJobTemplateSuggestionsLogicMeta
>

export const cyclotronJobTemplateSuggestionsLogic = kea<cyclotronJobTemplateSuggestionsLogicType>([
    props({} as CyclotronJobTemplateSuggestionsLogicProps),
    key(({ templating }: CyclotronJobTemplateSuggestionsLogicProps) => templating),

    path((key) => ['components', 'cyclotron-jobs', 'cyclotronJobTemplateSuggestionsLogic', key]),
    actions({
        setSearch: (search: string) => ({ search }),
    }),
    reducers({
        search: ['' as string, { setSearch: (_, { search }) => search }],
    }),

    selectors({
        allOptions: [
            (_, p) => [p.templating],
            (templating: 'hog' | 'liquid'): CyclotronJobTemplateOption[] => {
                return templating === 'hog' ? [...HOG_USAGE_EXAMPLES, ...HOG_STL_EXAMPLES] : LIQUID_USAGE_EXAMPLES
            },
        ],

        optionsFuse: [
            (s) => [s.allOptions],
            (allOptions: CyclotronJobTemplateOption[]): Fuse => {
                return createFuse(allOptions, {
                    keys: ['description', 'example'],
                })
            },
        ],

        optionsFiltered: [
            (s) => [s.allOptions, s.optionsFuse, s.search],
            (
                allOptions: CyclotronJobTemplateOption[],
                optionsFuse: Fuse,
                search: string
            ): CyclotronJobTemplateOption[] => {
                if (!search) {
                    return allOptions
                }
                return optionsFuse.search(search).map((result) => result.item)
            },
        ],
    }),
])