generated from spatie/package-skeleton-laravel
/
turbo-echo-stream-tag.js
48 lines (39 loc) · 1.29 KB
/
turbo-echo-stream-tag.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
import { connectStreamSource, disconnectStreamSource } from '@hotwired/turbo'
const subscribeTo = (type, channel) => {
if (type === 'presence') {
return window.Echo.join(channel)
}
if (type === 'private') {
return window.Echo.private(channel)
}
return window.Echo.channel(channel)
}
class TurboEchoStreamSourceElement extends HTMLElement {
async connectedCallback() {
connectStreamSource(this)
this.subscription = subscribeTo(this.type, this.channel)
.listen('.HotwiredLaravel\\TurboLaravel\\Events\\TurboStreamBroadcast', (e) => {
this.dispatchMessageEvent(e.message)
})
}
disconnectedCallback() {
disconnectStreamSource(this)
if (this.subscription) {
window.Echo.leave(this.channel)
this.subscription = null
}
}
dispatchMessageEvent(data) {
const event = new MessageEvent('message', { data })
return this.dispatchEvent(event)
}
get channel() {
return this.getAttribute('channel')
}
get type() {
return this.getAttribute('type') || 'private'
}
}
if (customElements.get('turbo-echo-stream-source') === undefined) {
customElements.define('turbo-echo-stream-source', TurboEchoStreamSourceElement)
}