import { ChangeDetectionStrategy, Component, ElementRef, EventEmitter, Input, OnChanges, Output, ViewChild, } from '@angular/core'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: 'adjust-value-bar-component', styleUrls: [ './adjust-value-bar.component.scss', ], templateUrl: './adjust-value-bar.component.template.pug', }) export class AdjustValueBarComponent implements OnChanges { @Input() public value = 50; @Input() public minValue = 0; @Input() public maxValue = 100; @Input() public buttonSteps = 1; @Input() public hideBackgroundToScrubber = false; @Input() public leftSideSvgHref = '#minus-icon'; @Input() public rightSideSvgHref = '#plus-icon'; @Input() public leftSideSvgClasses: string | string[]; @Input() public rightSideSvgClasses: string | string[]; @Output() public onChange = new EventEmitter(); @Output() public onLeftButtonClick = new EventEmitter(); @Output() public onRightButtonClick = new EventEmitter(); public percentOfTotal = 0; public isDragging = false; @ViewChild('adjustValueBarElement') public adjustValueBarElement: ElementRef; public ngOnChanges() { this.percentOfTotal = (this.value - this.minValue) / (this.maxValue - this.minValue); } public getTogglePercent() { return (this.percentOfTotal * 100) + '%'; } public emitNewValue() { const newValue = this.minValue + ( (this.maxValue - this.minValue) * this.percentOfTotal ); this.onChange.emit(newValue); } public updateTogglePosition(event: MouseEvent) { const boundingRect = this.adjustValueBarElement.nativeElement .getBoundingClientRect(); const xCoord = event.pageX - boundingRect.left; const elementTotalWidth = boundingRect.width; const percentOfTotal = Math.max( Math.min( xCoord / elementTotalWidth, 1, ), 0, ); this.percentOfTotal = percentOfTotal; this.emitNewValue(); } public dragStart() { this.isDragging = true; } public dragMove(event: MouseEvent) { if (this.isDragging) { this.updateTogglePosition(event); } } public dragEnd(event: MouseEvent) { this.dragMove(event); this.isDragging = false; } public handleLeftButtonClick() { if (this.onLeftButtonClick.observers.length > 0) { this.onLeftButtonClick.emit(); } else { this.adjustBarDown(); } } public handleRightButtonClick() { if (this.onRightButtonClick.observers.length > 0) { this.onRightButtonClick.emit(); } else { this.adjustBarUp(); } } public adjustBarDown() { this.percentOfTotal -= this._getAdjustStepsPercentage(); if (this.percentOfTotal < 0) { this.percentOfTotal = 0; } this.emitNewValue(); } public adjustBarUp() { this.percentOfTotal += this._getAdjustStepsPercentage(); if (this.percentOfTotal > 1) { this.percentOfTotal = 1; } this.emitNewValue(); } private _getAdjustStepsPercentage() { return this.buttonSteps / this.maxValue; } }