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.

6.5 KB
Raw Blame
import React, { MouseEventHandler, useContext, useEffect, useRef, useState } from 'react'

import { Popover, PopoverOverlayContext, PopoverProps } from '../Popover'

export interface LemonDropdownProps extends Omit<PopoverProps, 'children' | 'visible'> {
    visible?: boolean
    /**
     *  Setting `visible` shifts the component to controlled mode.
     *  This lets you choose whether to start open (Defaults to false).
     *  Without having to take control of the visibility state.
     *  */
    startVisible?: boolean
    onVisibilityChange?: (visible: boolean) => void
    /**
     * Whether the dropdown should be closed on click inside.
     * @default true
     */
    closeOnClickInside?: boolean
    /** @default 'click' */
    trigger?: 'click' | 'hover'
    hoverOpenDelayMs?: number
    /** Disabled state for the trigger, e.g. injected by an access-control guard. */
    disabled?: boolean
    /** Reason shown when the trigger is disabled. */
    disabledReason?: string | null
    children: React.ReactElement<
        Record<string, any> & {
            onClick: MouseEventHandler
            active?: boolean
            'aria-haspopup': Required<React.AriaAttributes>['aria-haspopup']
        }
    >
}

/** A wrapper that provides a dropdown for any element supporting `onClick`. Built on top of Popover. */
export const LemonDropdown = React.forwardRef<HTMLDivElement, LemonDropdownProps>(
    (
        {
            visible,
            onVisibilityChange,
            onClickOutside,
            onClickInside,
            onMouseLeaveInside,
            closeOnClickInside = true,
            trigger = 'click',
            hoverOpenDelayMs = 0,
            children,
            startVisible,
            disabled,
            disabledReason,
            ...popoverProps
        },
        ref
    ) => {
        const isControlled = visible !== undefined

        const [, parentPopoverLevel] = useContext(PopoverOverlayContext)
        const [localVisible, setLocalVisible] = useState(visible ?? startVisible ?? false)

        const floatingRef = useRef<HTMLDivElement>(null)
        const referenceRef = useRef<HTMLSpanElement>(null)
        const hoverOpenTimeoutRef = useRef<number | null>(null)

        const clearHoverOpenTimeout = (): void => {
            if (hoverOpenTimeoutRef.current !== null) {
                window.clearTimeout(hoverOpenTimeoutRef.current)
                hoverOpenTimeoutRef.current = null
            }
        }

        useEffect(
            () => () => {
                if (hoverOpenTimeoutRef.current !== null) {
                    window.clearTimeout(hoverOpenTimeoutRef.current)
                }
            },
            []
        )

        const effectiveVisible = visible ?? localVisible

        const setVisible = (value: boolean): void => {
            if (!isControlled) {
                setLocalVisible(value)
            }
            onVisibilityChange?.(value)
        }

        // A guard clones these onto the dropdown, so merge them with whatever the trigger already has.
        const triggerDisabled = disabled || children.props.disabled
        const triggerDisabledReason = disabledReason ?? children.props.disabledReason

        return (
            <Popover
                ref={ref}
                floatingRef={floatingRef}
                referenceRef={referenceRef}
                onClickOutside={(e) => {
                    if (trigger === 'click') {
                        setVisible(false)
                    }
                    onClickOutside?.(e)
                }}
                onClickInside={(e) => {
                    e.stopPropagation()
                    closeOnClickInside && setVisible(false)
                    onClickInside?.(e)
                }}
                onMouseLeaveInside={(e) => {
                    // relatedTarget is null when leaving the window and isn't always a Node, so
                    // Node.contains() would throw — treat anything that isn't a contained Node as "left".
                    const relatedTarget = e.relatedTarget
                    if (
                        trigger === 'hover' &&
                        !(relatedTarget instanceof Node && referenceRef.current?.contains(relatedTarget))
                    ) {
                        setVisible(false)
                    }
                    onMouseLeaveInside?.(e)
                }}
                visible={effectiveVisible}
                {...popoverProps}
            >
                {React.cloneElement(children, {
                    onClick: (e: React.MouseEvent): void => {
                        clearHoverOpenTimeout()
                        setVisible(!effectiveVisible)
                        children.props.onClick?.(e)
                        if (parentPopoverLevel > -1) {
                            // If this button is inside another popover, let's not propagate this event so that
                            // the parent popover doesn't close
                            e.stopPropagation()
                        }
                    },
                    onMouseEnter: (): void => {
                        if (trigger === 'hover') {
                            clearHoverOpenTimeout()
                            if (hoverOpenDelayMs > 0) {
                                hoverOpenTimeoutRef.current = window.setTimeout(() => {
                                    hoverOpenTimeoutRef.current = null
                                    setVisible(true)
                                }, hoverOpenDelayMs)
                            } else {
                                setVisible(true)
                            }
                        }
                    },
                    onMouseLeave: (e: React.MouseEvent): void => {
                        clearHoverOpenTimeout()
                        const relatedTarget = e.relatedTarget
                        if (
                            trigger === 'hover' &&
                            !(relatedTarget instanceof Node && floatingRef.current?.contains(relatedTarget))
                        ) {
                            setVisible(false)
                        }
                    },
                    'aria-haspopup': 'true',
                    disabled: triggerDisabled,
                    // `disabledReason` is a LemonButton prop, so React warns if it reaches a plain element.
                    ...(triggerDisabledReason != null ? { disabledReason: triggerDisabledReason } : {}),
                })}
            </Popover>
        )
    }
)
LemonDropdown.displayName = 'Dropdown'