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.

17.5 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'

import { navigation3000Logic } from '../navigation-3000/navigationLogic'

export type PanelLayoutNavIdentifier = 'Project' | 'Notifications'
const PANEL_LAYOUT_NAV_IDENTIFIERS: string[] = ['Project', 'Notifications'] satisfies PanelLayoutNavIdentifier[]
export type NavExperimentTab = 'home' | 'files' | 'chat'
export type PanelLayoutMainContentRef = React.RefObject<HTMLElement> | null
export const PANEL_LAYOUT_DEFAULT_WIDTH: number = 245
export const PANEL_LAYOUT_MIN_WIDTH: number = 160

// Navbar resize: any width upward, snapping to collapsed below the threshold.
export const PANEL_NAVBAR_DEFAULT_WIDTH: number = 215
// Below this the drag snaps to collapsed mode.
export const PANEL_NAVBAR_COLLAPSE_THRESHOLD: number = 140

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface panelLayoutLogicValues {
    mobileLayout: boolean // navigation3000Logic
    location: {
        pathname: string
        search: string
        hash: string
    } // router
    activePanelIdentifier: string
    isLayoutNavCollapsed: boolean
    isLayoutNavCollapsedDesktop: boolean
    isLayoutNavbarVisible: boolean
    isLayoutNavbarVisibleForDesktop: boolean
    isLayoutNavbarVisibleForMobile: boolean
    isLayoutPanelVisible: boolean
    isNavOverlayOpen: boolean
    layoutNavCollapsedOverride: {
        collapsed: boolean
        owner: string
    } | null
    mainContentRect: DOMRect | null
    mainContentRef: PanelLayoutMainContentRef
    navExperimentActiveTab: NavExperimentTab
    navbarWidth: number
    panelIsResizing: boolean
    panelWidth: number
    panelWillHide: boolean
    pathname: string
    sidePanelWidth: number
    visitedNavTabs: NavExperimentTab[]
    visitedPanels: PanelLayoutNavIdentifier[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface panelLayoutLogicActions {
    clearActivePanelIdentifier: () => {
        value: true
    }
    closePanel: () => {
        value: true
    }
    resetPanelLayout: (keyboardAction: boolean) => {
        keyboardAction: boolean
    }
    setActivePanelIdentifier: (identifier: PanelLayoutNavIdentifier) => {
        identifier: PanelLayoutNavIdentifier
    }
    setLayoutNavCollapsedDesktop: (collapsed: boolean) => {
        collapsed: boolean
    }
    setLayoutNavCollapsedOverride: (
        owner: string,
        collapsed: boolean | null
    ) => {
        collapsed: boolean | null
        owner: string
    }
    setMainContentRect: (rect: DOMRect) => {
        rect: DOMRect
    }
    setMainContentRef: (
        ref: PanelLayoutMainContentRef,
        deferDuringResize?: boolean
    ) => {
        deferDuringResize: boolean
        ref: PanelLayoutMainContentRef
    }
    setNavExperimentTab: (tab: NavExperimentTab) => {
        tab: NavExperimentTab
    }
    setNavOverlayOpen: (open: boolean) => {
        open: boolean
    }
    setNavbarWidth: (width: number) => {
        width: number
    }
    setPanelIsResizing: (isResizing: boolean) => {
        isResizing: boolean
    }
    setPanelWidth: (width: number) => {
        width: number
    }
    setPanelWillHide: (willHide: boolean) => {
        willHide: boolean
    }
    setSidePanelWidth: (width: number) => {
        width: number
    }
    showLayoutNavBar: (visible: boolean) => {
        visible: boolean
    }
    showLayoutPanel: (visible: boolean) => {
        visible: boolean
    }
    toggleLayoutNavCollapsed: (override?: boolean) => {
        override: boolean | undefined
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface panelLayoutLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isLayoutNavCollapsed: (
            isLayoutNavCollapsedDesktop: boolean,
            layoutNavCollapsedOverride: {
                collapsed: boolean
                owner: string
            } | null,
            mobileLayout: boolean
        ) => boolean
        pathname: (location: { hash: string; pathname: string; search: string }) => string
    }
}

export type panelLayoutLogicType = MakeLogicType<
    panelLayoutLogicValues,
    panelLayoutLogicActions,
    Record<string, any>,
    panelLayoutLogicMeta
>

export const panelLayoutLogic = kea<panelLayoutLogicType>([
    path(['layout', 'panel-layout', 'panelLayoutLogic']),
    connect(() => ({
        values: [navigation3000Logic, ['mobileLayout'], router, ['location']],
    })),
    actions({
        closePanel: true,
        showLayoutNavBar: (visible: boolean) => ({ visible }),
        showLayoutPanel: (visible: boolean) => ({ visible }),
        // TODO: This is a temporary action to set the active navbar item
        // We should remove this once we have a proper way to handle the navbar item
        setActivePanelIdentifier: (identifier: PanelLayoutNavIdentifier) => ({ identifier }),
        clearActivePanelIdentifier: true,
        setMainContentRef: (ref: PanelLayoutMainContentRef, deferDuringResize: boolean = false) => ({
            ref,
            deferDuringResize,
        }),
        toggleLayoutNavCollapsed: (override?: boolean) => ({ override }),
        setLayoutNavCollapsedDesktop: (collapsed: boolean) => ({ collapsed }),
        setLayoutNavCollapsedOverride: (owner: string, collapsed: boolean | null) => ({ owner, collapsed }),
        setPanelWidth: (width: number) => ({ width }),
        setPanelIsResizing: (isResizing: boolean) => ({ isResizing }),
        setPanelWillHide: (willHide: boolean) => ({ willHide }),
        resetPanelLayout: (keyboardAction: boolean) => ({ keyboardAction }),
        setMainContentRect: (rect: DOMRect) => ({ rect }),
        setSidePanelWidth: (width: number) => ({ width }),
        setNavExperimentTab: (tab: NavExperimentTab) => ({ tab }),
        setNavbarWidth: (width: number) => ({ width }),
        setNavOverlayOpen: (open: boolean) => ({ open }),
    }),
    reducers({
        isNavOverlayOpen: [
            false,
            {
                setNavOverlayOpen: (_, { open }) => open,
                toggleLayoutNavCollapsed: () => false,
                resetPanelLayout: () => false,
                mobileLayout: () => false,
                showLayoutNavBar: () => false,
            },
        ],
        isLayoutNavbarVisibleForDesktop: [
            true,
            { persist: true },
            {
                showLayoutNavBar: (_, { visible }) => visible,
                mobileLayout: () => false,
            },
        ],
        isLayoutNavbarVisibleForMobile: [
            false,
            {
                showLayoutNavBar: (_, { visible }) => visible,
                mobileLayout: () => true,
            },
        ],
        isLayoutNavbarVisible: [
            false,
            { persist: true },
            {
                showLayoutNavBar: (_, { visible }) => visible,
            },
        ],
        isLayoutPanelVisible: [
            false,
            { persist: true, prefix: '2', separator: '.' },
            {
                showLayoutPanel: (_, { visible }) => visible,
            },
        ],
        activePanelIdentifier: [
            '',
            { persist: true, prefix: '2', separator: '.' },
            {
                setActivePanelIdentifier: (_, { identifier }) => identifier,
                clearActivePanelIdentifier: () => '',
            },
        ],
        // 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[],
            {
                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: [
            null as PanelLayoutMainContentRef,
            {
                setMainContentRef: (_, { ref }) => ref,
            },
        ],
        isLayoutNavCollapsedDesktop: [
            false,
            { persist: true },
            {
                setLayoutNavCollapsedDesktop: (_, { collapsed }) => collapsed,
            },
        ],
        // A scene sets this to collapse the nav while it shows. It is not persisted, so the saved
        // choice applies again when the scene clears it. Only the owner can clear it, because the
        // logic of one scene tab can unmount after the next scene tab set its own override.
        layoutNavCollapsedOverride: [
            null as { owner: string; collapsed: boolean } | null,
            {
                setLayoutNavCollapsedOverride: (state, { owner, collapsed }) =>
                    collapsed === null ? (state?.owner === owner ? null : state) : { owner, collapsed },
            },
        ],
        panelWidth: [
            PANEL_LAYOUT_DEFAULT_WIDTH,
            { persist: true, prefix: '2', separator: '.' },
            {
                setPanelWidth: (_, { width }) => width,
            },
        ],
        panelIsResizing: [
            false,
            {
                setPanelIsResizing: (_, { isResizing }) => isResizing,
            },
        ],
        panelWillHide: [
            false,
            {
                showLayoutPanel: (state, { visible }) => (visible ? false : state),
                setPanelWidth: (_, { width }) => width <= PANEL_LAYOUT_MIN_WIDTH - 1,
            },
        ],
        mainContentRect: [
            null as DOMRect | null,
            {
                setMainContentRect: (_, { rect }) => rect,
            },
        ],
        sidePanelWidth: [
            0,
            {
                setSidePanelWidth: (_, { width }) => width,
            },
        ],
        navExperimentActiveTab: [
            'home' as NavExperimentTab,
            { persist: true },
            {
                setNavExperimentTab: (_, { tab }) => tab,
            },
        ],
        // Transient: the live open width is restored from the resizer's persisted size on mount,
        // so persisting here would only duplicate it and thrash localStorage on every drag frame.
        navbarWidth: [
            PANEL_NAVBAR_DEFAULT_WIDTH,
            {
                setNavbarWidth: (_, { width }) => width,
            },
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        toggleLayoutNavCollapsed: ({ override }) => {
            // A toggle during a scene override changes the override only, so the saved choice survives the scene.
            const sceneOverride = values.layoutNavCollapsedOverride
            if (sceneOverride) {
                actions.setLayoutNavCollapsedOverride(sceneOverride.owner, override ?? !sceneOverride.collapsed)
            } else {
                actions.setLayoutNavCollapsedDesktop(override ?? !values.isLayoutNavCollapsedDesktop)
            }
        },
        closePanel: () => {
            actions.showLayoutPanel(false)
            actions.clearActivePanelIdentifier()
        },
        setPanelIsResizing: ({ isResizing }) => {
            // If we're not resizing and the panel is at or below the minimum width, hide it
            if (!isResizing && values.panelWidth <= PANEL_LAYOUT_MIN_WIDTH - 1) {
                actions.showLayoutPanel(false)
                actions.clearActivePanelIdentifier()
                actions.setPanelWidth(PANEL_LAYOUT_DEFAULT_WIDTH)
            }
        },
        resetPanelLayout: ({ keyboardAction = false }) => {
            // Hide the panel and clear active panel identifier
            actions.clearActivePanelIdentifier()
            actions.showLayoutPanel(false)
            // Hide the navbar if it's mobile and navbar is visible (which is an overlay on mobile)
            if (values.mobileLayout && values.isLayoutNavbarVisible) {
                actions.showLayoutNavBar(false)
            }
            // Focus the main content if it's a keyboard action
            if (keyboardAction && values.mainContentRef?.current) {
                values.mainContentRef?.current?.focus()
            }
        },
        setMainContentRef: ({ ref, deferDuringResize }) => {
            if (!ref?.current) {
                cache.disposables.dispose('resizeObserver')
            }
            // Measure width immediately when container ref is set
            if (ref?.current) {
                actions.setMainContentRect(ref.current.getBoundingClientRect())

                // Set up new ResizeObserver for the new container
                if (typeof ResizeObserver !== 'undefined') {
                    cache.disposables.add(() => {
                        // ref.current may be null when disposable resumes after visibility change
                        if (!ref.current) {
                            return () => {}
                        }
                        let resizeTimer: ReturnType<typeof setTimeout> | undefined
                        const updateRect = (): void => {
                            clearTimeout(resizeTimer)
                            // Keep sidebar drags from rendering navigation again for each scene measurement.
                            if (deferDuringResize && document.body.classList.contains('is-resizing')) {
                                resizeTimer = setTimeout(updateRect, 16)
                                return
                            }
                            if (ref.current) {
                                actions.setMainContentRect(ref.current.getBoundingClientRect())
                            }
                        }
                        const observer = new ResizeObserver(updateRect)
                        observer.observe(ref.current)
                        return () => {
                            observer.disconnect()
                            clearTimeout(resizeTimer)
                        }
                    }, 'resizeObserver')
                }
            }
        },
    })),
    selectors({
        isLayoutNavCollapsed: [
            (s) => [s.isLayoutNavCollapsedDesktop, s.layoutNavCollapsedOverride, s.mobileLayout],
            (
                isLayoutNavCollapsedDesktop: boolean,
                layoutNavCollapsedOverride: { owner: string; collapsed: boolean } | null,
                mobileLayout: boolean
            ): boolean => !mobileLayout && (layoutNavCollapsedOverride?.collapsed ?? isLayoutNavCollapsedDesktop),
        ],
        pathname: [
            (s) => [s.location],
            (location: { hash: string; pathname: string; search: string }): string => location.pathname,
        ],
    }),
    urlToAction(({ actions, values }) => ({
        '*': () => {
            if (values.isNavOverlayOpen) {
                actions.setNavOverlayOpen(false)
            }
            // Notifications sets activePanelIdentifier without flipping isLayoutPanelVisible, so check the
            // identifier too. Otherwise navigating away leaves the panel and its dim mounted.
            const panelIsShown = values.isLayoutPanelVisible || values.activePanelIdentifier !== ''
            if (values.mobileLayout && (values.isLayoutNavbarVisibleForMobile || panelIsShown)) {
                actions.showLayoutNavBar(false)
                actions.showLayoutPanel(false)
                actions.clearActivePanelIdentifier()
            }
        },
    })),
    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 (PANEL_LAYOUT_NAV_IDENTIFIERS.includes(values.activePanelIdentifier)) {
            actions.setActivePanelIdentifier(values.activePanelIdentifier as PanelLayoutNavIdentifier)
        } else if (values.activePanelIdentifier) {
            // A panel removed from the app can still be stored from an earlier session. Clear it, because
            // PanelLayout shows its dim for any stored panel, and nothing would render inside it.
            actions.clearActivePanelIdentifier()
            actions.showLayoutPanel(false)
        }
        // 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(() => {
                const handleResize = (): void => {
                    const mainContentRef = values.mainContentRef
                    if (mainContentRef?.current) {
                        actions.setMainContentRect(mainContentRef.current.getBoundingClientRect())
                    }
                }
                window.addEventListener('resize', handleResize)
                return () => window.removeEventListener('resize', handleResize)
            }, 'windowResize')
        }
    }),
])