Last active
December 31, 2019 04:15
-
-
Save davidgilbertson/9f37fa79449160be4798e4cd22b4ee5f to your computer and use it in GitHub Desktop.
This file contains 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
import cab from './cab.js'; // the file from above | |
const getOrCreateProgressData = async () => { | |
// Get the ID from the URL | |
const url = new URL(document.location); | |
const existingId = url.searchParams.get('id'); | |
// If there was an ID, fetch the associated data | |
if (existingId) { | |
const readResponse = await cab.read(existingId); | |
return {id: existingId, data: readResponse.data}; | |
} | |
// If there was no ID, create a new record | |
const initialData = {scrollPos: 0}; | |
const createResponse = await cab.create(initialData); | |
// Put the new ID in the URL | |
url.searchParams.set('id', createResponse.id); | |
window.history.replaceState('', null, url.href); | |
return {id: createResponse.id, data: initialData}; | |
}; | |
// Kickoff | |
(async () => { | |
const {id, data} = await getOrCreateProgressData(); | |
// If there was a scroll position, apply that now | |
if (data.scrollPos !== 0) window.scrollY = data.scrollPos; | |
// And keep the database up to date with the scroll position | |
window.addEventListener('scroll', () => { | |
cab.update(id, {scrollPos: window.scrollY}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment