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.

17.3 KB
Raw Blame
import { memo, type PointerEvent as ReactPointerEvent, useCallback, useRef } from 'react'
import clsx from 'clsx'
import { LemonButton, LemonMenu, LemonMenuItems } from '@posthog/lemon-ui'
import './NodeWrapper.scss'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import { notebookLogic } from '../Notebook/notebookLogic'
import { useInView } from 'react-intersection-observer'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { NotebookNodeLogicProps, notebookNodeLogic } from './notebookNodeLogic'
import { KNOWN_NODES } from '../utils'
import { NotebookNodeTitle } from './components/NotebookNodeTitle'
import { NotebookNodeContext } from './NotebookNodeContext'
import { IconCollapse, IconEllipsis, IconExpand, IconPencil } from '@posthog/icons'
import {
    CreatePostHogWidgetNodeOptions,
    CustomNotebookNodeAttributes,
    NotebookNodeProps,
    NodeWrapperProps,
    NotebookNodeResource,
    NotebookNodeType,
} from '../types'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { getNotebookWidgetViewMenuItem } from '../notebookWidgetMenu'
import { withoutNotebookMenuIcons } from 'lib/components/MarkdownNotebook/componentToolbarExtras'

const NON_COPYABLE_NODES = [
    NotebookNodeType.PersonProperties,
    NotebookNodeType.Person,
    NotebookNodeType.GroupProperties,
    NotebookNodeType.Group,
    NotebookNodeType.RelatedGroups,
]

function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperProps<T>): JSX.Element {
    const {
        nodeType,
        Component,
        selected,
        href,
        heightEstimate = '4rem',
        expandable = true,
        expandOnClick = true,
        autoHideMetadata = false,
        minHeight,
        attributes,
        updateAttributes,
        Settings = null,
        editableTitle = true,
        titlePlaceholder,
        defaultView,
        views,
        unmountWhenOutOfView = false,
    } = props

    const mountedNotebookLogic = useMountedLogic(notebookLogic)
    const { isEditable, editingNodeIds, containerSize, isShared } = useValues(mountedNotebookLogic)
    const { unregisterNodeLogic, insertComment, selectComment } = useActions(notebookLogic)

    const logicProps: NotebookNodeLogicProps = {
        ...props,
        notebookLogic: mountedNotebookLogic,
    }

    // nodeId can start null, but should then immediately be generated
    const nodeLogic = useMountedLogic(notebookNodeLogic(logicProps))
    const {
        resizeable,
        expanded,
        nodeId,
        settingsPlacement: resolvedSettingsPlacement,
        sourceComment,
        customMenuItems,
        actions,
    } = useValues(nodeLogic)
    const { setRef, setExpanded, deleteNode, toggleEditing, toggleEditingTitle, copyToClipboard } =
        useActions(nodeLogic)

    const { ref: inViewRef, inView } = useInView({ triggerOnce: !unmountWhenOutOfView })

    const setRefs = useCallback(
        (node: HTMLDivElement | null) => {
            setRef(node)
            inViewRef(node)
        },
        // oxlint-disable-next-line exhaustive-deps
        [inViewRef]
    )

    // TRICKY: child nodes mount the parent logic so we need to control the mounting / unmounting directly in this component
    useOnMountEffect(() => {
        return () => unregisterNodeLogic(nodeId)
    })

    const contentRef = useRef<HTMLDivElement | null>(null)

    // If resizeable is true then the node attr "height" is required
    const height = attributes.height ?? heightEstimate

    const onResizeStart = useCallback((): void => {
        if (!resizeable) {
            return
        }
        const initialHeightAttr = contentRef.current?.style.height
        const onResizedEnd = (): void => {
            window.removeEventListener('mouseup', onResizedEnd)
            // css resize sets the style attr so we check that to detect changes. Resize obsserver doesn't trigger for style changes
            const heightAttr = contentRef.current?.style.height
            if (heightAttr && heightAttr !== initialHeightAttr) {
                updateAttributes({ height: contentRef.current?.clientHeight } as any)
            }
        }

        window.addEventListener('mouseup', onResizedEnd)
    }, [resizeable, updateAttributes])

    const parsedHref = typeof href === 'function' ? href(attributes) : href

    // Element is resizable if resizable is set to true. If expandable is set to true then is is only resizable if expanded is true
    const isResizeable = resizeable && (!expandable || expanded)
    const onResizeHandlePointerDown = useCallback(
        (event: ReactPointerEvent<HTMLDivElement>): void => {
            if (!isEditable || !isResizeable || !contentRef.current) {
                return
            }

            event.preventDefault()
            event.stopPropagation()

            const element = contentRef.current
            const startY = event.clientY
            const startHeight = element.getBoundingClientRect().height
            const parsedMinHeight = Number.parseFloat(window.getComputedStyle(element).minHeight)
            const minResizeHeight = Number.isFinite(parsedMinHeight) ? parsedMinHeight : 0

            const onPointerMove = (moveEvent: PointerEvent): void => {
                moveEvent.preventDefault()
                const nextHeight = Math.max(minResizeHeight, startHeight + moveEvent.clientY - startY)
                element.style.height = `${Math.round(nextHeight)}px`
            }

            const onPointerUp = (): void => {
                window.removeEventListener('pointermove', onPointerMove)
                window.removeEventListener('pointerup', onPointerUp)

                updateAttributes({ height: element.clientHeight } as any)
            }

            window.addEventListener('pointermove', onPointerMove)
            window.addEventListener('pointerup', onPointerUp)
        },
        [isEditable, isResizeable, updateAttributes]
    )
    const defaultMenuItems: LemonMenuItems = [
        // Copy round-trips the node attrs through HTML for paste into another notebook — doesn't
        // make sense for an anonymous shared viewer who has no editor to paste into.
        !NON_COPYABLE_NODES.includes(nodeType) && !isShared
            ? {
                  label: 'Copy',
                  onClick: () => copyToClipboard(),
              }
            : null,
        isEditable && isResizeable
            ? {
                  label: 'Reset height to default',
                  onClick: () => {
                      updateAttributes({ height: null } as any)
                  },
              }
            : null,
        isEditable && editableTitle ? { label: 'Edit title', onClick: () => toggleEditingTitle(true) } : null,
        isEditable
            ? sourceComment
                ? { label: 'Show comment', onClick: () => selectComment(nodeId) }
                : { label: 'Comment', onClick: () => insertComment({ type: 'node', id: nodeId }) }
            : null,
        isEditable ? { label: 'Remove', onClick: () => deleteNode(), status: 'danger' } : null,
    ]

    const viewMenuItem = getNotebookWidgetViewMenuItem(
        { defaultView, views },
        attributes,
        updateAttributes
    )
    const resourceLabel = titlePlaceholder.charAt(0).toLocaleLowerCase() + titlePlaceholder.slice(1)
    const menuItems: LemonMenuItems = withoutNotebookMenuIcons([
        parsedHref && !isShared
            ? {
                  label: `Open ${resourceLabel}`,
                  to: parsedHref,
              }
            : null,
        parsedHref && !isShared
            ? {
                  label: 'Open in new tab',
                  to: parsedHref,
                  targetBlank: true,
              }
            : null,
        ...(isEditable
            ? actions.map((action) => ({
                  label: action.text,
                  disabledReason: action.disabledReason,
                  onClick: action.onClick,
              }))
            : []),
        isEditable ? viewMenuItem : null,
        ...(customMenuItems ?? defaultMenuItems),
    ])

    const hasMenu = menuItems.some((x) => !!x)

    return (
        <NotebookNodeContext.Provider value={nodeLogic}>
            <BindLogic logic={notebookNodeLogic} props={logicProps}>
                <div>
                    <div
                        ref={setRefs}
                        className={clsx(nodeType, 'NotebookNode', {
                            'NotebookNode--auto-hide-metadata': autoHideMetadata,
                            'NotebookNode--selected': isEditable && selected,
                        })}
                    >
                        <div className="NotebookNode__box">
                            <ErrorBoundary>
                                {!inView ? (
                                    <>
                                        <div className="h-10 p-2 flex justify-between">
                                            <LemonSkeleton className="w-1/4" />
                                            <LemonSkeleton className="w-20" />
                                        </div>
                                        {/* eslint-disable-next-line react/forbid-dom-props */}
                                        <div
                                            className="flex items-center p-2"
                                            style={isResizeable ? { height, minHeight } : { height: heightEstimate }}
                                        >
                                            <LemonSkeleton className="w-full h-full" />
                                        </div>
                                    </>
                                ) : (
                                    <>
                                        <div className="NotebookNode__meta">
                                            <div className="flex items-center flex-1 overflow-hidden">
                                                <NotebookNodeTitle />
                                            </div>

                                            <div className="flex deprecated-space-x-1">
                                                {isEditable && Settings ? (
                                                    <LemonButton
                                                        onClick={() => toggleEditing()}
                                                        size="small"
                                                        icon={<IconPencil />}
                                                        active={editingNodeIds[nodeId]}
                                                        tooltip={
                                                            editingNodeIds[nodeId]
                                                                ? 'Hide editor'
                                                                : 'Show editor and settings'
                                                        }
                                                        data-attr="notebook-node-edit-settings"
                                                    />
                                                ) : null}

                                                {expandable && (
                                                    <LemonButton
                                                        onClick={() => setExpanded(!expanded)}
                                                        size="small"
                                                        icon={expanded ? <IconCollapse /> : <IconExpand />}
                                                        tooltip={expanded ? 'Hide output' : 'Show output'}
                                                    />
                                                )}

                                                {hasMenu ? (
                                                    <LemonMenu items={menuItems} placement="bottom-end">
                                                        <LemonButton
                                                            icon={<IconEllipsis />}
                                                            size="small"
                                                            tooltip="More actions"
                                                        />
                                                    </LemonMenu>
                                                ) : null}
                                            </div>
                                        </div>

                                        {Settings &&
                                        !isShared &&
                                        editingNodeIds[nodeId] &&
                                        (containerSize === 'small' || resolvedSettingsPlacement === 'inline') ? (
                                            <div className="NotebookNode__settings">
                                                <ErrorBoundary>
                                                    <Settings
                                                        key={nodeId}
                                                        attributes={attributes}
                                                        updateAttributes={updateAttributes}
                                                    />
                                                </ErrorBoundary>
                                            </div>
                                        ) : null}

                                        <div
                                            ref={contentRef}
                                            className={clsx(
                                                'NotebookNode__content flex flex-col relative z-0 overflow-hidden',
                                                isEditable && isResizeable && 'resize-y'
                                            )}
                                            // eslint-disable-next-line react/forbid-dom-props
                                            style={isResizeable ? { height, minHeight } : {}}
                                            onClick={!expanded && expandOnClick ? () => setExpanded(true) : undefined}
                                            onMouseDown={onResizeStart}
                                        >
                                            <ErrorBoundary>
                                                <Component
                                                    attributes={attributes}
                                                    updateAttributes={updateAttributes}
                                                />
                                                {isEditable && isResizeable ? (
                                                    <div
                                                        className="NotebookNode__resize-handle"
                                                        aria-hidden="true"
                                                        onPointerDown={onResizeHandlePointerDown}
                                                    />
                                                ) : null}
                                            </ErrorBoundary>
                                        </div>
                                    </>
                                )}
                            </ErrorBoundary>
                        </div>
                    </div>
                </div>
            </BindLogic>
        </NotebookNodeContext.Provider>
    )
}

export const MemoizedNodeWrapper = memo(NodeWrapper) as typeof NodeWrapper

/**
 * Registers a notebook node component so the markdown notebook registry (KNOWN_NODES)
 * can render it. The returned options are also the module's export for direct imports.
 */
export function createPostHogWidgetNode<T extends CustomNotebookNodeAttributes>(
    options: CreatePostHogWidgetNodeOptions<T>
): CreatePostHogWidgetNodeOptions<T> {
    const DefaultComponent = options.Component
    const ToolbarComponent = options.ToolbarComponent
    const registeredOptions: CreatePostHogWidgetNodeOptions<T> = options.views || options.ToolbarComponent
        ? {
              ...options,
              Component: (props: NotebookNodeProps<T>): JSX.Element | null => {
                  const viewKey = typeof props.attributes.view === 'string' ? props.attributes.view : null
                  const ViewComponent = (viewKey ? options.views?.[viewKey]?.Component : null) ?? DefaultComponent

                  return (
                      <>
                          {ToolbarComponent ? <ToolbarComponent {...props} /> : null}
                          <ViewComponent {...props} />
                      </>
                  )
              },
          }
        : options

    KNOWN_NODES[options.nodeType] = registeredOptions
    return registeredOptions
}

export const NotebookNodeChildRenderer = ({
    // nodeLogic: nodeLogic,
    content,
}: {
    // nodeLogic: BuiltLogic<notebookNodeLogicType>
    content: NotebookNodeResource
}): JSX.Element => {
    const options = KNOWN_NODES[content.type]

    // TODO: Respect attr changes

    // TODO: Allow deletion

    return (
        <MemoizedNodeWrapper
            {...options}
            // parentNodeLogic={nodeLogic}
            Component={options.Component}
            nodeType={content.type}
            titlePlaceholder={options.titlePlaceholder}
            attributes={content.attrs}
            updateAttributes={() => undefined}
            selected={false}
        />
    )
}