Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions package/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
const snapShot = [];
const mode = { jumping: false };

const linkState = require('./linkState')(snapShot, mode);
const timeJump = require('./timeJump')(snapShot, mode);

const getShot = () => snapShot.map(({ component }) => component.state);

window.addEventListener('message', ({ data: { action, payload } }) => {
if (action === 'jumpToSnap') {
console.log('snap received from chrome', payload);
timeJump(payload);
}
});

const linkState = require('./linkState')(snapShot);

module.exports = {
linkState,
timeJump,
getShot,
};
27 changes: 22 additions & 5 deletions package/linkState.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,46 @@
// links component state to library
// changes the setState method to also update our snapshot

module.exports = (snapShot) => {
module.exports = (snapShot, mode) => {
// send message to window containing component states
// unless library is currently jumping through time
function sendSnapShot() {
const payload = snapShot.map(comp => comp.state);
if (mode.jumping) return;
const payload = snapShot.map(({ component }) => component.state);
window.postMessage({
action: 'recordSnap',
payload,
});
}

return (component) => {
snapShot.push(component);
// make a copy of setState
const oldSetState = component.setState.bind(component);

sendSnapShot();
// convert setState to promise
const setStateAsync = (state) => {
return new Promise(resolve => oldSetState(state, resolve));
};

const oldSetState = component.setState.bind(component);
// add component to snapshot
snapShot.push({ component, setStateAsync });

let first = true;
function newSetState(state, callback = () => { }) {
// if setState is being called for the first time, this conditional sends the initial snapshot
if (first) {
first = false;
sendSnapShot();
}

// continue normal setState functionality, except add sending message middleware
oldSetState(state, () => {
sendSnapShot();
callback();
});
}

// replace component's setState so developer doesn't change syntax
component.setState = newSetState;
};
};
9 changes: 9 additions & 0 deletions package/timeJump.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = (snapShot, mode) => {
return (newSnapShot) => {
mode.jumping = true;
newSnapShot.forEach(async (state, i) => {
await snapShot[i].setStateAsync(state);
});
mode.jumping = false;
};
};