Guest User

Untitled

a guest
Nov 19th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import {
  2. AfterViewInit,
  3. Component,
  4. ElementRef,
  5. EventEmitter,
  6. Input,
  7. OnDestroy,
  8. OnInit,
  9. Output,
  10. ViewChild
  11. } from '@angular/core';
  12.  
  13. import {Subscription} from "rxjs/Subscription";
  14. import {Observable} from "rxjs/Observable";
  15. import 'rxjs/add/observable/fromEvent';
  16. import 'rxjs/add/operator/do';
  17. import 'rxjs/add/operator/startWith';
  18. import 'rxjs/add/operator/takeUntil';
  19. import 'rxjs/add/operator/take';
  20. import 'rxjs/add/operator/mergeMap';
  21.  
  22. import {clamp} from 'lodash';
  23.  
  24. @Component({
  25. selector: 'app-slider',
  26. templateUrl: './slider.component.html',
  27. styleUrls: ['./slider.component.scss']
  28. })
  29. export class SliderComponent implements OnInit, AfterViewInit, OnDestroy {
  30.  
  31. @Input() label: string = '';
  32. @Input() min = 0;
  33. @Input() max = 1;
  34. @Input() value = 0;
  35. @Output() valueChange = new EventEmitter<number>();
  36.  
  37. @ViewChild('slider') slider: ElementRef;
  38. cursorPt: SVGPoint = {x: 0, y: 0} as any;
  39. handle: Subscription;
  40. pt: SVGPoint;
  41.  
  42. constructor() {
  43. }
  44.  
  45. ngOnInit() {
  46. const scaledValue = (this.value - this.min) / (this.max - this.min);
  47. this.cursorPt = {x: 0, y: 128 - (scaledValue * 128)} as any;
  48. }
  49.  
  50. ngAfterViewInit() {
  51. this.pt = this.slider.nativeElement.createSVGPoint();
  52.  
  53. const down = Observable.fromEvent(this.slider.nativeElement, 'mousedown')
  54. .do((md: MouseEvent) => md.preventDefault());
  55. const move = Observable.fromEvent(document, 'mousemove')
  56. .do((mm: MouseEvent) => mm.preventDefault());
  57. const up = Observable.fromEvent(document, 'mouseup')
  58. .do((mu: MouseEvent) => mu.preventDefault());
  59.  
  60. const drag = down.mergeMap((md: MouseEvent) => {
  61. return move.startWith(md).takeUntil(up.take(1));
  62. });
  63.  
  64. this.handle = drag
  65. .subscribe((md: MouseEvent) => {
  66. this.pt.x = md.clientX;
  67. this.pt.y = md.clientY;
  68. this.cursorPt = this.pt.matrixTransform(
  69. this.slider.nativeElement.getScreenCTM().inverse());
  70. this.cursorPt.y = clamp(this.cursorPt.y, 0, 128);
  71.  
  72. const normalValue = 1 - (this.cursorPt.y / 128);
  73. const scaledValue = (normalValue * (this.max - this.min)) + this.min;
  74. this.valueChange.emit(scaledValue);
  75. });
  76. }
  77.  
  78. ngOnDestroy() {
  79. this.handle.unsubscribe();
  80. }
  81. }
Add Comment
Please, Sign In to add comment