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.

4.8 KB
Raw Blame
import clsx from 'clsx'
import { useEffect, useRef, useState } from 'react'

import { IconCheck, IconX } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'

import { AutoSizer } from 'lib/components/AutoSizer'
import { CodeEditor, CodeEditorProps } from 'lib/monaco/CodeEditor'

export interface CodeEditorResizableProps extends Omit<CodeEditorProps, 'height'> {
    height?: number
    minHeight?: string | number
    maxHeight?: string | number
    editorClassName?: string
    embedded?: boolean
    showDiffActions?: boolean
    onAcceptChanges?: () => void
    onRejectChanges?: () => void
    originalValue?: string
    allowManualResize?: boolean
}

// Floor for a dragged height. Two Monaco lines stay readable, and the editor cannot be
// dragged away to nothing.
const MANUAL_RESIZE_MIN_HEIGHT = 44

export function CodeEditorResizeable({
    height: defaultHeight,
    minHeight = '5rem',
    maxHeight = '90vh',
    className,
    editorClassName,
    embedded = false,
    showDiffActions = false,
    onAcceptChanges,
    onRejectChanges,
    originalValue,
    allowManualResize = true,
    ...props
}: CodeEditorResizableProps): JSX.Element {
    const [height, setHeight] = useState(defaultHeight)
    const [manualHeight, setManualHeight] = useState<number | undefined>(defaultHeight)

    const ref = useRef<HTMLDivElement | null>(null)

    useEffect(() => {
        const value = typeof props.value !== 'string' ? JSON.stringify(props.value, null, 2) : props.value
        const lineCount = (value?.split('\n').length ?? 1) + 1
        const lineHeight = 18
        setHeight(lineHeight * lineCount)
    }, [props.value])

    return (
        <div
            ref={ref}
            className={clsx('relative CodeEditorResizeable', !embedded ? 'w-full rounded border' : '', className)}
            // eslint-disable-next-line react/forbid-dom-props
            style={{
                // `minHeight` and `maxHeight` bound how the editor sizes itself to its content.
                // A drag is a deliberate choice, so it overrides both. A `minHeight` that still
                // applied after a drag would let the editor grow but never shrink.
                minHeight: manualHeight ?? minHeight,
                maxHeight: manualHeight ?? maxHeight,
                height: manualHeight ?? height,
            }}
        >
            <AutoSizer
                disableWidth
                renderProp={({ height }) =>
                    height ? (
                        <CodeEditor
                            {...props}
                            className={editorClassName}
                            height={height - 2} // Account for border
                            originalValue={originalValue}
                        />
                    ) : null
                }
            />

            {showDiffActions && (
                <div className="flex absolute top-2 right-2 z-20 gap-1 p-1 bg-white rounded-lg border shadow-sm">
                    <LemonButton
                        status="danger"
                        icon={<IconX />}
                        onClick={onRejectChanges}
                        tooltipPlacement="top"
                        size="small"
                    >
                        Reject
                    </LemonButton>
                    <LemonButton
                        type="tertiary"
                        icon={<IconCheck color="var(--success)" />}
                        onClick={onAcceptChanges}
                        tooltipPlacement="top"
                        size="small"
                    >
                        Accept
                    </LemonButton>
                </div>
            )}

            {/* Using a standard resize css means we need overflow-hidden which hides parts of the editor unnecessarily */}
            {allowManualResize && (
                <div
                    className="overflow-hidden absolute right-0 bottom-0 z-20 w-5 h-5 resize-y cursor-s-resize"
                    onMouseDown={(e) => {
                        const startY = e.clientY
                        const startHeight = ref.current?.clientHeight ?? 0
                        const onMouseMove = (event: MouseEvent): void => {
                            setManualHeight(Math.max(startHeight + event.clientY - startY, MANUAL_RESIZE_MIN_HEIGHT))
                        }
                        const onMouseUp = (): void => {
                            window.removeEventListener('mousemove', onMouseMove)
                            window.removeEventListener('mouseup', onMouseUp)
                        }
                        window.addEventListener('mousemove', onMouseMove)
                        window.addEventListener('mouseup', onMouseUp)
                    }}
                />
            )}
        </div>
    )
}