RCTUIManager.m 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RCTUIManager.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. #import "RCTAccessibilityManager.h"
  10. #import "RCTAssert.h"
  11. #import "RCTBridge+Private.h"
  12. #import "RCTBridge.h"
  13. #import "RCTComponent.h"
  14. #import "RCTComponentData.h"
  15. #import "RCTConvert.h"
  16. #import "RCTDefines.h"
  17. #import "RCTEventDispatcher.h"
  18. #import "RCTLayoutAnimation.h"
  19. #import "RCTLayoutAnimationGroup.h"
  20. #import "RCTLog.h"
  21. #import "RCTModuleData.h"
  22. #import "RCTModuleMethod.h"
  23. #import "RCTProfile.h"
  24. #import "RCTRootContentView.h"
  25. #import "RCTRootShadowView.h"
  26. #import "RCTRootViewInternal.h"
  27. #import "RCTScrollableProtocol.h"
  28. #import "RCTShadowView+Internal.h"
  29. #import "RCTShadowView.h"
  30. #import "RCTSurfaceRootShadowView.h"
  31. #import "RCTSurfaceRootView.h"
  32. #import "RCTUIManagerObserverCoordinator.h"
  33. #import "RCTUIManagerUtils.h"
  34. #import "RCTUtils.h"
  35. #import "RCTView.h"
  36. #import "RCTViewManager.h"
  37. #import "UIView+React.h"
  38. static void RCTTraverseViewNodes(id<RCTComponent> view, void (^block)(id<RCTComponent>))
  39. {
  40. if (view.reactTag) {
  41. block(view);
  42. for (id<RCTComponent> subview in view.reactSubviews) {
  43. RCTTraverseViewNodes(subview, block);
  44. }
  45. }
  46. }
  47. NSString *const RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification = @"RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification";
  48. @implementation RCTUIManager
  49. {
  50. // Root views are only mutated on the shadow queue
  51. NSMutableSet<NSNumber *> *_rootViewTags;
  52. NSMutableArray<RCTViewManagerUIBlock> *_pendingUIBlocks;
  53. // Animation
  54. RCTLayoutAnimationGroup *_layoutAnimationGroup; // Main thread only
  55. NSMutableDictionary<NSNumber *, RCTShadowView *> *_shadowViewRegistry; // RCT thread only
  56. NSMutableDictionary<NSNumber *, UIView *> *_viewRegistry; // Main thread only
  57. NSMapTable<RCTShadowView *, NSArray<NSString *> *> *_shadowViewsWithUpdatedProps; // UIManager queue only.
  58. NSHashTable<RCTShadowView *> *_shadowViewsWithUpdatedChildren; // UIManager queue only.
  59. // Keyed by viewName
  60. NSMutableDictionary *_componentDataByName;
  61. }
  62. @synthesize bridge = _bridge;
  63. RCT_EXPORT_MODULE()
  64. + (BOOL)requiresMainQueueSetup
  65. {
  66. return NO;
  67. }
  68. - (void)dealloc
  69. {
  70. [NSNotificationCenter.defaultCenter removeObserver:self];
  71. }
  72. - (void)invalidate
  73. {
  74. /**
  75. * Called on the JS Thread since all modules are invalidated on the JS thread
  76. */
  77. // This only accessed from the shadow queue
  78. _pendingUIBlocks = nil;
  79. RCTExecuteOnMainQueue(^{
  80. RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"UIManager invalidate", nil);
  81. for (NSNumber *rootViewTag in self->_rootViewTags) {
  82. UIView *rootView = self->_viewRegistry[rootViewTag];
  83. if ([rootView conformsToProtocol:@protocol(RCTInvalidating)]) {
  84. [(id<RCTInvalidating>)rootView invalidate];
  85. }
  86. }
  87. self->_rootViewTags = nil;
  88. self->_shadowViewRegistry = nil;
  89. self->_viewRegistry = nil;
  90. self->_bridge = nil;
  91. [[NSNotificationCenter defaultCenter] removeObserver:self];
  92. RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
  93. });
  94. }
  95. - (NSMutableDictionary<NSNumber *, RCTShadowView *> *)shadowViewRegistry
  96. {
  97. // NOTE: this method only exists so that it can be accessed by unit tests
  98. if (!_shadowViewRegistry) {
  99. _shadowViewRegistry = [NSMutableDictionary new];
  100. }
  101. return _shadowViewRegistry;
  102. }
  103. - (NSMutableDictionary<NSNumber *, UIView *> *)viewRegistry
  104. {
  105. // NOTE: this method only exists so that it can be accessed by unit tests
  106. if (!_viewRegistry) {
  107. _viewRegistry = [NSMutableDictionary new];
  108. }
  109. return _viewRegistry;
  110. }
  111. - (void)setBridge:(RCTBridge *)bridge
  112. {
  113. RCTAssert(_bridge == nil, @"Should not re-use same UIIManager instance");
  114. _bridge = bridge;
  115. _shadowViewRegistry = [NSMutableDictionary new];
  116. _viewRegistry = [NSMutableDictionary new];
  117. _shadowViewsWithUpdatedProps = [NSMapTable weakToStrongObjectsMapTable];
  118. _shadowViewsWithUpdatedChildren = [NSHashTable weakObjectsHashTable];
  119. // Internal resources
  120. _pendingUIBlocks = [NSMutableArray new];
  121. _rootViewTags = [NSMutableSet new];
  122. _observerCoordinator = [RCTUIManagerObserverCoordinator new];
  123. // Get view managers from bridge=
  124. _componentDataByName = [NSMutableDictionary new];
  125. for (Class moduleClass in _bridge.moduleClasses) {
  126. if ([moduleClass isSubclassOfClass:[RCTViewManager class]]) {
  127. RCTComponentData *componentData = [[RCTComponentData alloc] initWithManagerClass:moduleClass
  128. bridge:_bridge];
  129. _componentDataByName[componentData.name] = componentData;
  130. }
  131. }
  132. [[NSNotificationCenter defaultCenter] addObserver:self
  133. selector:@selector(didReceiveNewContentSizeMultiplier)
  134. name:RCTAccessibilityManagerDidUpdateMultiplierNotification
  135. object:_bridge.accessibilityManager];
  136. #if !TARGET_OS_TV
  137. [[NSNotificationCenter defaultCenter] addObserver:self
  138. selector:@selector(namedOrientationDidChange)
  139. name:UIDeviceOrientationDidChangeNotification
  140. object:nil];
  141. #endif
  142. [RCTLayoutAnimation initializeStatics];
  143. }
  144. #pragma mark - Event emitting
  145. - (void)didReceiveNewContentSizeMultiplier
  146. {
  147. // Report the event across the bridge.
  148. #pragma clang diagnostic push
  149. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  150. [_bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateContentSizeMultiplier"
  151. body:@([_bridge.accessibilityManager multiplier])];
  152. #pragma clang diagnostic pop
  153. RCTExecuteOnUIManagerQueue(^{
  154. [[NSNotificationCenter defaultCenter] postNotificationName:RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification
  155. object:self];
  156. [self setNeedsLayout];
  157. });
  158. }
  159. #if !TARGET_OS_TV
  160. // Names and coordinate system from html5 spec:
  161. // https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation
  162. // https://developer.mozilla.org/en-US/docs/Web/API/Screen.lockOrientation
  163. static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation)
  164. {
  165. NSString *name;
  166. NSNumber *degrees = @0;
  167. BOOL isLandscape = NO;
  168. switch(orientation) {
  169. case UIDeviceOrientationPortrait:
  170. name = @"portrait-primary";
  171. break;
  172. case UIDeviceOrientationPortraitUpsideDown:
  173. name = @"portrait-secondary";
  174. degrees = @180;
  175. break;
  176. case UIDeviceOrientationLandscapeRight:
  177. name = @"landscape-primary";
  178. degrees = @-90;
  179. isLandscape = YES;
  180. break;
  181. case UIDeviceOrientationLandscapeLeft:
  182. name = @"landscape-secondary";
  183. degrees = @90;
  184. isLandscape = YES;
  185. break;
  186. case UIDeviceOrientationFaceDown:
  187. case UIDeviceOrientationFaceUp:
  188. case UIDeviceOrientationUnknown:
  189. // Unsupported
  190. return nil;
  191. }
  192. return @{
  193. @"name": name,
  194. @"rotationDegrees": degrees,
  195. @"isLandscape": @(isLandscape),
  196. };
  197. }
  198. - (void)namedOrientationDidChange
  199. {
  200. NSDictionary *orientationEvent = deviceOrientationEventBody([UIDevice currentDevice].orientation);
  201. if (!orientationEvent) {
  202. return;
  203. }
  204. #pragma clang diagnostic push
  205. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  206. [_bridge.eventDispatcher sendDeviceEventWithName:@"namedOrientationDidChange"
  207. body:orientationEvent];
  208. #pragma clang diagnostic pop
  209. }
  210. #endif
  211. - (dispatch_queue_t)methodQueue
  212. {
  213. return RCTGetUIManagerQueue();
  214. }
  215. - (void)registerRootViewTag:(NSNumber *)rootTag
  216. {
  217. RCTAssertUIManagerQueue();
  218. RCTAssert(RCTIsReactRootView(rootTag),
  219. @"Attempt to register rootTag (%@) which is not actually root tag.", rootTag);
  220. RCTAssert(![_rootViewTags containsObject:rootTag],
  221. @"Attempt to register rootTag (%@) which was already registred.", rootTag);
  222. [_rootViewTags addObject:rootTag];
  223. // Registering root shadow view
  224. RCTSurfaceRootShadowView *shadowView = [RCTSurfaceRootShadowView new];
  225. shadowView.reactTag = rootTag;
  226. _shadowViewRegistry[rootTag] = shadowView;
  227. // Registering root view
  228. RCTExecuteOnMainQueue(^{
  229. RCTSurfaceRootView *rootView = [RCTSurfaceRootView new];
  230. rootView.reactTag = rootTag;
  231. self->_viewRegistry[rootTag] = rootView;
  232. });
  233. }
  234. - (void)registerRootView:(RCTRootContentView *)rootView
  235. {
  236. RCTAssertMainQueue();
  237. NSNumber *reactTag = rootView.reactTag;
  238. RCTAssert(RCTIsReactRootView(reactTag),
  239. @"View %@ with tag #%@ is not a root view", rootView, reactTag);
  240. UIView *existingView = _viewRegistry[reactTag];
  241. RCTAssert(existingView == nil || existingView == rootView,
  242. @"Expect all root views to have unique tag. Added %@ twice", reactTag);
  243. CGSize availableSize = rootView.availableSize;
  244. // Register view
  245. _viewRegistry[reactTag] = rootView;
  246. // Register shadow view
  247. RCTExecuteOnUIManagerQueue(^{
  248. if (!self->_viewRegistry) {
  249. return;
  250. }
  251. RCTRootShadowView *shadowView = [RCTRootShadowView new];
  252. shadowView.availableSize = availableSize;
  253. shadowView.reactTag = reactTag;
  254. shadowView.viewName = NSStringFromClass([rootView class]);
  255. self->_shadowViewRegistry[shadowView.reactTag] = shadowView;
  256. [self->_rootViewTags addObject:reactTag];
  257. });
  258. }
  259. - (NSString *)viewNameForReactTag:(NSNumber *)reactTag
  260. {
  261. RCTAssertUIManagerQueue();
  262. return _shadowViewRegistry[reactTag].viewName;
  263. }
  264. - (UIView *)viewForReactTag:(NSNumber *)reactTag
  265. {
  266. RCTAssertMainQueue();
  267. return _viewRegistry[reactTag];
  268. }
  269. - (RCTShadowView *)shadowViewForReactTag:(NSNumber *)reactTag
  270. {
  271. RCTAssertUIManagerQueue();
  272. return _shadowViewRegistry[reactTag];
  273. }
  274. - (void)_executeBlockWithShadowView:(void (^)(RCTShadowView *shadowView))block forTag:(NSNumber *)tag
  275. {
  276. RCTAssertMainQueue();
  277. RCTExecuteOnUIManagerQueue(^{
  278. RCTShadowView *shadowView = self->_shadowViewRegistry[tag];
  279. if (shadowView == nil) {
  280. RCTLogInfo(@"Could not locate shadow view with tag #%@, this is probably caused by a temporary inconsistency between native views and shadow views.", tag);
  281. return;
  282. }
  283. block(shadowView);
  284. });
  285. }
  286. - (void)setAvailableSize:(CGSize)availableSize forRootView:(UIView *)rootView
  287. {
  288. RCTAssertMainQueue();
  289. [self _executeBlockWithShadowView:^(RCTShadowView *shadowView) {
  290. RCTAssert([shadowView isKindOfClass:[RCTRootShadowView class]], @"Located shadow view is actually not root view.");
  291. RCTRootShadowView *rootShadowView = (RCTRootShadowView *)shadowView;
  292. if (CGSizeEqualToSize(availableSize, rootShadowView.availableSize)) {
  293. return;
  294. }
  295. rootShadowView.availableSize = availableSize;
  296. [self setNeedsLayout];
  297. } forTag:rootView.reactTag];
  298. }
  299. - (void)setLocalData:(NSObject *)localData forView:(UIView *)view
  300. {
  301. RCTAssertMainQueue();
  302. [self _executeBlockWithShadowView:^(RCTShadowView *shadowView) {
  303. shadowView.localData = localData;
  304. [self setNeedsLayout];
  305. } forTag:view.reactTag];
  306. }
  307. /**
  308. * TODO(yuwang): implement the nativeID functionality in a more efficient way
  309. * instead of searching the whole view tree
  310. */
  311. - (UIView *)viewForNativeID:(NSString *)nativeID withRootTag:(NSNumber *)rootTag
  312. {
  313. RCTAssertMainQueue();
  314. UIView *view = [self viewForReactTag:rootTag];
  315. return [self _lookupViewForNativeID:nativeID inView:view];
  316. }
  317. - (UIView *)_lookupViewForNativeID:(NSString *)nativeID inView:(UIView *)view
  318. {
  319. RCTAssertMainQueue();
  320. if (view != nil && [nativeID isEqualToString:view.nativeID]) {
  321. return view;
  322. }
  323. for (UIView *subview in view.subviews) {
  324. UIView *targetView = [self _lookupViewForNativeID:nativeID inView:subview];
  325. if (targetView != nil) {
  326. return targetView;
  327. }
  328. }
  329. return nil;
  330. }
  331. - (void)setSize:(CGSize)size forView:(UIView *)view
  332. {
  333. RCTAssertMainQueue();
  334. [self _executeBlockWithShadowView:^(RCTShadowView *shadowView) {
  335. if (CGSizeEqualToSize(size, shadowView.size)) {
  336. return;
  337. }
  338. shadowView.size = size;
  339. [self setNeedsLayout];
  340. } forTag:view.reactTag];
  341. }
  342. - (void)setIntrinsicContentSize:(CGSize)intrinsicContentSize forView:(UIView *)view
  343. {
  344. RCTAssertMainQueue();
  345. [self _executeBlockWithShadowView:^(RCTShadowView *shadowView) {
  346. if (CGSizeEqualToSize(shadowView.intrinsicContentSize, intrinsicContentSize)) {
  347. return;
  348. }
  349. shadowView.intrinsicContentSize = intrinsicContentSize;
  350. [self setNeedsLayout];
  351. } forTag:view.reactTag];
  352. }
  353. /**
  354. * Unregisters views from registries
  355. */
  356. - (void)_purgeChildren:(NSArray<id<RCTComponent>> *)children
  357. fromRegistry:(NSMutableDictionary<NSNumber *, id<RCTComponent>> *)registry
  358. {
  359. for (id<RCTComponent> child in children) {
  360. RCTTraverseViewNodes(registry[child.reactTag], ^(id<RCTComponent> subview) {
  361. RCTAssert(![subview isReactRootView], @"Root views should not be unregistered");
  362. if ([subview conformsToProtocol:@protocol(RCTInvalidating)]) {
  363. [(id<RCTInvalidating>)subview invalidate];
  364. }
  365. [registry removeObjectForKey:subview.reactTag];
  366. });
  367. }
  368. }
  369. - (void)addUIBlock:(RCTViewManagerUIBlock)block
  370. {
  371. RCTAssertUIManagerQueue();
  372. if (!block || !_viewRegistry) {
  373. return;
  374. }
  375. [_pendingUIBlocks addObject:block];
  376. }
  377. - (void)prependUIBlock:(RCTViewManagerUIBlock)block
  378. {
  379. RCTAssertUIManagerQueue();
  380. if (!block || !_viewRegistry) {
  381. return;
  382. }
  383. [_pendingUIBlocks insertObject:block atIndex:0];
  384. }
  385. - (void)setNextLayoutAnimationGroup:(RCTLayoutAnimationGroup *)layoutAnimationGroup
  386. {
  387. RCTAssertMainQueue();
  388. if (_layoutAnimationGroup && ![_layoutAnimationGroup isEqual:layoutAnimationGroup]) {
  389. RCTLogWarn(@"Warning: Overriding previous layout animation with new one before the first began:\n%@ -> %@.",
  390. [_layoutAnimationGroup description],
  391. [layoutAnimationGroup description]);
  392. }
  393. _layoutAnimationGroup = layoutAnimationGroup;
  394. }
  395. - (RCTViewManagerUIBlock)uiBlockWithLayoutUpdateForRootView:(RCTRootShadowView *)rootShadowView
  396. {
  397. RCTAssertUIManagerQueue();
  398. NSHashTable<RCTShadowView *> *affectedShadowViews = [NSHashTable weakObjectsHashTable];
  399. [rootShadowView layoutWithAffectedShadowViews:affectedShadowViews];
  400. if (!affectedShadowViews.count) {
  401. // no frame change results in no UI update block
  402. return nil;
  403. }
  404. typedef struct {
  405. CGRect frame;
  406. UIUserInterfaceLayoutDirection layoutDirection;
  407. BOOL isNew;
  408. BOOL parentIsNew;
  409. RCTDisplayType displayType;
  410. } RCTFrameData;
  411. // Construct arrays then hand off to main thread
  412. NSUInteger count = affectedShadowViews.count;
  413. NSMutableArray *reactTags = [[NSMutableArray alloc] initWithCapacity:count];
  414. NSMutableData *framesData = [[NSMutableData alloc] initWithLength:sizeof(RCTFrameData) * count];
  415. {
  416. NSUInteger index = 0;
  417. RCTFrameData *frameDataArray = (RCTFrameData *)framesData.mutableBytes;
  418. for (RCTShadowView *shadowView in affectedShadowViews) {
  419. reactTags[index] = shadowView.reactTag;
  420. RCTLayoutMetrics layoutMetrics = shadowView.layoutMetrics;
  421. frameDataArray[index++] = (RCTFrameData){
  422. layoutMetrics.frame,
  423. layoutMetrics.layoutDirection,
  424. shadowView.isNewView,
  425. shadowView.superview.isNewView,
  426. layoutMetrics.displayType
  427. };
  428. }
  429. }
  430. for (RCTShadowView *shadowView in affectedShadowViews) {
  431. // We have to do this after we build the parentsAreNew array.
  432. shadowView.newView = NO;
  433. NSNumber *reactTag = shadowView.reactTag;
  434. if (shadowView.onLayout) {
  435. CGRect frame = shadowView.layoutMetrics.frame;
  436. shadowView.onLayout(@{
  437. @"layout": @{
  438. @"x": @(frame.origin.x),
  439. @"y": @(frame.origin.y),
  440. @"width": @(frame.size.width),
  441. @"height": @(frame.size.height),
  442. },
  443. });
  444. }
  445. if (
  446. RCTIsReactRootView(reactTag) &&
  447. [shadowView isKindOfClass:[RCTRootShadowView class]]
  448. ) {
  449. CGSize contentSize = shadowView.layoutMetrics.frame.size;
  450. RCTExecuteOnMainQueue(^{
  451. UIView *view = self->_viewRegistry[reactTag];
  452. RCTAssert(view != nil, @"view (for ID %@) not found", reactTag);
  453. RCTRootView *rootView = (RCTRootView *)[view superview];
  454. if ([rootView isKindOfClass:[RCTRootView class]]) {
  455. rootView.intrinsicContentSize = contentSize;
  456. }
  457. });
  458. }
  459. }
  460. // Perform layout (possibly animated)
  461. return ^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  462. const RCTFrameData *frameDataArray = (const RCTFrameData *)framesData.bytes;
  463. RCTLayoutAnimationGroup *layoutAnimationGroup = uiManager->_layoutAnimationGroup;
  464. __block NSUInteger completionsCalled = 0;
  465. NSInteger index = 0;
  466. for (NSNumber *reactTag in reactTags) {
  467. RCTFrameData frameData = frameDataArray[index++];
  468. UIView *view = viewRegistry[reactTag];
  469. CGRect frame = frameData.frame;
  470. UIUserInterfaceLayoutDirection layoutDirection = frameData.layoutDirection;
  471. BOOL isNew = frameData.isNew;
  472. RCTLayoutAnimation *updatingLayoutAnimation = isNew ? nil : layoutAnimationGroup.updatingLayoutAnimation;
  473. BOOL shouldAnimateCreation = isNew && !frameData.parentIsNew;
  474. RCTLayoutAnimation *creatingLayoutAnimation = shouldAnimateCreation ? layoutAnimationGroup.creatingLayoutAnimation : nil;
  475. BOOL isHidden = frameData.displayType == RCTDisplayTypeNone;
  476. void (^completion)(BOOL) = ^(BOOL finished) {
  477. completionsCalled++;
  478. if (layoutAnimationGroup.callback && completionsCalled == count) {
  479. layoutAnimationGroup.callback(@[@(finished)]);
  480. // It's unsafe to call this callback more than once, so we nil it out here
  481. // to make sure that doesn't happen.
  482. layoutAnimationGroup.callback = nil;
  483. }
  484. };
  485. if (view.reactLayoutDirection != layoutDirection) {
  486. view.reactLayoutDirection = layoutDirection;
  487. }
  488. if (view.isHidden != isHidden) {
  489. view.hidden = isHidden;
  490. }
  491. if (creatingLayoutAnimation) {
  492. // Animate view creation
  493. [view reactSetFrame:frame];
  494. CATransform3D finalTransform = view.layer.transform;
  495. CGFloat finalOpacity = view.layer.opacity;
  496. NSString *property = creatingLayoutAnimation.property;
  497. if ([property isEqualToString:@"scaleXY"]) {
  498. view.layer.transform = CATransform3DMakeScale(0, 0, 0);
  499. } else if ([property isEqualToString:@"scaleX"]) {
  500. view.layer.transform = CATransform3DMakeScale(0, 1, 0);
  501. } else if ([property isEqualToString:@"scaleY"]) {
  502. view.layer.transform = CATransform3DMakeScale(1, 0, 0);
  503. } else if ([property isEqualToString:@"opacity"]) {
  504. view.layer.opacity = 0.0;
  505. } else {
  506. RCTLogError(@"Unsupported layout animation createConfig property %@",
  507. creatingLayoutAnimation.property);
  508. }
  509. [creatingLayoutAnimation performAnimations:^{
  510. if (
  511. [property isEqualToString:@"scaleX"] ||
  512. [property isEqualToString:@"scaleY"] ||
  513. [property isEqualToString:@"scaleXY"]
  514. ) {
  515. view.layer.transform = finalTransform;
  516. } else if ([property isEqualToString:@"opacity"]) {
  517. view.layer.opacity = finalOpacity;
  518. }
  519. } withCompletionBlock:completion];
  520. } else if (updatingLayoutAnimation) {
  521. // Animate view update
  522. [updatingLayoutAnimation performAnimations:^{
  523. [view reactSetFrame:frame];
  524. } withCompletionBlock:completion];
  525. } else {
  526. // Update without animation
  527. [view reactSetFrame:frame];
  528. completion(YES);
  529. }
  530. }
  531. // Clean up
  532. uiManager->_layoutAnimationGroup = nil;
  533. };
  534. }
  535. /**
  536. * A method to be called from JS, which takes a container ID and then releases
  537. * all subviews for that container upon receipt.
  538. */
  539. RCT_EXPORT_METHOD(removeSubviewsFromContainerWithID:(nonnull NSNumber *)containerID)
  540. {
  541. id<RCTComponent> container = _shadowViewRegistry[containerID];
  542. RCTAssert(container != nil, @"container view (for ID %@) not found", containerID);
  543. NSUInteger subviewsCount = [container reactSubviews].count;
  544. NSMutableArray<NSNumber *> *indices = [[NSMutableArray alloc] initWithCapacity:subviewsCount];
  545. for (NSUInteger childIndex = 0; childIndex < subviewsCount; childIndex++) {
  546. [indices addObject:@(childIndex)];
  547. }
  548. [self manageChildren:containerID
  549. moveFromIndices:nil
  550. moveToIndices:nil
  551. addChildReactTags:nil
  552. addAtIndices:nil
  553. removeAtIndices:indices];
  554. }
  555. /**
  556. * Disassociates children from container. Doesn't remove from registries.
  557. * TODO: use [NSArray getObjects:buffer] to reuse same fast buffer each time.
  558. *
  559. * @returns Array of removed items.
  560. */
  561. - (NSArray<id<RCTComponent>> *)_childrenToRemoveFromContainer:(id<RCTComponent>)container
  562. atIndices:(NSArray<NSNumber *> *)atIndices
  563. {
  564. // If there are no indices to move or the container has no subviews don't bother
  565. // We support parents with nil subviews so long as they're all nil so this allows for this behavior
  566. if (atIndices.count == 0 || [container reactSubviews].count == 0) {
  567. return nil;
  568. }
  569. // Construction of removed children must be done "up front", before indices are disturbed by removals.
  570. NSMutableArray<id<RCTComponent>> *removedChildren = [NSMutableArray arrayWithCapacity:atIndices.count];
  571. RCTAssert(container != nil, @"container view (for ID %@) not found", container);
  572. for (NSNumber *indexNumber in atIndices) {
  573. NSUInteger index = indexNumber.unsignedIntegerValue;
  574. if (index < [container reactSubviews].count) {
  575. [removedChildren addObject:[container reactSubviews][index]];
  576. }
  577. }
  578. if (removedChildren.count != atIndices.count) {
  579. NSString *message = [NSString stringWithFormat:@"removedChildren count (%tu) was not what we expected (%tu)",
  580. removedChildren.count, atIndices.count];
  581. RCTFatal(RCTErrorWithMessage(message));
  582. }
  583. return removedChildren;
  584. }
  585. - (void)_removeChildren:(NSArray<id<RCTComponent>> *)children
  586. fromContainer:(id<RCTComponent>)container
  587. {
  588. for (id<RCTComponent> removedChild in children) {
  589. [container removeReactSubview:removedChild];
  590. }
  591. }
  592. /**
  593. * Remove subviews from their parent with an animation.
  594. */
  595. - (void)_removeChildren:(NSArray<UIView *> *)children
  596. fromContainer:(UIView *)container
  597. withAnimation:(RCTLayoutAnimationGroup *)animation
  598. {
  599. RCTAssertMainQueue();
  600. RCTLayoutAnimation *deletingLayoutAnimation = animation.deletingLayoutAnimation;
  601. __block NSUInteger completionsCalled = 0;
  602. for (UIView *removedChild in children) {
  603. void (^completion)(BOOL) = ^(BOOL finished) {
  604. completionsCalled++;
  605. [removedChild removeFromSuperview];
  606. if (animation.callback && completionsCalled == children.count) {
  607. animation.callback(@[@(finished)]);
  608. // It's unsafe to call this callback more than once, so we nil it out here
  609. // to make sure that doesn't happen.
  610. animation.callback = nil;
  611. }
  612. };
  613. // Hack: At this moment we have two contradict intents.
  614. // First one: We want to delete the view from view hierarchy.
  615. // Second one: We want to animate this view, which implies the existence of this view in the hierarchy.
  616. // So, we have to remove this view from React's view hierarchy but postpone removing from UIKit's hierarchy.
  617. // Here the problem: the default implementation of `-[UIView removeReactSubview:]` also removes the view from UIKit's hierarchy.
  618. // So, let's temporary restore the view back after removing.
  619. // To do so, we have to memorize original `superview` (which can differ from `container`) and an index of removed view.
  620. UIView *originalSuperview = removedChild.superview;
  621. NSUInteger originalIndex = [originalSuperview.subviews indexOfObjectIdenticalTo:removedChild];
  622. [container removeReactSubview:removedChild];
  623. // Disable user interaction while the view is animating
  624. // since the view is (conceptually) deleted and not supposed to be interactive.
  625. removedChild.userInteractionEnabled = NO;
  626. [originalSuperview insertSubview:removedChild atIndex:originalIndex];
  627. NSString *property = deletingLayoutAnimation.property;
  628. [deletingLayoutAnimation performAnimations:^{
  629. if ([property isEqualToString:@"scaleXY"]) {
  630. removedChild.layer.transform = CATransform3DMakeScale(0.001, 0.001, 0.001);
  631. } else if ([property isEqualToString:@"scaleX"]) {
  632. removedChild.layer.transform = CATransform3DMakeScale(0.001, 1, 0.001);
  633. } else if ([property isEqualToString:@"scaleY"]) {
  634. removedChild.layer.transform = CATransform3DMakeScale(1, 0.001, 0.001);
  635. } else if ([property isEqualToString:@"opacity"]) {
  636. removedChild.layer.opacity = 0.0;
  637. } else {
  638. RCTLogError(@"Unsupported layout animation createConfig property %@",
  639. deletingLayoutAnimation.property);
  640. }
  641. } withCompletionBlock:completion];
  642. }
  643. }
  644. RCT_EXPORT_METHOD(removeRootView:(nonnull NSNumber *)rootReactTag)
  645. {
  646. RCTShadowView *rootShadowView = _shadowViewRegistry[rootReactTag];
  647. RCTAssert(rootShadowView.superview == nil, @"root view cannot have superview (ID %@)", rootReactTag);
  648. [self _purgeChildren:(NSArray<id<RCTComponent>> *)rootShadowView.reactSubviews
  649. fromRegistry:(NSMutableDictionary<NSNumber *, id<RCTComponent>> *)_shadowViewRegistry];
  650. [_shadowViewRegistry removeObjectForKey:rootReactTag];
  651. [_rootViewTags removeObject:rootReactTag];
  652. [self addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry){
  653. RCTAssertMainQueue();
  654. UIView *rootView = viewRegistry[rootReactTag];
  655. [uiManager _purgeChildren:(NSArray<id<RCTComponent>> *)rootView.reactSubviews
  656. fromRegistry:(NSMutableDictionary<NSNumber *, id<RCTComponent>> *)viewRegistry];
  657. [(NSMutableDictionary *)viewRegistry removeObjectForKey:rootReactTag];
  658. }];
  659. }
  660. RCT_EXPORT_METHOD(replaceExistingNonRootView:(nonnull NSNumber *)reactTag
  661. withView:(nonnull NSNumber *)newReactTag)
  662. {
  663. RCTShadowView *shadowView = _shadowViewRegistry[reactTag];
  664. RCTAssert(shadowView != nil, @"shadowView (for ID %@) not found", reactTag);
  665. RCTShadowView *superShadowView = shadowView.superview;
  666. if (!superShadowView) {
  667. RCTAssert(NO, @"shadowView super (of ID %@) not found", reactTag);
  668. return;
  669. }
  670. NSUInteger indexOfView = [superShadowView.reactSubviews indexOfObjectIdenticalTo:shadowView];
  671. RCTAssert(indexOfView != NSNotFound, @"View's superview doesn't claim it as subview (id %@)", reactTag);
  672. NSArray<NSNumber *> *removeAtIndices = @[@(indexOfView)];
  673. NSArray<NSNumber *> *addTags = @[newReactTag];
  674. [self manageChildren:superShadowView.reactTag
  675. moveFromIndices:nil
  676. moveToIndices:nil
  677. addChildReactTags:addTags
  678. addAtIndices:removeAtIndices
  679. removeAtIndices:removeAtIndices];
  680. }
  681. RCT_EXPORT_METHOD(setChildren:(nonnull NSNumber *)containerTag
  682. reactTags:(NSArray<NSNumber *> *)reactTags)
  683. {
  684. RCTSetChildren(containerTag, reactTags,
  685. (NSDictionary<NSNumber *, id<RCTComponent>> *)_shadowViewRegistry);
  686. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry){
  687. RCTSetChildren(containerTag, reactTags,
  688. (NSDictionary<NSNumber *, id<RCTComponent>> *)viewRegistry);
  689. }];
  690. [self _shadowViewDidReceiveUpdatedChildren:_shadowViewRegistry[containerTag]];
  691. }
  692. static void RCTSetChildren(NSNumber *containerTag,
  693. NSArray<NSNumber *> *reactTags,
  694. NSDictionary<NSNumber *, id<RCTComponent>> *registry)
  695. {
  696. id<RCTComponent> container = registry[containerTag];
  697. NSInteger index = 0;
  698. for (NSNumber *reactTag in reactTags) {
  699. id<RCTComponent> view = registry[reactTag];
  700. if (view) {
  701. [container insertReactSubview:view atIndex:index++];
  702. }
  703. }
  704. }
  705. RCT_EXPORT_METHOD(manageChildren:(nonnull NSNumber *)containerTag
  706. moveFromIndices:(NSArray<NSNumber *> *)moveFromIndices
  707. moveToIndices:(NSArray<NSNumber *> *)moveToIndices
  708. addChildReactTags:(NSArray<NSNumber *> *)addChildReactTags
  709. addAtIndices:(NSArray<NSNumber *> *)addAtIndices
  710. removeAtIndices:(NSArray<NSNumber *> *)removeAtIndices)
  711. {
  712. [self _manageChildren:containerTag
  713. moveFromIndices:moveFromIndices
  714. moveToIndices:moveToIndices
  715. addChildReactTags:addChildReactTags
  716. addAtIndices:addAtIndices
  717. removeAtIndices:removeAtIndices
  718. registry:(NSMutableDictionary<NSNumber *, id<RCTComponent>> *)_shadowViewRegistry];
  719. [self addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry){
  720. [uiManager _manageChildren:containerTag
  721. moveFromIndices:moveFromIndices
  722. moveToIndices:moveToIndices
  723. addChildReactTags:addChildReactTags
  724. addAtIndices:addAtIndices
  725. removeAtIndices:removeAtIndices
  726. registry:(NSMutableDictionary<NSNumber *, id<RCTComponent>> *)viewRegistry];
  727. }];
  728. [self _shadowViewDidReceiveUpdatedChildren:_shadowViewRegistry[containerTag]];
  729. }
  730. - (void)_manageChildren:(NSNumber *)containerTag
  731. moveFromIndices:(NSArray<NSNumber *> *)moveFromIndices
  732. moveToIndices:(NSArray<NSNumber *> *)moveToIndices
  733. addChildReactTags:(NSArray<NSNumber *> *)addChildReactTags
  734. addAtIndices:(NSArray<NSNumber *> *)addAtIndices
  735. removeAtIndices:(NSArray<NSNumber *> *)removeAtIndices
  736. registry:(NSMutableDictionary<NSNumber *, id<RCTComponent>> *)registry
  737. {
  738. id<RCTComponent> container = registry[containerTag];
  739. RCTAssert(moveFromIndices.count == moveToIndices.count, @"moveFromIndices had size %tu, moveToIndices had size %tu", moveFromIndices.count, moveToIndices.count);
  740. RCTAssert(addChildReactTags.count == addAtIndices.count, @"there should be at least one React child to add");
  741. // Removes (both permanent and temporary moves) are using "before" indices
  742. NSArray<id<RCTComponent>> *permanentlyRemovedChildren =
  743. [self _childrenToRemoveFromContainer:container atIndices:removeAtIndices];
  744. NSArray<id<RCTComponent>> *temporarilyRemovedChildren =
  745. [self _childrenToRemoveFromContainer:container atIndices:moveFromIndices];
  746. BOOL isUIViewRegistry = ((id)registry == (id)_viewRegistry);
  747. if (isUIViewRegistry && _layoutAnimationGroup.deletingLayoutAnimation) {
  748. [self _removeChildren:(NSArray<UIView *> *)permanentlyRemovedChildren
  749. fromContainer:(UIView *)container
  750. withAnimation:_layoutAnimationGroup];
  751. } else {
  752. [self _removeChildren:permanentlyRemovedChildren fromContainer:container];
  753. }
  754. [self _removeChildren:temporarilyRemovedChildren fromContainer:container];
  755. [self _purgeChildren:permanentlyRemovedChildren fromRegistry:registry];
  756. // Figure out what to insert - merge temporary inserts and adds
  757. NSMutableDictionary *destinationsToChildrenToAdd = [NSMutableDictionary dictionary];
  758. for (NSInteger index = 0, length = temporarilyRemovedChildren.count; index < length; index++) {
  759. destinationsToChildrenToAdd[moveToIndices[index]] = temporarilyRemovedChildren[index];
  760. }
  761. for (NSInteger index = 0, length = addAtIndices.count; index < length; index++) {
  762. id<RCTComponent> view = registry[addChildReactTags[index]];
  763. if (view) {
  764. destinationsToChildrenToAdd[addAtIndices[index]] = view;
  765. }
  766. }
  767. NSArray<NSNumber *> *sortedIndices =
  768. [destinationsToChildrenToAdd.allKeys sortedArrayUsingSelector:@selector(compare:)];
  769. for (NSNumber *reactIndex in sortedIndices) {
  770. [container insertReactSubview:destinationsToChildrenToAdd[reactIndex]
  771. atIndex:reactIndex.integerValue];
  772. }
  773. }
  774. RCT_EXPORT_METHOD(createView:(nonnull NSNumber *)reactTag
  775. viewName:(NSString *)viewName
  776. rootTag:(nonnull NSNumber *)rootTag
  777. props:(NSDictionary *)props)
  778. {
  779. RCTComponentData *componentData = _componentDataByName[viewName];
  780. if (componentData == nil) {
  781. RCTLogError(@"No component found for view with name \"%@\"", viewName);
  782. }
  783. // Register shadow view
  784. RCTShadowView *shadowView = [componentData createShadowViewWithTag:reactTag];
  785. if (shadowView) {
  786. [componentData setProps:props forShadowView:shadowView];
  787. _shadowViewRegistry[reactTag] = shadowView;
  788. RCTShadowView *rootView = _shadowViewRegistry[rootTag];
  789. RCTAssert([rootView isKindOfClass:[RCTRootShadowView class]] ||
  790. [rootView isKindOfClass:[RCTSurfaceRootShadowView class]],
  791. @"Given `rootTag` (%@) does not correspond to a valid root shadow view instance.", rootTag);
  792. shadowView.rootView = (RCTRootShadowView *)rootView;
  793. }
  794. // Dispatch view creation directly to the main thread instead of adding to
  795. // UIBlocks array. This way, it doesn't get deferred until after layout.
  796. __block UIView *preliminaryCreatedView = nil;
  797. void (^createViewBlock)(void) = ^{
  798. // Do nothing on the second run.
  799. if (preliminaryCreatedView) {
  800. return;
  801. }
  802. preliminaryCreatedView = [componentData createViewWithTag:reactTag];
  803. if (preliminaryCreatedView) {
  804. self->_viewRegistry[reactTag] = preliminaryCreatedView;
  805. }
  806. };
  807. // We cannot guarantee that asynchronously scheduled block will be executed
  808. // *before* a block is added to the regular mounting process (simply because
  809. // mounting process can be managed externally while the main queue is
  810. // locked).
  811. // So, we positively dispatch it asynchronously and double check inside
  812. // the regular mounting block.
  813. RCTExecuteOnMainQueue(createViewBlock);
  814. [self addUIBlock:^(__unused RCTUIManager *uiManager, __unused NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  815. createViewBlock();
  816. if (preliminaryCreatedView) {
  817. [componentData setProps:props forView:preliminaryCreatedView];
  818. }
  819. }];
  820. [self _shadowView:shadowView didReceiveUpdatedProps:[props allKeys]];
  821. }
  822. RCT_EXPORT_METHOD(updateView:(nonnull NSNumber *)reactTag
  823. viewName:(NSString *)viewName // not always reliable, use shadowView.viewName if available
  824. props:(NSDictionary *)props)
  825. {
  826. RCTShadowView *shadowView = _shadowViewRegistry[reactTag];
  827. RCTComponentData *componentData = _componentDataByName[shadowView.viewName ?: viewName];
  828. [componentData setProps:props forShadowView:shadowView];
  829. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  830. UIView *view = viewRegistry[reactTag];
  831. [componentData setProps:props forView:view];
  832. }];
  833. [self _shadowView:shadowView didReceiveUpdatedProps:[props allKeys]];
  834. }
  835. - (void)synchronouslyUpdateViewOnUIThread:(NSNumber *)reactTag
  836. viewName:(NSString *)viewName
  837. props:(NSDictionary *)props
  838. {
  839. RCTAssertMainQueue();
  840. RCTComponentData *componentData = _componentDataByName[viewName];
  841. UIView *view = _viewRegistry[reactTag];
  842. [componentData setProps:props forView:view];
  843. }
  844. RCT_EXPORT_METHOD(focus:(nonnull NSNumber *)reactTag)
  845. {
  846. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  847. UIView *newResponder = viewRegistry[reactTag];
  848. [newResponder reactFocus];
  849. }];
  850. }
  851. RCT_EXPORT_METHOD(blur:(nonnull NSNumber *)reactTag)
  852. {
  853. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry){
  854. UIView *currentResponder = viewRegistry[reactTag];
  855. [currentResponder reactBlur];
  856. }];
  857. }
  858. RCT_EXPORT_METHOD(findSubviewIn:(nonnull NSNumber *)reactTag atPoint:(CGPoint)point callback:(RCTResponseSenderBlock)callback)
  859. {
  860. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  861. UIView *view = viewRegistry[reactTag];
  862. UIView *target = [view hitTest:point withEvent:nil];
  863. CGRect frame = [target convertRect:target.bounds toView:view];
  864. while (target.reactTag == nil && target.superview != nil) {
  865. target = target.superview;
  866. }
  867. callback(@[
  868. RCTNullIfNil(target.reactTag),
  869. @(frame.origin.x),
  870. @(frame.origin.y),
  871. @(frame.size.width),
  872. @(frame.size.height),
  873. ]);
  874. }];
  875. }
  876. RCT_EXPORT_METHOD(dispatchViewManagerCommand:(nonnull NSNumber *)reactTag
  877. commandID:(NSInteger)commandID
  878. commandArgs:(NSArray<id> *)commandArgs)
  879. {
  880. RCTShadowView *shadowView = _shadowViewRegistry[reactTag];
  881. RCTComponentData *componentData = _componentDataByName[shadowView.viewName];
  882. Class managerClass = componentData.managerClass;
  883. RCTModuleData *moduleData = [_bridge moduleDataForName:RCTBridgeModuleNameForClass(managerClass)];
  884. id<RCTBridgeMethod> method = moduleData.methods[commandID];
  885. NSArray *args = [@[reactTag] arrayByAddingObjectsFromArray:commandArgs];
  886. [method invokeWithBridge:_bridge module:componentData.manager arguments:args];
  887. }
  888. - (void)batchDidComplete
  889. {
  890. [self _layoutAndMount];
  891. }
  892. /**
  893. * Sets up animations, computes layout, creates UI mounting blocks for computed layout,
  894. * runs these blocks and all other already existing blocks.
  895. */
  896. - (void)_layoutAndMount
  897. {
  898. [self _dispatchPropsDidChangeEvents];
  899. [self _dispatchChildrenDidChangeEvents];
  900. [_observerCoordinator uiManagerWillPerformLayout:self];
  901. // Perform layout
  902. for (NSNumber *reactTag in _rootViewTags) {
  903. RCTRootShadowView *rootView = (RCTRootShadowView *)_shadowViewRegistry[reactTag];
  904. [self addUIBlock:[self uiBlockWithLayoutUpdateForRootView:rootView]];
  905. }
  906. [_observerCoordinator uiManagerDidPerformLayout:self];
  907. [_observerCoordinator uiManagerWillPerformMounting:self];
  908. [self flushUIBlocksWithCompletion:^{
  909. [self->_observerCoordinator uiManagerDidPerformMounting:self];
  910. }];
  911. }
  912. - (void)flushUIBlocksWithCompletion:(void (^)(void))completion;
  913. {
  914. RCTAssertUIManagerQueue();
  915. // First copy the previous blocks into a temporary variable, then reset the
  916. // pending blocks to a new array. This guards against mutation while
  917. // processing the pending blocks in another thread.
  918. NSArray<RCTViewManagerUIBlock> *previousPendingUIBlocks = _pendingUIBlocks;
  919. _pendingUIBlocks = [NSMutableArray new];
  920. if (previousPendingUIBlocks.count == 0) {
  921. completion();
  922. return;
  923. }
  924. __weak typeof(self) weakSelf = self;
  925. void (^mountingBlock)(void) = ^{
  926. typeof(self) strongSelf = weakSelf;
  927. @try {
  928. for (RCTViewManagerUIBlock block in previousPendingUIBlocks) {
  929. block(strongSelf, strongSelf->_viewRegistry);
  930. }
  931. }
  932. @catch (NSException *exception) {
  933. RCTLogError(@"Exception thrown while executing UI block: %@", exception);
  934. }
  935. };
  936. if ([self.observerCoordinator uiManager:self performMountingWithBlock:mountingBlock]) {
  937. completion();
  938. return;
  939. }
  940. // Execute the previously queued UI blocks
  941. RCTProfileBeginFlowEvent();
  942. RCTExecuteOnMainQueue(^{
  943. RCTProfileEndFlowEvent();
  944. RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[UIManager flushUIBlocks]", (@{
  945. @"count": [@(previousPendingUIBlocks.count) stringValue],
  946. }));
  947. mountingBlock();
  948. RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
  949. RCTExecuteOnUIManagerQueue(completion);
  950. });
  951. }
  952. - (void)setNeedsLayout
  953. {
  954. // If there is an active batch layout will happen when batch finished, so we will wait for that.
  955. // Otherwise we immediately trigger layout.
  956. if (![_bridge isBatchActive] && ![_bridge isLoading]) {
  957. [self _layoutAndMount];
  958. }
  959. }
  960. - (void)_shadowView:(RCTShadowView *)shadowView didReceiveUpdatedProps:(NSArray<NSString *> *)props
  961. {
  962. // We collect a set with changed `shadowViews` and its changed props,
  963. // so we have to maintain this collection properly.
  964. NSArray<NSString *> *previousProps;
  965. if ((previousProps = [_shadowViewsWithUpdatedProps objectForKey:shadowView])) {
  966. // Merging already registred changed props and new ones.
  967. NSMutableSet *set = [NSMutableSet setWithArray:previousProps];
  968. [set addObjectsFromArray:props];
  969. props = [set allObjects];
  970. }
  971. [_shadowViewsWithUpdatedProps setObject:props forKey:shadowView];
  972. }
  973. - (void)_shadowViewDidReceiveUpdatedChildren:(RCTShadowView *)shadowView
  974. {
  975. [_shadowViewsWithUpdatedChildren addObject:shadowView];
  976. }
  977. - (void)_dispatchChildrenDidChangeEvents
  978. {
  979. if (_shadowViewsWithUpdatedChildren.count == 0) {
  980. return;
  981. }
  982. NSHashTable<RCTShadowView *> *shadowViews = _shadowViewsWithUpdatedChildren;
  983. _shadowViewsWithUpdatedChildren = [NSHashTable weakObjectsHashTable];
  984. NSMutableArray *tags = [NSMutableArray arrayWithCapacity:shadowViews.count];
  985. for (RCTShadowView *shadowView in shadowViews) {
  986. [shadowView didUpdateReactSubviews];
  987. [tags addObject:shadowView.reactTag];
  988. }
  989. [self addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  990. for (NSNumber *tag in tags) {
  991. UIView<RCTComponent> *view = viewRegistry[tag];
  992. [view didUpdateReactSubviews];
  993. }
  994. }];
  995. }
  996. - (void)_dispatchPropsDidChangeEvents
  997. {
  998. if (_shadowViewsWithUpdatedProps.count == 0) {
  999. return;
  1000. }
  1001. NSMapTable<RCTShadowView *, NSArray<NSString *> *> *shadowViews = _shadowViewsWithUpdatedProps;
  1002. _shadowViewsWithUpdatedProps = [NSMapTable weakToStrongObjectsMapTable];
  1003. NSMapTable<NSNumber *, NSArray<NSString *> *> *tags = [NSMapTable strongToStrongObjectsMapTable];
  1004. for (RCTShadowView *shadowView in shadowViews) {
  1005. NSArray<NSString *> *props = [shadowViews objectForKey:shadowView];
  1006. [shadowView didSetProps:props];
  1007. [tags setObject:props forKey:shadowView.reactTag];
  1008. }
  1009. [self addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  1010. for (NSNumber *tag in tags) {
  1011. UIView<RCTComponent> *view = viewRegistry[tag];
  1012. [view didSetProps:[tags objectForKey:tag]];
  1013. }
  1014. }];
  1015. }
  1016. RCT_EXPORT_METHOD(measure:(nonnull NSNumber *)reactTag
  1017. callback:(RCTResponseSenderBlock)callback)
  1018. {
  1019. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  1020. UIView *view = viewRegistry[reactTag];
  1021. if (!view) {
  1022. // this view was probably collapsed out
  1023. RCTLogWarn(@"measure cannot find view with tag #%@", reactTag);
  1024. callback(@[]);
  1025. return;
  1026. }
  1027. // If in a <Modal>, rootView will be the root of the modal container.
  1028. UIView *rootView = view;
  1029. while (rootView.superview && ![rootView isReactRootView]) {
  1030. rootView = rootView.superview;
  1031. }
  1032. // By convention, all coordinates, whether they be touch coordinates, or
  1033. // measurement coordinates are with respect to the root view.
  1034. CGRect frame = view.frame;
  1035. CGRect globalBounds = [view convertRect:view.bounds toView:rootView];
  1036. callback(@[
  1037. @(frame.origin.x),
  1038. @(frame.origin.y),
  1039. @(globalBounds.size.width),
  1040. @(globalBounds.size.height),
  1041. @(globalBounds.origin.x),
  1042. @(globalBounds.origin.y),
  1043. ]);
  1044. }];
  1045. }
  1046. RCT_EXPORT_METHOD(measureInWindow:(nonnull NSNumber *)reactTag
  1047. callback:(RCTResponseSenderBlock)callback)
  1048. {
  1049. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  1050. UIView *view = viewRegistry[reactTag];
  1051. if (!view) {
  1052. // this view was probably collapsed out
  1053. RCTLogWarn(@"measure cannot find view with tag #%@", reactTag);
  1054. callback(@[]);
  1055. return;
  1056. }
  1057. // Return frame coordinates in window
  1058. CGRect windowFrame = [view.window convertRect:view.frame fromView:view.superview];
  1059. callback(@[
  1060. @(windowFrame.origin.x),
  1061. @(windowFrame.origin.y),
  1062. @(windowFrame.size.width),
  1063. @(windowFrame.size.height),
  1064. ]);
  1065. }];
  1066. }
  1067. /**
  1068. * Returs if the shadow view provided has the `ancestor` shadow view as
  1069. * an actual ancestor.
  1070. */
  1071. RCT_EXPORT_METHOD(viewIsDescendantOf:(nonnull NSNumber *)reactTag
  1072. ancestor:(nonnull NSNumber *)ancestorReactTag
  1073. callback:(RCTResponseSenderBlock)callback)
  1074. {
  1075. RCTShadowView *shadowView = _shadowViewRegistry[reactTag];
  1076. RCTShadowView *ancestorShadowView = _shadowViewRegistry[ancestorReactTag];
  1077. if (!shadowView) {
  1078. return;
  1079. }
  1080. if (!ancestorShadowView) {
  1081. return;
  1082. }
  1083. BOOL viewIsAncestor = [shadowView viewIsDescendantOf:ancestorShadowView];
  1084. callback(@[@(viewIsAncestor)]);
  1085. }
  1086. static void RCTMeasureLayout(RCTShadowView *view,
  1087. RCTShadowView *ancestor,
  1088. RCTResponseSenderBlock callback)
  1089. {
  1090. if (!view) {
  1091. return;
  1092. }
  1093. if (!ancestor) {
  1094. return;
  1095. }
  1096. CGRect result = [view measureLayoutRelativeToAncestor:ancestor];
  1097. if (CGRectIsNull(result)) {
  1098. RCTLogError(@"view %@ (tag #%@) is not a descendant of %@ (tag #%@)",
  1099. view, view.reactTag, ancestor, ancestor.reactTag);
  1100. return;
  1101. }
  1102. CGFloat leftOffset = result.origin.x;
  1103. CGFloat topOffset = result.origin.y;
  1104. CGFloat width = result.size.width;
  1105. CGFloat height = result.size.height;
  1106. if (isnan(leftOffset) || isnan(topOffset) || isnan(width) || isnan(height)) {
  1107. RCTLogError(@"Attempted to measure layout but offset or dimensions were NaN");
  1108. return;
  1109. }
  1110. callback(@[@(leftOffset), @(topOffset), @(width), @(height)]);
  1111. }
  1112. /**
  1113. * Returns the computed recursive offset layout in a dictionary form. The
  1114. * returned values are relative to the `ancestor` shadow view. Returns `nil`, if
  1115. * the `ancestor` shadow view is not actually an `ancestor`. Does not touch
  1116. * anything on the main UI thread. Invokes supplied callback with (x, y, width,
  1117. * height).
  1118. */
  1119. RCT_EXPORT_METHOD(measureLayout:(nonnull NSNumber *)reactTag
  1120. relativeTo:(nonnull NSNumber *)ancestorReactTag
  1121. errorCallback:(__unused RCTResponseSenderBlock)errorCallback
  1122. callback:(RCTResponseSenderBlock)callback)
  1123. {
  1124. RCTShadowView *shadowView = _shadowViewRegistry[reactTag];
  1125. RCTShadowView *ancestorShadowView = _shadowViewRegistry[ancestorReactTag];
  1126. RCTMeasureLayout(shadowView, ancestorShadowView, callback);
  1127. }
  1128. /**
  1129. * Returns the computed recursive offset layout in a dictionary form. The
  1130. * returned values are relative to the `ancestor` shadow view. Returns `nil`, if
  1131. * the `ancestor` shadow view is not actually an `ancestor`. Does not touch
  1132. * anything on the main UI thread. Invokes supplied callback with (x, y, width,
  1133. * height).
  1134. */
  1135. RCT_EXPORT_METHOD(measureLayoutRelativeToParent:(nonnull NSNumber *)reactTag
  1136. errorCallback:(__unused RCTResponseSenderBlock)errorCallback
  1137. callback:(RCTResponseSenderBlock)callback)
  1138. {
  1139. RCTShadowView *shadowView = _shadowViewRegistry[reactTag];
  1140. RCTMeasureLayout(shadowView, shadowView.reactSuperview, callback);
  1141. }
  1142. RCT_EXPORT_METHOD(takeSnapshot:(id /* NSString or NSNumber */)target
  1143. withOptions:(NSDictionary *)options
  1144. resolve:(RCTPromiseResolveBlock)resolve
  1145. reject:(RCTPromiseRejectBlock)reject)
  1146. {
  1147. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  1148. // Get view
  1149. UIView *view;
  1150. if (target == nil || [target isEqual:@"window"]) {
  1151. view = RCTKeyWindow();
  1152. } else if ([target isKindOfClass:[NSNumber class]]) {
  1153. view = viewRegistry[target];
  1154. if (!view) {
  1155. RCTLogError(@"No view found with reactTag: %@", target);
  1156. return;
  1157. }
  1158. }
  1159. // Get options
  1160. CGSize size = [RCTConvert CGSize:options];
  1161. NSString *format = [RCTConvert NSString:options[@"format"] ?: @"png"];
  1162. // Capture image
  1163. if (size.width < 0.1 || size.height < 0.1) {
  1164. size = view.bounds.size;
  1165. }
  1166. UIGraphicsBeginImageContextWithOptions(size, NO, 0);
  1167. BOOL success = [view drawViewHierarchyInRect:(CGRect){CGPointZero, size} afterScreenUpdates:YES];
  1168. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  1169. UIGraphicsEndImageContext();
  1170. if (!success || !image) {
  1171. reject(RCTErrorUnspecified, @"Failed to capture view snapshot.", nil);
  1172. return;
  1173. }
  1174. // Convert image to data (on a background thread)
  1175. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1176. NSData *data;
  1177. if ([format isEqualToString:@"png"]) {
  1178. data = UIImagePNGRepresentation(image);
  1179. } else if ([format isEqualToString:@"jpeg"]) {
  1180. CGFloat quality = [RCTConvert CGFloat:options[@"quality"] ?: @1];
  1181. data = UIImageJPEGRepresentation(image, quality);
  1182. } else {
  1183. RCTLogError(@"Unsupported image format: %@", format);
  1184. return;
  1185. }
  1186. // Save to a temp file
  1187. NSError *error = nil;
  1188. NSString *tempFilePath = RCTTempFilePath(format, &error);
  1189. if (tempFilePath) {
  1190. if ([data writeToFile:tempFilePath options:(NSDataWritingOptions)0 error:&error]) {
  1191. resolve(tempFilePath);
  1192. return;
  1193. }
  1194. }
  1195. // If we reached here, something went wrong
  1196. reject(RCTErrorUnspecified, error.localizedDescription, error);
  1197. });
  1198. }];
  1199. }
  1200. /**
  1201. * JS sets what *it* considers to be the responder. Later, scroll views can use
  1202. * this in order to determine if scrolling is appropriate.
  1203. */
  1204. RCT_EXPORT_METHOD(setJSResponder:(nonnull NSNumber *)reactTag
  1205. blockNativeResponder:(__unused BOOL)blockNativeResponder)
  1206. {
  1207. [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  1208. _jsResponder = viewRegistry[reactTag];
  1209. if (!_jsResponder) {
  1210. RCTLogWarn(@"Invalid view set to be the JS responder - tag %@", reactTag);
  1211. }
  1212. }];
  1213. }
  1214. RCT_EXPORT_METHOD(clearJSResponder)
  1215. {
  1216. [self addUIBlock:^(__unused RCTUIManager *uiManager, __unused NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  1217. _jsResponder = nil;
  1218. }];
  1219. }
  1220. static NSMutableDictionary<NSString *, id> *moduleConstantsForComponent(
  1221. NSMutableDictionary<NSString *, NSDictionary *> *directEvents,
  1222. NSMutableDictionary<NSString *, NSDictionary *> *bubblingEvents,
  1223. RCTComponentData *componentData) {
  1224. NSMutableDictionary<NSString *, id> *moduleConstants = [NSMutableDictionary new];
  1225. // Register which event-types this view dispatches.
  1226. // React needs this for the event plugin.
  1227. NSMutableDictionary<NSString *, NSDictionary *> *bubblingEventTypes = [NSMutableDictionary new];
  1228. NSMutableDictionary<NSString *, NSDictionary *> *directEventTypes = [NSMutableDictionary new];
  1229. // Add manager class
  1230. moduleConstants[@"Manager"] = RCTBridgeModuleNameForClass(componentData.managerClass);
  1231. // Add native props
  1232. NSDictionary<NSString *, id> *viewConfig = [componentData viewConfig];
  1233. moduleConstants[@"NativeProps"] = viewConfig[@"propTypes"];
  1234. moduleConstants[@"baseModuleName"] = viewConfig[@"baseModuleName"];
  1235. moduleConstants[@"bubblingEventTypes"] = bubblingEventTypes;
  1236. moduleConstants[@"directEventTypes"] = directEventTypes;
  1237. // Add direct events
  1238. for (NSString *eventName in viewConfig[@"directEvents"]) {
  1239. if (!directEvents[eventName]) {
  1240. directEvents[eventName] = @{
  1241. @"registrationName": [eventName stringByReplacingCharactersInRange:(NSRange){0, 3} withString:@"on"],
  1242. };
  1243. }
  1244. directEventTypes[eventName] = directEvents[eventName];
  1245. if (RCT_DEBUG && bubblingEvents[eventName]) {
  1246. RCTLogError(@"Component '%@' re-registered bubbling event '%@' as a "
  1247. "direct event", componentData.name, eventName);
  1248. }
  1249. }
  1250. // Add bubbling events
  1251. for (NSString *eventName in viewConfig[@"bubblingEvents"]) {
  1252. if (!bubblingEvents[eventName]) {
  1253. NSString *bubbleName = [eventName stringByReplacingCharactersInRange:(NSRange){0, 3} withString:@"on"];
  1254. bubblingEvents[eventName] = @{
  1255. @"phasedRegistrationNames": @{
  1256. @"bubbled": bubbleName,
  1257. @"captured": [bubbleName stringByAppendingString:@"Capture"],
  1258. }
  1259. };
  1260. }
  1261. bubblingEventTypes[eventName] = bubblingEvents[eventName];
  1262. if (RCT_DEBUG && directEvents[eventName]) {
  1263. RCTLogError(@"Component '%@' re-registered direct event '%@' as a "
  1264. "bubbling event", componentData.name, eventName);
  1265. }
  1266. }
  1267. return moduleConstants;
  1268. }
  1269. - (NSDictionary<NSString *, id> *)constantsToExport
  1270. {
  1271. return [self getConstants];
  1272. }
  1273. - (NSDictionary<NSString *, id> *)getConstants
  1274. {
  1275. NSMutableDictionary<NSString *, NSDictionary *> *constants = [NSMutableDictionary new];
  1276. NSMutableDictionary<NSString *, NSDictionary *> *directEvents = [NSMutableDictionary new];
  1277. NSMutableDictionary<NSString *, NSDictionary *> *bubblingEvents = [NSMutableDictionary new];
  1278. [_componentDataByName enumerateKeysAndObjectsUsingBlock:^(NSString *name, RCTComponentData *componentData, __unused BOOL *stop) {
  1279. RCTAssert(!constants[name], @"UIManager already has constants for %@", componentData.name);
  1280. NSMutableDictionary<NSString *, id> *moduleConstants = moduleConstantsForComponent(directEvents, bubblingEvents, componentData);
  1281. constants[name] = moduleConstants;
  1282. }];
  1283. return constants;
  1284. }
  1285. RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(lazilyLoadView:(NSString *)name)
  1286. {
  1287. if (_componentDataByName[name]) {
  1288. return @{};
  1289. }
  1290. id<RCTBridgeDelegate> delegate = self.bridge.delegate;
  1291. if (![delegate respondsToSelector:@selector(bridge:didNotFindModule:)]) {
  1292. return @{};
  1293. }
  1294. NSString *moduleName = name;
  1295. BOOL result = [delegate bridge:self.bridge didNotFindModule:moduleName];
  1296. if (!result) {
  1297. moduleName = [name stringByAppendingString:@"Manager"];
  1298. result = [delegate bridge:self.bridge didNotFindModule:moduleName];
  1299. }
  1300. if (!result) {
  1301. return @{};
  1302. }
  1303. id module = [self.bridge moduleForName:moduleName];
  1304. if (module == nil) {
  1305. // There is all sorts of code in this codebase that drops prefixes.
  1306. //
  1307. // If we didn't find a module, it's possible because it's stored under a key
  1308. // which had RCT Prefixes stripped. Lets check one more time...
  1309. module = [self.bridge moduleForName:RCTDropReactPrefixes(moduleName)];
  1310. }
  1311. if (!module) {
  1312. return @{};
  1313. }
  1314. RCTComponentData *componentData = [[RCTComponentData alloc] initWithManagerClass:[module class] bridge:self.bridge];
  1315. _componentDataByName[componentData.name] = componentData;
  1316. NSMutableDictionary *directEvents = [NSMutableDictionary new];
  1317. NSMutableDictionary *bubblingEvents = [NSMutableDictionary new];
  1318. NSMutableDictionary<NSString *, id> *moduleConstants = moduleConstantsForComponent(directEvents, bubblingEvents, componentData);
  1319. return
  1320. @{
  1321. @"viewConfig": moduleConstants,
  1322. };
  1323. }
  1324. RCT_EXPORT_METHOD(configureNextLayoutAnimation:(NSDictionary *)config
  1325. withCallback:(RCTResponseSenderBlock)callback
  1326. errorCallback:(__unused RCTResponseSenderBlock)errorCallback)
  1327. {
  1328. RCTLayoutAnimationGroup *layoutAnimationGroup =
  1329. [[RCTLayoutAnimationGroup alloc] initWithConfig:config
  1330. callback:callback];
  1331. [self addUIBlock:^(RCTUIManager *uiManager, __unused NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  1332. [uiManager setNextLayoutAnimationGroup:layoutAnimationGroup];
  1333. }];
  1334. }
  1335. - (void)rootViewForReactTag:(NSNumber *)reactTag withCompletion:(void (^)(UIView *view))completion
  1336. {
  1337. RCTAssertMainQueue();
  1338. RCTAssert(completion != nil, @"Attempted to resolve rootView for tag %@ without a completion block", reactTag);
  1339. if (reactTag == nil) {
  1340. completion(nil);
  1341. return;
  1342. }
  1343. RCTExecuteOnUIManagerQueue(^{
  1344. NSNumber *rootTag = [self shadowViewForReactTag:reactTag].rootView.reactTag;
  1345. RCTExecuteOnMainQueue(^{
  1346. UIView *rootView = nil;
  1347. if (rootTag != nil) {
  1348. rootView = [self viewForReactTag:rootTag];
  1349. }
  1350. completion(rootView);
  1351. });
  1352. });
  1353. }
  1354. static UIView *_jsResponder;
  1355. + (UIView *)JSResponder
  1356. {
  1357. return _jsResponder;
  1358. }
  1359. @end
  1360. @implementation RCTBridge (RCTUIManager)
  1361. - (RCTUIManager *)uiManager
  1362. {
  1363. return [self moduleForClass:[RCTUIManager class]];
  1364. }
  1365. @end