All files / src/services/zd-alert alert-replace.ts

100% Statements 18/18
100% Branches 5/5
100% Functions 4/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 4693x               93x 4x   4x     3x   3x 3x     3x 3x 3x   3x               5x 2x     5x 5x 5x       7x      
import { Alert, IAlert } from '../../components';
import { IAlertsManager } from './interfaces';
 
/**
 * Displays alerts using replace.
 * Only one alert can be visible at a time, and when a new alert is shown,
 * the previous one is instantly removed
 */
export class AlertReplace implements IAlertsManager {
	protected queue: IAlert[] = [];
 
	public visibleInstances: Alert[] = [];
 
	show(alert: IAlert): number {
		this.queue.push(alert);
 
		if ((this.visibleInstances.length === 0 || !this.visibleInstances[0].isVisible) && this.queue.length === 1) {
			this.display(alert);
		}
 
		this.visibleInstances[0].hide();
		this.remove(0);
		setTimeout(() => this.display(alert), 200);
 
		return 0;
	}
 
	/**
	 * Displays an alert
	 * @param alert Alert Structure
	 */
	protected display(alert: IAlert) {
		if (this.visibleInstances.length === 0) {
			this.visibleInstances.push(new Alert({ name: 'alert-instance', id: 0 }));
		}
 
		this.visibleInstances[0].assignAlertProperties(alert);
		this.visibleInstances[0].show();
		return 0;
	}
 
	remove(index: number): void {
		this.queue.splice(index, 1);
	}
}