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