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.

8.0 KB
Raw Blame
import React, { useCallback, useEffect, useRef, useState } from 'react'

import { cn } from 'lib/utils/css-classes'

const SNAP_TO_DEFAULT_THRESHOLD = 16

type ResizableElementProps = {
    defaultWidth: number
    minWidth?: number
    maxWidth?: number
    snapToDefault?: boolean
    onResize: (width: number) => void
    children?: React.ReactNode
    className?: string
    innerClassName?: string
    style?: React.CSSProperties
    borderPosition?: 'center' | 'left' | 'right'
    onResizeStart?: () => void
    onResizeEnd?: () => void
}

export function ResizableElement({
    defaultWidth,
    minWidth = 100,
    maxWidth = 1000,
    snapToDefault = false,
    onResize,
    children,
    className,
    innerClassName,
    style,
    borderPosition = 'center',
    onResizeStart,
    onResizeEnd,
    ...props
}: ResizableElementProps): JSX.Element {
    const [width, setWidth] = useState(defaultWidth)
    const containerRef = useRef<HTMLDivElement>(null)
    const handleRef = useRef<HTMLDivElement>(null)
    const startXRef = useRef<number>(0)
    const startWidthRef = useRef<number>(0)
    const isResizing = useRef(false)
    const rafRef = useRef<number | null>(null)
    const currentWidthRef = useRef(defaultWidth)

    // Update the current width ref when state changes
    useEffect(() => {
        currentWidthRef.current = width
    }, [width])

    // Function to apply width directly to DOM for smoother resizing
    const applyWidth = useCallback((newWidth: number) => {
        if (containerRef.current) {
            containerRef.current.style.width = `${newWidth}px`
        }
        currentWidthRef.current = newWidth
    }, [])

    useEffect(() => {
        if (!isResizing.current && defaultWidth !== currentWidthRef.current) {
            setWidth(defaultWidth)
            if (containerRef.current) {
                containerRef.current.style.width = `${defaultWidth}px`
            }
            currentWidthRef.current = defaultWidth
        }
    }, [defaultWidth])

    const handleMouseDown = useCallback(
        (e: React.MouseEvent | React.TouchEvent) => {
            document.body.classList.add('is-resizing')
            const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX
            startXRef.current = clientX
            startWidthRef.current = currentWidthRef.current
            isResizing.current = true
            e.preventDefault()
            onResizeStart?.()
        },
        [onResizeStart]
    )

    const handleMove = useCallback(
        (clientX: number) => {
            if (!isResizing.current) {
                return
            }

            // Cancel any ongoing animation frame
            if (rafRef.current !== null) {
                cancelAnimationFrame(rafRef.current)
            }

            // Schedule a new frame for smooth animation
            rafRef.current = requestAnimationFrame(() => {
                // Calculate the difference from start position
                const deltaX = clientX - startXRef.current

                // Apply the delta to the starting width
                let newWidth = Math.min(Math.max(startWidthRef.current + deltaX, minWidth), maxWidth)
                const isSnapping = snapToDefault && Math.abs(newWidth - defaultWidth) <= SNAP_TO_DEFAULT_THRESHOLD
                if (isSnapping) {
                    newWidth = defaultWidth
                }
                handleRef.current?.classList.toggle('is-snapping', isSnapping)

                // Apply width directly to DOM for smoother animation
                applyWidth(newWidth)

                // Call onResize callback but not setState (we'll do that on mouseup)
                onResize(newWidth)

                rafRef.current = null
            })
        },
        [applyWidth, defaultWidth, maxWidth, minWidth, onResize, snapToDefault]
    )

    const handleMouseMove = useCallback(
        (e: MouseEvent) => {
            handleMove(e.clientX)
        },
        [handleMove]
    )

    const handleTouchMove = useCallback(
        (e: TouchEvent) => {
            handleMove(e.touches[0].clientX)
        },
        [handleMove]
    )

    const handleEnd = useCallback(() => {
        if (isResizing.current) {
            let finalWidth = currentWidthRef.current
            if (snapToDefault && Math.abs(finalWidth - defaultWidth) <= SNAP_TO_DEFAULT_THRESHOLD) {
                finalWidth = defaultWidth
                applyWidth(defaultWidth)
            }
            setWidth(finalWidth)
            currentWidthRef.current = finalWidth
            isResizing.current = false
            handleRef.current?.classList.remove('is-snapping')

            // Clean up any pending animation frame
            if (rafRef.current !== null) {
                cancelAnimationFrame(rafRef.current)
                rafRef.current = null
            }
            document.body.classList.remove('is-resizing')
            onResizeEnd?.()
        }
    }, [applyWidth, defaultWidth, onResizeEnd, snapToDefault])

    // Keep latest handler implementations in refs so the document listeners
    // below can be registered exactly once per mount, regardless of how
    // often caller props change and rebuild the useCallbacks.
    const handleMouseMoveRef = useRef(handleMouseMove)
    const handleTouchMoveRef = useRef(handleTouchMove)
    const handleEndRef = useRef(handleEnd)
    useEffect(() => {
        handleMouseMoveRef.current = handleMouseMove
        handleTouchMoveRef.current = handleTouchMove
        handleEndRef.current = handleEnd
    }, [handleMouseMove, handleTouchMove, handleEnd])

    useEffect(() => {
        const onMouseMove = (e: MouseEvent): void => handleMouseMoveRef.current(e)
        const onTouchMove = (e: TouchEvent): void => handleTouchMoveRef.current(e)
        const onEnd = (): void => handleEndRef.current()

        document.addEventListener('mousemove', onMouseMove)
        document.addEventListener('mouseup', onEnd)
        document.addEventListener('touchmove', onTouchMove, { passive: true })
        document.addEventListener('touchend', onEnd)

        return () => {
            document.removeEventListener('mousemove', onMouseMove)
            document.removeEventListener('mouseup', onEnd)
            document.removeEventListener('touchmove', onTouchMove)
            document.removeEventListener('touchend', onEnd)

            if (rafRef.current !== null) {
                cancelAnimationFrame(rafRef.current)
            }
        }
    }, [])

    return (
        <div
            ref={containerRef}
            // eslint-disable-next-line react/forbid-dom-props
            style={{ width, ...style }}
            className={cn('relative', className)}
        >
            {children}
            <div
                ref={handleRef}
                onMouseDown={handleMouseDown}
                onTouchStart={handleMouseDown}
                className={cn(
                    'absolute top-0 right-0 w-1 h-full cursor-ew-resize w-[var(--resizer-thickness)] touch-none overflow-hidden hover:bg-accent-highlight-primary [&.is-snapping]:bg-accent-primary after:content-[""] after:absolute after:top-0 after:w-[1px] after:h-full after:bg-border-primary after:-translate-x-1/2 after:left-1/2',
                    {
                        'bg-accent-highlight-primary': isResizing.current,
                        'after:left-0': borderPosition === 'left',
                        'after:left-full': borderPosition === 'right',
                    },
                    innerClassName
                )}
                role="separator"
                tabIndex={0}
                onKeyDown={(e) => {
                    if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
                        e.preventDefault()
                        const delta = e.key === 'ArrowLeft' ? -10 : 10
                        const newWidth = Math.min(Math.max(width + delta, minWidth), maxWidth)
                        setWidth(newWidth)
                        applyWidth(newWidth)
                        onResize(newWidth)
                    }
                }}
                {...props}
            />
        </div>
    )
}