-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.js
64 lines (49 loc) · 1.65 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
"use strict";
const v4 = require('uuid/v4');
const EventTarget = require('event-target-shim');
const MacNotification = require('bindings')('Notification').MacNotification
const notifications = [];
module.exports = class Notification extends EventTarget {
constructor(title, options) {
super();
if (!title) throw new Error('Title is required');
Object.assign(this, { title }, options);
options = options || {};
options.id = options.id || v4();
options.body = options.body || '';
options.canReply = !!options.canReply;
const activated = (isReply, response, id) => {
const notification = this.getNotificationById(id);
if (!notification) return;
if (isReply) {
notification.dispatchEvent({ type: 'reply', response });
} else {
notification.dispatchEvent({ type: 'click' });
}
};
const args = Object.assign({ title, activated }, options);
this.notification = new MacNotification(args);
notifications.push(this);
}
close() {
if (!this.notification) return;
if (notifications && notifications.length > 0) {
const i = this.getNotificationIndexById(this.notification.id);
if (i) notifications.splice(i, 1);
}
this.notification.close();
this.notification = null;
this.dispatchEvent({ type: 'close' });
}
getNotificationById(id) {
return notifications.find((item) => this.compareItemWithId(item, id));
}
getNotificationIndexById(id) {
return notifications.findIndex((item) => this.compareItemWithId(item, id));
}
compareItemWithId(item, id) {
return item &&
item.notification &&
item.notification.id === id;
}
};