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.

refactor(frontend): drop the unused sidebar machinery from navigation3000Logic (#105129)

Paul D'Ambrade4486fbba7c
diff --git a/frontend/src/layout/navigation-3000/navigationLogic.tsx b/frontend/src/layout/navigation-3000/navigationLogic.tsx
index 8d70b61f45f7..43ae74565e08 100644
--- a/frontend/src/layout/navigation-3000/navigationLogic.tsx
+++ b/frontend/src/layout/navigation-3000/navigationLogic.tsx
@@ -1,179 +1,35 @@
-import { MakeLogicType, actions, connect, events, kea, listeners, path, props, reducers, selectors } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
-import React from 'react'
-
-import {
- IconChat,
- IconCursorClick,
- IconDashboard,
- IconDatabase,
- IconDecisionTree,
- IconGraph,
- IconHome,
- IconLive,
- IconLlmAnalytics,
- IconMessage,
- IconNotebook,
- IconPeople,
- IconPieChart,
- IconPlug,
- IconPlusSmall,
- IconRewindPlay,
- IconRocket,
- IconServer,
- IconSpotlight,
- IconTestTube,
- IconToggle,
- IconWarning,
-} from '@posthog/icons'
-import { LemonSkeleton, lemonToast } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
-import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { getAppContext } from 'lib/utils/getAppContext'
-import { isNotNil } from 'lib/utils/guards'
import { onboardingVariantChrome, resolveOnboardingFlowVariant } from 'scenes/onboarding/onboardingVariants'
import { organizationLogic } from 'scenes/organizationLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
-import { sessionRecordingSavedFiltersLogic } from 'scenes/session-recordings/filters/sessionRecordingSavedFiltersLogic'
-import { urls } from 'scenes/urls'
-
-import { groupsModel } from '~/models/groupsModel'
-import { AccessControlLevel, AccessControlResourceType, ReplayTabs } from '~/types'
-import type { GroupsAccessStatus } from '../../lib/introductions/groupsAccessLogic'
-import type { SceneConfig, SceneExport, SceneParams, SceneProps } from '../../scenes/sceneTypes'
-import type { GroupType, GroupTypeIndex, SavedSessionRecordingPlaylistsResult } from '../../types'
+import type { SceneConfig } from '../../scenes/sceneTypes'
import { navigationLogic } from '../navigation/navigationLogic'
-import { BasicListItem, ExtendedListItem, NavbarItem, SidebarNavbarItem } from './types'
-
-/** Multi-segment item keys are joined using this separator for easy comparisons. */
-export const ITEM_KEY_PART_SEPARATOR = '::'
export type Navigation3000Mode = 'none' | 'minimal' | 'zen' | 'full'
export type ZenModeTrigger = 'shortcut' | 'account_menu' | 'help_menu' | 'exit_button' | 'url'
-const MINIMUM_SIDEBAR_WIDTH_PX: number = 192
-const DEFAULT_SIDEBAR_WIDTH_PX: number = 288
-const MAXIMUM_SIDEBAR_WIDTH_PX: number = 1024
-const MAXIMUM_SIDEBAR_WIDTH_PERCENTAGE: number = 50
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface navigation3000LogicValues {
- groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel
- groupsAccessStatus: GroupsAccessStatus // groupsModel
mobileLayout: boolean // navigationLogic
isCurrentOrganizationUnavailable: boolean // organizationLogic
activeSceneId: string | null // sceneLogic
sceneConfig: SceneConfig | null // sceneLogic
- savedFilters: SavedSessionRecordingPlaylistsResult // sessionRecordingSavedFiltersLogic
- savedFiltersLoading: boolean // sessionRecordingSavedFiltersLogic
- accordionCollapseMapping: Record<string, boolean>
- activeNavbarItem: SidebarNavbarItem | null
- activeNavbarItemId: string | null
- activeNavbarItemIdRaw: string
- internalSearchTerm: string
- isListItemVisible: (key: string) => boolean
- isNavCollapsed: boolean
- isNavCollapsedDesktop: boolean
- isNavShown: boolean
- isNavShownMobile: boolean
- isResizeInProgress: boolean
- isSearchShown: boolean
- isSidebarKeyboardShortcutAcknowledged: boolean
- isSidebarShown: boolean
- lastFocusedItemIndex: number
- listItemAccordionCollapseMapping: Record<string, boolean>
mode: Navigation3000Mode
- navbarItemIdMapping: Record<string, NavbarItem>
- navbarItems: NavbarItem[][]
- newItemCategory: string | null
- newItemInlineCategory: string | null
- normalizedActiveListItemKey: number | string | string[] | null
- savingNewItem: boolean
- searchTerm: string
- sidebarContentsFlattened: BasicListItem[] | ExtendedListItem[]
- sidebarOverslide: number
- sidebarOverslideDirection: 'max' | 'min' | null
- sidebarWidth: number
zenMode: boolean
zenModeFromUrl: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface navigation3000LogicActions {
- setScene: (
- sceneId: string,
- sceneKey: string | undefined,
- params: SceneParams,
- scrollToTop?: boolean | undefined,
- exportedScene?: SceneExport<SceneProps> | undefined
- ) => {
- exportedScene: SceneExport<SceneProps> | undefined
- params: SceneParams
- sceneId: string
- sceneKey: string | undefined
- scrollToTop: boolean
- } // sceneLogic
- acknowledgeSidebarKeyboardShortcut: () => {
- value: true
- }
- beginResize: () => {
- value: true
- }
- cancelNewItem: () => {
- value: true
- }
- endResize: () => {
- value: true
- }
- focusNextItem: () => {
- value: true
- }
- focusPreviousItem: () => {
- value: true
- }
- hideNavOnMobile: () => {
- value: true
- }
- hideSidebar: () => {
- value: true
- }
- initiateNewItemInCategory: (category: string) => {
- category: string
- }
- initiateNewItemInlineInCategory: (category: string) => {
- category: string
- }
- saveNewItem: (itemName: string) => {
- itemName: string
- }
- saveNewItemComplete: () => {
- value: true
- }
- setIsSearchShown: (isSearchShown: boolean) => {
- isSearchShown: boolean
- }
- setLastFocusedItemByKey: (key: number | string) => {
- key: number | string
- }
- setLastFocusedItemIndex: (index: number) => {
- index: number
- }
- setSearchTerm: (searchTerm: string) => {
- searchTerm: string
- }
- setSidebarOverslide: (overslide: number) => {
- overslide: number
- }
- setSidebarWidth: (width: number) => {
- width: number
- }
setZenMode: (
zenMode: boolean,
trigger: ZenModeTrigger
@@ -181,40 +37,11 @@ export interface navigation3000LogicActions {
trigger: ZenModeTrigger
zenMode: boolean
}
- showNavOnMobile: () => {
- value: true
- }
- showSidebar: (newNavbarItemId?: string) => {
- newNavbarItemId: string | undefined
- }
- syncSidebarWidthWithMouseMove: (delta: number) => {
- delta: number
- }
- syncSidebarWidthWithViewport: () => {
- value: true
- }
- toggleAccordion: (key: string) => {
- key: string
- }
- toggleListItemAccordion: (key: string) => {
- key: string
- }
- toggleNavCollapsed: (override?: boolean) => {
- override: boolean | undefined
- }
- toggleSidebar: () => {
- value: true
- }
toggleZenMode: (trigger: ZenModeTrigger) => {
trigger: ZenModeTrigger
}
}
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface navigation3000LogicProps {
- inputElement?: HTMLInputElement | null
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface navigation3000LogicMeta {
__keaTypeGenInternalSelectorTypes: {
@@ -226,220 +53,33 @@ export interface navigation3000LogicMeta {
activeSceneId: string | null,
featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet
) => Navigation3000Mode
- isNavShown: (isNavShownMobile: boolean, mobileLayout: boolean) => boolean
- isNavCollapsed: (isNavCollapsedDesktop: boolean, mobileLayout: boolean) => boolean
- navbarItems: (
- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,
- savedFilters: SavedSessionRecordingPlaylistsResult,
- savedFiltersLoading: boolean
- ) => NavbarItem[][]
- navbarItemIdMapping: (navbarItems: NavbarItem[][]) => Record<string, NavbarItem>
- sidebarOverslideDirection: (sidebarOverslide: number) => 'max' | 'min' | null
- activeNavbarItem: (
- activeNavbarItemId: string | null,
- navbarItemIdMapping: Record<string, NavbarItem>
- ) => SidebarNavbarItem | null
- searchTerm: (internalSearchTerm: string, isSearchShown: boolean) => string
- sidebarContentsFlattened: (
- arg: import('./types').SidebarCategory[] | null
- ) => BasicListItem[] | ExtendedListItem[]
- normalizedActiveListItemKey: (
- arg: number | string | [string, number | string] | null
- ) => number | string | string[] | null
- isListItemVisible: (listItemAccordionCollapseMapping: Record<string, boolean>) => (key: string) => boolean
- activeNavbarItemId: (activeNavbarItemIdRaw: string) => string | null
- newItemCategory: (
- arg: import('./types').SidebarCategory[] | null,
- newItemInlineCategory: string | null,
- location: {
- hash: string
- pathname: string
- search: string
- }
- ) => string | null
}
}
export type navigation3000LogicType = MakeLogicType<
navigation3000LogicValues,
navigation3000LogicActions,
- navigation3000LogicProps,
+ Record<string, any>,
navigation3000LogicMeta
>
export const navigation3000Logic = kea<navigation3000LogicType>([
path(['layout', 'navigation-3000', 'navigationLogic']),
- props({} as { inputElement?: HTMLInputElement | null }),
connect(() => ({
values: [
- groupsModel,
- ['groupTypes', 'groupsAccessStatus'],
sceneLogic,
['sceneConfig', 'activeSceneId'],
navigationLogic,
['mobileLayout'],
- sessionRecordingSavedFiltersLogic,
- ['savedFilters', 'savedFiltersLoading'],
organizationLogic,
['isCurrentOrganizationUnavailable'],
],
- actions: [sceneLogic, ['setScene']],
})),
actions({
- hideSidebar: true,
- showSidebar: (newNavbarItemId?: string) => ({ newNavbarItemId }),
- toggleNavCollapsed: (override?: boolean) => ({ override }),
- showNavOnMobile: true,
- hideNavOnMobile: true,
- toggleSidebar: true,
- setSidebarWidth: (width: number) => ({ width }),
- setSidebarOverslide: (overslide: number) => ({ overslide }),
- syncSidebarWidthWithMouseMove: (delta: number) => ({ delta }),
- syncSidebarWidthWithViewport: true,
- beginResize: true,
- endResize: true,
- acknowledgeSidebarKeyboardShortcut: true,
- setIsSearchShown: (isSearchShown: boolean) => ({ isSearchShown }),
- setSearchTerm: (searchTerm: string) => ({ searchTerm }),
- initiateNewItemInCategory: (category: string) => ({ category }),
- initiateNewItemInlineInCategory: (category: string) => ({ category }),
- cancelNewItem: true,
- saveNewItem: (itemName: string) => ({ itemName }),
- saveNewItemComplete: true,
- setLastFocusedItemIndex: (index: number) => ({ index }),
- setLastFocusedItemByKey: (key: string | number) => ({ key }), // A wrapper over setLastFocusedItemIndex
- focusNextItem: true,
- focusPreviousItem: true,
- toggleAccordion: (key: string) => ({ key }),
- toggleListItemAccordion: (key: string) => ({ key }),
setZenMode: (zenMode: boolean, trigger: ZenModeTrigger) => ({ zenMode, trigger }),
toggleZenMode: (trigger: ZenModeTrigger) => ({ trigger }),
}),
reducers({
- isSidebarShown: [
- true,
- {
- hideSidebar: () => false,
- showSidebar: () => true,
- toggleSidebar: (isSidebarShown) => !isSidebarShown,
- },
- ],
- sidebarWidth: [
- DEFAULT_SIDEBAR_WIDTH_PX,
- {
- setSidebarWidth: (_, { width }) => width,
- },
- ],
- sidebarOverslide: [
- // Overslide is how far beyond the min/max sidebar width the cursor has moved
- 0,
- {
- setSidebarOverslide: (_, { overslide }) => overslide,
- },
- ],
- isResizeInProgress: [
- false,
- {
- beginResize: () => true,
- endResize: () => false,
- },
- ],
- isNavCollapsedDesktop: [
- false,
- { persist: true },
- {
- toggleNavCollapsed: (state, { override }) => override ?? !state,
- },
- ],
- isNavShownMobile: [
- false,
- { persist: true },
- {
- showNavOnMobile: () => true,
- hideNavOnMobile: () => false,
- },
- ],
- isSidebarKeyboardShortcutAcknowledged: [
- false,
- {
- persist: true,
- },
- {
- acknowledgeSidebarKeyboardShortcut: () => true,
- },
- ],
- activeNavbarItemIdRaw: [
- Scene.Dashboards as string,
- {
- persist: true,
- },
- {
- showSidebar: (state, { newNavbarItemId }) => newNavbarItemId || state,
- setScene: (state, { sceneId }) => sceneId || state,
- },
- ],
- isSearchShown: [
- true,
- {
- setIsSearchShown: (_, { isSearchShown }) => isSearchShown,
- },
- ],
- internalSearchTerm: [
- // Do not reference this outside of this file
- // `searchTerm` is the outwards-facing value, as it's made empty when search is hidden
- '',
- {
- setSearchTerm: (_, { searchTerm }) => searchTerm,
- },
- ],
- lastFocusedItemIndex: [
- -1 as number,
- {
- setLastFocusedItemIndex: (_, { index }) => index,
- },
- ],
- accordionCollapseMapping: [
- {} as Record<string, boolean>,
- {
- persist: true,
- },
- {
- toggleAccordion: (state, { key }) => ({
- ...state,
- [key]: !state[key],
- }),
- },
- ],
- listItemAccordionCollapseMapping: [
- {} as Record<string, boolean>,
- {
- persist: true,
- },
- {
- toggleListItemAccordion: (state, { key }) => ({
- ...state,
- [key]: !state[key],
- }),
- },
- ],
- newItemInlineCategory: [
- null as string | null,
- {
- initiateNewItemInlineInCategory: (_, { category }) => category,
- saveNewItemComplete: () => null,
- cancelNewItem: () => null,
- toggleSidebar: () => null,
- showSidebar: () => null,
- hideSidebar: () => null,
- },
- ],
- savingNewItem: [
- false,
- {
- saveNewItem: () => true,
- saveNewItemComplete: () => false,
- },
- ],
zenMode: [
false,
{ persist: true },
@@ -455,106 +95,6 @@ export const navigation3000Logic = kea<navigation3000LogicType>([
toggleZenMode: ({ trigger }) => {
actions.setZenMode(!values.zenMode, trigger)
},
- initiateNewItemInCategory: ({ category: categoryKey }) => {
- let category = values.activeNavbarItem?.logic.values.contents?.find((item) => item.key === categoryKey)
- if (!category) {
- // Only the SQL editor uses this component, with the tree view, the activeNavbarItem doesnt get properly set, so lets fallback
- category = (
- values.navbarItemIdMapping[Scene.SQLEditor] as SidebarNavbarItem
- )?.logic.values.contents?.find((item) => item.key === categoryKey)
- if (!category) {
- throw new Error(`Sidebar category '${categoryKey}' doesn't exist`)
- }
- }
-
- if (!category.onAdd || typeof category.onAdd !== 'function') {
- throw new Error(`Sidebar category '${categoryKey}' doesn't support onAdd`)
- }
-
- if (category.onAdd.length === 0) {
- ;(category.onAdd as () => void)() // If a zero-arg function, call it immediately
- } else {
- actions.initiateNewItemInlineInCategory(categoryKey) // Otherwise initiate inline item creation
- }
- },
- saveNewItem: async ({ itemName }) => {
- try {
- const categoryKey = values.newItemInlineCategory
- if (!categoryKey) {
- throw new Error(`Can't save new sidebar item without a category`)
- }
- const category = values.activeNavbarItem?.logic.values.contents?.find(
- (item) => item.key === categoryKey
- )
- if (!category) {
- throw new Error(`Sidebar category '${categoryKey}' doesn't exist`)
- } else if (!category.onAdd || typeof category.onAdd !== 'function') {
- throw new Error(`Sidebar category '${categoryKey}' doesn't support onAdd`)
- }
- await category.onAdd(itemName)
- } catch (e) {
- posthog.captureException(e)
- console.error(e)
- lemonToast.error('Something went wrong while saving the item. Please try again.')
- } finally {
- actions.saveNewItemComplete()
- }
- },
- syncSidebarWidthWithMouseMove: ({ delta }) => {
- const newWidthRaw = values.sidebarWidth + values.sidebarOverslide + delta
- let newWidth = newWidthRaw
- if (newWidth < MINIMUM_SIDEBAR_WIDTH_PX) {
- newWidth = MINIMUM_SIDEBAR_WIDTH_PX
- } else if (newWidth > MAXIMUM_SIDEBAR_WIDTH_PX) {
- newWidth = MAXIMUM_SIDEBAR_WIDTH_PX
- }
- if (newWidth > window.innerWidth * (MAXIMUM_SIDEBAR_WIDTH_PERCENTAGE / 100)) {
- newWidth = window.innerWidth * (MAXIMUM_SIDEBAR_WIDTH_PERCENTAGE / 100)
- }
- actions.setSidebarWidth(newWidth)
- actions.setSidebarOverslide(newWidthRaw - newWidth)
- if (newWidthRaw < MINIMUM_SIDEBAR_WIDTH_PX / 2) {
- if (values.isSidebarShown) {
- actions.hideSidebar()
- }
- } else {
- if (!values.isSidebarShown) {
- actions.showSidebar()
- }
- }
- },
- syncSidebarWidthWithViewport: () => {
- if (values.sidebarWidth > window.innerWidth * (MAXIMUM_SIDEBAR_WIDTH_PERCENTAGE / 100)) {
- // Clamp
- actions.setSidebarWidth(window.innerWidth * (MAXIMUM_SIDEBAR_WIDTH_PERCENTAGE / 100))
- }
- },
- endResize: () => {
- actions.setSidebarOverslide(values.isSidebarShown ? 0 : -MINIMUM_SIDEBAR_WIDTH_PX)
- },
- toggleSidebar: () => {
- actions.endResize()
- },
- focusNextItem: () => {
- const nextIndex = values.lastFocusedItemIndex + 1
- if (nextIndex < values.sidebarContentsFlattened.length) {
- actions.setLastFocusedItemIndex(nextIndex)
- }
- },
- focusPreviousItem: () => {
- const nextIndex = values.lastFocusedItemIndex - 1
- if (nextIndex >= -1) {
- actions.setLastFocusedItemIndex(nextIndex)
- }
- },
- setLastFocusedItemByKey: ({ key }) => {
- const index = values.sidebarContentsFlattened.findIndex((item) =>
- Array.isArray(item.key) ? item.key.includes(key as string) : item.key === key
- )
- if (index !== -1) {
- actions.setLastFocusedItemIndex(index)
- }
- },
})),
selectors({
zenModeFromUrl: [
@@ -601,424 +141,8 @@ export const navigation3000Logic = kea<navigation3000LogicType>([
return sceneConfig?.layout !== 'plain' ? 'full' : 'none'
},
],
- isNavShown: [
- (s) => [s.isNavShownMobile, s.mobileLayout],
- (isNavShownMobile: boolean, mobileLayout: boolean): boolean => !mobileLayout || isNavShownMobile,
- ],
- isNavCollapsed: [
- (s) => [s.isNavCollapsedDesktop, s.mobileLayout],
- (isNavCollapsedDesktop: boolean, mobileLayout: boolean): boolean => !mobileLayout && isNavCollapsedDesktop,
- ],
- navbarItems: [
- (s) => [featureFlagLogic.selectors.featureFlags, s.savedFilters, s.savedFiltersLoading],
- (
- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,
- savedFilters: import('~/types').SavedSessionRecordingPlaylistsResult,
- savedFiltersLoading: boolean
- ): NavbarItem[][] => {
- return [
- [
- {
- identifier: Scene.ProjectHomepage,
- label: 'Home',
- icon: <IconHome />,
- to: urls.projectRoot(),
- },
- {
- identifier: Scene.Dashboards,
- label: 'Dashboards',
- icon: <IconDashboard />,
- tooltipDocLink: 'https://posthog.com/docs/product-analytics/dashboards',
- to: urls.dashboards(),
- },
- {
- identifier: Scene.Notebooks,
- label: 'Notebooks',
- icon: <IconNotebook />,
- to: urls.notebooks(),
- tooltipDocLink: 'https://posthog.com/docs/notebooks',
- },
- {
- identifier: Scene.DataManagement,
- label: 'Data management',
- icon: <IconDatabase />,
- to: urls.eventDefinitions(),
- tooltipDocLink: 'https://posthog.com/docs/data',
- },
- {
- identifier: Scene.Persons,
- label: 'People and groups',
- icon: <IconPeople />,
- to: urls.persons(),
- tooltipDocLink: 'https://posthog.com/docs/data/persons',
- },
- {
- identifier: Scene.ExploreEvents,
- label: 'Activity',
- icon: <IconLive />,
- to: urls.activity(),
- tooltipDocLink: 'https://posthog.com/docs/data/events',
- },
- ],
- [
- {
- identifier: Scene.SavedInsights,
- label: 'Product analytics',
- icon: <IconGraph />,
- tooltipDocLink: 'https://posthog.com/docs/product-analytics/insights',
- to: urls.savedInsights(),
- sideAction:
- getAppContext()?.resource_access_control?.[AccessControlResourceType.Insight] ===
- AccessControlLevel.Editor
- ? {
- icon: <IconPlusSmall />, // The regular plus is too big
- to: urls.insightNew(),
- tooltip: 'New insight',
- identifier: Scene.Insight,
- }
- : undefined,
- },
- {
- identifier: Scene.WebAnalytics,
- label: 'Web analytics',
- icon: <IconPieChart />,
- to: urls.webAnalytics(),
- tooltipDocLink: 'https://posthog.com/docs/web-analytics/getting-started',
- },
- {
- identifier: Scene.Replay,
- label: 'Session replay',
- icon: <IconRewindPlay />,
- to: urls.replay(),
- tooltipDocLink: 'https://posthog.com/docs/session-replay',
- sideAction: {
- identifier: 'replay-dropdown',
- dropdown: {
- onVisibilityChange: (visible: boolean): void => {
- if (visible) {
- sessionRecordingSavedFiltersLogic.actions.loadSavedFiltersIfNeeded()
- }
- },
- overlay: (
- <LemonMenuOverlay
- items={
- savedFiltersLoading
- ? [
- {
- title: 'Saved filters',
- items: [
- {
- label: () => (
- <div className="px-2 py-1">
- <LemonSkeleton
- className="h-4 w-32"
- repeat={3}
- />
- </div>
- ),
- },
- ],
- },
- ]
- : savedFilters.count > 0
- ? [
- {
- title: 'Saved filters',
- items: savedFilters.results.map((savedFilter) => ({
- label:
- savedFilter.name ||
- savedFilter.derived_name ||
- 'Unnamed',
- to: combineUrl(urls.replay(ReplayTabs.Home), {
- savedFilterId: savedFilter.short_id,
- }).url,
- })),
- },
- ]
- : [
- {
- label: 'All recordings',
- to: urls.replay(ReplayTabs.Home),
- },
- {
- label: 'Saved filters',
- to: urls.replay(ReplayTabs.Home),
- },
- ]
- }
- />
- ),
- placement: 'bottom-end',
- },
- },
- },
- {
- identifier: Scene.FeatureFlags,
- label: 'Feature flags',
- icon: <IconToggle />,
- to: urls.featureFlags(),
- tooltipDocLink: 'https://posthog.com/docs/feature-flags/creating-feature-flags',
- },
- {
- identifier: Scene.Experiments,
- label: 'Experiments',
- icon: <IconTestTube />,
- to: urls.experiments(),
- tooltipDocLink: 'https://posthog.com/docs/experiments/creating-an-experiment',
- },
- {
- identifier: Scene.Surveys,
- label: 'Surveys',
- icon: <IconMessage />,
- to: urls.surveys(),
- tooltipDocLink: 'https://posthog.com/docs/surveys/creating-surveys',
- },
- featureFlags[FEATURE_FLAGS.PRODUCT_TOURS]
- ? {
- identifier: Scene.ProductTours,
- label: 'Product tours',
- icon: <IconSpotlight />,
- tag: 'alpha' as const,
- to: urls.productTours(),
- }
- : null,
- {
- identifier: Scene.EarlyAccessFeatures,
- label: 'Early access features',
- icon: <IconRocket />,
- to: urls.earlyAccessFeatures(),
- tooltipDocLink: 'https://posthog.com/docs/feature-flags/early-access-feature-management',
- },
- featureFlags[FEATURE_FLAGS.USER_INTERVIEWS]
- ? {
- identifier: Scene.UserInterviews,
- label: 'User research',
- icon: <IconChat />,
- tag: 'alpha' as const,
- to: urls.userInterviews(),
- }
- : null,
- {
- identifier: 'AIObservability',
- label: 'AI observability',
- icon: <IconLlmAnalytics />,
- to: urls.aiObservabilityDashboard(),
- tooltipDocLink: 'https://posthog.com/docs/ai-observability/dashboard',
- },
- featureFlags[FEATURE_FLAGS.MCP_ANALYTICS]
- ? {
- identifier: 'MCPAnalytics',
- label: 'MCP analytics',
- icon: <IconLlmAnalytics />,
- to: urls.mcpAnalytics(),
- tooltipDocLink: 'https://posthog.com/docs/mcp-analytics/installation',
- }
- : null,
- {
- identifier: Scene.Logs,
- label: 'Logs',
- icon: <IconLive />,
- to: urls.logs(),
- tag: 'beta' as const,
- tooltipDocLink: 'https://posthog.com/docs/logs',
- },
- {
- identifier: Scene.ErrorTracking,
- label: 'Error tracking',
- icon: <IconWarning />,
- to: urls.errorTracking(),
- tooltipDocLink: 'https://posthog.com/docs/error-tracking/stack-traces',
- },
- {
- identifier: Scene.SQLEditor,
- label: 'SQL editor',
- icon: <IconServer />,
- to: urls.sqlEditor(),
- tooltipDocLink: 'https://posthog.com/docs/data-warehouse/query#querying-sources-with-sql',
- },
- {
- identifier: Scene.WebScripts,
- label: 'Web scripts',
- icon: <IconPlug />,
- to: urls.webScripts(),
- tooltipDocLink: 'https://posthog.com/docs/cdp/apps',
- },
- {
- identifier: Scene.Heatmaps,
- label: 'Heatmaps',
- icon: <IconCursorClick />,
- to: urls.heatmaps(),
- tag: 'beta' as const,
- tooltipDocLink: 'https://posthog.com/docs/toolbar/heatmaps',
- },
- featureFlags[FEATURE_FLAGS.LINKS]
- ? {
- identifier: Scene.Links,
- label: 'Links',
- icon: <IconCursorClick />,
- to: urls.links(),
- tag: 'alpha' as const,
- tooltipDocLink: 'https://posthog.com/docs/links',
- }
- : null,
- {
- identifier: Scene.Workflows,
- label: 'Workflows',
- icon: <IconDecisionTree />,
- to: urls.workflows(),
- },
- ].filter(isNotNil) as NavbarItem[],
- ]
- },
- ],
- navbarItemIdMapping: [
- (s) => [s.navbarItems],
- (navbarItems: NavbarItem[][]): Record<string, NavbarItem> => {
- return Object.fromEntries(navbarItems.flat().map((item) => [item.identifier, item]))
- },
- ],
- sidebarOverslideDirection: [
- (s) => [s.sidebarOverslide],
- (sidebarOverslide: number): 'min' | 'max' | null => {
- if (sidebarOverslide < 0) {
- return 'min'
- } else if (sidebarOverslide > 0) {
- return 'max'
- }
- return null
- },
- ],
- activeNavbarItem: [
- (s) => [s.activeNavbarItemId, s.navbarItemIdMapping],
- (
- activeNavbarItemId: string | null,
- navbarItemIdMapping: Record<string, NavbarItem>
- ): SidebarNavbarItem | null => {
- const item = activeNavbarItemId ? navbarItemIdMapping[activeNavbarItemId] : null
- return item && 'logic' in item ? (item as SidebarNavbarItem) : null
- },
- ],
- searchTerm: [
- (s) => [s.internalSearchTerm, s.isSearchShown],
- (internalSearchTerm: string, isSearchShown: boolean): string => {
- return isSearchShown ? internalSearchTerm : ''
- },
- ],
- sidebarContentsFlattened: [
- (s) => [(state) => s.activeNavbarItem(state)?.logic?.findMounted()?.selectors.contents(state) || null],
- (sidebarContents: import('./types').SidebarCategory[] | null): BasicListItem[] | ExtendedListItem[] => {
- const flattenItems = (items: any[]): (BasicListItem | ExtendedListItem)[] => {
- return items.flatMap((item) => {
- if ('items' in item) {
- return flattenItems(item.items)
- }
- return item
- })
- }
- return sidebarContents ? flattenItems(sidebarContents) : []
- },
- ],
- normalizedActiveListItemKey: [
- (s) => [
- (state) =>
- s.activeNavbarItem(state)?.logic?.findMounted()?.selectors.activeListItemKey?.(state) || null,
- ],
- (
- activeListItemKey: number | string | [string, number | string] | null
- ): string | number | string[] | null =>
- activeListItemKey
- ? Array.isArray(activeListItemKey)
- ? activeListItemKey.join(ITEM_KEY_PART_SEPARATOR)
- : activeListItemKey
- : null,
- ],
- isListItemVisible: [
- (s) => [s.listItemAccordionCollapseMapping],
- (listItemAccordionCollapseMapping: Record<string, boolean>) => {
- return (key: string): boolean => {
- // Split the key into parts to check each parent's visibility
- const parts = key.split(ITEM_KEY_PART_SEPARATOR)
- // Check if any parent is collapsed
- for (let i = 1; i < parts.length; i++) {
- const parentKey = parts.slice(0, i).join(ITEM_KEY_PART_SEPARATOR)
- if (listItemAccordionCollapseMapping[parentKey]) {
- return false
- }
- }
- return true
- }
- },
- ],
- activeNavbarItemId: [
- (s) => [s.activeNavbarItemIdRaw],
- (activeNavbarItemIdRaw: string): string | null => {
- if (activeNavbarItemIdRaw === Scene.SQLEditor) {
- return Scene.SQLEditor
- }
- return null
- },
- ],
- newItemCategory: [
- (s) => [
- (state) => s.activeNavbarItem(state)?.logic?.findMounted()?.selectors.contents(state) || null,
- s.newItemInlineCategory,
- router.selectors.location,
- ],
- (
- sidebarContents: import('./types').SidebarCategory[] | null,
- newItemInlineCategory: string | null,
- location: {
- hash: string
- pathname: string
- search: string
- }
- ): string | null => {
- if (!sidebarContents) {
- return null
- }
- if (newItemInlineCategory) {
- return newItemInlineCategory
- }
- return (
- sidebarContents.find(
- (category) => typeof category.onAdd === 'string' && category.onAdd === location.pathname
- )?.key || null
- )
- },
- ],
}),
- subscriptions(({ props, cache, actions, values }) => ({
- isResizeInProgress: (isResizeInProgress) => {
- if (isResizeInProgress) {
- cache.onMouseMove = (e: MouseEvent): void => actions.syncSidebarWidthWithMouseMove(e.movementX)
- cache.onMouseUp = (e: MouseEvent): void => {
- if (e.button === 0) {
- actions.endResize()
- }
- }
- document.addEventListener('mousemove', cache.onMouseMove)
- document.addEventListener('mouseup', cache.onMouseUp)
- return () => {}
- }
- document.removeEventListener('mousemove', cache.onMouseMove)
- document.removeEventListener('mouseup', cache.onMouseUp)
- },
- sidebarContentsFlattened: (sidebarContentsFlattened) => {
- for (const item of sidebarContentsFlattened) {
- if (!item.ref) {
- item.ref = React.createRef() // Inject refs for keyboard navigation
- }
- }
- actions.setLastFocusedItemIndex(-1) // Reset focused item index on contents change
- },
- lastFocusedItemIndex: (lastFocusedItemIndex) => {
- if (lastFocusedItemIndex >= 0) {
- const item = values.sidebarContentsFlattened[lastFocusedItemIndex]
- item.ref?.current?.focus()
- } else {
- props.inputElement?.focus()
- }
- },
+ subscriptions(({ actions, values }) => ({
zenModeFromUrl: (zenModeFromUrl: boolean) => {
// Enable zen mode when URL parameter is present (e.g., ?zen or ?zen=true)
// Only enable, never disable from URL - user can manually disable
@@ -1027,28 +151,4 @@ export const navigation3000Logic = kea<navigation3000LogicType>([
}
},
})),
- events(({ props, actions, cache }) => ({
- afterMount: () => {
- cache.onResize = () => actions.syncSidebarWidthWithViewport()
- cache.onKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'b' && (e.metaKey || e.ctrlKey)) {
- actions.toggleSidebar()
- e.preventDefault()
- }
- if (e.key === 'f' && e.shiftKey && (e.metaKey || e.ctrlKey)) {
- actions.setIsSearchShown(true)
- props.inputElement?.focus()
- e.preventDefault()
- }
- }
- cache.disposables.add(() => {
- window.addEventListener('resize', cache.onResize)
- return () => window.removeEventListener('resize', cache.onResize)
- }, 'resizeListener')
- cache.disposables.add(() => {
- window.addEventListener('keydown', cache.onKeyDown)
- return () => window.removeEventListener('keydown', cache.onKeyDown)
- }, 'keydownListener')
- },
- })),
])
diff --git a/frontend/src/layout/navigation-3000/types.ts b/frontend/src/layout/navigation-3000/types.ts
deleted file mode 100644
index e3534b6976ef..000000000000
--- a/frontend/src/layout/navigation-3000/types.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { Logic, LogicWrapper } from 'kea'
-import React from 'react'
-
-import { LemonTagType, SideAction } from '@posthog/lemon-ui'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { Dayjs } from 'lib/dayjs'
-import { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
-
-export interface SidebarLogic extends Logic {
- actions: Record<never, never> // No actions required in the base version
- values: {
- contents: SidebarCategory[]
- /**
- * Tuple for an item inside an accordion, the first element being the accordion key.
- * Otherwise a primitive (string or number key). Null if no item is active.
- */
- activeListItemKey?: string | number | [string, string | number] | null
- /** If this selector returns true, the searchTerm value will be debounced. */
- debounceSearch?: boolean
- }
- selectors: {
- contents: (state: any, props?: any) => SidebarLogic['values']['contents']
- activeListItemKey?: (state: any, props?: any) => SidebarLogic['values']['activeListItemKey']
- debounceSearch?: (state: any, props?: any) => SidebarLogic['values']['debounceSearch']
- }
-}
-
-interface NavbarItemBase {
- identifier: string
- label: string
- icon: JSX.Element
- featureFlag?: (typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS]
- tag?: 'alpha' | 'beta' | 'new'
- sideAction?: Omit<SideAction, 'divider' | 'data-attr' | 'tooltipPlacement'> & { identifier: string }
- tooltipDocLink?: string
- /** @deprecated */
- onClick?: () => void
-}
-export interface SceneNavbarItem extends NavbarItemBase {
- to: string
- logic?: undefined
-}
-export interface SidebarNavbarItem extends NavbarItemBase {
- to?: undefined
- logic: LogicWrapper<SidebarLogic>
-}
-/** A navbar item either points to a sidebar (via a sidebar logic) or directly to a scene (via a URL). */
-export type NavbarItem = NavbarItemBase | SceneNavbarItem | SidebarNavbarItem
-
-export type ListItemSaveHandler = (newName: string) => Promise<void>
-
-export interface SidebarCategoryBase {
- key: string
- /** Category content noun. If the plural form is non-standard, provide a tuple with both forms. @example 'person' */
- noun: string | [singular: string, plural: string]
- items: BasicListItem[] | ExtendedListItem[] | ListItemAccordion[]
- icon?: JSX.Element
- /** Ref to the corresponding <a> element. This is injected automatically when the element is rendered. */
- ref?: React.MutableRefObject<HTMLElement | null>
-}
-
-export interface ListItemAccordion extends SidebarCategoryBase {
- depth?: number
-}
-
-/** A category of items. This is either displayed directly for sidebars with only one category, or as an accordion. */
-export interface SidebarCategory extends SidebarCategoryBase {
- loading: boolean
- /**
- * Items can be created in three ways:
- * 1. In a "new item" scene, in which case this is a string pointing to the scene URL (such as new insight).
- * 2. In a modal, in which case this is a zero-argument function that opens the modal.
- * 3. Directly in the sidebar, in which case this is a single-argument function that takes the new item's name
- * and saves it. For a smooth experience, this should only resolve once the new item is present in `contents`.
- */
- onAdd?: string | (() => void) | ListItemSaveHandler
- /**
- * Name validation. Returns a message string in case of an error, otherwise null.
- * This is relevant if the category has `onAdd` or items have `onRename`.
- */
- validateName?: (name: string) => string | null
- /** Optional extra JSX rendered in the background, enabling category-specific modals. */
- modalContent?: JSX.Element
- /** Controls for data that's only loaded partially from the API at first. This powers infinite loading. */
- remote?: {
- isItemLoaded: (index: number) => boolean
- loadMoreItems: (startIndex: number, stopIndex: number) => Promise<void>
- itemCount: number
- /** The "page" size. @default 100 */
- minimumBatchSize?: number
- }
-
- /** Optional component to render when the category is empty. */
- emptyComponent?: JSX.Element
- /** Optional function to determine whether the empty component should be shown */
- emptyComponentLogic?: (items: BasicListItem[] | ExtendedListItem[] | ListItemAccordion[]) => boolean
-}
-
-export interface SearchMatch {
- /**
- * Fields that are matching the search term - they will be shown within the list item.
- * Not included in server-side search.
- */
- matchingFields?: readonly string[]
- /** What parts of the name were matched - they will be bolded. */
- nameHighlightRanges?: readonly [number, number][]
-}
-
-/** Single-row list item. */
-export interface BasicListItem {
- /**
- * Key uniquely identifying this item.
- *
- * This can also be an array of keys - for example persons have multiple distinct IDs.
- * Note that in such an array, EACH key must represent this and ONLY this item.
- */
- key: string | number | string[]
- /** Item name. This must be a string for accesibility. */
- name: string
- /** Whether the name is a placeholder (e.g. an insight derived name), in which case it'll be italicized. */
- isNamePlaceholder?: boolean
- /**
- * URL within the app. In specific cases this can be null - such items are italicized.
- */
- url: string | null
- onClick?: () => void
- /** An optional marker to highlight item state. */
- marker?: {
- /** A marker of type `fold` is a small triangle in the top left, `ribbon` is a narrow ribbon to the left. */
- type: 'fold' | 'ribbon'
- /**
- * Optional marker color.
- * @default 'muted'
- */
- status?: 'muted' | 'success' | 'warning' | 'danger' | 'completion'
- }
- /** An optional tag shown as a suffix of the name. */
- tag?: {
- status: LemonTagType
- text: string
- }
- /** If search is on, this should be present to convey why this item is included in results. */
- searchMatch?: SearchMatch | null
- menuItems?: LemonMenuItems | ((initiateRename?: () => void) => LemonMenuItems)
- onRename?: ListItemSaveHandler
- /** Ref to the corresponding <a> element. This is injected automatically when the element is rendered. */
- ref?: React.MutableRefObject<HTMLElement | null>
- /** If this item is inside an accordion, this is the depth of the accordion. */
- depth?: number
- /** Element to render at the end of the row */
- endElement?: string | JSX.Element
-}
-
-export type ExtraListItemContext = string | Dayjs
-/** Double-row list item. */
-export interface ExtendedListItem extends BasicListItem {
- summary: string | JSX.Element
- /** A small piece of extra context to be displayed in the top right of the row. */
- extraContextTop: ExtraListItemContext
- /** A small piece of extra context to be displayed in the bottom right of the row. */
- extraContextBottom: ExtraListItemContext
-}
-
-/** Just a stub for a list item that's being added. */
-export interface TentativeListItem {
- key: '__tentative__'
- onSave: ListItemSaveHandler
- onCancel: () => void
- loading: boolean
- adding: boolean
- ref?: BasicListItem['ref']
-}
-
-export interface ButtonListItem extends BasicListItem {
- key: '__button__'
- onClick: () => void
- icon?: JSX.Element
-}