-
-
Notifications
You must be signed in to change notification settings - Fork 643
Expand file tree
/
Copy pathRNSTabBarController.mm
More file actions
1008 lines (846 loc) · 37.4 KB
/
RNSTabBarController.mm
File metadata and controls
1008 lines (846 loc) · 37.4 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
#import "RNSTabBarController.h"
#import <React/RCTAssert.h>
#import <React/RCTLog.h>
#import <objc/message.h>
#import <objc/runtime.h>
#import "NSString+RNSUtility.h"
#import "RNSLog.h"
#import "RNSScreenWindowTraits.h"
#import "RNSTabsHostComponentView.h"
#define RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE !TARGET_OS_TV && !TARGET_OS_VISION
// We need UINavigationControllerDelegate to handle navigation within `moreNavigationController`
@interface RNSTabBarController () <UITabBarControllerDelegate, UINavigationControllerDelegate>
@end
@interface RNSTabBarController ()
/// Consulted by the ISA-swizzled `pushViewController:animated:` on `moreNavigationController`
/// to decide whether a push should proceed.
- (BOOL)moreNavigationController:(UINavigationController *)navigationController
shouldPushViewController:(UIViewController *)viewController;
@property (nonatomic, readwrite) BOOL shouldProgressStateOnMoreNavigationControllerPush;
@end
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
/**
* Replacement implementation for `pushViewController:animated:` injected into
* a dynamic subclass of `UIMoreNavigationController` via ISA-swizzle.
*
* Before allowing the push, this function consults the owning `RNSTabBarController`
* (reached via UIKit's `tabBarController` property on the parent chain)
* to check whether the push should be prevented (e.g. due to `preventNativeSelection`).
*/
static void
rns_pushViewController(__unsafe_unretained id self, SEL _cmd, UIViewController *viewController, BOOL animated)
{
UITabBarController *rawTabBarController = static_cast<UIViewController *>(self).tabBarController;
RCTAssert(
[rawTabBarController isKindOfClass:RNSTabBarController.class],
@"[RNScreens] Expected tabBarController to be of class %@, got: %@",
RNSTabBarController.class,
rawTabBarController.class);
RNSTabBarController *tabBarController = static_cast<RNSTabBarController *>(rawTabBarController);
if ([tabBarController moreNavigationController:self shouldPushViewController:viewController]) {
struct objc_super superInfo = {
.receiver = self,
.super_class = class_getSuperclass(object_getClass(self)),
};
const auto msgSendSuperPushViewController =
reinterpret_cast<void (*)(struct objc_super *, SEL, UIViewController *, BOOL)>(objc_msgSendSuper);
[tabBarController setShouldProgressStateOnMoreNavigationControllerPush:YES];
msgSendSuperPushViewController(&superInfo, _cmd, viewController, animated);
}
}
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
@implementation RNSTabBarController {
NSArray<RNSTabsScreenViewController *> *_Nullable _tabScreenControllers;
/// This property is nullable until first container update. Later it MUST NOT be nil.
RNSTabsNavigationState *_Nullable _navigationState;
/// Holds last state that has been a result of UI-side navigation (user request).
/// This one is also updated in cases where UIKit modifies the selected tab implicitly,
/// e.g. when user resizes the app and more tab disappears.
///
/// This property is nullable until first container update. Later it MUST NOT be nil.
RNSTabsNavigationState *_Nullable _lastUINavigationState;
RNSTabsNavigationState *_Nullable _pendingOperation;
/// When YES, the controller is inside an explicit selection-changing code path (container update,
/// delegate handling). Setter overrides skip reconciliation while this flag is set.
BOOL _isHandlingExplicitSelectionUpdate;
#if !RCT_NEW_ARCH_ENABLED
BOOL _isControllerFlushBlockScheduled;
#endif // !RCT_NEW_ARCH_ENABLED
}
- (instancetype)init
{
if (self = [super init]) {
_tabScreenControllers = nil;
_tabBarAppearanceCoordinator = [RNSTabBarAppearanceCoordinator new];
_tabsHostComponentView = nil;
_navigationState = nil;
_pendingOperation = nil;
_shouldProgressStateOnMoreNavigationControllerPush = NO;
// Delegate field retains weakly, no risk of cycle.
self.delegate = self;
#if !RCT_NEW_ARCH_ENABLED
_isControllerFlushBlockScheduled = NO;
#endif // !RCT_NEW_ARCH_ENABLED
}
return self;
}
- (instancetype)initWithTabsHostComponentView:(nullable RNSTabsHostComponentView *)tabsHostComponentView
{
if (self = [self init]) {
_tabsHostComponentView = tabsHostComponentView;
}
return self;
}
#pragma mark - UIKit callbacks
- (void)didMoveToParentViewController:(UIViewController *)parent
{
[super didMoveToParentViewController:parent];
if (parent != nil) {
[self updateLayoutDirectionBelowIOS17IfNeeded];
}
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
RNSLog(@"TabBar: %@ didSelectItem: %@", tabBar, item);
}
- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
[super setSelectedIndex:selectedIndex];
if (!_isHandlingExplicitSelectionUpdate) {
[self reconcileNavigationStateWithUIKitState];
}
}
- (void)setSelectedViewController:(__kindof UIViewController *)selectedViewController
{
[super setSelectedViewController:selectedViewController];
if (!_isHandlingExplicitSelectionUpdate) {
[self reconcileNavigationStateWithUIKitState];
}
}
#pragma mark - Signals
- (void)setPendingNavigationStateUpdate:(nullable RNSTabsNavigationState *)navState
{
_pendingOperation = navState;
}
- (void)childViewControllersHaveChangedTo:(NSArray<RNSTabsScreenViewController *> *)reactChildControllers
{
_tabScreenControllers = reactChildControllers;
self.needsUpdateOfChildViewControllers = true;
}
- (void)setNeedsUpdateOfChildViewControllers:(bool)needsReactChildrenUpdate
{
_needsUpdateOfChildViewControllers = true;
#if !RCT_NEW_ARCH_ENABLED
[self scheduleControllerUpdateIfNeeded];
#endif // !RCT_NEW_ARCH_ENABLED
}
- (void)setNeedsUpdateOfTabBarAppearance:(bool)needsUpdateOfTabBarAppearance
{
_needsUpdateOfTabBarAppearance = needsUpdateOfTabBarAppearance;
#if !RCT_NEW_ARCH_ENABLED
[self scheduleControllerUpdateIfNeeded];
#endif // !RCT_NEW_ARCH_ENABLED
}
- (void)setNeedsOrientationUpdate:(bool)needsOrientationUpdate
{
_needsOrientationUpdate = needsOrientationUpdate;
#if !RCT_NEW_ARCH_ENABLED
[self scheduleControllerUpdateIfNeeded];
#endif // !RCT_NEW_ARCH_ENABLED
}
- (void)setNeedsLayoutDirectionUpdateBelowIOS17:(bool)needsLayoutDirectionUpdate
{
_needsLayoutDirectionUpdateBelowIOS17 = needsLayoutDirectionUpdate;
}
#pragma mark - RNSReactTransactionObserving
- (void)reactMountingTransactionWillMount
{
RNSLog(@"TabBarCtrl mountintTransactionWillMount");
}
- (void)reactMountingTransactionDidMount
{
RNSLog(@"TabBarCtrl mountintTransactionDidMount running updates");
[self performContainerUpdate];
}
#pragma mark - Container update
- (void)performContainerUpdate
{
_isHandlingExplicitSelectionUpdate = YES;
[self updateChildViewControllersIfNeeded];
[self updateSelectedViewControllerIfNeeded];
_isHandlingExplicitSelectionUpdate = NO;
[self updateTabBarAppearanceIfNeeded];
[self updateTabBarA11yIfNeeded];
[self updateOrientationIfNeeded];
}
/**
* Update UIKit model and associated navigation state.
*
* This method will advance state in case the selected view controller is repeated.
*
* This method MUST be called only in situations where `UITabBarController` state has not been updated yet.
* Otherwise it'll progress the state incorrectly.
*
* @returns whether the state has been updated or not.
*/
- (BOOL)updateSelectedViewControllerTo:(nullable UIViewController *)nextSelectedViewController
withKey:(nullable NSString *)screenKey
{
if (nextSelectedViewController == nil) {
return NO;
}
UIViewController *currSelectedViewController = self.selectedViewController;
RCTAssert(
![NSString rnscreens_isBlankOrNull:screenKey],
@"[RNScreens] The screenKey MUST NOT be null if the view controller is not null");
[self progressNavigationState:screenKey withOrigin:RNSTabsActionOriginProgrammaticJs];
if (currSelectedViewController == nextSelectedViewController) {
return YES;
}
[self setSelectedViewController:nextSelectedViewController];
return YES;
}
/**
* Update tabs navigation state in reaction to UIKit model update.
*
* This method does not update the UIKit model. It assumes that exactly one model update happened,
* and will sync the state with the UIKit and progress the provenance.
*/
- (void)updateNavigationStateOnModelUpdate
{
[self progressNavigationState:[self screenKeyForSelectedViewController] withOrigin:RNSTabsActionOriginUser];
}
- (void)userDidRepeatViewControllerSelection:(nonnull UIViewController *)viewController
{
RCTAssert(
self.selectedViewController == viewController, @"[RNScreens] Expected UIKit to update selectedViewController");
if ([self isSelectedViewControllerTheMoreNavigationController]) {
// We don't want to run neither state update nor side effects.
return;
}
[self updateNavigationStateOnModelUpdate];
// After state progression we trigger the special effect.
BOOL repeatedSelectionHandledBySpecialEffect = [[self selectedScreenViewController] tabScreenSelectedRepeatedly];
auto *updateContext =
[[RNSTabsNavigationStateUpdateContext alloc] initWithNavState:_navigationState
isRepeated:YES
hasTriggeredSpecialEffect:repeatedSelectionHandledBySpecialEffect
actionOrigin:RNSTabsActionOriginUser];
[self.tabsHostComponentView tabBarController:self didUpdateStateTo:_navigationState withContext:updateContext];
}
- (void)userDidSelectViewController:(nonnull UIViewController *)viewController
{
// At this moment the `UITabBarController` model is already updated.
RCTAssert(
self.selectedViewController == viewController, @"[RNScreens] Expected UIKit to update selectedViewController");
if ([self isSelectedViewControllerTheMoreNavigationController]) {
[self disableNavigationBarInMoreNavigationController];
[self prepareForMoreNavigationControllerHandlingIfNeeded];
// We don't want to progress state in case a user selected the more navigation controller.
// Instead, we emit a dedicated event so JS knows the More tab was tapped.
[self.tabsHostComponentView tabBarController:self didSelectMoreTabWithCurrentState:_navigationState];
} else {
[self updateNavigationStateOnModelUpdate];
auto *updateContext = [[RNSTabsNavigationStateUpdateContext alloc] initWithNavState:_navigationState
isRepeated:NO
hasTriggeredSpecialEffect:NO
actionOrigin:RNSTabsActionOriginUser];
[self.tabsHostComponentView tabBarController:self didUpdateStateTo:_navigationState withContext:updateContext];
}
}
- (void)onDidPreventUserFromSelectingViewControllerWithKey:(nonnull NSString *)screenKey
{
[self.tabsHostComponentView tabBarController:self preventedSelectionOf:screenKey currentState:_navigationState];
}
- (BOOL)shouldPreventNativeTabSelection:(nonnull UIViewController *)nextViewController
{
if (![nextViewController isKindOfClass:RNSTabsScreenViewController.class]) {
// Allow for more view controller selection
return NO;
}
auto *screenViewController = static_cast<RNSTabsScreenViewController *>(nextViewController);
return screenViewController.isPreventNativeSelectionEnabled;
}
#pragma mark - UITabBarControllerDelegate
// These methods are not called on programatic selection!
// They are called only when a user taps on tab bar.
- (BOOL)tabBarController:(UITabBarController *)tabBarController
shouldSelectViewController:(UIViewController *)viewController
{
RCTAssert(tabBarController == self, @"[RNScreens] Unexpected type of controller: %@", tabBarController.class);
// Can be UINavigationController in case of MoreNavigationController
RCTAssert(
[viewController isKindOfClass:RNSTabsScreenViewController.class] ||
[viewController isKindOfClass:UINavigationController.class],
@"[RNScreens] Unexpected type of controller: %@",
viewController.class);
// TODO: handle enforcing orientation with natively-driven tabs
// Detect repeated selection and inform tabScreenController
BOOL repeatedSelection = self.selectedViewController == viewController;
if (repeatedSelection) {
// On repeated selection we return false to prevent native *pop to root* effect that works only starting from iOS 26
// and interferes with our implementation (which is necessary for controlled tabs).
// We trigger the state update from here, because `tabBarController:didSelectViewController:` won't be called.
[self userDidRepeatViewControllerSelection:viewController];
return NO;
}
BOOL shouldPreventTabSelection = [self shouldPreventNativeTabSelection:viewController];
if (shouldPreventTabSelection) {
// Ideally we'd call this AFTER we prevent, but there is no appropriate callback.
// As long as we emit the event asynchronously this is rather fine.
[self onDidPreventUserFromSelectingViewControllerWithKey:[self screenKeyForViewController:viewController]];
return NO;
}
// If we're gonna allow navigation to `moreNavigationController`, then we need to ensure
// that on top of its stack there is no controller with preventNativeSelection enabled.
// In such case, we want to pop to root.
// We do it here, because in `tabBarController:didSelectViewController:` we won't receive
// `moreNavigationController` in case there is already a tab pushed on the stack.
if ([self isViewControllerTheMoreNavigationController:viewController]) {
auto *poppedViewController = [self popToRootInMoreNavigationControllerRespectSelectionPrevention:YES animated:NO];
if (poppedViewController != nil) {
// We actually popped something -> let's notify JS realm of this fact.
[self onDidPreventUserFromSelectingViewControllerWithKey:[self screenKeyForViewController:poppedViewController]];
}
}
_isHandlingExplicitSelectionUpdate = YES;
return YES;
}
- (void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController
{
RCTAssert(self == tabBarController, @"[RNScreens] Unexpected type of controller: %@", tabBarController.class);
// Can be UINavigationController in case of MoreNavigationController
RCTAssert(
[viewController isKindOfClass:RNSTabsScreenViewController.class] ||
[viewController isKindOfClass:UINavigationController.class],
@"[RNScreens] Unexpected type of controller: %@",
viewController.class);
[self userDidSelectViewController:viewController];
_isHandlingExplicitSelectionUpdate = NO;
}
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
RCTAssert(
self.moreNavigationController == navigationController,
@"[RNScreens] Unexpected view controller called delegate method: %@",
navigationController);
// The root view controller is of different type.
if ([viewController isKindOfClass:RNSTabsScreenViewController.class] &&
[self shouldProgressStateOnMoreNavigationControllerPush]) {
[self userDidSelectViewController:viewController];
[self setShouldProgressStateOnMoreNavigationControllerPush:NO];
}
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
#pragma mark - Signals related
- (void)updateChildViewControllersIfNeeded
{
if (_needsUpdateOfChildViewControllers) {
[self updateReactChildrenControllers];
}
}
- (void)updateReactChildrenControllers
{
RNSLog(@"TabBarCtrl updateReactChildrenControllers");
_needsUpdateOfChildViewControllers = false;
if (_tabScreenControllers == nil) {
RCTLogWarn(@"[RNScreens] Attempt to update react children while the _updatedChildren array is nil!");
return;
}
[self setViewControllers:_tabScreenControllers animated:[[self viewControllers] count] != 0];
}
- (void)updateSelectedViewControllerIfNeeded
{
if (_pendingOperation != nil) {
[self updateSelectedViewController];
}
}
- (void)updateSelectedViewController
{
if (_pendingOperation == nil || self.viewControllers.count == 0) {
return;
}
RNSLog(@"TabBarCtrl updateSelectedViewController");
[self updateSelectedViewControllerInner];
_pendingOperation = nil;
}
/**
* NEVER call this method directly. Call the proper function `updateSelectedViewController`
*
* The logic is extracted to an inner method to correctly manage _pendingOperation cleanup.
*/
- (void)updateSelectedViewControllerInner
{
UIViewController *_Nonnull currSelectedViewController = self.selectedViewController;
NSString *_Nonnull nextSelectedViewControllerKey = _pendingOperation.selectedScreenKey;
UIViewController *nextSelectedViewController = [self findChildViewControllerForKey:nextSelectedViewControllerKey];
RCTAssert(
nextSelectedViewController != nil,
@"[RNScreens] Failed to determine next selected view controller for key: %@",
nextSelectedViewControllerKey);
RCTAssert(
[nextSelectedViewController isKindOfClass:RNSTabsScreenViewController.class],
@"[RNScreens] nextSelectedViewController MUST be %@, got: %@",
RNSTabsScreenViewController.class,
nextSelectedViewController.class);
if (self.rejectStaleNavigationStateUpdates && [self isNavigationStateUpdateStale:_pendingOperation]) {
[self.tabsHostComponentView tabBarController:self
rejectedStateUpdateTo:_pendingOperation
currentState:_navigationState
withReason:RNSTabsNavigationStateRejectionReasonStale];
return;
}
if (currSelectedViewController == nextSelectedViewController && _navigationState != nil) {
// Nothing to do, we don't allow for programmatic repeat selection, unless
// we're during first render.
[self.tabsHostComponentView tabBarController:self
rejectedStateUpdateTo:_pendingOperation
currentState:_navigationState
withReason:RNSTabsNavigationStateRejectionReasonRepeated];
return;
}
// TODO: This code MUST be moved to some callback.
// Should this be called only on JS updates?
auto *screenViewController = static_cast<RNSTabsScreenViewController *>(nextSelectedViewController);
if (@available(iOS 26.0, *)) {
// On iOS 26, we need to set user interface style 2 parent views above the tab bar
// for this prop to take effect.
self.tabBar.superview.superview.overrideUserInterfaceStyle =
screenViewController.tabScreenComponentView.userInterfaceStyle;
} else {
self.tabBar.overrideUserInterfaceStyle = screenViewController.tabScreenComponentView.userInterfaceStyle;
}
RNSLog(@"Change selected view controller to: %@", nextSelectedViewControllerKey);
BOOL hasStateProgressed = [self updateSelectedViewControllerTo:nextSelectedViewController
withKey:nextSelectedViewControllerKey];
if (hasStateProgressed) {
RNSTabsNavigationStateUpdateContext *context =
[[RNSTabsNavigationStateUpdateContext alloc] initWithNavState:_navigationState
isRepeated:NO
hasTriggeredSpecialEffect:NO
actionOrigin:RNSTabsActionOriginProgrammaticJs];
[self.tabsHostComponentView tabBarController:self didUpdateStateTo:_navigationState withContext:context];
}
}
- (void)updateTabBarAppearanceIfNeeded
{
if (_needsUpdateOfTabBarAppearance) {
[self updateTabBarAppearance];
}
}
- (void)updateTabBarAppearance
{
RNSLog(@"TabBarCtrl updateTabBarAppearance");
_needsUpdateOfTabBarAppearance = false;
[_tabBarAppearanceCoordinator updateAppearanceOfTabBar:[self tabBar]
withHostComponentView:self.tabsHostComponentView
tabScreenControllers:_tabScreenControllers
imageLoader:[self.tabsHostComponentView reactImageLoader]];
}
- (void)updateTabBarA11yIfNeeded
{
for (UIViewController *tabViewController in self.viewControllers) {
auto screenView = static_cast<RNSTabsScreenViewController *>(tabViewController).tabScreenComponentView;
if (!screenView.tabBarItemNeedsA11yUpdate) {
continue;
}
screenView.tabBarItemNeedsA11yUpdate = NO;
tabViewController.tabBarItem.accessibilityIdentifier = screenView.tabItemTestID;
tabViewController.tabBarItem.accessibilityLabel = screenView.tabItemAccessibilityLabel;
}
}
#pragma mark - Utility
- (nullable RNSTabsScreenViewController *)findChildViewControllerForKey:(nullable NSString *)screenKey
{
if (screenKey == nil) {
return nil;
}
for (UIViewController *viewController in self.viewControllers) {
RCTAssert(
[viewController isKindOfClass:RNSTabsScreenViewController.class],
@"[RNScreens] Unexpected type of controller: %@",
viewController.class);
auto *screenViewController = static_cast<RNSTabsScreenViewController *>(viewController);
if ([screenViewController.getScreenKeyOrNull isEqualToString:screenKey]) {
return screenViewController;
}
}
return nil;
}
- (void)progressNavigationState:(nonnull NSString *)newSelectedScreenKey withOrigin:(RNSTabsActionOrigin)origin
{
RCTAssert(newSelectedScreenKey != nil, @"[RNScreens] newSelectedScreenKey MUST NOT be nil");
if (_navigationState == nil) {
_navigationState = [RNSTabsNavigationState stateWithSelectedScreenKey:newSelectedScreenKey provenance:0];
return;
}
_navigationState = [RNSTabsNavigationState stateWithSelectedScreenKey:newSelectedScreenKey
provenance:_navigationState.provenance + 1];
if (origin != RNSTabsActionOriginProgrammaticJs) {
_lastUINavigationState = [_navigationState cloneState];
}
}
/**
* Be sure to call this method IF AND ONLY IF you know that the `self.selectedViewController`
* is not the `moreNavigationController`.
*/
- (RNSTabsScreenViewController *)selectedScreenViewController
{
RCTAssert(
[self.selectedViewController isKindOfClass:RNSTabsScreenViewController.class],
@"[RNScreens] Unexpected type of selectedViewController: %@",
self.selectedViewController.class);
return static_cast<RNSTabsScreenViewController *>(self.selectedViewController);
}
- (nonnull NSString *)screenKeyForViewController:(nonnull UIViewController *)viewController
{
RCTAssert(
[viewController isKindOfClass:RNSTabsScreenViewController.class],
@"[RNScreens] Expected selected view controller to be of class %@, got: %@",
RNSTabsScreenViewController.class,
viewController.class);
auto *screenKey = static_cast<RNSTabsScreenViewController *>(viewController).getScreenKeyOrNull;
RCTAssert(screenKey != nil, @"[RNScreens] screenKey MUST NOT be nil");
return screenKey;
}
- (nonnull NSString *)screenKeyForSelectedViewController
{
return [self screenKeyForViewController:self.selectedViewController];
}
/**
* Detect and fix any mismatch between `_navigationState` and UIKit's actual selected view controller.
*
* This is called from the `setSelectedIndex:` / `setSelectedViewController:` overrides when
* the change was NOT initiated by a known code path (container update, delegate handling).
* The primary case is UIKit restoring a tab when the More navigation controller disappears
* during a horizontal size class transition on iPad.
*/
- (void)reconcileNavigationStateWithUIKitState
{
if (_navigationState == nil) {
// Before the first container update, _navigationState is nil — there is no established baseline
// to drift from. The normal initialization path (performContainerUpdate → progressNavigationState:)
// handles the nil → first state transition. Reconciling here would prematurely initialize state
// and emit a delegate notification before the controller is fully set up.
return;
}
if ([self isSelectedViewControllerTheMoreNavigationController]) {
// We don't want to progress the state in case of more navigation controller.
// If we're reconciling here, it means that it won't be handled correctly.
// I'm not aware of any flow where this could happen, hence assertion.
RCTAssert(NO, @"[RNScreens] Unexpected state reconciliation with More Navigation Controller");
return;
}
if (![self.selectedViewController isKindOfClass:RNSTabsScreenViewController.class]) {
RCTAssert(
NO,
@"[RNScreens] Unexpected controller type during state reconciliation: %@",
self.selectedViewController.class);
return;
}
NSString *selectedScreenKey = [self screenKeyForSelectedViewController];
if ([_navigationState.selectedScreenKey isEqualToString:selectedScreenKey]) {
return;
}
RNSLog(
@"TabBarCtrl reconcileNavigationStateWithUIKitState: %@ -> %@",
_navigationState.selectedScreenKey,
selectedScreenKey);
[self progressNavigationState:selectedScreenKey withOrigin:RNSTabsActionOriginImplicit];
auto *context = [[RNSTabsNavigationStateUpdateContext alloc] initWithNavState:_navigationState
isRepeated:NO
hasTriggeredSpecialEffect:NO
actionOrigin:RNSTabsActionOriginImplicit];
[self.tabsHostComponentView tabBarController:self didUpdateStateTo:_navigationState withContext:context];
}
/**
* This function assumes that the source of the state is NOT user. In current model, user update is never stale.
*/
- (BOOL)isNavigationStateUpdateStale:(nullable RNSTabsNavigationState *)newState
{
if (newState == nil) {
return YES;
}
if (_navigationState == nil || _lastUINavigationState == nil) {
return NO;
}
return newState.provenance < _lastUINavigationState.provenance;
}
#pragma mark-- More Navigation Controller
- (BOOL)canHaveMoreNavigationController
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
// https://developer.apple.com/documentation/uikit/uitabbarcontroller?language=objc#The-More-navigation-controller
return self.viewControllers.count > 5;
#else
return NO;
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
- (BOOL)isViewControllerTheMoreNavigationController:(nonnull UIViewController *)viewController
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
return [self canHaveMoreNavigationController] && viewController == self.moreNavigationController;
#else
return NO;
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
- (BOOL)isSelectedViewControllerTheMoreNavigationController
{
return [self isViewControllerTheMoreNavigationController:self.selectedViewController];
}
- (BOOL)isMoreNavigationControllerPresentInTabBar
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
return [self canHaveMoreNavigationController] &&
[self.tabBar.items containsObject:self.moreNavigationController.tabBarItem];
#else
return NO;
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
- (BOOL)isMoreNavigationControllerTabBarItemSelected
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
return [self canHaveMoreNavigationController] && self.tabBar.selectedItem == self.moreNavigationController.tabBarItem;
#else
return NO;
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
- (void)disableNavigationBarInMoreNavigationController
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
if (!self.moreNavigationController.navigationBar.isHidden) {
[self.moreNavigationController setNavigationBarHidden:YES animated:NO];
}
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
- (nullable UIViewController *)popToRootInMoreNavigationControllerRespectSelectionPrevention:
(BOOL)shouldRespectSelectionPrevention
animated:(BOOL)shouldAnimate
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
if ([self isMoreNavigationControllerPresentInTabBar] && self.moreNavigationController.viewControllers.count > 1) {
// We quietly assume here, that the root view controller is the `UIMoreListViewController`.
if (shouldRespectSelectionPrevention) {
UIViewController *topViewController = self.moreNavigationController.topViewController;
RCTAssert(
[topViewController isKindOfClass:RNSTabsScreenViewController.class],
@"[RNScreens] Unexpected type of view controller on moreNavigationControllerStack: %@",
topViewController.class);
RNSTabsScreenViewController *screenController = static_cast<RNSTabsScreenViewController *>(topViewController);
if (screenController.isPreventNativeSelectionEnabled) {
return [self popToRootMoreNavigationController:self.moreNavigationController animated:shouldAnimate];
}
} else {
return [self popToRootMoreNavigationController:self.moreNavigationController animated:shouldAnimate];
}
}
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
return nil;
}
/**
* Pops the top view controller from more navigation controller. We expect at most two controllers on the stack of more
* navigation controller. If this assumption ever becomes invalid, this method needs to be updated.
*
* @returns nil if there was nothing to pop, the topViewController otherwise.
*/
- (nullable UIViewController *)popToRootMoreNavigationController:
(nonnull UINavigationController *)moreNavigationController
animated:(BOOL)animated
{
if (moreNavigationController.viewControllers.count < 2) {
return nil;
}
auto *poppedViewControllers = [moreNavigationController popToRootViewControllerAnimated:animated];
RCTAssert(
poppedViewControllers != nil && poppedViewControllers.count == 1,
@"[RNScreens] Expected exactly one view controller to be popped");
return [poppedViewControllers firstObject];
}
- (void)prepareForMoreNavigationControllerHandlingIfNeeded
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
// This can be called multiple times in lifetime of `RNSTabBarController`.
// UIKit reuses the same `UIMoreNavigationController` instance, but resets both
// the delegate and the isa pointer when the More controller disappears from the
// tab bar (e.g. user resizing the app on iPad). We re-apply both unconditionally.
if (self.moreNavigationController.delegate == nil) {
self.moreNavigationController.delegate = self;
}
[self ensurePushInterceptorOnMoreNavigationController];
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
/// Creates a dynamic subclass of the runtime class of `moreNavigationController`
/// (which is the private `UIMoreNavigationController`) and overrides `pushViewController:animated:`
/// with our gating implementation.
///
/// The subclass name is derived from the actual runtime class of `moreNavigationController`
/// (e.g. `RNS_UIMoreNavigationController`), so if another library ISA-swizzles it first or Apple
/// changes the private class, each distinct original class gets its own correct dynamic subclass.
///
/// This method is idempotent — safe to call multiple times regardless of whether UIKit has
/// reset the ISA between calls. When the ISA already carries our `RNS_` prefix, we return
/// early. When UIKit has reset the ISA (e.g. iPad app resize crossing the threshold at which UIKit introduces the More
/// controller (currently >5 tabs)), the dynamic subclass is looked up (or created) and re-applied.
- (void)ensurePushInterceptorOnMoreNavigationController
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
Class currentClass = object_getClass(self.moreNavigationController);
const char *currentClassName = class_getName(currentClass);
// If the ISA already points to our dynamic subclass, the interceptor is in place.
// Without this guard, repeated calls when UIKit has NOT reset the ISA would stack
// `RNS_RNS_...` subclasses, causing infinite recursion in rns_pushViewController's
// objc_msgSendSuper call.
if (strncmp(currentClassName, "RNS_", 4) == 0) {
return;
}
// Build a unique subclass name per original runtime class: "RNS_<originalClassName>"
char dynamicSubclassName[256];
snprintf(dynamicSubclassName, sizeof(dynamicSubclassName), "RNS_%s", currentClassName);
Class dynamicSubclass = objc_getClass(dynamicSubclassName);
if (dynamicSubclass == nil) {
dynamicSubclass = objc_allocateClassPair(currentClass, dynamicSubclassName, 0);
RCTAssert(dynamicSubclass != nil, @"[RNScreens] Failed to allocate dynamic subclass of %s", currentClassName);
Method pushMethod = class_getInstanceMethod(currentClass, @selector(pushViewController:animated:));
class_addMethod(
dynamicSubclass,
@selector(pushViewController:animated:),
(IMP)rns_pushViewController,
method_getTypeEncoding(pushMethod));
objc_registerClassPair(dynamicSubclass);
}
object_setClass(self.moreNavigationController, dynamicSubclass);
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
/// Decides whether `moreNavigationController` should be allowed to push `viewController`.
/// This mirrors the logic in `shouldPreventNativeTabSelection:` for the More list context.
- (BOOL)moreNavigationController:(UINavigationController *)navigationController
shouldPushViewController:(UIViewController *)viewController
{
BOOL shouldPrevent = [self shouldPreventNativeTabSelection:viewController];
if (shouldPrevent) {
[self onDidPreventUserFromSelectingViewControllerWithKey:[self screenKeyForViewController:viewController]];
[self deselectMoreListSelectionInNavigationController:navigationController];
}
return !shouldPrevent;
}
/// When we prevent a push from the More list, the tapped table view cell stays highlighted
/// because UIKit expects the push to handle deselection on return. We deselect it manually.
- (void)deselectMoreListSelectionInNavigationController:(UINavigationController *)navigationController
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
UIViewController *topVC = navigationController.topViewController;
UITableView *tableView = [self findTableViewInView:topVC.view];
if (tableView != nil) {
NSIndexPath *selectedIndexPath = tableView.indexPathForSelectedRow;
if (selectedIndexPath != nil) {
[tableView deselectRowAtIndexPath:selectedIndexPath animated:YES];
}
} else {
RCTLogWarn(@"[RNScreens] Failed to find a table view to clear focus!");
}
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
}
/**
* Unbounded DFS looking for ANY `UITableView` in the subtree rooted at view.
* The `view` parameter is included in the search.
*/
- (nullable UITableView *)findTableViewInView:(UIView *)view
{
if ([view isKindOfClass:UITableView.class]) {
return (UITableView *)view;
}
for (UIView *subview in view.subviews) {
UITableView *result = [self findTableViewInView:subview];
if (result != nil) {
return result;
}
}
return nil;
}
/**
* This method allows getting the `moreNavigationController` instance under a couple of conditions.
*
* First, it verifies whether we are on an appropriate platform, where the `moreNavigationController`
* is available.
* Second, it verifies whether the `moreNavigationController` can even be in the interface right now.
*/
- (nullable UINavigationController *)resolveMoreNavigationController
{
#if RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
if ([self canHaveMoreNavigationController]) {
return self.moreNavigationController;
}
#endif // RNS_MORE_NAVIGATION_CONTROLLER_AVAILABLE
return nil;
}
#if !RCT_NEW_ARCH_ENABLED
#pragma mark - LEGACY Paper scheduling methods
// TODO: These could be moved to separate scheduler class
- (void)scheduleControllerUpdateIfNeeded
{
if (_isControllerFlushBlockScheduled) {
return;
}
_isControllerFlushBlockScheduled = YES;
auto *__weak weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
auto *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
strongSelf->_isControllerFlushBlockScheduled = NO;
[strongSelf reactMountingTransactionWillMount];
[strongSelf reactMountingTransactionDidMount];
});
}
#endif // !RCT_NEW_ARCH_ENABLED
- (void)updateOrientationIfNeeded
{
if (_needsOrientationUpdate) {
[self updateOrientation];
}
}
- (void)updateOrientation
{
_needsOrientationUpdate = false;
[RNSScreenWindowTraits enforceDesiredDeviceOrientation];
}
- (void)updateLayoutDirectionBelowIOS17IfNeeded
{
if (_needsLayoutDirectionUpdateBelowIOS17) {
[self updateLayoutDirectionBelowIOS17];
}
}
- (void)updateLayoutDirectionBelowIOS17
{
_needsLayoutDirectionUpdateBelowIOS17 = false;
#if RNS_IPHONE_OS_VERSION_AVAILABLE(17_0)
if (@available(iOS 17.0, *)) {
return;
}
#endif // RNS_IPHONE_OS_VERSION_AVAILABLE(17_0)
RCTAssert(
self.parentViewController != nil,
@"[RNScreens] Expected non-null parent view controller for layout direction update.");
[self.parentViewController
setOverrideTraitCollection:[UITraitCollection
traitCollectionWithLayoutDirection:self.tabsHostComponentView.layoutDirection]
forChildViewController:self];
}
#pragma mark - RNSOrientationProviding
#if !TARGET_OS_TV
- (RNSOrientation)evaluateOrientation
{
if ([self.selectedViewController respondsToSelector:@selector(evaluateOrientation)]) {
id<RNSOrientationProviding> selected = static_cast<id<RNSOrientationProviding>>(self.selectedViewController);
return [selected evaluateOrientation];