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.

fix(navigation): keep visited nav panels mounted instead of remounting per switch (#68452)

Paul D'Ambra30de58620dc5
diff --git a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
index 2af809115c7b..bd26b47c4bf9 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
@@ -66,6 +66,8 @@ export interface ProjectTreeProps {
checkedItemsOverride?: Record<string, boolean>
/** Override the onItemChecked handler from the internal logic */
onItemCheckedOverride?: (id: string, checked: boolean) => void
+ /** True while this tree's nav panel is active — refocuses search on panel re-activation. */
+ isActiveInPanel?: boolean
}
export const PROJECT_TREE_KEY = 'project-tree'
@@ -126,6 +128,7 @@ export function ProjectTree({
selectModeOverride,
checkedItemsOverride,
onItemCheckedOverride,
+ isActiveInPanel,
}: ProjectTreeProps): JSX.Element {
const [uniqueKey] = useState(() => `project-tree-${counter++}`)
const { viableItems, shortcutEntryIdMap } = useValues(projectTreeDataLogic)
@@ -167,7 +170,7 @@ export function ProjectTree({
const selectMode = selectModeOverride ?? projectTreeSelectMode
const onItemChecked = onItemCheckedOverride ?? projectTreeOnItemChecked
- const { setPanelTreeRef, resetPanelLayout } = useActions(panelLayoutLogic)
+ const { resetPanelLayout } = useActions(panelLayoutLogic)
const { mainContentRef } = useValues(panelLayoutLogic)
const { currentTeamId } = useValues(teamLogic)
const treeRef = useRef<LemonTreeRef>(null)
@@ -308,10 +311,6 @@ export function ProjectTree({
}
}
- useEffect(() => {
- setPanelTreeRef(treeRef)
- }, [treeRef, setPanelTreeRef])
-
useEffect(() => {
if (projectSortMethod !== (sortMethod ?? 'folder')) {
setSortMethod(sortMethod ?? 'folder')
@@ -751,7 +750,12 @@ export function ProjectTree({
<PanelLayoutPanel
searchField={
<BindLogic logic={projectTreeLogic} props={projectTreeLogicProps}>
- <TreeSearchField root={root} placeholder={searchPlaceholder} />
+ <TreeSearchField
+ root={root}
+ placeholder={searchPlaceholder}
+ treeRef={treeRef}
+ isActive={isActiveInPanel}
+ />
</BindLogic>
}
filterDropdown={
diff --git a/frontend/src/layout/panel-layout/ProjectTree/TreeSearchField.tsx b/frontend/src/layout/panel-layout/ProjectTree/TreeSearchField.tsx
index 7f46f82b6ffe..44bc1ee816f4 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/TreeSearchField.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/TreeSearchField.tsx
@@ -1,14 +1,15 @@
import { useActions, useValues } from 'kea'
+import { useEffect, useRef } from 'react'
import { IconCdCase, IconDocument, IconPlug, IconUser } from '@posthog/icons'
import { SearchAutocomplete } from 'lib/components/SearchAutocomplete/SearchAutocomplete'
+import { LemonTreeRef } from 'lib/lemon-ui/LemonTree/LemonTree'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { fileSystemTypes } from '~/products'
import { FileSystemType } from '~/types'
-import { panelLayoutLogic } from '../panelLayoutLogic'
import { iconForType } from './defaultTree'
import { projectTreeLogic } from './projectTreeLogic'
@@ -35,27 +36,42 @@ const productTypesMapped = [
interface TreeSearchFieldProps {
root?: string
placeholder?: string
+ /** The tree this search field belongs to — ArrowDown moves focus into it. Multiple trees can be
+ * mounted at once (panel switching keeps them alive), so a shared global ref would focus the
+ * wrong, possibly hidden, tree. */
+ treeRef: React.RefObject<LemonTreeRef>
+ /** True while this field's panel is the active one. Kept-mounted panels don't remount on
+ * re-open, so `autoFocus` fires only once — refocus on every activation to keep the
+ * "open panel, type to search" flow working. */
+ isActive?: boolean
}
-export function TreeSearchField({ root, placeholder }: TreeSearchFieldProps): JSX.Element {
- const { panelTreeRef } = useValues(panelLayoutLogic)
+export function TreeSearchField({ root, placeholder, treeRef, isActive }: TreeSearchFieldProps): JSX.Element {
const { searchTerm } = useValues(projectTreeLogic)
const { setSearchTerm, clearSearch } = useActions(projectTreeLogic)
const { featureFlags } = useValues(featureFlagLogic)
+ const containerRef = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (isActive) {
+ containerRef.current?.querySelector('input')?.focus()
+ }
+ }, [isActive])
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>): void {
if (e.key === 'ArrowDown') {
e.preventDefault() // Prevent scrolling
- const visibleItems = panelTreeRef?.current?.getVisibleItems()
+ const visibleItems = treeRef.current?.getVisibleItems()
if (visibleItems && visibleItems.length > 0) {
e.currentTarget.blur() // Remove focus from input
- panelTreeRef?.current?.focusItem(visibleItems[0].id)
+ treeRef.current?.focusItem(visibleItems[0].id)
}
}
}
return (
<SearchAutocomplete
+ ref={containerRef}
inputPlaceholder={placeholder}
includeNegation
defaultValue={searchTerm}
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx
index 0319c2adb36a..f1da6c819599 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx
@@ -1112,8 +1112,17 @@ export const projectTreeLogic = kea<projectTreeLogicType>([
}
},
})),
- subscriptions(({ actions, values }) => ({
+ subscriptions(({ actions, values, props }) => ({
projectTreeRef: (newRef: ProjectTreeRef | null) => {
+ // Only the project:// tree navigates to breadcrumb-driven items. Other roots
+ // (data-and-people, products, shortcuts) don't contain project file-system items,
+ // so subscribing on those instances would fire duplicate api.fileSystem.list calls
+ // for every navigation when those panels are keep-mounted.
+ // undefined root means the panel loads the project root (''), so it is project-equivalent.
+ const isProjectRoot = props.root === undefined || props.root.startsWith('project://')
+ if (!isProjectRoot) {
+ return
+ }
if (newRef) {
if (newRef.ref === null) {
if (typeof values.lastNewFolder === 'string') {
@@ -1133,7 +1142,9 @@ export const projectTreeLogic = kea<projectTreeLogicType>([
} else {
actions.loadFolder('')
}
- if (values.projectTreeRef) {
+ // Same gate as the subscription: only project:// trees handle breadcrumb-driven visibility.
+ const isProjectRoot = props.root === undefined || props.root.startsWith('project://')
+ if (values.projectTreeRef && isProjectRoot) {
actions.assureVisibility(values.projectTreeRef)
}
if (typeof props.defaultOnlyFolders !== 'undefined') {
diff --git a/frontend/src/layout/panel-layout/ai-first/Nav.tsx b/frontend/src/layout/panel-layout/ai-first/Nav.tsx
index 98df2c557309..8ed2d03186b8 100644
--- a/frontend/src/layout/panel-layout/ai-first/Nav.tsx
+++ b/frontend/src/layout/panel-layout/ai-first/Nav.tsx
@@ -119,8 +119,13 @@ export function Nav(): JSX.Element {
clearActivePanelIdentifier,
setNavbarWidth,
} = useActions(panelLayoutLogic)
- const { isLayoutPanelVisible, isLayoutNavCollapsed, navExperimentActiveTab, activePanelIdentifier } =
- useValues(panelLayoutLogic)
+ const {
+ isLayoutPanelVisible,
+ isLayoutNavCollapsed,
+ navExperimentActiveTab,
+ activePanelIdentifier,
+ visitedNavTabs,
+ } = useValues(panelLayoutLogic)
const { mobileLayout: isMobileLayout } = useValues(navigation3000Logic)
const { toggleCommand } = useActions(commandLogic)
const showCreateButton = useFeatureFlag('CREATE_BUTTON_NAV_EXPERIMENT', 'test')
@@ -272,52 +277,53 @@ export function Nav(): JSX.Element {
}}
orientation={isLayoutNavCollapsed ? 'vertical' : 'horizontal'}
>
- {!isLayoutNavCollapsed && (
- <div className="p-1">
- <Tabs.List className="relative flex items-center gap-1 shrink-0 z-0 p-1 rounded-lg bg-(--color-bg-fill-highlight-50) dark:bg-surface-primary">
- {TAB_CONFIG.map((tab) => (
- <Tabs.Tab
- key={tab.id}
- value={tab.id}
- render={(props) => (
- <ButtonPrimitive
- {...props}
- className="group data-[composite-item-active]:bg-surface-tertiary w-1/2 justify-center"
- data-attr={`nav-tab-${tab.id}`}
+ <div className={cn('p-1', isLayoutNavCollapsed && 'hidden')}>
+ <Tabs.List className="relative flex items-center gap-1 shrink-0 z-0 p-1 rounded-lg bg-(--color-bg-fill-highlight-50) dark:bg-surface-primary">
+ {TAB_CONFIG.map((tab) => (
+ <Tabs.Tab
+ key={tab.id}
+ value={tab.id}
+ render={(props) => (
+ <ButtonPrimitive
+ {...props}
+ className="group data-[composite-item-active]:bg-surface-tertiary w-1/2 justify-center"
+ data-attr={`nav-tab-${tab.id}`}
+ >
+ <span
+ className={cn(
+ 'flex size-4',
+ navExperimentActiveTab === tab.id
+ ? 'text-primary'
+ : 'text-secondary group-hover:text-primary'
+ )}
>
- <span
- className={cn(
- 'flex size-4',
- navExperimentActiveTab === tab.id
- ? 'text-primary'
- : 'text-secondary group-hover:text-primary'
- )}
- >
- {tab.icon}
- </span>
- <span
- className={cn(
- 'text-xs',
- navExperimentActiveTab === tab.id
- ? 'text-primary'
- : 'text-secondary group-hover:text-primary'
- )}
- >
- {tab.label}
- </span>
- </ButtonPrimitive>
- )}
- />
- ))}
- </Tabs.List>
- </div>
- )}
+ {tab.icon}
+ </span>
+ <span
+ className={cn(
+ 'text-xs',
+ navExperimentActiveTab === tab.id
+ ? 'text-primary'
+ : 'text-secondary group-hover:text-primary'
+ )}
+ >
+ {tab.label}
+ </span>
+ </ButtonPrimitive>
+ )}
+ />
+ ))}
+ </Tabs.List>
+ </div>
<div className="flex-1 overflow-hidden relative">
<Tabs.Panel value="home" className="absolute inset-0 flex flex-col" keepMounted tabIndex={-1}>
<NavTabBrowse />
</Tabs.Panel>
- {!isLayoutNavCollapsed && (
+ {/* Lazy until first activated: the visited list only ever grows, so once
+ mounted the panel never unmounts — keepMounted then preserves it across
+ tab switches. Users who never open chat never pay for its chunk. */}
+ {visitedNavTabs.includes('chat') && (
<Tabs.Panel
value="chat"
className="absolute inset-0 flex flex-col"
diff --git a/frontend/src/layout/panel-layout/ai-first/PanelLayoutPanels.test.tsx b/frontend/src/layout/panel-layout/ai-first/PanelLayoutPanels.test.tsx
new file mode 100644
index 000000000000..7e6e165264a9
--- /dev/null
+++ b/frontend/src/layout/panel-layout/ai-first/PanelLayoutPanels.test.tsx
@@ -0,0 +1,63 @@
+import { act, render } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import { panelLayoutLogic } from '../panelLayoutLogic'
+import { PanelLayoutPanels } from './PanelLayoutPanels'
+
+jest.mock('../ProjectTree/ProjectTree', () => ({
+ PROJECT_TREE_KEY: 'project-tree',
+ ProjectTree: ({ root }: { root: string }) => <div data-attr="mock-tree" data-root={root} />,
+}))
+jest.mock('lib/components/NotificationsMenu/NotificationsPanel', () => ({
+ NotificationsPanel: () => <div data-attr="mock-notifications" />,
+}))
+jest.mock('./tabs/NavTabChat', () => ({
+ NavTabChat: () => <div data-attr="mock-chat" />,
+}))
+
+describe('PanelLayoutPanels', () => {
+ beforeEach(() => {
+ initKeaTests()
+ panelLayoutLogic.mount()
+ })
+
+ function renderedTrees(container: HTMLElement): { root: string | null; hidden: boolean }[] {
+ return Array.from(container.querySelectorAll('[data-attr="mock-tree"]')).map((tree) => ({
+ root: tree.getAttribute('data-root'),
+ hidden: !!tree.closest('.hidden'),
+ }))
+ }
+
+ it('keeps previously opened panels mounted but hidden when switching', () => {
+ const { container } = render(<PanelLayoutPanels />)
+ expect(renderedTrees(container)).toEqual([])
+
+ act(() => panelLayoutLogic.actions.setActivePanelIdentifier('Project'))
+ expect(renderedTrees(container)).toEqual([{ root: 'project://', hidden: false }])
+
+ // Switching must not tear down the project tree — it stays in the DOM, hidden.
+ act(() => panelLayoutLogic.actions.setActivePanelIdentifier('Products'))
+ expect(renderedTrees(container)).toEqual([
+ { root: 'project://', hidden: true },
+ { root: 'products://', hidden: false },
+ ])
+
+ act(() => panelLayoutLogic.actions.clearActivePanelIdentifier())
+ expect(renderedTrees(container)).toEqual([
+ { root: 'project://', hidden: true },
+ { root: 'products://', hidden: true },
+ ])
+ })
+
+ it('mounts the notifications panel only while it is the active panel', () => {
+ const { container } = render(<PanelLayoutPanels />)
+
+ act(() => panelLayoutLogic.actions.setActivePanelIdentifier('Notifications'))
+ expect(container.querySelector('[data-attr="mock-notifications"]')).toBeTruthy()
+
+ // Notifications is excluded from keep-mounted: its logic drives unread/read semantics.
+ act(() => panelLayoutLogic.actions.clearActivePanelIdentifier())
+ expect(container.querySelector('[data-attr="mock-notifications"]')).toBeNull()
+ })
+})
diff --git a/frontend/src/layout/panel-layout/ai-first/PanelLayoutPanels.tsx b/frontend/src/layout/panel-layout/ai-first/PanelLayoutPanels.tsx
index 0a3a733534b2..553e3c4f1f68 100644
--- a/frontend/src/layout/panel-layout/ai-first/PanelLayoutPanels.tsx
+++ b/frontend/src/layout/panel-layout/ai-first/PanelLayoutPanels.tsx
@@ -1,11 +1,11 @@
import { useActions, useValues } from 'kea'
-import { lazy, Suspense } from 'react'
+import { lazy, Suspense, useCallback, useMemo } from 'react'
import { NotificationsPanel } from 'lib/components/NotificationsMenu/NotificationsPanel'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/WrappingLoadingSkeleton'
-import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
+import { PanelLayoutNavIdentifier, panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
import { PROJECT_TREE_KEY, ProjectTree } from '../ProjectTree/ProjectTree'
@@ -15,50 +15,92 @@ const NavTabChat = lazy(() => import('./tabs/NavTabChat').then((m) => ({ default
// same active-panel JSX can be mounted at different positions in the DOM/stacking tree depending
// on layout mode — inside the nav container on desktop, as a fixed sibling on mobile.
export function PanelLayoutPanels(): JSX.Element | null {
- const { activePanelIdentifier } = useValues(panelLayoutLogic)
+ const { activePanelIdentifier, visitedPanels } = useValues(panelLayoutLogic)
const { clearActivePanelIdentifier, showLayoutPanel } = useActions(panelLayoutLogic)
- if (activePanelIdentifier === 'DataAndPeople') {
- return <ProjectTree root="data-and-people://" searchPlaceholder="Search data" />
- }
- if (activePanelIdentifier === 'Project') {
- return (
- <ProjectTree root="project://" logicKey={PROJECT_TREE_KEY} searchPlaceholder="Search files" showRecents />
- )
- }
- if (activePanelIdentifier === 'Products') {
- return <ProjectTree root="products://" searchPlaceholder="Search tools" />
- }
- if (activePanelIdentifier === 'Shortcuts') {
- return <ProjectTree root="shortcuts://" searchPlaceholder="Search starred items" />
- }
- if (activePanelIdentifier === 'Notifications') {
- return <NotificationsPanel />
- }
- if (activePanelIdentifier === 'Chat') {
- return (
- <div className="pointer-events-auto flex flex-col h-full min-h-screen max-h-screen bg-surface-tertiary border-r overflow-hidden w-[var(--project-panel-width)]">
- <Suspense
- fallback={
- <div className="flex flex-col gap-px px-1 pt-2">
- {Array.from({ length: 15 }).map((_, index) => (
- <WrappingLoadingSkeleton fullWidth key={index}>
- <ButtonPrimitive aria-hidden inert menuItem />
- </WrappingLoadingSkeleton>
- ))}
- </div>
- }
- >
- <NavTabChat
- inPanel
- onItemClick={() => {
- clearActivePanelIdentifier()
- showLayoutPanel(false)
- }}
- />
- </Suspense>
- </div>
- )
- }
- return null
+ // Stable reference: the chat panel stays mounted now, so a fresh closure here would re-render
+ // NavTabChat's memoized internals on every re-render of this component.
+ const onChatItemClick = useCallback(() => {
+ clearActivePanelIdentifier()
+ showLayoutPanel(false)
+ }, [clearActivePanelIdentifier, showLayoutPanel])
+
+ // Memoized so keep-mounted trees don't re-render on every PanelLayoutPanels re-render.
+ // Notifications is deliberately absent: its logic drives unread/read semantics that should
+ // only run while the panel is actually open. The keep-mounted set is derived from these
+ // keys so adding a panel here automatically opts it in — no second list to keep in sync.
+ const panelContent: Partial<Record<PanelLayoutNavIdentifier, JSX.Element>> = useMemo(
+ () => ({
+ DataAndPeople: (
+ <ProjectTree
+ root="data-and-people://"
+ searchPlaceholder="Search data"
+ isActiveInPanel={activePanelIdentifier === 'DataAndPeople'}
+ />
+ ),
+ Project: (
+ <ProjectTree
+ root="project://"
+ logicKey={PROJECT_TREE_KEY}
+ searchPlaceholder="Search files"
+ showRecents
+ isActiveInPanel={activePanelIdentifier === 'Project'}
+ />
+ ),
+ Products: (
+ <ProjectTree
+ root="products://"
+ searchPlaceholder="Search tools"
+ isActiveInPanel={activePanelIdentifier === 'Products'}
+ />
+ ),
+ Shortcuts: (
+ <ProjectTree
+ root="shortcuts://"
+ searchPlaceholder="Search starred items"
+ isActiveInPanel={activePanelIdentifier === 'Shortcuts'}
+ />
+ ),
+ Chat: (
+ <div className="pointer-events-auto flex flex-col h-full min-h-screen max-h-screen bg-surface-tertiary border-r overflow-hidden w-[var(--project-panel-width)]">
+ <Suspense
+ fallback={
+ <div className="flex flex-col gap-px px-1 pt-2">
+ {Array.from({ length: 15 }).map((_, index) => (
+ <WrappingLoadingSkeleton fullWidth key={index}>
+ <ButtonPrimitive aria-hidden inert menuItem />
+ </WrappingLoadingSkeleton>
+ ))}
+ </div>
+ }
+ >
+ <NavTabChat inPanel onItemClick={onChatItemClick} />
+ </Suspense>
+ </div>
+ ),
+ }),
+ // activePanelIdentifier feeds isActiveInPanel so kept trees refocus search on re-activation;
+ // it only changes on panel switches, so this memo still shields trees from unrelated re-renders.
+ [onChatItemClick, activePanelIdentifier]
+ )
+
+ // All panel-content keys are keep-mounted (hidden when inactive) so switching panels doesn't
+ // tear down and rebuild whole trees on every toggle — that churn was the app's dominant
+ // detached-DOM source and also loses scroll/expansion state.
+ const keepMountedPanels = Object.keys(panelContent) as PanelLayoutNavIdentifier[]
+
+ return (
+ <>
+ {keepMountedPanels
+ .filter((identifier) => identifier === activePanelIdentifier || visitedPanels.includes(identifier))
+ .map((identifier) => (
+ // `contents` keeps the wrapper out of layout when active, so each panel's own
+ // chrome positions exactly as it did when returned bare from this component.
+ <div key={identifier} className={identifier === activePanelIdentifier ? 'contents' : 'hidden'}>
+ {panelContent[identifier]}
+ </div>
+ ))}
+ {activePanelIdentifier === 'Notifications' && <NotificationsPanel />}
+ </>
+ )
}
diff --git a/frontend/src/layout/panel-layout/ai-first/tabs/NavTabChat.tsx b/frontend/src/layout/panel-layout/ai-first/tabs/NavTabChat.tsx
index 859ce7638a00..e11d429bf62c 100644
--- a/frontend/src/layout/panel-layout/ai-first/tabs/NavTabChat.tsx
+++ b/frontend/src/layout/panel-layout/ai-first/tabs/NavTabChat.tsx
@@ -1,7 +1,7 @@
import { Combobox } from '@base-ui/react/combobox'
import { useValues } from 'kea'
import { router } from 'kea-router'
-import { useMemo, useState } from 'react'
+import { useId, useMemo, useState } from 'react'
import { IconPlusSmall, IconSearch, IconX } from '@posthog/icons'
import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
@@ -58,6 +58,9 @@ export function NavTabChat({
inPanel?: boolean
onItemClick?: () => void
}): JSX.Element {
+ // The chat surface can be mounted twice at once (nav tab, kept mounted, plus the side panel),
+ // so the search input's id must be per-instance to keep label/htmlFor pairing valid.
+ const searchInputId = useId()
const { conversationHistory, conversationHistoryLoading, currentConversationId } = useValues(maxGlobalLogic)
const [inputValue, setInputValue] = useState('')
@@ -91,7 +94,7 @@ export function NavTabChat({
<div className="flex flex-col h-full min-h-0">
<div className={cn('flex items-center gap-1 p-2 shrink-0', inPanel && 'p-1')}>
<label
- htmlFor="nav-search-chats"
+ htmlFor={searchInputId}
className={cn(
'input-like flex items-center flex-1 px-1 gap-1 group h-[30px]',
inPanel && 'bg-fill-input'
@@ -99,7 +102,7 @@ export function NavTabChat({
>
<IconSearch className="size-4 text-tertiary group-focus-within:text-primary w-4 shrink-0" />
<Combobox.Input
- id="nav-search-chats"
+ id={searchInputId}
placeholder="Chat history"
aria-label="Chat history"
className="w-full text-sm bg-transparent border-none focus:outline-none focus:ring-0 transition-[width] duration-100 h-[30px]"
diff --git a/frontend/src/layout/panel-layout/panelLayoutLogic.tsx b/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
index 703a4b6bfe22..efa017eee712 100644
--- a/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
+++ b/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
@@ -1,7 +1,6 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'
-import { LemonTreeRef } from 'lib/lemon-ui/LemonTree/LemonTree'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { navigation3000Logic } from '../navigation-3000/navigationLogic'
@@ -18,7 +17,6 @@ export type PanelLayoutNavIdentifier =
| 'Chat'
| 'Notifications'
export type NavExperimentTab = 'home' | 'chat'
-export type PanelLayoutTreeRef = React.RefObject<LemonTreeRef> | null
export type PanelLayoutMainContentRef = React.RefObject<HTMLElement> | null
export const PANEL_LAYOUT_DEFAULT_WIDTH: number = 245
export const PANEL_LAYOUT_MIN_WIDTH: number = 160
@@ -41,7 +39,6 @@ export const panelLayoutLogic = kea<panelLayoutLogicType>([
// We should remove this once we have a proper way to handle the navbar item
setActivePanelIdentifier: (identifier: PanelLayoutNavIdentifier) => ({ identifier }),
clearActivePanelIdentifier: true,
- setPanelTreeRef: (ref: PanelLayoutTreeRef) => ({ ref }),
setMainContentRef: (ref: PanelLayoutMainContentRef) => ({ ref }),
toggleLayoutNavCollapsed: (override?: boolean) => ({ override }),
setVisibleSideAction: (sideAction: string) => ({ sideAction }),
@@ -99,10 +96,24 @@ export const panelLayoutLogic = kea<panelLayoutLogicType>([
clearActivePanelIdentifier: () => '',
},
],
- panelTreeRef: [
- null as PanelLayoutTreeRef,
+ // Panels opened at least once this session. PanelLayoutPanels keeps these mounted (hidden)
+ // so switching panels doesn't tear down and rebuild whole trees on every toggle.
+ // Notifications is excluded: its logic drives unread/read semantics that must only run
+ // while the panel is active, so keeping it mounted would be incorrect.
+ visitedPanels: [
+ [] as PanelLayoutNavIdentifier[],
{
- setPanelTreeRef: (_, { ref }) => ref,
+ setActivePanelIdentifier: (state, { identifier }) =>
+ identifier === 'Notifications' || state.includes(identifier) ? state : [...state, identifier],
+ },
+ ],
+ // Nav tabs activated at least once this session. Nav renders the chat tab's keepMounted
+ // panel only after first activation, so collapsed-nav users who never open chat don't
+ // download and mount the lazy chat chunk on every app load.
+ visitedNavTabs: [
+ [] as NavExperimentTab[],
+ {
+ setNavExperimentTab: (state, { tab }) => (state.includes(tab) ? state : [...state, tab]),
},
],
mainContentRef: [
@@ -286,6 +297,16 @@ export const panelLayoutLogic = kea<panelLayoutLogicType>([
},
})),
afterMount(({ actions, cache, values }) => {
+ // visitedPanels is not persisted, but activePanelIdentifier is. Seed visitedPanels from
+ // the rehydrated identifier so the panel that was open on the previous session starts
+ // keep-mounted — without this, the first switch after reload tears the panel down once.
+ if (values.activePanelIdentifier) {
+ actions.setActivePanelIdentifier(values.activePanelIdentifier as PanelLayoutNavIdentifier)
+ }
+ // Same for the persisted nav tab: a user who was on the chat tab last session gets its
+ // panel mounted from the start.
+ actions.setNavExperimentTab(values.navExperimentActiveTab)
+
// Watch for window resize
if (typeof window !== 'undefined') {
cache.disposables.add(() => {