-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotification-manager.html
110 lines (92 loc) · 2.89 KB
/
notification-manager.html
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
102
103
104
105
106
107
108
109
110
<link rel="import" href="../polymer/polymer-element.html">
<link rel="import" href="notification-overlay.html">
<dom-module id="notification-manager">
<script>
class NotificationManager extends Polymer.Element {
static get is() {return 'notification-manager';}
static get properties() {
return {
disabled: {
type: Boolean,
value: false
},
__overlays: {
type: Array,
value: _ => {
return [];
}
}
};
}
static get observers() {
return [
'__positionizeOverlays(__overlays.length)'
];
}
constructor() {
super();
this.__rects = null;
this.__notificationsReceived = new Map();
this.notify = this.notify.bind(this);
}
connectedCallback() {
super.connectedCallback();
requestAnimationFrame(_ => {
this.__toggleListeners(true);
});
}
disconnectedCallback() {
this.__toggleListeners(false);
super.disconnectedCallback();
}
notify(event) {
if (event.defaultPrevented || this.disabled) {
return;
}
const type = event.type.replace('notify-', '');
const text = event.detail.text;
const duration = event.detail.duration || Infinity;
const key = text + type;
// Ignore the same notification until it is closed
if (this.__notificationsReceived.get(key)) {return;}
this.__notificationsReceived.set(key, true);
const overlay = document.createElement('notification-overlay')
overlay.type = type;
overlay.text = text;
overlay.duration = duration;
overlay.onDetach = _ => {
this.splice('__overlays', this.__overlays.indexOf(overlay), 1);
this.__notificationsReceived.delete(key);
};
this.push('__overlays', overlay);
overlay.open();
}
__toggleListeners(enable) {
const m = enable ? 'addEventListener' : 'removeEventListener';
document.body[m]('notify-error', this.notify);
document.body[m]('notify-warning', this.notify);
document.body[m]('notify-info', this.notify);
document.body[m]('notify-success', this.notify);
}
__positionizeOverlays() {
this._updateRects();
this.__overlays.forEach((overlay, index) => {
let top = 10;
if (index) {
let i = index;
while(i--) {
top += this.__rects[i].height + 4;
}
}
overlay.style.top = top + 'px';
});
}
_updateRects() {
this.__rects = this.__overlays.map(overlay => {
return overlay.getBoundingClientRect();
});
}
}
customElements.define(NotificationManager.is, NotificationManager);
</script>
</dom-module>