feature: sync multiple tabs using local storage

This commit is contained in:
Ondřej Synáček 2020-12-15 21:16:30 +01:00
parent 61985990d0
commit e28b378e07
5 changed files with 59 additions and 12 deletions

View File

@ -4,8 +4,6 @@
import { configStore } from '../stores'
$: showTrackingPanel = $configStore.track === undefined
configStore.subscribe(console.log)
</script>
{#if showTrackingPanel}

View File

@ -1,8 +1,12 @@
import App from './components/App.svelte'
import * as stores from './stores'
import * as services from './services'
const boot = () => {
services.storageListener.register()
new App({
target: document.querySelector('#root'),
})
@ -10,6 +14,7 @@ const boot = () => {
if (process.env.NODE_ENV === 'development') {
window._fb2ical = {
...stores,
...services,
}
}
}

View File

@ -0,0 +1,5 @@
import storageListener from './storageListener'
export {
storageListener,
}

View File

@ -0,0 +1,45 @@
import { configStore } from '../stores'
const STORAGE_KEYS = {
CONFIG: 'fb-to-ical-config',
}
class StorageListener {
constructor() {
this._storeSubscribers = new Set()
}
register() {
window.addEventListener('storage', this._handleStorageChange)
const unsubscribeConfigStore = configStore.subscribe(this._handleConfigStoreChange)
this._storeSubscribers = new Set([
...this._storeSubscribers,
unsubscribeConfigStore,
])
}
unregister() {
window.removeEventListener('storage', this._handleStorageChange)
this._storeSubscribers.forEach((unsubscribe) => unsubscribe())
this._storeSubscribers.clear()
}
_handleStorageChange(event) {
switch (event.key) {
case STORAGE_KEYS.CONFIG:
configStore.set(JSON.parse(event.newValue))
break
default:
return
}
}
_handleConfigStoreChange(value) {
localStorage.setItem(STORAGE_KEYS.CONFIG, JSON.stringify(value))
}
}
export default new StorageListener()

View File

@ -6,17 +6,10 @@ const createConfigStore = () => {
const { subscribe, set, update } = writable(state)
const setValue = (key, value) => {
update((prevState) => {
const nextState = {
...prevState,
[key]: value,
update((prevState) => ({ ...prevState, [key]: value }))
}
localStorage.setItem('fb-to-ical-config', JSON.stringify(nextState))
return nextState
})
}
const getState = () => state
return {
...state,
@ -24,6 +17,7 @@ const createConfigStore = () => {
set,
update,
setValue,
getState,
}
}