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
/
Copy pathNavigationDrawer.kt
825 lines (775 loc) · 31.9 KB
/
NavigationDrawer.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
/*
* Copyright 2021 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.AnimationSpec
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.width
import androidx.compose.material3.tokens.NavigationDrawerTokens
import androidx.compose.material3.tokens.PaletteTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.dismiss
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.paneTitle
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
/**
* Possible values of [DrawerState].
*/
@ExperimentalMaterial3Api
enum class DrawerValue {
/**
* The state of the drawer when it is closed.
*/
Closed,
/**
* The state of the drawer when it is open.
*/
Open
}
/**
* State of the [ModalNavigationDrawer] and [DismissibleNavigationDrawer] composable.
*
* @param initialValue The initial value of the state.
* @param confirmStateChange Optional callback invoked to confirm or veto a pending state change.
*/
@Suppress("NotCloseable")
@ExperimentalMaterial3Api
@Stable
class DrawerState(
initialValue: DrawerValue,
confirmStateChange: (DrawerValue) -> Boolean = { true }
) {
internal val swipeableState = SwipeableState(
initialValue = initialValue,
animationSpec = AnimationSpec,
confirmStateChange = confirmStateChange
)
/**
* Whether the drawer is open.
*/
val isOpen: Boolean
get() = currentValue == DrawerValue.Open
/**
* Whether the drawer is closed.
*/
val isClosed: Boolean
get() = currentValue == DrawerValue.Closed
/**
* The current value of the state.
*
* If no swipe or animation is in progress, this corresponds to the start the drawer
* currently in. If a swipe or an animation is in progress, this corresponds the state drawer
* was in before the swipe or animation started.
*/
val currentValue: DrawerValue
get() {
return swipeableState.currentValue
}
/**
* Whether the state is currently animating.
*/
val isAnimationRunning: Boolean
get() {
return swipeableState.isAnimationRunning
}
/**
* Open the drawer with animation and suspend until it if fully opened or animation has been
* cancelled. This method will throw [CancellationException] if the animation is
* interrupted
*
* @return the reason the open animation ended
*/
suspend fun open() = animateTo(DrawerValue.Open, AnimationSpec)
/**
* Close the drawer with animation and suspend until it if fully closed or animation has been
* cancelled. This method will throw [CancellationException] if the animation is
* interrupted
*
* @return the reason the close animation ended
*/
suspend fun close() = animateTo(DrawerValue.Closed, AnimationSpec)
/**
* Set the state of the drawer with specific animation
*
* @param targetValue The new value to animate to.
* @param anim The animation that will be used to animate to the new value.
*/
@ExperimentalMaterial3Api
suspend fun animateTo(targetValue: DrawerValue, anim: AnimationSpec<Float>) {
swipeableState.animateTo(targetValue, anim)
}
/**
* Set the state without any animation and suspend until it's set
*
* @param targetValue The new target value
*/
@ExperimentalMaterial3Api
suspend fun snapTo(targetValue: DrawerValue) {
swipeableState.snapTo(targetValue)
}
/**
* The target value of the drawer state.
*
* If a swipe is in progress, this is the value that the Drawer would animate to if the
* swipe finishes. If an animation is running, this is the target value of that animation.
* Finally, if no swipe or animation is in progress, this is the same as the [currentValue].
*/
@Suppress("OPT_IN_MARKER_ON_WRONG_TARGET")
@ExperimentalMaterial3Api
@get:ExperimentalMaterial3Api
val targetValue: DrawerValue
get() = swipeableState.targetValue
/**
* The current position (in pixels) of the drawer container.
*/
@Suppress("OPT_IN_MARKER_ON_WRONG_TARGET")
@ExperimentalMaterial3Api
@get:ExperimentalMaterial3Api
val offset: State<Float>
get() = swipeableState.offset
companion object {
/**
* The default [Saver] implementation for [DrawerState].
*/
fun Saver(confirmStateChange: (DrawerValue) -> Boolean) =
Saver<DrawerState, DrawerValue>(
save = { it.currentValue },
restore = { DrawerState(it, confirmStateChange) }
)
}
}
/**
* Create and [remember] a [DrawerState].
*
* @param initialValue The initial value of the state.
* @param confirmStateChange Optional callback invoked to confirm or veto a pending state change.
*/
@Composable
@ExperimentalMaterial3Api
fun rememberDrawerState(
initialValue: DrawerValue,
confirmStateChange: (DrawerValue) -> Boolean = { true }
): DrawerState {
return rememberSaveable(saver = DrawerState.Saver(confirmStateChange)) {
DrawerState(initialValue, confirmStateChange)
}
}
/**
* <a href="https://m3.material.io/components/navigation-drawer/overview" class="external" target="_blank">Material Design navigation drawer</a>.
*
* Navigation drawers provide ergonomic access to destinations in an app.
*
* Modal navigation drawers block interaction with the rest of an app’s content with a scrim.
* They are elevated above most of the app’s UI and don’t affect the screen’s layout grid.
*
* ![Navigation drawer image](https://developer.android.com/images/reference/androidx/compose/material3/navigation-drawer.png)
*
* @sample androidx.compose.material3.samples.ModalNavigationDrawerSample
*
* @param drawerContent content inside this drawer
* @param modifier the [Modifier] to be applied to this drawer
* @param drawerState state of the drawer
* @param gesturesEnabled whether or not the drawer can be interacted by gestures
* @param drawerShape defines the shape of this drawer's container
* @param drawerTonalElevation when [drawerContainerColor] is [ColorScheme.surface], a translucent
* primary color overlay is applied on top of the container. A higher tonal elevation value will
* result in a darker color in light theme and lighter color in dark theme. See also: [Surface].
* @param drawerContainerColor the color used for the background of this drawer. Use
* [Color.Transparent] to have no color.
* @param drawerContentColor the preferred color for content inside this drawer. Defaults to either
* the matching content color for [drawerContainerColor], or to the current [LocalContentColor] if
* [drawerContainerColor] is not a color from the theme.
* @param scrimColor color of the scrim that obscures content when the drawer is open
* @param content content of the rest of the UI
*/
@Composable
@ExperimentalMaterial3Api
fun ModalNavigationDrawer(
drawerContent: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier,
drawerState: DrawerState = rememberDrawerState(DrawerValue.Closed),
gesturesEnabled: Boolean = true,
drawerShape: Shape = DrawerDefaults.Shape,
drawerTonalElevation: Dp = DrawerDefaults.ModalDrawerElevation,
drawerContainerColor: Color = DrawerDefaults.ContainerColor,
drawerContentColor: Color = contentColorFor(drawerContainerColor),
scrimColor: Color = DrawerDefaults.ScrimColor,
content: @Composable () -> Unit
) {
val scope = rememberCoroutineScope()
val minValue = -with(LocalDensity.current) { NavigationDrawerTokens.ContainerWidth.toPx() }
val maxValue = 0f
val anchors = mapOf(minValue to DrawerValue.Closed, maxValue to DrawerValue.Open)
val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
Box(
modifier.fillMaxSize().swipeable(
state = drawerState.swipeableState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.5f) },
orientation = Orientation.Horizontal,
enabled = gesturesEnabled,
reverseDirection = isRtl,
velocityThreshold = DrawerVelocityThreshold,
resistance = null
)
) {
Box {
content()
}
Scrim(
open = drawerState.isOpen,
onClose = {
if (
gesturesEnabled &&
drawerState.swipeableState.confirmStateChange(DrawerValue.Closed)
) {
scope.launch { drawerState.close() }
}
},
fraction = {
calculateFraction(minValue, maxValue, drawerState.offset.value)
},
color = scrimColor
)
val navigationMenu = getString(Strings.NavigationMenu)
Surface(
modifier = Modifier
.sizeIn(maxWidth = NavigationDrawerTokens.ContainerWidth)
.offset { IntOffset(drawerState.offset.value.roundToInt(), 0) }
.semantics {
paneTitle = navigationMenu
if (drawerState.isOpen) {
dismiss {
if (
drawerState.swipeableState
.confirmStateChange(DrawerValue.Closed)
) {
scope.launch { drawerState.close() }
}; true
}
}
},
shape = drawerShape,
color = drawerContainerColor,
contentColor = drawerContentColor,
tonalElevation = drawerTonalElevation
) {
Column(Modifier.fillMaxSize(), content = drawerContent)
}
}
}
@Composable
@ExperimentalMaterial3Api
@Deprecated(
"NavigationDrawer has been renamed to ModalNavigationDrawer to better specify " +
"its modal nature", replaceWith = ReplaceWith(
"ModalNavigationDrawer(drawerContent,\n" +
" modifier,\n" +
" drawerState,\n" +
" gesturesEnabled,\n" +
" drawerShape,\n" +
" drawerTonalElevation,\n" +
" drawerContainerColor,\n" +
" drawerContentColor,\n" +
" scrimColor,\n" +
" content)"
)
)
fun NavigationDrawer(
drawerContent: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier,
drawerState: DrawerState = rememberDrawerState(DrawerValue.Closed),
gesturesEnabled: Boolean = true,
drawerShape: Shape = DrawerDefaults.Shape,
drawerTonalElevation: Dp = DrawerDefaults.ModalDrawerElevation,
drawerContainerColor: Color = DrawerDefaults.ContainerColor,
drawerContentColor: Color = contentColorFor(drawerContainerColor),
scrimColor: Color = DrawerDefaults.ScrimColor,
content: @Composable () -> Unit
) {
ModalNavigationDrawer(
drawerContent,
modifier,
drawerState,
gesturesEnabled,
drawerShape,
drawerTonalElevation,
drawerContainerColor,
drawerContentColor,
scrimColor,
content
)
}
/**
* <a href="https://m3.material.io/components/navigation-drawer/overview" class="external" target="_blank">Material Design navigation drawer</a>.
*
* Navigation drawers provide ergonomic access to destinations in an app. They’re often next to
* app content and affect the screen’s layout grid.
*
* ![Navigation drawer image](https://developer.android.com/images/reference/androidx/compose/material3/navigation-drawer.png)
*
* Dismissible standard drawers can be used for layouts that prioritize content (such as a
* photo gallery) or for apps where users are unlikely to switch destinations often. They should
* use a visible navigation menu icon to open and close the drawer.
*
* @sample androidx.compose.material3.samples.DismissibleNavigationDrawerSample
*
* @param drawerContent content inside this drawer
* @param modifier the [Modifier] to be applied to this drawer
* @param drawerState state of the drawer
* @param gesturesEnabled whether or not the drawer can be interacted by gestures
* @param drawerShape defines the shape of this drawer's container
* @param drawerTonalElevation when [drawerContainerColor] is [ColorScheme.surface], a translucent
* primary color overlay is applied on top of the container. A higher tonal elevation value will
* result in a darker color in light theme and lighter color in dark theme. See also: [Surface].
* @param drawerContainerColor the color used for the background of this drawer. Use
* [Color.Transparent] to have no color.
* @param drawerContentColor the preferred color for content inside this drawer. Defaults to either
* the matching content color for [drawerContainerColor], or to the current [LocalContentColor] if
* [drawerContainerColor] is not a color from the theme.
* @param content content of the rest of the UI
*/
@Composable
@ExperimentalMaterial3Api
fun DismissibleNavigationDrawer(
drawerContent: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier,
drawerState: DrawerState = rememberDrawerState(DrawerValue.Closed),
gesturesEnabled: Boolean = true,
drawerShape: Shape = RectangleShape,
drawerTonalElevation: Dp = DrawerDefaults.DismissibleDrawerElevation,
drawerContainerColor: Color = MaterialTheme.colorScheme.surface,
drawerContentColor: Color = contentColorFor(drawerContainerColor),
content: @Composable () -> Unit
) {
val scope = rememberCoroutineScope()
val drawerWidth = NavigationDrawerTokens.ContainerWidth
val drawerWidthPx = with(LocalDensity.current) { drawerWidth.toPx() }
val minValue = -drawerWidthPx
val maxValue = 0f
val anchors = mapOf(minValue to DrawerValue.Closed, maxValue to DrawerValue.Open)
val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
Box(
modifier.swipeable(
state = drawerState.swipeableState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.5f) },
orientation = Orientation.Horizontal,
enabled = gesturesEnabled,
reverseDirection = isRtl,
velocityThreshold = DrawerVelocityThreshold,
resistance = null
)
) {
Layout(content = {
val navigationMenu = getString(Strings.NavigationMenu)
Surface(
modifier = Modifier
.sizeIn(maxWidth = drawerWidth)
.semantics {
paneTitle = navigationMenu
if (drawerState.isOpen) {
dismiss {
if (
drawerState.swipeableState
.confirmStateChange(DrawerValue.Closed)
) {
scope.launch { drawerState.close() }
}; true
}
}
},
shape = drawerShape,
color = drawerContainerColor,
contentColor = drawerContentColor,
tonalElevation = drawerTonalElevation
) {
Column(Modifier.fillMaxSize(), content = drawerContent)
}
Box {
content()
}
}) { measurables, constraints ->
val sheetPlaceable = measurables[0].measure(constraints)
val contentPlaceable = measurables[1].measure(constraints)
layout(contentPlaceable.width, contentPlaceable.height) {
contentPlaceable.placeRelative(
sheetPlaceable.width + drawerState.offset.value.roundToInt(),
0
)
sheetPlaceable.placeRelative(drawerState.offset.value.roundToInt(), 0)
}
}
}
}
/**
* <a href="https://m3.material.io/components/navigation-drawer/overview" class="external" target="_blank">Material Design navigation permanent drawer</a>.
*
* Navigation drawers provide ergonomic access to destinations in an app. They’re often next to app
* content and affect the screen’s layout grid.
*
* ![Navigation drawer image](https://developer.android.com/images/reference/androidx/compose/material3/navigation-drawer.png)
*
* The permanent navigation drawer is always visible and usually used for frequently switching
* destinations. On mobile screens, use [ModalNavigationDrawer] instead.
*
* @sample androidx.compose.material3.samples.PermanentNavigationDrawerSample
*
* @param drawerContent content inside this drawer
* @param modifier the [Modifier] to be applied to this drawer
* @param drawerShape defines the shape of this drawer's container
* @param drawerTonalElevation when [drawerContainerColor] is [ColorScheme.surface], a translucent
* primary color overlay is applied on top of the container. A higher tonal elevation value will
* result in a darker color in light theme and lighter color in dark theme. See also: [Surface].
* @param drawerContainerColor the color used for the background of this drawer. Use
* [Color.Transparent] to have no color.
* @param drawerContentColor the preferred color for content inside this drawer. Defaults to either
* the matching content color for [drawerContainerColor], or to the current [LocalContentColor] if
* [drawerContainerColor] is not a color from the theme.
* @param content content of the rest of the UI
*/
@ExperimentalMaterial3Api
@Composable
fun PermanentNavigationDrawer(
drawerContent: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier,
drawerShape: Shape = RectangleShape,
drawerTonalElevation: Dp = DrawerDefaults.PermanentDrawerElevation,
drawerContainerColor: Color = MaterialTheme.colorScheme.surface,
drawerContentColor: Color = contentColorFor(drawerContainerColor),
content: @Composable () -> Unit
) {
val drawerWidth = NavigationDrawerTokens.ContainerWidth
Row(modifier.fillMaxSize()) {
val navigationMenu = getString(Strings.NavigationMenu)
Surface(
modifier = Modifier
.sizeIn(maxWidth = drawerWidth)
.semantics {
paneTitle = navigationMenu
},
shape = drawerShape,
color = drawerContainerColor,
contentColor = drawerContentColor,
tonalElevation = drawerTonalElevation
) {
Column(Modifier.fillMaxSize(), content = drawerContent)
}
Box {
content()
}
}
}
/**
* Object to hold default values for [ModalNavigationDrawer]
*/
@ExperimentalMaterial3Api
object DrawerDefaults {
/** Default shape for a navigation drawer. */
val Shape: Shape @Composable get() = NavigationDrawerTokens.ContainerShape.toShape()
/**
* Default Elevation for drawer container in the [ModalNavigationDrawer] as specified in the
* Material specification.
*/
val ModalDrawerElevation = NavigationDrawerTokens.ModalContainerElevation
/**
* Default Elevation for drawer container in the [PermanentNavigationDrawer] as specified in the
* Material specification.
*/
val PermanentDrawerElevation = NavigationDrawerTokens.StandardContainerElevation
/**
* Default Elevation for drawer container in the [DismissibleNavigationDrawer] as specified in
* the Material specification.
*/
val DismissibleDrawerElevation = NavigationDrawerTokens.StandardContainerElevation
/** Default color of the scrim that obscures content when the drawer is open */
val ScrimColor: Color
@Composable
get() = PaletteTokens.NeutralVariant0.copy(alpha = NavigationDrawerTokens.ScrimOpacity)
/** Default container color for a navigation drawer */
val ContainerColor: Color @Composable get() = NavigationDrawerTokens.ContainerColor.toColor()
}
/**
* Material Design navigation drawer item.
*
* A [NavigationDrawerItem] represents a destination within drawers, either [ModalNavigationDrawer],
* [PermanentNavigationDrawer] or [DismissibleNavigationDrawer].
*
* @sample androidx.compose.material3.samples.ModalNavigationDrawerSample
*
* @param label text label for this item
* @param selected whether this item is selected
* @param onClick called when this item is clicked
* @param modifier the [Modifier] to be applied to this item
* @param icon optional icon for this item, typically an [Icon]
* @param badge optional badge to show on this item from the end side
* @param colors [NavigationDrawerItemColors] that will be used to resolve the colors used for this
* item in different states. See [NavigationDrawerItemDefaults.colors].
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this item. You can create and pass in your own `remember`ed instance to observe
* [Interaction]s and customize the appearance / behavior of this item in different states.
*/
@Composable
@ExperimentalMaterial3Api
fun NavigationDrawerItem(
label: @Composable () -> Unit,
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
icon: (@Composable () -> Unit)? = null,
badge: (@Composable () -> Unit)? = null,
shape: Shape = NavigationDrawerTokens.ActiveIndicatorShape.toShape(),
colors: NavigationDrawerItemColors = NavigationDrawerItemDefaults.colors(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
) {
Surface(
selected = selected,
onClick = onClick,
modifier = modifier
.height(NavigationDrawerTokens.ActiveIndicatorHeight)
.fillMaxWidth(),
shape = shape,
color = colors.containerColor(selected).value,
interactionSource = interactionSource,
) {
Row(
Modifier.padding(start = 16.dp, end = 24.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (icon != null) {
val iconColor = colors.iconColor(selected).value
CompositionLocalProvider(LocalContentColor provides iconColor, content = icon)
Spacer(Modifier.width(12.dp))
}
Box(Modifier.weight(1f)) {
val labelColor = colors.textColor(selected).value
CompositionLocalProvider(LocalContentColor provides labelColor, content = label)
}
if (badge != null) {
Spacer(Modifier.width(12.dp))
val badgeColor = colors.badgeColor(selected).value
CompositionLocalProvider(LocalContentColor provides badgeColor, content = badge)
}
}
}
}
/** Represents the colors of the various elements of a drawer item. */
@Stable
@ExperimentalMaterial3Api
interface NavigationDrawerItemColors {
/**
* Represents the icon color for this item, depending on whether it is [selected].
*
* @param selected whether the item is selected
*/
@Composable
fun iconColor(selected: Boolean): State<Color>
/**
* Represents the text color for this item, depending on whether it is [selected].
*
* @param selected whether the item is selected
*/
@Composable
fun textColor(selected: Boolean): State<Color>
/**
* Represents the badge color for this item, depending on whether it is [selected].
*
* @param selected whether the item is selected
*/
@Composable
fun badgeColor(selected: Boolean): State<Color>
/**
* Represents the container color for this item, depending on whether it is [selected].
*
* @param selected whether the item is selected
*/
@Composable
fun containerColor(selected: Boolean): State<Color>
}
/** Defaults used in [NavigationDrawerItem]. */
@ExperimentalMaterial3Api
object NavigationDrawerItemDefaults {
/**
* Creates a [NavigationDrawerItemColors] with the provided colors according to the Material
* specification.
*
* @param selectedContainerColor the color to use for the background of the item when selected
* @param unselectedContainerColor the color to use for the background of the item when
* unselected
* @param selectedIconColor the color to use for the icon when the item is selected.
* @param unselectedIconColor the color to use for the icon when the item is unselected.
* @param selectedTextColor the color to use for the text label when the item is selected.
* @param unselectedTextColor the color to use for the text label when the item is unselected.
* @param selectedBadgeColor the color to use for the badge when the item is selected.
* @param unselectedBadgeColor the color to use for the badge when the item is unselected.
*
* @return the resulting [NavigationDrawerItemColors] used for [NavigationDrawerItem]
*/
@Composable
fun colors(
selectedContainerColor: Color = NavigationDrawerTokens.ActiveIndicatorColor.toColor(),
unselectedContainerColor: Color = NavigationDrawerTokens.ContainerColor.toColor(),
selectedIconColor: Color = NavigationDrawerTokens.ActiveIconColor.toColor(),
unselectedIconColor: Color = NavigationDrawerTokens.InactiveIconColor.toColor(),
selectedTextColor: Color = NavigationDrawerTokens.ActiveLabelTextColor.toColor(),
unselectedTextColor: Color = NavigationDrawerTokens.InactiveLabelTextColor.toColor(),
selectedBadgeColor: Color = selectedTextColor,
unselectedBadgeColor: Color = unselectedTextColor,
): NavigationDrawerItemColors = DefaultDrawerItemsColor(
selectedIconColor,
unselectedIconColor,
selectedTextColor,
unselectedTextColor,
selectedContainerColor,
unselectedContainerColor,
selectedBadgeColor,
unselectedBadgeColor
)
/**
* Default external padding for a [NavigationDrawerItem] according to the Material
* specification.
*/
val ItemPadding = PaddingValues(horizontal = 12.dp)
}
@OptIn(ExperimentalMaterial3Api::class)
private class DefaultDrawerItemsColor(
val selectedIconColor: Color,
val unselectedIconColor: Color,
val selectedTextColor: Color,
val unselectedTextColor: Color,
val selectedContainerColor: Color,
val unselectedContainerColor: Color,
val selectedBadgeColor: Color,
val unselectedBadgeColor: Color
) : NavigationDrawerItemColors {
@Composable
override fun iconColor(selected: Boolean): State<Color> {
return rememberUpdatedState(if (selected) selectedIconColor else unselectedIconColor)
}
@Composable
override fun textColor(selected: Boolean): State<Color> {
return rememberUpdatedState(if (selected) selectedTextColor else unselectedTextColor)
}
@Composable
override fun containerColor(selected: Boolean): State<Color> {
return rememberUpdatedState(
if (selected) selectedContainerColor else unselectedContainerColor
)
}
@Composable
override fun badgeColor(selected: Boolean): State<Color> {
return rememberUpdatedState(
if (selected) selectedBadgeColor else unselectedBadgeColor
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is DefaultDrawerItemsColor) return false
if (selectedIconColor != other.selectedIconColor) return false
if (unselectedIconColor != other.unselectedIconColor) return false
if (selectedTextColor != other.selectedTextColor) return false
if (unselectedTextColor != other.unselectedTextColor) return false
if (selectedContainerColor != other.selectedContainerColor) return false
if (unselectedContainerColor != other.unselectedContainerColor) return false
if (selectedBadgeColor != other.selectedBadgeColor) return false
if (unselectedBadgeColor != other.unselectedBadgeColor) return false
return true
}
override fun hashCode(): Int {
var result = selectedIconColor.hashCode()
result = 31 * result + unselectedIconColor.hashCode()
result = 31 * result + selectedTextColor.hashCode()
result = 31 * result + unselectedTextColor.hashCode()
result = 31 * result + selectedContainerColor.hashCode()
result = 31 * result + unselectedContainerColor.hashCode()
result = 31 * result + selectedBadgeColor.hashCode()
result = 31 * result + unselectedBadgeColor.hashCode()
return result
}
}
private fun calculateFraction(a: Float, b: Float, pos: Float) =
((pos - a) / (b - a)).coerceIn(0f, 1f)
@Composable
private fun Scrim(
open: Boolean,
onClose: () -> Unit,
fraction: () -> Float,
color: Color
) {
val closeDrawer = getString(Strings.CloseDrawer)
val dismissDrawer = if (open) {
Modifier
.pointerInput(onClose) { detectTapGestures { onClose() } }
.semantics(mergeDescendants = true) {
contentDescription = closeDrawer
onClick { onClose(); true }
}
} else {
Modifier
}
Canvas(
Modifier
.fillMaxSize()
.then(dismissDrawer)
) {
drawRect(color, alpha = fraction())
}
}
private val DrawerVelocityThreshold = 400.dp
// TODO: b/177571613 this should be a proper decay settling
// this is taken from the DrawerLayout's DragViewHelper as a min duration.
private val AnimationSpec = TweenSpec<Float>(durationMillis = 256)