summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-plugin-copy-code/src/index.js
blob: 73d46c6d122bfd1dd75a942f592ec39c40559c82 (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
const copy = require('copy-to-clipboard');
const GitBook = require('gitbook-core');
const { React } = GitBook;

const COPIED_TIMEOUT = 1000;

/**
 * Get children as text
 * @param {React.Children} children
 * @return {String}
 */
function getChildrenToText(children) {
    return React.Children.map(children, child => {
        if (typeof child === 'string') {
            return child;
        } else {
            return child.props.children ?
                getChildrenToText(child.props.children) : '';
        }
    }).join('');
}

let CodeBlockWithCopy = React.createClass({
    propTypes: {
        children: React.PropTypes.node,
        i18n: GitBook.PropTypes.I18n
    },

    getInitialState() {
        return {
            copied: false
        };
    },

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

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

        const text = getChildrenToText(children);
        copy(text);

        this.setState({ copied: true }, () => {
            this.timeout = setTimeout(() => {
                this.setState({
                    copied: false
                });
            }, COPIED_TIMEOUT);
        });
    },

    componentWillUnmount() {
        if (this.timeout) {
            clearTimeout(this.timeout);
        }
    },

    render() {
        const { children, i18n } = this.props;
        const { copied } = this.state;

        return (
            <div className="CodeBlockWithCopy-Container">
                <GitBook.ImportCSS href="gitbook/copy-code/button.css" />

                {children}
                <span className="CodeBlockWithCopy-Button" onClick={this.onClick}>
                    {copied ? i18n.t('COPIED') : i18n.t('COPY')}
                </span>
            </div>
        );
    }
});

CodeBlockWithCopy = GitBook.connect(CodeBlockWithCopy);

module.exports = GitBook.createPlugin({
    activate: (dispatch, getState, { Components }) => {
        dispatch(Components.registerComponent(CodeBlockWithCopy, { role: 'html:pre' }));
    }
});