-
Notifications
You must be signed in to change notification settings - Fork 98
/
Drawer.kt
1231 lines (1168 loc) · 48.7 KB
/
Drawer.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
package com.microsoft.fluentui.tokenized.drawer
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.focusTarget
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.collapse
import androidx.compose.ui.semantics.dismiss
import androidx.compose.ui.semantics.expand
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import androidx.compose.ui.window.PopupProperties
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.core.view.WindowInsetsCompat
import com.microsoft.fluentui.compose.FixedThreshold
import com.microsoft.fluentui.compose.ModalPopup
import com.microsoft.fluentui.compose.NonDismissiblePostDownNestedScrollConnection
import com.microsoft.fluentui.compose.NonDismissiblePreUpPostDownNestedScrollConnection
import com.microsoft.fluentui.compose.PostDownNestedScrollConnection
import com.microsoft.fluentui.compose.PreUpPostDownNestedScrollConnection
import com.microsoft.fluentui.compose.SwipeableState
import com.microsoft.fluentui.compose.swipeable
import com.microsoft.fluentui.drawer.R
import com.microsoft.fluentui.theme.FluentTheme
import com.microsoft.fluentui.theme.token.ControlTokens
import com.microsoft.fluentui.theme.token.Icon
import com.microsoft.fluentui.theme.token.controlTokens.BehaviorType
import com.microsoft.fluentui.theme.token.controlTokens.DrawerInfo
import com.microsoft.fluentui.theme.token.controlTokens.DrawerTokens
import com.microsoft.fluentui.tokenized.calculateFraction
import com.microsoft.fluentui.util.dpToPx
import com.microsoft.fluentui.util.pxToDp
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Possible values of [DrawerState].
*/
enum class DrawerValue {
/**
* The state of the drawer when it is closed.
*/
Closed,
/**
* The state of the drawer when it is open.
*/
Open,
/**
* The state of the bottom drawer when it is expanded (i.e. at 100% height).
*/
Expanded
}
/**
* State of the [Drawer] composable.
*
* @param initialValue The initial value of the state.
* @param expandable defines if the drawer is allowed to take the Expanded state.
* @param skipOpenState defines if the drawer is allowed to take the Open state. (Open State is skipped in case of true)
* expandable = true & skipOpenState = false -> Drawer can take all the three states.
* expandable = true & skipOpenState = true -> Drawer can take only Closed & Expanded states.
* expandable = false & skipOpenState = false -> Drawer can take only Closed & Open states.
* expandable = false & skipOpenState = true -> Invalid state.
* @param confirmStateChange Optional callback invoked to confirm or veto a pending state change.
*/
class DrawerState(
private val initialValue: DrawerValue = DrawerValue.Closed,
internal val expandable: Boolean = true,
internal val skipOpenState: Boolean = false,
confirmStateChange: (DrawerValue) -> Boolean = { true }
) : SwipeableState<DrawerValue>(
initialValue = initialValue,
animationSpec = AnimationSpec,
confirmStateChange = confirmStateChange
) {
init {
if (skipOpenState) {
require(initialValue != DrawerValue.Open) {
"The initial value must not be set to Open if skipOpenState is set to" +
" true."
}
require(expandable) {
"Invalid state: expandable = false & skipOpenState = true"
}
}
if (!expandable) {
require(initialValue != DrawerValue.Expanded) {
"The initial value must not be set to Expanded if expandable is set to" +
" false."
}
}
}
var enable: Boolean by mutableStateOf(false)
/**
* Whether drawer has Open state.
* It is false in case of skipOpenState is true.
*/
internal val hasOpenedState: Boolean
get() = anchors.values.contains(DrawerValue.Open)
/**
* Whether the drawer is closed.
*/
val isClosed: Boolean
get() = currentValue == DrawerValue.Closed
/**
* Whether drawer has expanded state.
*/
internal val hasExpandedState: Boolean
get() = anchors.values.contains(DrawerValue.Expanded)
var animationInProgress: Boolean = false
/**
* 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() {
enable = true
animationInProgress = true
do {
delay(50)
} while (!anchorsFilled)
/*
* first try to open the drawer
* if not possible then try to expand the drawer
*/
var targetValue = when {
hasOpenedState -> DrawerValue.Open
hasExpandedState -> DrawerValue.Expanded
else -> DrawerValue.Closed
}
if (targetValue != currentValue) {
try {
animateTo(targetValue = targetValue, AnimationSpec)
} catch (e: Exception) {
//TODO: When previous instance of drawer changes its content & closed then on
// re-triggering the same drawer, it open but stuck to end of screen due to
// JobCancellationException thrown with message "ScopeCoroutine was cancelled".
// Hence re-triggering "animateTo". Check for better sol
animateTo(targetValue = targetValue, AnimationSpec)
} finally {
animationInProgress = false
}
} else {
animationInProgress = false
}
}
/**
* 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() {
animationInProgress = true
try {
animateTo(DrawerValue.Closed, AnimationSpec)
} catch (e: Exception) {
animateTo(DrawerValue.Closed, AnimationSpec)
} finally {
animationInProgress = false
enable = false
anchors = emptyMap()
anchorsFilled = false
}
}
/**
* Fully expand the drawer with animation and suspend until it if fully expanded or
* animation has been cancelled.
* *
* @throws [CancellationException] if the animation is interrupted
*/
suspend fun expand() {
enable = true
animationInProgress = true
do {
delay(50)
} while (!anchorsFilled)
/*
* first try to expand the drawer
* if not possible then try to open the drawer
*/
val targetValue = when {
hasExpandedState -> DrawerValue.Expanded
hasOpenedState -> DrawerValue.Open
else -> DrawerValue.Closed
}
if (targetValue != currentValue) {
try {
animateTo(targetValue = targetValue, AnimationSpec)
} catch (e: Exception) {
animateTo(targetValue = targetValue, AnimationSpec)
} finally {
animationInProgress = false
}
} else {
animationInProgress = false
}
}
val nestedScrollConnection = this.PreUpPostDownNestedScrollConnection
companion object {
/**
* The default [Saver] implementation for [DrawerState].
*/
fun Saver(
expandable: Boolean,
skipOpenState: Boolean,
confirmStateChange: (DrawerValue) -> Boolean
) =
Saver<DrawerState, DrawerValue>(
save = { it.currentValue },
restore = {
DrawerState(
initialValue = it,
expandable = expandable,
skipOpenState = skipOpenState,
confirmStateChange = confirmStateChange
)
}
)
/**
* The default [Saver] implementation for [DrawerState].
*/
@Deprecated(
message = "Please specify the expandable And/Or skipOpenState parameter",
replaceWith = ReplaceWith(
"DrawerState.Saver(" +
"expandable = ," +
"skipOpenState = ," +
"confirmStateChange = confirmStateChange" +
")"
)
)
fun Saver(confirmStateChange: (DrawerValue) -> Boolean): Saver<DrawerState, DrawerValue> =
Saver(expandable = true, skipOpenState = false, confirmStateChange = confirmStateChange)
}
}
/**
* Create and [remember] a [DrawerState].
* @param confirmStateChange Optional callback invoked to confirm or veto a pending state change.
*/
@Composable
fun rememberDrawerState(confirmStateChange: (DrawerValue) -> Boolean = { true }): DrawerState {
return rememberSaveable(
saver = DrawerState.Saver(
expandable = true,
skipOpenState = false,
confirmStateChange = confirmStateChange
)
) {
DrawerState(
initialValue = DrawerValue.Closed,
expandable = true,
skipOpenState = false,
confirmStateChange
)
}
}
@Composable
fun rememberBottomDrawerState(
expandable: Boolean = true,
skipOpenState: Boolean = false,
confirmStateChange: (DrawerValue) -> Boolean = { true }
): DrawerState {
return rememberSaveable(
confirmStateChange, expandable, skipOpenState,
saver = DrawerState.Saver(expandable, skipOpenState, confirmStateChange)
) {
DrawerState(DrawerValue.Closed, expandable, skipOpenState, confirmStateChange)
}
}
private class DrawerPositionProvider(val offset: IntOffset?) : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize
): IntOffset {
if (offset != null) {
return IntOffset(anchorBounds.left + offset.x, anchorBounds.top + offset.y)
}
return IntOffset(0, 0)
}
}
@Composable
private fun Scrim(
open: Boolean,
onClose: () -> Unit,
fraction: () -> Float,
color: Color,
preventDismissalOnScrimClick: Boolean = false,
onScrimClick: () -> Unit = {},
) {
val dismissDrawer = if (open) {
Modifier.pointerInput(onClose) {
detectTapGestures {
if (!preventDismissalOnScrimClick) {
onClose()
}
onScrimClick() //this function runs post onClose() so that the drawer is closed before the callback is invoked
}
}
} else {
Modifier
}
Canvas(
Modifier
.fillMaxSize()
.then(dismissDrawer)
.testTag(DRAWER_SCRIM_TAG)
) {
drawRect(color, alpha = fraction())
}
}
private val EndDrawerPadding = 56.dp
private val DrawerVelocityThreshold = 400.dp
private val AnimationSpec = TweenSpec<Float>(durationMillis = 256)
private const val DrawerOpenFraction = 0.5f
//Tag use for testing
const val DRAWER_HANDLE_TAG = "Fluent Drawer Handle"
const val DRAWER_CONTENT_TAG = "Fluent Drawer Content"
const val DRAWER_SCRIM_TAG = "Fluent Drawer Scrim"
//Drawer Handle height + padding
private val DrawerHandleHeightOffset = 20.dp
private fun Modifier.drawerHeight(
slideOver: Boolean,
fixedHeight: Float,
fullHeight: Float,
drawerState: DrawerState
): Modifier {
val modifier = if (slideOver) {
if (drawerState.expandable) {
Modifier
} else {
Modifier.heightIn(
0.dp,
pxToDp(fixedHeight)
)
}
} else {
Modifier.height(pxToDp(fullHeight - drawerState.offset.value))
}
return this.then(modifier)
}
private fun Modifier.bottomDrawerSwipeable(
drawerState: DrawerState,
slideOver: Boolean,
maxOpenHeight: Float,
fullHeight: Float,
drawerHeight: Float?
): Modifier {
val modifier = if (slideOver) {
if (drawerHeight != null) {
val minHeight = 0f
val bottomOpenStateY = max(maxOpenHeight, fullHeight - drawerHeight)
val bottomExpandedStateY = max(minHeight, fullHeight - drawerHeight)
val anchors =
if (drawerHeight <= maxOpenHeight) { // when contentHeight is less than maxOpenHeight
if (drawerState.anchors.containsValue(DrawerValue.Expanded)) {
/*
*For dynamic content when drawerHeight was previously greater than maxOpenHeight and now less than maxOpenHEight
*The old anchors won't have Open state, so we need to continue with Expanded state.
*/
mapOf(
bottomOpenStateY to DrawerValue.Expanded,
fullHeight to DrawerValue.Closed,
)
} else {
mapOf(
bottomOpenStateY to DrawerValue.Open,
fullHeight to DrawerValue.Closed
)
}
} else {
if (drawerState.expandable) {
if (drawerState.skipOpenState) {
if (drawerState.anchors.containsValue(DrawerValue.Open)) {
/*
*For dynamic content when drawerHeight was previously less than maxOpenHeight and now greater than maxOpenHEight
*The old anchors won't have Expanded state, so we need to continue with Open state.
*/
mapOf(
bottomExpandedStateY to DrawerValue.Open, // when drawerHeight is greater than maxOpenHeight but less than fullHeight, then Expanded state starts from fullHeight-drawerHeight
fullHeight to DrawerValue.Closed
)
} else {
mapOf(
bottomExpandedStateY to DrawerValue.Expanded, // when drawerHeight is greater than maxOpenHeight but less than fullHeight, then Expanded state starts from fullHeight-drawerHeight
fullHeight to DrawerValue.Closed,
)
}
} else {
mapOf(
maxOpenHeight to DrawerValue.Open,
bottomExpandedStateY to DrawerValue.Expanded,
fullHeight to DrawerValue.Closed
)
}
} else {
mapOf(
maxOpenHeight to DrawerValue.Open,
fullHeight to DrawerValue.Closed
)
}
}
Modifier.swipeable(
state = drawerState,
anchors = anchors,
orientation = Orientation.Vertical,
enabled = false,
resistance = null
)
} else {
Modifier
}
} else {
val anchors = if (drawerState.expandable) {
if (drawerState.skipOpenState) {
mapOf(
0F to DrawerValue.Expanded,
fullHeight to DrawerValue.Closed,
)
} else {
mapOf(
maxOpenHeight to DrawerValue.Open,
0F to DrawerValue.Expanded,
fullHeight to DrawerValue.Closed
)
}
} else {
mapOf(
maxOpenHeight to DrawerValue.Open,
fullHeight to DrawerValue.Closed
)
}
Modifier.swipeable(
state = drawerState,
anchors = anchors,
orientation = Orientation.Vertical,
enabled = false,
resistance = null
)
}
return this.then(modifier)
}
/**
*
*
* Side 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.
*
* @param drawerContent composable that represents content inside the drawer
* @param modifier optional modifier for the drawer
* @param drawerState state of the drawer
* @param drawerShape shape of the drawer sheet
* @param drawerElevation drawer sheet elevation. This controls the size of the shadow below the
* drawer sheet
* @param drawerBackground background color to be used for the drawer sheet
* @param scrimColor color of the scrim that obscures content when the drawer is open
* @param preventDismissalOnScrimClick when true, the drawer will not be dismissed when the scrim is clicked
* @param onScrimClick callback to be invoked when the scrim is clicked
*
* @throws IllegalStateException when parent has [Float.POSITIVE_INFINITY] width
*/
@Composable
private fun HorizontalDrawer(
modifier: Modifier,
behaviorType: BehaviorType,
drawerState: DrawerState,
drawerShape: Shape,
drawerElevation: Dp,
drawerBackground: Brush,
scrimColor: Color,
scrimVisible: Boolean,
onDismiss: () -> Unit,
drawerContent: @Composable () -> Unit,
preventDismissalOnScrimClick: Boolean = false,
onScrimClick: () -> Unit = {}
) {
BoxWithConstraints(modifier.fillMaxSize()) {
val modalDrawerConstraints = constraints
// TODO : think about Infinite max bounds case
if (!modalDrawerConstraints.hasBoundedWidth) {
throw IllegalStateException("Drawer shouldn't have infinite width")
}
val fullWidth = modalDrawerConstraints.maxWidth.toFloat()
var drawerWidth by remember(fullWidth) { mutableStateOf(fullWidth) }
//Hack to get exact drawerHeight wrt to content.
val visible = remember { mutableStateOf(true) }
if (visible.value) {
Box(
modifier = Modifier
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
drawerWidth = placeable.width.toFloat()
visible.value = false
}
}
) {
drawerContent()
}
} else {
val paddingPx = pxToDp(max(dpToPx(EndDrawerPadding), (fullWidth - drawerWidth)))
val leftSlide = behaviorType == BehaviorType.LEFT_SLIDE_OVER
val minValue =
modalDrawerConstraints.maxWidth.toFloat() * (if (leftSlide) (-1F) else (1F))
val maxValue = 0f
val anchors = mapOf(minValue to DrawerValue.Closed, maxValue to DrawerValue.Open)
val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
Scrim(
open = !drawerState.isClosed,
onClose = onDismiss,
fraction = {
calculateFraction(minValue, maxValue, drawerState.offset.value)
},
color = if (scrimVisible) scrimColor else Color.Transparent,
preventDismissalOnScrimClick = preventDismissalOnScrimClick,
onScrimClick = onScrimClick
)
Box(
modifier = with(LocalDensity.current) {
Modifier
.sizeIn(
minWidth = modalDrawerConstraints.minWidth.toDp(),
minHeight = modalDrawerConstraints.minHeight.toDp(),
maxWidth = modalDrawerConstraints.maxWidth.toDp(),
maxHeight = modalDrawerConstraints.maxHeight.toDp()
)
}
.offset { IntOffset(drawerState.offset.value.roundToInt(), 0) }
.padding(
start = if (leftSlide) 0.dp else paddingPx,
end = if (leftSlide) paddingPx else 0.dp
)
.semantics {
if (!drawerState.isClosed) {
dismiss {
onDismiss()
true
}
}
}
.shadow(drawerElevation)
.clip(drawerShape)
.background(drawerBackground)
.swipeable(
state = drawerState,
anchors = anchors,
thresholds = { _, _ -> FixedThreshold(pxToDp(value = drawerWidth / 2)) },
orientation = Orientation.Horizontal,
enabled = false,
reverseDirection = isRtl,
velocityThreshold = DrawerVelocityThreshold,
resistance = null
),
) {
Column(
Modifier
.draggable(
orientation = Orientation.Horizontal,
state = rememberDraggableState { delta ->
drawerState.performDrag(delta)
},
onDragStopped = { velocity ->
launch {
drawerState.performFling(
velocity
)
if (drawerState.isClosed) {
onDismiss()
}
}
},
)
.testTag(DRAWER_CONTENT_TAG), content = { drawerContent() })
}
}
}
}
@Composable
private fun TopDrawer(
modifier: Modifier,
drawerState: DrawerState,
drawerShape: Shape,
drawerElevation: Dp,
drawerBackground: Brush,
drawerHandleColor: Color,
scrimColor: Color,
scrimVisible: Boolean,
onDismiss: () -> Unit,
drawerContent: @Composable () -> Unit,
preventDismissalOnScrimClick: Boolean = false,
onScrimClick: () -> Unit = {}
) {
BoxWithConstraints(modifier.fillMaxSize()) {
val fullHeight = constraints.maxHeight.toFloat()
var drawerHeight by remember(fullHeight) { mutableStateOf(fullHeight) }
Box(
modifier = Modifier
.alpha(0f)
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
drawerHeight =
placeable.height.toFloat() + dpToPx(DrawerHandleHeightOffset)
}
}
) {
drawerContent()
}
val maxOpenHeight = fullHeight * DrawerOpenFraction
val minHeight = 0f
val topCloseHeight = minHeight
val topOpenHeight = min(maxOpenHeight, drawerHeight)
val minValue: Float = topCloseHeight
val maxValue: Float = topOpenHeight
val anchors = mapOf(
topCloseHeight to DrawerValue.Closed,
topOpenHeight to DrawerValue.Open
)
val drawerConstraints = with(LocalDensity.current) {
Modifier
.sizeIn(
maxWidth = constraints.maxWidth.toDp(),
maxHeight = constraints.maxHeight.toDp()
)
}
Scrim(
open = !drawerState.isClosed,
onClose = onDismiss,
fraction = {
calculateFraction(minValue, maxValue, drawerState.offset.value)
},
color = if (scrimVisible) scrimColor else Color.Transparent,
preventDismissalOnScrimClick = preventDismissalOnScrimClick,
onScrimClick = onScrimClick
)
Box(
drawerConstraints
.offset { IntOffset(0, 0) }
.semantics {
if (!drawerState.isClosed) {
dismiss {
onDismiss()
true
}
}
}
.height(
pxToDp(drawerState.offset.value)
)
.shadow(drawerElevation)
.clip(drawerShape)
.background(drawerBackground)
.swipeable(
state = drawerState,
anchors = anchors,
orientation = Orientation.Vertical,
enabled = false,
resistance = null
)
.focusable(false),
) {
ConstraintLayout(modifier = Modifier.padding(bottom = 8.dp)) {
val (drawerContentConstrain, drawerHandleConstrain) = createRefs()
Column(modifier = Modifier
.offset { IntOffset(0, 0) }
.padding(bottom = 8.dp)
.constrainAs(drawerContentConstrain) {
top.linkTo(parent.top)
bottom.linkTo(drawerHandleConstrain.top)
}
.focusTarget()
.testTag(DRAWER_CONTENT_TAG), content = { drawerContent() }
)
Column(horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.constrainAs(drawerHandleConstrain) {
top.linkTo(drawerContentConstrain.bottom)
bottom.linkTo(parent.bottom)
}
.fillMaxWidth()
.draggable(
orientation = Orientation.Vertical,
state = rememberDraggableState { delta ->
drawerState.performDrag(delta)
},
onDragStopped = { velocity ->
launch {
drawerState.performFling(
velocity
)
if (drawerState.isClosed) {
onDismiss()
}
}
},
)
.testTag(DRAWER_HANDLE_TAG)
) {
Icon(
painterResource(id = R.drawable.ic_drawer_handle),
contentDescription = null,
tint = drawerHandleColor
)
}
}
}
}
}
@Composable
private fun BottomDrawer(
modifier: Modifier,
drawerState: DrawerState,
drawerShape: Shape,
drawerElevation: Dp,
drawerBackground: Brush,
drawerHandleColor: Color,
scrimColor: Color,
scrimVisible: Boolean,
slideOver: Boolean,
enableSwipeDismiss: Boolean = true,
showHandle: Boolean,
onDismiss: () -> Unit,
drawerContent: @Composable () -> Unit,
preventDismissalOnScrimClick: Boolean = false,
onScrimClick: () -> Unit = {}
) {
BoxWithConstraints(modifier.fillMaxSize()) {
val fullHeight = constraints.maxHeight.toFloat()
val drawerHeight =
remember(drawerContent.hashCode()) { mutableStateOf<Float?>(null) }
val maxOpenHeight = fullHeight * DrawerOpenFraction
val drawerConstraints = with(LocalDensity.current) {
Modifier
.sizeIn(
maxWidth = constraints.maxWidth.toDp(),
maxHeight = constraints.maxHeight.toDp()
)
}
val scope = rememberCoroutineScope()
Scrim(
open = !drawerState.isClosed || (drawerHeight != null && drawerHeight.value == 0f),
onClose = onDismiss,
fraction = {
if (drawerState.anchors.isEmpty() || (drawerHeight != null && drawerHeight.value == 0f)) {
0.toFloat()
} else {
var targetValue: DrawerValue = if (slideOver) {
drawerState.anchors.maxBy { it.value }.value
} else if (drawerState.skipOpenState) {
DrawerValue.Expanded
} else {
DrawerValue.Open
}
calculateFraction(
drawerState.anchors.entries.firstOrNull { it.value == DrawerValue.Closed }?.key!!,
drawerState.anchors.entries.firstOrNull { it.value == targetValue }?.key!!,
drawerState.offset.value
)
}
},
color = if (scrimVisible) scrimColor else Color.Transparent,
preventDismissalOnScrimClick = preventDismissalOnScrimClick,
onScrimClick = onScrimClick
)
Box(
drawerConstraints
.fillMaxWidth()
.nestedScroll(
if(!enableSwipeDismiss && drawerState.offset.value >= maxOpenHeight) drawerState.NonDismissiblePreUpPostDownNestedScrollConnection else
if (slideOver) drawerState.nestedScrollConnection else drawerState.PostDownNestedScrollConnection)
.offset {
val y = if (drawerState.anchors == null) {
fullHeight.roundToInt()
} else {
drawerState.offset.value.roundToInt()
}
IntOffset(x = 0, y = y)
}
.onGloballyPositioned { layoutCoordinates ->
if (!drawerState.animationInProgress
&& drawerState.currentValue == DrawerValue.Closed
&& drawerState.targetValue == DrawerValue.Closed
) {
onDismiss()
}
if (slideOver) {
val originalSize = layoutCoordinates.size.height.toFloat()
drawerHeight.value = if (drawerState.expandable) {
originalSize
} else {
min(
originalSize,
maxOpenHeight
)
}
}
}
.bottomDrawerSwipeable(
drawerState,
slideOver,
maxOpenHeight,
fullHeight,
drawerHeight.value
)
.drawerHeight(
slideOver,
maxOpenHeight,
fullHeight,
drawerState
)
.shadow(drawerElevation)
.clip(drawerShape)
.background(drawerBackground)
.semantics {
if (!drawerState.isClosed) {
dismiss {
onDismiss()
true
}
if (drawerState.currentValue == DrawerValue.Open && drawerState.hasExpandedState) {
expand {
if (drawerState.confirmStateChange(DrawerValue.Expanded)) {
scope.launch { drawerState.expand() }
}
true
}
} else if (drawerState.hasExpandedState && drawerState.hasOpenedState) {
collapse {
if (drawerState.confirmStateChange(DrawerValue.Open)) {
scope.launch { drawerState.open() }
}
true
}
}
}
}
.focusable(false),
) {
Column {
if (showHandle) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth()
.draggable(
orientation = Orientation.Vertical,
state = rememberDraggableState { delta ->
if(!enableSwipeDismiss && drawerState.offset.value >= maxOpenHeight)
{
if(delta < 0){
drawerState.performDrag(delta)
}
}else {
drawerState.performDrag(delta)
}
},
onDragStopped = { velocity ->
launch {
drawerState.performFling(
velocity
)
if (drawerState.isClosed) {
if(enableSwipeDismiss)
onDismiss()
else
scope.launch { drawerState.open() }
}
}
},
)
.testTag(DRAWER_HANDLE_TAG)
) {
Icon(
painterResource(id = R.drawable.ic_drawer_handle),
contentDescription = LocalContext.current.resources.getString(R.string.drag_handle),
tint = drawerHandleColor,
modifier = Modifier
.clickable(
enabled = drawerState.hasExpandedState,
role = Role.Button,
onClickLabel =
if (drawerState.currentValue == DrawerValue.Expanded) {
LocalContext.current.resources.getString(R.string.collapse)
} else {
if (drawerState.hasExpandedState && !drawerState.isClosed) LocalContext.current.resources.getString(
R.string.expand
) else null
}
) {
if (drawerState.currentValue == DrawerValue.Expanded) {
if (drawerState.hasOpenedState && drawerState.confirmStateChange(
DrawerValue.Open
)