-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathKnob.js
1077 lines (863 loc) · 33.4 KB
/
Knob.js
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let Knob;
(function(undefined) {
/**
* Default
* Orientation
* 90
* 180 + 0
* 270
**/
Knob = function(inputEl, callback) {
this.__callback = callback;
this.element = inputEl;
if(!this.element) {
throw new Error('No input element specified for knob.');
}
/*
<input id="prog-knob"
type="range"
name="progressive-knob"
min="1" max="10"
data-angle-start="-400"
data-angle-end="360"
data-angle-value-ratio="0.1"
data-angle-slide-ratio="1"
data-gesture-spin-enabled="true"
data-gesture-slidex-enabled="true"
data-gesture-slidey-enabled="true"
data-gesture-scroll-enabled="true"
data-center-offset-x="0"
data-center-offset-y="0"
data-indicator-auto-rotate="false"
data-indicator-auto-position="false"
data-indicator-start-angle="0"
data-indicator-radius="0"
data-sprite-width="67"
data-sprite-height="67"
data-sprite-count="1"
data-sprite-direction="ccw"
data-sprite-start-angle="0"
data-sprite-separation-angle="3"
data-sprite-separation-gap="0"
/>
*/
// parse the attributes from the input element
const options = {}
if (inputEl.hasAttribute('min')) {
options.valueMin = parseFloat(inputEl.getAttribute('min'));
}
if (inputEl.hasAttribute('max')) {
options.valueMax = parseFloat(inputEl.getAttribute('max'));
}
if (inputEl.hasAttribute('value')) {
options.value = parseFloat(inputEl.getAttribute('value'));
}
if (inputEl.hasAttribute('data-angle-start')) {
options.angleStart = parseFloat(inputEl.getAttribute('data-angle-start'));
}
if (inputEl.hasAttribute('data-angle-end')) {
options.angleEnd = parseFloat(inputEl.getAttribute('data-angle-end'));
}
if (inputEl.hasAttribute('data-angle-value-ratio')) {
options.angleValueRatio = parseFloat(inputEl.getAttribute('data-angle-value-ratio'));
}
if (inputEl.hasAttribute('data-angle-slide-ratio')) {
options.angleSlideRatio = parseFloat(inputEl.getAttribute('data-angle-slide-ratio'));
}
if (inputEl.hasAttribute('data-angle-scroll-ratio')) {
options.angleScrollRatio = parseFloat(inputEl.getAttribute('data-angle-scroll-ratio'));
}
if (inputEl.hasAttribute('data-gesture-spin-enabled')) {
options.gestureSpinEnabled = parseBool(inputEl.getAttribute('data-gesture-spin-enabled'));
}
if (inputEl.hasAttribute('data-gesture-slidex-enabled')) {
options.gestureSlideXEnabled = parseBool(inputEl.getAttribute('data-gesture-slidex-enabled'));
}
if (inputEl.hasAttribute('data-gesture-slidey-enabled')) {
options.gestureSlideYEnabled = parseBool(inputEl.getAttribute('data-gesture-slidey-enabled'));
}
if (inputEl.hasAttribute('data-gesture-scroll-enabled')) {
options.gestureScrollEnabled = parseBool(inputEl.getAttribute('data-gesture-scroll-enabled'));
}
if (inputEl.hasAttribute('data-center-offset-x')) {
options.centerOffsetX = parseFloat(inputEl.getAttribute('data-center-offset-x'));
}
if (inputEl.hasAttribute('data-center-offset-y')) {
options.centerOffsetY = parseFloat(inputEl.getAttribute('data-center-offset-y'));
}
if (inputEl.hasAttribute('data-indicator-auto-rotate')) {
options.indicatorAutoRotate = parseBool(inputEl.getAttribute('data-indicator-auto-rotate'));
}
if (inputEl.hasAttribute('data-indicator-auto-position')) {
options.indicatorAutoPosition = parseBool(inputEl.getAttribute('data-indicator-auto-position'));
}
if (inputEl.hasAttribute('data-indicator-start-angle')) {
options.indicatorStartAngle = parseFloat(inputEl.getAttribute('data-indicator-start-angle'));
}
if (inputEl.hasAttribute('data-indicator-radius')) {
options.indicatorRadius = parseFloat(inputEl.getAttribute('data-indicator-radius'));
}
if (inputEl.hasAttribute('data-sprite-width')) {
options.spriteWidth = parseFloat(inputEl.getAttribute('data-sprite-width'));
}
if (inputEl.hasAttribute('data-sprite-height')) {
options.spriteHeight = parseFloat(inputEl.getAttribute('data-sprite-height'));
}
if (inputEl.hasAttribute('data-sprite-count')) {
options.spriteCount = parseInt(inputEl.getAttribute('data-sprite-count'), 10);
}
if (inputEl.hasAttribute('data-sprite-direction')) {
options.spriteDirection = parseDirection(inputEl.getAttribute('data-sprite-direction'));
}
if (inputEl.hasAttribute('data-sprite-start-angle')) {
options.spriteStartAngle = parseFloat(inputEl.getAttribute('data-sprite-start-angle'));
}
if (inputEl.hasAttribute('data-sprite-separation-angle')) {
options.spriteSeparationAngle = parseFloat(inputEl.getAttribute('data-sprite-separation-angle'));
}
if (inputEl.hasAttribute('data-sprite-separation-gap')) {
options.spriteSeparationGap = parseFloat(inputEl.getAttribute('data-sprite-separation-gap'));
}
this.options = {
/** Enable turning of the knob in a circular motion */
gestureSpinEnabled: true,
/** Enable turning of the knob in a horizontal sliding motion */
gestureSlideXEnabled: true,
/** Enable turning of the knob with a vertical sliding motion */
gestureSlideYEnabled: true,
/** Enable turning of the knob with a mouse scroll */
gestureScrollEnabled: true,
/** During spin gestures, point the indicator to the finger as it spins */
// followFinger: true,
/** Setting this will prevent the knob from turning below this angle */
angleStart: Number.NEGATIVE_INFINITY,
/** Setting this will prevent the knob from turning past this angle */
angleEnd: Number.POSITIVE_INFINITY,
/** The minimum value the knob can go down to */
valueMin: 0, // default for html sliders
/** The maximum value the knob can go up to */
valueMax: 100, // default for html sliders
// valueMax: 11, // This one goes to eleven.
/** The current value of the knob */
value: 0,
/**
* How much the value increases per degree turned.
* Only used if both angleStart/End and valueMax/valueMin
* are NOT +/- Infinity.
**/
angleValueRatio: 0.1,
/** How much the angle increases per pixel moved during the slide */
angleSlideRatio: 2.0,
/** How much the angle increases per pixel moved during the scroll */
angleScrollRatio: 0.5,
/** Number of pixels the rotational center of the knob is shifted from element's center along the X axis */
centerOffsetX: 0,
/** Number of pixels the rotational center of the knob is shifted from element's center along the Y axis */
centerOffsetY: 0,
/*
---------------------------------------------------------------------------
INDICATOR OPTIONS
---------------------------------------------------------------------------
*/
/** Angle the indicator is at when first rendered */
indicatorStartAngle: 0,
/** Automatically rotate the indicator based on the angle */
indicatorAutoRotate: false,
/** Automatically position the indicator around the rotational center */
indicatorAutoPosition: false,
/**
* The distance of the indicator from the rotational center.
* Only used when indicatorAutoPosition is true.
**/
indicatorRadius: 0,
/*
---------------------------------------------------------------------------
SPRITE OPTIONS
---------------------------------------------------------------------------
*/
/** Width of the image or individual images in the sprite */
spriteWidth: 67, /* (default to Apple's standard size in GarageBand) */
/** Height of the image or individual images in the sprite */
spriteHeight: 67, /* (default to Apple's standard size in GarageBand) */
/** Number of images in the sprite */
spriteCount: 1,
/** Which way the images turn when viewing left to right in the sprite */
spriteDirection: 'ccw', /* cw = clockwise, ccw = counter-clockwise */
/** Angle of the 1st sprite image relative to the default orientation */
spriteStartAngle: 0,
/** Number of degrees turned between each image in the sprite */
spriteSeparationAngle: 3,
/** The thickness of the gap surrounding images in the sprite */
spriteSeparationGap: 0,
};
for (const key in options) {
if(this.options[key] !== undefined)
this.options[key] = options[key];
}
if(this.options.valueMin > this.options.valueMax) {
throw new Error("valueMin must be less than valueMax");
}
this.val(this.options.value);
};
/*
---------------------------------------------------------------------------
PRIVATE FUNCTIONS
---------------------------------------------------------------------------
*/
/**
* Parse input to a boolean.
*
* @param boolStr {String} True or false
*
* @return {Boolean}
**/
function parseBool(boolStr) {
return boolStr && boolStr.toLowerCase() == 'true';
};
/**
* Parse input to a turning direction.
*
* @param dirStr {String} Turning direction
*
* @return {String} 'cw' or 'ccw' (clockwise or counter-clockwise)
**/
function parseDirection(dirStr) {
if(dirStr) {
dirStr = dirStr.toLowerCase();
if(dirStr == 'cw' || dirStr == 'ccw') {
return dirStr;
}
}
return undefined;
};
/**
* Convenience function to map a variable from one coordinate space
* to another.
* Thanks to http://www.trembl.org/codec/737/
*
* @param value {Number} value
* @param istart {Number} Lower boundary of first coordinate space
* @param istop {Number} Higher boundary of first coordinate space
* @param ostart {Number} Lower boundary of second coordinate space
* @param ostop {Number} Higher boundary of second coordinate space
*
* @return {Number} The value mapped from the first coordinate space
* to the latter.
*/
function map(value, istart, istop, ostart, ostop) {
return ostart + (ostop - ostart) * ((value - istart)/(istop - istart));
}
/**
* Convenience function to constrain a value between two numbers.
*
* @param value {Number} value
* @param low {Number} Lower number boundary
* @param high {Number} Higher number boundary
*
* @return {Number} A number from low to high.
*/
function constrain(value, low, high) {
if(low > high) {
const tmp = low;
low = high;
high = tmp;
}
return (value < low) ? low : ((value > high) ? high : value);
};
/**
* Convert degrees to radians.
*
* @param degrees {Number} Angle in degrees
*
* @return {Number} Angle in radians
**/
function toRadians(degrees) {
return degrees*(Math.PI/180);
};
/**
* Convert radians to degrees.
*
* @param radians {Number} Angle in radians
*
* @return {Number} Angle in degrees
**/
function toDegrees(radians) {
return radians*(180/Math.PI);
};
/**
* Get the smallest distance between two angles.
*
* @param angle1 {Number} First angle in degrees
* @param angle2 {Number} Second angle in degrees
*
* @return {Number} Angle distance in degrees (0 >= angle <= 180)
**/
function smallestAngleDistance(angle1, angle2) {
const d = Math.abs(angle1 - angle2) % 360;
return d > 180 ? 360 - d : d;
}
/**
* Get the raw distance between two angles.
*
* @param angle1 {Number} First angle in degrees
* @param angle2 {Number} Second angle in degrees
*
* @return {Number} Angle distance in degrees
**/
function angleDistance(angle1, angle2) {
return angle1 % 360 - angle2 % 360;
}
/**
* Get the angle from x and y coordinates using
* the specified origin.
*
* @param x {Number}
* @param y {Number}
*
* @return {Number} Angle distance in degrees
**/
function angleFromCoord(x, y, originX, originY) {
const ny = originY - y,
nx = x - originX;
// http://stackoverflow.com/questions/1311049/how-to-map-atan2-to-degrees-0-360
return toDegrees(Math.atan2(-ny,-nx)+Math.PI);
}
function pointDistance(x0, y0, x1, y1) {
return Math.sqrt((x0 -= x1) * x0 + (y0 -= y1) * y0);
}
/**
* Returns true if angle is increasing.
* An angle is increasing if going from a lower
* number to a higher number or if the angle
* crosses bottom to top (e.g. 358 -> 2).
*
* @param prevAngle {Number} Previous angle in degrees
* @param nextAngle {Number} Next angle in degrees
*
* @return {Boolean} True if the angle is increasing
**/
function isAngleIncreasing(prevAngle, nextAngle) {
const lowerBound = 30,
upperBound = 360 - lowerBound;
if(prevAngle < lowerBound && nextAngle > upperBound) {
return false;
} else if(prevAngle > upperBound && nextAngle < lowerBound) {
return true;
} else {
return prevAngle < nextAngle;
}
}
/**
* Normalize the angle to 0 - 360.
*
* @param angle {Number} Angle in degrees
*
* @return {Number} Normalized angle
**/
function normalizeAngle(angle) {
// get normalized base angles by chopping off any previous turns
let normalized = angle % 360;
// ensure the normalized angle is positive
while (normalized < 0) { normalized += 360; }
return normalized;
};
const members = {
/*
---------------------------------------------------------------------------
INTERNAL FIELDS ::
---------------------------------------------------------------------------
*/
/** {Number} Current angle of the knob */
__angle: 0,
/** {Number} Current value of the knob */
__value: 0,
/** {Number} Center of the knob in the context of the page */
__centerPageX: 0,
/** {Number} Center of the knob in the context of the page */
__centerPageY: 0,
/** {Boolean} Whether only a single finger is used in touch handling */
__isSingleTouch: false,
/** {Boolean} Whether a touch event sequence is in progress */
__isTracking: false,
/**
* {Boolean} Whether the user has moved by such a distance that we have enabled
* spinning mode. Hint: It's only enabled after some pixels of movement to
* not interrupt with clicks etc.
*/
__isTurning: false,
/*
---------------------------------------------------------------------------
INTERNAL FIELDS :: INITIAL POSITIONS
---------------------------------------------------------------------------
*/
/** {Number} Left position of finger at start */
__initialTouchLeft: null,
/** {Number} Top position of finger at start */
__initialTouchTop: null,
/**
* {Number} Position of finger relative to center at start along X axis.
* Possible values are "left" and "right".
**/
__initialTouchLocationX: null,
/**
* {Number} Position of finger relative to center at start along Y axis.
* Possible values are "top" and "bottom".
**/
__initialTouchLocationY: null,
/** {Boolean} Flag used for locking */
__slideXDetected: false,
/** {Boolean} Flag used for locking */
__slideYDetected: false,
/** {Boolean} Flag used for locking */
__spinDetected: false,
/*
---------------------------------------------------------------------------
INTERNAL FIELDS :: LAST POSITIONS
---------------------------------------------------------------------------
*/
/** {Number} The previous left position of finger */
__lastTouchLeft: null,
/** {Number} The previous top position of finger */
__lastTouchTop: null,
/** {Date} Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */
__lastTouchMove: null,
/** {Array} List of positions, uses three indexes for each state: left, top, timestamp */
__positions: null,
/*
---------------------------------------------------------------------------
INTERNAL FIELDS :: DIMENSIONS
---------------------------------------------------------------------------
*/
/** {Integer} Available outer left position (from document perspective) */
__clientLeft: 0,
/** {Integer} Available outer top position (from document perspective) */
__clientTop: 0,
/** {Integer} Available outer width */
__clientWidth: 0,
/** {Integer} Available outer height */
__clientHeight: 0,
/*
---------------------------------------------------------------------------
PUBLIC API
---------------------------------------------------------------------------
*/
/**
* Set the width and height of the knob.
*
* All values which are falsy (null or zero etc.) are ignored and the old value is kept.
*
* @param clientWidth {Integer ? null} Inner width of outer element
* @param clientHeight {Integer ? null} Inner height of outer element
*/
setDimensions: function(clientWidth, clientHeight) {
const self = this;
// Only update values which are defined
if (clientWidth) {
self.__clientWidth = clientWidth;
}
if (clientHeight) {
self.__clientHeight = clientHeight;
}
self.__updateCenterLocation();
self.__publish();
},
/**
* Sets the client coordinates in relation to the document.
*
* @param left {Integer ? 0} Left position of outer element
* @param top {Integer ? 0} Top position of outer element
*/
setPosition: function(left, top) {
const self = this;
self.__clientLeft = left || 0;
self.__clientTop = top || 0;
self.__updateCenterLocation();
self.__publish();
},
/**
* Gets or sets the knob value.
*
* @return {Number} `value`
*/
val: function(value) {
if(value) {
this.__validateAndPublishValue(value, true);
}
return this.__value;
},
/**
* Gets or sets the knob angle.
*
* @return {Number} `angle`
*/
angle: function(angle) {
if(angle) {
this.__validateAndPublishAngle(angle, true);
}
return this.__angle;
},
// turnByValue: function(value) {
// },
// turnByAngle: function(angle) {
// },
/*
---------------------------------------------------------------------------
EVENT CALLBACKS
---------------------------------------------------------------------------
*/
/**
* Mouse wheel/scroll handler for knob turning support
*/
doMouseScroll: function(wheelDelta, timeStamp, pageX, pageY) {
const self = this;
if (!self.options.gestureScrollEnabled) return
// Figure out where the touch was relative to the center
let change = constrain(wheelDelta, -20, 20);
change = (pageX >= self.__centerPageX) ? -change : change;
change *= self.options.angleScrollRatio;
self.__validateAndPublishAngle(self.__angle + change);
},
/**
* Touch start handler for knob turning support
*/
doTouchStart: function(touches, timeStamp) {
// Array-like check is enough here
if (touches.length == null) {
throw new Error("Invalid touch list: " + touches);
}
if (typeof timeStamp !== "number") {
throw new Error("Invalid timestamp value: " + timeStamp);
}
const self = this,
isSingleTouch = touches.length === 1,
currentTouchLeft = touches[0].pageX,
currentTouchTop = touches[0].pageY;
// Store initial positions
self.__initialTouchLeft = currentTouchLeft;
self.__initialTouchTop = currentTouchTop;
self.__initialAngle = angleFromCoord(self.__initialTouchLeft, self.__initialTouchTop, self.__centerPageX, self.__centerPageY);
self.__initialAngleDiff = angleDistance(self.__initialAngle, self.__angle);
// Store initial touch positions
self.__lastTouchLeft = currentTouchLeft;
self.__lastTouchTop = currentTouchTop;
// Store initial move time stamp
self.__lastTouchMove = timeStamp;
// Reset locking flags
self.__slideXDetected = !isSingleTouch && self.options.gestureSlideXEnabled;
self.__slideYDetected = !isSingleTouch && self.options.gestureSlideYEnabled;
// Figure out where the touch was relative to the center
self.__initialTouchLocationX = (currentTouchLeft >= self.__centerPageX) ? "right" : "left";
self.__initialTouchLocationY = (currentTouchTop >= self.__centerPageY) ? "bottom" : "top";
// Reset tracking flag
self.__isTracking = true;
// Spinning starts directly with two fingers, otherwise lazy with an offset
self.__isTurning = !isSingleTouch;
self.__spinDetected = self.options.gestureSpinEnabled;
self.__totalDistance = 0;
// Some features are disabled in multi touch scenarios
self.__isSingleTouch = isSingleTouch;
// Reset locking flag
self.__isGestureLocked = false;
// Clearing data structure
self.__positions = [];
},
/**
* Touch move handler for knob turning support
*/
doTouchMove: function(touches, timeStamp, scale) {
// Array-like check is enough here
if (touches.length == null) {
throw new Error("Invalid touch list: " + touches);
}
if (typeof timeStamp !== "number") {
throw new Error("Invalid timestamp value: " + timeStamp);
}
const self = this;
// Ignore event when tracking is not enabled (event might be outside of element)
if (!self.__isTracking) {
return;
}
const currentTouchLeft = touches[0].pageX,
currentTouchTop = touches[0].pageY,
positions = self.__positions;
self.__validateAndPublishAngle(self.__getAngleFromGesture(currentTouchLeft, currentTouchTop));
self.__isTurning = true;
if (!self.__isGestureLocked) {
const minimumTrackingForChange = 35,
minimumDistanceForLocking = 40,
maximumSlideVariance = 5,
distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft),
distanceY = Math.abs(currentTouchTop - self.__initialTouchTop);
self.__slideXDetected = self.options.gestureSlideXEnabled && distanceX >= minimumTrackingForChange && distanceY < maximumSlideVariance;
self.__slideYDetected = self.options.gestureSlideYEnabled && distanceY >= minimumTrackingForChange && distanceX < maximumSlideVariance;
// if(self.__isTurning && !self.__isGestureLocked) {
// if(self.__spinDetected) { console.log("spinning") }
// if(self.__slideXDetected) { console.log("sliding left/right") }
// if(self.__slideYDetected) { console.log("sliding up/down") }
// }
if(self.__totalDistance > minimumDistanceForLocking) {
self.__isGestureLocked = true;
if(self.__slideXDetected && self.__slideYDetected) {
// gesture isn't definitively in one direction or another,
// so clear the slides and lock in the spin
self.__slideXDetected = self.__slideYDetected = false;
self.__spinDetected = self.options.gestureSpinEnabled;
}
else if(self.__slideXDetected) {
// lock in the slide X
self.__spinDetected = self.__slideYDetected = false;
}
else if(self.__slideYDetected) {
// lock in the slide Y
self.__spinDetected = self.__slideXDetected = false;
}
}
self.__totalDistance += pointDistance(self.__lastTouchLeft, self.__lastTouchTop, currentTouchLeft, currentTouchTop);
}
// Keep list from growing infinitely (holding min 10, max 20 measure points)
if (positions.length > 60) {
positions.splice(0, 30);
}
// Track scroll movement for deceleration
positions.push({
left: currentTouchLeft,
top: currentTouchTop,
time: timeStamp
});
// Update last touch positions and time stamp for next event
self.__lastTouchLeft = currentTouchLeft;
self.__lastTouchTop = currentTouchTop;
self.__lastTouchMove = timeStamp;
},
/**
* Touch end handler for knob turning support
*/
doTouchEnd: function(timeStamp) {
if (typeof timeStamp !== "number") {
throw new Error("Invalid timestamp value: " + timeStamp);
}
const self = this;
// Ignore event when tracking is not enabled (no touchstart event on element)
// This is required as this listener ('touchmove') sits on the document and not on the element itself.
if (!self.__isTracking) {
return;
}
// Not touching anymore (when two finger hit the screen there are two touch end events)
// *** Temporarily commented out due to problems with multitouch
// *** Touch end on one knob causes all knobs to stop
// self.__isTracking = false;
// Reset turning flag
self.__isTurning = false;
// Fully cleanup list
self.__positions.length = 0;
},
/*
---------------------------------------------------------------------------
PRIVATE API
---------------------------------------------------------------------------
*/
__validateAndPublishAngle: function(angle, forcePublish) {
const self = this
let diff;
if (forcePublish) {
this.__angle = self.__validateAngle(angle, true);
}
const prevAngle = self.__angle;
const nPreviousAngle = normalizeAngle(prevAngle);
const nCurrentAngle = normalizeAngle(angle);
diff = smallestAngleDistance(nPreviousAngle, nCurrentAngle);
diff = isAngleIncreasing(nPreviousAngle, nCurrentAngle) ? diff : -diff;
const nextAngle = self.__validateAngle(self.__angle + diff);
self.__angle = nextAngle;
self.__value = self.__valueFromAngles(forcePublish ? nextAngle : prevAngle, nextAngle);
self.__publish();
},
__validateAndPublishValue: function(value, forcePublish) {
const self = this;
// if(forcePublish) {
self.__value = self.__validateValue(value, true);
// }
self.__angle = self.__angleFromValue(self.__value);
self.__publish();
},
/**
* Returns an angle with the angleStart angleEnd constraints applied.
*
* @param angle {Number} Angle to validate
*/
__validateAngle: function(angle, force) {
const self = this;
angle = constrain(angle, self.options.angleStart, self.options.angleEnd);
if(!force) {
// if prevAngle was at a boundary, only allow a legal natural move to change the existing angle.
const threshold = 30;
if(self.__angle == self.options.angleStart && Math.abs(angle-self.__angle) > threshold ) {
angle = self.options.angleStart;
}
if(self.__angle == self.options.angleEnd && Math.abs(angle-self.__angle) > threshold) {
angle = self.options.angleEnd;
}
}
return angle;
},
/**
* Returns a value with the valueMin and valueMax constraints applied.
*
* @param value {Number} Value to validate
*/
__validateValue: function(value, force) {
const self = this;
return constrain(value, self.options.valueMin, self.options.valueMax);
},
/**
* Returns a value with the valueMin valueMax constraints applied from the given angles.
*
* @param prevAngle {Number} previous angle of the knob
* @param nextAngle {Number} next angle of the knob
*/
__valueFromAngles: function(prevAngle, nextAngle) {
const self = this;
// If angle and value bounds are real, map angle directly to value
if (isFinite(self.options.angleStart) &&
isFinite(self.options.angleEnd) &&
self.options.valueMin != Number.NEGATIVE_INFINITY &&
self.options.valueMax != Number.POSITIVE_INFINITY) {
// mapping angleStart->valueMax and angleEnd->valueMin to increase the value as the knob turns clockwise
return map(nextAngle, self.options.angleStart, self.options.angleEnd, self.options.valueMax, self.options.valueMin);
}
// If bounds aren't real, just increase/decrease value based on the change in angle.
// it's prevAngle - nextAngle to increase the value as the knob turns clockwise
const value = self.__value + (prevAngle - nextAngle) * self.options.angleValueRatio;
return self.__validateValue(value);
},
/**
* Returns the angle that corresponds to the given value.
*
* @param value {Number} angle represented by the value
*/
__angleFromValue: function(value) {
const self = this;
// If angle and value bounds are real, map angle directly to value
if (isFinite(self.options.valueMin) &&
isFinite(self.options.valueMax) &&
self.options.angleStart != Number.NEGATIVE_INFINITY &&
self.options.angleEnd != Number.POSITIVE_INFINITY) {
return map(value, self.options.valueMin, self.options.valueMax, self.options.angleStart, self.options.angleEnd);
}
// If bounds aren't real, just increase/decrease angle based on the change in value.
const angle = self.__angle + (value - self.__value) / self.options.angleValueRatio;
return self.__validateAngle(angle, true);
},
/**
* Applies the values to the callback function.
*/
__publish: function() {
const self = this,
indicator = self.__getIndicator(self.__angle),
spriteOffset = self.__getSpriteOffset(self.__angle);
// Set the input element's value
self.element.value = self.__value;
self.element.dispatchEvent(new CustomEvent('change'));
// Push values out
if (self.__callback) {
self.__callback(self, indicator, spriteOffset);
}
},
/**
* Returns the indicator position and rotation information.
*
* @param angle {Number} angle
*
* @return {Map} `x` and `y` position and `angle`
*/
__getIndicator: function(angle) {
const self = this,
indicator = {};
if(self.options.indicatorAutoPosition) {
const rads = toRadians(angle);
// Subtract Y component because of canvas's inverted Y coordinate compared to output of sin.
indicator.x = self.__centerPageX - self.__clientLeft + self.options.indicatorRadius * Math.cos(rads),
indicator.y = self.__centerPageY - self.__clientTop - self.options.indicatorRadius * Math.sin(rads);
}
else {
// If not positioning, set x & y to the center of the knob
indicator.x = self.__centerPageX - self.__clientLeft,
indicator.y = self.__centerPageY - self.__clientTop;
}
if(self.options.indicatorAutoRotate) {
indicator.angle = angle - self.options.indicatorStartAngle;
}
else {
indicator.angle = 0;
}
return indicator;
},
/**
* Returns the offset for the image within the sprite.
*
* @param angle {Number} angle
*
* @return {Map} `x`, `y` offset of image within sprite
*/