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.

13.3 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 { urlToAction } from 'kea-router'

import '@posthog/lemon-ui'

import api, { ApiConfig } from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { Dayjs, dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { annotationsModel, deserializeAnnotation } from '~/models/annotationsModel'
import { AnnotationScope, AnnotationType, DashboardBasicType, InsightModel } from '~/types'

import type { UserType } from '../../../../frontend/src/types'
import type { RawAnnotationType } from '../../../../frontend/src/types'
import { annotationsPartialUpdate } from '../generated/api'

export const ANNOTATION_DAYJS_FORMAT = 'MMMM DD, YYYY h:mm A'

export const annotationScopeToName: Record<AnnotationScope, string> = {
    [AnnotationScope.Insight]: 'Insight',
    [AnnotationScope.Dashboard]: 'Dashboard',
    [AnnotationScope.Project]: 'Project',
    [AnnotationScope.Organization]: 'Organization',
}

export const annotationScopeToLevel: Record<AnnotationScope, number> = {
    [AnnotationScope.Insight]: 0,
    [AnnotationScope.Dashboard]: 1,
    [AnnotationScope.Project]: 2,
    [AnnotationScope.Organization]: 3,
}

export interface AnnotationModalForm {
    dateMarker: Dayjs
    scope: AnnotationType['scope']
    content: AnnotationType['content']
    emoji: AnnotationType['emoji']
    dashboardItemId: AnnotationType['dashboard_item'] | null
    dashboardId: AnnotationType['dashboard_id'] | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationModalLogicValues {
    annotations: AnnotationType[] // annotationsModel
    annotationsLoading: boolean // annotationsModel
    timezone: string // teamLogic
    user: UserType | null // userLogic
    annotationModal: AnnotationModalForm
    annotationModalAllErrors: Record<string, any>
    annotationModalChanged: boolean
    annotationModalErrors: DeepPartialMap<AnnotationModalForm, ValidationErrorType>
    annotationModalHasErrors: boolean
    annotationModalManualErrors: Record<string, any>
    annotationModalTouched: boolean
    annotationModalTouches: Record<string, boolean>
    annotationModalValidationErrors: DeepPartialMap<AnnotationModalForm, ValidationErrorType>
    existingModalAnnotation: AnnotationType | null
    isAnnotationModalSubmitting: boolean
    isAnnotationModalValid: boolean
    isModalOpen: boolean
    onSavedInsight: boolean
    scope: AnnotationType['scope'] | null
    shouldShowEmptyState: boolean
    showAnnotationModalErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationModalLogicActions {
    appendAnnotations: (annotations: RawAnnotationType[]) => {
        annotations: RawAnnotationType[]
    } // annotationsModel
    deleteAnnotation: (annotation: AnnotationType) => {
        annotation: AnnotationType
    } // annotationsModel
    loadAnnotationsSuccess: (
        rawAnnotations: RawAnnotationType[],
        payload?: any
    ) => {
        payload?: any
        rawAnnotations: RawAnnotationType[]
    } // annotationsModel
    replaceAnnotation: (annotation: RawAnnotationType) => {
        annotation: RawAnnotationType
    } // annotationsModel
    closeModal: () => {
        value: true
    }
    openModalToCreateAnnotation: (
        initialDate?: Dayjs | null,
        insightId?: InsightModel['id'] | null,
        dashboardId?: DashboardBasicType['id'] | null
    ) => {
        dashboardId: number | null | undefined
        initialDate: Dayjs | null | undefined
        insightId: number | null | undefined
    }
    openModalToEditAnnotation: (
        annotation: AnnotationType,
        insightId?: InsightModel['id'] | null,
        dashboardId?: DashboardBasicType['id'] | null
    ) => {
        annotation: AnnotationType
        dashboardId: number | null | undefined
        insightId: number | null | undefined
    }
    resetAnnotationModal: (values?: AnnotationModalForm) => {
        values?: AnnotationModalForm
    }
    setAnnotationModalManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setAnnotationModalValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setAnnotationModalValues: (values: DeepPartial<AnnotationModalForm>) => {
        values: DeepPartial<AnnotationModalForm>
    }
    setScope: (scope: AnnotationType['scope'] | null) => {
        scope: AnnotationScope | null
    }
    submitAnnotationModal: () => {
        value: boolean
    }
    submitAnnotationModalFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitAnnotationModalRequest: (annotationModal: AnnotationModalForm) => {
        annotationModal: AnnotationModalForm
    }
    submitAnnotationModalSuccess: (annotationModal: AnnotationModalForm) => {
        annotationModal: AnnotationModalForm
    }
    touchAnnotationModalField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationModalLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        shouldShowEmptyState: (annotations: AnnotationType[], annotationsLoading: boolean) => boolean
    }
}

export type annotationModalLogicType = MakeLogicType<
    annotationModalLogicValues,
    annotationModalLogicActions,
    Record<string, any>,
    annotationModalLogicMeta
>

export const annotationModalLogic = kea<annotationModalLogicType>([
    path(['scenes', 'annotations', 'annotationModalLogic']),
    connect(() => ({
        actions: [
            annotationsModel,
            ['loadAnnotationsSuccess', 'replaceAnnotation', 'appendAnnotations', 'deleteAnnotation'],
        ],
        values: [annotationsModel, ['annotations', 'annotationsLoading'], teamLogic, ['timezone'], userLogic, ['user']],
    })),
    actions({
        openModalToCreateAnnotation: (
            initialDate?: Dayjs | null,
            insightId?: InsightModel['id'] | null,
            dashboardId?: DashboardBasicType['id'] | null
        ) => ({
            initialDate,
            insightId,
            dashboardId,
        }),
        openModalToEditAnnotation: (
            annotation: AnnotationType,
            insightId?: InsightModel['id'] | null,
            dashboardId?: DashboardBasicType['id'] | null
        ) => ({
            annotation,
            insightId,
            dashboardId,
        }),
        closeModal: true,
        setScope: (scope: AnnotationType['scope'] | null) => ({ scope }),
    }),
    reducers(() => ({
        scope: [null as AnnotationType['scope'] | null, { setScope: (_, { scope }) => scope }],
        isModalOpen: [
            false,
            {
                openModalToCreateAnnotation: () => true,
                openModalToEditAnnotation: () => true,
                closeModal: () => false,
            },
        ],
        existingModalAnnotation: [
            null as AnnotationType | null,
            {
                openModalToCreateAnnotation: () => null,
                openModalToEditAnnotation: (_, { annotation }) => annotation,
            },
        ],
        onSavedInsight: [
            false,
            {
                openModalToCreateAnnotation: (_, { insightId }) => !!insightId,
                openModalToEditAnnotation: (_, { insightId }) => !!insightId,
            },
        ],
    })),
    listeners(({ cache, actions, values }) => ({
        openModalToEditAnnotation: ({ annotation: { date_marker, scope, content, emoji }, insightId, dashboardId }) => {
            actions.setAnnotationModalValues({
                dateMarker: dayjs(date_marker).tz(values.timezone),
                scope,
                content,
                emoji,
            })
            if (insightId) {
                actions.setAnnotationModalValue('dashboardItemId', insightId)
            }
            if (dashboardId) {
                actions.setAnnotationModalValue('dashboardId', dashboardId)
            }
        },
        openModalToCreateAnnotation: ({ initialDate, insightId, dashboardId }) => {
            actions.resetAnnotationModal()
            if (initialDate) {
                actions.setAnnotationModalValue('dateMarker', initialDate)
            }
            if (insightId) {
                actions.setAnnotationModalValue('dashboardItemId', insightId)
            }
            if (dashboardId) {
                actions.setAnnotationModalValue('dashboardId', dashboardId)
            }
        },
        loadAnnotationsSuccess: ({ rawAnnotations }) => {
            if (!values.isModalOpen && cache.annotationToShowId) {
                const annotation = rawAnnotations.find((a) => a.id === cache.annotationToShowId)
                if (!annotation) {
                    return // If the annotation isn't there by now, then we're lost
                }
                actions.openModalToEditAnnotation(deserializeAnnotation(annotation, teamLogic.values.timezone))
                delete cache.annotationToShowId
            }
        },
    })),
    selectors(() => ({
        shouldShowEmptyState: [
            (s) => [s.annotations, s.annotationsLoading],
            (annotations: AnnotationType[], annotationsLoading: boolean): boolean => {
                return annotations.length === 0 && !annotationsLoading
            },
        ],
    })),
    forms(({ actions, values }) => ({
        annotationModal: {
            defaults: {
                dateMarker: dayjs().tz(values.timezone),
                content: '',
                emoji: null,
                scope: AnnotationScope.Project,
                dashboardItemId: null,
                dashboardId: null,
            } as AnnotationModalForm,
            errors: ({ content }) => ({
                content: !content?.trim() ? 'An annotation must have text content.' : null,
            }),
            submit: async (data) => {
                const { dateMarker, content, emoji, scope, dashboardItemId, dashboardId } = data

                if (values.existingModalAnnotation) {
                    // annotationsModel's updateAnnotation inlined so that isAnnotationModalSubmitting works
                    const updatedAnnotation = await annotationsPartialUpdate(
                        String(ApiConfig.getCurrentProjectId()),
                        values.existingModalAnnotation.id,
                        {
                            date_marker: dateMarker.toISOString(),
                            content,
                            emoji: emoji || null,
                            scope,
                            // Off an insight, omit the field so the PATCH keeps the stored insight. An organization-scoped
                            // row can point at another team's insight, which fails the team-scoped lookup if sent back.
                            ...(dashboardItemId ? { dashboard_item: dashboardItemId } : {}),
                            // A row without a dashboard that moves to dashboard scope takes the one it was opened on,
                            // because the API rejects that scope without an id.
                            dashboard_id:
                                values.existingModalAnnotation.dashboard_id ??
                                (scope === AnnotationScope.Dashboard ? dashboardId : null),
                        }
                    )
                    actions.replaceAnnotation(updatedAnnotation as unknown as RawAnnotationType)
                } else {
                    // annotationsModel's createAnnotationGenerically inlined so that isAnnotationModalSubmitting works
                    const createdAnnotation = await api.annotations.create({
                        date_marker: dateMarker.toISOString(),
                        content,
                        emoji: emoji || null,
                        scope,
                        dashboard_item: dashboardItemId,
                        dashboard_id: dashboardId,
                    })
                    actions.appendAnnotations([createdAnnotation])
                    const trimmedContent = content?.trim() ?? ''
                    const snippet = trimmedContent.length > 60 ? trimmedContent.slice(0, 57) + '…' : trimmedContent
                    const date = dateMarker.format('YYYY-MM-DD')
                    tryShowMCPHint('annotations.create', {
                        derivedPrompt: snippet ? `Annotate ${date}: ${snippet}` : undefined,
                    })
                }
                actions.closeModal()
            },
        },
    })),
    urlToAction(({ values, actions, cache }) => ({
        [urls.annotation(':id')]: ({ id }) => {
            cache.annotationToShowId = parseInt(id as string)
            const annotation = values.annotations.find((a) => a.id === cache.annotationToShowId)
            if (!annotation) {
                return // This means there are no annotations yet, so we'll open the modal in loadAnnotationsSuccess
            }
            actions.openModalToEditAnnotation(annotation)
        },
    })),
])