-
-
Notifications
You must be signed in to change notification settings - Fork 643
Expand file tree
/
Copy pathScreenStackFragment.kt
More file actions
803 lines (707 loc) · 31.6 KB
/
ScreenStackFragment.kt
File metadata and controls
803 lines (707 loc) · 31.6 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
package com.swmansion.rnscreens
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.Transformation
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.WindowInsetsCompat
import com.facebook.react.uimanager.PixelUtil
import com.facebook.react.uimanager.PointerEvents
import com.facebook.react.uimanager.ReactPointerEventsView
import com.facebook.react.uimanager.UIManagerHelper
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.ScrollingViewBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.google.android.material.shape.CornerFamily
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.ShapeAppearanceModel
import com.swmansion.rnscreens.bottomsheet.DimmingViewManager
import com.swmansion.rnscreens.bottomsheet.SheetDelegate
import com.swmansion.rnscreens.bottomsheet.SheetUtils
import com.swmansion.rnscreens.bottomsheet.isSheetFitToContents
import com.swmansion.rnscreens.bottomsheet.useSingleDetent
import com.swmansion.rnscreens.bottomsheet.useThreeDetents
import com.swmansion.rnscreens.bottomsheet.useTwoDetents
import com.swmansion.rnscreens.bottomsheet.usesFormSheetPresentation
import com.swmansion.rnscreens.events.ScreenDismissedEvent
import com.swmansion.rnscreens.events.ScreenEventDelegate
import com.swmansion.rnscreens.ext.recycle
import com.swmansion.rnscreens.transition.ExternalBoundaryValuesEvaluator
import com.swmansion.rnscreens.utils.DeviceUtils
import com.swmansion.rnscreens.utils.resolveBackgroundColor
sealed class KeyboardState
object KeyboardNotVisible : KeyboardState()
object KeyboardDidHide : KeyboardState()
class KeyboardVisible(
val height: Int,
) : KeyboardState()
class ScreenStackFragment :
ScreenFragment,
ScreenStackFragmentWrapper {
public var nativeDismissalObserver: NativeDismissalObserver? = null
private var appBarLayout: AppBarLayout? = null
private var toolbar: Toolbar? = null
private var isToolbarShadowHidden = false
private var isToolbarTranslucent = false
private var lastFocusedChild: View? = null
var searchView: CustomSearchView? = null
var onSearchViewCreate: ((searchView: CustomSearchView) -> Unit)? = null
private lateinit var coordinatorLayout: ScreensCoordinatorLayout
private val screenStack: ScreenStack
get() {
val container = screen.container
check(container is ScreenStack) { "ScreenStackFragment added into a non-stack container" }
return container
}
private val dimmingDelegate =
lazy(LazyThreadSafetyMode.NONE) {
DimmingViewManager(screen.reactContext, screen)
}
private var sheetDelegate: SheetDelegate? = null
@SuppressLint("ValidFragment")
constructor(screenView: Screen) : super(screenView)
constructor() {
throw IllegalStateException(
"ScreenStack fragments should never be restored. Follow instructions from https://github.com/software-mansion/react-native-screens/issues/17#issuecomment-424704067 to properly configure your main activity.",
)
}
override fun removeToolbar() {
appBarLayout?.let {
toolbar?.let { toolbar ->
if (toolbar.parent === it) {
it.removeView(toolbar)
}
}
}
toolbar = null
}
override fun setToolbar(toolbar: Toolbar) {
appBarLayout?.addView(toolbar)
toolbar.layoutParams =
AppBarLayout
.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT,
).apply { scrollFlags = 0 }
this.toolbar = toolbar
}
override fun setToolbarShadowHidden(hidden: Boolean) {
if (isToolbarShadowHidden != hidden) {
appBarLayout?.elevation = if (hidden) 0f else PixelUtil.toPixelFromDIP(4f)
appBarLayout?.stateListAnimator = null
isToolbarShadowHidden = hidden
}
}
override fun setToolbarTranslucent(translucent: Boolean) {
if (isToolbarTranslucent != translucent) {
val params = screen.layoutParams
(params as CoordinatorLayout.LayoutParams).behavior =
if (translucent) null else ScrollingViewBehavior()
isToolbarTranslucent = translucent
}
}
override fun onContainerUpdate() {
super.onContainerUpdate()
screen.headerConfig?.onUpdate()
}
override fun onViewAnimationEnd() {
super.onViewAnimationEnd()
// Rely on guards inside the callee to detect whether this was indeed appear transition.
notifyViewAppearTransitionEnd()
// Rely on guards inside the callee to detect whether this was indeed removal transition.
screen.endRemovalTransition()
}
private fun notifyViewAppearTransitionEnd() {
val screenStack = view?.parent
if (screenStack is ScreenStack) {
screenStack.onViewAppearTransitionEnd()
}
}
// If the Screen has `formSheet` presentation this callback is attached to its behavior.
// It is responsible for firing detent changed events & removing the sheet from the container
// once it is hidden by user gesture.
private val bottomSheetStateCallback =
object : BottomSheetCallback() {
private var lastStableState: Int =
SheetUtils.sheetStateFromDetentIndex(
screen.sheetInitialDetentIndex,
screen.sheetDetents.count(),
)
override fun onStateChanged(
bottomSheet: View,
newState: Int,
) {
if (SheetUtils.isStateStable(newState)) {
lastStableState = newState
screen.notifySheetDetentChange(
SheetUtils.detentIndexFromSheetState(
lastStableState,
screen.sheetDetents.count(),
),
true,
)
} else if (newState == BottomSheetBehavior.STATE_DRAGGING) {
screen.notifySheetDetentChange(
SheetUtils.detentIndexFromSheetState(
lastStableState,
screen.sheetDetents.count(),
),
false,
)
}
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismissSelf()
}
}
override fun onSlide(
bottomSheet: View,
slideOffset: Float,
) = Unit
}
/**
* Currently this method dispatches event to JS where state is recomputed and fragment
* gets removed in the result of incoming state update.
*/
internal fun dismissSelf() {
if (!this.isRemoving || !this.isDetached) {
val reactContext = screen.reactContext
val surfaceId = UIManagerHelper.getSurfaceId(reactContext)
UIManagerHelper
.getEventDispatcherForReactTag(reactContext, screen.id)
?.dispatchEvent(ScreenDismissedEvent(surfaceId, screen.id))
}
}
internal fun onSheetCornerRadiusChange() {
screen.onSheetCornerRadiusChange()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
coordinatorLayout = ScreensCoordinatorLayout(requireContext(), this)
screen.layoutParams =
CoordinatorLayout
.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT,
).apply {
behavior =
if (screen.usesFormSheetPresentation()) {
createAndConfigureBottomSheetBehaviour()
} else if (isToolbarTranslucent) {
null
} else {
ScrollingViewBehavior()
}
}
if (screen.usesFormSheetPresentation()) {
screen.clipToOutline = true
// TODO(@kkafar): without this line there is no drawable / outline & nothing shows...? Determine what's going on here
attachShapeToScreen(screen)
screen.elevation = screen.sheetElevation
}
coordinatorLayout.addView(screen.recycle())
if (!screen.usesFormSheetPresentation()) {
appBarLayout =
context?.let { AppBarLayout(it) }?.apply {
// By default AppBarLayout will have a background color set but since we cover the whole layout
// with toolbar (that can be semi-transparent) the bar layout background color does not pay a
// role. On top of that it breaks screens animations when alfa offscreen compositing is off
// (which is the default)
setBackgroundColor(Color.TRANSPARENT)
layoutParams =
AppBarLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT,
)
}
coordinatorLayout.addView(appBarLayout)
if (isToolbarShadowHidden) {
appBarLayout?.targetElevation = 0f
}
toolbar?.let { appBarLayout?.addView(it.recycle()) }
setHasOptionsMenu(true)
}
return coordinatorLayout
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?,
) {
super.onViewCreated(view, savedInstanceState)
if (!screen.usesFormSheetPresentation()) {
return
}
sheetDelegate = SheetDelegate(screen)
assert(view == coordinatorLayout)
dimmingDelegate.value.onViewHierarchyCreated(screen, coordinatorLayout)
dimmingDelegate.value.onBehaviourAttached(screen, screen.sheetBehavior!!)
val container = screen.container!!
coordinatorLayout.measure(
View.MeasureSpec.makeMeasureSpec(container.width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(container.height, View.MeasureSpec.EXACTLY),
)
coordinatorLayout.layout(0, 0, container.width, container.height)
}
override fun onCreateAnimation(
transit: Int,
enter: Boolean,
nextAnim: Int,
): Animation? {
// Ensure onCreateAnimator is called
return null
}
override fun onCreateAnimator(
transit: Int,
enter: Boolean,
nextAnim: Int,
): Animator? {
if (!screen.usesFormSheetPresentation()) {
// Use animation defined while defining transaction in screen stack
return null
}
val animatorSet = AnimatorSet()
if (enter) {
val alphaAnimator =
ValueAnimator.ofFloat(0f, dimmingDelegate.value.maxAlpha).apply {
addUpdateListener { anim ->
val animatedValue = anim.animatedValue as? Float
animatedValue?.let { dimmingDelegate.value.dimmingView.alpha = it }
}
}
val startValueCallback = { initialStartValue: Number? -> screen.height.toFloat() }
val evaluator = ExternalBoundaryValuesEvaluator(startValueCallback, { 0f })
val slideAnimator =
ValueAnimator.ofObject(evaluator, screen.height.toFloat(), 0f).apply {
addUpdateListener { anim ->
val animatedValue = anim.animatedValue as? Float
animatedValue?.let { screen.translationY = it }
}
}
animatorSet.play(alphaAnimator).with(slideAnimator)
} else {
val alphaAnimator =
ValueAnimator.ofFloat(dimmingDelegate.value.dimmingView.alpha, 0f).apply {
addUpdateListener { anim ->
val animatedValue = anim.animatedValue as? Float
animatedValue?.let { dimmingDelegate.value.dimmingView.alpha = it }
}
}
val slideAnimator =
ValueAnimator.ofFloat(0f, (coordinatorLayout.bottom - screen.top).toFloat()).apply {
addUpdateListener { anim ->
val animatedValue = anim.animatedValue as? Float
animatedValue?.let { screen.translationY = it }
}
}
animatorSet.play(alphaAnimator).with(slideAnimator)
}
animatorSet.addListener(ScreenEventDelegate(this))
return animatorSet
}
/**
* This method might return slightly different values depending on code path,
* but during testing I've found this effect negligible. For practical purposes
* this is acceptable.
*/
private fun tryResolveContainerHeight(): Int? {
if (screen.container != null) {
return screenStack.height
}
context
?.resources
?.displayMetrics
?.heightPixels
?.let { return it }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
(context?.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)
?.currentWindowMetrics
?.bounds
?.height()
?.let { return it }
}
return null
}
private val keyboardSheetCallback =
object : BottomSheetCallback() {
@RequiresApi(Build.VERSION_CODES.M)
override fun onStateChanged(
bottomSheet: View,
newState: Int,
) {
if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
val isImeVisible =
WindowInsetsCompat
.toWindowInsetsCompat(bottomSheet.rootWindowInsets)
.isVisible(WindowInsetsCompat.Type.ime())
if (isImeVisible) {
// Does it not interfere with React Native focus mechanism? In any case I'm not aware
// of different way of hiding the keyboard.
// https://stackoverflow.com/questions/1109022/how-can-i-close-hide-the-android-soft-keyboard-programmatically
// https://developer.android.com/develop/ui/views/touch-and-input/keyboard-input/visibility
// I want to be polite here and request focus before dismissing the keyboard,
// however even if it fails I want to try to hide the keyboard. This sometimes works...
bottomSheet.requestFocus()
val imm = requireContext().getSystemService(InputMethodManager::class.java)
imm.hideSoftInputFromWindow(bottomSheet.windowToken, 0)
}
}
}
override fun onSlide(
bottomSheet: View,
slideOffset: Float,
) = Unit
}
internal fun configureBottomSheetBehaviour(
behavior: BottomSheetBehavior<Screen>,
keyboardState: KeyboardState = KeyboardNotVisible,
): BottomSheetBehavior<Screen> {
val containerHeight = tryResolveContainerHeight()
check(containerHeight != null) {
"[RNScreens] Failed to find window height during bottom sheet behaviour configuration"
}
behavior.apply {
isHideable = true
isDraggable = true
// It seems that there is a guard in material implementation that will prevent
// this callback from being registered multiple times.
addBottomSheetCallback(bottomSheetStateCallback)
}
screen.footer?.registerWithSheetBehavior(behavior)
return when (keyboardState) {
is KeyboardNotVisible -> {
when (screen.sheetDetents.count()) {
1 ->
behavior.apply {
val height =
if (screen.isSheetFitToContents()) {
screen.contentWrapper
.get()
?.height
.takeIf { screen.contentWrapper.get()?.isLaidOut == true }
} else {
(screen.sheetDetents.first() * containerHeight).toInt()
}
useSingleDetent(height = height)
}
2 ->
behavior.useTwoDetents(
state =
SheetUtils.sheetStateFromDetentIndex(
screen.sheetInitialDetentIndex,
screen.sheetDetents.count(),
),
firstHeight = (screen.sheetDetents[0] * containerHeight).toInt(),
secondHeight = (screen.sheetDetents[1] * containerHeight).toInt(),
)
3 ->
behavior.useThreeDetents(
state =
SheetUtils.sheetStateFromDetentIndex(
screen.sheetInitialDetentIndex,
screen.sheetDetents.count(),
),
firstHeight = (screen.sheetDetents[0] * containerHeight).toInt(),
halfExpandedRatio = (screen.sheetDetents[1] / screen.sheetDetents[2]).toFloat(),
expandedOffsetFromTop = ((1 - screen.sheetDetents[2]) * containerHeight).toInt(),
)
else -> throw IllegalStateException(
"[RNScreens] Invalid detent count ${screen.sheetDetents.count()}. Expected at most 3.",
)
}
}
is KeyboardVisible -> {
val newMaxHeight =
if (behavior.maxHeight - keyboardState.height > 1) {
behavior.maxHeight - keyboardState.height
} else {
behavior.maxHeight
}
when (screen.sheetDetents.count()) {
1 ->
behavior.apply {
useSingleDetent(height = newMaxHeight)
addBottomSheetCallback(keyboardSheetCallback)
}
2 ->
behavior.apply {
useTwoDetents(
state = BottomSheetBehavior.STATE_EXPANDED,
secondHeight = newMaxHeight,
)
addBottomSheetCallback(keyboardSheetCallback)
}
3 ->
behavior.apply {
useThreeDetents(
state = BottomSheetBehavior.STATE_EXPANDED,
)
maxHeight = newMaxHeight
addBottomSheetCallback(keyboardSheetCallback)
}
else -> throw IllegalStateException(
"[RNScreens] Invalid detent count ${screen.sheetDetents.count()}. Expected at most 3.",
)
}
}
is KeyboardDidHide -> {
// Here we assume that the keyboard was either closed explicitly by user,
// or the user dragged the sheet down. In any case the state should
// stay unchanged.
behavior.removeBottomSheetCallback(keyboardSheetCallback)
when (screen.sheetDetents.count()) {
1 ->
behavior.useSingleDetent(
height = (screen.sheetDetents.first() * containerHeight).toInt(),
forceExpandedState = false,
)
2 ->
behavior.useTwoDetents(
firstHeight = (screen.sheetDetents[0] * containerHeight).toInt(),
secondHeight = (screen.sheetDetents[1] * containerHeight).toInt(),
)
3 ->
behavior.useThreeDetents(
firstHeight = (screen.sheetDetents[0] * containerHeight).toInt(),
halfExpandedRatio = (screen.sheetDetents[1] / screen.sheetDetents[2]).toFloat(),
expandedOffsetFromTop = ((1 - screen.sheetDetents[2]) * containerHeight).toInt(),
)
else -> throw IllegalStateException(
"[RNScreens] Invalid detent count ${screen.sheetDetents.count()}. Expected at most 3.",
)
}
}
}
}
private fun createBottomSheetBehaviour(): BottomSheetBehavior<Screen> = BottomSheetBehavior<Screen>()
// In general it would be great to create BottomSheetBehaviour only via this method as it runs some
// side effects.
private fun createAndConfigureBottomSheetBehaviour(): BottomSheetBehavior<Screen> =
configureBottomSheetBehaviour(createBottomSheetBehaviour())
private fun resolveBackgroundColor(screen: Screen): Int? {
val screenColor =
(screen.background as? ColorDrawable?)?.color
?: (screen.background as? MaterialShapeDrawable?)?.tintList?.defaultColor
if (screenColor != null) {
return screenColor
}
val contentWrapper = screen.contentWrapper.get()
if (contentWrapper == null) {
return null
}
val contentWrapperColor = contentWrapper.resolveBackgroundColor()
return contentWrapperColor
}
private fun attachShapeToScreen(screen: Screen) {
val cornerSize = PixelUtil.toPixelFromDIP(screen.sheetCornerRadius)
val shapeAppearanceModel =
ShapeAppearanceModel
.Builder()
.apply {
setTopLeftCorner(CornerFamily.ROUNDED, cornerSize)
setTopRightCorner(CornerFamily.ROUNDED, cornerSize)
}.build()
val shape = MaterialShapeDrawable(shapeAppearanceModel)
val backgroundColor = resolveBackgroundColor(screen)
shape.setTint(backgroundColor ?: Color.TRANSPARENT)
screen.background = shape
}
override fun onStart() {
lastFocusedChild?.requestFocus()
super.onStart()
}
override fun onStop() {
if (DeviceUtils.isPlatformAndroidTV(context)) {
lastFocusedChild = findLastFocusedChild()
}
super.onStop()
}
override fun onPrepareOptionsMenu(menu: Menu) {
// If the screen is a transparent modal with hidden header we don't want to update the toolbar
// menu because it may erase the menu of the previous screen (which is still visible in these
// circumstances). See here: https://github.com/software-mansion/react-native-screens/issues/2271
if (!screen.isTransparent() || screen.headerConfig?.isHeaderHidden == false) {
updateToolbarMenu(menu)
}
return super.onPrepareOptionsMenu(menu)
}
override fun onCreateOptionsMenu(
menu: Menu,
inflater: MenuInflater,
) {
updateToolbarMenu(menu)
return super.onCreateOptionsMenu(menu, inflater)
}
private fun shouldShowSearchBar(): Boolean {
val config = screen.headerConfig
val numberOfSubViews = config?.configSubviewsCount ?: 0
if (config != null && numberOfSubViews > 0) {
for (i in 0 until numberOfSubViews) {
val subView = config.getConfigSubview(i)
if (subView.type == ScreenStackHeaderSubview.Type.SEARCH_BAR) {
return true
}
}
}
return false
}
private fun updateToolbarMenu(menu: Menu) {
menu.clear()
if (shouldShowSearchBar()) {
val currentContext = context
if (searchView == null && currentContext != null) {
val newSearchView = CustomSearchView(currentContext, this)
searchView = newSearchView
onSearchViewCreate?.invoke(newSearchView)
}
menu.add("").apply {
setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
actionView = searchView
}
}
}
private fun findLastFocusedChild(): View? {
var view: View? = screen
while (view != null) {
if (view.isFocused) return view
view = if (view is ViewGroup) view.focusedChild else null
}
return null
}
override fun canNavigateBack(): Boolean {
val container: ScreenContainer? = screen.container
check(container is ScreenStack) { "ScreenStackFragment added into a non-stack container" }
return if (container.rootScreen == screen) {
// this screen is the root of the container, if it is nested we can check parent container
// if it is also a root or not
val parentFragment = parentFragment
if (parentFragment is ScreenStackFragment) {
parentFragment.canNavigateBack()
} else {
false
}
} else {
true
}
}
override fun dismissFromContainer() {
screenStack.dismiss(this)
}
private class ScreensCoordinatorLayout(
context: Context,
private val fragment: ScreenStackFragment,
// ) : CoordinatorLayout(context), ReactCompoundViewGroup, ReactHitSlopView {
) : CoordinatorLayout(context),
ReactPointerEventsView {
override fun onApplyWindowInsets(insets: WindowInsets?): WindowInsets = super.onApplyWindowInsets(insets)
private val animationListener: Animation.AnimationListener =
object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
fragment.onViewAnimationStart()
}
override fun onAnimationEnd(animation: Animation) {
fragment.onViewAnimationEnd()
}
override fun onAnimationRepeat(animation: Animation) {}
}
override fun startAnimation(animation: Animation) {
// For some reason View##onAnimationEnd doesn't get called for
// exit transitions so we explicitly attach animation listener.
// We also have some animations that are an AnimationSet, so we don't wrap them
// in another set since it causes some visual glitches when going forward.
// We also set the listener only when going forward, since when going back,
// there is already a listener for dismiss action added, which would be overridden
// and also this is not necessary when going back since the lifecycle methods
// are correctly dispatched then.
// We also add fakeAnimation to the set of animations, which sends the progress of animation
val fakeAnimation = ScreensAnimation(fragment).apply { duration = animation.duration }
if (animation is AnimationSet && !fragment.isRemoving) {
animation
.apply {
addAnimation(fakeAnimation)
setAnimationListener(animationListener)
}.also {
super.startAnimation(it)
}
} else {
AnimationSet(true)
.apply {
addAnimation(animation)
addAnimation(fakeAnimation)
setAnimationListener(animationListener)
}.also {
super.startAnimation(it)
}
}
}
/**
* This method implements a workaround for RN's autoFocus functionality. Because of the way
* autoFocus is implemented it dismisses soft keyboard in fragment transition
* due to change of visibility of the view at the start of the transition. Here we override the
* call to `clearFocus` when the visibility of view is `INVISIBLE` since `clearFocus` triggers the
* hiding of the keyboard in `ReactEditText.java`.
*/
override fun clearFocus() {
if (visibility != INVISIBLE) {
super.clearFocus()
}
}
// override fun reactTagForTouch(touchX: Float, touchY: Float): Int {
// throw IllegalStateException("Screen wrapper should never be asked for the view tag")
// }
//
// override fun interceptsTouchEvent(touchX: Float, touchY: Float): Boolean {
// return false
// }
//
// override fun getHitSlopRect(): Rect? {
// val screen: Screen = fragment.screen
// // left – The X coordinate of the left side of the rectangle
// // top – The Y coordinate of the top of the rectangle i
// // right – The X coordinate of the right side of the rectangle
// // bottom – The Y coordinate of the bottom of the rectangle
// return Rect(screen.x.toInt(), -screen.y.toInt(), screen.x.toInt() + screen.width, screen.y.toInt() + screen.height)
// }
// We set pointer events to BOX_NONE, because we don't want the ScreensCoordinatorLayout
// to be target of react gestures and effectively prevent interaction with screens
// underneath the current screen (useful in `modal` & `formSheet` presentation).
override fun getPointerEvents(): PointerEvents = PointerEvents.BOX_NONE
}
private class ScreensAnimation(
private val mFragment: ScreenFragment,
) : Animation() {
override fun applyTransformation(
interpolatedTime: Float,
t: Transformation,
) {
super.applyTransformation(interpolatedTime, t)
// interpolated time should be the progress of the current transition
mFragment.dispatchTransitionProgressEvent(interpolatedTime, !mFragment.isResumed)
}
}
}