-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
101 lines (86 loc) · 2.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { ref, isRef, watch, computed } from 'vue'
import vuex from 'vuex'
let { useStore } = vuex
export function useSubscription(channels, options = {}) {
let store = options.store || useStore()
let debounce = options.debounce || 0
let isSubscribing = ref(true)
if (!isRef(channels)) {
channels = ref(channels)
}
let subscriptions = computed(() => unifyChannelsObject(channels.value))
let id = computed(() => subscriptionsId(subscriptions.value))
watch(
id,
(newId, oldId, onInvalidate) => {
let oldSubscriptions = subscriptions.value
let ignoreResponse = false
let timeout
function resetTimeout() {
clearTimeout(timeout)
timeout = null
}
if (debounce > 0) {
timeout = setTimeout(() => {
isSubscribing.value = true
}, debounce)
} else {
isSubscribing.value = true
}
subscribe(store, subscriptions.value).then(() => {
if (timeout) resetTimeout(timeout)
if (!ignoreResponse) {
isSubscribing.value = false
}
})
onInvalidate(() => {
ignoreResponse = true
unsubscribe(store, oldSubscriptions)
if (timeout) resetTimeout(timeout)
})
},
{ immediate: true }
)
return isSubscribing
}
function unifyChannelsObject(channels) {
return channels.map(i => {
let subscription = typeof i === 'string' ? { channel: i } : i
return [subscription, JSON.stringify(subscription)]
})
}
function subscriptionsId(subscriptions) {
return subscriptions
.map(i => i[1])
.sort()
.join(' ')
}
function subscribe(store, subscriptions) {
if (!store.subscriptions) store.subscriptions = {}
if (!store.subscribers) store.subscribers = {}
return Promise.all(
subscriptions.map(i => {
let subscription = i[0]
let json = i[1]
if (!store.subscribers[json]) store.subscribers[json] = 0
store.subscribers[json] += 1
if (store.subscribers[json] === 1) {
let action = { ...subscription, type: 'logux/subscribe' }
store.subscriptions[json] = store.commit.sync(action)
}
return store.subscriptions[json]
})
)
}
function unsubscribe(store, subscriptions) {
subscriptions.forEach(i => {
let subscription = i[0]
let json = i[1]
store.subscribers[json] -= 1
if (store.subscribers[json] === 0) {
let action = { ...subscription, type: 'logux/unsubscribe' }
store.log.add(action, { sync: true })
delete store.subscriptions[json]
}
})
}