-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathTrueSheetViewController.kt
More file actions
1148 lines (939 loc) · 37.9 KB
/
TrueSheetViewController.kt
File metadata and controls
1148 lines (939 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.lodev09.truesheet
import android.annotation.SuppressLint
import android.os.Build
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityNodeInfo
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.isNotEmpty
import androidx.core.view.isVisible
import com.facebook.react.R
import com.facebook.react.uimanager.JSPointerDispatcher
import com.facebook.react.uimanager.JSTouchDispatcher
import com.facebook.react.uimanager.PixelUtil.dpToPx
import com.facebook.react.uimanager.PixelUtil.pxToDp
import com.facebook.react.uimanager.RootView
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.events.EventDispatcher
import com.facebook.react.util.RNLog
import com.facebook.react.views.view.ReactViewGroup
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.lodev09.truesheet.core.GrabberOptions
import com.lodev09.truesheet.core.RNScreensFragmentObserver
import com.lodev09.truesheet.core.TrueSheetBottomSheetView
import com.lodev09.truesheet.core.TrueSheetBottomSheetViewDelegate
import com.lodev09.truesheet.core.TrueSheetCoordinatorLayout
import com.lodev09.truesheet.core.TrueSheetCoordinatorLayoutDelegate
import com.lodev09.truesheet.core.TrueSheetDetentCalculator
import com.lodev09.truesheet.core.TrueSheetDetentCalculatorDelegate
import com.lodev09.truesheet.core.TrueSheetDimView
import com.lodev09.truesheet.core.TrueSheetDimViewDelegate
import com.lodev09.truesheet.core.TrueSheetKeyboardObserver
import com.lodev09.truesheet.core.TrueSheetKeyboardObserverDelegate
import com.lodev09.truesheet.core.TrueSheetStackManager
import com.lodev09.truesheet.utils.KeyboardUtils
import com.lodev09.truesheet.utils.ScreenUtils
// =============================================================================
// MARK: - Data Types & Delegate Protocol
// =============================================================================
data class DetentInfo(val index: Int, val position: Float)
interface TrueSheetViewControllerDelegate {
fun viewControllerWillPresent(index: Int, position: Float, detent: Float)
fun viewControllerDidPresent(index: Int, position: Float, detent: Float)
fun viewControllerWillDismiss()
fun viewControllerDidDismiss(hadParent: Boolean)
fun viewControllerDidChangeDetent(index: Int, position: Float, detent: Float)
fun viewControllerDidDragBegin(index: Int, position: Float, detent: Float)
fun viewControllerDidDragChange(index: Int, position: Float, detent: Float)
fun viewControllerDidDragEnd(index: Int, position: Float, detent: Float)
fun viewControllerDidChangePosition(index: Float, position: Float, detent: Float, realtime: Boolean)
fun viewControllerDidChangeSize(width: Int, height: Int)
fun viewControllerWillFocus()
fun viewControllerDidFocus()
fun viewControllerWillBlur()
fun viewControllerDidBlur()
fun viewControllerDidBackPress()
}
// =============================================================================
// MARK: - TrueSheetViewController
// =============================================================================
/**
* Controls the presentation and behavior of a bottom sheet.
*
* Uses CoordinatorLayout with BottomSheetBehavior to manage the sheet within the activity window,
* enabling touch pass-through to underlying views. Handles detent configuration, drag interactions,
* keyboard avoidance, dimmed backgrounds, back button, and lifecycle events for stacked sheets.
*/
@SuppressLint("ClickableViewAccessibility", "ViewConstructor")
class TrueSheetViewController(private val reactContext: ThemedReactContext) :
ReactViewGroup(reactContext),
RootView,
TrueSheetDetentCalculatorDelegate,
TrueSheetDimViewDelegate,
TrueSheetCoordinatorLayoutDelegate,
TrueSheetBottomSheetViewDelegate {
companion object {
const val TAG_NAME = "TrueSheet"
private const val DEFAULT_MAX_WIDTH = 640 // dp
private const val DEFAULT_CORNER_RADIUS = 16 // dp
private const val TRANSLATE_ANIMATION_DURATION = 200L
private const val DISMISS_DURATION = 200L
private const val MODAL_FADE_DURATION = 150L
}
// =============================================================================
// MARK: - Types
// =============================================================================
private sealed class InteractionState {
data object Idle : InteractionState()
data class Dragging(val startTop: Int) : InteractionState()
data object Reconfiguring : InteractionState()
}
// =============================================================================
// MARK: - Properties
// =============================================================================
var delegate: TrueSheetViewControllerDelegate? = null
// CoordinatorLayout components (replaces DialogFragment)
internal var sheetView: TrueSheetBottomSheetView? = null
internal var coordinatorLayout: TrueSheetCoordinatorLayout? = null
private var dimView: TrueSheetDimView? = null
private var parentDimView: TrueSheetDimView? = null
// Back button handling
private var backCallback: OnBackPressedCallback? = null
// Presentation State
var isPresented = false
private set
var isSheetVisible = false
private set
var currentDetentIndex: Int = -1
private set
private var interactionState: InteractionState = InteractionState.Idle
private var isDismissing = false
private var wasHiddenByModal = false
private var shouldAnimatePresent = false
private var isPresentAnimating = false
private var lastStateWidth: Int = 0
private var lastStateHeight: Int = 0
private var lastEmittedPositionPx: Int = -1
// Keyboard State
private var detentIndexBeforeKeyboard: Int = -1
// Promises
var presentPromise: (() -> Unit)? = null
var dismissPromise: (() -> Unit)? = null
// For stacked sheets
var parentSheetView: TrueSheetView? = null
// Helper Objects
private var keyboardObserver: TrueSheetKeyboardObserver? = null
private var rnScreensObserver: RNScreensFragmentObserver? = null
internal val detentCalculator = TrueSheetDetentCalculator(reactContext).apply {
delegate = this@TrueSheetViewController
}
// Touch Dispatchers
internal var eventDispatcher: EventDispatcher? = null
private val jsTouchDispatcher = JSTouchDispatcher(this)
private var jsPointerDispatcher: JSPointerDispatcher? = null
// Detent Configuration
override var maxSheetHeight: Int? = null
override var detents: MutableList<Double> = mutableListOf(0.5, 1.0)
// Appearance Configuration
var dimmed = true
var dimmedDetentIndex = 0
override var grabber: Boolean = true
override var grabberOptions: GrabberOptions? = null
override var sheetBackgroundColor: Int? = null
var insetAdjustment: String = "automatic"
var scrollable: Boolean = false
set(value) {
field = value
coordinatorLayout?.scrollable = value
}
override var sheetCornerRadius: Float = DEFAULT_CORNER_RADIUS.dpToPx()
set(value) {
field = if (value < 0) DEFAULT_CORNER_RADIUS.dpToPx() else value
if (isPresented) sheetView?.setupBackground()
}
override var sheetElevation: Float = -1f
set(value) {
field = value
if (isPresented) sheetView?.setupElevation()
}
var dismissible: Boolean = true
set(value) {
field = value
behavior?.isHideable = value
}
var draggable: Boolean = true
set(value) {
field = value
behavior?.isDraggable = value
if (isPresented) sheetView?.setupGrabber()
}
val isDimmedAtCurrentDetent: Boolean
get() = dimmed && currentDetentIndex >= dimmedDetentIndex
// =============================================================================
// MARK: - Computed Properties
// =============================================================================
// Behavior
private val behavior: BottomSheetBehavior<TrueSheetBottomSheetView>?
get() = sheetView?.behavior
private val containerView: TrueSheetContainerView?
get() = if (this.isNotEmpty()) getChildAt(0) as? TrueSheetContainerView else null
// Screen Measurements
override val screenHeight: Int
get() = ScreenUtils.getScreenHeight(reactContext)
val screenWidth: Int
get() = ScreenUtils.getScreenWidth(reactContext)
// Includes system bars for accurate positioning
override val realScreenHeight: Int
get() = ScreenUtils.getRealScreenHeight(reactContext)
// Content Measurements
override val contentHeight: Int
get() = containerView?.contentHeight ?: 0
override val headerHeight: Int
get() = containerView?.headerHeight ?: 0
// Insets
// Target keyboard height used for detent calculations
override val keyboardInset: Int
get() = keyboardObserver?.targetHeight ?: 0
// Current animated keyboard height for positioning
private val currentKeyboardInset: Int
get() = keyboardObserver?.currentHeight ?: 0
private val isKeyboardTransitioning: Boolean
get() = keyboardObserver?.isTransitioning ?: false
private fun isFocusedViewWithinSheet(): Boolean {
val sheet = sheetView ?: return false
return keyboardObserver?.isFocusedViewWithinSheet(sheet) ?: false
}
val bottomInset: Int
get() = if (edgeToEdgeEnabled) ScreenUtils.getInsets(reactContext).bottom else 0
val topInset: Int
get() = if (edgeToEdgeEnabled) ScreenUtils.getInsets(reactContext).top else 0
override val contentBottomInset: Int
get() = if (insetAdjustment == "automatic") bottomInset else 0
private val edgeToEdgeEnabled: Boolean
get() {
val defaultEnabled = android.os.Build.VERSION.SDK_INT >= 36
return BuildConfig.EDGE_TO_EDGE_ENABLED || defaultEnabled
}
// Sheet State
val isExpanded: Boolean
get() {
val sheetTop = sheetView?.top ?: return false
return sheetTop <= topInset
}
val currentTranslationY: Int
get() = sheetView?.translationY?.toInt() ?: 0
override val isTopmostSheet: Boolean
get() {
val hostView = delegate as? TrueSheetView ?: return true
return TrueSheetStackManager.isTopmostSheet(hostView)
}
private val dimViews: List<TrueSheetDimView>
get() = listOfNotNull(dimView, parentDimView)
// =============================================================================
// MARK: - Initialization
// =============================================================================
init {
jsPointerDispatcher = JSPointerDispatcher(this)
}
// =============================================================================
// MARK: - Sheet Creation & Cleanup
// =============================================================================
fun createSheet() {
if (coordinatorLayout != null) return
// Create coordinator layout
coordinatorLayout = TrueSheetCoordinatorLayout(reactContext).apply {
delegate = this@TrueSheetViewController
scrollable = this@TrueSheetViewController.scrollable
}
sheetView = TrueSheetBottomSheetView(reactContext).apply {
delegate = this@TrueSheetViewController
}
}
private fun cleanupSheet() {
cleanupKeyboardObserver()
cleanupModalObserver()
cleanupBackCallback()
sheetView?.animate()?.cancel()
// Cleanup dim views
dimView?.detach()
dimView = null
parentDimView?.detach()
parentDimView = null
// Detach content from sheet
sheetView?.removeView(this)
coordinatorLayout = null
sheetView = null
interactionState = InteractionState.Idle
isDismissing = false
isPresented = false
isSheetVisible = false
wasHiddenByModal = false
isPresentAnimating = false
lastEmittedPositionPx = -1
detentIndexBeforeKeyboard = -1
shouldAnimatePresent = true
}
// =============================================================================
// MARK: - Back Button Handling
// =============================================================================
private fun setupBackCallback() {
val activity = reactContext.currentActivity as? AppCompatActivity ?: return
backCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
delegate?.viewControllerDidBackPress()
dismissOrCollapseToLowest()
}
}
activity.onBackPressedDispatcher.addCallback(backCallback!!)
}
private fun cleanupBackCallback() {
backCallback?.remove()
backCallback = null
}
// =============================================================================
// MARK: - TrueSheetCoordinatorLayout.Delegate
// =============================================================================
override fun coordinatorLayoutDidLayout(changed: Boolean) {
// Reposition footer when layout changes
if (isPresented && changed) {
positionFooter()
}
}
// =============================================================================
// MARK: - TrueSheetDimViewDelegate
// =============================================================================
override fun dimViewDidTap() {
val hostView = delegate as? TrueSheetView ?: return
val children = TrueSheetStackManager.getSheetsAbove(hostView)
val topmostChild = children.firstOrNull()?.viewController
// If topmost child is dimmed, only handle that child
if (topmostChild?.isDimmedAtCurrentDetent == true) {
if (topmostChild.dismissible) {
topmostChild.dismiss(animated = true)
}
return
}
// Pass through to parent - dismiss all if possible
val allDismissible = dismissible && children.all { it.viewController.dismissible }
if (allDismissible) {
children.forEach { it.viewController.dismiss(animated = true) }
}
dismissOrCollapseToLowest()
}
// =============================================================================
// MARK: - BottomSheetCallback
// =============================================================================
private val sheetCallback = object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(sheetView: View, newState: Int) {
handleStateChanged(sheetView, newState)
}
override fun onSlide(sheetView: View, slideOffset: Float) {
handleSlide(sheetView, slideOffset)
}
}
private fun handleStateChanged(sheetView: View, newState: Int) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
if (isDismissing) return
isDismissing = true
dismissKeyboard()
emitWillDismissEvents()
finishDismiss()
return
}
if (!isPresented) return
when (newState) {
BottomSheetBehavior.STATE_DRAGGING -> handleDragBegin(sheetView)
BottomSheetBehavior.STATE_EXPANDED,
BottomSheetBehavior.STATE_COLLAPSED,
BottomSheetBehavior.STATE_HALF_EXPANDED -> handleStateSettled(sheetView, newState)
else -> {}
}
}
private fun handleSlide(sheetView: View, slideOffset: Float) {
// Skip during dismiss animation
if (isDismissing) return
val behavior = behavior ?: return
when (behavior.state) {
BottomSheetBehavior.STATE_DRAGGING,
BottomSheetBehavior.STATE_SETTLING -> handleDragChange(sheetView)
else -> { }
}
emitChangePositionDelegate(sheetView.top)
// On older APIs, use onSlide for footer positioning during keyboard transitions
val useLegacyKeyboardHandling = Build.VERSION.SDK_INT < Build.VERSION_CODES.R
if (!isKeyboardTransitioning || useLegacyKeyboardHandling) {
positionFooter(slideOffset)
}
if (!isKeyboardTransitioning) {
updateDimAmount(sheetView.top)
}
}
private fun handleStateSettled(sheetView: View, newState: Int) {
if (interactionState is InteractionState.Reconfiguring) return
val index = detentCalculator.getDetentIndexForState(newState) ?: return
val position = getPositionDpForView(sheetView)
val detentInfo = DetentInfo(index, position)
// Handle present animation completion
if (isPresentAnimating) {
isPresentAnimating = false
finishPresent()
return
}
when (interactionState) {
is InteractionState.Dragging -> {
val detent = detentCalculator.getDetentValueForIndex(detentInfo.index)
delegate?.viewControllerDidDragEnd(detentInfo.index, detentInfo.position, detent)
if (detentInfo.index != currentDetentIndex) {
currentDetentIndex = detentInfo.index
setupDimmedBackground(detentInfo.index)
delegate?.viewControllerDidChangeDetent(detentInfo.index, detentInfo.position, detent)
}
interactionState = InteractionState.Idle
}
else -> {
if (detentInfo.index != currentDetentIndex) {
currentDetentIndex = detentInfo.index
if (!isKeyboardTransitioning) {
val detent = detentCalculator.getDetentValueForIndex(detentInfo.index)
delegate?.viewControllerDidChangeDetent(detentInfo.index, detentInfo.position, detent)
}
}
}
}
}
// =============================================================================
// MARK: - Modal Observer (react-native-screens)
// =============================================================================
private fun setupModalObserver() {
rnScreensObserver = RNScreensFragmentObserver(
reactContext = reactContext,
onModalPresented = {
if (isPresented && isSheetVisible && isTopmostSheet) {
hideForModal()
}
},
onModalWillDismiss = {
if (isPresented && wasHiddenByModal && isTopmostSheet) {
showAfterModal()
}
},
onModalDidDismiss = {
if (isPresented && wasHiddenByModal) {
wasHiddenByModal = false
// Restore parent sheet after this sheet is restored
parentSheetView?.viewController?.let { parent ->
post { parent.showAfterModal() }
}
}
}
)
rnScreensObserver?.start()
}
private fun cleanupModalObserver() {
rnScreensObserver?.stop()
rnScreensObserver = null
}
private fun setSheetVisibility(visible: Boolean) {
coordinatorLayout?.visibility = if (visible) VISIBLE else GONE
dimViews.forEach { it.visibility = if (visible) VISIBLE else INVISIBLE }
}
private fun hideForModal() {
val sheet = sheetView ?: run {
RNLog.e(reactContext, "TrueSheet: sheetView is null in hideForModal")
return
}
isSheetVisible = false
wasHiddenByModal = true
dimViews.forEach { it.animate().alpha(0f).setDuration(MODAL_FADE_DURATION).start() }
sheet.animate()
.alpha(0f)
.setDuration(MODAL_FADE_DURATION)
.withEndAction {
setSheetVisibility(false)
}
.start()
// This will hide parent sheets first
parentSheetView?.viewController?.hideForModal()
}
private fun showAfterModal() {
isSheetVisible = true
setSheetVisibility(true)
sheetView?.alpha = 1f
updateDimAmount(animated = true)
}
/**
* Re-applies hidden state after returning from background.
* Android may restore visibility on activity resume, so we need to hide it again.
*/
fun reapplyHiddenState() {
if (!wasHiddenByModal) return
setSheetVisibility(false)
}
// =============================================================================
// MARK: - Presentation
// =============================================================================
fun present(detentIndex: Int, animated: Boolean = true) {
val coordinator = this.coordinatorLayout ?: run {
RNLog.w(reactContext, "TrueSheet: No coordinator layout available. Ensure the sheet is mounted before presenting.")
return
}
val sheet = this.sheetView ?: run {
RNLog.w(reactContext, "TrueSheet: No sheet view available.")
return
}
if (isPresented) {
setupDimmedBackground(detentIndex)
setStateForDetentIndex(detentIndex)
} else {
shouldAnimatePresent = animated
currentDetentIndex = detentIndex
interactionState = InteractionState.Idle
// Setup sheet in coordinator layout
setupSheetInCoordinator(coordinator, sheet)
emitWillPresentEvents()
setupSheetDetents()
setupDimmedBackground(currentDetentIndex)
setupKeyboardObserver()
setupModalObserver()
setupBackCallback()
sheet.setupBackground()
sheet.setupElevation()
sheet.setupGrabber()
if (shouldAnimatePresent) {
isPresentAnimating = true
post { setStateForDetentIndex(currentDetentIndex) }
} else {
setStateForDetentIndex(currentDetentIndex)
emitChangePositionDelegate(detentCalculator.getSheetTopForDetentIndex(currentDetentIndex))
updateDimAmount()
finishPresent()
}
isPresented = true
isSheetVisible = true
}
}
private fun setupSheetInCoordinator(coordinator: TrueSheetCoordinatorLayout, sheet: TrueSheetBottomSheetView) {
// Add this controller as content to the sheet
(parent as? ViewGroup)?.removeView(this)
sheet.addView(this)
// Create layout params with behavior
val params = sheet.createLayoutParams()
val behavior = params.behavior as BottomSheetBehavior<TrueSheetBottomSheetView>
// Configure behavior
behavior.isHideable = true
behavior.isDraggable = draggable
behavior.state = BottomSheetBehavior.STATE_HIDDEN
behavior.addBottomSheetCallback(sheetCallback)
// Add sheet to coordinator
coordinator.addView(sheet, params)
}
fun dismiss(animated: Boolean = true) {
if (isDismissing) return
isDismissing = true
dismissKeyboard()
emitWillDismissEvents()
if (animated) {
animateDismiss()
} else {
emitChangePositionDelegate(realScreenHeight)
finishDismiss()
}
}
private fun dismissKeyboard() {
KeyboardUtils.dismiss(reactContext)
}
private fun dismissOrCollapseToLowest() {
if (dismissible) {
dismiss(animated = true)
} else if (parentSheetView == null && isDimmedAtCurrentDetent && dimmedDetentIndex > 0) {
setStateForDetentIndex(dimmedDetentIndex - 1)
}
}
private fun animateDismiss() {
val sheet = sheetView ?: run {
finishDismiss()
return
}
sheet.animate()
.y(realScreenHeight.toFloat())
.setDuration(DISMISS_DURATION)
.setInterpolator(android.view.animation.AccelerateInterpolator())
.setUpdateListener { updateSheetVisuals(sheet.y.toInt()) }
.withEndAction { finishDismiss() }
.start()
}
private fun finishPresent() {
// Restore isHideable to actual value after present animation
behavior?.isHideable = dismissible
val (index, position, detent) = getDetentInfoWithValue(currentDetentIndex)
delegate?.viewControllerDidPresent(index, position, detent)
parentSheetView?.viewControllerDidBlur()
delegate?.viewControllerDidFocus()
presentPromise?.invoke()
presentPromise = null
}
private fun finishDismiss() {
emitDidDismissEvents()
cleanupSheet()
}
// =============================================================================
// MARK: - Sheet Configuration
// =============================================================================
fun setupSheetDetents() {
val behavior = this.behavior ?: run {
RNLog.e(reactContext, "TrueSheet: behavior is null in setupSheetDetents")
return
}
interactionState = InteractionState.Reconfiguring
behavior.isFitToContents = false
val maxAvailableHeight = realScreenHeight - topInset
val peekHeight = minOf(detentCalculator.getDetentHeight(detents[0]), maxAvailableHeight)
val halfExpandedDetentHeight = when (detents.size) {
1 -> peekHeight
else -> detentCalculator.getDetentHeight(detents[1])
}
val maxDetentHeight = minOf(detentCalculator.getDetentHeight(detents.last()), maxAvailableHeight)
val adjustedHalfExpandedHeight = minOf(halfExpandedDetentHeight, maxAvailableHeight)
val halfExpandedRatio = (adjustedHalfExpandedHeight.toFloat() / realScreenHeight.toFloat())
val expandedOffset = realScreenHeight - maxDetentHeight
// fitToContents works better with <= 2 detents when no expanded offset
val fitToContents = detents.size < 3 && expandedOffset == 0
configureDetents(
behavior = behavior,
peekHeight = peekHeight,
halfExpandedRatio = halfExpandedRatio,
expandedOffset = expandedOffset,
fitToContents = fitToContents,
animate = isPresented
)
val offset = if (expandedOffset == 0) topInset else 0
val newHeight = realScreenHeight - expandedOffset - offset
val newWidth = minOf(screenWidth, DEFAULT_MAX_WIDTH.dpToPx().toInt())
if (lastStateWidth != newWidth || lastStateHeight != newHeight) {
lastStateWidth = newWidth
lastStateHeight = newHeight
delegate?.viewControllerDidChangeSize(newWidth, newHeight)
}
if (isPresented) {
setStateForDetentIndex(currentDetentIndex)
}
interactionState = InteractionState.Idle
}
private fun configureDetents(
behavior: BottomSheetBehavior<TrueSheetBottomSheetView>,
peekHeight: Int,
halfExpandedRatio: Float,
expandedOffset: Int,
fitToContents: Boolean,
animate: Boolean
) {
behavior.apply {
isFitToContents = fitToContents
skipCollapsed = false
setPeekHeight(peekHeight, animate)
this.halfExpandedRatio = halfExpandedRatio.coerceIn(0.01f, 0.999f)
this.expandedOffset = expandedOffset
}
}
fun setupSheetDetentsForSizeChange() {
setupSheetDetents()
positionFooter()
}
fun setStateForDetentIndex(index: Int) {
behavior?.state = detentCalculator.getStateForDetentIndex(index)
}
// =============================================================================
// MARK: - Dimmed Background
// =============================================================================
fun setupDimmedBackground(detentIndex: Int) {
val coordinator = this.coordinatorLayout ?: run {
RNLog.e(reactContext, "TrueSheet: coordinatorLayout is null in setupDimmedBackground")
return
}
if (dimmed) {
val parentDimVisible = (parentSheetView?.viewController?.dimView?.alpha ?: 0f) > 0f
if (dimView == null) {
dimView = TrueSheetDimView(reactContext).apply {
delegate = this@TrueSheetViewController
}
}
if (!parentDimVisible) {
dimView?.attachToCoordinator(coordinator)
}
// Attach dim view to parent sheet if stacked
val parentController = parentSheetView?.viewController
val parentBottomSheet = parentController?.sheetView
if (parentBottomSheet != null) {
if (parentDimView == null) {
parentDimView = TrueSheetDimView(reactContext).apply {
delegate = this@TrueSheetViewController
}
}
parentDimView?.attach(parentBottomSheet, parentController.sheetCornerRadius)
}
} else {
dimView?.detach()
dimView = null
parentDimView?.detach()
parentDimView = null
}
}
fun updateDimAmount(sheetTop: Int? = null, animated: Boolean = false) {
if (!dimmed) return
val keyboardOffset = if (isDismissing) 0 else currentKeyboardInset
val top = (sheetTop ?: sheetView?.top ?: return) + keyboardOffset
if (animated) {
val targetAlpha = dimView?.calculateAlpha(
top,
dimmedDetentIndex,
detentCalculator::getSheetTopForDetentIndex
) ?: 0f
dimViews.forEach { it.animate().alpha(targetAlpha).setDuration(200).start() }
} else {
dimViews.forEach { it.interpolateAlpha(top, dimmedDetentIndex, detentCalculator::getSheetTopForDetentIndex) }
}
}
// =============================================================================
// MARK: - Footer Positioning
// =============================================================================
fun positionFooter(slideOffset: Float? = null) {
if (!isPresented) return
val footerView = containerView?.footerView ?: return
val sheet = sheetView ?: return
val footerHeight = footerView.height
val sheetHeight = sheet.height
val sheetTop = sheet.top
var footerY = (sheetHeight - sheetTop - footerHeight - currentKeyboardInset).toFloat()
// Adjust during dismiss animation when slideOffset is negative
if (slideOffset != null && slideOffset < 0) {
footerY -= (footerHeight * slideOffset)
}
// Clamp to prevent footer going above safe area
val maxAllowedY = (sheetHeight - topInset - footerHeight).toFloat()
footerView.y = minOf(footerY, maxAllowedY)
}
// =============================================================================
// MARK: - Keyboard Handling
// =============================================================================
private fun shouldHandleKeyboard(checkFocus: Boolean = true): Boolean {
if (wasHiddenByModal) return false
if (!isTopmostSheet) return false
if (checkFocus && !isFocusedViewWithinSheet()) return false
return true
}
fun setupKeyboardObserver() {
val coordinator = coordinatorLayout ?: run {
RNLog.e(reactContext, "TrueSheet: coordinatorLayout is null in setupKeyboardObserver")
return
}
cleanupKeyboardObserver()
keyboardObserver = TrueSheetKeyboardObserver(coordinator, reactContext).apply {
delegate = object : TrueSheetKeyboardObserverDelegate {
override fun keyboardWillShow(height: Int) {
if (!shouldHandleKeyboard()) return
detentIndexBeforeKeyboard = currentDetentIndex
setupSheetDetents()
setStateForDetentIndex(detents.size - 1)
}
override fun keyboardWillHide() {
if (!shouldHandleKeyboard(checkFocus = false)) return
setupSheetDetents()
if (!isDismissing && detentIndexBeforeKeyboard >= 0) {
setStateForDetentIndex(detentIndexBeforeKeyboard)
detentIndexBeforeKeyboard = -1
}
}
override fun keyboardDidHide() {}
override fun keyboardDidChangeHeight(height: Int) {
if (!shouldHandleKeyboard()) return
positionFooter()
}
}
start()
}
}
fun cleanupKeyboardObserver() {
keyboardObserver?.stop()
keyboardObserver = null
}
// =============================================================================
// MARK: - Drag Handling
// =============================================================================
private fun getPositionDpForView(sheetView: View): Float =
detentCalculator.getPositionDp(detentCalculator.getVisibleSheetHeight(sheetView.top))
private fun handleDragBegin(sheetView: View) {
val position = getPositionDpForView(sheetView)
val detent = detentCalculator.getDetentValueForIndex(currentDetentIndex)
delegate?.viewControllerDidDragBegin(currentDetentIndex, position, detent)
interactionState = InteractionState.Dragging(startTop = sheetView.top)
}
private fun handleDragChange(sheetView: View) {
if (interactionState !is InteractionState.Dragging) return
val position = getPositionDpForView(sheetView)
val detent = detentCalculator.getDetentValueForIndex(currentDetentIndex)
delegate?.viewControllerDidDragChange(currentDetentIndex, position, detent)
}
// =============================================================================
// MARK: - Event Emission
// =============================================================================
private fun emitWillPresentEvents() {
val (index, position, detent) = getDetentInfoWithValue(currentDetentIndex)
parentSheetView?.viewControllerWillBlur()
delegate?.viewControllerWillPresent(index, position, detent)
delegate?.viewControllerWillFocus()
}
private fun emitWillDismissEvents() {
delegate?.viewControllerWillBlur()
delegate?.viewControllerWillDismiss()
parentSheetView?.viewControllerWillFocus()
}
private fun emitDidDismissEvents() {
val hadParent = parentSheetView != null
parentSheetView?.viewControllerDidFocus()
parentSheetView = null
delegate?.viewControllerDidBlur()
delegate?.viewControllerDidDismiss(hadParent)
dismissPromise?.invoke()
dismissPromise = null
}
private fun emitChangePositionDelegate(currentTop: Int, realtime: Boolean = true) {
// Dedupe emissions for same position
if (currentTop == lastEmittedPositionPx) return
lastEmittedPositionPx = currentTop
val visibleHeight = realScreenHeight - currentTop
val position = detentCalculator.getPositionDp(visibleHeight)
val interpolatedIndex = detentCalculator.getInterpolatedIndexForPosition(currentTop)
val detent = detentCalculator.getInterpolatedDetentForPosition(currentTop)
delegate?.viewControllerDidChangePosition(interpolatedIndex, position, detent, realtime)
}
/**
* Updates position emission, footer, and dim amount together.
* This pattern is commonly used during animations and state changes.
*/