-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathrange.tsx
More file actions
1266 lines (1133 loc) · 40 KB
/
range.tsx
File metadata and controls
1266 lines (1133 loc) · 40 KB
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
import type { ComponentInterface, EventEmitter } from '@stencil/core';
import { Build, Component, Element, Event, Host, Prop, State, Watch, h } from '@stencil/core';
import { findClosestIonContent, disableContentScrollY, resetContentScrollY } from '@utils/content';
import type { Attributes } from '@utils/helpers';
import { inheritAriaAttributes, clamp, debounceEvent, renderHiddenInput, isSafeNumber } from '@utils/helpers';
import { printIonWarning } from '@utils/logging';
import { isRTL } from '@utils/rtl';
import { createColorClasses, hostContext } from '@utils/theme';
import { getIonTheme } from '../../global/ionic-global';
import type { Color, Gesture, GestureDetail } from '../../interface';
import { roundToMaxDecimalPlaces } from '../../utils/floating-point';
import type {
KnobName,
KnobPosition,
RangeChangeEventDetail,
RangeKnobMoveEndEventDetail,
RangeKnobMoveStartEventDetail,
RangeValue,
PinFormatter,
} from './range-interface';
// TODO(FW-2832): types
/**
* @virtualProp {"ios" | "md"} mode - The mode determines the platform behaviors of the component.
* @virtualProp {"ios" | "md" | "ionic"} theme - The theme determines the visual appearance of the component.
*
* @slot label - The label text to associate with the range. Use the "labelPlacement" property to control where the label is placed relative to the range.
* @slot start - Content is placed to the left of the range slider in LTR, and to the right in RTL.
* @slot end - Content is placed to the right of the range slider in LTR, and to the left in RTL.
*
* @part label - The label text describing the range.
* @part tick - An inactive tick mark.
* @part tick-active - An active tick mark.
* @part bar - The inactive part of the bar.
* @part bar-active - The active part of the bar.
* @part knob-handle - The container that wraps the knob and handles drag interactions.
* @part knob-handle-a - The container for the knob with the static `A` identity when `dualKnobs` is `true`. This identity does not change, even if the knobs cross and swap which one represents the lower or upper value.
* @part knob-handle-b - The container for the knob with the static `B` identity when `dualKnobs` is `true`. This identity does not change, even if the knobs cross and swap which one represents the lower or upper value.
* @part knob-handle-lower - The container for the knob whose current `value` is `lower` when `dualKnobs` is `true`. The lower and upper parts swap which knob handle they refer to when the knobs cross.
* @part knob-handle-upper - The container for the knob whose current `value` is `upper` when `dualKnobs` is `true`. The lower and upper parts swap which knob handle they refer to when the knobs cross.
* @part pin - The value indicator displayed above a knob.
* @part pin-a - The value indicator above the knob with the static `A` identity when `dualKnobs` is `true`. This identity does not change, even if the knobs cross and swap which one represents the lower or upper value.
* @part pin-b - The value indicator above the knob with the static `B` identity when `dualKnobs` is `true`. This identity does not change, even if the knobs cross and swap which one represents the lower or upper value.
* @part pin-lower - The value indicator above the knob whose current `value` is `lower` when `dualKnobs` is `true`. The lower and upper parts swap which pin they refer to when the knobs cross.
* @part pin-upper - The value indicator above the knob whose current `value` is `upper` when `dualKnobs` is `true`. The lower and upper parts swap which pin they refer to when the knobs cross.
* @part knob - The visual knob element on the range track.
* @part knob-a - The visual knob for the static `A` identity when `dualKnobs` is `true`. This identity does not change, even if the knobs cross and swap which one represents the lower or upper value.
* @part knob-b - The visual knob for the static `B` identity when `dualKnobs` is `true`. This identity does not change, even if the knobs cross and swap which one represents the lower or upper value.
* @part knob-lower - The visual knob whose current `value` is `lower` when `dualKnobs` is `true`. The lower and upper parts swap which knob they refer to when the knobs cross.
* @part knob-upper - The visual knob whose current `value` is `upper` when `dualKnobs` is `true`. The lower and upper parts swap which knob they refer to when the knobs cross.
* @part activated - Added to the knob-handle, knob, and pin when the knob is active. Only one set has this part at a time when `dualKnobs` is `true`.
* @part focused - Added to the knob-handle, knob, and pin that currently has focus. Only one set has this part at a time when `dualKnobs` is `true`.
* @part hover - Added to the knob-handle, knob, and pin when the knob has hover. Only one set has this part at a time when `dualKnobs` is `true`.
* @part pressed - Added to the knob-handle, knob, and pin that is currently being pressed to drag. Only one set has this part at a time when `dualKnobs` is `true`.
*/
@Component({
tag: 'ion-range',
styleUrls: {
ios: 'range.ios.scss',
md: 'range.md.scss',
ionic: 'range.ionic.scss',
},
shadow: true,
})
export class Range implements ComponentInterface {
private rangeId = `ion-r-${rangeIds++}`;
private didLoad = false;
private noUpdate = false;
private rect!: ClientRect;
private hasFocus = false;
private rangeSlider?: HTMLElement;
private gesture?: Gesture;
private inheritedAttributes: Attributes = {};
private contentEl: HTMLElement | null = null;
private initialContentScrollY = true;
private originalIonInput?: EventEmitter<RangeChangeEventDetail>;
/**
* Used to avoid setting the focused state on click or tap. The focused
* state is only set when the focus comes from the keyboard (e.g. Tab).
* This is set to true on pointer down (mouse/touch).
*/
private focusFromPointer = false;
/**
* Observes class changes on the knob handles to keep the activatedKnob
* state in sync with the ion-activated class. This is necessary to
* determine which knob the user is dragging when using dual knobs and
* apply the activated part correctly.
*/
private activatedObserver?: MutationObserver;
@Element() el!: HTMLIonRangeElement;
@State() private ratioA = 0;
@State() private ratioB = 0;
@State() private activatedKnob: KnobName;
@State() private focusedKnob: KnobName;
@State() private hoveredKnob: KnobName;
@State() private pressedKnob: KnobName;
/**
* The color to use from your application's color palette.
* Default options are: `"primary"`, `"secondary"`, `"tertiary"`, `"success"`, `"warning"`, `"danger"`, `"light"`, `"medium"`, and `"dark"`.
* For more information on colors, see [theming](/docs/theming/basics).
*/
@Prop({ reflect: true }) color?: Color;
/**
* How long, in milliseconds, to wait to trigger the
* `ionInput` event after each change in the range value.
*/
@Prop() debounce?: number;
@Watch('debounce')
protected debounceChanged() {
const { ionInput, debounce, originalIonInput } = this;
/**
* If debounce is undefined, we have to manually revert the ionInput emitter in case
* debounce used to be set to a number. Otherwise, the event would stay debounced.
*/
this.ionInput = debounce === undefined ? originalIonInput ?? ionInput : debounceEvent(ionInput, debounce);
}
/**
* The name of the control, which is submitted with the form data.
*/
@Prop() name = this.rangeId;
/**
* The text to display as the control's label. Use this over the `label` slot if
* you only need plain text. The `label` property will take priority over the
* `label` slot if both are used.
*/
@Prop() label?: string;
/**
* Show two knobs.
*/
@Prop() dualKnobs = false;
/**
* Minimum integer value of the range.
*/
@Prop() min = 0;
@Watch('min')
protected minChanged(newValue: number) {
if (!isSafeNumber(newValue)) {
this.min = 0;
}
if (!this.noUpdate) {
this.updateRatio();
}
}
/**
* Maximum integer value of the range.
*/
@Prop() max = 100;
@Watch('max')
protected maxChanged(newValue: number) {
if (!isSafeNumber(newValue)) {
this.max = 100;
}
if (!this.noUpdate) {
this.updateRatio();
}
}
/**
* If `true`, a pin with integer value is shown when the knob
* is pressed.
*/
@Prop() pin = false;
/**
* A callback used to format the pin text.
* By default the pin text is set to `Math.round(value)`.
*
* See https://ionicframework.com/docs/troubleshooting/runtime#accessing-this
* if you need to access `this` from within the callback.
*/
@Prop() pinFormatter: PinFormatter = (value: number): number => Math.round(value);
/**
* If `true`, the knob snaps to tick marks evenly spaced based
* on the step property value.
*/
@Prop() snaps = false;
/**
* Specifies the value granularity.
*/
@Prop() step = 1;
@Watch('step')
protected stepChanged(newValue: number) {
if (!isSafeNumber(newValue)) {
this.step = 1;
}
}
/**
* If `true`, tick marks are displayed based on the step value.
* Only applies when `snaps` is `true`.
*/
@Prop() ticks = true;
/**
* The start position of the range active bar. This feature is only available with a single knob (dualKnobs="false").
* Valid values are greater than or equal to the min value and less than or equal to the max value.
*/
@Prop({ mutable: true }) activeBarStart?: number;
@Watch('activeBarStart')
protected activeBarStartChanged() {
const { activeBarStart } = this;
if (activeBarStart !== undefined) {
if (activeBarStart > this.max) {
printIonWarning(
`[ion-range] - The value of activeBarStart (${activeBarStart}) is greater than the max (${this.max}). Valid values are greater than or equal to the min value and less than or equal to the max value.`,
this.el
);
this.activeBarStart = this.max;
} else if (activeBarStart < this.min) {
printIonWarning(
`[ion-range] - The value of activeBarStart (${activeBarStart}) is less than the min (${this.min}). Valid values are greater than or equal to the min value and less than or equal to the max value.`,
this.el
);
this.activeBarStart = this.min;
}
}
}
/**
* If `true`, the user cannot interact with the range.
*/
@Prop() disabled = false;
@Watch('disabled')
protected disabledChanged() {
if (this.gesture) {
this.gesture.enable(!this.disabled);
}
}
/**
* the value of the range.
*/
@Prop({ mutable: true }) value: RangeValue = 0;
@Watch('value')
protected valueChanged(newValue: RangeValue, oldValue: RangeValue) {
const valuesChanged = this.compareValues(newValue, oldValue);
if (valuesChanged) {
this.ionInput.emit({ value: this.value });
}
if (!this.noUpdate) {
this.updateRatio();
}
}
/**
* Compares two RangeValue inputs to determine if they are different.
*
* @param newVal - The new value.
* @param oldVal - The old value.
* @returns `true` if the values are different, `false` otherwise.
*/
private compareValues = (newVal: RangeValue, oldVal: RangeValue) => {
if (typeof newVal === 'object' && typeof oldVal === 'object') {
return newVal.lower !== oldVal.lower || newVal.upper !== oldVal.upper;
}
return newVal !== oldVal;
};
private clampBounds = (value: any): number => {
return clamp(this.min, value, this.max);
};
private ensureValueInBounds = (value: any) => {
if (this.dualKnobs) {
return {
lower: this.clampBounds(value.lower),
upper: this.clampBounds(value.upper),
};
} else {
return this.clampBounds(value);
}
};
/**
* Where to place the label relative to the range.
* `"start"`: The label will appear to the left of the range in LTR and to the right in RTL.
* `"end"`: The label will appear to the right of the range in LTR and to the left in RTL.
* `"fixed"`: The label has the same behavior as `"start"` except it also has a fixed width. Long text will be truncated with ellipses ("...").
* `"stacked"`: The label will appear above the range regardless of the direction.
*/
@Prop() labelPlacement: 'start' | 'end' | 'fixed' | 'stacked' = 'start';
/**
* The `ionChange` event is fired for `<ion-range>` elements when the user
* modifies the element's value:
* - When the user releases the knob after dragging;
* - When the user moves the knob with keyboard arrows
*
* This event will not emit when programmatically setting the `value` property.
*/
@Event() ionChange!: EventEmitter<RangeChangeEventDetail>;
/**
* The `ionInput` event is fired for `<ion-range>` elements when the value
* is modified. Unlike `ionChange`, `ionInput` is fired continuously
* while the user is dragging the knob.
*/
@Event() ionInput!: EventEmitter<RangeChangeEventDetail>;
/**
* Emitted when the range has focus.
*/
@Event() ionFocus!: EventEmitter<void>;
/**
* Emitted when the range loses focus.
*/
@Event() ionBlur!: EventEmitter<void>;
/**
* Emitted when the user starts moving the range knob, whether through
* mouse drag, touch gesture, or keyboard interaction.
*/
@Event() ionKnobMoveStart!: EventEmitter<RangeKnobMoveStartEventDetail>;
/**
* Emitted when the user finishes moving the range knob, whether through
* mouse drag, touch gesture, or keyboard interaction.
*/
@Event() ionKnobMoveEnd!: EventEmitter<RangeKnobMoveEndEventDetail>;
private setupGesture = async () => {
const rangeSlider = this.rangeSlider;
if (rangeSlider) {
this.gesture = (await import('../../utils/gesture')).createGesture({
el: rangeSlider,
gestureName: 'range',
gesturePriority: 100,
/**
* Provide a threshold since the drag movement
* might be a user scrolling the view.
* If this is true, then the range
* should not move.
*/
threshold: 10,
onStart: () => this.onStart(),
onMove: (ev) => this.onMove(ev),
onEnd: (ev) => this.onEnd(ev),
});
this.gesture.enable(!this.disabled);
}
};
/**
* Observes the knob handles for the ion-activated class and syncs
* activatedKnob so the activated part is correctly set on the handle,
* knob, and pin.
*/
private setupActivatedObserver = () => {
const knobHandleA = this.el.shadowRoot!.querySelector('.range-knob-handle-a');
const knobHandleB = this.el.shadowRoot!.querySelector('.range-knob-handle-b');
const syncActivated = () => {
this.activatedKnob = (knobHandleA as HTMLElement)?.classList.contains('ion-activated')
? 'A'
: (knobHandleB as HTMLElement)?.classList.contains('ion-activated')
? 'B'
: undefined;
};
if (Build.isBrowser && typeof MutationObserver !== 'undefined') {
this.activatedObserver = new MutationObserver(syncActivated);
this.activatedObserver.observe(this.el.shadowRoot!, {
attributes: true,
attributeFilter: ['class'],
subtree: true,
});
}
syncActivated();
};
componentWillLoad() {
/**
* If user has custom ID set then we should
* not assign the default incrementing ID.
*/
if (this.el.hasAttribute('id')) {
this.rangeId = this.el.getAttribute('id')!;
}
this.inheritedAttributes = inheritAriaAttributes(this.el);
// If min, max, or step are not safe, set them to 0, 100, and 1, respectively.
// Each watch does this, but not before the initial load.
this.min = isSafeNumber(this.min) ? this.min : 0;
this.max = isSafeNumber(this.max) ? this.max : 100;
this.step = isSafeNumber(this.step) ? this.step : 1;
}
componentDidLoad() {
this.originalIonInput = this.ionInput;
this.setupGesture();
this.updateRatio();
this.setupActivatedObserver();
this.didLoad = true;
}
connectedCallback() {
this.updateRatio();
this.debounceChanged();
this.disabledChanged();
this.activeBarStartChanged();
/**
* If we have not yet rendered
* ion-range, then rangeSlider is not defined.
* But if we are moving ion-range via appendChild,
* then rangeSlider will be defined.
*/
if (this.didLoad) {
this.setupGesture();
this.setupActivatedObserver();
}
const ionContent = findClosestIonContent(this.el);
this.contentEl = ionContent?.querySelector('.ion-content-scroll-host') ?? ionContent;
}
disconnectedCallback() {
if (this.gesture) {
this.gesture.destroy();
this.gesture = undefined;
}
if (this.activatedObserver) {
this.activatedObserver.disconnect();
this.activatedObserver = undefined;
}
}
private handleKeyboard = (knob: KnobName, isIncrease: boolean) => {
const { ensureValueInBounds } = this;
let step = this.step;
step = step > 0 ? step : 1;
step = step / (this.max - this.min);
if (!isIncrease) {
step *= -1;
}
if (knob === 'A') {
this.ratioA = clamp(0, this.ratioA + step, 1);
} else {
this.ratioB = clamp(0, this.ratioB + step, 1);
}
this.ionKnobMoveStart.emit({ value: ensureValueInBounds(this.value) });
this.updateValue();
this.emitValueChange();
this.ionKnobMoveEnd.emit({ value: ensureValueInBounds(this.value) });
};
private getValue(): RangeValue {
const value = this.value ?? 0;
if (this.dualKnobs) {
if (typeof value === 'object') {
return value;
}
return {
lower: 0,
upper: value,
};
} else {
if (typeof value === 'object') {
return value.upper;
}
return value;
}
}
/**
* Emits an `ionChange` event.
*
* This API should be called for user committed changes.
* This API should not be used for external value changes.
*/
private emitValueChange() {
this.value = this.ensureValueInBounds(this.value);
this.ionChange.emit({ value: this.value });
}
/**
* The value should be updated on touch end or
* when the component is being dragged.
* This follows the native behavior of mobile devices.
*
* For example: When the user lifts their finger from the
* screen after tapping the bar or dragging the bar or knob.
*/
private onStart() {
this.ionKnobMoveStart.emit({ value: this.ensureValueInBounds(this.value) });
}
/**
* The value should be updated while dragging the
* bar or knob.
*
* While the user is dragging, the view
* should not scroll. This is to prevent the user from
* feeling disoriented while dragging.
*
* The user can scroll on the view if the knob or
* bar is not being dragged.
*
* @param detail The details of the gesture event.
*/
private onMove(detail: GestureDetail) {
const { contentEl, pressedKnob } = this;
const currentX = detail.currentX;
/**
* Since the user is dragging on the bar or knob, the view should not scroll.
*
* This only needs to be done once.
*/
if (contentEl && this.pressedKnob === undefined) {
this.initialContentScrollY = disableContentScrollY(contentEl);
}
/**
* The `pressedKnob` can be undefined if the user just
* started dragging the knob.
*
* This is necessary to determine which knob the user is dragging,
* especially when using dual knobs.
* Plus, it determines when to apply certain styles.
*
* This only needs to be done once since the knob won't change
* while the user is dragging.
*/
if (pressedKnob === undefined) {
this.setPressedKnob(currentX);
}
this.update(currentX);
}
/**
* The value should be updated on touch end:
* - When the user lifts their finger from the screen after
* tapping the bar.
*
* @param detail The details of the gesture or mouse event.
*/
private onEnd(detail: GestureDetail | MouseEvent) {
const { contentEl, initialContentScrollY } = this;
const currentX = (detail as GestureDetail).currentX ?? (detail as MouseEvent).clientX;
/**
* The `pressedKnob` can be undefined if the user never
* dragged the knob. They just tapped on the bar.
*
* This is necessary to determine which knob the user is changing,
* especially when using dual knobs.
* Plus, it determines when to apply certain styles.
*/
if (this.pressedKnob === undefined) {
this.setPressedKnob(currentX);
}
/**
* The user is no longer dragging the bar or
* knob (if they were dragging it).
*
* The user can now scroll on the view in the next gesture event.
*/
if (contentEl && this.pressedKnob !== undefined) {
resetContentScrollY(contentEl, initialContentScrollY);
}
// update the active knob's position
this.update(currentX);
/**
* Reset the pressed knob to undefined since the user
* may start dragging a different knob in the next gesture event.
*/
this.pressedKnob = undefined;
this.emitValueChange();
this.ionKnobMoveEnd.emit({ value: this.ensureValueInBounds(this.value) });
}
private update(currentX: number) {
// figure out where the pointer is currently at
// update the knob being interacted with
const rect = this.rect;
let ratio = clamp(0, (currentX - rect.left) / rect.width, 1);
if (isRTL(this.el)) {
ratio = 1 - ratio;
}
if (this.snaps) {
// snaps the ratio to the current value
ratio = valueToRatio(ratioToValue(ratio, this.min, this.max, this.step), this.min, this.max);
}
// update which knob is pressed
if (this.pressedKnob === 'A') {
this.ratioA = ratio;
} else {
this.ratioB = ratio;
}
// Update input value
this.updateValue();
}
private setPressedKnob(currentX: number) {
const rect = (this.rect = this.rangeSlider!.getBoundingClientRect() as any);
// figure out which knob they started closer to
let ratio = clamp(0, (currentX - rect.left) / rect.width, 1);
if (isRTL(this.el)) {
ratio = 1 - ratio;
}
this.pressedKnob = !this.dualKnobs || Math.abs(this.ratioA - ratio) < Math.abs(this.ratioB - ratio) ? 'A' : 'B';
}
private get valA() {
return ratioToValue(this.ratioA, this.min, this.max, this.step);
}
private get valB() {
return ratioToValue(this.ratioB, this.min, this.max, this.step);
}
private get ratioLower() {
if (this.dualKnobs) {
return Math.min(this.ratioA, this.ratioB);
}
const { activeBarStart } = this;
if (activeBarStart == null) {
return 0;
}
return valueToRatio(activeBarStart, this.min, this.max);
}
private get ratioUpper() {
if (this.dualKnobs) {
return Math.max(this.ratioA, this.ratioB);
}
return this.ratioA;
}
private updateRatio() {
const value = this.getValue() as any;
const { min, max } = this;
/**
* For dual knobs, value gives lower/upper but not which is A vs B.
* Assign (lowerRatio, upperRatio) to (ratioA, ratioB) in the way that
* minimizes change from the current ratios so the knobs don't swap.
*/
if (this.dualKnobs) {
const lowerRatio = valueToRatio(value.lower, min, max);
const upperRatio = valueToRatio(value.upper, min, max);
if (
Math.abs(this.ratioA - lowerRatio) + Math.abs(this.ratioB - upperRatio) <=
Math.abs(this.ratioA - upperRatio) + Math.abs(this.ratioB - lowerRatio)
) {
this.ratioA = lowerRatio;
this.ratioB = upperRatio;
} else {
this.ratioA = upperRatio;
this.ratioB = lowerRatio;
}
} else {
this.ratioA = valueToRatio(value, min, max);
}
}
private updateValue() {
this.noUpdate = true;
const { valA, valB } = this;
this.value = !this.dualKnobs
? valA
: {
lower: Math.min(valA, valB),
upper: Math.max(valA, valB),
};
this.noUpdate = false;
}
private onBlur = () => {
if (this.hasFocus) {
this.hasFocus = false;
this.focusedKnob = undefined;
this.ionBlur.emit();
}
};
private onFocus = () => {
if (!this.hasFocus) {
this.hasFocus = true;
this.ionFocus.emit();
}
};
private onKnobFocus = (knob: KnobName) => {
// Clicking focuses the range which is needed for the keyboard,
// but we only want to add the ion-focused class when focused via Tab.
if (!this.focusFromPointer) {
this.focusedKnob = knob;
} else {
this.focusFromPointer = false;
this.focusedKnob = undefined;
}
// If the knob was not already focused, emit the focus event
if (!this.hasFocus) {
this.hasFocus = true;
this.ionFocus.emit();
}
};
private onKnobBlur = () => {
// Check if focus is moving to another knob within the same range
// by delaying the reset to allow the new focus to register
setTimeout(() => {
const activeElement = this.el.shadowRoot?.activeElement;
const isStillFocusedOnKnob = activeElement && activeElement.classList.contains('range-knob-handle');
if (!isStillFocusedOnKnob) {
if (this.hasFocus) {
this.hasFocus = false;
this.focusedKnob = undefined;
this.ionBlur.emit();
}
}
}, 0);
};
private onKnobMouseEnter = (knob: KnobName) => {
this.hoveredKnob = knob;
};
private onKnobMouseLeave = () => {
this.hoveredKnob = undefined;
};
/**
* Returns true if content was passed to the "start" slot
*/
private get hasStartSlotContent() {
return this.el.querySelector('[slot="start"]') !== null;
}
/**
* Returns true if content was passed to the "end" slot
*/
private get hasEndSlotContent() {
return this.el.querySelector('[slot="end"]') !== null;
}
private get hasLabel() {
return this.label !== undefined || this.el.querySelector('[slot="label"]') !== null;
}
private renderRangeSlider() {
const {
min,
max,
step,
handleKeyboard,
activatedKnob,
focusedKnob,
hoveredKnob,
pressedKnob,
disabled,
pin,
ratioLower,
ratioUpper,
pinFormatter,
inheritedAttributes,
} = this;
let barStart = `${ratioLower * 100}%`;
let barEnd = `${100 - ratioUpper * 100}%`;
const rtl = isRTL(this.el);
const start = rtl ? 'right' : 'left';
const end = rtl ? 'left' : 'right';
const tickStyle = (tick: any) => {
return {
[start]: tick[start],
};
};
if (this.dualKnobs === false) {
/**
* When the value is less than the activeBarStart or the min value,
* the knob will display at the start of the active bar.
*/
if (this.valA < (this.activeBarStart ?? this.min)) {
/**
* Sets the bar positions relative to the upper and lower limits.
* Converts the ratio values into percentages, used as offsets for left/right styles.
*
* The ratioUpper refers to the knob position on the bar.
* The ratioLower refers to the end position of the active bar (the value).
*/
barStart = `${ratioUpper * 100}%`;
barEnd = `${100 - ratioLower * 100}%`;
} else {
/**
* Otherwise, the knob will display at the end of the active bar.
*
* The ratioLower refers to the start position of the active bar (the value).
* The ratioUpper refers to the knob position on the bar.
*/
barStart = `${ratioLower * 100}%`;
barEnd = `${100 - ratioUpper * 100}%`;
}
}
const barStyle = {
[start]: barStart,
[end]: barEnd,
};
const ticks = [];
if (this.snaps && this.ticks) {
for (let value = min; value <= max; value += step) {
const ratio = valueToRatio(value, min, max);
const ratioMin = Math.min(ratioLower, ratioUpper);
const ratioMax = Math.max(ratioLower, ratioUpper);
const tick: any = {
ratio,
/**
* Sets the tick mark as active when the tick is between the min bounds and the knob.
* When using activeBarStart, the tick mark will be active between the knob and activeBarStart.
*/
active: ratio >= ratioMin && ratio <= ratioMax,
};
tick[start] = `${ratio * 100}%`;
ticks.push(tick);
}
}
return (
<div
class="range-slider"
ref={(rangeEl) => (this.rangeSlider = rangeEl)}
onPointerDown={() => {
this.focusFromPointer = true;
}}
/**
* Since the gesture has a threshold, the value
* won't change until the user has dragged past
* the threshold. This is to prevent the range
* from moving when the user is scrolling.
*
* This results in the value not being updated
* and the event emitters not being triggered
* if the user taps on the range. This is why
* we need to listen for the "pointerUp" event.
*/
onPointerUp={(ev: PointerEvent) => {
this.focusFromPointer = false;
/**
* If the user drags the knob on the web
* version (does not occur on mobile),
* the "pointerUp" event will be triggered
* along with the gesture's events.
* This leads to duplicate events.
*
* By checking if the pressedKnob is undefined,
* we can determine if the "pointerUp" event was
* triggered by a tap or a drag. If it was
* dragged, the pressedKnob will be defined.
*/
if (this.pressedKnob === undefined) {
this.onStart();
this.onEnd(ev);
}
}}
>
{ticks.map((tick) => (
<div
style={tickStyle(tick)}
role="presentation"
class={{
'range-tick': true,
'range-tick-active': tick.active,
}}
part={tick.active ? 'tick-active' : 'tick'}
/>
))}
<div class="range-bar-container">
<div
class={{
'range-bar': true,
'has-ticks': ticks.length > 0,
}}
role="presentation"
part="bar"
/>
<div
class={{
'range-bar': true,
'range-bar-active': true,
'has-ticks': ticks.length > 0,
}}
role="presentation"
style={barStyle}
part="bar-active"
/>
</div>
{renderKnob(rtl, {
knob: 'A',
position: getKnobPosition('A', this.ratioA, this.ratioB, this.dualKnobs),
dualKnobs: this.dualKnobs,
activated: activatedKnob === 'A',
focused: focusedKnob === 'A',
hovered: hoveredKnob === 'A',
pressed: pressedKnob === 'A',
value: this.valA,
ratio: this.ratioA,
pin,
pinFormatter,
disabled,
handleKeyboard,
min,
max,
inheritedAttributes,
onKnobFocus: this.onKnobFocus,
onKnobBlur: this.onKnobBlur,
onKnobMouseEnter: this.onKnobMouseEnter,
onKnobMouseLeave: this.onKnobMouseLeave,
})}
{this.dualKnobs &&
renderKnob(rtl, {
knob: 'B',
position: getKnobPosition('B', this.ratioA, this.ratioB, this.dualKnobs),
dualKnobs: this.dualKnobs,
activated: activatedKnob === 'B',
focused: focusedKnob === 'B',
hovered: hoveredKnob === 'B',
pressed: pressedKnob === 'B',
value: this.valB,
ratio: this.ratioB,
pin,
pinFormatter,
disabled,
handleKeyboard,
min,
max,
inheritedAttributes,
onKnobFocus: this.onKnobFocus,
onKnobBlur: this.onKnobBlur,
onKnobMouseEnter: this.onKnobMouseEnter,
onKnobMouseLeave: this.onKnobMouseLeave,
})}
</div>
);
}
render() {
const { disabled, el, hasLabel, rangeId, pin, pressedKnob, labelPlacement, label, dualKnobs, min, max } = this;
const inItem = hostContext('ion-item', el);
/**
* If there is no start content then the knob at
* the min value will be cut off by the item margin.
*/
const hasStartContent =
(hasLabel && (labelPlacement === 'start' || labelPlacement === 'fixed')) || this.hasStartSlotContent;
const needsStartAdjustment = inItem && !hasStartContent;