Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {
- AfterViewInit,
- Component,
- ElementRef,
- EventEmitter,
- Input,
- OnDestroy,
- OnInit,
- Output,
- ViewChild
- } from '@angular/core';
- import {Subscription} from "rxjs/Subscription";
- import {Observable} from "rxjs/Observable";
- import 'rxjs/add/observable/fromEvent';
- import 'rxjs/add/operator/do';
- import 'rxjs/add/operator/startWith';
- import 'rxjs/add/operator/takeUntil';
- import 'rxjs/add/operator/take';
- import 'rxjs/add/operator/mergeMap';
- import {clamp} from 'lodash';
- @Component({
- selector: 'app-slider',
- templateUrl: './slider.component.html',
- styleUrls: ['./slider.component.scss']
- })
- export class SliderComponent implements OnInit, AfterViewInit, OnDestroy {
- @Input() label: string = '';
- @Input() min = 0;
- @Input() max = 1;
- @Input() value = 0;
- @Output() valueChange = new EventEmitter<number>();
- @ViewChild('slider') slider: ElementRef;
- cursorPt: SVGPoint = {x: 0, y: 0} as any;
- handle: Subscription;
- pt: SVGPoint;
- constructor() {
- }
- ngOnInit() {
- const scaledValue = (this.value - this.min) / (this.max - this.min);
- this.cursorPt = {x: 0, y: 128 - (scaledValue * 128)} as any;
- }
- ngAfterViewInit() {
- this.pt = this.slider.nativeElement.createSVGPoint();
- const down = Observable.fromEvent(this.slider.nativeElement, 'mousedown')
- .do((md: MouseEvent) => md.preventDefault());
- const move = Observable.fromEvent(document, 'mousemove')
- .do((mm: MouseEvent) => mm.preventDefault());
- const up = Observable.fromEvent(document, 'mouseup')
- .do((mu: MouseEvent) => mu.preventDefault());
- const drag = down.mergeMap((md: MouseEvent) => {
- return move.startWith(md).takeUntil(up.take(1));
- });
- this.handle = drag
- .subscribe((md: MouseEvent) => {
- this.pt.x = md.clientX;
- this.pt.y = md.clientY;
- this.cursorPt = this.pt.matrixTransform(
- this.slider.nativeElement.getScreenCTM().inverse());
- this.cursorPt.y = clamp(this.cursorPt.y, 0, 128);
- const normalValue = 1 - (this.cursorPt.y / 128);
- const scaledValue = (normalValue * (this.max - this.min)) + this.min;
- this.valueChange.emit(scaledValue);
- });
- }
- ngOnDestroy() {
- this.handle.unsubscribe();
- }
- }
Add Comment
Please, Sign In to add comment