-
Notifications
You must be signed in to change notification settings - Fork 77
/
index.js
92 lines (75 loc) · 2.48 KB
/
index.js
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
import React, { Component } from 'react';
import ExecutionEnvironment from 'exenv';
import shallowEqual from 'shallowequal';
export default function withSideEffect(
reducePropsToState,
handleStateChangeOnClient,
mapStateOnServer
) {
if (typeof reducePropsToState !== 'function') {
throw new Error('Expected reducePropsToState to be a function.');
}
if (typeof handleStateChangeOnClient !== 'function') {
throw new Error('Expected handleStateChangeOnClient to be a function.');
}
if (typeof mapStateOnServer !== 'undefined' && typeof mapStateOnServer !== 'function') {
throw new Error('Expected mapStateOnServer to either be undefined or a function.');
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
return function wrap(WrappedComponent) {
if (typeof WrappedComponent !== 'function') {
throw new Error('Expected WrappedComponent to be a React component.');
}
let mountedInstances = [];
let state;
function emitChange() {
state = reducePropsToState(mountedInstances.map(function (instance) {
return instance.props;
}));
if (SideEffect.canUseDOM) {
handleStateChangeOnClient(state);
} else if (mapStateOnServer) {
state = mapStateOnServer(state);
}
}
class SideEffect extends Component {
// Try to use displayName of wrapped component
static displayName = `SideEffect(${getDisplayName(WrappedComponent)})`;
// Expose canUseDOM so tests can monkeypatch it
static canUseDOM = ExecutionEnvironment.canUseDOM;
static peek() {
return state;
}
static rewind() {
if (SideEffect.canUseDOM) {
throw new Error('You may only call rewind() on the server. Call peek() to read the current state.');
}
let recordedState = state;
state = undefined;
mountedInstances = [];
return recordedState;
}
shouldComponentUpdate(nextProps) {
return !shallowEqual(nextProps, this.props);
}
componentWillMount() {
mountedInstances.push(this);
emitChange();
}
componentDidUpdate() {
emitChange();
}
componentWillUnmount() {
const index = mountedInstances.indexOf(this);
mountedInstances.splice(index, 1);
emitChange();
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return SideEffect;
}
}