summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-core/src/components/UnsafeComponent.js
blob: e9d2895be6a2430fb205b8c618f64a6a613956ff (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
/* eslint-disable no-console */
const React = require('react');
const ReactDOM = require('react-dom');
const ReactRedux = require('react-redux');

/*
 Public: Renders a component provided via the `component` prop, and ensures that
 failures in the component's code do not cause state inconsistencies elsewhere in
 the application. This component is used by {InjectedComponent} and
 {InjectedComponentSet} to isolate third party code that could be buggy.

 Occasionally, having your component wrapped in {UnsafeComponent} can cause style
 issues. For example, in a Flexbox, the `div.unsafe-component-wrapper` will cause
 your `flex` and `order` values to be one level too deep. For these scenarios,
 UnsafeComponent looks for `containerStyles` on your React component and attaches
 them to the wrapper div.
 */


const UnsafeComponent = React.createClass({
    propTypes: {
        Component: React.PropTypes.func.isRequired,
        props:     React.PropTypes.object
    },

    componentDidMount() {
        return this.renderInjected();
    },

    componentDidUpdate() {
        return this.renderInjected();
    },

    componentWillUnmount() {
        return this.unmountInjected();
    },

    renderInjected() {
        const { Component, props } = this.props;
        const { store } = this.context;

        const node = ReactDOM.findDOMNode(this);

        try {
            this.injected = (
                <ReactRedux.Provider store={store}>
                    <Component {...props}/>
                </ReactRedux.Provider>
            );

            ReactDOM.render(this.injected, node);
        } catch (err) {
            console.error(err);
        }
    },

    unmountInjected() {
        try {
            const node = ReactDOM.findDOMNode(this);
            return ReactDOM.unmountComponentAtNode(node);
        } catch (err) {
            console.error(err);
        }
    },

    focus() {
        if (this.injected.focus != null) {
            return this.injected.focus();
        }
    },

    blur() {
        if (this.injected.blur != null) {
            return this.injected.blur();
        }
    },

    render() {
        return <div name="unsafe-component-wrapper" />;
    }
});

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