-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifier.js
312 lines (276 loc) · 11.5 KB
/
notifier.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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
/**
* @author Wiktor Olejniczak <myfrom.13th@gmail.com>
* @license MIT
*
* @module notifier
*/
if (!document) throw new Error('Notifier can\'t run without document object.');
// Read global options to local const
const options = window.NotifierOptions || {};
/**
* Elements that are required for full Notifier functionality
*
* @constant
*/
const elementsToImport = [
'@polymer/paper-dialog/paper-dialog.js', '@polymer/paper-dialog-scrollable/paper-dialog-scrollable.js',
'@polymer/paper-button/paper-button.js', '@polymer/paper-toast/paper-toast.js',
'web-animations-js/web-animations.min.js', '@polymer/neon-animation/animations/fade-in-animation.js',
'@polymer/neon-animation/animations/fade-out-animation.js', '@polymer/neon-animation/animations/slide-from-bottom-animation.js',
'@polymer/neon-animation/animations/slide-down-animation.js'
]
const loadingImports = [];
if (!options.elementsImported) {
elementsToImport.forEach(url => {
loadingImports.push(import(url));
});
}
if (!options.stylesLoaded)
loadingImports.push(import('./styles-loader.js'));
const mobileMediaQuery = options.mobileMediaQuery ||
['(orientation: landscape) and (max-width: 960px)',
'(orientation: portrait) and (max-width: 600px)'];
/**
* Main class. It contains all functions and manages paper-dialog and paper-toast elements currently on the page.
* You don't have to worry about multiple instances
*
* @class
* @demo demo/demo.html
*/
class Notifier {
/**
* Get toast element or create one if needed
*
* @returns {Element} Toast element
* @throws This will throw if paper-toast element isn't imported
*/
get toast() {
if (!customElements.get('paper-toast'))
throw new Error('You must import paper-toast for Notifier.showToast functionality to work');
if (this._toast)
return this._toast;
else {
const toastSearchRes = document.querySelector('paper-toast.notifier');
if (toastSearchRes) {
return this._toast = toastSearchRes
} else {
const toastEl = document.createElement('paper-toast');
document.body.appendChild(toastEl);
return this._toast = toastEl;
}
}
}
/**
* Get dialog element or create one if needed
*
* @returns {Element} Dialog element
* @throws This will throw if paper-dialog element isn't imported
*/
get dialog() {
if (!customElements.get('paper-dialog'))
throw new Error('You must import paper-dialog for Notifier.showDialog functionality to work');
if (this._dialog)
return this._dialog;
else {
const dialogSearchRes = document.querySelector('paper-dialog.notifier');
if (dialogSearchRes) {
return this._dialog = dialogSearchRes
} else {
const dialogEl = document.createElement('paper-dialog');
document.body.appendChild(dialogEl);
return this._dialog = dialogEl;
}
}
}
/**
* @throws This will throw if run in non-browser environment
*/
constructor() {
// Check for window object
if (typeof window === 'undefined')
throw new Error('Notifier can\'t be run in non-browser environment');
// Add shortcut for layout
window.addEventListener('resize', e => {
this._mobile = window.matchMedia(mobileMediaQuery).matches;
});
this._mobile = window.matchMedia(mobileMediaQuery).matches;
// Define Material animation for dialogs
// This is a part related to neon-animation and will be removed in future
/** @constant */
this.MATERIAL_DIALOG_ANIMATION = {
'entry': [
{
'name': 'slide-from-bottom-animation',
'node': this.dialog,
'timing': {
'duration': 160,
'easing': 'ease-out'
}
},
{
'name': 'fade-in-animation',
'node': this.dialog,
'timing': {
'duration': 160,
'easing': 'ease-out'
}
}
],
'exit': [
{
'name': 'slide-down-animation',
'node': this.dialog,
'timing': {
'duration': 160,
'easing': 'ease-in'
}
},
{
'name': 'fade-out-animation',
'node': this.dialog,
'timing': {
'duration': 160,
'easing': 'ease-in'
}
}
]
}
}
/**
* Opens a toast with provided message
* @param {string} msg Message to be shown
* @param {object} [options]
* @param {string} [options.btnText] Text on paper button, leave empty to not show
* @param {EventListener} [options.btnFunction] Function to be called when button is pressed
* @param {number} [options.duration = 3000] Time in milliseconds before dialog will close, set to 0 to only allow manual close
* @param {object} [options.attributes] Attributes to be passed down to the dialog, { attr: value }
* @throws This will throw if `msg` is empty
*/
async showToast(msg, options = {}) {
await Promise.all(loadingImports);
if (!msg) throw new Error('Provided empty toast message');
if (!options.attributes) options.attributes = [];
const toast = this.toast;
if (toast.opened) toast.close();
toast.innerHTML = options.btnText ? `<paper-button>${options.btnText}</paper-button>` : null;
for (let i = 0; i < toast.attributes.length; i++) {
const attrName = toast.attributes[i].name;
if (options.attributes[attrName])
toast.setAttribute(attrName, options.attributes[attrName]);
else
toast.removeAttribute(attrName);
}
Object.keys(options.attributes).forEach(attrName => {
toast.setAttribute(attrName, options.attributes[attrName]);
});
toast.classList.toggle('fit-bottom', this._mobile);
toast.text = msg;
toast.duration = String(typeof options.duration).toLowerCase() === 'number' ? options.duration : 3000;
if (options.btnText && options.btnFunction) {
toast.querySelector('paper-button').addEventListener('tap', options.btnFunction);
}
if (options.btnText) {
const btnWidth = toast.querySelector('paper-button').getBoundingClientRect().width;
toast.style.paddingRight = btnWidth + 48 + 'px';
}
toast.classList.add('notifier');
toast.open();
}
/**
* Opens a dialog
* @param {string} header Header of the dialog
* @param {string} content Content of the dialog, must be a string with all tags, including bottom buttons
* @param {object} [options]
* @param {object} [options.attributes] Attributes to be passed down to the dialog, { attr: value }
* @param {boolean} [options.noBackdrop] Don't show backdrop behind dialog
* @param {boolean} [options.formatted=false] If true,`content` will be put directly into element, otherwise put inside `<paper-scrollable-dialog>`
* @param {Element} [options.target=window] Target element on which dialog will be appended
* @param {function} [options.beforeClose] Function to be run after accepting but before removing the dialog, if set promise will resolve with it's resoluts
* @param {object} [options.animationConfig] animationConfig on dialog element, if unset will default to Material animation
* @returns {Promise} A promise that will resolve if dialog was accepted or reject with `error: false` when cancelled
*/
showDialog(header, content, options = {}) {
return new Promise((resolve, reject) => {
Promise.all(loadingImports).then(() => {
if (!options.attributes) options.attributes = [];
const dialog = this.dialog;
if (dialog.opened) dialog.close();
const target = options.target || document.body;
if (dialog.parentElement !== target) target.appendChild(dialog);
const innerHTML =
(header ? `<h2>${header}</h2>` : '') +
(options.formatted ? content : `<paper-dialog-scrollable>${content}</paper-dialog-scrollable>`);
if ('ShadyDOM' in window && ShadyDOM.inUse) {
const template = document.createElement('template');
template.innerHTML = innerHTML;
dialog.innerHTML = '';
dialog.appendChild(document.importNode(template.content, true));
} else
dialog.innerHTML = innerHTML;
for (let i = 0; i < dialog.attributes.length; i++) {
const attrName = dialog.attributes[i].name;
if (attrName === 'animation-config' && dialog.animationConfig === this.MATERIAL_DIALOG_ANIMATION)
continue;
else if (options.attributes[attrName])
dialog.setAttribute(attrName, options.attributes[attrName]);
else
dialog.removeAttribute(attrName);
}
Object.keys(options.attributes).forEach(attrName => {
dialog.setAttribute(attrName, options.attributes[attrName]);
});
if (!dialog.animationConfig) {
dialog.animationConfig = this.MATERIAL_DIALOG_ANIMATION;
}
if (!dialog.withBackdrop && !options.noBackdrop) {
dialog.withBackdrop = true;
}
const closedHandler = e => {
if (e.target !== dialog) return;
if (e.detail.confirmed)
resolve(options.beforeClose && options.beforeClose(e));
else
reject({ error: false });
dialog.removeEventListener('iron-overlay-closed', closedHandler);
};
dialog.addEventListener('iron-overlay-closed', closedHandler);
dialog.classList.add('notifier');
dialog.open();
});
});
}
/**
* Predefined dialog with a yes/no question
* @param {String} [msg='Are you sure?'] Header text
* @param {Object} [options]
* @param {String} [options.innerMsg] Massage in dialog body
* @param {String} [options.cancelText='No'] Text to show in cancel button
* @param {String} [options.acceptText='Yes'] Text to show in accept button
* @param {object} [options.attributes] Attributes to be passed down to the dialog, { attr: value }
* @param {boolean} [options.noBackdrop] Don't show backdrop behind dialog
* @param {boolean} [options.formatted=false] If true,`content` will be put directly into element, otherwise put inside `<paper-scrollable-dialog>`
* @param {Element} [options.target=window] Target element on which dialog will be appended
* @param {function} [options.beforeClose] Function to be run after accepting but before removing the dialog, if set returned promise will resolve with it's results
* @param {object} [options.animationConfig] animationConfig on dialog element, if unset will default to Material animation
* @returns {Promise} A promise that will resolve if dialog was accepted or reject with `error: false` when cancelled
*/
askDialog(msg = 'Are you sure?', options = {}) {
const innerMsg = options.innerMsg || '',
cancelText = options.cancelText || 'No',
acceptText = options.acceptText || 'Yes',
content = `
<paper-dialog-scrollable>
${innerMsg}
</paper-dialog-scrollable>
<div class="buttons">
<paper-button dialog-dismiss>${cancelText}</paper-button>
<paper-button dialog-confirm autofocus>${acceptText}</paper-button>
</div>
`;
options.formatted = true;
return this.showDialog(msg, content, options);
}
}
/** Initialised Notifier class */
export default new Notifier();
export { elementsToImport };