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.

7.9 KB
Raw Blame
import './LemonCollapse.scss'

import clsx from 'clsx'
import React, { ReactNode, useEffect, useId, useMemo, useRef, useState } from 'react'
import useResizeObserver from 'use-resize-observer'

import { IconCollapse, IconExpand } from '@posthog/icons'

import { useAnimatedPresence } from 'lib/hooks/useAnimatedPresence'

import { LemonButton, LemonButtonProps } from '../LemonButton'

export interface LemonCollapsePanel<K extends React.Key> {
    key: K
    header: ReactNode | LemonButtonProps
    content: ReactNode
    dataAttr?: string
    className?: string
    bodyClassName?: string
}

interface LemonCollapsePropsBase<K extends React.Key> {
    /** Panels in order of display. Falsy values mean that the panel isn't rendered. */
    panels: (LemonCollapsePanel<K> | null | false)[]
    className?: string
    size?: LemonButtonProps['size']
    embedded?: boolean
}

interface LemonCollapsePropsSingle<K extends React.Key> extends LemonCollapsePropsBase<K> {
    /** Pass this to control the panel. `null` or `undefined` then means closed, not uncontrolled. */
    activeKey?: K | null
    defaultActiveKey?: K
    onChange?: (activeKey: K | null) => void
    multiple?: false
}

interface LemonCollapsePropsMultiple<K extends React.Key> extends LemonCollapsePropsBase<K> {
    activeKeys?: K[]
    defaultActiveKeys?: K[]
    onChange?: (activeKeys: K[]) => void
    multiple: true
}

export type LemonCollapseProps<K extends React.Key> = LemonCollapsePropsSingle<K> | LemonCollapsePropsMultiple<K>

export function LemonCollapse<K extends React.Key>({
    panels,
    className,
    size,
    embedded,
    ...props
}: LemonCollapseProps<K>): JSX.Element {
    let isPanelExpanded: (key: K) => boolean
    let onPanelChange: (key: K, isExpanded: boolean) => void
    if (props.multiple) {
        const defaultActiveKeys = props.defaultActiveKeys ?? []
        const defaultActiveKeysString = defaultActiveKeys.join(',')
        // eslint-disable-next-line react-hooks/rules-of-hooks
        const [localActiveKeys, setLocalActiveKeys] = useState<Set<K>>(new Set(defaultActiveKeys))
        // eslint-disable-next-line react-hooks/rules-of-hooks
        useEffect(() => {
            setLocalActiveKeys(new Set(defaultActiveKeys))
        }, [defaultActiveKeysString])
        const effectiveActiveKeys = props.activeKeys ? new Set(props.activeKeys) : localActiveKeys
        isPanelExpanded = (key: K) => effectiveActiveKeys.has(key)
        onPanelChange = (key: K, isExpanded: boolean): void => {
            const newActiveKeys = new Set(effectiveActiveKeys)
            if (isExpanded) {
                newActiveKeys.add(key)
            } else {
                newActiveKeys.delete(key)
            }
            props.onChange?.(Array.from(newActiveKeys))
            setLocalActiveKeys(newActiveKeys)
        }
    } else {
        // eslint-disable-next-line react-hooks/rules-of-hooks
        const [localActiveKey, setLocalActiveKey] = useState<K | null>(props.defaultActiveKey ?? null)
        // Read the presence of `activeKey` rather than its value. A caller that controls the panel
        // has no other way to say "closed", so falling back on a nullish value would reopen the
        // panel from whatever the user last clicked.
        const effectiveActiveKey = 'activeKey' in props ? (props.activeKey ?? null) : localActiveKey
        isPanelExpanded = (key: K) => key === effectiveActiveKey
        onPanelChange = (key: K, isExpanded: boolean): void => {
            props.onChange?.(isExpanded ? key : null)
            setLocalActiveKey(isExpanded ? key : null)
        }
    }

    const displayPanels = panels.filter(Boolean) as LemonCollapsePanel<K>[]
    const hasExpandablePanels = displayPanels.some((p) => !!p.content)

    return (
        <div className={clsx('LemonCollapse', embedded && 'LemonCollapse--embedded', className)}>
            {displayPanels.map(({ key, ...panel }) => (
                <LemonCollapsePanel
                    key={key}
                    {...panel}
                    size={size}
                    isExpanded={isPanelExpanded(key)}
                    indexUnexpanableHeader={hasExpandablePanels}
                    onChange={(isExanded) => onPanelChange(key, isExanded)}
                />
            ))}
        </div>
    )
}

interface LemonCollapsePanelProps {
    header: ReactNode | LemonButtonProps
    content: ReactNode
    isExpanded: boolean
    indexUnexpanableHeader: boolean
    size: LemonButtonProps['size']
    onChange: (isExpanded: boolean) => void
    className?: string
    bodyClassName?: string
    dataAttr?: string
    onHeaderClick?: () => void
}

interface HeaderDefinition {
    headerChildren: ReactNode
    headerProps: LemonButtonProps
}

function LemonCollapsePanel({
    header,
    content,
    isExpanded,
    size,
    className,
    bodyClassName,
    dataAttr,
    indexUnexpanableHeader,
    onChange,
    onHeaderClick,
}: LemonCollapsePanelProps): JSX.Element {
    const { height: contentHeight, ref: contentRef } = useResizeObserver({ box: 'border-box' })
    const bodyRef = useRef<HTMLDivElement>(null)
    const { rendered, shown } = useAnimatedPresence(isExpanded, 200, bodyRef)
    const bodyId = useId()

    const { headerChildren, headerProps } = useMemo((): HeaderDefinition => {
        if (header && typeof header === 'object' && 'children' in header) {
            const { children, ...rest } = header as LemonButtonProps
            return { headerChildren: children, headerProps: rest }
        }

        return { headerChildren: header as ReactNode, headerProps: {} }
    }, [header])

    return (
        <div className="LemonCollapsePanel" aria-expanded={isExpanded}>
            {content ? (
                <LemonButton
                    {...headerProps}
                    fullWidth
                    className={clsx('LemonCollapsePanel__header', headerProps?.className)}
                    onClick={(e) => {
                        onHeaderClick && onHeaderClick()
                        onChange(!isExpanded)
                        headerProps.onClick?.(e)
                        e.stopPropagation()
                    }}
                    icon={isExpanded ? <IconCollapse /> : <IconExpand />}
                    {...(dataAttr ? { 'data-attr': dataAttr } : {})}
                    size={size}
                    // The header button is the only focusable control, so the panel state has to
                    // reach a screen reader from here. The wrapper below carries the same state for
                    // CSS, where a non-focusable element is all a stylesheet needs.
                    aria-expanded={isExpanded}
                    // A closed panel unmounts its body, so point at it only while it exists.
                    aria-controls={rendered ? bodyId : undefined}
                >
                    {headerChildren}
                </LemonButton>
            ) : (
                <LemonButton
                    className="LemonCollapsePanel__header LemonCollapsePanel__header--disabled"
                    {...(dataAttr ? { 'data-attr': dataAttr } : {})}
                    size={size}
                    icon={indexUnexpanableHeader ? <div className="w-[1em] h-[1em]" /> : null}
                >
                    {headerChildren}
                </LemonButton>
            )}

            {rendered && (
                <div
                    ref={bodyRef}
                    id={bodyId}
                    className={clsx('LemonCollapsePanel__body', bodyClassName)}
                    // eslint-disable-next-line react/forbid-dom-props
                    style={{ height: shown ? contentHeight : 0 }}
                    aria-busy={rendered !== shown}
                >
                    <div className={clsx('LemonCollapsePanel__content', className)} ref={contentRef}>
                        {content}
                    </div>
                </div>
            )}
        </div>
    )
}

LemonCollapse.Panel = LemonCollapsePanel