summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-core/src/components/Dropdown.js
blob: 78bad8db88337ba50097aaaf5a1d801f298221a7 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const React      = require('react');
const classNames = require('classnames');

/**
 * Dropdown to display a menu
 *
 * <Dropdown.Container>
 *
 *     <Button />
 *
 *     <Dropdown.Menu>
 *         <Dropdown.Item href={...}> ... </Dropdown.Item>
 *         <Dropdown.Item onClick={...}> ... </Dropdown.Item>
 *     </Dropdown.Menu>
 * </Dropdown.Container>
 */

const DropdownContainer = React.createClass({
    propTypes: {
        className:  React.PropTypes.string,
        children: React.PropTypes.node
    },

    render() {
        let { className, children } = this.props;

        className = classNames(
            'GitBook-Dropdown',
            className
        );

        return (
            <div className={className}>
                {children}
            </div>
        );
    }
});

/**
 * A dropdown item, which is always a link, and can contain a nested
 * DropdownMenu.
 */
const DropdownItem = React.createClass({
    propTypes: {
        children:  React.PropTypes.node,
        onClick:   React.PropTypes.func,
        href:      React.PropTypes.string
    },

    onClick(event) {
        const { onClick, href } = this.props;

        if (href) {
            return;
        }

        event.preventDefault();
        event.stopPropagation();

        if (onClick) {
            onClick();
        }
    },

    render() {
        const { children, href, onClick, ...otherProps } = this.props;

        let inner = children;

        if (href || onClick) {
            inner = (
                <a className="GitBook-DropdownItemLink" href={href || '#'} onClick={this.onClick} {...otherProps} >
                    {inner}
                </a>
            );
        }

        return (
            <div className="GitBook-DropdownItem">
                {inner}
            </div>
        );
    }
});

/**
 * A DropdownMenu to display DropdownItems. Must be inside a
 * DropdownContainer.
 */
const DropdownMenu = React.createClass({
    propTypes: {
        className: React.PropTypes.string,
        children:  React.PropTypes.node
    },

    render() {
        let { className, children } = this.props;
        className = classNames('GitBook-DropdownMenu', className);

        return (
            <div className={className}>
                {children}
            </div>
        );
    }
});

const Dropdown = {
    Item: DropdownItem,
    Menu: DropdownMenu,
    Container: DropdownContainer
};

module.exports = Dropdown;