diff --git a/src/itemService.js b/src/itemService.js index c98737a..e43c97c 100644 --- a/src/itemService.js +++ b/src/itemService.js @@ -54,22 +54,46 @@ }, async setItem(id, item) { - if (!window.user) { - return new Promise(resolve => resolve()); + const d = deferred(); + var remotePromise; + // TODO: check why we need to save locally always? + const obj = { + [id]: item + }; + db.local.set(obj, () => { + // Is extension OR is app but logged out OR is logged in but offline + // If logged in but offline, resolve immediately so + // that you see the feedback msg immediately and not wait for + // later sync. + if (window.IS_EXTENSION || !window.user || !navigator.onLine) { + d.resolve(); + } + }); + + // If `id` is `code`, this is a call on unloadbefore to save the last open thing. + // Do not presist that on remote. + if (id === 'code') { + // No deferred required here as this gets called on unloadbefore + return false; } - var remoteDb = await window.db.getDb(); - utils.log(`Starting to save item ${id}`); - item.createdBy = window.user.uid; - return remoteDb - .collection('items') - .doc(id) - .set(item, { - merge: true - }) - .then(arg => { - utils.log('Document written', arg); - }) - .catch(error => utils.log(error)); + if (window.user) { + var remoteDb = await window.db.getDb(); + utils.log(`Starting to save item ${id}`); + item.createdBy = window.user.uid; + remotePromise = remoteDb + .collection('items') + .doc(id) + .set(item, { + merge: true + }) + .then(arg => { + utils.log('Document written', arg); + d.resolve(); + }) + .catch(d.reject); + } + + return (window.user && navigator.onLine) ? remotePromise : d.promise; }, /** diff --git a/src/script.js b/src/script.js index 828144d..1b38aa4 100644 --- a/src/script.js +++ b/src/script.js @@ -423,18 +423,19 @@ loginModal, profileModal, profileAvatarImg, profileUserName currentItem.mainSizes = getMainPaneSizes(); utils.log('saving key', key || currentItem.id, currentItem); - saveSetting(key || currentItem.id, currentItem); - // If key is `code`, this is a call on unloadbefore to save the last open thing. - // Do not presist that on remote. - if (key === 'code') { - // No deferred required here as this gets called on unloadbefore - return false; - } - return itemService.setItem(key || currentItem.id, currentItem).then(() => { - alertsService.add('Item saved.'); + + function onSaveComplete() { + if (window.user && !navigator.onLine) { + alertsService.add('Item saved locally. Will save to account when you are online.'); + } else { + alertsService.add('Item saved.'); + + } unsavedEditCount = 0; saveBtn.classList.remove('is-marked'); - }); + } + + return itemService.setItem(key || currentItem.id, currentItem).then(onSaveComplete); } function populateItemsInSavedPane(items) {