This repository has been archived by the owner on Jul 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Slider.kt
1134 lines (1056 loc) · 43.5 KB
/
Slider.kt
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
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.MutatorMutex
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.DragScope
import androidx.compose.foundation.gestures.DraggableState
import androidx.compose.foundation.gestures.GestureCancellationException
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.gestures.horizontalDrag
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.DragInteraction
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSizeIn
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.progressSemantics
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.tokens.SliderTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.lerp
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PointMode
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.input.pointer.AwaitPointerEventScope
import androidx.compose.ui.input.pointer.PointerId
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.PointerType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.disabled
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.setProgress
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/**
* Material Design slider
*
* Sliders allow users to make selections from a range of values.
*
* Sliders reflect a range of values along a bar, from which users may select a single value.
* They are ideal for adjusting settings such as volume, brightness, or applying image filters.
*
* ![Sliders image](https://developer.android.com/images/reference/androidx/compose/material3/sliders.png)
*
* Use continuous sliders to allow users to make meaningful selections that don’t
* require a specific value:
*
* @sample androidx.compose.material3.samples.SliderSample
*
* You can allow the user to choose only between predefined set of values by specifying the amount
* of steps between min and max values:
*
* @sample androidx.compose.material3.samples.StepsSliderSample
*
* @param value current value of the slider. If outside of [valueRange] provided, value will be
* coerced to this range.
* @param onValueChange callback in which value should be updated
* @param modifier the [Modifier] to be applied to this slider
* @param enabled controls the enabled state of this slider. When `false`, this component will not
* respond to user input, and it will appear visually disabled and disabled to accessibility
* services.
* @param valueRange range of values that this slider can take. The passed [value] will be coerced
* to this range.
* @param steps if greater than 0, specifies the amount of discrete allowable values, evenly
* distributed across the whole value range. If 0, the slider will behave continuously and allow any
* value from the range specified. Must not be negative.
* @param onValueChangeFinished called when value change has ended. This should not be used to
* update the slider value (use [onValueChange] instead), but rather to know when the user has
* completed selecting a new value by ending a drag or a click.
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this slider. You can create and pass in your own `remember`ed instance to observe
* [Interaction]s and customize the appearance / behavior of this slider in different states.
* @param colors [SliderColors] that will be used to resolve the colors used for this slider in
* different states. See [SliderDefaults.colors].
*/
// TODO(b/229979132): Add m.io link
@Composable
fun Slider(
value: Float,
onValueChange: (Float) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
valueRange: ClosedFloatingPointRange<Float> = 0f..1f,
/*@IntRange(from = 0)*/
steps: Int = 0,
onValueChangeFinished: (() -> Unit)? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
colors: SliderColors = SliderDefaults.colors()
) {
require(steps >= 0) { "steps should be >= 0" }
val onValueChangeState = rememberUpdatedState<(Float) -> Unit> {
if (it != value) {
onValueChange(it)
}
}
val tickFractions = remember(steps) {
stepsToTickFractions(steps)
}
BoxWithConstraints(
modifier
.minimumTouchTargetSize()
.requiredSizeIn(
minWidth = SliderTokens.HandleWidth,
minHeight = SliderTokens.HandleHeight
)
.sliderSemantics(
value,
enabled,
onValueChange,
onValueChangeFinished,
valueRange,
steps
)
.focusable(enabled, interactionSource)
) {
val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
val widthPx = constraints.maxWidth.toFloat()
val maxPx: Float
val minPx: Float
val thumbRadius = ThumbDiameter / 2
with(LocalDensity.current) {
maxPx = max(widthPx - thumbRadius.toPx(), 0f)
minPx = min(thumbRadius.toPx(), maxPx)
}
fun scaleToUserValue(offset: Float) =
scale(minPx, maxPx, offset, valueRange.start, valueRange.endInclusive)
fun scaleToOffset(userValue: Float) =
scale(valueRange.start, valueRange.endInclusive, userValue, minPx, maxPx)
val rawOffset = remember { mutableStateOf(scaleToOffset(value)) }
val pressOffset = remember { mutableStateOf(0f) }
val draggableState = remember(minPx, maxPx, valueRange) {
SliderDraggableState {
rawOffset.value = (rawOffset.value + it + pressOffset.value)
pressOffset.value = 0f
val offsetInTrack = snapValueToTick(rawOffset.value, tickFractions, minPx, maxPx)
onValueChangeState.value.invoke(scaleToUserValue(offsetInTrack))
}
}
val gestureEndAction = rememberUpdatedState {
if (!draggableState.isDragging) {
// check isDragging in case the change is still in progress (touch -> drag case)
onValueChangeFinished?.invoke()
}
}
val press = Modifier.sliderTapModifier(
draggableState,
interactionSource,
widthPx,
isRtl,
rawOffset,
gestureEndAction,
pressOffset,
enabled
)
val drag = Modifier.draggable(
orientation = Orientation.Horizontal,
reverseDirection = isRtl,
enabled = enabled,
interactionSource = interactionSource,
onDragStopped = { _ -> gestureEndAction.value.invoke() },
startDragImmediately = draggableState.isDragging,
state = draggableState
)
val coerced = value.coerceIn(valueRange.start, valueRange.endInclusive)
val fraction = calcFraction(valueRange.start, valueRange.endInclusive, coerced)
SliderImpl(
enabled,
fraction,
tickFractions,
colors,
maxPx - minPx,
interactionSource,
modifier = press.then(drag)
)
}
}
/**
* Material Design Range slider
*
* Range Sliders expand upon [Slider] using the same concepts but allow the user to select 2 values.
*
* The two values are still bounded by the value range but they also cannot cross each other.
*
* Use continuous Range Sliders to allow users to make meaningful selections that don’t
* require a specific values:
*
* @sample androidx.compose.material3.samples.RangeSliderSample
*
* You can allow the user to choose only between predefined set of values by specifying the amount
* of steps between min and max values:
*
* @sample androidx.compose.material3.samples.StepRangeSliderSample
*
* @param value current values of the RangeSlider. If either value is outside of [valueRange]
* provided, it will be coerced to this range.
* @param onValueChange lambda in which values should be updated
* @param modifier modifiers for the Range Slider layout
* @param enabled whether or not component is enabled and can we interacted with or not
* @param valueRange range of values that Range Slider values can take. Passed [value] will be
* coerced to this range
* @param steps if greater than 0, specifies the amounts of discrete values, evenly distributed
* between across the whole value range. If 0, range slider will behave as a continuous slider and
* allow to choose any value from the range specified. Must not be negative.
* @param onValueChangeFinished lambda to be invoked when value change has ended. This callback
* shouldn't be used to update the range slider values (use [onValueChange] for that), but rather to
* know when the user has completed selecting a new value by ending a drag or a click.
* @param colors [SliderColors] that will be used to determine the color of the Range Slider
* parts in different state. See [SliderDefaults.colors] to customize.
*/
@Composable
@ExperimentalMaterial3Api
fun RangeSlider(
value: ClosedFloatingPointRange<Float>,
onValueChange: (ClosedFloatingPointRange<Float>) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
valueRange: ClosedFloatingPointRange<Float> = 0f..1f,
/*@IntRange(from = 0)*/
steps: Int = 0,
onValueChangeFinished: (() -> Unit)? = null,
colors: SliderColors = SliderDefaults.colors()
) {
val startInteractionSource: MutableInteractionSource = remember { MutableInteractionSource() }
val endInteractionSource: MutableInteractionSource = remember { MutableInteractionSource() }
require(steps >= 0) { "steps should be >= 0" }
val onValueChangeState = rememberUpdatedState<(ClosedFloatingPointRange<Float>) -> Unit> {
if (it != value) {
onValueChange(it)
}
}
val tickFractions = remember(steps) {
stepsToTickFractions(steps)
}
BoxWithConstraints(
modifier = modifier
.minimumTouchTargetSize()
.requiredSizeIn(minWidth = ThumbWidth * 2, minHeight = ThumbHeight * 2)
) {
val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
val widthPx = constraints.maxWidth.toFloat()
val maxPx: Float
val minPx: Float
with(LocalDensity.current) {
maxPx = widthPx - ThumbWidth.toPx() / 2
minPx = ThumbWidth.toPx() / 2
}
fun scaleToUserValue(offset: ClosedFloatingPointRange<Float>) =
scale(minPx, maxPx, offset, valueRange.start, valueRange.endInclusive)
fun scaleToOffset(userValue: Float) =
scale(valueRange.start, valueRange.endInclusive, userValue, minPx, maxPx)
val rawOffsetStart = remember { mutableStateOf(scaleToOffset(value.start)) }
val rawOffsetEnd = remember { mutableStateOf(scaleToOffset(value.endInclusive)) }
val gestureEndAction = rememberUpdatedState<(Boolean) -> Unit> {
onValueChangeFinished?.invoke()
}
val onDrag = rememberUpdatedState<(Boolean, Float) -> Unit> { isStart, offset ->
val offsetRange = if (isStart) {
rawOffsetStart.value = (rawOffsetStart.value + offset)
rawOffsetEnd.value = scaleToOffset(value.endInclusive)
val offsetEnd = rawOffsetEnd.value
var offsetStart = rawOffsetStart.value.coerceIn(minPx, offsetEnd)
offsetStart = snapValueToTick(offsetStart, tickFractions, minPx, maxPx)
offsetStart..offsetEnd
} else {
rawOffsetEnd.value = (rawOffsetEnd.value + offset)
rawOffsetStart.value = scaleToOffset(value.start)
val offsetStart = rawOffsetStart.value
var offsetEnd = rawOffsetEnd.value.coerceIn(offsetStart, maxPx)
offsetEnd = snapValueToTick(offsetEnd, tickFractions, minPx, maxPx)
offsetStart..offsetEnd
}
onValueChangeState.value.invoke(scaleToUserValue(offsetRange))
}
val pressDrag = Modifier.rangeSliderPressDragModifier(
startInteractionSource,
endInteractionSource,
rawOffsetStart,
rawOffsetEnd,
enabled,
isRtl,
widthPx,
valueRange,
gestureEndAction,
onDrag,
)
// The positions of the thumbs are dependant on each other.
val coercedStart = value.start.coerceIn(valueRange.start, value.endInclusive)
val coercedEnd = value.endInclusive.coerceIn(value.start, valueRange.endInclusive)
val fractionStart = calcFraction(valueRange.start, valueRange.endInclusive, coercedStart)
val fractionEnd = calcFraction(valueRange.start, valueRange.endInclusive, coercedEnd)
val startSteps = floor(steps * fractionEnd).toInt()
val endSteps = floor(steps * (1f - fractionStart)).toInt()
val startThumbSemantics = Modifier.sliderSemantics(
coercedStart,
enabled,
{ value -> onValueChangeState.value.invoke(value..coercedEnd) },
onValueChangeFinished,
valueRange.start..coercedEnd,
startSteps
)
val endThumbSemantics = Modifier.sliderSemantics(
coercedEnd,
enabled,
{ value -> onValueChangeState.value.invoke(coercedStart..value) },
onValueChangeFinished,
coercedStart..valueRange.endInclusive,
endSteps
)
RangeSliderImpl(
enabled,
fractionStart,
fractionEnd,
tickFractions,
colors,
maxPx - minPx,
startInteractionSource,
endInteractionSource,
modifier = pressDrag,
startThumbSemantics,
endThumbSemantics
)
}
}
@Composable
private fun RangeSliderImpl(
enabled: Boolean,
positionFractionStart: Float,
positionFractionEnd: Float,
tickFractions: List<Float>,
colors: SliderColors,
width: Float,
startInteractionSource: MutableInteractionSource,
endInteractionSource: MutableInteractionSource,
modifier: Modifier,
startThumbSemantics: Modifier,
endThumbSemantics: Modifier
) {
val startContentDescription = getString(Strings.SliderRangeStart)
val endContentDescription = getString(Strings.SliderRangeEnd)
Box(modifier.then(DefaultSliderConstraints)) {
val trackStrokeWidth: Float
val widthDp: Dp
with(LocalDensity.current) {
trackStrokeWidth = TrackHeight.toPx()
widthDp = width.toDp()
}
val offsetStart = widthDp * positionFractionStart
val offsetEnd = widthDp * positionFractionEnd
Track(
Modifier
.align(Alignment.CenterStart)
.fillMaxSize(),
colors,
enabled,
positionFractionStart,
positionFractionEnd,
tickFractions,
ThumbWidth,
trackStrokeWidth
)
SliderThumb(
Modifier
.semantics(mergeDescendants = true) { contentDescription = startContentDescription }
.focusable(true, startInteractionSource)
.then(startThumbSemantics),
offsetStart,
startInteractionSource,
colors,
enabled,
ThumbSize
)
SliderThumb(
Modifier
.semantics(mergeDescendants = true) { contentDescription = endContentDescription }
.focusable(true, endInteractionSource)
.then(endThumbSemantics),
offsetEnd,
endInteractionSource,
colors,
enabled,
ThumbSize
)
}
}
/**
* Object to hold defaults used by [Slider]
*/
object SliderDefaults {
/**
* Creates a [SliderColors] that represents the different colors used in parts of the
* [Slider] in different states.
*
* For the name references below the words "active" and "inactive" are used. Active part of
* the slider is filled with progress, so if slider's progress is 30% out of 100%, left (or
* right in RTL) 30% of the track will be active, while the rest is inactive.
*
* @param thumbColor thumb color when enabled
* @param disabledThumbColor thumb colors when disabled
* @param activeTrackColor color of the track in the part that is "active", meaning that the
* thumb is ahead of it
* @param inactiveTrackColor color of the track in the part that is "inactive", meaning that the
* thumb is before it
* @param disabledActiveTrackColor color of the track in the "active" part when the Slider is
* disabled
* @param disabledInactiveTrackColor color of the track in the "inactive" part when the
* Slider is disabled
* @param activeTickColor colors to be used to draw tick marks on the active track, if `steps`
* is specified
* @param inactiveTickColor colors to be used to draw tick marks on the inactive track, if
* `steps` are specified on the Slider is specified
* @param disabledActiveTickColor colors to be used to draw tick marks on the active track
* when Slider is disabled and when `steps` are specified on it
* @param disabledInactiveTickColor colors to be used to draw tick marks on the inactive part
* of the track when Slider is disabled and when `steps` are specified on it
*/
@Composable
fun colors(
thumbColor: Color = SliderTokens.HandleColor.toColor(),
disabledThumbColor: Color = SliderTokens.DisabledHandleColor
.toColor()
.copy(alpha = SliderTokens.DisabledHandleOpacity)
.compositeOver(MaterialTheme.colorScheme.surface),
activeTrackColor: Color = SliderTokens.ActiveTrackColor.toColor(),
inactiveTrackColor: Color = SliderTokens.InactiveTrackColor.toColor(),
disabledActiveTrackColor: Color =
SliderTokens.DisabledActiveTrackColor
.toColor()
.copy(alpha = SliderTokens.DisabledActiveTrackOpacity),
disabledInactiveTrackColor: Color =
SliderTokens.DisabledInactiveTrackColor
.toColor()
.copy(alpha = SliderTokens.DisabledInactiveTrackOpacity),
activeTickColor: Color = SliderTokens.TickMarksActiveContainerColor
.toColor()
.copy(alpha = SliderTokens.TickMarksActiveContainerOpacity),
inactiveTickColor: Color = SliderTokens.TickMarksInactiveContainerColor.toColor()
.copy(alpha = SliderTokens.TickMarksInactiveContainerOpacity),
disabledActiveTickColor: Color = SliderTokens.TickMarksDisabledContainerColor
.toColor()
.copy(alpha = SliderTokens.TickMarksDisabledContainerOpacity),
disabledInactiveTickColor: Color = SliderTokens.TickMarksDisabledContainerColor.toColor()
.copy(alpha = SliderTokens.TickMarksDisabledContainerOpacity)
): SliderColors = DefaultSliderColors(
thumbColor = thumbColor,
disabledThumbColor = disabledThumbColor,
activeTrackColor = activeTrackColor,
inactiveTrackColor = inactiveTrackColor,
disabledActiveTrackColor = disabledActiveTrackColor,
disabledInactiveTrackColor = disabledInactiveTrackColor,
activeTickColor = activeTickColor,
inactiveTickColor = inactiveTickColor,
disabledActiveTickColor = disabledActiveTickColor,
disabledInactiveTickColor = disabledInactiveTickColor
)
}
/**
* Represents the colors used by a [Slider] and its parts in different states
*
* See [SliderDefaults.colors] for the default implementation that follows Material
* specifications.
*/
@Stable
interface SliderColors {
/**
* Represents the color used for the slider's thumb, depending on [enabled].
*
* @param enabled whether the [Slider] is enabled or not
*/
@Composable
fun thumbColor(enabled: Boolean): State<Color>
/**
* Represents the color used for the slider's track, depending on [enabled] and [active].
*
* Active part is filled with progress, so if sliders progress is 30% out of 100%, left (or
* right in RTL) 30% of the track will be active, while the rest is inactive.
*
* @param enabled whether the [Slider] is enabled or not
* @param active whether the part of the track is active of not
*/
@Composable
fun trackColor(enabled: Boolean, active: Boolean): State<Color>
/**
* Represents the color used for the slider's tick which is the dot separating steps, if
* they are set on the slider, depending on [enabled] and [active].
*
* Active tick is the tick that is in the part of the track filled with progress, so if
* sliders progress is 30% out of 100%, left (or right in RTL) 30% of the track and the ticks
* in this 30% will be active, the rest is not active.
*
* @param enabled whether the [Slider] is enabled or not
* @param active whether the part of the track this tick is in is active of not
*/
@Composable
fun tickColor(enabled: Boolean, active: Boolean): State<Color>
}
@Composable
private fun SliderImpl(
enabled: Boolean,
positionFraction: Float,
tickFractions: List<Float>,
colors: SliderColors,
width: Float,
interactionSource: MutableInteractionSource,
modifier: Modifier
) {
Box(modifier.then(DefaultSliderConstraints)) {
val trackStrokeWidth: Float
val widthDp: Dp
with(LocalDensity.current) {
trackStrokeWidth = TrackHeight.toPx()
widthDp = width.toDp()
}
val offset = widthDp * positionFraction
Track(
Modifier.fillMaxSize(),
colors,
enabled,
0f,
positionFraction,
tickFractions,
ThumbWidth,
trackStrokeWidth
)
SliderThumb(Modifier, offset, interactionSource, colors, enabled, ThumbSize)
}
}
@Composable
private fun BoxScope.SliderThumb(
modifier: Modifier,
offset: Dp,
interactionSource: MutableInteractionSource,
colors: SliderColors,
enabled: Boolean,
thumbSize: DpSize
) {
Box(
Modifier
.padding(start = offset)
.align(Alignment.CenterStart)) {
val interactions = remember { mutableStateListOf<Interaction>() }
LaunchedEffect(interactionSource) {
interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> interactions.add(interaction)
is PressInteraction.Release -> interactions.remove(interaction.press)
is PressInteraction.Cancel -> interactions.remove(interaction.press)
is DragInteraction.Start -> interactions.add(interaction)
is DragInteraction.Stop -> interactions.remove(interaction.start)
is DragInteraction.Cancel -> interactions.remove(interaction.start)
}
}
}
val elevation = if (interactions.isNotEmpty()) {
ThumbPressedElevation
} else {
ThumbDefaultElevation
}
val shape = SliderTokens.HandleShape.toShape()
Spacer(
modifier
.size(thumbSize)
.indication(
interactionSource = interactionSource,
indication = rememberRipple(
bounded = false,
radius = SliderTokens.StateLayerSize / 2
)
)
.hoverable(interactionSource = interactionSource)
.shadow(if (enabled) elevation else 0.dp, shape, clip = false)
.background(colors.thumbColor(enabled).value, shape)
)
}
}
@Composable
private fun Track(
modifier: Modifier,
colors: SliderColors,
enabled: Boolean,
positionFractionStart: Float,
positionFractionEnd: Float,
tickFractions: List<Float>,
thumbWidth: Dp,
trackStrokeWidth: Float
) {
val thumbRadiusPx: Float
val tickSize: Float
with(LocalDensity.current) {
thumbRadiusPx = thumbWidth.toPx() / 2
tickSize = TickSize.toPx()
}
val inactiveTrackColor = colors.trackColor(enabled, active = false)
val activeTrackColor = colors.trackColor(enabled, active = true)
val inactiveTickColor = colors.tickColor(enabled, active = false)
val activeTickColor = colors.tickColor(enabled, active = true)
Canvas(modifier) {
val isRtl = layoutDirection == LayoutDirection.Rtl
val sliderLeft = Offset(thumbRadiusPx, center.y)
val sliderRight = Offset(size.width - thumbRadiusPx, center.y)
val sliderStart = if (isRtl) sliderRight else sliderLeft
val sliderEnd = if (isRtl) sliderLeft else sliderRight
drawLine(
inactiveTrackColor.value,
sliderStart,
sliderEnd,
trackStrokeWidth,
StrokeCap.Round
)
val sliderValueEnd = Offset(
sliderStart.x + (sliderEnd.x - sliderStart.x) * positionFractionEnd,
center.y
)
val sliderValueStart = Offset(
sliderStart.x + (sliderEnd.x - sliderStart.x) * positionFractionStart,
center.y
)
drawLine(
activeTrackColor.value,
sliderValueStart,
sliderValueEnd,
trackStrokeWidth,
StrokeCap.Round
)
tickFractions.groupBy { it > positionFractionEnd || it < positionFractionStart }
.forEach { (outsideFraction, list) ->
drawPoints(
list.map {
Offset(lerp(sliderStart, sliderEnd, it).x, center.y)
},
PointMode.Points,
(if (outsideFraction) inactiveTickColor else activeTickColor).value,
tickSize,
StrokeCap.Round
)
}
}
}
private fun snapValueToTick(
current: Float,
tickFractions: List<Float>,
minPx: Float,
maxPx: Float
): Float {
// target is a closest anchor to the `current`, if exists
return tickFractions
.minByOrNull { abs(lerp(minPx, maxPx, it) - current) }
?.run { lerp(minPx, maxPx, this) }
?: current
}
private suspend fun AwaitPointerEventScope.awaitSlop(
id: PointerId,
type: PointerType
): Pair<PointerInputChange, Float>? {
var initialDelta = 0f
val postPointerSlop = { pointerInput: PointerInputChange, offset: Float ->
pointerInput.consume()
initialDelta = offset
}
val afterSlopResult = awaitHorizontalPointerSlopOrCancellation(id, type, postPointerSlop)
return if (afterSlopResult != null) afterSlopResult to initialDelta else null
}
private fun stepsToTickFractions(steps: Int): List<Float> {
return if (steps == 0) emptyList() else List(steps + 2) { it.toFloat() / (steps + 1) }
}
// Scale x1 from a1..b1 range to a2..b2 range
private fun scale(a1: Float, b1: Float, x1: Float, a2: Float, b2: Float) =
lerp(a2, b2, calcFraction(a1, b1, x1))
// Scale x.start, x.endInclusive from a1..b1 range to a2..b2 range
private fun scale(a1: Float, b1: Float, x: ClosedFloatingPointRange<Float>, a2: Float, b2: Float) =
scale(a1, b1, x.start, a2, b2)..scale(a1, b1, x.endInclusive, a2, b2)
// Calculate the 0..1 fraction that `pos` value represents between `a` and `b`
private fun calcFraction(a: Float, b: Float, pos: Float) =
(if (b - a == 0f) 0f else (pos - a) / (b - a)).coerceIn(0f, 1f)
private fun Modifier.sliderSemantics(
value: Float,
enabled: Boolean,
onValueChange: (Float) -> Unit,
onValueChangeFinished: (() -> Unit)? = null,
valueRange: ClosedFloatingPointRange<Float> = 0f..1f,
steps: Int = 0
): Modifier {
val coerced = value.coerceIn(valueRange.start, valueRange.endInclusive)
return semantics {
if (!enabled) disabled()
setProgress(
action = { targetValue ->
var newValue = targetValue.coerceIn(valueRange.start, valueRange.endInclusive)
val originalVal = newValue
val resolvedValue = if (steps > 0) {
var distance: Float = newValue
for (i in 0..steps + 1) {
val stepValue = lerp(
valueRange.start,
valueRange.endInclusive,
i.toFloat() / (steps + 1)
)
if (abs(stepValue - originalVal) <= distance) {
distance = abs(stepValue - originalVal)
newValue = stepValue
}
}
newValue
} else {
newValue
}
// This is to keep it consistent with AbsSeekbar.java: return false if no
// change from current.
if (resolvedValue == coerced) {
false
} else {
onValueChange(resolvedValue)
onValueChangeFinished?.invoke()
true
}
}
)
}.progressSemantics(value, valueRange, steps)
}
private fun Modifier.sliderTapModifier(
draggableState: DraggableState,
interactionSource: MutableInteractionSource,
maxPx: Float,
isRtl: Boolean,
rawOffset: State<Float>,
gestureEndAction: State<() -> Unit>,
pressOffset: MutableState<Float>,
enabled: Boolean
) = composed(
factory = {
if (enabled) {
val scope = rememberCoroutineScope()
pointerInput(draggableState, interactionSource, maxPx, isRtl) {
detectTapGestures(
onPress = { pos ->
val to = if (isRtl) maxPx - pos.x else pos.x
pressOffset.value = to - rawOffset.value
try {
awaitRelease()
} catch (_: GestureCancellationException) {
pressOffset.value = 0f
}
},
onTap = {
scope.launch {
draggableState.drag(MutatePriority.UserInput) {
// just trigger animation, press offset will be applied
dragBy(0f)
}
gestureEndAction.value.invoke()
}
}
)
}
} else {
this
}
},
inspectorInfo = debugInspectorInfo {
name = "sliderTapModifier"
properties["draggableState"] = draggableState
properties["interactionSource"] = interactionSource
properties["maxPx"] = maxPx
properties["isRtl"] = isRtl
properties["rawOffset"] = rawOffset
properties["gestureEndAction"] = gestureEndAction
properties["pressOffset"] = pressOffset
properties["enabled"] = enabled
})
private suspend fun animateToTarget(
draggableState: DraggableState,
current: Float,
target: Float,
velocity: Float
) {
draggableState.drag {
var latestValue = current
Animatable(initialValue = current).animateTo(target, SliderToTickAnimation, velocity) {
dragBy(this.value - latestValue)
latestValue = this.value
}
}
}
private fun Modifier.rangeSliderPressDragModifier(
startInteractionSource: MutableInteractionSource,
endInteractionSource: MutableInteractionSource,
rawOffsetStart: State<Float>,
rawOffsetEnd: State<Float>,
enabled: Boolean,
isRtl: Boolean,
maxPx: Float,
valueRange: ClosedFloatingPointRange<Float>,
gestureEndAction: State<(Boolean) -> Unit>,
onDrag: State<(Boolean, Float) -> Unit>,
): Modifier =
if (enabled) {
pointerInput(startInteractionSource, endInteractionSource, maxPx, isRtl, valueRange) {
val rangeSliderLogic = RangeSliderLogic(
startInteractionSource,
endInteractionSource,
rawOffsetStart,
rawOffsetEnd,
onDrag
)
coroutineScope {
forEachGesture {
awaitPointerEventScope {
val event = awaitFirstDown(requireUnconsumed = false)
val interaction = DragInteraction.Start()
var posX = if (isRtl) maxPx - event.position.x else event.position.x
val compare = rangeSliderLogic.compareOffsets(posX)
var draggingStart = if (compare != 0) {
compare < 0
} else {
rawOffsetStart.value > posX
}
awaitSlop(event.id, event.type)?.let {
val slop = viewConfiguration.pointerSlop(event.type)
val shouldUpdateCapturedThumb = abs(rawOffsetEnd.value - posX) < slop &&
abs(rawOffsetStart.value - posX) < slop
if (shouldUpdateCapturedThumb) {
val dir = it.second
draggingStart = if (isRtl) dir >= 0f else dir < 0f
posX += it.first.positionChange().x
}
}
rangeSliderLogic.captureThumb(
draggingStart,
posX,
interaction,
this@coroutineScope
)
val finishInteraction = try {
val success = horizontalDrag(pointerId = event.id) {
val deltaX = it.positionChange().x
onDrag.value.invoke(draggingStart, if (isRtl) -deltaX else deltaX)
}
if (success) {
DragInteraction.Stop(interaction)
} else {
DragInteraction.Cancel(interaction)
}
} catch (e: CancellationException) {
DragInteraction.Cancel(interaction)
}
gestureEndAction.value.invoke(draggingStart)
launch {
rangeSliderLogic
.activeInteraction(draggingStart)
.emit(finishInteraction)
}
}
}
}
}
} else {
this
}
private class RangeSliderLogic(
val startInteractionSource: MutableInteractionSource,
val endInteractionSource: MutableInteractionSource,
val rawOffsetStart: State<Float>,
val rawOffsetEnd: State<Float>,
val onDrag: State<(Boolean, Float) -> Unit>,
) {
fun activeInteraction(draggingStart: Boolean): MutableInteractionSource =
if (draggingStart) startInteractionSource else endInteractionSource
fun compareOffsets(eventX: Float): Int {
val diffStart = abs(rawOffsetStart.value - eventX)
val diffEnd = abs(rawOffsetEnd.value - eventX)
return diffStart.compareTo(diffEnd)
}
fun captureThumb(
draggingStart: Boolean,
posX: Float,