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.

9.3 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'
import type { BuiltLogic } from 'kea'
import { router } from 'kea-router'

import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { analyticsBackLink } from 'scenes/analytics/analyticsBackLink'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
import { notebooksModel } from '~/models/notebooksModel'
import { ActivityScope, Breadcrumb, ProjectTreeRef } from '~/types'

import type { JSONContent } from '../../lib/components/RichContentEditor/types'
import { notebookLogic } from './Notebook/notebookLogic'
import type { notebookLogicType } from './Notebook/notebookLogic'
import type { NotebookTarget } from './types'
import type { NotebookType } from './types'

export type NotebookSceneLogicProps = {
    shortId: string
}

const MAX_SCROLL_RESTORE_FRAMES = 60
const scrollPositions = new Map<string, number>()

function getSceneScrollContainer(): HTMLElement | null {
    return panelLayoutLogic.findMounted()?.values.mainContentRef?.current ?? null
}

function restoreScrollPosition(cache: Record<string, any>): void {
    const target: number | undefined = cache.scrollRestoreTarget
    cache.scrollRestoreTarget = undefined
    if (!target) {
        return
    }
    let frames = 0
    const restore = (): void => {
        const element = getSceneScrollContainer()
        if (!element) {
            return
        }
        if (element.scrollHeight - element.clientHeight >= target || ++frames >= MAX_SCROLL_RESTORE_FRAMES) {
            element.scrollTop = target
            return
        }
        cache.disposables.add(() => {
            const id = requestAnimationFrame(restore)
            return () => cancelAnimationFrame(id)
        }, 'scrollRestore')
    }
    restore()
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookSceneLogicValues {
    isLocalOnly: boolean // notebookLogic
    notebook: NotebookType | null // notebookLogic
    notebookLoading: boolean // notebookLogic
    notebooksLoading: boolean // notebooksModel
    breadcrumbs: Breadcrumb[]
    loading: boolean
    notebookId: string
    projectTreeRef: ProjectTreeRef | null
    sidePanelContext: SidePanelSceneContext | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookSceneLogicActions {
    loadNotebook: () => {
        value: true
    } // notebookLogic
    loadNotebookSuccess: (
        notebook: NotebookType | null,
        payload?:
            | {
                  value: true
              }
            | undefined
    ) => {
        notebook: NotebookType | null
        payload?: {
            value: true
        }
    } // notebookLogic
    createNotebook: (
        location: NotebookTarget,
        title?: string | undefined,
        content?: JSONContent[] | undefined,
        onCreate?: ((notebook: BuiltLogic<notebookLogicType>) => void) | undefined,
        shortId?: string | undefined
    ) => {
        content: JSONContent[] | undefined
        location: NotebookTarget
        onCreate: ((notebook: BuiltLogic<notebookLogicType>) => void) | undefined
        shortId: string | undefined
        title: string | undefined
    } // notebooksModel
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookSceneLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        notebookId: (shortId: string) => string
        loading: (notebookLoading: boolean, notebooksLoading: boolean) => boolean
        breadcrumbs: (
            notebook: NotebookType | null,
            loading: boolean,
            searchParams: Record<string, any>,
            featureFlags: FeatureFlagsSet
        ) => Breadcrumb[]
        projectTreeRef: (arg: string) => ProjectTreeRef | null
        sidePanelContext: (notebookId: string, isLocalOnly: boolean) => SidePanelSceneContext | null
    }
}

export type notebookSceneLogicType = MakeLogicType<
    notebookSceneLogicValues,
    notebookSceneLogicActions,
    NotebookSceneLogicProps,
    notebookSceneLogicMeta
>

export const notebookSceneLogic = kea<notebookSceneLogicType>([
    path((key) => ['scenes', 'notebooks', 'notebookSceneLogic', key]),
    props({} as NotebookSceneLogicProps),
    key(({ shortId }) => shortId),
    connect((props: NotebookSceneLogicProps) => ({
        values: [
            notebookLogic(props),
            ['notebook', 'notebookLoading', 'isLocalOnly'],
            notebooksModel,
            ['notebooksLoading'],
        ],
        actions: [notebookLogic(props), ['loadNotebook', 'loadNotebookSuccess'], notebooksModel, ['createNotebook']],
    })),
    selectors(() => ({
        notebookId: [(_, p) => [p.shortId], (shortId: string) => shortId],

        loading: [
            (s) => [s.notebookLoading, s.notebooksLoading],
            (notebookLoading: boolean, notebooksLoading: boolean) => notebookLoading || notebooksLoading,
        ],

        breadcrumbs: [
            (s) => [s.notebook, s.loading, router.selectors.searchParams, featureFlagLogic.selectors.featureFlags],
            (
                notebook: NotebookType | null,
                loading: boolean,
                searchParams: Record<string, any>,
                featureFlags: FeatureFlagsSet
            ): Breadcrumb[] => {
                // The Analytics list that opened the notebook names the way back, like the dashboard scene allows.
                const backLink = analyticsBackLink(searchParams, featureFlags)
                const parent: Breadcrumb = backLink
                    ? {
                          key: backLink.url,
                          name: backLink.name,
                          path: backLink.url,
                          iconType: 'notebook',
                      }
                    : notebook?.parent_resource?.type === 'account'
                      ? {
                            key: Scene.CustomerAnalytics,
                            name: 'Accounts',
                            path: urls.customerAnalyticsAccount(notebook.parent_resource.id),
                            iconType: 'group',
                        }
                      : {
                            key: Scene.Notebooks,
                            name: 'Notebooks',
                            path: urls.notebooks(),
                            iconType: 'notebook',
                        }
                return [
                    parent,
                    {
                        key: [Scene.Notebook, notebook?.short_id || 'new'],
                        name: notebook ? notebook?.title || 'Unnamed' : loading ? null : 'Notebook not found',
                        iconType: 'notebook',
                    },
                ]
            },
        ],

        projectTreeRef: [
            () => [(_, props: NotebookSceneLogicProps) => props.shortId],
            (shortId: string): ProjectTreeRef | null =>
                shortId === 'new' ? null : { type: 'notebook', ref: String(shortId) },
        ],

        [SIDE_PANEL_CONTEXT_KEY]: [
            (s) => [s.notebookId, s.isLocalOnly],
            (notebookId: string, isLocalOnly: boolean): SidePanelSceneContext | null => {
                return notebookId && !isLocalOnly
                    ? {
                          activity_scope: ActivityScope.NOTEBOOK,
                          activity_item_id: notebookId,
                          access_control_resource: 'notebook',
                          access_control_resource_id: notebookId,
                      }
                    : null
            },
        ],
    })),

    listeners(({ cache }) => ({
        loadNotebookSuccess: () => restoreScrollPosition(cache),
    })),
    afterMount(({ actions, props, values, cache }) => {
        if (router.values.lastMethod === 'POP') {
            cache.scrollRestoreTarget = scrollPositions.get(props.shortId)
            if (values.notebook) {
                restoreScrollPosition(cache)
            }
        }
        // Navigating away resets the scroll position while this notebook is still rendered, so positions are
        // recorded while mounted, and only while the URL still points at this notebook.
        const pathname = router.values.location.pathname
        cache.disposables.add(() => {
            // Scroll events don't bubble, so a capturing listener sees the scene container even when it mounts later.
            const onScroll = (event: Event): void => {
                const element = getSceneScrollContainer()
                if (element && event.target === element && router.values.location.pathname === pathname) {
                    scrollPositions.set(props.shortId, element.scrollTop)
                }
            }
            document.addEventListener('scroll', onScroll, { capture: true, passive: true })
            return () => document.removeEventListener('scroll', onScroll, { capture: true })
        }, 'scrollTracking')
        // notebookLogic already revalidates a retained copy when it mounts.
        if (props.shortId !== 'new' && !values.notebookLoading) {
            actions.loadNotebook()
        }
    }),
])