Created
February 26, 2018 00:44
-
-
Save treyhuffine/fdc49adbf509a064db751d54f274ca27 to your computer and use it in GitHub Desktop.
An educational time travel implementation for Redux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const timeline = []; | |
let activeItem = 0; | |
const saveTimeline = () => { | |
timeline.push(store.getState()); | |
timelineNode.innerHTML = timeline | |
.map(item => JSON.stringify(item)) | |
.join('<br/>'); | |
activeItem = timeline.length - 1; | |
}; | |
store.subscribe(saveTimeline); | |
// FOR DEBUGGING & EDUCATIONAL PURPOSES ONLY | |
// The store should not be extended like this. | |
store.setState = desiredState => { | |
store.state = desiredState; | |
// Assume the debugger is injected last. We don't want to update | |
// the saved states as we're debugging. | |
const applicationListeners = store.listeners.slice(0, -1); | |
applicationListeners.forEach(listener => listener()); | |
}; | |
// This assumes there are previous/next buttons with the give IDs to control the time travel | |
const previous = document.getElementById('previous'); | |
const next = document.getElementById('next'); | |
previous.addEventListener('click', e => { | |
e.preventDefault(); | |
e.stopPropagation(); | |
let index = activeItem - 1; | |
index = index <= 0 ? 0 : index; | |
activeItem = index; | |
const desiredState = timeline[index]; | |
store.setState(desiredState); | |
}); | |
next.addEventListener('click', e => { | |
e.preventDefault(); | |
e.stopPropagation(); | |
let index = activeItem + 1; | |
index = index >= timeline.length - 1 ? timeline.length - 1 : index; | |
activeItem = index; | |
const desiredState = timeline[index]; | |
store.setState(desiredState); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment