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

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

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

        if (href) {
            return href;
        }

        if (typeof to === 'string') {
            return to;
        }

        // Article
        if (typeof to.ref === 'string') {
            const parts = url.parse(to.ref);
            const ext = path.extname(parts.pathname);
            const pathname = path.basename(parts.pathname, ext) + '.html';

            return pathname + (parts.hash || '');
        }
    },

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

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