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.3 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { PaginationManual, Sorting } from '@posthog/lemon-ui'

import api, { CountedPaginatedResponse } from 'lib/api'
import { objectClean, objectsEqual } from 'lib/utils/objects'

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

import { NotebookListItemType, NotebookNodeType } from '../types'
import type { NotebookType } from '../types'

export interface NotebooksListFilters {
    search: string
    // UUID of the user that created the notebook
    createdBy: string | null
    contains: NotebookNodeType[]
}

export const DEFAULT_FILTERS: NotebooksListFilters = {
    search: '',
    createdBy: null,
    contains: [],
}

const RESULTS_PER_PAGE = 50
const DEFAULT_SORTING: Sorting = { columnKey: '-created_at', order: 1 }

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebooksTableLogicValues {
    notebookTemplates: NotebookType[] // notebooksModel
    breadcrumbs: Breadcrumb[]
    filters: NotebooksListFilters
    notebooks: NotebookListItemType[]
    notebooksAndTemplates: NotebookListItemType[]
    notebooksResponse: CountedPaginatedResponse<NotebookListItemType> | null
    notebooksResponseLoading: boolean
    page: number
    pagination: PaginationManual
    sidePanelContext: SidePanelSceneContext
    sortValue: string | null
    tableSorting: Sorting
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebooksTableLogicActions {
    deleteNotebookSuccess: (
        notebooks: NotebookListItemType[],
        payload?:
            | {
                  shortId: string
                  title: string | undefined
              }
            | undefined
    ) => {
        notebooks: NotebookListItemType[]
        payload?: {
            shortId: string
            title: string | undefined
        }
    } // notebooksModel
    loadNotebooks: () => {
        value: true
    }
    loadNotebooksFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadNotebooksSuccess: (
        notebooksResponse: CountedPaginatedResponse<NotebookListItemType>,
        payload?: {
            value: true
        }
    ) => {
        notebooksResponse: CountedPaginatedResponse<NotebookListItemType>
        payload?: {
            value: true
        }
    }
    setFilters: (filters: Partial<NotebooksListFilters>) => {
        filters: Partial<NotebooksListFilters>
    }
    setPage: (page: number) => {
        page: number
    }
    tableSortingChanged: (sorting: Sorting | null) => {
        sorting: Sorting | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebooksTableLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        notebooksAndTemplates: (
            notebooks: NotebookListItemType[],
            notebookTemplates: NotebookType[],
            filters: NotebooksListFilters
        ) => NotebookListItemType[]
        notebooks: (notebooksResponse: CountedPaginatedResponse<NotebookListItemType> | null) => NotebookListItemType[]
        pagination: (
            page: number,
            notebooksResponse: CountedPaginatedResponse<NotebookListItemType> | null
        ) => PaginationManual
    }
}

export type notebooksTableLogicType = MakeLogicType<
    notebooksTableLogicValues,
    notebooksTableLogicActions,
    Record<string, any>,
    notebooksTableLogicMeta
>

export const notebooksTableLogic = kea<notebooksTableLogicType>([
    path(['scenes', 'notebooks', 'NotebooksTable', 'notebooksTableLogic']),
    actions({
        loadNotebooks: true,
        setFilters: (filters: Partial<NotebooksListFilters>) => ({ filters }),
        tableSortingChanged: (sorting: Sorting | null) => ({
            sorting,
        }),
        setPage: (page: number) => ({ page }),
    }),
    connect(() => ({
        values: [notebooksModel, ['notebookTemplates']],
        actions: [notebooksModel, ['deleteNotebookSuccess']],
    })),
    reducers({
        filters: [
            DEFAULT_FILTERS,
            {
                setFilters: (state, { filters }) =>
                    objectClean({
                        ...state,
                        ...filters,
                    }),
            },
        ],
        sortValue: [
            null as string | null,
            {
                setSortValue: (_, { sortValue }) => sortValue,
            },
        ],
        page: [
            1,
            {
                setPage: (_, { page }) => page,
                setFilters: () => 1,
                setSortValue: () => 1,
            },
        ],
        tableSorting: [
            DEFAULT_SORTING,
            { persist: true },
            {
                tableSortingChanged: (_, { sorting }) => sorting || DEFAULT_SORTING,
            },
        ],
    }),
    loaders(({ values }) => ({
        notebooksResponse: [
            null as CountedPaginatedResponse<NotebookListItemType> | null,
            {
                loadNotebooks: async (_, breakpoint) => {
                    // TODO: Support pagination
                    await breakpoint(100)

                    const contains = values.filters?.contains.map((type) => ({ type, attrs: {} })) || undefined

                    const createdByForQuery =
                        values.filters?.createdBy === DEFAULT_FILTERS.createdBy ? undefined : values.filters?.createdBy

                    const res = await api.notebooks.list({
                        contains,
                        created_by: createdByForQuery ?? undefined,
                        search: values.filters?.search || undefined,
                        order: values.sortValue ?? '-last_modified_at',
                        limit: RESULTS_PER_PAGE,
                        offset: (values.page - 1) * RESULTS_PER_PAGE,
                    })

                    breakpoint()
                    return res
                },
            },
        ],
    })),
    listeners(({ actions }) => ({
        setFilters: () => actions.loadNotebooks(),
        setSortValue: () => actions.loadNotebooks(),
        setPage: () => actions.loadNotebooks(),
        deleteNotebookSuccess: () => actions.loadNotebooks(),
    })),
    selectors(({ actions }) => ({
        notebooksAndTemplates: [
            (s) => [s.notebooks, s.notebookTemplates, s.filters],
            (
                notebooks: NotebookListItemType[],
                notebookTemplates: NotebookType[],
                filters: NotebooksListFilters
            ): NotebookListItemType[] => {
                const includeTemplates = objectsEqual(filters, DEFAULT_FILTERS)
                return [...(includeTemplates ? (notebookTemplates as NotebookListItemType[]) : []), ...notebooks]
            },
        ],

        notebooks: [
            (s) => [s.notebooksResponse],
            (notebooksResponse: CountedPaginatedResponse<NotebookListItemType> | null): NotebookListItemType[] => {
                return notebooksResponse?.results || []
            },
        ],

        pagination: [
            (s) => [s.page, s.notebooksResponse],
            (
                page: number,
                notebooksResponse: CountedPaginatedResponse<NotebookListItemType> | null
            ): PaginationManual => {
                return {
                    controlled: true,
                    pageSize: RESULTS_PER_PAGE,
                    currentPage: page,
                    entryCount: notebooksResponse?.count ?? 0,
                    onBackward: () => actions.setPage(page - 1),
                    onForward: () => actions.setPage(page + 1),
                }
            },
        ],
    })),
    selectors({
        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => [
                {
                    key: 'notebooks',
                    name: 'Notebooks',
                    iconType: 'notebook',
                },
            ],
        ],
        [SIDE_PANEL_CONTEXT_KEY]: [
            () => [],
            (): SidePanelSceneContext => ({
                activity_scope: ActivityScope.NOTEBOOK,
            }),
        ],
    }),
])