|
1 | 1 | // links component state to library |
2 | 2 | // changes the setState method to also update our snapshot |
3 | 3 |
|
4 | | -module.exports = (snapShot) => { |
| 4 | +module.exports = (snapShot, mode) => { |
| 5 | + // send message to window containing component states |
| 6 | + // unless library is currently jumping through time |
5 | 7 | function sendSnapShot() { |
6 | | - const payload = snapShot.map(comp => comp.state); |
| 8 | + if (mode.jumping) return; |
| 9 | + const payload = snapShot.map(({ component }) => component.state); |
7 | 10 | window.postMessage({ |
8 | 11 | action: 'recordSnap', |
9 | 12 | payload, |
10 | 13 | }); |
11 | 14 | } |
12 | 15 |
|
13 | 16 | return (component) => { |
14 | | - snapShot.push(component); |
| 17 | + // make a copy of setState |
| 18 | + const oldSetState = component.setState.bind(component); |
15 | 19 |
|
16 | | - sendSnapShot(); |
| 20 | + // convert setState to promise |
| 21 | + const setStateAsync = (state) => { |
| 22 | + return new Promise(resolve => oldSetState(state, resolve)); |
| 23 | + }; |
17 | 24 |
|
18 | | - const oldSetState = component.setState.bind(component); |
| 25 | + // add component to snapshot |
| 26 | + snapShot.push({ component, setStateAsync }); |
19 | 27 |
|
| 28 | + let first = true; |
20 | 29 | function newSetState(state, callback = () => { }) { |
| 30 | + // if setState is being called for the first time, this conditional sends the initial snapshot |
| 31 | + if (first) { |
| 32 | + first = false; |
| 33 | + sendSnapShot(); |
| 34 | + } |
| 35 | + |
| 36 | + // continue normal setState functionality, except add sending message middleware |
21 | 37 | oldSetState(state, () => { |
22 | 38 | sendSnapShot(); |
23 | 39 | callback(); |
24 | 40 | }); |
25 | 41 | } |
26 | 42 |
|
| 43 | + // replace component's setState so developer doesn't change syntax |
27 | 44 | component.setState = newSetState; |
28 | 45 | }; |
29 | 46 | }; |
0 commit comments