feature: sync multiple tabs using local storage
This commit is contained in:
parent
61985990d0
commit
e28b378e07
|
@ -4,8 +4,6 @@
|
|||
import { configStore } from '../stores'
|
||||
|
||||
$: showTrackingPanel = $configStore.track === undefined
|
||||
|
||||
configStore.subscribe(console.log)
|
||||
</script>
|
||||
|
||||
{#if showTrackingPanel}
|
||||
|
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,5 @@
|
|||
import storageListener from './storageListener'
|
||||
|
||||
export {
|
||||
storageListener,
|
||||
}
|
|
@ -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()
|
|
@ -6,24 +6,18 @@ const createConfigStore = () => {
|
|||
const { subscribe, set, update } = writable(state)
|
||||
|
||||
const setValue = (key, value) => {
|
||||
update((prevState) => {
|
||||
const nextState = {
|
||||
...prevState,
|
||||
[key]: value,
|
||||
}
|
||||
|
||||
localStorage.setItem('fb-to-ical-config', JSON.stringify(nextState))
|
||||
|
||||
return nextState
|
||||
})
|
||||
update((prevState) => ({ ...prevState, [key]: value }))
|
||||
}
|
||||
|
||||
const getState = () => state
|
||||
|
||||
return {
|
||||
...state,
|
||||
subscribe,
|
||||
set,
|
||||
update,
|
||||
setValue,
|
||||
getState,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue