showTasks = true)
"
x-data="{
showSnoozedTasks: false,
forceMarkdown: $persist(true).as(`page-${page.id}-markdown`),
confirmedSyncDialog: true, // TODO: Rename to what it is...
shouldSyncUp: true, // gets disabled while fetching from server. otherwise would repush that fetched change, messing with timestamps.
handleChange() {
const now = new Date()
page.lastChangedAt = now
if(!isOnline) return;
if(!page.globalId) return;
if(!this.shouldSyncUp) return;
debouncedSyncUp(page, this)
},
async establishSync() {
if(!isOnline) return;
if(!page.globalId) return;
// get page state from server to compare
response = await window.pb.collection('pages').getOne(page.globalId)
const { data } = response
// if latest local version got synced (aka no changes while offline)
if(page.lastChangedAt === page.lastSyncedAt) {
// is local sync time same as server change time? Nothing to do.
if(page.lastSyncedAt === data.lastChangedAt) {
this.confirmedSyncDialog = true
return
};
// is server change time newer than local sync time?
if(data.lastChangedAt > page.lastSyncedAt) {
// then update form server data
this.shouldSyncUp = false
await syncDown(page, data)
$nextTick(() => {
this.shouldSyncUp = true
})
this.confirmedSyncDialog = true
}
}
else if(page.lastSyncedAt === data.lastChangedAt) {
// if local lastSyncedAt is the same as the last change on the server, we know no other clients have pushed changes while we were offline.
// so it is save to push our offline changes.
syncUp(page, this)
this.confirmedSyncDialog = true
} else {
this.confirmedSyncDialog = false // Conflict!
}
},
subscribeToRealtimeChanges() {
pb.collection('pages').subscribe(page.globalId, function (e) {
page.text = e.record.data.text
page.tasks = e.record.data.tasks
page.lastChangedAt = e.record.data.lastChangedAt
page.lastSyncedAt = e.record.data.lastChangedAt
});
},
}"
x-init="
$watch('isOnline', (isOnline) => {
if(isOnline) establishSync()
})
// Watching not the whole page because watcher updates timestamp within page.
// Prevents infinite loop!
$watch('page.text', () => handleChange())
$watch('page.tasks', () => handleChange())
$watch('page.folder', () => handleChange())
// // Subscribe to remote page changes and keep in sync
subscribeToRealtimeChanges()
"
>