-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
64 lines (56 loc) · 1.67 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
const React = require('react');
function identity(props) {
return props;
}
module.exports = {
CloudCannonConnect: function (Component, options = {}) {
const processProps = options?.processProps || identity;
return class LivePageComponent extends React.Component{
constructor(props) {
super(props);
this.state = props.page?.data || {};
this.onLoadEventListener = (e) => {
this.onCloudCannonLoad(e.detail.CloudCannon);
};
this.onUpdateEventListener = (e) => {
this.loadNewPropsFromCloudCannon(e.detail.CloudCannon);
};
}
componentDidMount() {
document.addEventListener('cloudcannon:load', this.onLoadEventListener);
document.addEventListener('cloudcannon:update', this.onUpdateEventListener);
if (window.CloudCannon) {
this.onCloudCannonLoad(window.CloudCannon);
}
}
async loadNewPropsFromCloudCannon(CloudCannon) {
try {
const latestValue = await CloudCannon.value(options?.valueOptions);
this.setState(latestValue);
} catch(fetchError) {
console.warn('Failed to fetch latest page props', fetchError);
}
}
onCloudCannonLoad(CloudCannon) {
CloudCannon.enableEvents();
this.loadNewPropsFromCloudCannon(CloudCannon);
}
componentWillUnmount() {
document.removeEventListener('cloudcannon:load', this.onLoadEventListener);
document.removeEventListener('cloudcannon:update', this.onUpdateEventListener);
}
render() {
const hydratedProps = {
...this.props,
page: {
...this.props.page,
data: {
...processProps(this.state)
},
}
}
return React.createElement(Component, hydratedProps, this.props.children);
}
}
}
}