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
/
Switch.kt
500 lines (468 loc) · 21 KB
/
Switch.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
/*
* 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.background
import androidx.compose.foundation.border
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.tokens.SwitchTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import kotlinx.coroutines.launch
/**
* <a href="https://m3.material.io/components/switch" class="external" target="_blank">Material Design Switch</a>.
*
* Switches toggle the state of a single item on or off.
*
* ![Switch image](https://developer.android.com/images/reference/androidx/compose/material3/switch.png)
*
* @sample androidx.compose.material3.samples.SwitchSample
*
* Switch can be used with a custom icon via [thumbContent] parameter
*
* @sample androidx.compose.material3.samples.SwitchWithThumbIconSample
*
* @param checked whether or not this switch is checked
* @param onCheckedChange called when this switch is clicked. If `null`, then this switch will not
* be interactable, unless something else handles its input events and updates its state.
* @param modifier the [Modifier] to be applied to this switch
* @param thumbContent content that will be drawn inside the thumb, expected to measure
* [SwitchDefaults.IconSize]
* @param enabled controls the enabled state of this switch. When `false`, this component will not
* respond to user input, and it will appear visually disabled and disabled to accessibility
* services.
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this switch. You can create and pass in your own `remember`ed instance to observe
* [Interaction]s and customize the appearance / behavior of this switch in different states.
* @param colors [SwitchColors] that will be used to resolve the colors used for this switch in
* different states. See [SwitchDefaults.colors].
*/
@Composable
@Suppress("ComposableLambdaParameterNaming", "ComposableLambdaParameterPosition")
fun Switch(
checked: Boolean,
onCheckedChange: ((Boolean) -> Unit)?,
modifier: Modifier = Modifier,
thumbContent: (@Composable () -> Unit)? = null,
enabled: Boolean = true,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
colors: SwitchColors = SwitchDefaults.colors(),
) {
val uncheckedThumbDiameter = if (thumbContent == null) {
UncheckedThumbDiameter
} else {
ThumbDiameter
}
val thumbPaddingStart = (SwitchHeight - uncheckedThumbDiameter) / 2
val minBound = with(LocalDensity.current) { thumbPaddingStart.toPx() }
val maxBound = with(LocalDensity.current) { ThumbPathLength.toPx() }
val valueToOffset = remember<(Boolean) -> Float>(minBound, maxBound) {
{ value -> if (value) maxBound else minBound }
}
val targetValue = valueToOffset(checked)
val offset = remember { Animatable(targetValue) }
val scope = rememberCoroutineScope()
SideEffect {
// min bound might have changed if the icon is only rendered in checked state.
offset.updateBounds(lowerBound = minBound)
}
DisposableEffect(checked) {
if (offset.targetValue != targetValue) {
scope.launch {
offset.animateTo(targetValue)
}
}
onDispose { }
}
// TODO: Add Swipeable modifier b/223797571
val toggleableModifier =
if (onCheckedChange != null) {
Modifier.toggleable(
value = checked,
onValueChange = { value: Boolean ->
onCheckedChange(value)
scope.launch {
offset.animateTo(valueToOffset(value), AnimationSpec)
}
},
enabled = enabled,
role = Role.Switch,
interactionSource = interactionSource,
indication = null
)
} else {
Modifier
}
Box(
modifier
.then(
if (onCheckedChange != null) Modifier.minimumTouchTargetSize() else Modifier
)
.then(toggleableModifier)
.wrapContentSize(Alignment.Center)
.requiredSize(SwitchWidth, SwitchHeight)
) {
SwitchImpl(
checked = checked,
enabled = enabled,
colors = colors,
thumbValue = offset.asState(),
interactionSource = interactionSource,
thumbShape = SwitchTokens.HandleShape.toShape(),
uncheckedThumbDiameter = uncheckedThumbDiameter,
minBound = thumbPaddingStart,
maxBound = ThumbPathLength,
thumbContent = thumbContent,
)
}
}
/**
* Represents the colors used by a [Switch] in different states
*
* See [SwitchDefaults.colors] for the default implementation that follows Material
* specifications.
*/
@Stable
interface SwitchColors {
/**
* Represents the color used for the switch's thumb, depending on [enabled] and [checked].
*
* @param enabled whether the [Switch] is enabled or not
* @param checked whether the [Switch] is checked or not
*/
@Composable
fun thumbColor(enabled: Boolean, checked: Boolean): State<Color>
/**
* Represents the color used for the switch's track, depending on [enabled] and [checked].
*
* @param enabled whether the [Switch] is enabled or not
* @param checked whether the [Switch] is checked or not
*/
@Composable
fun trackColor(enabled: Boolean, checked: Boolean): State<Color>
/**
* Represents the color used for the switch's border, depending on [enabled] and [checked].
*
* @param enabled whether the [Switch] is enabled or not
* @param checked whether the [Switch] is checked or not
*/
@Composable
fun borderColor(enabled: Boolean, checked: Boolean): State<Color>
/**
* Represents the content color passed to the icon if used
*
* @param enabled whether the [Switch] is enabled or not
* @param checked whether the [Switch] is checked or not
*/
@Composable
fun iconColor(enabled: Boolean, checked: Boolean): State<Color>
}
@Composable
@Suppress("ComposableLambdaParameterNaming", "ComposableLambdaParameterPosition")
private fun BoxScope.SwitchImpl(
checked: Boolean,
enabled: Boolean,
colors: SwitchColors,
thumbValue: State<Float>,
thumbContent: (@Composable () -> Unit)?,
interactionSource: InteractionSource,
thumbShape: Shape,
uncheckedThumbDiameter: Dp,
minBound: Dp,
maxBound: Dp,
) {
val trackColor by colors.trackColor(enabled, checked)
val isPressed by interactionSource.collectIsPressedAsState()
val thumbValueDp = with(LocalDensity.current) { thumbValue.value.toDp() }
val thumbSizeDp = if (isPressed) {
SwitchTokens.PressedHandleWidth
} else {
uncheckedThumbDiameter + (ThumbDiameter - uncheckedThumbDiameter) *
((thumbValueDp - minBound) / (maxBound - minBound))
}
val thumbOffset = if (isPressed) {
with(LocalDensity.current) {
if (checked) {
ThumbPathLength - SwitchTokens.TrackOutlineWidth
} else {
SwitchTokens.TrackOutlineWidth
}.toPx()
}
} else {
thumbValue.value
}
val trackShape = SwitchTokens.TrackShape.toShape()
val modifier = Modifier
.align(Alignment.Center)
.width(SwitchWidth)
.height(SwitchHeight)
.border(
SwitchTokens.TrackOutlineWidth,
colors.borderColor(enabled, checked).value,
trackShape
)
.background(trackColor, trackShape)
Box(modifier) {
val thumbColor by colors.thumbColor(enabled, checked)
val resolvedThumbColor = thumbColor
Box(
modifier = Modifier
.align(Alignment.CenterStart)
.offset { IntOffset(thumbOffset.roundToInt(), 0) }
.indication(
interactionSource = interactionSource,
indication = rememberRipple(bounded = false, SwitchTokens.StateLayerSize / 2)
)
.requiredSize(thumbSizeDp)
.background(resolvedThumbColor, thumbShape),
contentAlignment = Alignment.Center
) {
if (thumbContent != null) {
val iconColor = colors.iconColor(enabled, checked)
CompositionLocalProvider(
LocalContentColor provides iconColor.value,
content = thumbContent
)
}
}
}
}
internal val ThumbDiameter = SwitchTokens.SelectedHandleWidth
internal val UncheckedThumbDiameter = SwitchTokens.UnselectedHandleWidth
private val SwitchWidth = SwitchTokens.TrackWidth
private val SwitchHeight = SwitchTokens.TrackHeight
private val ThumbPadding = (SwitchHeight - ThumbDiameter) / 2
private val ThumbPathLength = (SwitchWidth - ThumbDiameter) - ThumbPadding
private val AnimationSpec = TweenSpec<Float>(durationMillis = 100)
/**
* Contains the default values used by [Switch]
*/
object SwitchDefaults {
/**
* Creates a [SwitchColors] that represents the different colors used in a [Switch] in
* different states.
*
* @param checkedThumbColor the color used for the thumb when enabled and checked
* @param checkedTrackColor the color used for the track when enabled and checked
* @param checkedBorderColor the color used for the border when enabled and checked
* @param checkedIconColor the color used for the icon when enabled and checked
* @param uncheckedThumbColor the color used for the thumb when enabled and unchecked
* @param uncheckedTrackColor the color used for the track when enabled and unchecked
* @param uncheckedBorderColor the color used for the border when enabled and unchecked
* @param uncheckedIconColor the color used for the icon when enabled and unchecked
* @param disabledCheckedThumbColor the color used for the thumb when disabled and checked
* @param disabledCheckedTrackColor the color used for the track when disabled and checked
* @param disabledCheckedBorderColor the color used for the border when disabled and checked
* @param disabledCheckedIconColor the color used for the icon when disabled and checked
* @param disabledUncheckedThumbColor the color used for the thumb when disabled and unchecked
* @param disabledUncheckedTrackColor the color used for the track when disabled and unchecked
* @param disabledUncheckedBorderColor the color used for the border when disabled and unchecked
* @param disabledUncheckedIconColor the color used for the icon when disabled and unchecked
*/
@Composable
fun colors(
checkedThumbColor: Color = SwitchTokens.SelectedHandleColor.toColor(),
checkedTrackColor: Color = SwitchTokens.SelectedTrackColor.toColor(),
checkedBorderColor: Color = Color.Transparent,
checkedIconColor: Color = SwitchTokens.SelectedIconColor.toColor(),
uncheckedThumbColor: Color = SwitchTokens.UnselectedHandleColor.toColor(),
uncheckedTrackColor: Color = SwitchTokens.UnselectedTrackColor.toColor(),
uncheckedBorderColor: Color = SwitchTokens.UnselectedFocusTrackOutlineColor.toColor(),
uncheckedIconColor: Color = SwitchTokens.UnselectedIconColor.toColor(),
disabledCheckedThumbColor: Color = SwitchTokens.DisabledSelectedHandleColor.toColor()
.copy(alpha = SwitchTokens.DisabledSelectedHandleOpacity)
.compositeOver(MaterialTheme.colorScheme.surface),
disabledCheckedTrackColor: Color = SwitchTokens.DisabledSelectedTrackColor.toColor()
.copy(alpha = SwitchTokens.DisabledTrackOpacity)
.compositeOver(MaterialTheme.colorScheme.surface),
disabledCheckedBorderColor: Color = Color.Transparent,
disabledCheckedIconColor: Color = SwitchTokens.DisabledSelectedIconColor.toColor()
.copy(alpha = SwitchTokens.DisabledSelectedIconOpacity)
.compositeOver(MaterialTheme.colorScheme.surface),
disabledUncheckedThumbColor: Color = SwitchTokens.DisabledUnselectedHandleColor.toColor()
.copy(alpha = SwitchTokens.DisabledUnselectedHandleOpacity)
.compositeOver(MaterialTheme.colorScheme.surface),
disabledUncheckedTrackColor: Color = SwitchTokens.DisabledUnselectedTrackColor.toColor()
.copy(alpha = SwitchTokens.DisabledTrackOpacity)
.compositeOver(MaterialTheme.colorScheme.surface),
disabledUncheckedBorderColor: Color =
SwitchTokens.DisabledUnselectedTrackOutlineColor.toColor()
.copy(alpha = SwitchTokens.DisabledTrackOpacity)
.compositeOver(MaterialTheme.colorScheme.surface),
disabledUncheckedIconColor: Color = SwitchTokens.DisabledUnselectedIconColor.toColor()
.copy(alpha = SwitchTokens.DisabledUnselectedIconOpacity)
.compositeOver(MaterialTheme.colorScheme.surface),
): SwitchColors = DefaultSwitchColors(
checkedThumbColor = checkedThumbColor,
checkedTrackColor = checkedTrackColor,
checkedBorderColor = checkedBorderColor,
checkedIconColor = checkedIconColor,
uncheckedThumbColor = uncheckedThumbColor,
uncheckedTrackColor = uncheckedTrackColor,
uncheckedBorderColor = uncheckedBorderColor,
uncheckedIconColor = uncheckedIconColor,
disabledCheckedThumbColor = disabledCheckedThumbColor,
disabledCheckedTrackColor = disabledCheckedTrackColor,
disabledCheckedBorderColor = disabledCheckedBorderColor,
disabledCheckedIconColor = disabledCheckedIconColor,
disabledUncheckedThumbColor = disabledUncheckedThumbColor,
disabledUncheckedTrackColor = disabledUncheckedTrackColor,
disabledUncheckedBorderColor = disabledUncheckedBorderColor,
disabledUncheckedIconColor = disabledUncheckedIconColor
)
/**
* Icon size to use for `thumbContent`
*/
val IconSize = 16.dp
}
/**
* Default [SwitchColors] implementation.
*/
@Immutable
private class DefaultSwitchColors(
private val checkedThumbColor: Color,
private val checkedTrackColor: Color,
private val checkedBorderColor: Color,
private val checkedIconColor: Color,
private val uncheckedThumbColor: Color,
private val uncheckedTrackColor: Color,
private val uncheckedBorderColor: Color,
private val uncheckedIconColor: Color,
private val disabledCheckedThumbColor: Color,
private val disabledCheckedTrackColor: Color,
private val disabledCheckedBorderColor: Color,
private val disabledCheckedIconColor: Color,
private val disabledUncheckedThumbColor: Color,
private val disabledUncheckedTrackColor: Color,
private val disabledUncheckedBorderColor: Color,
private val disabledUncheckedIconColor: Color
) : SwitchColors {
@Composable
override fun thumbColor(enabled: Boolean, checked: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (checked) checkedThumbColor else uncheckedThumbColor
} else {
if (checked) disabledCheckedThumbColor else disabledUncheckedThumbColor
}
)
}
@Composable
override fun trackColor(enabled: Boolean, checked: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (checked) checkedTrackColor else uncheckedTrackColor
} else {
if (checked) disabledCheckedTrackColor else disabledUncheckedTrackColor
}
)
}
@Composable
override fun borderColor(enabled: Boolean, checked: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (checked) checkedBorderColor else uncheckedBorderColor
} else {
if (checked) disabledCheckedBorderColor else disabledUncheckedBorderColor
}
)
}
@Composable
override fun iconColor(enabled: Boolean, checked: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (checked) checkedIconColor else uncheckedIconColor
} else {
if (checked) disabledCheckedIconColor else disabledUncheckedIconColor
}
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as DefaultSwitchColors
if (checkedThumbColor != other.checkedThumbColor) return false
if (checkedTrackColor != other.checkedTrackColor) return false
if (checkedBorderColor != other.checkedBorderColor) return false
if (checkedIconColor != other.checkedIconColor) return false
if (uncheckedThumbColor != other.uncheckedThumbColor) return false
if (uncheckedTrackColor != other.uncheckedTrackColor) return false
if (uncheckedBorderColor != other.uncheckedBorderColor) return false
if (uncheckedIconColor != other.uncheckedIconColor) return false
if (disabledCheckedThumbColor != other.disabledCheckedThumbColor) return false
if (disabledCheckedTrackColor != other.disabledCheckedTrackColor) return false
if (disabledCheckedBorderColor != other.disabledCheckedBorderColor) return false
if (disabledCheckedIconColor != other.disabledCheckedIconColor) return false
if (disabledUncheckedThumbColor != other.disabledUncheckedThumbColor) return false
if (disabledUncheckedTrackColor != other.disabledUncheckedTrackColor) return false
if (disabledUncheckedBorderColor != other.disabledUncheckedBorderColor) return false
if (disabledUncheckedIconColor != other.disabledUncheckedIconColor) return false
return true
}
override fun hashCode(): Int {
var result = checkedThumbColor.hashCode()
result = 31 * result + checkedTrackColor.hashCode()
result = 31 * result + checkedBorderColor.hashCode()
result = 31 * result + checkedIconColor.hashCode()
result = 31 * result + uncheckedThumbColor.hashCode()
result = 31 * result + uncheckedTrackColor.hashCode()
result = 31 * result + uncheckedBorderColor.hashCode()
result = 31 * result + uncheckedIconColor.hashCode()
result = 31 * result + disabledCheckedThumbColor.hashCode()
result = 31 * result + disabledCheckedTrackColor.hashCode()
result = 31 * result + disabledCheckedBorderColor.hashCode()
result = 31 * result + disabledCheckedIconColor.hashCode()
result = 31 * result + disabledUncheckedThumbColor.hashCode()
result = 31 * result + disabledUncheckedTrackColor.hashCode()
result = 31 * result + disabledUncheckedBorderColor.hashCode()
result = 31 * result + disabledUncheckedIconColor.hashCode()
return result
}
}