summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-core/src/components/Link.js
blob: 8c142ea6dad78f548cbef3deb22c6ea10161b3a1 (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
const React = require('react');
const ReactRedux = require('react-redux');

const File = require('../models/File');
const SummaryArticle = require('../models/SummaryArticle');
const SummaryArticleShape = require('../shapes/SummaryArticle');
const ContextShape = require('../shapes/Context');

const Link = React.createClass({
    propTypes: {
        children: React.PropTypes.node,
        href:     React.PropTypes.string,
        to:       React.PropTypes.oneOfType([
            React.PropTypes.string,
            SummaryArticleShape
        ])
    },

    contextTypes: {
        gitbook: ContextShape.isRequired
    },

    getHref() {
        const { gitbook } = this.context;
        let { to, href } = this.props;

        if (href) {
            return href;
        }

        if (SummaryArticle.is(to)) {
            return to.toURL(gitbook);
        }

        if (typeof to === 'string') {
            to = new File(to);
        }

        if (File.is(to)) {
            return to.toURL(gitbook);
        }

        throw new Error('Invalid format for prop "to"');
    },

    render() {
        const { children, ...props } = this.props;
        const href = this.getHref();
        return <a href={href} {...props}>{children}</a>;
    }
});

module.exports = ReactRedux.connect()(Link);