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.

18.3 KB
Raw Blame
import {
    MakeLogicType,
    BuiltLogic,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import posthog from 'posthog-js'

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

import type { NotebookComponentToolbarTitleStatus } from 'lib/components/MarkdownNotebook/componentToolbarExtras'
import { JSONContent, RichContentNode } from 'lib/components/RichContentEditor/types'

import { isHogQLQuery, isNodeWithSource } from '~/queries/schema/node-guards'

import type { CommentType } from '../../../types'
import {
    convertNotebookContentToMarkdown,
    insertMarkdownNotebookBlockAfterNode,
    isMarkdownNotebookContent,
} from '../Notebook/markdownNotebookV2'
import type { notebookLogicType } from '../Notebook/notebookLogic'
import {
    CustomNotebookNodeAttributes,
    NotebookNodeAction,
    NotebookNodeAttributeProperties,
    NotebookNodeAttributes,
    NotebookNodeResource,
    NotebookNodeSettings,
    NotebookNodeSettingsPlacement,
    NotebookNodeType,
} from '../types'
import type { NotebookType } from '../types'
import { NotebookNodeMessages, NotebookNodeMessagesListeners } from './messaging/notebook-node-messages'
import {
    type NotebookDependencyGraph,
    type NotebookDependencyUsage,
    getUniqueSqlV2ReturnVariable,
} from './notebookNodeContent'
import type { SqlV2NodeSummary } from './notebookNodeContent'
import { buildNotebookNodeClipboardHTML } from './utils'

const isSqlQueryNode = (nodeAttributes: NotebookNodeAttributes<any>): boolean => {
    const query = nodeAttributes?.query
    if (!query) {
        return false
    }
    if (isHogQLQuery(query)) {
        return true
    }
    if (isNodeWithSource(query)) {
        return isHogQLQuery(query.source)
    }
    return false
}

export type NotebookNodeLogicProps = {
    nodeType: NotebookNodeType
    notebookLogic: BuiltLogic<notebookLogicType>
    resizeable?: boolean | ((attributes: CustomNotebookNodeAttributes) => boolean)
    Settings?: NotebookNodeSettings
    messageListeners?: NotebookNodeMessagesListeners
    startExpanded?: boolean
    titlePlaceholder: string
    editableTitle?: boolean
    settingsPlacement?: NotebookNodeSettingsPlacement
} & NotebookNodeAttributeProperties<any>

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookNodeLogicValues {
    comments: CommentType[] | null // props.notebookLogic
    dependencyGraph: NotebookDependencyGraph // props.notebookLogic
    isEditable: boolean // props.notebookLogic
    notebook: NotebookType | null // props.notebookLogic
    sqlV2NodeSummaries: SqlV2NodeSummary[] // props.notebookLogic
    Settings: NotebookNodeSettings | null
    actions: NotebookNodeAction[]
    children: NotebookNodeResource[]
    customMenuItems: LemonMenuItems | null
    editableTitle: boolean
    expanded: boolean
    isEditingTitle: boolean
    messageListeners: NotebookNodeMessagesListeners
    nextNode: RichContentNode | null
    nodeAttributes: NotebookNodeAttributes<any>
    nodeId: string
    nodeType: NotebookNodeType
    notebookLogic: BuiltLogic<notebookLogicType>
    previousNode: RichContentNode | null
    ref: HTMLElement | null
    resizeable: boolean
    sendMessage: <T extends keyof NotebookNodeMessages>(message: T, payload: NotebookNodeMessages[T]) => boolean
    settingsDisabledReason: string | null
    settingsPlacement: NotebookNodeSettingsPlacement
    sourceComment: CommentType | null | undefined
    sqlV2ReturnVariable: string
    sqlV2ReturnVariableUsage: NotebookDependencyUsage[]
    title: any
    titlePlaceholder: string
    titleStatus: NotebookComponentToolbarTitleStatus | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookNodeLogicActions {
    copyToClipboard: () => {
        value: true
    }
    deleteNode: () => {
        value: true
    }
    initializeNode: () => {
        value: true
    }
    insertAfter: (content: JSONContent) => {
        content: JSONContent
    }
    navigateToNode: (nodeId: string) => {
        nodeId: string
    }
    selectNode: (scroll?: boolean) => {
        scroll: boolean | undefined
    }
    setActions: (actions: (NotebookNodeAction | undefined)[]) => {
        actions: (NotebookNodeAction | undefined)[]
    }
    setExpanded: (expanded: boolean) => {
        expanded: boolean
    }
    setMenuItems: (menuItems: LemonMenuItems | null) => {
        menuItems: LemonMenuItems | null
    }
    setMessageListeners: (listeners: NotebookNodeMessagesListeners) => {
        listeners: NotebookNodeMessagesListeners
    }
    setNextNode: (node: RichContentNode | null) => {
        node: RichContentNode | null
    }
    setPreviousNode: (node: RichContentNode | null) => {
        node: RichContentNode | null
    }
    setRef: (ref: HTMLElement | null) => {
        ref: HTMLElement | null
    }
    setResizeable: (resizeable: boolean) => {
        resizeable: boolean
    }
    setSettingsDisabledReason: (settingsDisabledReason: string | null) => {
        settingsDisabledReason: string | null
    }
    setTitlePlaceholder: (titlePlaceholder: string) => {
        titlePlaceholder: string
    }
    setTitleStatus: (titleStatus: NotebookComponentToolbarTitleStatus | null) => {
        titleStatus: NotebookComponentToolbarTitleStatus | null
    }
    toggleEditing: (visible?: boolean) => {
        visible: boolean | undefined
    }
    toggleEditingTitle: (editing?: boolean) => {
        editing: boolean | undefined
    }
    updateAttributes: (attributes: Partial<NotebookNodeAttributes<any>>) => {
        attributes: Partial<any>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookNodeLogicMeta {
    key: any
    __keaTypeGenInternalSelectorTypes: {
        notebookLogic: (notebookLogic: BuiltLogic<notebookLogicType>) => BuiltLogic<notebookLogicType>
        nodeAttributes: (attributes: any) => NotebookNodeAttributes<any>
        nodeId: (attributes: any) => string
        nodeType: (nodeType: NotebookNodeType) => NotebookNodeType
        Settings: (arg: any) => NotebookNodeSettings | null
        settingsPlacement: (arg: any) => NotebookNodeSettingsPlacement
        editableTitle: (arg: any) => boolean
        title: (titlePlaceholder: string, nodeAttributes: any, editableTitle: boolean) => any
        children: (nodeAttributes: any) => NotebookNodeResource[]
        sqlV2ReturnVariable: (sqlV2NodeSummaries: SqlV2NodeSummary[], nodeId: string, nodeAttributes: any) => string
        sqlV2ReturnVariableUsage: (
            dependencyGraph: NotebookDependencyGraph,
            nodeId: string,
            sqlV2ReturnVariable: string
        ) => NotebookDependencyUsage[]
        sendMessage: (
            messageListeners: NotebookNodeMessagesListeners
        ) => <T extends keyof NotebookNodeMessages>(message: T, payload: NotebookNodeMessages[T]) => boolean
        sourceComment: (comments: CommentType[] | null, nodeId: string) => CommentType | null | undefined
    }
}

export type notebookNodeLogicType = MakeLogicType<
    notebookNodeLogicValues,
    notebookNodeLogicActions,
    NotebookNodeLogicProps,
    notebookNodeLogicMeta
>

export const notebookNodeLogic = kea<notebookNodeLogicType>([
    props({} as NotebookNodeLogicProps),
    path((key) => ['scenes', 'notebooks', 'Notebook', 'Nodes', 'notebookNodeLogic', key]),
    key(({ attributes }) => attributes.nodeId || 'no-node-id-set'),
    actions({
        setExpanded: (expanded: boolean) => ({ expanded }),
        setResizeable: (resizeable: boolean) => ({ resizeable }),
        setActions: (actions: (NotebookNodeAction | undefined)[]) => ({ actions }),
        setMenuItems: (menuItems: LemonMenuItems | null) => ({ menuItems }),
        setSettingsDisabledReason: (settingsDisabledReason: string | null) => ({ settingsDisabledReason }),
        insertAfter: (content: JSONContent) => ({ content }),
        updateAttributes: (attributes: Partial<NotebookNodeAttributes<any>>) => ({ attributes }),
        setPreviousNode: (node: RichContentNode | null) => ({ node }),
        setNextNode: (node: RichContentNode | null) => ({ node }),
        deleteNode: true,
        selectNode: (scroll?: boolean) => ({ scroll }),
        toggleEditing: (visible?: boolean) => ({ visible }),
        initializeNode: true,
        setMessageListeners: (listeners: NotebookNodeMessagesListeners) => ({ listeners }),
        setTitlePlaceholder: (titlePlaceholder: string) => ({ titlePlaceholder }),
        setTitleStatus: (titleStatus: NotebookComponentToolbarTitleStatus | null) => ({ titleStatus }),
        setRef: (ref: HTMLElement | null) => ({ ref }),
        toggleEditingTitle: (editing?: boolean) => ({ editing }),
        copyToClipboard: true,
        navigateToNode: (nodeId: string) => ({ nodeId }),
    }),

    connect((props: NotebookNodeLogicProps) => ({
        values: [props.notebookLogic, ['isEditable', 'comments', 'sqlV2NodeSummaries', 'dependencyGraph', 'notebook']],
    })),

    reducers(({ props }) => ({
        ref: [
            null as HTMLElement | null,
            {
                setRef: (_, { ref }) => ref,
            },
        ],
        expanded: [
            props.startExpanded ?? true,
            {
                setExpanded: (_, { expanded }) => expanded,
            },
        ],
        resizeable: [
            false,
            {
                setResizeable: (_, { resizeable }) => resizeable,
            },
        ],
        previousNode: [
            null as RichContentNode | null,
            {
                setPreviousNode: (_, { node }) => node,
            },
        ],
        nextNode: [
            null as RichContentNode | null,
            {
                setNextNode: (_, { node }) => node,
            },
        ],
        actions: [
            [] as NotebookNodeAction[],
            {
                setActions: (_, { actions }) => actions.filter((x) => !!x) as NotebookNodeAction[],
            },
        ],
        customMenuItems: [
            null as LemonMenuItems | null,
            {
                setMenuItems: (_, { menuItems }) => menuItems,
            },
        ],
        settingsDisabledReason: [
            null as string | null,
            {
                setSettingsDisabledReason: (_, { settingsDisabledReason }) => settingsDisabledReason,
            },
        ],
        messageListeners: [
            props.messageListeners as NotebookNodeMessagesListeners,
            {
                setMessageListeners: (_, { listeners }) => listeners,
            },
        ],
        titlePlaceholder: [
            props.titlePlaceholder,
            {
                setTitlePlaceholder: (_, { titlePlaceholder }) => titlePlaceholder,
            },
        ],
        titleStatus: [
            null as NotebookComponentToolbarTitleStatus | null,
            {
                setTitleStatus: (_, { titleStatus }) => titleStatus,
            },
        ],
        isEditingTitle: [
            false,
            {
                toggleEditingTitle: (state, { editing }) => (typeof editing === 'boolean' ? editing : !state),
            },
        ],
    })),

    selectors({
        notebookLogic: [
            (_, p) => [p.notebookLogic],
            (notebookLogic: BuiltLogic<notebookLogicType>): BuiltLogic<notebookLogicType> => notebookLogic,
        ],
        nodeAttributes: [(_, p) => [p.attributes], (nodeAttributes): NotebookNodeAttributes<any> => nodeAttributes],
        nodeId: [
            (_, p) => [p.attributes],
            (nodeAttributes: NotebookNodeAttributes<any>): string => nodeAttributes.nodeId,
        ],
        nodeType: [(_, p) => [p.nodeType], (nodeType: NotebookNodeType) => nodeType],
        Settings: [() => [(_, props) => props], (props): NotebookNodeSettings | null => props.Settings ?? null],
        settingsPlacement: [
            () => [(_, props) => props],
            (props): NotebookNodeSettingsPlacement => props.settingsPlacement ?? 'left',
        ],
        editableTitle: [
            () => [(_, props) => props.editableTitle],
            (editableTitle: boolean | undefined): boolean => editableTitle ?? true,
        ],

        title: [
            (s) => [s.titlePlaceholder, s.nodeAttributes, s.editableTitle],
            (titlePlaceholder: string, nodeAttributes, editableTitle: boolean) =>
                (editableTitle ? nodeAttributes.title : null) || titlePlaceholder,
        ],
        // TODO: Fix the typing of nodeAttributes
        children: [
            (s) => [s.nodeAttributes],
            (nodeAttributes): NotebookNodeResource[] =>
                Array.isArray(nodeAttributes.children) ? nodeAttributes.children : [],
        ],

        sqlV2ReturnVariable: [
            (s) => [s.sqlV2NodeSummaries, s.nodeId, s.nodeAttributes],
            (sqlV2NodeSummaries: SqlV2NodeSummary[], nodeId: string, nodeAttributes): string =>
                getUniqueSqlV2ReturnVariable(sqlV2NodeSummaries, nodeId, nodeAttributes.returnVariable ?? ''),
        ],
        sqlV2ReturnVariableUsage: [
            (s) => [s.dependencyGraph, s.nodeId, s.sqlV2ReturnVariable],
            (
                dependencyGraph: NotebookDependencyGraph,
                nodeId: string,
                sqlV2ReturnVariable: string
            ): NotebookDependencyUsage[] => dependencyGraph.downstreamUsageByNode[nodeId]?.[sqlV2ReturnVariable] ?? [],
        ],

        sendMessage: [
            (s) => [s.messageListeners],
            (messageListeners: NotebookNodeMessagesListeners) => {
                return <T extends keyof NotebookNodeMessages>(
                    message: T,
                    payload: NotebookNodeMessages[T]
                ): boolean => {
                    if (!messageListeners[message]) {
                        return false
                    }

                    messageListeners[message]?.(payload)
                    return true
                }
            },
        ],

        sourceComment: [
            (s) => [s.comments, s.nodeId],
            (comments: CommentType[] | null, nodeId: string) =>
                comments &&
                comments.find(
                    (comment) => comment.item_context?.type === 'node' && comment.item_context?.id === nodeId
                ),
        ],
    }),

    listeners(({ actions, values, props }) => ({
        deleteNode: () => {
            if (values.notebookLogic.values.editingNodeIds[values.nodeId]) {
                values.notebookLogic.actions.setEditingNodeEditing(values.nodeId, false)
            }
        },

        navigateToNode: ({ nodeId }) => {
            const targetLogic = values.notebookLogic.values.findNodeLogicById(nodeId)
            targetLogic?.actions.selectNode()
        },

        insertAfter: ({ content }) => {
            const notebookLogic = values.notebookLogic
            if (!isMarkdownNotebookContent(notebookLogic.values.content)) {
                return
            }
            // The converter serializes the children of a doc, so a single leaf node must be
            // wrapped in an array to be serialized itself.
            const insertedMarkdown = convertNotebookContentToMarkdown(content.type === 'doc' ? content : [content])
            if (!insertedMarkdown.trim()) {
                return
            }
            notebookLogic.actions.setLocalContent(
                insertMarkdownNotebookBlockAfterNode(notebookLogic.values.content, values.nodeId, insertedMarkdown)
            )
        },

        setExpanded: ({ expanded }) => {
            if (expanded) {
                posthog.capture('notebook node expanded', {
                    node_type: props.nodeType,
                    short_id: props.notebookLogic.props.shortId,
                })
            }
        },

        updateAttributes: ({ attributes }) => {
            props.updateAttributes(attributes)
        },
        toggleEditing: ({ visible }) => {
            const isEditing = values.notebookLogic.values.editingNodeIds[values.nodeId]
            const shouldShowThis = typeof visible === 'boolean' ? visible : !isEditing

            props.notebookLogic.actions.setEditingNodeEditing(values.nodeId, shouldShowThis)
            if (props.nodeType === NotebookNodeType.Query && isSqlQueryNode(values.nodeAttributes)) {
                actions.updateAttributes({ showSettings: shouldShowThis })
            }
        },
        initializeNode: () => {
            const { __init } = values.nodeAttributes
            const isSqlQuery = props.nodeType === NotebookNodeType.Query && isSqlQueryNode(values.nodeAttributes)

            if (__init) {
                if (__init.expanded) {
                    actions.setExpanded(true)
                }
                if (__init.showSettings) {
                    actions.toggleEditing(true)
                }
                if (isSqlQuery && __init.showSettings) {
                    actions.updateAttributes({ showSettings: true })
                }
                props.updateAttributes({ __init: null })
            }
            if (isSqlQuery) {
                const shouldShowSettings = __init?.showSettings ?? values.nodeAttributes.showSettings
                if (typeof shouldShowSettings === 'boolean') {
                    props.notebookLogic.actions.setEditingNodeEditing(values.nodeId, shouldShowSettings)
                }
            }
        },

        copyToClipboard: async () => {
            const html = buildNotebookNodeClipboardHTML(props.nodeType, values.nodeAttributes)
            const type = 'text/html'
            const blob = new Blob([html], { type })
            await window.navigator.clipboard.write([new ClipboardItem({ [type]: blob })])
        },
    })),

    afterMount((logic) => {
        const { props, actions, values } = logic

        // The node logic is mounted after the editor is mounted, so we need to wait a tick before we can register it
        queueMicrotask(() => {
            props.notebookLogic.actions.registerNodeLogic(values.nodeId, logic as any)
        })

        const isResizeable =
            typeof props.resizeable === 'function' ? props.resizeable(props.attributes) : (props.resizeable ?? true)

        actions.setResizeable(isResizeable)
        actions.initializeNode()
    }),

    beforeUnmount(({ props, values }) => {
        // Note this doesn't work as there may be other places where this is used. The NodeWrapper should be in charge of somehow unmounting this
        props.notebookLogic.actions.unregisterNodeLogic(values.nodeId)
    }),
])