-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathservice.ts
More file actions
460 lines (416 loc) · 15.2 KB
/
service.ts
File metadata and controls
460 lines (416 loc) · 15.2 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import { BreakpointObserver } from '@angular/cdk/layout';
import { TitleCasePipe } from '@angular/common';
import { ComponentRef, Injectable, Type, ViewContainerRef } from '@angular/core';
import { Title } from '@angular/platform-browser';
import * as _introJs from 'intro.js';
import { BehaviorSubject, Subject } from 'rxjs';
import { default as swal, SweetAlertType } from 'sweetalert2';
import { DropdownItem } from '../dropdown/dropdown-item.interface';
import { NotificationsService } from './../toast/simple-notifications/services/notifications.service';
import { PlexTitle } from './plex-title.interface';
import { WizardConfig } from './wizard-config.interface';
const introJs: any = _introJs;
@Injectable()
export class Plex {
public menu: DropdownItem[];
public loaderCount = 0;
public appStatus: Subject<any> = new Subject();
public userInfo: any;
public navbarVisible = true;
private navbarHost?: ViewContainerRef;
private navbarCmpRef?: ComponentRef<any>;
private pending?: { component: Type<any>; inputs?: any };
/**
* Cuenta los POST, PATCH, PUT, DELETE
*/
public networkCounter = new BehaviorSubject(0);
/**
* Contiene el título y breadcrumb que se muestran en el navbar
*/
public title: PlexTitle[];
constructor(
private titleService: Title,
private noficationService: NotificationsService,
private breakpointObserver: BreakpointObserver,
private titlecasePipe: TitleCasePipe
) {
}
collapse() {
this.menu = this.menu.map((item) => ({ ...item, collapsed: true }));
}
/**
* Actualiza el ménu de la aplicación
*
* @param {DropdownItem[]} menu Items del menú
*
* @memberof Plex
*/
updateMenu(menu: DropdownItem[]) {
this.menu = menu.map((item) => {
item.collapsed = true;
if (item.icon) {
const words = item.icon.split(' ');
if (words.length > 1) {
item.prefix = words[0];
item.icon = words[1].substr(4);
} else {
item.prefix = item.prefix || 'adi';
}
}
return item;
});
}
/**
* Actualiza el título del navegador y breadcrumb
*
* @param {string} title Título
*
* @memberof Plex
*/
updateTitle(title: string | PlexTitle[]) {
setTimeout(() => {
if (title) {
if (typeof title === 'string') {
this.title = [{ name: title }];
} else {
this.title = title as PlexTitle[];
}
const name = this.titlecasePipe.transform(this.title[this.title.length - 1].name);
this.titleService.setTitle(name);
} else {
this.titleService.setTitle('');
this.title = null;
}
});
}
/**
* Actualiza el estado de la aplicación en el navbar
*
* @param {*} status Objeto de estado
*
* @memberof Plex
*/
updateAppStatus(status: any) {
this.appStatus.next(status);
}
/**
* Actualiza la información del usuario actual
*
* @param {*} user Objeto con datos de usuario
*
* @memberof Plex
*/
updateUserInfo(user: any) {
this.userInfo = user;
}
/**
* TODO: Migrar para usar 1 sólo objeto con su type como param
* Muestra un diálogo de confirmación
*
* @param {string} content Texto
* @param {string} [title='Confirmación'] Título
* @returns {Promise<any>} Devuelve una promise se que resuelve con true/false cuando el diálogo se cierra
*
* @memberof Plex
*/
confirm(params: {
content: string; title: string; confirmButtonText: string; cancelButtonText: string; confirmButtonType?: string; cancelButtonType?: string; type?: string; customClass?: string;
});
confirm(content: string, title?: string, confirmButtonText?: string, cancelButtonText?: string, confirmButtonType?: string, cancelButtonType?: string, type?: string, customClass?: string);
confirm(content, title = 'Confirmación', confirmButtonText = 'Confirmar', cancelButtonText = 'Cancelar', confirmButtonType = 'success', cancelButtonType = 'danger', type = 'question', customClass = ''): Promise<any> {
let htmlContent;
// Para compatibilidad
if (typeof content === 'object') {
title = content.title || 'Confirmación';
htmlContent = content.content;
confirmButtonText = content.confirmButtonText || 'Confirmar';
cancelButtonText = content.cancelButtonText || 'Cancelar';
confirmButtonType = content.confirmButtonType || 'success';
cancelButtonType = content.cancelButtonType || 'danger';
type = content.type || 'question';
customClass = content.customClass || '';
} else {
htmlContent = content;
}
return new Promise((resolve, reject) => {
swal({
title,
html: htmlContent,
type: type as SweetAlertType,
showCancelButton: true,
confirmButtonText: confirmButtonText.toLocaleUpperCase(),
cancelButtonText: cancelButtonText.toLocaleUpperCase(),
buttonsStyling: false,
confirmButtonClass: `btn btn-${confirmButtonType}`,
cancelButtonClass: `btn btn-${cancelButtonType}`,
customClass
}).then(() => resolve(true))
.catch(() => resolve(false));
});
}
/**
* TODO: Migrar para usar 1 sólo objeto con su type como param
* Muestra un mensaje invasivo al usuario
*
* @param {string} type success, danger (error), warning, info
* @param {string} content Texto del mensaje
* @param {string} [title='Información'] Título
* @param {number} [timeOut=0] Tiempo en ms cuando se oculta el mensaje. Por default no se oculta.
*
* @memberof Plex
*/
info(type: String, content: String, title?: String, timeOut?: Number, confirmButtonText?: String, customClass?: string);
info(params: { type: String; content: String; title: String; confirmButtonText: String; timeOut?: Number; customClass?: string });
info(type, content = '', title = 'Información', timeOut = 0, confirmButtonText = 'Aceptar', customClass = '') {
let modalType;
// Para compatibilidad
if (typeof type === 'object') {
// TODO: Usar el tipo SweetAlertType?
modalType = type.type === 'danger' ? 'error' : type.type;
content = type.content || '';
title = type.title || 'Información';
confirmButtonText = type.confirmButtonText ? type.confirmButtonText.toLocaleUpperCase() : 'Aceptar';
timeOut = type.timeOut || 0;
customClass = type.customClass || '';
} else {
// TODO: Usar el tipo SweetAlertType?
if (type === 'danger') {
type = modalType = 'error';
}
modalType = type;
}
return swal({
title,
html: content,
type: modalType,
confirmButtonText,
buttonsStyling: false,
confirmButtonClass: `btn btn-${modalType === 'error' ? 'danger' : modalType}`,
timer: timeOut || null,
customClass
}).catch(swal.noop);
}
/**
* Muestra un mensaje no invasivo al usuario
*
* @param {string} type success, danger, warning, info
* @param {string} content Texto del mensaje
* @param {string} [title='Información'] Título
* @param {number} [timeOut=5000] Tiempo en ms cuando se oculta el mensaje
*
* @memberof Plex
*/
toast(type: string, content: string, title: string = 'Información', timeOut: number = 2500) {
const options = {
theClass: 'toast',
timeOut
};
switch (type) {
case 'success':
this.noficationService.success(title, content, options);
break;
case 'info':
this.noficationService.info(title, content, options);
break;
case 'danger':
this.noficationService.error(title, content, options);
break;
case 'warning':
this.noficationService.alert(title, content, options);
break;
}
}
/**
* Muestra el loader en el navbar de la aplicación.
*
* @memberof Plex
*/
showLoader() {
// Debe ir dentro de setTimeout por un bug de Angular2
setTimeout(() => {
this.loaderCount++;
});
}
/**
* Oculta el loader en el navbar de la aplicación.
*
* @memberof Plex
*/
hideLoader() {
// Debe ir dentro de setTimeout por un bug de Angular2
setTimeout(() => {
if (this.loaderCount > 0) {
this.loaderCount--;
}
});
}
/**
* Muestra al usuario una secuencia de imágenes y textos organizados en pasos
*
* @param {WizardConfig} config
* @returns {Promise<any>}
* @memberof Plex
*/
wizard(config: WizardConfig): Promise<any> {
// Cheque si el usuario no desea verlo más
if (!config.forceShow && localStorage[`wizard-${config.id}-${config.updatedOn.toISOString()}-hide`]) {
return null;
}
// Promise que devolverá la función
let resolve: any;
const promise = new Promise((res, rej) => {
resolve = res;
});
if (config.fullScreen) {
// Utiliza SweetAlert2
// Configura SweetAlert
let steps = [];
for (const i in config.steps) {
steps.push({
title: config.steps[i].title,
html: config.steps[i].content,
// Empty gif
imageUrl: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
imageClass: config.steps[i].imageClass,
imageWidth: 500,
imageHeight: 250,
confirmButtonText: 'Siguiente',
cancelButtonText: 'Cancelar',
showCancelButton: true
});
}
// En el primer paso el botón principal dice "Comenzar"
steps[0].confirmButtonText = 'Comenzar';
// En los pasos intermedios los botones dicen "Siguiente" y "Cancelar"
steps = steps.map(s => {
return { ...s, buttonsStyling: false, confirmButtonClass: 'btn btn-info', cancelButtonClass: 'btn btn-danger' };
});
// En el último paso el botón principal dice "Finalizar" y el botón "Cancelar" se oculta
const last = steps[steps.length - 1];
last.confirmButtonText = 'Finalizar';
last.showCancelButton = false;
// Crea el modal
let modal: Promise<any>;
if (steps.length === 1) {
modal = swal(steps[0]);
} else {
const progressSteps: number[] = [];
steps.forEach((element, index) => progressSteps.push(index + 1));
steps.forEach((element, value, index) => element.progressSteps = progressSteps);
modal = swal.queue(steps);
if (config.showNumbers) {
swal.showProgressSteps();
} else {
swal.hideProgressSteps();
}
}
// Crea la promise
modal.then((reason) => {
// No volver a mostrar
localStorage[`wizard-${config.id}-${config.updatedOn.toISOString()}-hide`] = true;
resolve(true);
}).catch((reason) => {
resolve(false);
});
} else {
// Utiliza Intro.js
const steps: introJs.Step[] = [];
for (const i in config.steps) {
steps.push({
intro: (config.steps[i].title ? `<h3>${config.steps[i].title}</h3>` : '') + config.steps[i].content,
element: document.querySelector(`[plex-wizard-ref="${i}"]`),
position: 'right'
});
}
const intro = introJs();
intro.setOptions({
nextLabel: 'Siguiente',
prevLabel: 'Volver',
skipLabel: 'Cerrar',
doneLabel: 'Finalizar',
showProgress: true,
showBullets: false,
showStepNumbers: config.showNumbers,
steps
});
intro.start()
.oncomplete(() => {
// No volver a mostrar
localStorage[`wizard-${config.id}-${config.updatedOn.toISOString()}-hide`] = true;
resolve(true);
})
.onexit(() => resolve(false));
}
return promise;
}
/**
* Navbar dinamico
*/
private viewContainerRef: ViewContainerRef;
setViewContainerRef(viewContainerRef) {
this.viewContainerRef = viewContainerRef;
}
setNavbarHost(vcr: ViewContainerRef) {
this.navbarHost = vcr;
if (this.pending) {
const p = this.pending;
this.pending = undefined;
this.setNavbarItem(p.component, p.inputs);
}
}
/**
* Instancia una componente y la injecta en la parte dinamica del plex-app
* @param componentRef
* @param inputs
*/
setNavbarItem<T>(component: Type<T>, inputs?: Partial<T>) {
if (!this.navbarHost) {
this.pending = { component, inputs };
return; // evita reintentos infinitos
}
this.navbarHost.clear();
const cmpRef = this.navbarHost.createComponent(component);
if (inputs) { Object.assign(cmpRef.instance, inputs); }
cmpRef.changeDetectorRef.detectChanges();
this.navbarCmpRef = cmpRef;
}
clearNavbarItem() {
this.navbarCmpRef?.destroy();
this.navbarCmpRef = undefined;
this.navbarHost?.clear();
}
/**
* Borra el item dinamico agregado.
*/
clearNavbar() {
this.viewContainerRef?.clear();
}
/**
* Esconde la barra de navegación.
* Sólo para pantalla de login
*/
toggleHideNavBar() {
this.navbarVisible = !this.navbarVisible;
return this.navbarVisible;
}
navVisible(visible: boolean) {
this.navbarVisible = visible;
return this.navbarVisible;
}
/**
* Determina si estamos en un dispositivo mobile.
*/
isMobile() {
return this.breakpointObserver.isMatched('(max-width: 599px)');
}
updateNetwork(action: 'inc' | 'dec') {
const count = this.networkCounter.getValue();
if (action === 'inc') {
this.networkCounter.next(count + 1);
} else {
if (count > 0) {
this.networkCounter.next(count - 1);
}
}
}
}