-
-
Notifications
You must be signed in to change notification settings - Fork 643
Expand file tree
/
Copy pathRNSScreenStackHeaderConfig.mm
More file actions
1153 lines (1009 loc) · 48.6 KB
/
RNSScreenStackHeaderConfig.mm
File metadata and controls
1153 lines (1009 loc) · 48.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
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 "RNSScreenStackHeaderConfig.h"
#import <React/RCTConversions.h>
#import <React/RCTFabricComponentsPlugins.h>
#import <React/RCTFont.h>
#import <React/RCTImageComponentView.h>
#import <React/RCTImageLoader.h>
#import <React/RCTImageSource.h>
#import <React/RCTMountingTransactionObserving.h>
#import <React/UIView+React.h>
#import <ReactCommon/TurboModuleUtils.h>
#import <cxxreact/ReactNativeVersion.h>
#import <react/renderer/components/image/ImageProps.h>
#import <react/renderer/components/rnscreens/ComponentDescriptors.h>
#import <react/renderer/components/rnscreens/EventEmitters.h>
#import <react/renderer/components/rnscreens/Props.h>
#import <react/renderer/components/rnscreens/RCTComponentViewHelpers.h>
#import <react/utils/ManagedObjectWrapper.h>
#import <rnscreens/RNSScreenStackHeaderConfigComponentDescriptor.h>
#import "RCTImageComponentView+RNSScreenStackHeaderConfig.h"
#import "RNSBackBarButtonItem.h"
#import "RNSBarButtonItem.h"
#import "RNSConvert.h"
#import "RNSDefines.h"
#import "RNSScreen.h"
#import "RNSSearchBar.h"
#import "UINavigationBar+RNSUtility.h"
namespace react = facebook::react;
static const NSNumber *const DEFAULT_TITLE_FONT_SIZE = @17;
static const NSNumber *const DEFAULT_TITLE_LARGE_FONT_SIZE = @34;
@interface RCTImageLoader (Private)
- (id<RCTImageCache>)imageCache;
@end
@implementation NSString (RNSStringUtil)
+ (BOOL)rnscreens_isBlankOrNull:(NSString *)string
{
if (string == nil) {
return YES;
}
return [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0;
}
@end
@interface RNSScreenStackHeaderConfig () <RCTMountingTransactionObserving>
@end
@implementation RNSScreenStackHeaderConfig {
NSMutableArray<RNSScreenStackHeaderSubview *> *_reactSubviews;
BOOL _initialPropsSet;
react::RNSScreenStackHeaderConfigState _lastSendState;
react::RNSScreenStackHeaderConfigShadowNode::ConcreteState::Shared _state;
/// Whether a react subview has been added / removed in current transaction. This flag is reset after each react
/// transaction via RCTMountingTransactionObserving protocol.
bool _addedReactSubviewsInCurrentTransaction;
RCTImageLoader *_imageLoader;
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const react::RNSScreenStackHeaderConfigProps>();
_props = defaultProps;
_show = YES;
_translucent = NO;
_addedReactSubviewsInCurrentTransaction = false;
_lastSendState = react::RNSScreenStackHeaderConfigState(react::Size{}, react::EdgeInsets{});
[self initProps];
}
return self;
}
- (void)initProps
{
self.hidden = YES;
_reactSubviews = [NSMutableArray new];
_backTitleVisible = YES;
_blurEffect = RNSBlurEffectStyleNone;
_synchronousShadowStateUpdatesEnabled = YES;
}
RNS_IGNORE_SUPER_CALL_BEGIN
- (UIView *)reactSuperview
{
return _screenView;
}
- (NSArray<UIView *> *)reactSubviews
{
return _reactSubviews;
}
RNS_IGNORE_SUPER_CALL_END
- (void)removeFromSuperview
{
[super removeFromSuperview];
_screenView = nil;
}
// this method is never invoked by the system since this view
// is not added to native view hierarchy so we can apply our logic
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
for (RNSScreenStackHeaderSubview *subview in _reactSubviews) {
if (subview.type == RNSScreenStackHeaderSubviewTypeLeft || subview.type == RNSScreenStackHeaderSubviewTypeRight) {
// E.g. presence of focused search bar might cause the subviews to be temporarily unmounted & we don't want
// them to be touch targets then, otherwise we might e.g. block cancel button.
// See: https://github.com/software-mansion/react-native-screens/issues/2899
if (subview.window == nil) {
continue;
}
// We wrap the headerLeft/Right component in a UIBarButtonItem
// so we need to hit test subviews, because of the view flattening
// (we match RCTViewComponentView implementation).
for (UIView *headerComponentSubview in [subview.subviews reverseObjectEnumerator]) {
CGPoint convertedPoint = [self convertPoint:point toView:headerComponentSubview];
UIView *hitTestResult = [headerComponentSubview hitTest:convertedPoint withEvent:event];
if (hitTestResult != nil) {
return hitTestResult;
}
}
}
}
return nil;
}
- (void)updateViewControllerIfNeeded
{
UIViewController *vc = _screenView.controller;
UINavigationController *nav = (UINavigationController *)vc.parentViewController;
UIViewController *nextVC = nav.visibleViewController;
if (nav.transitionCoordinator != nil) {
// if navigator is performing transition instead of allowing to update of `visibleConttroller`
// we look at `topController`. This is because during transitiong the `visibleController` won't
// point to the controller that is going to be revealed after transition. This check fixes the
// problem when config gets updated while the transition is ongoing.
nextVC = nav.topViewController;
}
// we want updates sent to the VC directly below modal too since it is also visible
BOOL isPresentingVC = nextVC != nil && vc.presentedViewController == nextVC && vc == nav.topViewController;
BOOL isInFullScreenModal = nav == nil && _screenView.stackPresentation == RNSScreenStackPresentationFullScreenModal;
// if nav is nil, it means we can be in a fullScreen modal, so there is no nextVC, but we still want to update
if (vc != nil && (nextVC == vc || isInFullScreenModal || isPresentingVC)) {
[RNSScreenStackHeaderConfig updateViewController:self.screenView.controller withConfig:self animated:YES];
// As the header might have change in `updateViewController` we need to ensure that header height
// returned by the `onHeaderHeightChange` event is correct.
[self.screenView.controller calculateAndNotifyHeaderHeightChangeIsModal:NO];
}
}
- (void)layoutNavigationControllerView
{
// We need to layout navigation controller view after translucent prop changes, because otherwise
// frame of RNSScreen will not be changed and screen content will remain the same size.
// For more details look at https://github.com/software-mansion/react-native-screens/issues/1158
UIViewController *vc = _screenView.controller;
UINavigationController *navctr = vc.navigationController;
[navctr.view setNeedsLayout];
}
- (void)updateShadowStateWithSize:(CGSize)size edgeInsets:(NSDirectionalEdgeInsets)edgeInsets
{
// I believe Yoga handles RTL internally & .left will be treated as .right in RTL etc.
react::EdgeInsets convertedEdgeInsets{
.left = edgeInsets.leading, .top = edgeInsets.top, .right = edgeInsets.trailing, .bottom = edgeInsets.bottom};
react::Size convertedSize = RCTSizeFromCGSize(size);
auto newState = react::RNSScreenStackHeaderConfigState(convertedSize, convertedEdgeInsets);
if (newState != _lastSendState) {
_lastSendState = newState;
_state->updateState(
std::move(newState)
#if REACT_NATIVE_VERSION_MINOR >= 82
,
_synchronousShadowStateUpdatesEnabled ? facebook::react::EventQueue::UpdateMode::unstable_Immediate
: facebook::react::EventQueue::UpdateMode::Asynchronous
#endif
);
}
}
- (void)updateHeaderStateInShadowTreeInContextOfNavigationBar:(nullable UINavigationBar *)navigationBar
{
if (!navigationBar) {
return;
}
[self updateShadowStateWithSize:navigationBar.frame.size
edgeInsets:[self computeEdgeInsetsOfNavigationBar:navigationBar]];
for (RNSScreenStackHeaderSubview *subview in self.reactSubviews) {
[subview updateShadowStateInContextOfAncestorView:navigationBar];
}
}
- (NSDirectionalEdgeInsets)computeEdgeInsetsOfNavigationBar:(nonnull UINavigationBar *)navigationBar
{
NSDirectionalEdgeInsets navBarMargins = [navigationBar directionalLayoutMargins];
NSDirectionalEdgeInsets navBarContentMargins = [navigationBar.rnscreens_findContentView directionalLayoutMargins];
BOOL isDisplayingBackButton = [self shouldBackButtonBeVisibleInNavigationBar:navigationBar];
// 44.0 is just "closed eyes default". It is so on device I've tested with, nothing more.
UIView *barButtonView = isDisplayingBackButton ? navigationBar.rnscreens_findBackButtonWrapperView : nil;
CGFloat platformBackButtonWidth = barButtonView != nil ? barButtonView.frame.size.width : 44.0f;
const auto edgeInsets = NSDirectionalEdgeInsets{
.leading =
navBarMargins.leading + navBarContentMargins.leading + (isDisplayingBackButton ? platformBackButtonWidth : 0),
.trailing = navBarMargins.trailing + navBarContentMargins.trailing,
};
return edgeInsets;
}
- (BOOL)hasSubviewOfType:(RNSScreenStackHeaderSubviewType)type
{
for (RNSScreenStackHeaderSubview *subview in _reactSubviews) {
if (subview.type == type) {
return YES;
}
}
return NO;
}
- (BOOL)hasSubviewLeft
{
return [self hasSubviewOfType:RNSScreenStackHeaderSubviewTypeLeft];
}
- (BOOL)shouldHeaderBeVisible
{
return self.show;
}
- (BOOL)shouldBackButtonBeVisibleInNavigationBar:(nullable UINavigationBar *)navBar
{
return navBar.backItem != nil && !self.hideBackButton &&
!(self.backButtonInCustomView == false && self.hasSubviewLeft);
}
+ (void)setAnimatedConfig:(UIViewController *)vc withConfig:(RNSScreenStackHeaderConfig *)config
{
UINavigationBar *navbar = ((UINavigationController *)vc.parentViewController).navigationBar;
[navbar setTintColor:config.color];
// font customized on the navigation item level, so nothing to do here
}
+ (void)setTitleAttibutes:(NSDictionary *)attrs forButton:(UIBarButtonItem *)button
{
[button setTitleTextAttributes:attrs forState:UIControlStateNormal];
[button setTitleTextAttributes:attrs forState:UIControlStateHighlighted];
[button setTitleTextAttributes:attrs forState:UIControlStateDisabled];
[button setTitleTextAttributes:attrs forState:UIControlStateSelected];
[button setTitleTextAttributes:attrs forState:UIControlStateFocused];
}
- (UIImage *)loadBackButtonImageInViewController:(UIViewController *)vc
{
BOOL hasBackButtonImage = NO;
for (RNSScreenStackHeaderSubview *subview in self.reactSubviews) {
if (subview.type == RNSScreenStackHeaderSubviewTypeBackButton && subview.subviews.count > 0) {
hasBackButtonImage = YES;
RCTImageComponentView *imageView = subview.subviews[0];
if (imageView.image == nil) {
// This is yet another workaround for loading custom back icon. It turns out that under
// certain circumstances image attribute can be null despite the app running in production
// mode (when images are loaded from the filesystem). This can happen because image attribute
// is reset when image view is detached from window, and also in some cases initialization
// does not populate the frame of the image view before the loading start. The latter result
// in the image attribute not being updated. We manually set frame to the size of an image
// in order to trigger proper reload that'd update the image attribute.
RCTImageSource *imageSource = [RNSScreenStackHeaderConfig imageSourceFromImageView:imageView];
[imageView reactSetFrame:CGRectMake(
imageView.frame.origin.x,
imageView.frame.origin.y,
imageSource.size.width,
imageSource.size.height)];
}
UIImage *image = imageView.image;
#ifndef NDEBUG
// IMPORTANT!!!
// image can be nil in DEV MODE ONLY
//
// It is so, because in dev mode images are loaded over HTTP from the packager. In that case
// we first check if image is already loaded in cache and if it is, we take it from cache and
// display immediately. Otherwise we wait for the transition to finish and retry updating
// header config.
// Unfortunately due to some problems in UIKit we cannot update the image while the screen
// transition is ongoing. This results in the settings being reset after the transition is done
// to the state from before the transition.
if (image == nil) {
// in DEV MODE we try to load from cache (we use private API for that as it is not exposed
// publically in headers).
RCTImageSource *imageSource = [RNSScreenStackHeaderConfig imageSourceFromImageView:imageView];
RCTImageLoader *imageLoader = _imageLoader;
image = [imageLoader.imageCache
imageForUrl:imageSource.request.URL.absoluteString
size:imageSource.size
scale:imageSource.scale
resizeMode:resizeModeFromCppEquiv(
std::static_pointer_cast<const react::ImageProps>(imageView.props)->resizeMode)];
}
#endif // !NDEBUG
if (image == nil) {
// This will be triggered if the image is not in the cache yet. What we do is we wait until
// the end of transition and run header config updates again. We could potentially wait for
// image on load to trigger, but that would require even more private method hacking.
if (vc.transitionCoordinator) {
[vc.transitionCoordinator
animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
// nothing, we just want completion
}
completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
// in order for new back button image to be loaded we need to trigger another change
// in back button props that'd make UIKit redraw the button. Otherwise the changes are
// not reflected. Here we change back button visibility which is then immediately restored
#if !TARGET_OS_TV
vc.navigationItem.hidesBackButton = YES;
#endif
[self updateViewControllerIfNeeded];
}];
}
return [UIImage new];
} else {
return image;
}
}
}
return nil;
}
+ (void)willShowViewController:(UIViewController *)vc
animated:(BOOL)animated
withConfig:(RNSScreenStackHeaderConfig *)config
{
[self updateViewController:vc withConfig:config animated:animated];
// As the header might have change in `updateViewController` we need to ensure that header height
// returned by the `onHeaderHeightChange` event is correct.
if ([vc isKindOfClass:[RNSScreen class]]) {
[(RNSScreen *)vc calculateAndNotifyHeaderHeightChangeIsModal:NO];
}
}
+ (UINavigationBarAppearance *)buildAppearance:(UIViewController *)vc withConfig:(RNSScreenStackHeaderConfig *)config
{
UINavigationBarAppearance *appearance = [UINavigationBarAppearance new];
if (config.backgroundColor && CGColorGetAlpha(config.backgroundColor.CGColor) == 0.) {
// Preserve the shadow properties in case the user wants to show the shadow on scroll.
UIColor *shadowColor = appearance.shadowColor;
UIImage *shadowImage = appearance.shadowImage;
// transparent background color
[appearance configureWithTransparentBackground];
if (!config.hideShadow) {
appearance.shadowColor = shadowColor;
appearance.shadowImage = shadowImage;
}
} else {
[appearance configureWithOpaqueBackground];
}
// set background color if specified
if (config.backgroundColor) {
appearance.backgroundColor = config.backgroundColor;
}
switch (config.blurEffect) {
case RNSBlurEffectStyleNone:
appearance.backgroundEffect = nil;
break;
case RNSBlurEffectStyleSystemDefault:
RCTLogError(@"[RNScreens] ScreenStack does not support RNSBlurEffectStyleSystemDefault.");
break;
default:
appearance.backgroundEffect =
[UIBlurEffect effectWithStyle:[RNSConvert tryConvertRNSBlurEffectStyleToUIBlurEffectStyle:config.blurEffect]];
}
if (config.hideShadow) {
appearance.shadowColor = nil;
}
if (config.titleFontFamily || config.titleFontSize || config.titleFontWeight || config.titleColor) {
NSMutableDictionary *attrs = [NSMutableDictionary new];
// Ignore changing header title color on visionOS
#if !TARGET_OS_VISION
if (config.titleColor) {
attrs[NSForegroundColorAttributeName] = config.titleColor;
}
#endif
NSString *family = config.titleFontFamily ?: nil;
NSNumber *size = config.titleFontSize ?: [DEFAULT_TITLE_FONT_SIZE copy];
NSString *weight = config.titleFontWeight ?: nil;
if (family || weight) {
attrs[NSFontAttributeName] = [RCTFont updateFont:nil
withFamily:config.titleFontFamily
size:size
weight:weight
style:nil
variant:nil
scaleMultiplier:1.0];
} else {
attrs[NSFontAttributeName] = [UIFont boldSystemFontOfSize:[size floatValue]];
}
appearance.titleTextAttributes = attrs;
}
if (config.largeTitleFontFamily || config.largeTitleFontSize || config.largeTitleFontWeight ||
config.largeTitleColor || config.titleColor) {
NSMutableDictionary *largeAttrs = [NSMutableDictionary new];
// Ignore changing header title color on visionOS
#if !TARGET_OS_VISION
if (config.largeTitleColor || config.titleColor) {
largeAttrs[NSForegroundColorAttributeName] = config.largeTitleColor ? config.largeTitleColor : config.titleColor;
}
#endif
NSString *largeFamily = config.largeTitleFontFamily ?: nil;
NSNumber *largeSize = config.largeTitleFontSize ?: [DEFAULT_TITLE_LARGE_FONT_SIZE copy];
NSString *largeWeight = config.largeTitleFontWeight ?: nil;
if (largeFamily || largeWeight) {
largeAttrs[NSFontAttributeName] = [RCTFont updateFont:nil
withFamily:largeFamily
size:largeSize
weight:largeWeight
style:nil
variant:nil
scaleMultiplier:1.0];
} else {
largeAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:[largeSize floatValue] weight:UIFontWeightBold];
}
appearance.largeTitleTextAttributes = largeAttrs;
}
UIImage *backButtonImage = [config loadBackButtonImageInViewController:vc];
if (backButtonImage) {
[appearance setBackIndicatorImage:backButtonImage transitionMaskImage:backButtonImage];
} else if (appearance.backIndicatorImage) {
[appearance setBackIndicatorImage:nil transitionMaskImage:nil];
}
return appearance;
}
+ (void)updateViewController:(UIViewController *)vc
withConfig:(RNSScreenStackHeaderConfig *)config
animated:(BOOL)animated
{
UINavigationItem *navitem = vc.navigationItem;
UINavigationController *navctr = (UINavigationController *)vc.parentViewController;
// When modal is shown the underlying RNSScreen isn't attached to any navigation controller.
// During the modal dismissal transition this update method is called on this RNSScreen resulting in nil navctr.
// After the transition is completed it will be called again and will configure the navigation controller correctly.
// Also see: https://github.com/software-mansion/react-native-screens/pull/2336
if (navctr == nil) {
return;
}
NSUInteger currentIndex = [navctr.viewControllers indexOfObject:vc];
UIViewController *prevVC = currentIndex > 0 ? [navctr.viewControllers objectAtIndex:currentIndex - 1] : nil;
UINavigationItem *prevItem = currentIndex > 0 ? prevVC.navigationItem : nil;
BOOL wasHidden = navctr.navigationBarHidden;
BOOL shouldHide = config == nil || !config.shouldHeaderBeVisible;
if (!shouldHide && !config.translucent) {
// when nav bar is not translucent we change edgesForExtendedLayout to avoid system laying out
// the screen underneath navigation controllers
vc.edgesForExtendedLayout = UIRectEdgeAll - UIRectEdgeTop;
} else {
// system default is UIRectEdgeAll
vc.edgesForExtendedLayout = UIRectEdgeAll;
}
[config applySemanticContentAttributeIfNeededToNavCtrl:navctr];
if (shouldHide) {
navitem.title = config.title;
// Setting navigation bar visibility is split to mitigate iOS 26 bug with bar button items.
[navctr setNavigationBarHidden:YES animated:animated];
return;
}
navctr.navigationBar.overrideUserInterfaceStyle = config.userInterfaceStyle;
#if !TARGET_OS_TV
[config configureBackItem:prevItem withPrevVC:prevVC];
if (config.largeTitle) {
navctr.navigationBar.prefersLargeTitles = YES;
}
navitem.largeTitleDisplayMode =
config.largeTitle ? UINavigationItemLargeTitleDisplayModeAlways : UINavigationItemLargeTitleDisplayModeNever;
#endif
UINavigationBarAppearance *appearance = [self buildAppearance:vc withConfig:config];
navitem.standardAppearance = appearance;
navitem.compactAppearance = appearance;
// appearance does not apply to the tvOS so we need to use lagacy customization
#if TARGET_OS_TV
navctr.navigationBar.titleTextAttributes = appearance.titleTextAttributes;
navctr.navigationBar.backgroundColor = appearance.backgroundColor;
#endif
UINavigationBarAppearance *scrollEdgeAppearance =
[[UINavigationBarAppearance alloc] initWithBarAppearance:appearance];
if (config.largeTitleBackgroundColor != nil) {
// Add support for using a fully transparent bar when the backgroundColor is set to transparent.
if (CGColorGetAlpha(config.largeTitleBackgroundColor.CGColor) == 0.) {
// This will also remove the background blur effect in the large title which is otherwise inherited from the
// standard appearance.
[scrollEdgeAppearance configureWithTransparentBackground];
// This must be set to nil otherwise a default view will be added to the navigation bar background with an
// opaque background.
scrollEdgeAppearance.backgroundColor = nil;
} else {
scrollEdgeAppearance.backgroundColor = config.largeTitleBackgroundColor;
}
}
if (config.largeTitleHideShadow) {
scrollEdgeAppearance.shadowColor = nil;
}
navitem.scrollEdgeAppearance = scrollEdgeAppearance;
#if !TARGET_OS_TV
navitem.hidesBackButton = config.hideBackButton;
navitem.leftItemsSupplementBackButton = config.backButtonInCustomView;
#endif
navitem.titleView = nil;
navitem.leftBarButtonItems = nil;
navitem.rightBarButtonItems = nil;
#if !TARGET_OS_TV
// We want to set navitem.searchController to nil only if we are sure
// that we are removing the search bar from the header.
bool searchBarPresent = false;
#endif /* !TARGET_OS_TV */
for (RNSScreenStackHeaderSubview *subview in config.reactSubviews) {
// This code should be kept in sync on Fabric with analogous switch statement in
// `- [RNSScreenStackHeaderConfig replaceNavigationBarViewsWithSnapshotOfSubview:]` method.
switch (subview.type) {
case RNSScreenStackHeaderSubviewTypeLeft: {
NSArray<UIBarButtonItem *> *currentItems = navitem.leftBarButtonItems ?: @[];
NSMutableArray<UIBarButtonItem *> *mutableItems = [currentItems mutableCopy];
[mutableItems addObject:[subview getUIBarButtonItem]];
navitem.leftBarButtonItems = mutableItems;
break;
}
case RNSScreenStackHeaderSubviewTypeRight: {
NSArray<UIBarButtonItem *> *currentItems = navitem.rightBarButtonItems ?: @[];
NSMutableArray<UIBarButtonItem *> *mutableItems = [currentItems mutableCopy];
[mutableItems addObject:[subview getUIBarButtonItem]];
navitem.rightBarButtonItems = mutableItems;
break;
}
case RNSScreenStackHeaderSubviewTypeCenter:
case RNSScreenStackHeaderSubviewTypeTitle: {
navitem.titleView = subview;
break;
}
case RNSScreenStackHeaderSubviewTypeSearchBar: {
if (subview.subviews == nil || [subview.subviews count] == 0) {
RCTLogWarn(
@"Failed to attach search bar to the header. We recommend using `useLayoutEffect` when managing "
"searchBar properties dynamically. \n\nSee: github.com/software-mansion/react-native-screens/issues/1188");
break;
}
if ([subview.subviews[0] isKindOfClass:[RNSSearchBar class]]) {
#if !TARGET_OS_TV
RNSSearchBar *searchBar = subview.subviews[0];
searchBarPresent = true;
navitem.searchController = searchBar.controller;
navitem.hidesSearchBarWhenScrolling = searchBar.hideWhenScrolling;
#if RNS_IPHONE_OS_VERSION_AVAILABLE(16_0)
if (@available(iOS 16.0, *)) {
navitem.preferredSearchBarPlacement = [searchBar placementAsUINavigationItemSearchBarPlacement];
}
#endif /* Check for iOS 16.0 */
#if RNS_IPHONE_OS_VERSION_AVAILABLE(26_0)
if (@available(iOS 26.0, *)) {
// On iOS 26 beta 6, we observe that search bar is buggy if we change the configuration
// of search bar multiple times. Sometimes, when `stacked` search bar is enabled for root screen,
// it does not show up. It's because we're calling *this* method 2 additional times before
// UIKit does, in order to handle some other bugs. Only for the third time, UIKit "wants" to
// integrate the search bar - we suspect that this final "reconfiguration" causes the bug.
// Setting searchBarPlacementAllowsToolbarIntegration to NO fixes the issue without changing
// older stack logic and shouldn't impact users negatively - if user wants `stacked` placement,
// the search bar should not be integrated anyway. We should monitor if workaround is still
// necessary in next iOS versions and remove it when the bug gets fixed.
// More details: https://github.com/software-mansion/react-native-screens/pull/3168
if (navitem.preferredSearchBarPlacement != UINavigationItemSearchBarPlacementStacked) {
navitem.searchBarPlacementAllowsToolbarIntegration = searchBar.allowToolbarIntegration;
} else {
navitem.searchBarPlacementAllowsToolbarIntegration = NO;
}
}
#endif /* Check for iOS 26.0 */
#endif /* !TARGET_OS_TV */
}
break;
}
case RNSScreenStackHeaderSubviewTypeBackButton: {
break;
}
}
}
#if !TARGET_OS_TV
if (!searchBarPresent) {
navitem.searchController = nil;
}
#endif /* !TARGET_OS_TV */
// This assignment should be done after `navitem.titleView = ...` assignment (iOS 16.0 bug).
// See: https://github.com/software-mansion/react-native-screens/issues/1570 (comments)
navitem.title = config.title;
navitem.leftBarButtonItems = [config barButtonItemsFromConfigs:config.headerLeftBarButtonItems
withCurrentItems:navitem.leftBarButtonItems];
navitem.rightBarButtonItems = [config barButtonItemsFromConfigs:config.headerRightBarButtonItems
withCurrentItems:navitem.rightBarButtonItems];
// Setting navigation bar visibility is split to mitigate iOS 26 bug with bar button items
// (setting nav bar visibility should be done after `navitem.*BarButtonItems`).
RCTAssert(shouldHide == NO, @"[RNScreens] RNSScreenStackHeaderConfig: expected shouldHide to be NO.");
[navctr setNavigationBarHidden:NO animated:animated];
if (animated && vc.transitionCoordinator != nil &&
vc.transitionCoordinator.presentationStyle == UIModalPresentationNone && !wasHidden) {
// when there is an ongoing transition we may need to update navbar setting in animation block
// using animateAlongsideTransition. However, we only do that given the transition is not a modal
// transition (presentationStyle == UIModalPresentationNone) and that the bar was not previously
// hidden. This is because both for modal transitions and transitions from screen with hidden bar
// the transition animation block does not get triggered. This is ok, because with both of those
// types of transitions there is no "shared" navigation bar that needs to be updated in an animated
// way.
[vc.transitionCoordinator
animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
[self setAnimatedConfig:vc withConfig:config];
}
completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
if ([context isCancelled]) {
UIViewController *fromVC = [context viewControllerForKey:UITransitionContextFromViewControllerKey];
RNSScreenStackHeaderConfig *config = nil;
for (UIView *subview in fromVC.view.reactSubviews) {
if ([subview isKindOfClass:[RNSScreenStackHeaderConfig class]]) {
config = (RNSScreenStackHeaderConfig *)subview;
break;
}
}
[self setAnimatedConfig:fromVC withConfig:config];
}
}];
} else {
[self setAnimatedConfig:vc withConfig:config];
}
}
- (void)configureBackItem:(nullable UINavigationItem *)prevItem
withPrevVC:(nullable UIViewController *)prevVC API_UNAVAILABLE(tvos)
{
#if !TARGET_OS_TV
if (prevItem == nil) {
return;
}
const auto *config = self;
const auto isBackTitleBlank = [NSString rnscreens_isBlankOrNull:config.backTitle] == YES;
NSString *resolvedBackTitle = isBackTitleBlank ? prevItem.title : config.backTitle;
// If previous screen controller was recreated (e.g. when you go back to tab with stack that has multiple screens),
// its navigationItem may not have any information from screen's headerConfig, including the title.
// If this is the case, we attempt to extract the title from previous screen's config directly.
if (resolvedBackTitle == nil && [prevVC isKindOfClass:[RNSScreen class]]) {
RNSScreen *prevScreen = static_cast<RNSScreen *>(prevVC);
resolvedBackTitle = prevScreen.screenView.findHeaderConfig.title;
}
prevItem.backButtonTitle = resolvedBackTitle;
// This has any effect only in case the `backBarButtonItem` is not set.
// We apply it before we configure the back item, because it might get overriden.
prevItem.backButtonDisplayMode = config.backButtonDisplayMode;
if (config.isBackTitleVisible) {
RNSBackBarButtonItem *backBarButtonItem = [[RNSBackBarButtonItem alloc] initWithTitle:resolvedBackTitle
style:UIBarButtonItemStylePlain
target:nil
action:nil];
auto shouldUseCustomBackBarButtonItem = config.disableBackButtonMenu;
[backBarButtonItem setMenuHidden:config.disableBackButtonMenu];
if ((config.backTitleFontFamily &&
// While being used by react-navigation, the `backTitleFontFamily` will
// be set to "System" by default - which is the system default font.
// To avoid always considering the font as customized, we need to have an additional check.
// See: https://github.com/software-mansion/react-native-screens/pull/2105#discussion_r1565222738
![config.backTitleFontFamily isEqual:@"System"]) ||
config.backTitleFontSize) {
shouldUseCustomBackBarButtonItem = YES;
NSMutableDictionary *attrs = [NSMutableDictionary new];
NSNumber *size = config.backTitleFontSize ?: @17;
if (config.backTitleFontFamily) {
attrs[NSFontAttributeName] = [RCTFont updateFont:nil
withFamily:config.backTitleFontFamily
size:size
weight:nil
style:nil
variant:nil
scaleMultiplier:1.0];
} else {
attrs[NSFontAttributeName] = [UIFont boldSystemFontOfSize:[size floatValue]];
}
[RNSScreenStackHeaderConfig setTitleAttibutes:attrs forButton:backBarButtonItem];
}
// Prevent unnecessary assignment of backBarButtonItem if it is not customized,
// as assigning one will override the native behavior of automatically shortening
// the title to "Back" or hide the back title if there's not enough space.
// See: https://github.com/software-mansion/react-native-screens/issues/1589
if (shouldUseCustomBackBarButtonItem) {
prevItem.backBarButtonItem = backBarButtonItem;
}
} else {
// back button title should be not visible next to back button,
// but it should still appear in back menu
prevItem.backButtonDisplayMode = UINavigationItemBackButtonDisplayModeMinimal;
}
#endif
}
- (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *)navCtrl
{
if ((self.direction == UISemanticContentAttributeForceLeftToRight ||
self.direction == UISemanticContentAttributeForceRightToLeft) &&
// iOS 12 cancels swipe gesture when direction is changed. See #1091
navCtrl.view.semanticContentAttribute != self.direction) {
// This is needed for swipe back gesture direction
navCtrl.view.semanticContentAttribute = self.direction;
// This is responsible for the direction of the navigationBar and its contents
navCtrl.navigationBar.semanticContentAttribute = self.direction;
[[UIButton appearanceWhenContainedInInstancesOfClasses:@[ navCtrl.navigationBar.class ]]
setSemanticContentAttribute:self.direction];
[[UIView appearanceWhenContainedInInstancesOfClasses:@[ navCtrl.navigationBar.class ]]
setSemanticContentAttribute:self.direction];
[[UISearchBar appearanceWhenContainedInInstancesOfClasses:@[ navCtrl.navigationBar.class ]]
setSemanticContentAttribute:self.direction];
}
}
- (NSArray<UIBarButtonItem *> *)barButtonItemsFromConfigs:(NSArray<NSDictionary<NSString *, id> *> *)dicts
withCurrentItems:(NSArray<UIBarButtonItem *> *)currentItems
{
if (dicts.count == 0) {
return currentItems;
}
NSMutableArray<UIBarButtonItem *> *items = [NSMutableArray arrayWithCapacity:currentItems.count + dicts.count];
[items addObjectsFromArray:currentItems];
for (NSUInteger i = 0; i < dicts.count; i++) {
NSDictionary *dict = dicts[i];
if (dict[@"buttonId"] || dict[@"menu"]) {
RNSBarButtonItem *item = [[RNSBarButtonItem alloc] initWithConfig:dict
action:^(NSString *buttonId) {
auto eventEmitter = std::static_pointer_cast<const facebook::react::RNSScreenStackHeaderConfigEventEmitter>(
self->_eventEmitter);
if (eventEmitter && buttonId) {
eventEmitter->onPressHeaderBarButtonItem(
facebook::react::RNSScreenStackHeaderConfigEventEmitter::OnPressHeaderBarButtonItem{
.buttonId = std::string([buttonId UTF8String])});
}
}
menuAction:^(NSString *menuId) {
auto eventEmitter = std::static_pointer_cast<const facebook::react::RNSScreenStackHeaderConfigEventEmitter>(
self->_eventEmitter);
if (eventEmitter && menuId) {
eventEmitter->onPressHeaderBarButtonMenuItem(
facebook::react::RNSScreenStackHeaderConfigEventEmitter::OnPressHeaderBarButtonMenuItem{
.menuId = std::string([menuId UTF8String])});
}
}
imageLoader:_imageLoader];
NSNumber *index = dict[@"index"];
if (index.integerValue < items.count) {
[items insertObject:item atIndex:index.integerValue];
} else {
[items addObject:item];
}
} else if (dict[@"spacing"]) {
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
target:nil
action:nil];
NSNumber *spacingValue = dict[@"spacing"];
item.width = [spacingValue doubleValue];
NSNumber *index = dict[@"index"];
if (index.integerValue < items.count) {
[items insertObject:item atIndex:index.integerValue];
} else {
[items addObject:item];
}
}
}
return items;
}
RNS_IGNORE_SUPER_CALL_BEGIN
- (void)insertReactSubview:(RNSScreenStackHeaderSubview *)subview atIndex:(NSInteger)atIndex
{
[_reactSubviews insertObject:subview atIndex:atIndex];
subview.reactSuperview = self;
}
- (void)removeReactSubview:(RNSScreenStackHeaderSubview *)subview
{
[_reactSubviews removeObject:subview];
}
RNS_IGNORE_SUPER_CALL_END
#pragma mark - Fabric specific
- (void)mountChildComponentView:(UIView<RCTComponentViewProtocol> *)childComponentView index:(NSInteger)index
{
if (![childComponentView isKindOfClass:[RNSScreenStackHeaderSubview class]]) {
RCTLogError(@"ScreenStackHeader only accepts children of type ScreenStackHeaderSubview");
return;
}
RCTAssert(
childComponentView.superview == nil,
@"Attempt to mount already mounted component view. (parent: %@, child: %@, index: %@, existing parent: %@)",
self,
childComponentView,
@(index),
@([childComponentView.superview tag]));
// [_reactSubviews insertObject:(RNSScreenStackHeaderSubview *)childComponentView atIndex:index];
[self insertReactSubview:(RNSScreenStackHeaderSubview *)childComponentView atIndex:index];
_addedReactSubviewsInCurrentTransaction = true;
}
- (void)unmountChildComponentView:(UIView<RCTComponentViewProtocol> *)childComponentView index:(NSInteger)index
{
BOOL isGoingToBeRemoved = _screenView.isMarkedForUnmountInCurrentTransaction;
if (isGoingToBeRemoved) {
// For explanation of why we can make a snapshot here despite the fact that our children are already
// unmounted see https://github.com/software-mansion/react-native-screens/pull/2261
[self replaceNavigationBarViewsWithSnapshotOfSubview:(RNSScreenStackHeaderSubview *)childComponentView];
}
[_reactSubviews removeObject:(RNSScreenStackHeaderSubview *)childComponentView];
[childComponentView removeFromSuperview];
if (!isGoingToBeRemoved) {
[self updateViewControllerIfNeeded];
}
}
- (void)mountingTransactionDidMount:(const facebook::react::MountingTransaction &)transaction
withSurfaceTelemetry:(const facebook::react::SurfaceTelemetry &)surfaceTelemetry
{
if (_addedReactSubviewsInCurrentTransaction) {
[self updateViewControllerIfNeeded];
// This call is made for the sake of https://github.com/software-mansion/react-native-screens/pull/2466.
// In case header subview is added **after initial screen render** the system positions it correctly,
// however `viewDidLayoutSubviews` is not called on `RNSNavigationController` and updated frame sizes of the
// subviews are not sent to ShadowTree leading to issues with pressables.
// Sending state update to ShadowTree from here is not enough, because native layout has not yet
// happened after the child had been added. Requesting layout on navigation bar does not trigger layout callbacks
// either, however doing so on main view of navigation controller does the trick.
if (self.shouldHeaderBeVisible) {
[self layoutNavigationControllerView];
}
}
_addedReactSubviewsInCurrentTransaction = false;
}
- (void)replaceNavigationBarViewsWithSnapshotOfSubview:(RNSScreenStackHeaderSubview *)childComponentView
{
if (childComponentView.window != nil) {
UINavigationItem *navitem = _screenView.controller.navigationItem;
UIView *snapshot = [childComponentView snapshotViewAfterScreenUpdates:NO];
// This code should be kept in sync with analogous switch statement in
// `+ [RNSScreenStackHeaderConfig updateViewController: withConfig: animated:]` method.
switch (childComponentView.type) {
case RNSScreenStackHeaderSubviewTypeLeft: {
for (UIBarButtonItem *item in navitem.leftBarButtonItems) {
if (item.customView == childComponentView) {
item.customView = snapshot;
}
}
break;
}
case RNSScreenStackHeaderSubviewTypeCenter:
case RNSScreenStackHeaderSubviewTypeTitle:
navitem.titleView = snapshot;
break;
case RNSScreenStackHeaderSubviewTypeRight: {
for (UIBarButtonItem *item in navitem.rightBarButtonItems) {
if (item.customView == childComponentView) {
item.customView = snapshot;
}
}
break;
}
case RNSScreenStackHeaderSubviewTypeSearchBar:
case RNSScreenStackHeaderSubviewTypeBackButton:
break;
default:
RCTLogError(@"[RNScreens] Unhandled subview type: %ld", childComponentView.type);
}
}
}
static RCTResizeMode resizeModeFromCppEquiv(react::ImageResizeMode resizeMode)
{
switch (resizeMode) {
case react::ImageResizeMode::Cover:
return RCTResizeModeCover;
case react::ImageResizeMode::Contain:
return RCTResizeModeContain;
case react::ImageResizeMode::Stretch:
return RCTResizeModeStretch;
case react::ImageResizeMode::Center:
return RCTResizeModeCenter;
case react::ImageResizeMode::Repeat:
return RCTResizeModeRepeat;
default:
// Both RCTConvert and ImageProps use this as a default as of RN 0.76
return RCTResizeModeStretch;
}
}
+ (RCTImageSource *)imageSourceFromImageView:(RCTImageComponentView *)view
{
const auto &imageProps = *std::static_pointer_cast<const react::ImageProps>(view.props);
react::ImageSource cppImageSource = imageProps.sources.at(0);
auto imageSize = CGSize{cppImageSource.size.width, cppImageSource.size.height};
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:RCTNSStringFromStringNilIfEmpty(cppImageSource.uri)]];
RCTImageSource *imageSource = [[RCTImageSource alloc] initWithURLRequest:request
size:imageSize
scale:cppImageSource.scale];
return imageSource;
}
#pragma mark - RCTComponentViewProtocol
- (void)prepareForRecycle
{
[super prepareForRecycle];
_initialPropsSet = NO;
_lastSendState = react::RNSScreenStackHeaderConfigState(react::Size{}, react::EdgeInsets{});
}
- (NSNumber *)getFontSizePropValue:(int)value
{
if (value > 0)
return [NSNumber numberWithInt:value];
return nil;
}
+ (react::ComponentDescriptorProvider)componentDescriptorProvider
{
return react::concreteComponentDescriptorProvider<react::RNSScreenStackHeaderConfigComponentDescriptor>();
}
- (void)updateProps:(react::Props::Shared const &)props oldProps:(react::Props::Shared const &)oldProps
{
const auto &oldScreenProps = *std::static_pointer_cast<const react::RNSScreenStackHeaderConfigProps>(_props);
const auto &newScreenProps = *std::static_pointer_cast<const react::RNSScreenStackHeaderConfigProps>(props);
BOOL needsNavigationControllerLayout = !_initialPropsSet;