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.

8.7 KB
Raw Blame
import { MakeLogicType, connect, kea, key, listeners, path, props } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import posthog from 'posthog-js'

import { lemonToast } from '@posthog/lemon-ui'

import { dashboardsModel } from '~/models/dashboardsModel'
import { DashboardTile, DashboardTileIdOrNew, DashboardType, NewDashboardTile } from '~/types'

import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'

export interface TextTileForm {
    body: string
    agent_context: string
    transparent_background: boolean
}

export type TextCardTileType = 'text' | 'image'

export interface TextCardModalProps {
    dashboard: DashboardType
    textTileId: DashboardTileIdOrNew
    onClose: () => void
    tileType: TextCardTileType
    /** Creates the new tile. Without it, the tile is created on the dashboard as is. */
    onCreateTile?: (tile: NewDashboardTile) => void
}

const MAX_TEXT_CARD_BODY_LENGTH = 4000
const MAX_AGENT_CONTEXT_LENGTH = 10000

function firstValidationError(value: unknown): string | null {
    const firstValue = Array.isArray(value) ? value[0] : value
    return typeof firstValue === 'string' ? firstValue : null
}

function fieldValidationError(errors: Record<string, any>, field: string): string | null {
    return firstValidationError(errors[field]) || firstValidationError(errors.text?.[field])
}

const getExistingTextTile = (dashboard: DashboardType, textTileId: number): TextTileForm => {
    const tile = dashboard.tiles?.find((tt) => tt.id === textTileId)
    return {
        body: tile?.text?.body || '',
        agent_context: tile?.text?.agent_context || '',
        transparent_background: tile?.transparent_background ?? false,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface textCardModalLogicValues {
    isTextTileSubmitting: boolean
    isTextTileValid: boolean
    showTextTileErrors: boolean
    textTile: TextTileForm
    textTileAllErrors: Record<string, any>
    textTileChanged: boolean
    textTileErrors: DeepPartialMap<TextTileForm, ValidationErrorType>
    textTileHasErrors: boolean
    textTileManualErrors: Record<string, any>
    textTileTouched: boolean
    textTileTouches: Record<string, boolean>
    textTileValidationErrors: DeepPartialMap<TextTileForm, ValidationErrorType>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface textCardModalLogicActions {
    updateDashboard: (args_0: any) => any // dashboardsModel
    resetTextTile: (values?: TextTileForm) => {
        values?: TextTileForm
    }
    setTextTileManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setTextTileValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setTextTileValues: (values: DeepPartial<TextTileForm>) => {
        values: DeepPartial<TextTileForm>
    }
    submitTextTile: () => {
        value: boolean
    }
    submitTextTileFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitTextTileRequest: (textTile: TextTileForm) => {
        textTile: TextTileForm
    }
    submitTextTileSuccess: (textTile: TextTileForm) => {
        textTile: TextTileForm
    }
    touchTextTileField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface textCardModalLogicMeta {
    key: string
}

export type textCardModalLogicType = MakeLogicType<
    textCardModalLogicValues,
    textCardModalLogicActions,
    TextCardModalProps,
    textCardModalLogicMeta
>

export const textCardModalLogic = kea<textCardModalLogicType>([
    path(['scenes', 'dashboard', 'dashboardTextTileModal', 'logic']),
    props({} as TextCardModalProps),
    key((props) => `textCardModalLogic-${props.dashboard.id}-${props.textTileId}-${props.tileType}`),
    connect(() => ({ actions: [dashboardsModel, ['updateDashboard']] })),
    listeners(({ props, actions, values }) => ({
        submitTextTileFailure: (error) => {
            if (props.dashboard && props.textTileId) {
                const failure = error as {
                    errors?: Record<string, any>
                    error?: string | { error?: string; errors?: Record<string, any> }
                }
                const normalizedErrors = (failure.errors ||
                    (typeof failure.error === 'object' ? failure.error?.errors : undefined) ||
                    {}) as Record<string, any>
                const normalizedMessage =
                    (typeof failure.error === 'string' ? failure.error : null) ||
                    (typeof failure.error === 'object' && typeof failure.error?.error === 'string'
                        ? failure.error.error
                        : null) ||
                    'Unknown error'
                const formBodyError = values.textTileValidationErrors.body as string | null
                const apiBodyError = fieldValidationError(normalizedErrors, 'body')
                const formAgentContextError = values.textTileValidationErrors.agent_context as string | null
                const apiAgentContextError = fieldValidationError(normalizedErrors, 'agent_context')

                // Expected validation errors are shown inline on the form.
                if (formBodyError || apiBodyError || formAgentContextError || apiAgentContextError) {
                    return
                }

                lemonToast.error(`Could not save ${props.tileType}: ${normalizedMessage}`)
            }
        },
        submitTextTileSuccess: ({ textTile }: { textTile: TextTileForm }) => {
            actions.resetTextTile()
            props?.onClose?.()

            posthog.capture('dashboard text tile saved', {
                dashboard_id: props.dashboard.id,
                text_tile_id: props.textTileId,
                is_new: props.textTileId === null,
                body_length: textTile.body.length,
                agent_context_length: textTile.agent_context.length,
                has_agent_context: textTile.agent_context.trim().length > 0,
                content_type: getImageOnlyTextCardImage(textTile.body) ? 'image' : 'text',
            })
        },
    })),
    forms(({ props, actions }) => ({
        textTile: {
            defaults: (props.textTileId !== null
                ? getExistingTextTile(props.dashboard, props.textTileId)
                : { body: '', agent_context: '', transparent_background: props.tileType === 'image' }) as TextTileForm,
            errors: ({ body, agent_context }) => {
                return {
                    body: !body.trim()
                        ? 'This card would be empty! Type something first'
                        : body.length > MAX_TEXT_CARD_BODY_LENGTH
                          ? `Text is too long (${MAX_TEXT_CARD_BODY_LENGTH} characters max)`
                          : null,
                    agent_context:
                        agent_context.length > MAX_AGENT_CONTEXT_LENGTH
                            ? `Agent context is too long (${MAX_AGENT_CONTEXT_LENGTH} characters max)`
                            : null,
                }
            },
            submit: (formValues) => {
                if (props.textTileId === null) {
                    const tile = {
                        text: { body: formValues.body, agent_context: formValues.agent_context },
                        transparent_background: formValues.transparent_background,
                    }
                    if (props.onCreateTile) {
                        props.onCreateTile(tile)
                    } else {
                        actions.updateDashboard({ id: props.dashboard.id, tiles: [tile] })
                    }
                } else {
                    const updatedTiles = (props.dashboard.tiles || []).reduce((acc, tile) => {
                        if (tile.id === props.textTileId && tile.text) {
                            acc.push({
                                id: tile.id,
                                text: {
                                    ...tile.text,
                                    body: formValues.body,
                                    agent_context: formValues.agent_context,
                                },
                                transparent_background: formValues.transparent_background,
                            })
                        }
                        return acc
                    }, [] as Partial<DashboardTile>[])
                    actions.updateDashboard({ id: props.dashboard.id, tiles: updatedTiles })
                }
            },
        },
    })),
])