|
| 1 | +import { Controller } from '@hotwired/stimulus'; |
| 2 | + |
| 3 | +class default_1 extends Controller { |
| 4 | + constructor() { |
| 5 | + super(...arguments); |
| 6 | + this.eventSources = []; |
| 7 | + } |
| 8 | + initialize() { |
| 9 | + const errorMessages = []; |
| 10 | + if (!this.hasHubValue) |
| 11 | + errorMessages.push('A "hub" value pointing to the Mercure hub must be provided.'); |
| 12 | + if (!this.hasTopicsValue) |
| 13 | + errorMessages.push('A "topics" value must be provided.'); |
| 14 | + if (errorMessages.length) |
| 15 | + throw new Error(errorMessages.join(' ')); |
| 16 | + this.eventSources = this.topicsValue.map((topic) => { |
| 17 | + const u = new URL(this.hubValue); |
| 18 | + u.searchParams.append('topic', topic); |
| 19 | + return new EventSource(u); |
| 20 | + }); |
| 21 | + } |
| 22 | + connect() { |
| 23 | + if (!('Notification' in window)) { |
| 24 | + console.warn('This browser does not support desktop notifications.'); |
| 25 | + return; |
| 26 | + } |
| 27 | + this.eventSources.forEach((eventSource) => { |
| 28 | + eventSource.addEventListener('message', (event) => this._notify(JSON.parse(event.data).summary)); |
| 29 | + }); |
| 30 | + this._dispatchEvent('notify:connect', { eventSources: this.eventSources }); |
| 31 | + } |
| 32 | + disconnect() { |
| 33 | + this.eventSources.forEach((eventSource) => { |
| 34 | + eventSource.removeEventListener('message', this._notify); |
| 35 | + eventSource.close(); |
| 36 | + }); |
| 37 | + this.eventSources = []; |
| 38 | + } |
| 39 | + _notify(content) { |
| 40 | + if (!content) |
| 41 | + return; |
| 42 | + if ('granted' === Notification.permission) { |
| 43 | + new Notification(content); |
| 44 | + return; |
| 45 | + } |
| 46 | + if ('denied' !== Notification.permission) { |
| 47 | + Notification.requestPermission().then((permission) => { |
| 48 | + if ('granted' === permission) { |
| 49 | + new Notification(content); |
| 50 | + } |
| 51 | + }); |
| 52 | + } |
| 53 | + } |
| 54 | + _dispatchEvent(name, payload) { |
| 55 | + this.element.dispatchEvent(new CustomEvent(name, { detail: payload, bubbles: true })); |
| 56 | + } |
| 57 | +} |
| 58 | +default_1.values = { |
| 59 | + hub: String, |
| 60 | + topics: Array, |
| 61 | +}; |
| 62 | + |
| 63 | +export { default_1 as default }; |
0 commit comments