-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUi.notification.js
85 lines (74 loc) · 2.27 KB
/
Ui.notification.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
export class UiNotification extends CustomEvent {
static colors = { canvas: 'canvas', success: 'success', error: 'error', warning: 'warning' }
static type = 'whenNotifierNotificationReceived'
id = crypto.randomUUID()
#target = undefined
init
constructor() {
const detail = {
message: '',
color: UiNotification.colors.canvas,
closable: true, onClick: () => {},
autoHideDuration: 0
}
const init = { detail }
super(UiNotification.type, init);
this.init = init;
Reflect.ownKeys(UiNotification.prototype)
.filter(key => key !== 'constructor')
.forEach(method => this[method] = this[method].bind(this))
}
/** The notification text */
setMessage(message = '') {
this.init.detail.message = typeof message === 'string' ? message : message.toString();
return this
}
/** Mark as error */
error() {
this.init.detail.color = UiNotification.colors.error
return this
}
/** Mark as warning */
warning() {
this.init.detail.color = UiNotification.colors.warning
return this
}
/** Mark as success */
success() {
this.init.detail.color = UiNotification.colors.success
return this
}
/** Mark as Canvas color */
canvas() {
this.init.detail.color = UiNotification.colors.canvas
return this
}
/** A callback that will be triggered when the notification is clicked */
onClick(callback = () => {}) {
if (typeof callback !== 'function') { throw new Error('Invalid argument. Only functions are allowed'); }
this.init.detail.onClick = callback;
return this
}
hideCloseButton() {
this.init.detail.closable = false;
return this
}
/** This setting takes precedence over the Notifier */
setAutoHideDurationInMs(duration= 0) {
if (Number.isInteger(duration)) { this.init.detail.autoHideDuration = duration; }
return this
}
show() {
if (this.#target) { throw new Error('This notification has already been displayed'); }
document.dispatchEvent(this);
this.#target = document.getElementById(this.id);
return this
}
hide() {
if (!this.#target) { throw new Error('You cannot close a notification that has not yet been displayed'); }
this.#target.hidePopover();
this.#target.remove();
this.#target = undefined
return this
}
}