: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { isAnalyticsType } from 'scenes/analytics/analyticsUtils'
import { urls } from 'scenes/urls'
import { fileSystemTypes, getTreeItemsNew } from '~/products'
import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'
import {
LibraryObjectType,
baseObjectType,
isLibraryEntry,
isLibraryType,
libraryListHref,
sortLibraryTypes,
} from './libraryUtils'
export const LIBRARY_PAGE_SIZE = 50
// "All objects" drops tool and view entries after each page loads, so it reads ahead until a page has
// something to show. This caps how far it reads ahead in one go.
const MAX_PAGES_PER_LOAD = 5
const PLURAL_LABELS: Record<string, string> = {
session_recording_playlist: 'Replay playlists',
}
export interface LibraryObjects {
results: FileSystemEntry[]
count: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface libraryLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
createItemsByType: Record<string, FileSystemImport[]>
hasMore: boolean
loadFailed: boolean
objectType: string
objectTypeByValue: Record<string, LibraryObjectType>
objectTypes: LibraryObjectType[]
objects: LibraryObjects
objectsLoading: boolean
search: string
visibleObjects: FileSystemEntry[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface libraryLogicActions {
loadMoreObjects: (_: void) => void
loadMoreObjectsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadMoreObjectsSuccess: (
objects: {
count: number
results: FileSystemEntry[]
},
payload?: void
) => {
objects: {
count: number
results: FileSystemEntry[]
}
payload?: void
}
loadObjects: (_: void) => void
loadObjectsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadObjectsSuccess: (
objects: LibraryObjects,
payload?: void
) => {
objects: LibraryObjects
payload?: void
}
setObjectType: (objectType: string) => {
objectType: string
}
setSearch: (search: string) => {
search: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface libraryLogicMeta {
__keaTypeGenInternalSelectorTypes: {
objectTypes: (featureFlags: FeatureFlagsSet) => LibraryObjectType[]
objectTypeByValue: (objectTypes: LibraryObjectType[]) => Record<string, LibraryObjectType>
createItemsByType: (featureFlags: FeatureFlagsSet) => Record<string, FileSystemImport[]>
visibleObjects: (objects: LibraryObjects) => FileSystemEntry[]
hasMore: (objects: LibraryObjects) => boolean
}
}
export type libraryLogicType = MakeLogicType<
libraryLogicValues,
libraryLogicActions,
Record<string, any>,
libraryLogicMeta
>
export const libraryLogic = kea<libraryLogicType>([
path(['scenes', 'library', 'libraryLogic']),
connect(() => ({ values: [featureFlagLogic, ['featureFlags']] })),
actions({
setObjectType: (objectType: string) => ({ objectType }),
setSearch: (search: string) => ({ search }),
}),
reducers({
objectType: ['', { setObjectType: (_, { objectType }) => objectType }],
search: ['', { setSearch: (_, { search }) => search }],
}),
loaders(({ values }) => {
const fetchPage = (offset: number): Promise<LibraryObjects> =>
api.fileSystem
.list({
search: values.search || undefined,
notType: 'folder',
...(values.objectType === 'insight'
? { type__startswith: 'insight' }
: values.objectType
? { type: values.objectType }
: {}),
orderBy: '-created_at',
offset,
limit: LIBRARY_PAGE_SIZE,
})
.then((response) => ({ results: response.results, count: response.count }))
const fetchVisiblePage = async (offset: number): Promise<LibraryObjects> => {
const results: FileSystemEntry[] = []
let count = 0
for (let page = 0; page < MAX_PAGES_PER_LOAD; page++) {
const next = await fetchPage(offset + results.length)
results.push(...next.results)
count = next.count
const exhausted = next.results.length === 0 || offset + results.length >= count
if (exhausted || values.objectType || results.some(isLibraryEntry)) {
break
}
}
return { results, count }
}
return {
objects: [
{ results: [], count: 0 } as LibraryObjects,
{
loadObjects: async (_: void, breakpoint) => {
await breakpoint(250)
const page = await fetchVisiblePage(0)
breakpoint()
return page
},
loadMoreObjects: async (_: void, breakpoint) => {
const page = await fetchVisiblePage(values.objects.results.length)
breakpoint()
return { results: [...values.objects.results, ...page.results], count: page.count }
},
},
],
}
}),
reducers({
loadFailed: [
false,
{
loadObjects: () => false,
loadObjectsFailure: () => true,
loadMoreObjectsFailure: () => true,
},
],
}),
selectors({
objectTypes: [
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): LibraryObjectType[] =>
sortLibraryTypes(
Object.entries(fileSystemTypes)
.filter(
([type, entry]) =>
isLibraryType(type) &&
(!('flag' in entry) || !!featureFlags[entry.flag as keyof FeatureFlagsSet])
)
.map(([value, entry]) => ({
value,
label: entry.name,
pluralLabel: PLURAL_LABELS[value] ?? `${entry.name}s`,
}))
),
],
objectTypeByValue: [
(s) => [s.objectTypes],
(objectTypes: LibraryObjectType[]): Record<string, LibraryObjectType> =>
Object.fromEntries(objectTypes.map((type) => [type.value, type])),
],
createItemsByType: [
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): Record<string, FileSystemImport[]> => {
const byType: Record<string, FileSystemImport[]> = {}
for (const item of getTreeItemsNew()) {
const type = baseObjectType(item.type)
if (!item.href || !isFileSystemImportFlagEnabled(item, featureFlags)) {
continue
}
byType[type] = [...(byType[type] ?? []), item]
}
return byType
},
],
// "All objects" asks for every type, so drop the ones that live in Tools and Analytics.
visibleObjects: [
(s) => [s.objects],
(objects: LibraryObjects): FileSystemEntry[] => objects.results.filter(isLibraryEntry),
],
hasMore: [(s) => [s.objects], (objects: LibraryObjects): boolean => objects.results.length < objects.count],
}),
listeners(({ actions }) => ({
setObjectType: () => actions.loadObjects(),
setSearch: () => actions.loadObjects(),
})),
urlToAction(({ actions, values, cache }) => {
const openType = (objectType: string): void => {
// The Library scene renders nothing without the flag, so it must not load anything either.
if (!values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
return
}
if (objectType && !isLibraryType(objectType)) {
router.actions.replace(
isAnalyticsType(objectType) ? urls.analyticsList({ type: objectType }) : urls.analyticsList()
)
return
}
const listHref = objectType ? libraryListHref(objectType) : null
if (listHref) {
router.actions.replace(listHref)
return
}
if (objectType !== values.objectType || !cache.loaded) {
cache.loaded = true
actions.setObjectType(objectType)
}
}
return {
[urls.library()]: () => openType(''),
[urls.library(':objectType')]: ({ objectType }) => openType(objectType ?? ''),
}
}),
])