summaryrefslogtreecommitdiff
path: root/src/components/toolbar/ToolbarItem.tsx
blob: 76bd61558a11f69f78eead2ddc1ac1ebddc8b4ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import React, { useState } from 'react';

export interface ToolbarItemProps {
    children: React.ReactNode;
    renderContent?: (onClose: () => void) => React.ReactNode;
    onClick?: () => void;
    disabled?: boolean;
}

export const ToolbarItem: React.FC<ToolbarItemProps> = ({
    children,
    renderContent,
    onClick,
    disabled = false,
}) => {
    const [isOpen, setIsOpen] = useState(false);
    const [isFading, setIsFading] = useState(false);

    const handleClose = () => {
        setIsFading(true);
        setTimeout(() => {
            setIsOpen(false);
            setIsFading(false);
        }, 200);
    };

    const handleToggle = (e: React.MouseEvent) => {
        e.stopPropagation();
        if (disabled) return;

        if (renderContent) {
            if (isOpen) {
                handleClose();
            } else {
                setIsOpen(true);
            }
        }

        onClick?.();
    };

    return (
        <div className={`toolbar-item ${disabled ? 'disabled' : ''}`} onClick={handleToggle}>
            <div className='toolbar-item-content'>
                {children}
            </div>
            {renderContent && isOpen && !disabled && (
                <div
                    className={`toolbar-item-content-panel ${isFading ? 'fading' : ''}`}
                    onClick={(e) => e.stopPropagation()}
                >
                    {renderContent(handleClose)}
                </div>
            )}
        </div>
    );
};