From d0871d0a9a373e1d3ac35da46c85c0d0e793116d Mon Sep 17 00:00:00 2001 From: Valentin Shergin Date: Sun, 8 Mar 2020 22:58:01 -0700 Subject: [PATCH] Clang format for all React Native files Summary: Buckle up, this enables clang-format prettifier for all files in React Native opensource repo. Changelog: [Internal] Clang-format codemod. Reviewed By: mdvacca Differential Revision: D20331210 fbshipit-source-id: 8da0f94700be0c35bfd399e0c48f1706de04f5b1 --- React/Base/RCTAssert.h | 73 +- React/Base/RCTAssert.m | 65 +- React/Base/RCTBridge+Private.h | 7 +- React/Base/RCTBridge.h | 11 +- React/Base/RCTBridge.m | 51 +- React/Base/RCTBridgeDelegate.h | 15 +- React/Base/RCTBridgeMethod.h | 7 +- React/Base/RCTBridgeModule.h | 105 ++- React/Base/RCTBundleURLProvider.h | 13 +- React/Base/RCTBundleURLProvider.m | 61 +- React/Base/RCTComponentEvent.h | 2 +- React/Base/RCTComponentEvent.m | 7 +- React/Base/RCTConvert.h | 83 +- React/Base/RCTConvert.m | 839 ++++++++++-------- React/Base/RCTDefines.h | 28 +- React/Base/RCTDisplayLink.h | 3 +- React/Base/RCTDisplayLink.m | 22 +- React/Base/RCTErrorInfo.h | 4 +- React/Base/RCTErrorInfo.m | 4 +- React/Base/RCTEventDispatcher.h | 10 +- React/Base/RCTEventDispatcher.m | 50 +- React/Base/RCTFrameUpdate.m | 2 +- React/Base/RCTImageSource.h | 4 +- React/Base/RCTImageSource.m | 15 +- React/Base/RCTJSInvokerModule.h | 6 +- React/Base/RCTJSStackFrame.h | 6 +- React/Base/RCTJSStackFrame.m | 85 +- React/Base/RCTJavaScriptExecutor.h | 8 +- React/Base/RCTJavaScriptLoader.h | 24 +- React/Base/RCTJavaScriptLoader.mm | 300 ++++--- React/Base/RCTKeyCommands.h | 16 +- React/Base/RCTKeyCommands.m | 80 +- React/Base/RCTLog.h | 31 +- React/Base/RCTLog.mm | 97 +- React/Base/RCTManagedPointer.h | 5 +- React/Base/RCTManagedPointer.mm | 6 +- React/Base/RCTModuleData.h | 5 +- React/Base/RCTModuleData.mm | 160 ++-- React/Base/RCTModuleMethod.mm | 305 ++++--- React/Base/RCTMultipartDataTask.h | 7 +- React/Base/RCTMultipartDataTask.m | 51 +- React/Base/RCTMultipartStreamReader.h | 1 - React/Base/RCTMultipartStreamReader.m | 9 +- React/Base/RCTParserUtils.m | 16 +- React/Base/RCTPerformanceLogger.m | 10 +- React/Base/RCTRedBoxSetEnabled.h | 5 +- React/Base/RCTRedBoxSetEnabled.m | 6 +- React/Base/RCTReloadCommand.m | 12 +- React/Base/RCTRootContentView.m | 12 +- React/Base/RCTRootView.h | 14 +- React/Base/RCTRootView.m | 74 +- React/Base/RCTTVRemoteHandler.h | 1 - React/Base/RCTTVRemoteHandler.m | 17 +- React/Base/RCTTouchEvent.m | 38 +- React/Base/RCTTouchHandler.m | 29 +- React/Base/RCTURLRequestHandler.h | 3 +- React/Base/RCTUtils.h | 27 +- React/Base/RCTUtils.m | 230 +++-- React/Base/RCTVersion.h | 11 +- React/Base/Surface/RCTSurface.h | 10 +- React/Base/Surface/RCTSurface.mm | 72 +- React/Base/Surface/RCTSurfaceRootShadowView.m | 3 +- React/Base/Surface/RCTSurfaceRootView.mm | 2 +- React/Base/Surface/RCTSurfaceStage.h | 19 +- React/Base/Surface/RCTSurfaceStage.m | 14 +- React/Base/Surface/RCTSurfaceView.mm | 9 +- .../RCTSurfaceHostingProxyRootView.h | 4 +- .../RCTSurfaceHostingProxyRootView.mm | 27 +- .../RCTSurfaceHostingView.h | 2 +- .../RCTSurfaceHostingView.mm | 45 +- .../RCTSurfaceSizeMeasureMode.h | 21 +- .../RCTSurfaceSizeMeasureMode.mm | 16 +- React/CoreModules/RCTAccessibilityManager.mm | 133 +-- React/CoreModules/RCTActionSheetManager.mm | 91 +- React/CoreModules/RCTAlertManager.h | 1 - React/CoreModules/RCTAlertManager.mm | 113 +-- React/CoreModules/RCTAppState.mm | 41 +- React/CoreModules/RCTAppearance.mm | 27 +- React/CoreModules/RCTAsyncLocalStorage.h | 6 +- React/CoreModules/RCTAsyncLocalStorage.mm | 83 +- React/CoreModules/RCTClipboard.mm | 13 +- React/CoreModules/RCTDevLoadingView.h | 2 +- React/CoreModules/RCTDevLoadingView.mm | 79 +- React/CoreModules/RCTDevMenu.h | 12 +- React/CoreModules/RCTDevMenu.mm | 21 +- React/CoreModules/RCTDevSettings.mm | 32 +- React/CoreModules/RCTDeviceInfo.mm | 67 +- React/CoreModules/RCTExceptionsManager.h | 20 +- React/CoreModules/RCTExceptionsManager.mm | 104 ++- React/CoreModules/RCTFPSGraph.h | 3 +- React/CoreModules/RCTFPSGraph.m | 9 +- React/CoreModules/RCTI18nManager.mm | 15 +- React/CoreModules/RCTKeyboardObserver.mm | 64 +- React/CoreModules/RCTLogBox.mm | 28 +- React/CoreModules/RCTPerfMonitor.mm | 198 ++--- React/CoreModules/RCTPlatform.mm | 31 +- React/CoreModules/RCTRedBox.h | 8 +- React/CoreModules/RCTRedBox.mm | 768 +++++++++------- React/CoreModules/RCTSourceCode.mm | 5 +- React/CoreModules/RCTStatusBarManager.mm | 15 +- .../RCTTVNavigationEventEmitter.mm | 11 +- React/CoreModules/RCTTiming.h | 3 +- React/CoreModules/RCTWebSocketExecutor.mm | 110 +-- React/CoreModules/RCTWebSocketModule.mm | 68 +- React/CxxBridge/JSCExecutorFactory.h | 7 +- React/CxxBridge/JSCExecutorFactory.mm | 16 +- React/CxxBridge/NSDataBigString.h | 16 +- React/CxxBridge/NSDataBigString.mm | 3 +- React/CxxBridge/RCTCxxBridge.mm | 349 ++++---- React/CxxBridge/RCTMessageThread.h | 10 +- React/CxxBridge/RCTMessageThread.mm | 40 +- React/CxxBridge/RCTObjcExecutor.h | 16 +- React/CxxBridge/RCTObjcExecutor.mm | 108 +-- React/CxxModule/DispatchMessageQueueThread.h | 21 +- React/CxxModule/RCTCxxMethod.mm | 42 +- React/CxxModule/RCTCxxModule.mm | 11 +- React/CxxModule/RCTCxxUtils.h | 8 +- React/CxxModule/RCTCxxUtils.mm | 32 +- React/CxxModule/RCTNativeModule.h | 11 +- React/CxxModule/RCTNativeModule.mm | 69 +- React/CxxUtils/RCTFollyConvert.h | 3 +- React/CxxUtils/RCTFollyConvert.mm | 25 +- React/DevSupport/RCTDevLoadingViewProtocol.h | 2 +- .../DevSupport/RCTDevLoadingViewSetEnabled.m | 6 +- .../DevSupport/RCTInspectorDevServerHelper.h | 4 +- React/DevSupport/RCTPackagerClient.m | 16 +- React/DevSupport/RCTPackagerConnection.h | 3 +- React/DevSupport/RCTPackagerConnection.mm | 77 +- React/Inspector/RCTInspector.mm | 31 +- .../RCTInspectorPackagerConnection.h | 2 +- .../RCTInspectorPackagerConnection.m | 86 +- React/Modules/RCTEventEmitter.m | 46 +- React/Modules/RCTI18nUtil.m | 10 +- React/Modules/RCTLayoutAnimation.h | 8 +- React/Modules/RCTLayoutAnimation.m | 33 +- React/Modules/RCTLayoutAnimationGroup.h | 3 +- React/Modules/RCTLayoutAnimationGroup.m | 25 +- .../RCTRedBoxExtraDataViewController.m | 321 +++---- React/Modules/RCTSurfacePresenterStub.h | 1 - React/Modules/RCTUIManager.m | 509 ++++++----- .../RCTUIManagerObserverCoordinator.mm | 1 - React/Modules/RCTUIManagerUtils.h | 5 +- React/Modules/RCTUIManagerUtils.m | 3 +- React/Profiler/RCTProfile.h | 93 +- React/Profiler/RCTProfile.m | 323 ++++--- React/UIUtils/RCTUIUtils.h | 7 +- React/UIUtils/RCTUIUtils.m | 40 +- React/Views/RCTActivityIndicatorView.m | 4 +- React/Views/RCTActivityIndicatorViewManager.m | 15 +- React/Views/RCTBorderDrawing.h | 23 +- React/Views/RCTBorderDrawing.m | 321 ++++--- React/Views/RCTComponentData.h | 6 +- React/Views/RCTComponentData.m | 78 +- React/Views/RCTConvert+CoreLocation.m | 8 +- React/Views/RCTConvert+Transform.m | 3 +- React/Views/RCTDatePicker.m | 7 +- React/Views/RCTDatePickerManager.h | 2 +- React/Views/RCTDatePickerManager.m | 20 +- React/Views/RCTFont.h | 2 +- React/Views/RCTFont.mm | 111 +-- React/Views/RCTLayout.h | 9 +- React/Views/RCTLayout.m | 47 +- React/Views/RCTModalHostView.h | 8 +- React/Views/RCTModalHostView.m | 36 +- React/Views/RCTModalHostViewController.m | 20 +- React/Views/RCTModalHostViewManager.h | 8 +- React/Views/RCTModalHostViewManager.m | 32 +- React/Views/RCTPicker.m | 39 +- React/Views/RCTPickerManager.m | 6 +- React/Views/RCTProgressViewManager.m | 12 +- React/Views/RCTSegmentedControl.m | 38 +- React/Views/RCTShadowView+Internal.m | 3 +- React/Views/RCTShadowView+Layout.m | 30 +- React/Views/RCTShadowView.h | 6 +- React/Views/RCTShadowView.m | 270 +++--- React/Views/RCTSlider.h | 1 - React/Views/RCTSlider.m | 29 +- React/Views/RCTSliderManager.m | 26 +- React/Views/RCTSwitch.m | 3 +- React/Views/RCTSwitchManager.m | 10 +- React/Views/RCTTVView.m | 194 ++-- React/Views/RCTView.m | 305 +++---- React/Views/RCTViewManager.h | 36 +- React/Views/RCTViewManager.m | 148 +-- React/Views/RCTWrapperViewController.m | 11 +- .../Views/RefreshControl/RCTRefreshControl.m | 48 +- .../RefreshControl/RCTRefreshControlManager.m | 4 +- .../RefreshControl/RCTRefreshableProtocol.h | 2 +- .../SafeAreaView/RCTSafeAreaShadowView.m | 27 +- React/Views/SafeAreaView/RCTSafeAreaView.m | 24 +- .../ScrollView/RCTScrollContentShadowView.m | 3 +- React/Views/ScrollView/RCTScrollContentView.m | 3 +- React/Views/ScrollView/RCTScrollEvent.m | 49 +- React/Views/ScrollView/RCTScrollView.m | 309 ++++--- React/Views/ScrollView/RCTScrollViewManager.m | 214 ++--- .../Views/ScrollView/RCTScrollableProtocol.h | 2 +- React/Views/UIView+React.h | 2 +- React/Views/UIView+React.m | 62 +- 198 files changed, 5524 insertions(+), 5207 deletions(-) diff --git a/React/Base/RCTAssert.h b/React/Base/RCTAssert.h index 34b49e1af4b..6b5109ed74b 100644 --- a/React/Base/RCTAssert.h +++ b/React/Base/RCTAssert.h @@ -20,21 +20,25 @@ RCT_EXTERN BOOL RCTIsMainQueue(void); * assert handler through `RCTSetAssertFunction`. */ #ifndef NS_BLOCK_ASSERTIONS -#define RCTAssert(condition, ...) do { \ - if ((condition) == 0) { \ - _RCTAssertFormat(#condition, __FILE__, __LINE__, __func__, __VA_ARGS__); \ - if (RCT_NSASSERT) { \ - [[NSAssertionHandler currentHandler] handleFailureInFunction:(NSString * _Nonnull)@(__func__) \ - file:(NSString * _Nonnull)@(__FILE__) lineNumber:__LINE__ description:__VA_ARGS__]; \ - } \ - } \ -} while (false) +#define RCTAssert(condition, ...) \ + do { \ + if ((condition) == 0) { \ + _RCTAssertFormat(#condition, __FILE__, __LINE__, __func__, __VA_ARGS__); \ + if (RCT_NSASSERT) { \ + [[NSAssertionHandler currentHandler] handleFailureInFunction:(NSString * _Nonnull) @(__func__) \ + file:(NSString * _Nonnull) @(__FILE__) \ + lineNumber:__LINE__ \ + description:__VA_ARGS__]; \ + } \ + } \ + } while (false) #else -#define RCTAssert(condition, ...) do {} while (false) +#define RCTAssert(condition, ...) \ + do { \ + } while (false) #endif -RCT_EXTERN void _RCTAssertFormat( - const char *, const char *, int, const char *, NSString *, ... -) NS_FORMAT_FUNCTION(5,6); +RCT_EXTERN void _RCTAssertFormat(const char *, const char *, int, const char *, NSString *, ...) + NS_FORMAT_FUNCTION(5, 6); /** * Report a fatal condition when executing. These calls will _NOT_ be compiled out @@ -68,11 +72,12 @@ RCT_EXTERN NSString *const RCTFatalExceptionName; /** * A block signature to be used for custom assertion handling. */ -typedef void (^RCTAssertFunction)(NSString *condition, - NSString *fileName, - NSNumber *lineNumber, - NSString *function, - NSString *message); +typedef void (^RCTAssertFunction)( + NSString *condition, + NSString *fileName, + NSNumber *lineNumber, + NSString *function, + NSString *message); typedef void (^RCTFatalHandler)(NSError *error); typedef void (^RCTFatalExceptionHandler)(NSException *exception); @@ -85,14 +90,12 @@ typedef void (^RCTFatalExceptionHandler)(NSException *exception); /** * Convenience macro for asserting that we're running on main queue. */ -#define RCTAssertMainQueue() RCTAssert(RCTIsMainQueue(), \ - @"This function must be called on the main queue") +#define RCTAssertMainQueue() RCTAssert(RCTIsMainQueue(), @"This function must be called on the main queue") /** * Convenience macro for asserting that we're running off the main queue. */ -#define RCTAssertNotMainQueue() RCTAssert(!RCTIsMainQueue(), \ -@"This function must not be called on the main queue") +#define RCTAssertNotMainQueue() RCTAssert(!RCTIsMainQueue(), @"This function must not be called on the main queue") /** * These methods get and set the current assert function called by the RCTAssert @@ -133,7 +136,8 @@ RCT_EXTERN NSString *RCTCurrentThreadName(void); /** * Helper to get generate exception message from NSError */ -RCT_EXTERN NSString *RCTFormatError(NSString *message, NSArray *> *stacktrace, NSUInteger maxMessageLength); +RCT_EXTERN NSString * +RCTFormatError(NSString *message, NSArray *> *stacktrace, NSUInteger maxMessageLength); /** * Formats a JS stack trace for logging. @@ -145,20 +149,19 @@ RCT_EXTERN NSString *RCTFormatStackTrace(NSArray *> */ #if DEBUG -#define RCTAssertThread(thread, format...) \ -_Pragma("clang diagnostic push") \ -_Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ -RCTAssert( \ - [(id)thread isKindOfClass:[NSString class]] ? \ - [RCTCurrentThreadName() isEqualToString:(NSString *)thread] : \ - [(id)thread isKindOfClass:[NSThread class]] ? \ - [NSThread currentThread] == (NSThread *)thread : \ - dispatch_get_current_queue() == (dispatch_queue_t)thread, \ - format); \ -_Pragma("clang diagnostic pop") +#define RCTAssertThread(thread, format...) \ + _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") RCTAssert( \ + [(id)thread isKindOfClass:[NSString class]] \ + ? [RCTCurrentThreadName() isEqualToString:(NSString *)thread] \ + : [(id)thread isKindOfClass:[NSThread class]] ? [NSThread currentThread] == (NSThread *)thread \ + : dispatch_get_current_queue() == (dispatch_queue_t)thread, \ + format); \ + _Pragma("clang diagnostic pop") #else -#define RCTAssertThread(thread, format...) do { } while (0) +#define RCTAssertThread(thread, format...) \ + do { \ + } while (0) #endif diff --git a/React/Base/RCTAssert.m b/React/Base/RCTAssert.m index 3a50fb913f4..b454fae65b9 100644 --- a/React/Base/RCTAssert.m +++ b/React/Base/RCTAssert.m @@ -23,10 +23,12 @@ RCTFatalExceptionHandler RCTCurrentFatalExceptionHandler = nil; NSException *_RCTNotImplementedException(SEL, Class); NSException *_RCTNotImplementedException(SEL cmd, Class cls) { - NSString *msg = [NSString stringWithFormat:@"%s is not implemented " - "for the class %@", sel_getName(cmd), cls]; - return [NSException exceptionWithName:@"RCTNotDesignatedInitializerException" - reason:msg userInfo:nil]; + NSString *msg = [NSString stringWithFormat: + @"%s is not implemented " + "for the class %@", + sel_getName(cmd), + cls]; + return [NSException exceptionWithName:@"RCTNotDesignatedInitializerException" reason:msg userInfo:nil]; } void RCTSetAssertFunction(RCTAssertFunction assertFunction) @@ -43,15 +45,11 @@ void RCTAddAssertFunction(RCTAssertFunction assertFunction) { RCTAssertFunction existing = RCTCurrentAssertFunction; if (existing) { - RCTCurrentAssertFunction = ^(NSString *condition, - NSString *fileName, - NSNumber *lineNumber, - NSString *function, - NSString *message) { - - existing(condition, fileName, lineNumber, function, message); - assertFunction(condition, fileName, lineNumber, function, message); - }; + RCTCurrentAssertFunction = + ^(NSString *condition, NSString *fileName, NSNumber *lineNumber, NSString *function, NSString *message) { + existing(condition, fileName, lineNumber, function, message); + assertFunction(condition, fileName, lineNumber, function, message); + }; } else { RCTCurrentAssertFunction = assertFunction; } @@ -101,11 +99,12 @@ NSString *RCTCurrentThreadName(void) } void _RCTAssertFormat( - const char *condition, - const char *fileName, - int lineNumber, - const char *function, - NSString *format, ...) + const char *condition, + const char *fileName, + int lineNumber, + const char *function, + NSString *format, + ...) { RCTAssertFunction assertFunction = RCTGetLocalAssertFunction(); if (assertFunction) { @@ -143,9 +142,10 @@ void RCTFatal(NSError *error) // name: RCTFatalException: // reason: // userInfo: - @throw [[NSException alloc] initWithName:name reason:message userInfo:userInfo]; + @throw [[NSException alloc] initWithName:name reason:message userInfo:userInfo]; #if DEBUG - } @catch (NSException *e) {} + } @catch (NSException *e) { + } #endif } } @@ -160,7 +160,8 @@ RCTFatalHandler RCTGetFatalHandler(void) return RCTCurrentFatalHandler; } -NSString *RCTFormatError(NSString *message, NSArray *> *stackTrace, NSUInteger maxMessageLength) +NSString * +RCTFormatError(NSString *message, NSArray *> *stackTrace, NSUInteger maxMessageLength) { if (maxMessageLength > 0 && message.length > maxMessageLength) { message = [[message substringToIndex:maxMessageLength] stringByAppendingString:@"..."]; @@ -168,26 +169,31 @@ NSString *RCTFormatError(NSString *message, NSArray NSString *prettyStack = RCTFormatStackTrace(stackTrace); - return [NSString stringWithFormat:@"%@%@%@", message, prettyStack ? @", stack:\n" : @"", prettyStack ? prettyStack : @""]; + return [NSString + stringWithFormat:@"%@%@%@", message, prettyStack ? @", stack:\n" : @"", prettyStack ? prettyStack : @""]; } -NSString *RCTFormatStackTrace(NSArray *> *stackTrace) { +NSString *RCTFormatStackTrace(NSArray *> *stackTrace) +{ if (stackTrace) { NSMutableString *prettyStack = [NSMutableString string]; - NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b((?:seg-\\d+(?:_\\d+)?|\\d+)\\.js)" - options:NSRegularExpressionCaseInsensitive - error:NULL]; + NSRegularExpression *regex = + [NSRegularExpression regularExpressionWithPattern:@"\\b((?:seg-\\d+(?:_\\d+)?|\\d+)\\.js)" + options:NSRegularExpressionCaseInsensitive + error:NULL]; for (NSDictionary *frame in stackTrace) { NSString *fileName = [frame[@"file"] lastPathComponent]; - NSTextCheckingResult *match = fileName != nil ? [regex firstMatchInString:fileName options:0 range:NSMakeRange(0, fileName.length)] : nil; + NSTextCheckingResult *match = + fileName != nil ? [regex firstMatchInString:fileName options:0 range:NSMakeRange(0, fileName.length)] : nil; if (match) { fileName = [NSString stringWithFormat:@"%@:", [fileName substringWithRange:match.range]]; } else { fileName = @""; } - [prettyStack appendFormat:@"%@@%@%@:%@\n", frame[@"methodName"], fileName, frame[@"lineNumber"], frame[@"column"]]; + [prettyStack + appendFormat:@"%@@%@%@:%@\n", frame[@"methodName"], fileName, frame[@"lineNumber"], frame[@"column"]]; } return prettyStack; @@ -208,7 +214,8 @@ void RCTFatalException(NSException *exception) #endif @throw exception; #if DEBUG - } @catch (NSException *e) {} + } @catch (NSException *e) { + } #endif } } diff --git a/React/Base/RCTBridge+Private.h b/React/Base/RCTBridge+Private.h index d4bc4f74d6e..2bab73d3086 100644 --- a/React/Base/RCTBridge+Private.h +++ b/React/Base/RCTBridge+Private.h @@ -91,8 +91,7 @@ RCT_EXTERN void RCTRegisterModule(Class); * Used by RCTModuleData to register the module for frame updates after it is * lazily initialized. */ -- (void)registerModuleForFrameUpdates:(id)module - withModuleData:(RCTModuleData *)moduleData; +- (void)registerModuleForFrameUpdates:(id)module withModuleData:(RCTModuleData *)moduleData; /** * Dispatch work to a module's queue - this is also suports the fake RCTJSThread @@ -125,9 +124,7 @@ RCT_EXTERN void RCTRegisterModule(Class); /** * Synchronously call a specific native module's method and return the result */ -- (id)callNativeModule:(NSUInteger)moduleID - method:(NSUInteger)methodID - params:(NSArray *)params; +- (id)callNativeModule:(NSUInteger)moduleID method:(NSUInteger)methodID params:(NSArray *)params; /** * Hook exposed for RCTLog to send logs to JavaScript when not running in JSC diff --git a/React/Base/RCTBridge.h b/React/Base/RCTBridge.h index 8ea31da49a9..63a3b34d511 100644 --- a/React/Base/RCTBridge.h +++ b/React/Base/RCTBridge.h @@ -23,7 +23,6 @@ */ RCT_EXTERN NSString *const RCTJavaScriptWillStartLoadingNotification; - /** * This notification fires when the bridge starts executing the JS bundle. */ @@ -134,7 +133,7 @@ RCT_EXTERN NSString *const RCTBridgeDidDownloadScriptNotificationBridgeDescripti * For this reason, the block should always return new module instances, and * module instances should not be shared between bridges. */ -typedef NSArray> *(^RCTBridgeModuleListProvider)(void); +typedef NSArray> * (^RCTBridgeModuleListProvider)(void); /** * This function returns the module name for a given class. @@ -162,8 +161,7 @@ RCT_EXTERN void RCTEnableTurboModule(BOOL enabled); * pre-initialized module instances if they require additional init parameters * or configuration. */ -- (instancetype)initWithDelegate:(id)delegate - launchOptions:(NSDictionary *)launchOptions; +- (instancetype)initWithDelegate:(id)delegate launchOptions:(NSDictionary *)launchOptions; /** * DEPRECATED: Use initWithDelegate:launchOptions: instead @@ -185,7 +183,10 @@ RCT_EXTERN void RCTEnableTurboModule(BOOL enabled); * with the JavaScript code. Safe to call from any thread. */ - (void)enqueueJSCall:(NSString *)moduleDotMethod args:(NSArray *)args; -- (void)enqueueJSCall:(NSString *)module method:(NSString *)method args:(NSArray *)args completion:(dispatch_block_t)completion; +- (void)enqueueJSCall:(NSString *)module + method:(NSString *)method + args:(NSArray *)args + completion:(dispatch_block_t)completion; /** * This method registers the file path of an additional JS segment by its ID. diff --git a/React/Base/RCTBridge.m b/React/Base/RCTBridge.m index b47f212a30c..32eca6eeb4d 100644 --- a/React/Base/RCTBridge.m +++ b/React/Base/RCTBridge.m @@ -61,12 +61,14 @@ void RCTRegisterModule(Class moduleClass) static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ RCTModuleClasses = [NSMutableArray new]; - RCTModuleClassesSyncQueue = dispatch_queue_create("com.facebook.react.ModuleClassesSyncQueue", DISPATCH_QUEUE_CONCURRENT); + RCTModuleClassesSyncQueue = + dispatch_queue_create("com.facebook.react.ModuleClassesSyncQueue", DISPATCH_QUEUE_CONCURRENT); }); - RCTAssert([moduleClass conformsToProtocol:@protocol(RCTBridgeModule)], - @"%@ does not conform to the RCTBridgeModule protocol", - moduleClass); + RCTAssert( + [moduleClass conformsToProtocol:@protocol(RCTBridgeModule)], + @"%@ does not conform to the RCTBridgeModule protocol", + moduleClass); // Register module dispatch_barrier_async(RCTModuleClassesSyncQueue, ^{ @@ -80,8 +82,10 @@ void RCTRegisterModule(Class moduleClass) NSString *RCTBridgeModuleNameForClass(Class cls) { #if RCT_DEBUG - RCTAssert([cls conformsToProtocol:@protocol(RCTBridgeModule)], - @"Bridge module `%@` does not conform to RCTBridgeModule", cls); + RCTAssert( + [cls conformsToProtocol:@protocol(RCTBridgeModule)], + @"Bridge module `%@` does not conform to RCTBridgeModule", + cls); #endif NSString *name = [cls moduleName]; @@ -104,7 +108,8 @@ BOOL RCTTurboModuleEnabled(void) return turboModuleEnabled; } -void RCTEnableTurboModule(BOOL enabled) { +void RCTEnableTurboModule(BOOL enabled) +{ turboModuleEnabled = enabled; } @@ -158,8 +163,7 @@ void RCTVerifyAllModulesExported(NSArray *extraModules) @interface RCTBridge () @end -@implementation RCTBridge -{ +@implementation RCTBridge { NSURL *_delegateBundleURL; } @@ -169,7 +173,6 @@ dispatch_queue_t RCTJSThread; { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - // Set up JS thread RCTJSThread = (id)kCFNull; }); @@ -193,23 +196,16 @@ static RCTBridge *RCTCurrentBridgeInstance = nil; RCTCurrentBridgeInstance = currentBridge; } -- (instancetype)initWithDelegate:(id)delegate - launchOptions:(NSDictionary *)launchOptions +- (instancetype)initWithDelegate:(id)delegate launchOptions:(NSDictionary *)launchOptions { - return [self initWithDelegate:delegate - bundleURL:nil - moduleProvider:nil - launchOptions:launchOptions]; + return [self initWithDelegate:delegate bundleURL:nil moduleProvider:nil launchOptions:launchOptions]; } - (instancetype)initWithBundleURL:(NSURL *)bundleURL moduleProvider:(RCTBridgeModuleListProvider)block launchOptions:(NSDictionary *)launchOptions { - return [self initWithDelegate:nil - bundleURL:bundleURL - moduleProvider:block - launchOptions:launchOptions]; + return [self initWithDelegate:nil bundleURL:bundleURL moduleProvider:block launchOptions:launchOptions]; } - (instancetype)initWithDelegate:(id)delegate @@ -228,7 +224,7 @@ static RCTBridge *RCTCurrentBridgeInstance = nil; return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (void)dealloc { @@ -297,7 +293,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) */ - (void)reload { - [self reloadWithReason:@"Unknown from bridge"]; + [self reloadWithReason:@"Unknown from bridge"]; } /** @@ -305,14 +301,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) */ - (void)reloadWithReason:(NSString *)reason { - #if RCT_ENABLE_INSPECTOR +#if RCT_ENABLE_INSPECTOR // Disable debugger to resume the JsVM & avoid thread locks while reloading [RCTInspectorDevServerHelper disableDebugger]; - #endif +#endif - [[NSNotificationCenter defaultCenter] postNotificationName:RCTBridgeWillReloadNotification - object:self - userInfo:nil]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTBridgeWillReloadNotification object:self userInfo:nil]; /** * Any thread @@ -393,8 +387,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (void)invalidate { - [[NSNotificationCenter defaultCenter] postNotificationName:RCTBridgeWillBeInvalidatedNotification - object:self]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTBridgeWillBeInvalidatedNotification object:self]; RCTBridge *batchedBridge = self.batchedBridge; self.batchedBridge = nil; diff --git a/React/Base/RCTBridgeDelegate.h b/React/Base/RCTBridgeDelegate.h index 2ae1b8baa9a..00c26f2dac3 100644 --- a/React/Base/RCTBridgeDelegate.h +++ b/React/Base/RCTBridgeDelegate.h @@ -48,12 +48,12 @@ - (BOOL)shouldBridgeUseCustomJSC:(RCTBridge *)bridge; /** -* The bridge will call this method when a module been called from JS -* cannot be found among registered modules. -* It should return YES if the module with name 'moduleName' was registered -* in the implementation, and the system must attempt to look for it again among registered. -* If the module was not registered, return NO to prevent further searches. -*/ + * The bridge will call this method when a module been called from JS + * cannot be found among registered modules. + * It should return YES if the module with name 'moduleName' was registered + * in the implementation, and the system must attempt to look for it again among registered. + * If the module was not registered, return NO to prevent further searches. + */ - (BOOL)bridge:(RCTBridge *)bridge didNotFindModule:(NSString *)moduleName; /** @@ -69,8 +69,7 @@ * Similar to loadSourceForBridge:onProgress:onComplete: but without progress * reporting. */ -- (void)loadSourceForBridge:(RCTBridge *)bridge - withBlock:(RCTSourceLoadBlock)loadCallback; +- (void)loadSourceForBridge:(RCTBridge *)bridge withBlock:(RCTSourceLoadBlock)loadCallback; /** * Retrieve the list of lazy-native-modules names for the given bridge. diff --git a/React/Base/RCTBridgeMethod.h b/React/Base/RCTBridgeMethod.h index df0798158f7..35d2b893ae3 100644 --- a/React/Base/RCTBridgeMethod.h +++ b/React/Base/RCTBridgeMethod.h @@ -15,7 +15,8 @@ typedef NS_ENUM(NSUInteger, RCTFunctionType) { RCTFunctionTypeSync, }; -static inline const char *RCTFunctionDescriptorFromType(RCTFunctionType type) { +static inline const char *RCTFunctionDescriptorFromType(RCTFunctionType type) +{ switch (type) { case RCTFunctionTypeNormal: return "async"; @@ -31,8 +32,6 @@ static inline const char *RCTFunctionDescriptorFromType(RCTFunctionType type) { @property (nonatomic, readonly) const char *JSMethodName; @property (nonatomic, readonly) RCTFunctionType functionType; -- (id)invokeWithBridge:(RCTBridge *)bridge - module:(id)module - arguments:(NSArray *)arguments; +- (id)invokeWithBridge:(RCTBridge *)bridge module:(id)module arguments:(NSArray *)arguments; @end diff --git a/React/Base/RCTBridgeModule.h b/React/Base/RCTBridgeModule.h index 31d459b1555..98b7754ae75 100644 --- a/React/Base/RCTBridgeModule.h +++ b/React/Base/RCTBridgeModule.h @@ -68,21 +68,32 @@ RCT_EXTERN_C_END * will be used as the JS module name. If omitted, the JS module name will * match the Objective-C class name. */ -#define RCT_EXPORT_MODULE(js_name) \ -RCT_EXTERN void RCTRegisterModule(Class); \ -+ (NSString *)moduleName { return @#js_name; } \ -+ (void)load { RCTRegisterModule(self); } +#define RCT_EXPORT_MODULE(js_name) \ + RCT_EXTERN void RCTRegisterModule(Class); \ + +(NSString *)moduleName \ + { \ + return @ #js_name; \ + } \ + +(void)load \ + { \ + RCTRegisterModule(self); \ + } /** * Same as RCT_EXPORT_MODULE, but uses __attribute__((constructor)) for module * registration. Useful for registering swift classes that forbids use of load * Used in RCT_EXTERN_REMAP_MODULE */ -#define RCT_EXPORT_MODULE_NO_LOAD(js_name, objc_name) \ -RCT_EXTERN void RCTRegisterModule(Class); \ -+ (NSString *)moduleName { return @#js_name; } \ -__attribute__((constructor)) static void \ -RCT_CONCAT(initialize_, objc_name)() { RCTRegisterModule([objc_name class]); } +#define RCT_EXPORT_MODULE_NO_LOAD(js_name, objc_name) \ + RCT_EXTERN void RCTRegisterModule(Class); \ + +(NSString *)moduleName \ + { \ + return @ #js_name; \ + } \ + __attribute__((constructor)) static void RCT_CONCAT(initialize_, objc_name)() \ + { \ + RCTRegisterModule([objc_name class]); \ + } /** * To improve startup performance users may want to generate their module lists @@ -92,7 +103,10 @@ RCT_CONCAT(initialize_, objc_name)() { RCTRegisterModule([objc_name class]); } * */ #define RCT_EXPORT_PRE_REGISTERED_MODULE(js_name) \ -+ (NSString *)moduleName { return @#js_name; } + +(NSString *)moduleName \ + { \ + return @ #js_name; \ + } // Implemented by RCT_EXPORT_MODULE + (NSString *)moduleName; @@ -171,8 +185,7 @@ RCT_CONCAT(initialize_, objc_name)() { RCTRegisterModule([objc_name class]); } * native method implementation calls the respective block. * */ -#define RCT_EXPORT_METHOD(method) \ - RCT_REMAP_METHOD(, method) +#define RCT_EXPORT_METHOD(method) RCT_REMAP_METHOD(, method) /** * Same as RCT_EXPORT_METHOD but the method is called from JS @@ -190,13 +203,11 @@ RCT_CONCAT(initialize_, objc_name)() { RCTRegisterModule([objc_name class]); } * Calling these methods when running under the websocket executor * is currently not supported. */ -#define RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(method) \ - RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(id, method) +#define RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(method) RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(id, method) #define RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(returnType, method) \ RCT_REMAP_BLOCKING_SYNCHRONOUS_METHOD(, returnType, method) - /** * Similar to RCT_EXPORT_METHOD but lets you set the JS name of the exported * method. Example usage: @@ -205,9 +216,9 @@ RCT_CONCAT(initialize_, objc_name)() { RCTRegisterModule([objc_name class]); } * executeQuery:(NSString *)query parameters:(NSDictionary *)parameters) * { ... } */ -#define RCT_REMAP_METHOD(js_name, method) \ +#define RCT_REMAP_METHOD(js_name, method) \ _RCT_EXTERN_REMAP_METHOD(js_name, method, NO) \ - - (void)method RCT_DYNAMIC; + -(void)method RCT_DYNAMIC; /** * Similar to RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD but lets you set @@ -218,8 +229,8 @@ RCT_CONCAT(initialize_, objc_name)() { RCTRegisterModule([objc_name class]); } * { ... } */ #define RCT_REMAP_BLOCKING_SYNCHRONOUS_METHOD(js_name, returnType, method) \ - _RCT_EXTERN_REMAP_METHOD(js_name, method, YES) \ - - (returnType)method RCT_DYNAMIC; + _RCT_EXTERN_REMAP_METHOD(js_name, method, YES) \ + -(returnType)method RCT_DYNAMIC; /** * Use this macro in a private Objective-C implementation file to automatically @@ -249,42 +260,40 @@ RCT_CONCAT(initialize_, objc_name)() { RCTRegisterModule([objc_name class]); } * This will now expose MyModule and the method to JavaScript via * `NativeModules.MyModule.doSomething` */ -#define RCT_EXTERN_MODULE(objc_name, objc_supername) \ - RCT_EXTERN_REMAP_MODULE(, objc_name, objc_supername) +#define RCT_EXTERN_MODULE(objc_name, objc_supername) RCT_EXTERN_REMAP_MODULE(, objc_name, objc_supername) /** * Like RCT_EXTERN_MODULE, but allows setting a custom JavaScript name. */ #define RCT_EXTERN_REMAP_MODULE(js_name, objc_name, objc_supername) \ - objc_name : objc_supername \ - @end \ - @interface objc_name (RCTExternModule) \ - @end \ - @implementation objc_name (RCTExternModule) \ + objc_name: \ + objc_supername @ \ + end @interface objc_name(RCTExternModule) \ + @end \ + @implementation objc_name (RCTExternModule) \ RCT_EXPORT_MODULE_NO_LOAD(js_name, objc_name) /** * Use this macro in accordance with RCT_EXTERN_MODULE to export methods * of an external module. */ -#define RCT_EXTERN_METHOD(method) \ - _RCT_EXTERN_REMAP_METHOD(, method, NO) +#define RCT_EXTERN_METHOD(method) _RCT_EXTERN_REMAP_METHOD(, method, NO) /** * Use this macro in accordance with RCT_EXTERN_MODULE to export methods * of an external module that should be invoked synchronously. */ -#define RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(method) \ - _RCT_EXTERN_REMAP_METHOD(, method, YES) +#define RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(method) _RCT_EXTERN_REMAP_METHOD(, method, YES) /** * Like RCT_EXTERN_REMAP_METHOD, but allows setting a custom JavaScript name * and also whether this method is synchronous. */ -#define _RCT_EXTERN_REMAP_METHOD(js_name, method, is_blocking_synchronous_method) \ - + (const RCTMethodInfo *)RCT_CONCAT(__rct_export__, RCT_CONCAT(js_name, RCT_CONCAT(__LINE__, __COUNTER__))) { \ - static RCTMethodInfo config = {#js_name, #method, is_blocking_synchronous_method}; \ - return &config; \ +#define _RCT_EXTERN_REMAP_METHOD(js_name, method, is_blocking_synchronous_method) \ + +(const RCTMethodInfo *)RCT_CONCAT(__rct_export__, RCT_CONCAT(js_name, RCT_CONCAT(__LINE__, __COUNTER__))) \ + { \ + static RCTMethodInfo config = {#js_name, #method, is_blocking_synchronous_method}; \ + return &config; \ } /** @@ -337,21 +346,21 @@ RCT_CONCAT(initialize_, objc_name)() { RCTRegisterModule([objc_name class]); } * A protocol that allows TurboModules to do lookup on other TurboModules. * Calling these methods may cause a module to be synchronously instantiated. */ - @protocol RCTTurboModuleLookupDelegate - - (id)moduleForName:(const char *)moduleName; +@protocol RCTTurboModuleLookupDelegate +- (id)moduleForName:(const char *)moduleName; - /** - * Rationale: - * When TurboModules lookup other modules by name, we first check the TurboModule - * registry to see if a TurboModule exists with the respective name. In this case, - * we don't want a RedBox to be raised if the TurboModule isn't found. - * - * This method is deprecated and will be deleted after the migration from - * TurboModules to TurboModules is complete. - */ - - (id)moduleForName:(const char *)moduleName warnOnLookupFailure:(BOOL)warnOnLookupFailure; - - (BOOL)moduleIsInitialized:(const char *)moduleName; - @end +/** + * Rationale: + * When TurboModules lookup other modules by name, we first check the TurboModule + * registry to see if a TurboModule exists with the respective name. In this case, + * we don't want a RedBox to be raised if the TurboModule isn't found. + * + * This method is deprecated and will be deleted after the migration from + * TurboModules to TurboModules is complete. + */ +- (id)moduleForName:(const char *)moduleName warnOnLookupFailure:(BOOL)warnOnLookupFailure; +- (BOOL)moduleIsInitialized:(const char *)moduleName; +@end /** * Experimental. diff --git a/React/Base/RCTBundleURLProvider.h b/React/Base/RCTBundleURLProvider.h index 9ccf4194965..ba84d0ebb19 100644 --- a/React/Base/RCTBundleURLProvider.h +++ b/React/Base/RCTBundleURLProvider.h @@ -39,8 +39,7 @@ extern const NSUInteger kRCTBundleURLProviderDefaultPort; * Returns the jsBundleURL for a given bundle entrypoint and * the fallback offline JS bundle if the packager is not running. */ -- (NSURL *)jsBundleURLForBundleRoot:(NSString *)bundleRoot - fallbackURLProvider:(NSURL *(^)(void))fallbackURLProvider; +- (NSURL *)jsBundleURLForBundleRoot:(NSString *)bundleRoot fallbackURLProvider:(NSURL * (^)(void))fallbackURLProvider; /** * Returns the jsBundleURL for a given bundle entrypoint and @@ -56,16 +55,14 @@ extern const NSUInteger kRCTBundleURLProviderDefaultPort; * Returns the jsBundleURL for a given bundle entrypoint and * the fallback offline JS bundle if the packager is not running. */ -- (NSURL *)jsBundleURLForBundleRoot:(NSString *)bundleRoot - fallbackResource:(NSString *)resourceName; +- (NSURL *)jsBundleURLForBundleRoot:(NSString *)bundleRoot fallbackResource:(NSString *)resourceName; /** * Returns the jsBundleURL for a given bundle entrypoint and * the fallback offline JS bundle. If resourceName or extension * are nil, "main" and "jsbundle" will be used, respectively. */ -- (NSURL *)jsBundleURLForFallbackResource:(NSString *)resourceName - fallbackExtension:(NSString *)extension; +- (NSURL *)jsBundleURLForFallbackResource:(NSString *)resourceName fallbackExtension:(NSString *)extension; /** * Returns the resourceURL for a given bundle entrypoint and @@ -102,8 +99,6 @@ extern const NSUInteger kRCTBundleURLProviderDefaultPort; * In general, please use the instance method to decide if the packager is running and fallback to the pre-packaged * resource if it is not: -resourceURLForResourceRoot:resourceName:resourceExtension:offlineBundle: */ -+ (NSURL *)resourceURLForResourcePath:(NSString *)path - packagerHost:(NSString *)packagerHost - query:(NSString *)query; ++ (NSURL *)resourceURLForResourcePath:(NSString *)path packagerHost:(NSString *)packagerHost query:(NSString *)query; @end diff --git a/React/Base/RCTBundleURLProvider.m b/React/Base/RCTBundleURLProvider.m index 240fc4cadd5..96083efa2dc 100644 --- a/React/Base/RCTBundleURLProvider.m +++ b/React/Base/RCTBundleURLProvider.m @@ -35,9 +35,9 @@ static NSString *const kRCTEnableMinificationKey = @"RCT_enableMinification"; - (NSDictionary *)defaults { return @{ - kRCTEnableLiveReloadKey: @NO, - kRCTEnableDevKey: @YES, - kRCTEnableMinificationKey: @NO, + kRCTEnableLiveReloadKey : @NO, + kRCTEnableDevKey : @YES, + kRCTEnableMinificationKey : @NO, }; } @@ -62,14 +62,12 @@ static NSString *const kRCTEnableMinificationKey = @"RCT_enableMinification"; static NSURL *serverRootWithHostPort(NSString *hostPort) { - if([hostPort rangeOfString:@":"].location != NSNotFound){ - return [NSURL URLWithString: - [NSString stringWithFormat:@"http://%@/", - hostPort]]; + if ([hostPort rangeOfString:@":"].location != NSNotFound) { + return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@/", hostPort]]; } - return [NSURL URLWithString: - [NSString stringWithFormat:@"http://%@:%lu/", - hostPort, (unsigned long)kRCTBundleURLProviderDefaultPort]]; + return [NSURL + URLWithString:[NSString + stringWithFormat:@"http://%@:%lu/", hostPort, (unsigned long)kRCTBundleURLProviderDefaultPort]]; } #if RCT_DEV @@ -84,13 +82,11 @@ static NSURL *serverRootWithHostPort(NSString *hostPort) dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); [[session dataTaskWithRequest:request - completionHandler:^(NSData *d, - NSURLResponse *res, - __unused NSError *err) { - data = d; - response = res; - dispatch_semaphore_signal(semaphore); - }] resume]; + completionHandler:^(NSData *d, NSURLResponse *res, __unused NSError *err) { + data = d; + response = res; + dispatch_semaphore_signal(semaphore); + }] resume]; dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); NSString *status = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; @@ -103,8 +99,9 @@ static NSURL *serverRootWithHostPort(NSString *hostPort) static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSString *ipPath = [[NSBundle mainBundle] pathForResource:@"ip" ofType:@"txt"]; - ipGuess = [[NSString stringWithContentsOfFile:ipPath encoding:NSUTF8StringEncoding error:nil] - stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; + ipGuess = + [[NSString stringWithContentsOfFile:ipPath encoding:NSUTF8StringEncoding + error:nil] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; }); NSString *host = ipGuess ?: @"localhost"; @@ -130,7 +127,7 @@ static NSURL *serverRootWithHostPort(NSString *hostPort) return nil; } -- (NSURL *)jsBundleURLForBundleRoot:(NSString *)bundleRoot fallbackURLProvider:(NSURL *(^)(void))fallbackURLProvider +- (NSURL *)jsBundleURLForBundleRoot:(NSString *)bundleRoot fallbackURLProvider:(NSURL * (^)(void))fallbackURLProvider { NSString *packagerServerHost = [self packagerServerHost]; if (!packagerServerHost) { @@ -144,11 +141,13 @@ static NSURL *serverRootWithHostPort(NSString *hostPort) } - (NSURL *)jsBundleURLForBundleRoot:(NSString *)bundleRoot - fallbackResource:(NSString *)resourceName fallbackExtension:(NSString *)extension + fallbackResource:(NSString *)resourceName + fallbackExtension:(NSString *)extension { - return [self jsBundleURLForBundleRoot:bundleRoot fallbackURLProvider:^NSURL*{ - return [self jsBundleURLForFallbackResource:resourceName fallbackExtension:extension]; - }]; + return [self jsBundleURLForBundleRoot:bundleRoot + fallbackURLProvider:^NSURL * { + return [self jsBundleURLForFallbackResource:resourceName fallbackExtension:extension]; + }]; } - (NSURL *)jsBundleURLForBundleRoot:(NSString *)bundleRoot fallbackResource:(NSString *)resourceName @@ -156,8 +155,7 @@ static NSURL *serverRootWithHostPort(NSString *hostPort) return [self jsBundleURLForBundleRoot:bundleRoot fallbackResource:resourceName fallbackExtension:nil]; } -- (NSURL *)jsBundleURLForFallbackResource:(NSString *)resourceName - fallbackExtension:(NSString *)extension +- (NSURL *)jsBundleURLForFallbackResource:(NSString *)resourceName fallbackExtension:(NSString *)extension { resourceName = resourceName ?: @"main"; extension = extension ?: @"jsbundle"; @@ -187,16 +185,15 @@ static NSURL *serverRootWithHostPort(NSString *hostPort) NSString *path = [NSString stringWithFormat:@"/%@.bundle", bundleRoot]; // When we support only iOS 8 and above, use queryItems for a better API. NSString *query = [NSString stringWithFormat:@"platform=ios&dev=%@&minify=%@", - enableDev ? @"true" : @"false", - enableMinification ? @"true": @"false"]; + enableDev ? @"true" : @"false", + enableMinification ? @"true" : @"false"]; return [[self class] resourceURLForResourcePath:path packagerHost:packagerHost query:query]; } -+ (NSURL *)resourceURLForResourcePath:(NSString *)path - packagerHost:(NSString *)packagerHost - query:(NSString *)query ++ (NSURL *)resourceURLForResourcePath:(NSString *)path packagerHost:(NSString *)packagerHost query:(NSString *)query { - NSURLComponents *components = [NSURLComponents componentsWithURL:serverRootWithHostPort(packagerHost) resolvingAgainstBaseURL:NO]; + NSURLComponents *components = [NSURLComponents componentsWithURL:serverRootWithHostPort(packagerHost) + resolvingAgainstBaseURL:NO]; components.path = path; if (query != nil) { components.query = query; diff --git a/React/Base/RCTComponentEvent.h b/React/Base/RCTComponentEvent.h index f78f0caec06..cad756234b2 100644 --- a/React/Base/RCTComponentEvent.h +++ b/React/Base/RCTComponentEvent.h @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN * RCTBubblingEventBlock, for other use cases prefer using a class that implements * RCTEvent to have a type safe way to initialize it. */ -@interface RCTComponentEvent : NSObject +@interface RCTComponentEvent : NSObject - (instancetype)initWithName:(NSString *)name viewTag:(NSNumber *)viewTag body:(NSDictionary *)body; diff --git a/React/Base/RCTComponentEvent.m b/React/Base/RCTComponentEvent.m index e05dd0b836f..5fb4295752e 100644 --- a/React/Base/RCTComponentEvent.m +++ b/React/Base/RCTComponentEvent.m @@ -9,8 +9,7 @@ #import "RCTAssert.h" -@implementation RCTComponentEvent -{ +@implementation RCTComponentEvent { NSArray *_arguments; } @@ -25,12 +24,12 @@ _eventName = RCTNormalizeInputEventName(name); _viewTag = viewTag; - _arguments = @[_viewTag, _eventName, mutableBody]; + _arguments = @[ _viewTag, _eventName, mutableBody ]; } return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (NSArray *)arguments { diff --git a/React/Base/RCTConvert.h b/React/Base/RCTConvert.h index 781346e088b..31df920476d 100644 --- a/React/Base/RCTConvert.h +++ b/React/Base/RCTConvert.h @@ -170,35 +170,32 @@ RCT_EXTERN NSArray *RCTConvertArrayValue(SEL, id); * avoid repeating the same boilerplate for every error message. */ #define RCTLogConvertError(json, typeName) \ -RCTLogError(@"JSON value '%@' of type %@ cannot be converted to %@", \ -json, [json classForCoder], typeName) + RCTLogError(@"JSON value '%@' of type %@ cannot be converted to %@", json, [json classForCoder], typeName) /** * This macro is used for creating simple converter functions that just call * the specified getter method on the json value. */ -#define RCT_CONVERTER(type, name, getter) \ -RCT_CUSTOM_CONVERTER(type, name, [json getter]) +#define RCT_CONVERTER(type, name, getter) RCT_CUSTOM_CONVERTER(type, name, [json getter]) /** * This macro is used for creating converter functions with arbitrary logic. */ #define RCT_CUSTOM_CONVERTER(type, name, code) \ -+ (type)name:(id)json RCT_DYNAMIC \ -{ \ - if (!RCT_DEBUG) { \ - return code; \ - } else { \ - @try { \ + +(type)name : (id)json RCT_DYNAMIC \ + { \ + if (!RCT_DEBUG) { \ return code; \ + } else { \ + @try { \ + return code; \ + } @catch (__unused NSException * e) { \ + RCTLogConvertError(json, @ #type); \ + json = nil; \ + return code; \ + } \ } \ - @catch (__unused NSException *e) { \ - RCTLogConvertError(json, @#type); \ - json = nil; \ - return code; \ - } \ - } \ -} + } /** * This macro is similar to RCT_CONVERTER, but specifically geared towards @@ -206,7 +203,7 @@ RCT_CUSTOM_CONVERTER(type, name, [json getter]) * detailed error reporting if an invalid value is passed in. */ #define RCT_NUMBER_CONVERTER(type, getter) \ -RCT_CUSTOM_CONVERTER(type, type, [RCT_DEBUG ? [self NSNumber:json] : json getter]) + RCT_CUSTOM_CONVERTER(type, type, [RCT_DEBUG ? [self NSNumber:json] : json getter]) /** * When using RCT_ENUM_CONVERTER in ObjC, the compiler is OK with us returning @@ -222,41 +219,41 @@ RCT_CUSTOM_CONVERTER(type, type, [RCT_DEBUG ? [self NSNumber:json] : json getter /** * This macro is used for creating converters for enum types. */ -#define RCT_ENUM_CONVERTER(type, values, default, getter) \ -+ (type)type:(id)json RCT_DYNAMIC \ -{ \ - static NSDictionary *mapping; \ - static dispatch_once_t onceToken; \ - dispatch_once(&onceToken, ^{ \ - mapping = values; \ - }); \ - return _RCT_CAST(type, [RCTConvertEnumValue(#type, mapping, @(default), json) getter]); \ -} +#define RCT_ENUM_CONVERTER(type, values, default, getter) \ + +(type)type : (id)json RCT_DYNAMIC \ + { \ + static NSDictionary *mapping; \ + static dispatch_once_t onceToken; \ + dispatch_once(&onceToken, ^{ \ + mapping = values; \ + }); \ + return _RCT_CAST(type, [RCTConvertEnumValue(#type, mapping, @(default), json) getter]); \ + } /** * This macro is used for creating converters for enum types for * multiple enum values combined with | operator */ -#define RCT_MULTI_ENUM_CONVERTER(type, values, default, getter) \ -+ (type)type:(id)json RCT_DYNAMIC \ -{ \ - static NSDictionary *mapping; \ - static dispatch_once_t onceToken; \ - dispatch_once(&onceToken, ^{ \ - mapping = values; \ - }); \ - return _RCT_CAST(type, [RCTConvertMultiEnumValue(#type, mapping, @(default), json) getter]); \ -} +#define RCT_MULTI_ENUM_CONVERTER(type, values, default, getter) \ + +(type)type : (id)json RCT_DYNAMIC \ + { \ + static NSDictionary *mapping; \ + static dispatch_once_t onceToken; \ + dispatch_once(&onceToken, ^{ \ + mapping = values; \ + }); \ + return _RCT_CAST(type, [RCTConvertMultiEnumValue(#type, mapping, @(default), json) getter]); \ + } /** * This macro is used for creating explicitly-named converter functions * for typed arrays. */ -#define RCT_ARRAY_CONVERTER_NAMED(type, name) \ -+ (NSArray *)name##Array:(id)json RCT_DYNAMIC \ -{ \ - return RCTConvertArrayValue(@selector(name:), json); \ -} +#define RCT_ARRAY_CONVERTER_NAMED(type, name) \ + +(NSArray *)name##Array : (id)json RCT_DYNAMIC \ + { \ + return RCTConvertArrayValue(@selector(name:), json); \ + } /** * This macro is used for creating converter functions for typed arrays. diff --git a/React/Base/RCTConvert.m b/React/Base/RCTConvert.m index 9e0791cb8fc..0102ecf906a 100644 --- a/React/Base/RCTConvert.m +++ b/React/Base/RCTConvert.m @@ -36,19 +36,22 @@ RCT_NUMBER_CONVERTER(NSUInteger, unsignedIntegerValue) * representable json values that require no conversion. */ #if RCT_DEBUG -#define RCT_JSON_CONVERTER(type) \ -+ (type *)type:(id)json \ -{ \ - if ([json isKindOfClass:[type class]]) { \ - return json; \ - } else if (json) { \ - RCTLogConvertError(json, @#type); \ - } \ - return nil; \ -} +#define RCT_JSON_CONVERTER(type) \ + +(type *)type : (id)json \ + { \ + if ([json isKindOfClass:[type class]]) { \ + return json; \ + } else if (json) { \ + RCTLogConvertError(json, @ #type); \ + } \ + return nil; \ + } #else -#define RCT_JSON_CONVERTER(type) \ -+ (type *)type:(id)json { return json; } +#define RCT_JSON_CONVERTER(type) \ + +(type *)type : (id)json \ + { \ + return json; \ + } #endif RCT_JSON_CONVERTER(NSArray) @@ -116,20 +119,22 @@ RCT_CUSTOM_CONVERTER(NSData *, NSData, [json dataUsingEncoding:NSUTF8StringEncod RCTLogConvertError(json, @"a valid URL"); } return URL; - } - @catch (__unused NSException *e) { + } @catch (__unused NSException *e) { RCTLogConvertError(json, @"a valid URL"); return nil; } } -RCT_ENUM_CONVERTER(NSURLRequestCachePolicy, (@{ - @"default": @(NSURLRequestUseProtocolCachePolicy), - @"reload": @(NSURLRequestReloadIgnoringLocalCacheData), - @"force-cache": @(NSURLRequestReturnCacheDataElseLoad), - @"only-if-cached": @(NSURLRequestReturnCacheDataDontLoad), - }), NSURLRequestUseProtocolCachePolicy, integerValue) - +RCT_ENUM_CONVERTER( + NSURLRequestCachePolicy, + (@{ + @"default" : @(NSURLRequestUseProtocolCachePolicy), + @"reload" : @(NSURLRequestReloadIgnoringLocalCacheData), + @"force-cache" : @(NSURLRequestReturnCacheDataElseLoad), + @"only-if-cached" : @(NSURLRequestReturnCacheDataDontLoad), + }), + NSURLRequestUseProtocolCachePolicy, + integerValue) + (NSURLRequest *)NSURLRequest:(id)json { @@ -155,7 +160,8 @@ RCT_ENUM_CONVERTER(NSURLRequestCachePolicy, (@{ NSString *method = [self NSString:json[@"method"]].uppercaseString ?: @"GET"; NSURLRequestCachePolicy cachePolicy = [self NSURLRequestCachePolicy:json[@"cache"]]; NSDictionary *headers = [self NSDictionary:json[@"headers"]]; - if ([method isEqualToString:@"GET"] && headers == nil && body == nil && cachePolicy == NSURLRequestUseProtocolCachePolicy) { + if ([method isEqualToString:@"GET"] && headers == nil && body == nil && + cachePolicy == NSURLRequestUseProtocolCachePolicy) { return [NSURLRequest requestWithURL:URL]; } @@ -163,8 +169,10 @@ RCT_ENUM_CONVERTER(NSURLRequestCachePolicy, (@{ __block BOOL allHeadersAreStrings = YES; [headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, id header, BOOL *stop) { if (![header isKindOfClass:[NSString class]]) { - RCTLogError(@"Values of HTTP headers passed must be of type string. " - "Value of header '%@' is not a string.", key); + RCTLogError( + @"Values of HTTP headers passed must be of type string. " + "Value of header '%@' is not a string.", + key); allHeadersAreStrings = NO; *stop = YES; } @@ -217,8 +225,10 @@ RCT_ENUM_CONVERTER(NSURLRequestCachePolicy, (@{ }); NSDate *date = [formatter dateFromString:json]; if (!date) { - RCTLogError(@"JSON String '%@' could not be interpreted as a date. " - "Expected format: YYYY-MM-DD'T'HH:mm:ss.sssZ", json); + RCTLogError( + @"JSON String '%@' could not be interpreted as a date. " + "Expected format: YYYY-MM-DD'T'HH:mm:ss.sssZ", + json); } return date; } else if (json) { @@ -261,12 +271,15 @@ NSNumber *RCTConvertEnumValue(const char *typeName, NSDictionary *mapping, NSNum return defaultValue; } if (RCT_DEBUG && ![json isKindOfClass:[NSString class]]) { - RCTLogError(@"Expected NSNumber or NSString for %s, received %@: %@", - typeName, [json classForCoder], json); + RCTLogError(@"Expected NSNumber or NSString for %s, received %@: %@", typeName, [json classForCoder], json); } id value = mapping[json]; if (RCT_DEBUG && !value && [json description].length > 0) { - RCTLogError(@"Invalid %s '%@'. should be one of: %@", typeName, json, [[mapping allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)]); + RCTLogError( + @"Invalid %s '%@'. should be one of: %@", + typeName, + json, + [[mapping allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]); } return value ?: defaultValue; } @@ -287,61 +300,93 @@ NSNumber *RCTConvertMultiEnumValue(const char *typeName, NSDictionary *mapping, return RCTConvertEnumValue(typeName, mapping, defaultValue, json); } -RCT_ENUM_CONVERTER(NSLineBreakMode, (@{ - @"clip": @(NSLineBreakByClipping), - @"head": @(NSLineBreakByTruncatingHead), - @"tail": @(NSLineBreakByTruncatingTail), - @"middle": @(NSLineBreakByTruncatingMiddle), - @"wordWrapping": @(NSLineBreakByWordWrapping), -}), NSLineBreakByTruncatingTail, integerValue) +RCT_ENUM_CONVERTER( + NSLineBreakMode, + (@{ + @"clip" : @(NSLineBreakByClipping), + @"head" : @(NSLineBreakByTruncatingHead), + @"tail" : @(NSLineBreakByTruncatingTail), + @"middle" : @(NSLineBreakByTruncatingMiddle), + @"wordWrapping" : @(NSLineBreakByWordWrapping), + }), + NSLineBreakByTruncatingTail, + integerValue) -RCT_ENUM_CONVERTER(NSTextAlignment, (@{ - @"auto": @(NSTextAlignmentNatural), - @"left": @(NSTextAlignmentLeft), - @"center": @(NSTextAlignmentCenter), - @"right": @(NSTextAlignmentRight), - @"justify": @(NSTextAlignmentJustified), -}), NSTextAlignmentNatural, integerValue) +RCT_ENUM_CONVERTER( + NSTextAlignment, + (@{ + @"auto" : @(NSTextAlignmentNatural), + @"left" : @(NSTextAlignmentLeft), + @"center" : @(NSTextAlignmentCenter), + @"right" : @(NSTextAlignmentRight), + @"justify" : @(NSTextAlignmentJustified), + }), + NSTextAlignmentNatural, + integerValue) -RCT_ENUM_CONVERTER(NSUnderlineStyle, (@{ - @"solid": @(NSUnderlineStyleSingle), - @"double": @(NSUnderlineStyleDouble), - @"dotted": @(NSUnderlinePatternDot | NSUnderlineStyleSingle), - @"dashed": @(NSUnderlinePatternDash | NSUnderlineStyleSingle), -}), NSUnderlineStyleSingle, integerValue) +RCT_ENUM_CONVERTER( + NSUnderlineStyle, + (@{ + @"solid" : @(NSUnderlineStyleSingle), + @"double" : @(NSUnderlineStyleDouble), + @"dotted" : @(NSUnderlinePatternDot | NSUnderlineStyleSingle), + @"dashed" : @(NSUnderlinePatternDash | NSUnderlineStyleSingle), + }), + NSUnderlineStyleSingle, + integerValue) -RCT_ENUM_CONVERTER(RCTBorderStyle, (@{ - @"solid": @(RCTBorderStyleSolid), - @"dotted": @(RCTBorderStyleDotted), - @"dashed": @(RCTBorderStyleDashed), -}), RCTBorderStyleSolid, integerValue) +RCT_ENUM_CONVERTER( + RCTBorderStyle, + (@{ + @"solid" : @(RCTBorderStyleSolid), + @"dotted" : @(RCTBorderStyleDotted), + @"dashed" : @(RCTBorderStyleDashed), + }), + RCTBorderStyleSolid, + integerValue) -RCT_ENUM_CONVERTER(RCTTextDecorationLineType, (@{ - @"none": @(RCTTextDecorationLineTypeNone), - @"underline": @(RCTTextDecorationLineTypeUnderline), - @"line-through": @(RCTTextDecorationLineTypeStrikethrough), - @"underline line-through": @(RCTTextDecorationLineTypeUnderlineStrikethrough), -}), RCTTextDecorationLineTypeNone, integerValue) +RCT_ENUM_CONVERTER( + RCTTextDecorationLineType, + (@{ + @"none" : @(RCTTextDecorationLineTypeNone), + @"underline" : @(RCTTextDecorationLineTypeUnderline), + @"line-through" : @(RCTTextDecorationLineTypeStrikethrough), + @"underline line-through" : @(RCTTextDecorationLineTypeUnderlineStrikethrough), + }), + RCTTextDecorationLineTypeNone, + integerValue) -RCT_ENUM_CONVERTER(NSWritingDirection, (@{ - @"auto": @(NSWritingDirectionNatural), - @"ltr": @(NSWritingDirectionLeftToRight), - @"rtl": @(NSWritingDirectionRightToLeft), -}), NSWritingDirectionNatural, integerValue) +RCT_ENUM_CONVERTER( + NSWritingDirection, + (@{ + @"auto" : @(NSWritingDirectionNatural), + @"ltr" : @(NSWritingDirectionLeftToRight), + @"rtl" : @(NSWritingDirectionRightToLeft), + }), + NSWritingDirectionNatural, + integerValue) -RCT_ENUM_CONVERTER(UITextAutocapitalizationType, (@{ - @"none": @(UITextAutocapitalizationTypeNone), - @"words": @(UITextAutocapitalizationTypeWords), - @"sentences": @(UITextAutocapitalizationTypeSentences), - @"characters": @(UITextAutocapitalizationTypeAllCharacters) -}), UITextAutocapitalizationTypeSentences, integerValue) +RCT_ENUM_CONVERTER( + UITextAutocapitalizationType, + (@{ + @"none" : @(UITextAutocapitalizationTypeNone), + @"words" : @(UITextAutocapitalizationTypeWords), + @"sentences" : @(UITextAutocapitalizationTypeSentences), + @"characters" : @(UITextAutocapitalizationTypeAllCharacters) + }), + UITextAutocapitalizationTypeSentences, + integerValue) -RCT_ENUM_CONVERTER(UITextFieldViewMode, (@{ - @"never": @(UITextFieldViewModeNever), - @"while-editing": @(UITextFieldViewModeWhileEditing), - @"unless-editing": @(UITextFieldViewModeUnlessEditing), - @"always": @(UITextFieldViewModeAlways), -}), UITextFieldViewModeNever, integerValue) +RCT_ENUM_CONVERTER( + UITextFieldViewMode, + (@{ + @"never" : @(UITextFieldViewModeNever), + @"while-editing" : @(UITextFieldViewModeWhileEditing), + @"unless-editing" : @(UITextFieldViewModeUnlessEditing), + @"always" : @(UITextFieldViewModeAlways), + }), + UITextFieldViewModeNever, + integerValue) + (UIKeyboardType)UIKeyboardType:(id)json RCT_DYNAMIC { @@ -349,20 +394,20 @@ RCT_ENUM_CONVERTER(UITextFieldViewMode, (@{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSMutableDictionary *temporaryMapping = [NSMutableDictionary dictionaryWithDictionary:@{ - @"default": @(UIKeyboardTypeDefault), - @"ascii-capable": @(UIKeyboardTypeASCIICapable), - @"numbers-and-punctuation": @(UIKeyboardTypeNumbersAndPunctuation), - @"url": @(UIKeyboardTypeURL), - @"number-pad": @(UIKeyboardTypeNumberPad), - @"phone-pad": @(UIKeyboardTypePhonePad), - @"name-phone-pad": @(UIKeyboardTypeNamePhonePad), - @"email-address": @(UIKeyboardTypeEmailAddress), - @"decimal-pad": @(UIKeyboardTypeDecimalPad), - @"twitter": @(UIKeyboardTypeTwitter), - @"web-search": @(UIKeyboardTypeWebSearch), - // Added for Android compatibility - @"numeric": @(UIKeyboardTypeDecimalPad), - }]; + @"default" : @(UIKeyboardTypeDefault), + @"ascii-capable" : @(UIKeyboardTypeASCIICapable), + @"numbers-and-punctuation" : @(UIKeyboardTypeNumbersAndPunctuation), + @"url" : @(UIKeyboardTypeURL), + @"number-pad" : @(UIKeyboardTypeNumberPad), + @"phone-pad" : @(UIKeyboardTypePhonePad), + @"name-phone-pad" : @(UIKeyboardTypeNamePhonePad), + @"email-address" : @(UIKeyboardTypeEmailAddress), + @"decimal-pad" : @(UIKeyboardTypeDecimalPad), + @"twitter" : @(UIKeyboardTypeTwitter), + @"web-search" : @(UIKeyboardTypeWebSearch), + // Added for Android compatibility + @"numeric" : @(UIKeyboardTypeDecimalPad), + }]; temporaryMapping[@"ascii-capable-number-pad"] = @(UIKeyboardTypeASCIICapableNumberPad); mapping = temporaryMapping; }); @@ -372,78 +417,102 @@ RCT_ENUM_CONVERTER(UITextFieldViewMode, (@{ } #if !TARGET_OS_TV -RCT_MULTI_ENUM_CONVERTER(UIDataDetectorTypes, (@{ - @"phoneNumber": @(UIDataDetectorTypePhoneNumber), - @"link": @(UIDataDetectorTypeLink), - @"address": @(UIDataDetectorTypeAddress), - @"calendarEvent": @(UIDataDetectorTypeCalendarEvent), - @"none": @(UIDataDetectorTypeNone), - @"all": @(UIDataDetectorTypeAll), -}), UIDataDetectorTypePhoneNumber, unsignedLongLongValue) +RCT_MULTI_ENUM_CONVERTER( + UIDataDetectorTypes, + (@{ + @"phoneNumber" : @(UIDataDetectorTypePhoneNumber), + @"link" : @(UIDataDetectorTypeLink), + @"address" : @(UIDataDetectorTypeAddress), + @"calendarEvent" : @(UIDataDetectorTypeCalendarEvent), + @"none" : @(UIDataDetectorTypeNone), + @"all" : @(UIDataDetectorTypeAll), + }), + UIDataDetectorTypePhoneNumber, + unsignedLongLongValue) #if WEBKIT_IOS_10_APIS_AVAILABLE -RCT_MULTI_ENUM_CONVERTER(WKDataDetectorTypes, (@{ - @"phoneNumber": @(WKDataDetectorTypePhoneNumber), - @"link": @(WKDataDetectorTypeLink), - @"address": @(WKDataDetectorTypeAddress), - @"calendarEvent": @(WKDataDetectorTypeCalendarEvent), - @"trackingNumber": @(WKDataDetectorTypeTrackingNumber), - @"flightNumber": @(WKDataDetectorTypeFlightNumber), - @"lookupSuggestion": @(WKDataDetectorTypeLookupSuggestion), - @"none": @(WKDataDetectorTypeNone), - @"all": @(WKDataDetectorTypeAll), - }), WKDataDetectorTypePhoneNumber, unsignedLongLongValue) - #endif // WEBKIT_IOS_10_APIS_AVAILABLE +RCT_MULTI_ENUM_CONVERTER( + WKDataDetectorTypes, + (@{ + @"phoneNumber" : @(WKDataDetectorTypePhoneNumber), + @"link" : @(WKDataDetectorTypeLink), + @"address" : @(WKDataDetectorTypeAddress), + @"calendarEvent" : @(WKDataDetectorTypeCalendarEvent), + @"trackingNumber" : @(WKDataDetectorTypeTrackingNumber), + @"flightNumber" : @(WKDataDetectorTypeFlightNumber), + @"lookupSuggestion" : @(WKDataDetectorTypeLookupSuggestion), + @"none" : @(WKDataDetectorTypeNone), + @"all" : @(WKDataDetectorTypeAll), + }), + WKDataDetectorTypePhoneNumber, + unsignedLongLongValue) +#endif // WEBKIT_IOS_10_APIS_AVAILABLE - #endif // !TARGET_OS_TV +#endif // !TARGET_OS_TV -RCT_ENUM_CONVERTER(UIKeyboardAppearance, (@{ - @"default": @(UIKeyboardAppearanceDefault), - @"light": @(UIKeyboardAppearanceLight), - @"dark": @(UIKeyboardAppearanceDark), -}), UIKeyboardAppearanceDefault, integerValue) +RCT_ENUM_CONVERTER( + UIKeyboardAppearance, + (@{ + @"default" : @(UIKeyboardAppearanceDefault), + @"light" : @(UIKeyboardAppearanceLight), + @"dark" : @(UIKeyboardAppearanceDark), + }), + UIKeyboardAppearanceDefault, + integerValue) -RCT_ENUM_CONVERTER(UIReturnKeyType, (@{ - @"default": @(UIReturnKeyDefault), - @"go": @(UIReturnKeyGo), - @"google": @(UIReturnKeyGoogle), - @"join": @(UIReturnKeyJoin), - @"next": @(UIReturnKeyNext), - @"route": @(UIReturnKeyRoute), - @"search": @(UIReturnKeySearch), - @"send": @(UIReturnKeySend), - @"yahoo": @(UIReturnKeyYahoo), - @"done": @(UIReturnKeyDone), - @"emergency-call": @(UIReturnKeyEmergencyCall), -}), UIReturnKeyDefault, integerValue) +RCT_ENUM_CONVERTER( + UIReturnKeyType, + (@{ + @"default" : @(UIReturnKeyDefault), + @"go" : @(UIReturnKeyGo), + @"google" : @(UIReturnKeyGoogle), + @"join" : @(UIReturnKeyJoin), + @"next" : @(UIReturnKeyNext), + @"route" : @(UIReturnKeyRoute), + @"search" : @(UIReturnKeySearch), + @"send" : @(UIReturnKeySend), + @"yahoo" : @(UIReturnKeyYahoo), + @"done" : @(UIReturnKeyDone), + @"emergency-call" : @(UIReturnKeyEmergencyCall), + }), + UIReturnKeyDefault, + integerValue) -RCT_ENUM_CONVERTER(UIViewContentMode, (@{ - @"scale-to-fill": @(UIViewContentModeScaleToFill), - @"scale-aspect-fit": @(UIViewContentModeScaleAspectFit), - @"scale-aspect-fill": @(UIViewContentModeScaleAspectFill), - @"redraw": @(UIViewContentModeRedraw), - @"center": @(UIViewContentModeCenter), - @"top": @(UIViewContentModeTop), - @"bottom": @(UIViewContentModeBottom), - @"left": @(UIViewContentModeLeft), - @"right": @(UIViewContentModeRight), - @"top-left": @(UIViewContentModeTopLeft), - @"top-right": @(UIViewContentModeTopRight), - @"bottom-left": @(UIViewContentModeBottomLeft), - @"bottom-right": @(UIViewContentModeBottomRight), - // Cross-platform values - @"cover": @(UIViewContentModeScaleAspectFill), - @"contain": @(UIViewContentModeScaleAspectFit), - @"stretch": @(UIViewContentModeScaleToFill), -}), UIViewContentModeScaleAspectFill, integerValue) +RCT_ENUM_CONVERTER( + UIViewContentMode, + (@{ + @"scale-to-fill" : @(UIViewContentModeScaleToFill), + @"scale-aspect-fit" : @(UIViewContentModeScaleAspectFit), + @"scale-aspect-fill" : @(UIViewContentModeScaleAspectFill), + @"redraw" : @(UIViewContentModeRedraw), + @"center" : @(UIViewContentModeCenter), + @"top" : @(UIViewContentModeTop), + @"bottom" : @(UIViewContentModeBottom), + @"left" : @(UIViewContentModeLeft), + @"right" : @(UIViewContentModeRight), + @"top-left" : @(UIViewContentModeTopLeft), + @"top-right" : @(UIViewContentModeTopRight), + @"bottom-left" : @(UIViewContentModeBottomLeft), + @"bottom-right" : @(UIViewContentModeBottomRight), + // Cross-platform values + @"cover" : @(UIViewContentModeScaleAspectFill), + @"contain" : @(UIViewContentModeScaleAspectFit), + @"stretch" : @(UIViewContentModeScaleToFill), + }), + UIViewContentModeScaleAspectFill, + integerValue) #if !TARGET_OS_TV -RCT_ENUM_CONVERTER(UIBarStyle, (@{ - @"default": @(UIBarStyleDefault), - @"black": @(UIBarStyleBlack), - @"blackOpaque": @(UIBarStyleBlackOpaque), - @"blackTranslucent": @(UIBarStyleBlackTranslucent), -}), UIBarStyleDefault, integerValue) +RCT_ENUM_CONVERTER( + UIBarStyle, + (@{ + @"default" : @(UIBarStyleDefault), + @"black" : @(UIBarStyleBlack), + @"blackOpaque" : @(UIBarStyleBlackOpaque), + @"blackTranslucent" : @(UIBarStyleBlackTranslucent), + }), + UIBarStyleDefault, + integerValue) #endif static void convertCGStruct(const char *type, NSArray *fields, CGFloat *result, id json) @@ -451,7 +520,11 @@ static void convertCGStruct(const char *type, NSArray *fields, CGFloat *result, NSUInteger count = fields.count; if ([json isKindOfClass:[NSArray class]]) { if (RCT_DEBUG && [json count] != count) { - RCTLogError(@"Expected array with count %llu, but count is %llu: %@", (unsigned long long)count, (unsigned long long)[json count], json); + RCTLogError( + @"Expected array with count %llu, but count is %llu: %@", + (unsigned long long)count, + (unsigned long long)[json count], + json); } else { for (NSUInteger i = 0; i < count; i++) { result[i] = [RCTConvert CGFloat:RCTNilIfNull(json[i])]; @@ -470,41 +543,47 @@ static void convertCGStruct(const char *type, NSArray *fields, CGFloat *result, * This macro is used for creating converter functions for structs that consist * of a number of CGFloat properties, such as CGPoint, CGRect, etc. */ -#define RCT_CGSTRUCT_CONVERTER(type, values) \ -+ (type)type:(id)json \ -{ \ - static NSArray *fields; \ - static dispatch_once_t onceToken; \ - dispatch_once(&onceToken, ^{ \ - fields = values; \ - }); \ - type result; \ - convertCGStruct(#type, fields, (CGFloat *)&result, json); \ - return result; \ -} +#define RCT_CGSTRUCT_CONVERTER(type, values) \ + +(type)type : (id)json \ + { \ + static NSArray *fields; \ + static dispatch_once_t onceToken; \ + dispatch_once(&onceToken, ^{ \ + fields = values; \ + }); \ + type result; \ + convertCGStruct(#type, fields, (CGFloat *)&result, json); \ + return result; \ + } RCT_CUSTOM_CONVERTER(CGFloat, CGFloat, [self double:json]) -RCT_CGSTRUCT_CONVERTER(CGPoint, (@[@"x", @"y"])) -RCT_CGSTRUCT_CONVERTER(CGSize, (@[@"width", @"height"])) -RCT_CGSTRUCT_CONVERTER(CGRect, (@[@"x", @"y", @"width", @"height"])) -RCT_CGSTRUCT_CONVERTER(UIEdgeInsets, (@[@"top", @"left", @"bottom", @"right"])) +RCT_CGSTRUCT_CONVERTER(CGPoint, (@[ @"x", @"y" ])) +RCT_CGSTRUCT_CONVERTER(CGSize, (@[ @"width", @"height" ])) +RCT_CGSTRUCT_CONVERTER(CGRect, (@[ @"x", @"y", @"width", @"height" ])) +RCT_CGSTRUCT_CONVERTER(UIEdgeInsets, (@[ @"top", @"left", @"bottom", @"right" ])) -RCT_ENUM_CONVERTER(CGLineJoin, (@{ - @"miter": @(kCGLineJoinMiter), - @"round": @(kCGLineJoinRound), - @"bevel": @(kCGLineJoinBevel), -}), kCGLineJoinMiter, intValue) +RCT_ENUM_CONVERTER( + CGLineJoin, + (@{ + @"miter" : @(kCGLineJoinMiter), + @"round" : @(kCGLineJoinRound), + @"bevel" : @(kCGLineJoinBevel), + }), + kCGLineJoinMiter, + intValue) -RCT_ENUM_CONVERTER(CGLineCap, (@{ - @"butt": @(kCGLineCapButt), - @"round": @(kCGLineCapRound), - @"square": @(kCGLineCapSquare), -}), kCGLineCapButt, intValue) +RCT_ENUM_CONVERTER( + CGLineCap, + (@{ + @"butt" : @(kCGLineCapButt), + @"round" : @(kCGLineCapRound), + @"square" : @(kCGLineCapSquare), + }), + kCGLineCapButt, + intValue) -RCT_CGSTRUCT_CONVERTER(CGAffineTransform, (@[ - @"a", @"b", @"c", @"d", @"tx", @"ty" -])) +RCT_CGSTRUCT_CONVERTER(CGAffineTransform, (@[ @"a", @"b", @"c", @"d", @"tx", @"ty" ])) static NSString *const RCTFallback = @"fallback"; static NSString *const RCTFallbackARGB = @"fallback-argb"; @@ -521,126 +600,148 @@ static NSString *const RCTIndex = @"index"; * If the RCTIndex key is present then object returned from UIColor is an * NSArray and the object at index RCTIndex is to be used. */ -static NSDictionary* RCTSemanticColorsMap() +static NSDictionary *RCTSemanticColorsMap() { static NSDictionary *colorMap = nil; if (colorMap == nil) { colorMap = @{ // https://developer.apple.com/documentation/uikit/uicolor/ui_element_colors // Label Colors - @"labelColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFF000000) // fallback for iOS<=12: RGBA returned by this semantic color in light mode on iOS 13 + @"labelColor" : @{ + // iOS 13.0 + RCTFallbackARGB : + @(0xFF000000) // fallback for iOS<=12: RGBA returned by this semantic color in light mode on iOS 13 }, - @"secondaryLabelColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x993c3c43) + @"secondaryLabelColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x993c3c43) }, - @"tertiaryLabelColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x4c3c3c43) + @"tertiaryLabelColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x4c3c3c43) }, - @"quaternaryLabelColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x2d3c3c43) + @"quaternaryLabelColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x2d3c3c43) }, // Fill Colors - @"systemFillColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x33787880) + @"systemFillColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x33787880) }, - @"secondarySystemFillColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x28787880) + @"secondarySystemFillColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x28787880) }, - @"tertiarySystemFillColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x1e767680) + @"tertiarySystemFillColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x1e767680) }, - @"quaternarySystemFillColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x14747480) + @"quaternarySystemFillColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x14747480) }, // Text Colors - @"placeholderTextColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x4c3c3c43) + @"placeholderTextColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x4c3c3c43) }, // Standard Content Background Colors - @"systemBackgroundColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFffffff) + @"systemBackgroundColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFffffff) }, - @"secondarySystemBackgroundColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFf2f2f7) + @"secondarySystemBackgroundColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFf2f2f7) }, - @"tertiarySystemBackgroundColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFffffff) + @"tertiarySystemBackgroundColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFffffff) }, // Grouped Content Background Colors - @"systemGroupedBackgroundColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFf2f2f7) + @"systemGroupedBackgroundColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFf2f2f7) }, - @"secondarySystemGroupedBackgroundColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFffffff) + @"secondarySystemGroupedBackgroundColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFffffff) }, - @"tertiarySystemGroupedBackgroundColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFf2f2f7) + @"tertiarySystemGroupedBackgroundColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFf2f2f7) }, // Separator Colors - @"separatorColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0x493c3c43) + @"separatorColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0x493c3c43) }, - @"opaqueSeparatorColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFc6c6c8) + @"opaqueSeparatorColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFc6c6c8) }, // Link Color - @"linkColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFF007aff) + @"linkColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFF007aff) }, // Nonadaptable Colors - @"darkTextColor": @{}, - @"lightTextColor": @{}, + @"darkTextColor" : @{}, + @"lightTextColor" : @{}, // https://developer.apple.com/documentation/uikit/uicolor/standard_colors // Adaptable Colors - @"systemBlueColor": @{}, - @"systemBrownColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFa2845e) + @"systemBlueColor" : @{}, + @"systemBrownColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFa2845e) }, - @"systemGreenColor": @{}, - @"systemIndigoColor": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFF5856d6) + @"systemGreenColor" : @{}, + @"systemIndigoColor" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFF5856d6) }, - @"systemOrangeColor": @{}, - @"systemPinkColor": @{}, - @"systemPurpleColor": @{}, - @"systemRedColor": @{}, - @"systemTealColor": @{}, - @"systemYellowColor": @{}, + @"systemOrangeColor" : @{}, + @"systemPinkColor" : @{}, + @"systemPurpleColor" : @{}, + @"systemRedColor" : @{}, + @"systemTealColor" : @{}, + @"systemYellowColor" : @{}, // Adaptable Gray Colors - @"systemGrayColor": @{}, - @"systemGray2Color": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFaeaeb2) + @"systemGrayColor" : @{}, + @"systemGray2Color" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFaeaeb2) }, - @"systemGray3Color": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFc7c7cc) + @"systemGray3Color" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFc7c7cc) }, - @"systemGray4Color": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFd1d1d6) + @"systemGray4Color" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFd1d1d6) }, - @"systemGray5Color": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFe5e5ea) + @"systemGray5Color" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFe5e5ea) }, - @"systemGray6Color": @{ // iOS 13.0 - RCTFallbackARGB: @(0xFFf2f2f7) + @"systemGray6Color" : @{ + // iOS 13.0 + RCTFallbackARGB : @(0xFFf2f2f7) }, #if DEBUG // The follow exist for Unit Tests - @"unitTestFallbackColor": @{ - RCTFallback: @"gridColor" + @"unitTestFallbackColor" : @{RCTFallback : @"gridColor"}, + @"unitTestFallbackColorIOS" : @{RCTFallback : @"blueColor"}, + @"unitTestFallbackColorEven" : @{ + RCTSelector : @"unitTestFallbackColorEven", + RCTIndex : @0, + RCTFallback : @"controlAlternatingRowBackgroundColors" }, - @"unitTestFallbackColorIOS": @{ - RCTFallback: @"blueColor" - }, - @"unitTestFallbackColorEven": @{ - RCTSelector: @"unitTestFallbackColorEven", - RCTIndex: @0, - RCTFallback: @"controlAlternatingRowBackgroundColors" - }, - @"unitTestFallbackColorOdd": @{ - RCTSelector: @"unitTestFallbackColorOdd", - RCTIndex: @1, - RCTFallback: @"controlAlternatingRowBackgroundColors" + @"unitTestFallbackColorOdd" : @{ + RCTSelector : @"unitTestFallbackColorOdd", + RCTIndex : @1, + RCTFallback : @"controlAlternatingRowBackgroundColors" }, #endif }; @@ -671,7 +772,7 @@ static UIColor *RCTColorFromSemanticColorName(NSString *semanticColorName) semanticColorSelector = colorInfo[RCTFallback]; selector = NSSelectorFromString(semanticColorSelector); } - RCTAssert ([UIColor respondsToSelector:selector], @"RCTUIColor does not respond to a semantic color selector."); + RCTAssert([UIColor respondsToSelector:selector], @"RCTUIColor does not respond to a semantic color selector."); Class klass = [UIColor class]; IMP imp = [klass methodForSelector:selector]; id (*getSemanticColorObject)(id, SEL) = (void *)imp; @@ -696,9 +797,10 @@ static NSString *RCTSemanticColorNames() { NSMutableString *names = [[NSMutableString alloc] init]; NSDictionary *colorMap = RCTSemanticColorsMap(); - NSArray *allKeys = [[[colorMap allKeys] mutableCopy] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; + NSArray *allKeys = + [[[colorMap allKeys] mutableCopy] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; - for(id key in allKeys) { + for (id key in allKeys) { if ([names length]) { [names appendString:@", "]; } @@ -734,7 +836,9 @@ static NSString *RCTSemanticColorNames() NSString *semanticName = value; UIColor *color = RCTColorFromSemanticColorName(semanticName); if (color == nil) { - RCTLogConvertError(json, [@"a UIColor. Expected one of the following values: " stringByAppendingString:RCTSemanticColorNames()]); + RCTLogConvertError( + json, + [@"a UIColor. Expected one of the following values: " stringByAppendingString:RCTSemanticColorNames()]); } return color; } else if ([value isKindOfClass:[NSArray class]]) { @@ -744,10 +848,14 @@ static NSString *RCTSemanticColorNames() return color; } } - RCTLogConvertError(json, [@"a UIColor. None of the names in the array were one of the following values: " stringByAppendingString:RCTSemanticColorNames()]); + RCTLogConvertError( + json, + [@"a UIColor. None of the names in the array were one of the following values: " + stringByAppendingString:RCTSemanticColorNames()]); return nil; } - RCTLogConvertError(json, @"a UIColor. Expected either a single name or an array of names but got something else."); + RCTLogConvertError( + json, @"a UIColor. Expected either a single name or an array of names but got something else."); return nil; } else if ((value = [dictionary objectForKey:@"dynamic"])) { NSDictionary *appearances = value; @@ -758,9 +866,10 @@ static NSString *RCTSemanticColorNames() if (lightColor != nil && darkColor != nil) { #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 if (@available(iOS 13.0, *)) { - UIColor *color = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull collection) { - return collection.userInterfaceStyle == UIUserInterfaceStyleDark ? darkColor : lightColor; - }]; + UIColor *color = + [UIColor colorWithDynamicProvider:^UIColor *_Nonnull(UITraitCollection *_Nonnull collection) { + return collection.userInterfaceStyle == UIUserInterfaceStyleDark ? darkColor : lightColor; + }]; return color; } else { #endif @@ -792,13 +901,13 @@ static NSString *RCTSemanticColorNames() if (!json) { return YGValueUndefined; } else if ([json isKindOfClass:[NSNumber class]]) { - return (YGValue) { [json floatValue], YGUnitPoint }; + return (YGValue){[json floatValue], YGUnitPoint}; } else if ([json isKindOfClass:[NSString class]]) { - NSString *s = (NSString *) json; + NSString *s = (NSString *)json; if ([s isEqualToString:@"auto"]) { - return (YGValue) { YGUndefined, YGUnitAuto }; + return (YGValue){YGUndefined, YGUnitAuto}; } else if ([s hasSuffix:@"%"]) { - return (YGValue) { [[s substringToIndex:s.length] floatValue], YGUnitPercent }; + return (YGValue){[[s substringToIndex:s.length] floatValue], YGUnitPercent}; } else { RCTLogConvertError(json, @"a YGValue. Did you forget the % or pt suffix?"); } @@ -844,7 +953,11 @@ RCT_ARRAY_CONVERTER(UIColor) #if RCT_DEBUG #define RCT_JSON_ARRAY_CONVERTER_NAMED(type, name) RCT_ARRAY_CONVERTER_NAMED(type, name) #else -#define RCT_JSON_ARRAY_CONVERTER_NAMED(type, name) + (NSArray *)name##Array:(id)json { return json; } +#define RCT_JSON_ARRAY_CONVERTER_NAMED(type, name) \ + +(NSArray *)name##Array : (id)json \ + { \ + return json; \ + } #endif #define RCT_JSON_ARRAY_CONVERTER(type) RCT_JSON_ARRAY_CONVERTER_NAMED(type, type) @@ -916,81 +1029,111 @@ static id RCTConvertPropertyListValue(id json) return RCTConvertPropertyListValue(json); } -RCT_ENUM_CONVERTER(css_backface_visibility_t, (@{ - @"hidden": @NO, - @"visible": @YES -}), YES, boolValue) +RCT_ENUM_CONVERTER(css_backface_visibility_t, (@{@"hidden" : @NO, @"visible" : @YES}), YES, boolValue) -RCT_ENUM_CONVERTER(YGOverflow, (@{ - @"hidden": @(YGOverflowHidden), - @"visible": @(YGOverflowVisible), - @"scroll": @(YGOverflowScroll), -}), YGOverflowVisible, intValue) +RCT_ENUM_CONVERTER( + YGOverflow, + (@{ + @"hidden" : @(YGOverflowHidden), + @"visible" : @(YGOverflowVisible), + @"scroll" : @(YGOverflowScroll), + }), + YGOverflowVisible, + intValue) -RCT_ENUM_CONVERTER(YGDisplay, (@{ - @"flex": @(YGDisplayFlex), - @"none": @(YGDisplayNone), -}), YGDisplayFlex, intValue) +RCT_ENUM_CONVERTER( + YGDisplay, + (@{ + @"flex" : @(YGDisplayFlex), + @"none" : @(YGDisplayNone), + }), + YGDisplayFlex, + intValue) -RCT_ENUM_CONVERTER(YGFlexDirection, (@{ - @"row": @(YGFlexDirectionRow), - @"row-reverse": @(YGFlexDirectionRowReverse), - @"column": @(YGFlexDirectionColumn), - @"column-reverse": @(YGFlexDirectionColumnReverse) -}), YGFlexDirectionColumn, intValue) +RCT_ENUM_CONVERTER( + YGFlexDirection, + (@{ + @"row" : @(YGFlexDirectionRow), + @"row-reverse" : @(YGFlexDirectionRowReverse), + @"column" : @(YGFlexDirectionColumn), + @"column-reverse" : @(YGFlexDirectionColumnReverse) + }), + YGFlexDirectionColumn, + intValue) -RCT_ENUM_CONVERTER(YGJustify, (@{ - @"flex-start": @(YGJustifyFlexStart), - @"flex-end": @(YGJustifyFlexEnd), - @"center": @(YGJustifyCenter), - @"space-between": @(YGJustifySpaceBetween), - @"space-around": @(YGJustifySpaceAround), - @"space-evenly": @(YGJustifySpaceEvenly) -}), YGJustifyFlexStart, intValue) +RCT_ENUM_CONVERTER( + YGJustify, + (@{ + @"flex-start" : @(YGJustifyFlexStart), + @"flex-end" : @(YGJustifyFlexEnd), + @"center" : @(YGJustifyCenter), + @"space-between" : @(YGJustifySpaceBetween), + @"space-around" : @(YGJustifySpaceAround), + @"space-evenly" : @(YGJustifySpaceEvenly) + }), + YGJustifyFlexStart, + intValue) -RCT_ENUM_CONVERTER(YGAlign, (@{ - @"flex-start": @(YGAlignFlexStart), - @"flex-end": @(YGAlignFlexEnd), - @"center": @(YGAlignCenter), - @"auto": @(YGAlignAuto), - @"stretch": @(YGAlignStretch), - @"baseline": @(YGAlignBaseline), - @"space-between": @(YGAlignSpaceBetween), - @"space-around": @(YGAlignSpaceAround) -}), YGAlignFlexStart, intValue) +RCT_ENUM_CONVERTER( + YGAlign, + (@{ + @"flex-start" : @(YGAlignFlexStart), + @"flex-end" : @(YGAlignFlexEnd), + @"center" : @(YGAlignCenter), + @"auto" : @(YGAlignAuto), + @"stretch" : @(YGAlignStretch), + @"baseline" : @(YGAlignBaseline), + @"space-between" : @(YGAlignSpaceBetween), + @"space-around" : @(YGAlignSpaceAround) + }), + YGAlignFlexStart, + intValue) -RCT_ENUM_CONVERTER(YGDirection, (@{ - @"inherit": @(YGDirectionInherit), - @"ltr": @(YGDirectionLTR), - @"rtl": @(YGDirectionRTL), -}), YGDirectionInherit, intValue) +RCT_ENUM_CONVERTER( + YGDirection, + (@{ + @"inherit" : @(YGDirectionInherit), + @"ltr" : @(YGDirectionLTR), + @"rtl" : @(YGDirectionRTL), + }), + YGDirectionInherit, + intValue) -RCT_ENUM_CONVERTER(YGPositionType, (@{ - @"absolute": @(YGPositionTypeAbsolute), - @"relative": @(YGPositionTypeRelative) -}), YGPositionTypeRelative, intValue) +RCT_ENUM_CONVERTER( + YGPositionType, + (@{@"absolute" : @(YGPositionTypeAbsolute), @"relative" : @(YGPositionTypeRelative)}), + YGPositionTypeRelative, + intValue) -RCT_ENUM_CONVERTER(YGWrap, (@{ - @"wrap": @(YGWrapWrap), - @"nowrap": @(YGWrapNoWrap), - @"wrap-reverse": @(YGWrapWrapReverse) -}), YGWrapNoWrap, intValue) +RCT_ENUM_CONVERTER( + YGWrap, + (@{@"wrap" : @(YGWrapWrap), @"nowrap" : @(YGWrapNoWrap), @"wrap-reverse" : @(YGWrapWrapReverse)}), + YGWrapNoWrap, + intValue) -RCT_ENUM_CONVERTER(RCTPointerEvents, (@{ - @"none": @(RCTPointerEventsNone), - @"box-only": @(RCTPointerEventsBoxOnly), - @"box-none": @(RCTPointerEventsBoxNone), - @"auto": @(RCTPointerEventsUnspecified) -}), RCTPointerEventsUnspecified, integerValue) +RCT_ENUM_CONVERTER( + RCTPointerEvents, + (@{ + @"none" : @(RCTPointerEventsNone), + @"box-only" : @(RCTPointerEventsBoxOnly), + @"box-none" : @(RCTPointerEventsBoxNone), + @"auto" : @(RCTPointerEventsUnspecified) + }), + RCTPointerEventsUnspecified, + integerValue) -RCT_ENUM_CONVERTER(RCTAnimationType, (@{ - @"spring": @(RCTAnimationTypeSpring), - @"linear": @(RCTAnimationTypeLinear), - @"easeIn": @(RCTAnimationTypeEaseIn), - @"easeOut": @(RCTAnimationTypeEaseOut), - @"easeInEaseOut": @(RCTAnimationTypeEaseInEaseOut), - @"keyboard": @(RCTAnimationTypeKeyboard), -}), RCTAnimationTypeEaseInEaseOut, integerValue) +RCT_ENUM_CONVERTER( + RCTAnimationType, + (@{ + @"spring" : @(RCTAnimationTypeSpring), + @"linear" : @(RCTAnimationTypeLinear), + @"easeIn" : @(RCTAnimationTypeEaseIn), + @"easeOut" : @(RCTAnimationTypeEaseOut), + @"easeInEaseOut" : @(RCTAnimationTypeEaseInEaseOut), + @"keyboard" : @(RCTAnimationTypeKeyboard), + }), + RCTAnimationTypeEaseInEaseOut, + integerValue) @end @@ -1059,17 +1202,15 @@ RCT_ENUM_CONVERTER(RCTAnimationType, (@{ } if (scale) { - image = [UIImage imageWithCGImage:image.CGImage - scale:scale - orientation:image.imageOrientation]; + image = [UIImage imageWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; } - if (!CGSizeEqualToSize(imageSource.size, CGSizeZero) && - !CGSizeEqualToSize(imageSource.size, image.size)) { - RCTLogError(@"Image source %@ size %@ does not match loaded image size %@.", - URL.path.lastPathComponent, - NSStringFromCGSize(imageSource.size), - NSStringFromCGSize(image.size)); + if (!CGSizeEqualToSize(imageSource.size, CGSizeZero) && !CGSizeEqualToSize(imageSource.size, image.size)) { + RCTLogError( + @"Image source %@ size %@ does not match loaded image size %@.", + URL.path.lastPathComponent, + NSStringFromCGSize(imageSource.size), + NSStringFromCGSize(image.size)); } return image; diff --git a/React/Base/RCTDefines.h b/React/Base/RCTDefines.h index d1bbf9df01b..031864730a8 100644 --- a/React/Base/RCTDefines.h +++ b/React/Base/RCTDefines.h @@ -6,7 +6,7 @@ */ #if __OBJC__ -# import +#import #endif /** @@ -87,8 +87,8 @@ #define RCT_METRO_PORT 8081 #else // test if RCT_METRO_PORT is empty -#define RCT_METRO_PORT_DO_EXPAND(VAL) VAL ## 1 -#define RCT_METRO_PORT_EXPAND(VAL) RCT_METRO_PORT_DO_EXPAND(VAL) +#define RCT_METRO_PORT_DO_EXPAND(VAL) VAL##1 +#define RCT_METRO_PORT_EXPAND(VAL) RCT_METRO_PORT_DO_EXPAND(VAL) #if !defined(RCT_METRO_PORT) || (RCT_METRO_PORT_EXPAND(RCT_METRO_PORT) == 1) // Only here if RCT_METRO_PORT is not defined // OR RCT_METRO_PORT is the empty string @@ -116,12 +116,12 @@ * Concat two literals. Supports macro expansions, * e.g. RCT_CONCAT(foo, __FILE__). */ -#define RCT_CONCAT2(A, B) A ## B +#define RCT_CONCAT2(A, B) A##B #define RCT_CONCAT(A, B) RCT_CONCAT2(A, B) /** - * This attribute is used for static analysis. - */ + * This attribute is used for static analysis. + */ #if !defined RCT_DYNAMIC #if __has_attribute(objc_dynamic) #define RCT_DYNAMIC __attribute__((objc_dynamic)) @@ -133,13 +133,15 @@ /** * Throw an assertion for unimplemented methods. */ -#define RCT_NOT_IMPLEMENTED(method) \ -_Pragma("clang diagnostic push") \ -_Pragma("clang diagnostic ignored \"-Wmissing-method-return-type\"") \ -_Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \ -RCT_EXTERN NSException *_RCTNotImplementedException(SEL, Class); \ -method NS_UNAVAILABLE { @throw _RCTNotImplementedException(_cmd, [self class]); } \ -_Pragma("clang diagnostic pop") +#define RCT_NOT_IMPLEMENTED(method) \ + _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wmissing-method-return-type\"") \ + _Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \ + RCT_EXTERN NSException *_RCTNotImplementedException(SEL, Class); \ + method NS_UNAVAILABLE \ + { \ + @throw _RCTNotImplementedException(_cmd, [self class]); \ + } \ + _Pragma("clang diagnostic pop") /** * Check if WebKit iOS 10.0 APIs are available. diff --git a/React/Base/RCTDisplayLink.h b/React/Base/RCTDisplayLink.h index 4b54c2aa080..1e79c0baeda 100644 --- a/React/Base/RCTDisplayLink.h +++ b/React/Base/RCTDisplayLink.h @@ -14,8 +14,7 @@ - (instancetype)init; - (void)invalidate; -- (void)registerModuleForFrameUpdates:(id)module - withModuleData:(RCTModuleData *)moduleData; +- (void)registerModuleForFrameUpdates:(id)module withModuleData:(RCTModuleData *)moduleData; - (void)addToRunLoop:(NSRunLoop *)runLoop; @end diff --git a/React/Base/RCTDisplayLink.m b/React/Base/RCTDisplayLink.m index ddee18703d2..bcc7eab9715 100644 --- a/React/Base/RCTDisplayLink.m +++ b/React/Base/RCTDisplayLink.m @@ -17,11 +17,9 @@ #import "RCTProfile.h" #define RCTAssertRunLoop() \ - RCTAssert(_runLoop == [NSRunLoop currentRunLoop], \ - @"This method must be called on the CADisplayLink run loop") + RCTAssert(_runLoop == [NSRunLoop currentRunLoop], @"This method must be called on the CADisplayLink run loop") -@implementation RCTDisplayLink -{ +@implementation RCTDisplayLink { CADisplayLink *_jsDisplayLink; NSMutableSet *_frameUpdateObservers; NSRunLoop *_runLoop; @@ -37,8 +35,7 @@ return self; } -- (void)registerModuleForFrameUpdates:(id)module - withModuleData:(RCTModuleData *)moduleData +- (void)registerModuleForFrameUpdates:(id)module withModuleData:(RCTModuleData *)moduleData { if (![moduleData.moduleClass conformsToProtocol:@protocol(RCTFrameUpdateObserver)] || [_frameUpdateObservers containsObject:moduleData]) { @@ -97,8 +94,7 @@ [_jsDisplayLink invalidate]; } -- (void)dispatchBlock:(dispatch_block_t)block - queue:(dispatch_queue_t)queue +- (void)dispatchBlock:(dispatch_block_t)block queue:(dispatch_queue_t)queue { if (queue == RCTJSThread) { block(); @@ -119,10 +115,12 @@ if (!observer.paused) { if (moduleData.methodQueue) { RCTProfileBeginFlowEvent(); - [self dispatchBlock:^{ - RCTProfileEndFlowEvent(); - [observer didUpdateFrame:frameUpdate]; - } queue:moduleData.methodQueue]; + [self + dispatchBlock:^{ + RCTProfileEndFlowEvent(); + [observer didUpdateFrame:frameUpdate]; + } + queue:moduleData.methodQueue]; } else { [observer didUpdateFrame:frameUpdate]; } diff --git a/React/Base/RCTErrorInfo.h b/React/Base/RCTErrorInfo.h index 00bf2bdd190..a5d74d8e457 100644 --- a/React/Base/RCTErrorInfo.h +++ b/React/Base/RCTErrorInfo.h @@ -16,8 +16,6 @@ @property (nonatomic, copy, readonly) NSString *errorMessage; @property (nonatomic, copy, readonly) NSArray *stack; - -- (instancetype)initWithErrorMessage:(NSString *)errorMessage - stack:(NSArray *)stack; +- (instancetype)initWithErrorMessage:(NSString *)errorMessage stack:(NSArray *)stack; @end diff --git a/React/Base/RCTErrorInfo.m b/React/Base/RCTErrorInfo.m index 434ebad5406..ac492b00ed4 100644 --- a/React/Base/RCTErrorInfo.m +++ b/React/Base/RCTErrorInfo.m @@ -11,8 +11,8 @@ @implementation RCTErrorInfo -- (instancetype)initWithErrorMessage:(NSString *)errorMessage - stack:(NSArray *)stack { +- (instancetype)initWithErrorMessage:(NSString *)errorMessage stack:(NSArray *)stack +{ self = [super init]; if (self) { _errorMessage = [errorMessage copy]; diff --git a/React/Base/RCTEventDispatcher.h b/React/Base/RCTEventDispatcher.h index dd3bc6e61d5..e3648566a7c 100644 --- a/React/Base/RCTEventDispatcher.h +++ b/React/Base/RCTEventDispatcher.h @@ -9,8 +9,7 @@ #import -typedef NS_ENUM(NSInteger, RCTTextEventType) -{ +typedef NS_ENUM(NSInteger, RCTTextEventType) { RCTTextEventTypeFocus, RCTTextEventTypeBlur, RCTTextEventTypeChange, @@ -70,7 +69,6 @@ RCT_EXTERN NSString *RCTNormalizeInputEventName(NSString *eventName); @end - /** * This class wraps the -[RCTBridge enqueueJSCall:args:] method, and * provides some convenience methods for generating event calls. @@ -80,14 +78,12 @@ RCT_EXTERN NSString *RCTNormalizeInputEventName(NSString *eventName); /** * Deprecated, do not use. */ -- (void)sendAppEventWithName:(NSString *)name body:(id)body -__deprecated_msg("Subclass RCTEventEmitter instead"); +- (void)sendAppEventWithName:(NSString *)name body:(id)body __deprecated_msg("Subclass RCTEventEmitter instead"); /** * Deprecated, do not use. */ -- (void)sendDeviceEventWithName:(NSString *)name body:(id)body -__deprecated_msg("Subclass RCTEventEmitter instead"); +- (void)sendDeviceEventWithName:(NSString *)name body:(id)body __deprecated_msg("Subclass RCTEventEmitter instead"); /** * Send a text input/focus event. For internal use only. diff --git a/React/Base/RCTEventDispatcher.m b/React/Base/RCTEventDispatcher.m index bcf3a05f03e..3da2e268ed7 100644 --- a/React/Base/RCTEventDispatcher.m +++ b/React/Base/RCTEventDispatcher.m @@ -8,8 +8,8 @@ #import "RCTEventDispatcher.h" #import "RCTAssert.h" -#import "RCTBridge.h" #import "RCTBridge+Private.h" +#import "RCTBridge.h" #import "RCTComponentEvent.h" #import "RCTProfile.h" #import "RCTUtils.h" @@ -22,25 +22,21 @@ NSString *RCTNormalizeInputEventName(NSString *eventName) eventName = [eventName stringByReplacingCharactersInRange:(NSRange){0, 2} withString:@"top"]; } else if (![eventName hasPrefix:@"top"]) { eventName = [[@"top" stringByAppendingString:[eventName substringToIndex:1].uppercaseString] - stringByAppendingString:[eventName substringFromIndex:1]]; + stringByAppendingString:[eventName substringFromIndex:1]]; } return eventName; } static NSNumber *RCTGetEventID(NSNumber *viewTag, NSString *eventName, uint16_t coalescingKey) { - return @( - viewTag.intValue | - (((uint64_t)eventName.hash & 0xFFFF) << 32) | - (((uint64_t)coalescingKey) << 48) - ); + return @(viewTag.intValue | (((uint64_t)eventName.hash & 0xFFFF) << 32) | (((uint64_t)coalescingKey) << 48)); } static uint16_t RCTUniqueCoalescingKeyGenerator = 0; -@implementation RCTEventDispatcher -{ - // We need this lock to protect access to _events, _eventQueue and _eventsDispatchScheduled. It's filled in on main thread and consumed on js thread. +@implementation RCTEventDispatcher { + // We need this lock to protect access to _events, _eventQueue and _eventsDispatchScheduled. It's filled in on main + // thread and consumed on js thread. NSLock *_eventQueueLock; // We have this id -> event mapping so we coalesce effectively. NSMutableDictionary> *_events; @@ -70,7 +66,7 @@ RCT_EXPORT_MODULE() { [_bridge enqueueJSCall:@"RCTNativeAppEventEmitter" method:@"emit" - args:body ? @[name, body] : @[name] + args:body ? @[ name, body ] : @[ name ] completion:NULL]; } @@ -78,7 +74,7 @@ RCT_EXPORT_MODULE() { [_bridge enqueueJSCall:@"RCTDeviceEventEmitter" method:@"emit" - args:body ? @[name, body] : @[name] + args:body ? @[ name, body ] : @[ name ] completion:NULL]; } @@ -88,17 +84,10 @@ RCT_EXPORT_MODULE() key:(NSString *)key eventCount:(NSInteger)eventCount { - static NSString *events[] = { - @"focus", - @"blur", - @"change", - @"submitEditing", - @"endEditing", - @"keyPress" - }; + static NSString *events[] = {@"focus", @"blur", @"change", @"submitEditing", @"endEditing", @"keyPress"}; NSMutableDictionary *body = [[NSMutableDictionary alloc] initWithDictionary:@{ - @"eventCount": @(eventCount), + @"eventCount" : @(eventCount), }]; if (text) { @@ -122,9 +111,7 @@ RCT_EXPORT_MODULE() body[@"key"] = key; } - RCTComponentEvent *event = [[RCTComponentEvent alloc] initWithName:events[type] - viewTag:reactTag - body:body]; + RCTComponentEvent *event = [[RCTComponentEvent alloc] initWithName:events[type] viewTag:reactTag body:body]; [self sendEvent:event]; } @@ -152,7 +139,12 @@ RCT_EXPORT_MODULE() } else { id previousEvent = _events[eventID]; eventID = RCTGetEventID(event.viewTag, event.eventName, RCTUniqueCoalescingKeyGenerator++); - RCTAssert(previousEvent == nil, @"Got event %@ which cannot be coalesced, but has the same eventID %@ as the previous event %@", event, eventID, previousEvent); + RCTAssert( + previousEvent == nil, + @"Got event %@ which cannot be coalesced, but has the same eventID %@ as the previous event %@", + event, + eventID, + previousEvent); [_eventQueue addObject:eventID]; } @@ -170,9 +162,11 @@ RCT_EXPORT_MODULE() [_eventQueueLock unlock]; if (scheduleEventsDispatch) { - [_bridge dispatchBlock:^{ - [self flushEventsQueue]; - } queue:RCTJSThread]; + [_bridge + dispatchBlock:^{ + [self flushEventsQueue]; + } + queue:RCTJSThread]; } } diff --git a/React/Base/RCTFrameUpdate.m b/React/Base/RCTFrameUpdate.m index 0d4eced5f8a..7223c35db89 100644 --- a/React/Base/RCTFrameUpdate.m +++ b/React/Base/RCTFrameUpdate.m @@ -13,7 +13,7 @@ @implementation RCTFrameUpdate -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (instancetype)initWithDisplayLink:(CADisplayLink *)displayLink { diff --git a/React/Base/RCTImageSource.h b/React/Base/RCTImageSource.h index 5c328535210..928657c1146 100644 --- a/React/Base/RCTImageSource.h +++ b/React/Base/RCTImageSource.h @@ -23,9 +23,7 @@ * Pass a size of CGSizeZero if you do not know or wish to specify the image * size. Pass a scale of zero if you do not know or wish to specify the scale. */ -- (instancetype)initWithURLRequest:(NSURLRequest *)request - size:(CGSize)size - scale:(CGFloat)scale; +- (instancetype)initWithURLRequest:(NSURLRequest *)request size:(CGSize)size scale:(CGFloat)scale; /** * Create a copy of the image source with the specified size and scale. diff --git a/React/Base/RCTImageSource.m b/React/Base/RCTImageSource.m index abec6636bbc..19c6ed39b66 100644 --- a/React/Base/RCTImageSource.m +++ b/React/Base/RCTImageSource.m @@ -28,9 +28,7 @@ - (instancetype)imageSourceWithSize:(CGSize)size scale:(CGFloat)scale { - RCTImageSource *imageSource = [[RCTImageSource alloc] initWithURLRequest:_request - size:size - scale:scale]; + RCTImageSource *imageSource = [[RCTImageSource alloc] initWithURLRequest:_request size:size scale:scale]; imageSource.packagerAsset = _packagerAsset; return imageSource; } @@ -41,13 +39,16 @@ return NO; } return [_request isEqual:object.request] && _scale == object.scale && - (CGSizeEqualToSize(_size, object.size) || CGSizeEqualToSize(object.size, CGSizeZero)); + (CGSizeEqualToSize(_size, object.size) || CGSizeEqualToSize(object.size, CGSizeZero)); } - (NSString *)description { return [NSString stringWithFormat:@"", - self, _request.URL, NSStringFromCGSize(_size), _scale]; + self, + _request.URL, + NSStringFromCGSize(_size), + _scale]; } @end @@ -78,9 +79,7 @@ return nil; } - RCTImageSource *imageSource = [[RCTImageSource alloc] initWithURLRequest:request - size:size - scale:scale]; + RCTImageSource *imageSource = [[RCTImageSource alloc] initWithURLRequest:request size:size scale:scale]; imageSource.packagerAsset = packagerAsset; return imageSource; } diff --git a/React/Base/RCTJSInvokerModule.h b/React/Base/RCTJSInvokerModule.h index 9316b25b9f2..a0cbfbeacdc 100644 --- a/React/Base/RCTJSInvokerModule.h +++ b/React/Base/RCTJSInvokerModule.h @@ -6,9 +6,9 @@ */ /** -* This protocol should be adopted when a turbo module needs to directly call into Javascript. -* In bridge-less React Native, it is a replacement for [_bridge enqueueJSCall:]. -*/ + * This protocol should be adopted when a turbo module needs to directly call into Javascript. + * In bridge-less React Native, it is a replacement for [_bridge enqueueJSCall:]. + */ @protocol RCTJSInvokerModule @property (nonatomic, copy, nonnull) void (^invokeJS)(NSString *module, NSString *method, NSArray *args); diff --git a/React/Base/RCTJSStackFrame.h b/React/Base/RCTJSStackFrame.h index 73c6b834147..43592ec18d0 100644 --- a/React/Base/RCTJSStackFrame.h +++ b/React/Base/RCTJSStackFrame.h @@ -15,7 +15,11 @@ @property (nonatomic, readonly) NSInteger column; @property (nonatomic, readonly) NSInteger collapse; -- (instancetype)initWithMethodName:(NSString *)methodName file:(NSString *)file lineNumber:(NSInteger)lineNumber column:(NSInteger)column collapse:(NSInteger)collapse; +- (instancetype)initWithMethodName:(NSString *)methodName + file:(NSString *)file + lineNumber:(NSInteger)lineNumber + column:(NSInteger)column + collapse:(NSInteger)collapse; - (NSDictionary *)toDictionary; + (instancetype)stackFrameWithLine:(NSString *)line; diff --git a/React/Base/RCTJSStackFrame.m b/React/Base/RCTJSStackFrame.m index db177ddea08..2458626f349 100644 --- a/React/Base/RCTJSStackFrame.m +++ b/React/Base/RCTJSStackFrame.m @@ -11,37 +11,37 @@ #import "RCTUtils.h" /** -* The RegEx used to parse Error.stack. -* -* JavaScriptCore has the following format: -* -* Exception: Error: argh -* func1@/path/to/file.js:2:18 -* func2@/path/to/file.js:6:8 -* eval@[native code] -* global code@/path/to/file.js:13:5 -* -* Another supported format: -* -* Error: argh -* at func1 (/path/to/file.js:2:18) -* at func2 (/path/to/file.js:6:8) -* at eval (native) -* at global (/path/to/file.js:13:5) -*/ + * The RegEx used to parse Error.stack. + * + * JavaScriptCore has the following format: + * + * Exception: Error: argh + * func1@/path/to/file.js:2:18 + * func2@/path/to/file.js:6:8 + * eval@[native code] + * global code@/path/to/file.js:13:5 + * + * Another supported format: + * + * Error: argh + * at func1 (/path/to/file.js:2:18) + * at func2 (/path/to/file.js:6:8) + * at eval (native) + * at global (/path/to/file.js:13:5) + */ static NSRegularExpression *RCTJSStackFrameRegex() { static dispatch_once_t onceToken; static NSRegularExpression *_regex; dispatch_once(&onceToken, ^{ NSString *pattern = - @"\\s*(?:at)?\\s*" // Skip leading "at" and whitespace, noncapturing - @"(.+?)" // Capture the function name (group 1) - @"\\s*[@(]" // Skip whitespace, then @ or ( - @"(.*):" // Capture the file name (group 2), then colon - @"(\\d+):(\\d+)" // Line and column number (groups 3 and 4) - @"\\)?$" // Optional closing paren and EOL - ; + @"\\s*(?:at)?\\s*" // Skip leading "at" and whitespace, noncapturing + @"(.+?)" // Capture the function name (group 1) + @"\\s*[@(]" // Skip whitespace, then @ or ( + @"(.*):" // Capture the file name (group 2), then colon + @"(\\d+):(\\d+)" // Line and column number (groups 3 and 4) + @"\\)?$" // Optional closing paren and EOL + ; NSError *regexError; _regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:®exError]; if (regexError) { @@ -53,7 +53,11 @@ static NSRegularExpression *RCTJSStackFrameRegex() @implementation RCTJSStackFrame -- (instancetype)initWithMethodName:(NSString *)methodName file:(NSString *)file lineNumber:(NSInteger)lineNumber column:(NSInteger)column collapse:(NSInteger)collapse +- (instancetype)initWithMethodName:(NSString *)methodName + file:(NSString *)file + lineNumber:(NSInteger)lineNumber + column:(NSInteger)column + collapse:(NSInteger)collapse { if (self = [super init]) { _methodName = methodName; @@ -68,17 +72,19 @@ static NSRegularExpression *RCTJSStackFrameRegex() - (NSDictionary *)toDictionary { return @{ - @"methodName": RCTNullIfNil(self.methodName), - @"file": RCTNullIfNil(self.file), - @"lineNumber": @(self.lineNumber), - @"column": @(self.column), - @"collapse": @(self.collapse) + @"methodName" : RCTNullIfNil(self.methodName), + @"file" : RCTNullIfNil(self.file), + @"lineNumber" : @(self.lineNumber), + @"column" : @(self.column), + @"collapse" : @(self.collapse) }; } + (instancetype)stackFrameWithLine:(NSString *)line { - NSTextCheckingResult *match = [RCTJSStackFrameRegex() firstMatchInString:line options:0 range:NSMakeRange(0, line.length)]; + NSTextCheckingResult *match = [RCTJSStackFrameRegex() firstMatchInString:line + options:0 + range:NSMakeRange(0, line.length)]; if (!match) { return nil; } @@ -130,14 +136,15 @@ static NSRegularExpression *RCTJSStackFrameRegex() return stack; } -- (NSString *)description { +- (NSString *)description +{ return [NSString stringWithFormat:@"<%@: %p method name: %@; file name: %@; line: %ld; column: %ld>", - self.class, - self, - self.methodName, - self.file, - (long)self.lineNumber, - (long)self.column]; + self.class, + self, + self.methodName, + self.file, + (long)self.lineNumber, + (long)self.column]; } @end diff --git a/React/Base/RCTJavaScriptExecutor.h b/React/Base/RCTJavaScriptExecutor.h index 16202ddc47e..c42fb051792 100644 --- a/React/Base/RCTJavaScriptExecutor.h +++ b/React/Base/RCTJavaScriptExecutor.h @@ -51,9 +51,7 @@ typedef void (^RCTJavaScriptCallback)(id result, NSError *error); * and optional additional arguments on the JS thread and calls the * given callback with JSValue, containing the next queue, and JSContext. */ -- (void)invokeCallbackID:(NSNumber *)cbID - arguments:(NSArray *)args - callback:(RCTJavaScriptCallback)onComplete; +- (void)invokeCallbackID:(NSNumber *)cbID arguments:(NSArray *)args callback:(RCTJavaScriptCallback)onComplete; /** * Runs an application script, and notifies of the script load being complete via `onComplete`. @@ -63,8 +61,8 @@ typedef void (^RCTJavaScriptCallback)(id result, NSError *error); onComplete:(RCTJavaScriptCompleteBlock)onComplete; - (void)injectJSONText:(NSString *)script - asGlobalObjectNamed:(NSString *)objectName - callback:(RCTJavaScriptCompleteBlock)onComplete; + asGlobalObjectNamed:(NSString *)objectName + callback:(RCTJavaScriptCompleteBlock)onComplete; /** * Enqueue a block to run in the executors JS thread. Fallback to `dispatch_async` diff --git a/React/Base/RCTJavaScriptLoader.h b/React/Base/RCTJavaScriptLoader.h index a29594c7d71..9dbd7056e6c 100755 --- a/React/Base/RCTJavaScriptLoader.h +++ b/React/Base/RCTJavaScriptLoader.h @@ -11,21 +11,21 @@ extern NSString *const RCTJavaScriptLoaderErrorDomain; -NS_ENUM(NSInteger) { - RCTJavaScriptLoaderErrorNoScriptURL = 1, - RCTJavaScriptLoaderErrorFailedOpeningFile = 2, - RCTJavaScriptLoaderErrorFailedReadingFile = 3, - RCTJavaScriptLoaderErrorFailedStatingFile = 3, - RCTJavaScriptLoaderErrorURLLoadFailed = 3, - RCTJavaScriptLoaderErrorBCVersion = 4, - RCTJavaScriptLoaderErrorBCNotSupported = 4, +NS_ENUM(NSInteger){ + RCTJavaScriptLoaderErrorNoScriptURL = 1, + RCTJavaScriptLoaderErrorFailedOpeningFile = 2, + RCTJavaScriptLoaderErrorFailedReadingFile = 3, + RCTJavaScriptLoaderErrorFailedStatingFile = 3, + RCTJavaScriptLoaderErrorURLLoadFailed = 3, + RCTJavaScriptLoaderErrorBCVersion = 4, + RCTJavaScriptLoaderErrorBCNotSupported = 4, - RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously = 1000, + RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously = 1000, }; -NS_ENUM(NSInteger) { - RCTSourceFilesChangedCountNotBuiltByBundler = -2, - RCTSourceFilesChangedCountRebuiltFromScratch = -1, +NS_ENUM(NSInteger){ + RCTSourceFilesChangedCountNotBuiltByBundler = -2, + RCTSourceFilesChangedCountRebuiltFromScratch = -1, }; @interface RCTLoadingProgress : NSObject diff --git a/React/Base/RCTJavaScriptLoader.mm b/React/Base/RCTJavaScriptLoader.mm index c373b83a8b2..8c8e5fad02f 100755 --- a/React/Base/RCTJavaScriptLoader.mm +++ b/React/Base/RCTJavaScriptLoader.mm @@ -21,9 +21,8 @@ NSString *const RCTJavaScriptLoaderErrorDomain = @"RCTJavaScriptLoaderErrorDomai static const int32_t JSNoBytecodeFileFormatVersion = -1; -@interface RCTSource() -{ -@public +@interface RCTSource () { + @public NSURL *_url; NSData *_data; NSUInteger _length; @@ -64,9 +63,11 @@ static RCTSource *RCTSourceCreate(NSURL *url, NSData *data, int64_t length) NS_R @implementation RCTJavaScriptLoader -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) -+ (void)loadBundleAtURL:(NSURL *)scriptURL onProgress:(RCTSourceLoadProgressBlock)onProgress onComplete:(RCTSourceLoadBlock)onComplete ++ (void)loadBundleAtURL:(NSURL *)scriptURL + onProgress:(RCTSourceLoadProgressBlock)onProgress + onComplete:(RCTSourceLoadBlock)onComplete { int64_t sourceLength; NSError *error; @@ -79,9 +80,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) return; } - const BOOL isCannotLoadSyncError = - [error.domain isEqualToString:RCTJavaScriptLoaderErrorDomain] - && error.code == RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously; + const BOOL isCannotLoadSyncError = [error.domain isEqualToString:RCTJavaScriptLoaderErrorDomain] && + error.code == RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously; if (isCannotLoadSyncError) { attemptAsynchronousLoadOfBundleAtURL(scriptURL, onProgress, onComplete); @@ -101,12 +101,16 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) if (!scriptURL) { if (error) { - *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain - code:RCTJavaScriptLoaderErrorNoScriptURL - userInfo:@{NSLocalizedDescriptionKey: - [NSString stringWithFormat:@"No script URL provided. Make sure the packager is " - @"running or you have embedded a JS bundle in your application bundle.\n\n" - @"unsanitizedScriptURLString = %@", unsanitizedScriptURLString]}]; + *error = [NSError + errorWithDomain:RCTJavaScriptLoaderErrorDomain + code:RCTJavaScriptLoaderErrorNoScriptURL + userInfo:@{ + NSLocalizedDescriptionKey : [NSString + stringWithFormat:@"No script URL provided. Make sure the packager is " + @"running or you have embedded a JS bundle in your application bundle.\n\n" + @"unsanitizedScriptURLString = %@", + unsanitizedScriptURLString] + }]; } return nil; } @@ -116,9 +120,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) if (error) { *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain code:RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously - userInfo:@{NSLocalizedDescriptionKey: - [NSString stringWithFormat:@"Cannot load %@ URLs synchronously", - scriptURL.scheme]}]; + userInfo:@{ + NSLocalizedDescriptionKey : + [NSString stringWithFormat:@"Cannot load %@ URLs synchronously", scriptURL.scheme] + }]; } return nil; } @@ -130,10 +135,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) FILE *bundle = fopen(scriptURL.path.UTF8String, "r"); if (!bundle) { if (error) { - *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain - code:RCTJavaScriptLoaderErrorFailedOpeningFile - userInfo:@{NSLocalizedDescriptionKey: - [NSString stringWithFormat:@"Error opening bundle %@", scriptURL.path]}]; + *error = [NSError + errorWithDomain:RCTJavaScriptLoaderErrorDomain + code:RCTJavaScriptLoaderErrorFailedOpeningFile + userInfo:@{ + NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Error opening bundle %@", scriptURL.path] + }]; } return nil; } @@ -143,70 +150,70 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) fclose(bundle); if (readResult != 1) { if (error) { - *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain - code:RCTJavaScriptLoaderErrorFailedReadingFile - userInfo:@{NSLocalizedDescriptionKey: - [NSString stringWithFormat:@"Error reading bundle %@", scriptURL.path]}]; + *error = [NSError + errorWithDomain:RCTJavaScriptLoaderErrorDomain + code:RCTJavaScriptLoaderErrorFailedReadingFile + userInfo:@{ + NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Error reading bundle %@", scriptURL.path] + }]; } return nil; } facebook::react::ScriptTag tag = facebook::react::parseTypeFromHeader(header); switch (tag) { - case facebook::react::ScriptTag::RAMBundle: - break; + case facebook::react::ScriptTag::RAMBundle: + break; - case facebook::react::ScriptTag::String: { + case facebook::react::ScriptTag::String: { #if RCT_ENABLE_INSPECTOR - NSData *source = [NSData dataWithContentsOfFile:scriptURL.path - options:NSDataReadingMappedIfSafe - error:error]; - if (sourceLength && source != nil) { - *sourceLength = source.length; - } - return source; + NSData *source = [NSData dataWithContentsOfFile:scriptURL.path options:NSDataReadingMappedIfSafe error:error]; + if (sourceLength && source != nil) { + *sourceLength = source.length; + } + return source; #else - if (error) { - *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain - code:RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously - userInfo:@{NSLocalizedDescriptionKey: - @"Cannot load text/javascript files synchronously"}]; - } - return nil; + if (error) { + *error = + [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain + code:RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously + userInfo:@{NSLocalizedDescriptionKey : @"Cannot load text/javascript files synchronously"}]; + } + return nil; #endif - } - case facebook::react::ScriptTag::BCBundle: - if (runtimeBCVersion == JSNoBytecodeFileFormatVersion || runtimeBCVersion < 0) { - if (error) { - *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain - code:RCTJavaScriptLoaderErrorBCNotSupported - userInfo:@{NSLocalizedDescriptionKey: - @"Bytecode bundles are not supported by this runtime."}]; - } - return nil; } - else if ((uint32_t)runtimeBCVersion != header.version) { - if (error) { - NSString *errDesc = - [NSString stringWithFormat:@"BC Version Mismatch. Expect: %d, Actual: %u", - runtimeBCVersion, header.version]; + case facebook::react::ScriptTag::BCBundle: + if (runtimeBCVersion == JSNoBytecodeFileFormatVersion || runtimeBCVersion < 0) { + if (error) { + *error = [NSError + errorWithDomain:RCTJavaScriptLoaderErrorDomain + code:RCTJavaScriptLoaderErrorBCNotSupported + userInfo:@{NSLocalizedDescriptionKey : @"Bytecode bundles are not supported by this runtime."}]; + } + return nil; + } else if ((uint32_t)runtimeBCVersion != header.version) { + if (error) { + NSString *errDesc = [NSString + stringWithFormat:@"BC Version Mismatch. Expect: %d, Actual: %u", runtimeBCVersion, header.version]; - *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain - code:RCTJavaScriptLoaderErrorBCVersion - userInfo:@{NSLocalizedDescriptionKey: errDesc}]; + *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain + code:RCTJavaScriptLoaderErrorBCVersion + userInfo:@{NSLocalizedDescriptionKey : errDesc}]; + } + return nil; } - return nil; - } - break; + break; } struct stat statInfo; if (stat(scriptURL.path.UTF8String, &statInfo) != 0) { if (error) { - *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain - code:RCTJavaScriptLoaderErrorFailedStatingFile - userInfo:@{NSLocalizedDescriptionKey: - [NSString stringWithFormat:@"Error stating bundle %@", scriptURL.path]}]; + *error = [NSError + errorWithDomain:RCTJavaScriptLoaderErrorDomain + code:RCTJavaScriptLoaderErrorFailedStatingFile + userInfo:@{ + NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Error stating bundle %@", scriptURL.path] + }]; } return nil; } @@ -216,11 +223,15 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) return [NSData dataWithBytes:&header length:sizeof(header)]; } -static void parseHeaders(NSDictionary *headers, RCTSource *source) { +static void parseHeaders(NSDictionary *headers, RCTSource *source) +{ source->_filesChangedCount = [headers[@"X-Metro-Files-Changed-Count"] integerValue]; } -static void attemptAsynchronousLoadOfBundleAtURL(NSURL *scriptURL, RCTSourceLoadProgressBlock onProgress, RCTSourceLoadBlock onComplete) +static void attemptAsynchronousLoadOfBundleAtURL( + NSURL *scriptURL, + RCTSourceLoadProgressBlock onProgress, + RCTSourceLoadBlock onComplete) { scriptURL = sanitizeURL(scriptURL); @@ -228,85 +239,85 @@ static void attemptAsynchronousLoadOfBundleAtURL(NSURL *scriptURL, RCTSourceLoad // Reading in a large bundle can be slow. Dispatch to the background queue to do it. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSError *error = nil; - NSData *source = [NSData dataWithContentsOfFile:scriptURL.path - options:NSDataReadingMappedIfSafe - error:&error]; + NSData *source = [NSData dataWithContentsOfFile:scriptURL.path options:NSDataReadingMappedIfSafe error:&error]; onComplete(error, RCTSourceCreate(scriptURL, source, source.length)); }); return; } - RCTMultipartDataTask *task = [[RCTMultipartDataTask alloc] initWithURL:scriptURL partHandler:^(NSInteger statusCode, NSDictionary *headers, NSData *data, NSError *error, BOOL done) { - if (!done) { - if (onProgress) { - onProgress(progressEventFromData(data)); - } - return; - } + RCTMultipartDataTask *task = [[RCTMultipartDataTask alloc] initWithURL:scriptURL + partHandler:^(NSInteger statusCode, NSDictionary *headers, NSData *data, NSError *error, BOOL done) { + if (!done) { + if (onProgress) { + onProgress(progressEventFromData(data)); + } + return; + } - // Handle general request errors - if (error) { - if ([error.domain isEqualToString:NSURLErrorDomain]) { - error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain - code:RCTJavaScriptLoaderErrorURLLoadFailed - userInfo: - @{ - NSLocalizedDescriptionKey: - [@"Could not connect to development server.\n\n" - "Ensure the following:\n" - "- Node server is running and available on the same network - run 'npm start' from react-native root\n" - "- Node server URL is correctly set in AppDelegate\n" - "- WiFi is enabled and connected to the same network as the Node Server\n\n" - "URL: " stringByAppendingString:scriptURL.absoluteString], - NSLocalizedFailureReasonErrorKey: error.localizedDescription, - NSUnderlyingErrorKey: error, - }]; - } - onComplete(error, nil); - return; - } + // Handle general request errors + if (error) { + if ([error.domain isEqualToString:NSURLErrorDomain]) { + error = [NSError + errorWithDomain:RCTJavaScriptLoaderErrorDomain + code:RCTJavaScriptLoaderErrorURLLoadFailed + userInfo:@{ + NSLocalizedDescriptionKey : + [@"Could not connect to development server.\n\n" + "Ensure the following:\n" + "- Node server is running and available on the same network - run 'npm start' from react-native root\n" + "- Node server URL is correctly set in AppDelegate\n" + "- WiFi is enabled and connected to the same network as the Node Server\n\n" + "URL: " stringByAppendingString:scriptURL.absoluteString], + NSLocalizedFailureReasonErrorKey : error.localizedDescription, + NSUnderlyingErrorKey : error, + }]; + } + onComplete(error, nil); + return; + } - // For multipart responses packager sets X-Http-Status header in case HTTP status code - // is different from 200 OK - NSString *statusCodeHeader = headers[@"X-Http-Status"]; - if (statusCodeHeader) { - statusCode = [statusCodeHeader integerValue]; - } + // For multipart responses packager sets X-Http-Status header in case HTTP status code + // is different from 200 OK + NSString *statusCodeHeader = headers[@"X-Http-Status"]; + if (statusCodeHeader) { + statusCode = [statusCodeHeader integerValue]; + } - if (statusCode != 200) { - error = [NSError errorWithDomain:@"JSServer" + if (statusCode != 200) { + error = + [NSError errorWithDomain:@"JSServer" code:statusCode - userInfo:userInfoForRawResponse([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding])]; - onComplete(error, nil); - return; - } + userInfo:userInfoForRawResponse([[NSString alloc] initWithData:data + encoding:NSUTF8StringEncoding])]; + onComplete(error, nil); + return; + } - // Validate that the packager actually returned javascript. - NSString *contentType = headers[@"Content-Type"]; - NSString *mimeType = [[contentType componentsSeparatedByString:@";"] firstObject]; - if (![mimeType isEqualToString:@"application/javascript"] && - ![mimeType isEqualToString:@"text/javascript"]) { - NSString *description = [NSString stringWithFormat:@"Expected MIME-Type to be 'application/javascript' or 'text/javascript', but got '%@'.", mimeType]; - error = [NSError errorWithDomain:@"JSServer" - code:NSURLErrorCannotParseResponse - userInfo:@{ - NSLocalizedDescriptionKey: description, - @"headers": headers, - @"data": data - }]; - onComplete(error, nil); - return; - } + // Validate that the packager actually returned javascript. + NSString *contentType = headers[@"Content-Type"]; + NSString *mimeType = [[contentType componentsSeparatedByString:@";"] firstObject]; + if (![mimeType isEqualToString:@"application/javascript"] && ![mimeType isEqualToString:@"text/javascript"]) { + NSString *description = [NSString + stringWithFormat:@"Expected MIME-Type to be 'application/javascript' or 'text/javascript', but got '%@'.", + mimeType]; + error = [NSError + errorWithDomain:@"JSServer" + code:NSURLErrorCannotParseResponse + userInfo:@{NSLocalizedDescriptionKey : description, @"headers" : headers, @"data" : data}]; + onComplete(error, nil); + return; + } - RCTSource *source = RCTSourceCreate(scriptURL, data, data.length); - parseHeaders(headers, source); - onComplete(nil, source); - } progressHandler:^(NSDictionary *headers, NSNumber *loaded, NSNumber *total) { - // Only care about download progress events for the javascript bundle part. - if ([headers[@"Content-Type"] isEqualToString:@"application/javascript"]) { - onProgress(progressEventFromDownloadProgress(loaded, total)); - } - }]; + RCTSource *source = RCTSourceCreate(scriptURL, data, data.length); + parseHeaders(headers, source); + onComplete(nil, source); + } + progressHandler:^(NSDictionary *headers, NSNumber *loaded, NSNumber *total) { + // Only care about download progress events for the javascript bundle part. + if ([headers[@"Content-Type"] isEqualToString:@"application/javascript"]) { + onProgress(progressEventFromDownloadProgress(loaded, total)); + } + }]; [task startTask]; } @@ -346,21 +357,22 @@ static NSDictionary *userInfoForRawResponse(NSString *rawText) { NSDictionary *parsedResponse = RCTJSONParse(rawText, nil); if (![parsedResponse isKindOfClass:[NSDictionary class]]) { - return @{NSLocalizedDescriptionKey: rawText}; + return @{NSLocalizedDescriptionKey : rawText}; } NSArray *errors = parsedResponse[@"errors"]; if (![errors isKindOfClass:[NSArray class]]) { - return @{NSLocalizedDescriptionKey: rawText}; + return @{NSLocalizedDescriptionKey : rawText}; } NSMutableArray *fakeStack = [NSMutableArray new]; for (NSDictionary *err in errors) { - [fakeStack addObject: @{ - @"methodName": err[@"description"] ?: @"", - @"file": err[@"filename"] ?: @"", - @"lineNumber": err[@"lineNumber"] ?: @0 + [fakeStack addObject:@{ + @"methodName" : err[@"description"] ?: @"", + @"file" : err[@"filename"] ?: @"", + @"lineNumber" : err[@"lineNumber"] ?: @0 }]; } - return @{NSLocalizedDescriptionKey: parsedResponse[@"message"] ?: @"No message provided", @"stack": [fakeStack copy]}; + return + @{NSLocalizedDescriptionKey : parsedResponse[@"message"] ?: @"No message provided", @"stack" : [fakeStack copy]}; } @end diff --git a/React/Base/RCTKeyCommands.h b/React/Base/RCTKeyCommands.h index 572ee831bac..983348e9989 100644 --- a/React/Base/RCTKeyCommands.h +++ b/React/Base/RCTKeyCommands.h @@ -21,32 +21,28 @@ /** * Unregister a single-press keyboard command. */ -- (void)unregisterKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags; +- (void)unregisterKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags; /** * Check if a single-press command is registered. */ -- (BOOL)isKeyCommandRegisteredForInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags; +- (BOOL)isKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags; /** * Register a double-press keyboard command. */ - (void)registerDoublePressKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags - action:(void (^)(UIKeyCommand *command))block; + modifierFlags:(UIKeyModifierFlags)flags + action:(void (^)(UIKeyCommand *command))block; /** * Unregister a double-press keyboard command. */ -- (void)unregisterDoublePressKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags; +- (void)unregisterDoublePressKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags; /** * Check if a double-press command is registered. */ -- (BOOL)isDoublePressKeyCommandRegisteredForInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags; +- (BOOL)isDoublePressKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags; @end diff --git a/React/Base/RCTKeyCommands.m b/React/Base/RCTKeyCommands.m index c5c1ec33c01..d48ba935d22 100644 --- a/React/Base/RCTKeyCommands.m +++ b/React/Base/RCTKeyCommands.m @@ -23,8 +23,7 @@ @implementation RCTKeyCommand -- (instancetype)initWithKeyCommand:(UIKeyCommand *)keyCommand - block:(void (^)(UIKeyCommand *))block +- (instancetype)initWithKeyCommand:(UIKeyCommand *)keyCommand block:(void (^)(UIKeyCommand *))block { if ((self = [super init])) { _keyCommand = keyCommand; @@ -33,7 +32,7 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (id)copyWithZone:(__unused NSZone *)zone { @@ -50,8 +49,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) if (![object isKindOfClass:[RCTKeyCommand class]]) { return NO; } - return [self matchesInput:object.keyCommand.input - flags:object.keyCommand.modifierFlags]; + return [self matchesInput:object.keyCommand.input flags:object.keyCommand.modifierFlags]; } - (BOOL)matchesInput:(NSString *)input flags:(UIKeyModifierFlags)flags @@ -62,8 +60,11 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (NSString *)description { return [NSString stringWithFormat:@"<%@:%p input=\"%@\" flags=%lld hasBlock=%@>", - [self class], self, _keyCommand.input, (long long)_keyCommand.modifierFlags, - _block ? @"YES" : @"NO"]; + [self class], + self, + _keyCommand.input, + (long long)_keyCommand.modifierFlags, + _block ? @"YES" : @"NO"]; } @end @@ -84,12 +85,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) return view; } else if ([view isKindOfClass:[UIViewController class]]) { if ([(UIViewController *)view parentViewController]) { - firstResponder = [UIResponder RCT_getFirstResponder: [(UIViewController *)view parentViewController]]; + firstResponder = [UIResponder RCT_getFirstResponder:[(UIViewController *)view parentViewController]]; } - return firstResponder ? firstResponder : [UIResponder RCT_getFirstResponder: [(UIViewController *)view view]]; + return firstResponder ? firstResponder : [UIResponder RCT_getFirstResponder:[(UIViewController *)view view]]; } else if ([view isKindOfClass:[UIView class]]) { for (UIView *subview in [(UIView *)view subviews]) { - firstResponder = [UIResponder RCT_getFirstResponder: subview]; + firstResponder = [UIResponder RCT_getFirstResponder:subview]; if (firstResponder) { return firstResponder; } @@ -142,9 +143,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) if (firstPress) { for (RCTKeyCommand *command in [RCTKeyCommands sharedInstance].commands) { if ([command.keyCommand.input isEqualToString:key.input] && - command.keyCommand.modifierFlags == key.modifierFlags && - command.block) { - + command.keyCommand.modifierFlags == key.modifierFlags && command.block) { firstPress = NO; lastCommand = CACurrentMediaTime(); lastInput = key.input; @@ -155,15 +154,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) } else { // Second keyevent within 0.2 second, // with the same key as the first one. - if (CACurrentMediaTime() - lastCommand < 0.2 && - lastInput == key.input && - lastModifierFlags == key.modifierFlags) { - + if (CACurrentMediaTime() - lastCommand < 0.2 && lastInput == key.input && lastModifierFlags == key.modifierFlags) { for (RCTKeyCommand *command in [RCTKeyCommands sharedInstance].commands) { if ([command.keyCommand.input isEqualToString:key.input] && - command.keyCommand.modifierFlags == key.modifierFlags && - command.block) { - + command.keyCommand.modifierFlags == key.modifierFlags && command.block) { // NOTE: throttle the key handler because on iOS 9 the handleKeyCommand: // method gets called repeatedly if the command key is held down. if (CACurrentMediaTime() - lastDoubleCommand > 0.5) { @@ -189,9 +183,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) + (void)initialize { // swizzle UIResponder - RCTSwapInstanceMethods([UIResponder class], - @selector(keyCommands), - @selector(RCT_keyCommands)); + RCTSwapInstanceMethods([UIResponder class], @selector(keyCommands), @selector(RCT_keyCommands)); } + (instancetype)sharedInstance @@ -228,8 +220,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) [_commands addObject:keyCommand]; } -- (void)unregisterKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags +- (void)unregisterKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { RCTAssertMainQueue(); @@ -241,8 +232,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) } } -- (BOOL)isKeyCommandRegisteredForInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags +- (BOOL)isKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { RCTAssertMainQueue(); @@ -255,8 +245,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) } - (void)registerDoublePressKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags - action:(void (^)(UIKeyCommand *))block + modifierFlags:(UIKeyModifierFlags)flags + action:(void (^)(UIKeyCommand *))block { RCTAssertMainQueue(); @@ -269,8 +259,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) [_commands addObject:keyCommand]; } -- (void)unregisterDoublePressKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags +- (void)unregisterDoublePressKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { RCTAssertMainQueue(); @@ -282,8 +271,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) } } -- (BOOL)isDoublePressKeyCommandRegisteredForInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags +- (BOOL)isDoublePressKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { RCTAssertMainQueue(); @@ -308,26 +296,30 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (void)registerKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags - action:(void (^)(UIKeyCommand *))block {} + action:(void (^)(UIKeyCommand *))block +{ +} -- (void)unregisterKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags {} +- (void)unregisterKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags +{ +} -- (BOOL)isKeyCommandRegisteredForInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags +- (BOOL)isKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { return NO; } - (void)registerDoublePressKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags - action:(void (^)(UIKeyCommand *))block {} + modifierFlags:(UIKeyModifierFlags)flags + action:(void (^)(UIKeyCommand *))block +{ +} -- (void)unregisterDoublePressKeyCommandWithInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags {} +- (void)unregisterDoublePressKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags +{ +} -- (BOOL)isDoublePressKeyCommandRegisteredForInput:(NSString *)input - modifierFlags:(UIKeyModifierFlags)flags +- (BOOL)isDoublePressKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { return NO; } diff --git a/React/Base/RCTLog.h b/React/Base/RCTLog.h index be091309d1d..0d79797f055 100644 --- a/React/Base/RCTLog.h +++ b/React/Base/RCTLog.h @@ -48,10 +48,7 @@ typedef NS_ENUM(NSInteger, RCTLogLevel) { /** * An enum representing the source of a log message. */ -typedef NS_ENUM(NSInteger, RCTLogSource) { - RCTLogSourceNative = 1, - RCTLogSourceJavaScript = 2 -}; +typedef NS_ENUM(NSInteger, RCTLogSource) { RCTLogSourceNative = 1, RCTLogSourceJavaScript = 2 }; /** * A block signature to be used for custom logging functions. In most cases you @@ -59,24 +56,18 @@ typedef NS_ENUM(NSInteger, RCTLogSource) { * generate a string. */ typedef void (^RCTLogFunction)( - RCTLogLevel level, - RCTLogSource source, - NSString *fileName, - NSNumber *lineNumber, - NSString *message -); + RCTLogLevel level, + RCTLogSource source, + NSString *fileName, + NSNumber *lineNumber, + NSString *message); /** * A method to generate a string from a collection of log data. To omit any * particular data from the log, just pass nil or zero for the argument. */ -RCT_EXTERN NSString *RCTFormatLog( - NSDate *timestamp, - RCTLogLevel level, - NSString *fileName, - NSNumber *lineNumber, - NSString *message -); +RCT_EXTERN NSString * +RCTFormatLog(NSDate *timestamp, RCTLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message); /** * A method to generate a string RCTLogLevel @@ -136,8 +127,10 @@ RCT_EXTERN void RCTPerformBlockWithLogPrefix(void (^block)(void), NSString *pref #if RCTLOG_ENABLED #define _RCTLog(lvl, ...) _RCTLogNativeInternal(lvl, __FILE__, __LINE__, __VA_ARGS__) #else -#define _RCTLog(lvl, ...) do { } while (0) +#define _RCTLog(lvl, ...) \ + do { \ + } while (0) #endif -RCT_EXTERN void _RCTLogNativeInternal(RCTLogLevel, const char *, int, NSString *, ...) NS_FORMAT_FUNCTION(4,5); +RCT_EXTERN void _RCTLogNativeInternal(RCTLogLevel, const char *, int, NSString *, ...) NS_FORMAT_FUNCTION(4, 5); RCT_EXTERN void _RCTLogJavaScriptInternal(RCTLogLevel, NSString *); diff --git a/React/Base/RCTLog.mm b/React/Base/RCTLog.mm index adfcadc0c35..dfee013c7a6 100644 --- a/React/Base/RCTLog.mm +++ b/React/Base/RCTLog.mm @@ -12,21 +12,21 @@ #import #import -#import "RCTRedBoxSetEnabled.h" #import "RCTAssert.h" #import "RCTBridge+Private.h" #import "RCTBridge.h" #import "RCTDefines.h" +#import "RCTRedBoxSetEnabled.h" #import "RCTUtils.h" static NSString *const RCTLogFunctionStack = @"RCTLogFunctionStack"; const char *RCTLogLevels[] = { - "trace", - "info", - "warn", - "error", - "fatal", + "trace", + "info", + "warn", + "error", + "fatal", }; /* os log will discard debug and info messages if they are not needed */ @@ -40,7 +40,8 @@ RCTLogLevel RCTGetLogThreshold() return RCTCurrentLogThreshold; } -void RCTSetLogThreshold(RCTLogLevel threshold) { +void RCTSetLogThreshold(RCTLogLevel threshold) +{ RCTCurrentLogThreshold = threshold; } @@ -77,16 +78,14 @@ static os_log_t RCTLogForLogSource(RCTLogSource source) } } -RCTLogFunction RCTDefaultLogFunction = ^( - RCTLogLevel level, - RCTLogSource source, - __unused NSString *fileName, - __unused NSNumber *lineNumber, - NSString *message -) -{ - os_log_with_type(RCTLogForLogSource(source), RCTLogTypeForLogLevel(level), "%{public}s", message.UTF8String); -}; +RCTLogFunction RCTDefaultLogFunction = + ^(RCTLogLevel level, + RCTLogSource source, + __unused NSString *fileName, + __unused NSNumber *lineNumber, + NSString *message) { + os_log_with_type(RCTLogForLogSource(source), RCTLogTypeForLogLevel(level), "%{public}s", message.UTF8String); + }; void RCTSetLogFunction(RCTLogFunction logFunction) { @@ -105,10 +104,11 @@ void RCTAddLogFunction(RCTLogFunction logFunction) { RCTLogFunction existing = RCTGetLogFunction(); if (existing) { - RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { - existing(level, source, fileName, lineNumber, message); - logFunction(level, source, fileName, lineNumber, message); - }); + RCTSetLogFunction( + ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { + existing(level, source, fileName, lineNumber, message); + logFunction(level, source, fileName, lineNumber, message); + }); } else { RCTSetLogFunction(logFunction); } @@ -146,21 +146,15 @@ void RCTPerformBlockWithLogPrefix(void (^block)(void), NSString *prefix) { RCTLogFunction logFunction = RCTGetLocalLogFunction(); if (logFunction) { - RCTPerformBlockWithLogFunction(block, ^(RCTLogLevel level, RCTLogSource source, - NSString *fileName, NSNumber *lineNumber, - NSString *message) { - logFunction(level, source, fileName, lineNumber, [prefix stringByAppendingString:message]); - }); + RCTPerformBlockWithLogFunction( + block, ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { + logFunction(level, source, fileName, lineNumber, [prefix stringByAppendingString:message]); + }); } } -NSString *RCTFormatLog( - NSDate *timestamp, - RCTLogLevel level, - NSString *fileName, - NSNumber *lineNumber, - NSString *message -) +NSString * +RCTFormatLog(NSDate *timestamp, RCTLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message) { NSMutableString *log = [NSMutableString new]; if (timestamp) { @@ -195,21 +189,22 @@ NSString *RCTFormatLog( NSString *RCTFormatLogLevel(RCTLogLevel level) { - NSDictionary *levelsToString = @{@(RCTLogLevelTrace) : @"trace", - @(RCTLogLevelInfo) : @"info", - @(RCTLogLevelWarning) : @"warning", - @(RCTLogLevelFatal) : @"fatal", - @(RCTLogLevelError) : @"error"}; + NSDictionary *levelsToString = @{ + @(RCTLogLevelTrace) : @"trace", + @(RCTLogLevelInfo) : @"info", + @(RCTLogLevelWarning) : @"warning", + @(RCTLogLevelFatal) : @"fatal", + @(RCTLogLevelError) : @"error" + }; - return levelsToString[@(level)]; + return levelsToString[@(level)]; } NSString *RCTFormatLogSource(RCTLogSource source) { - NSDictionary *sourcesToString = @{@(RCTLogSourceNative) : @"native", - @(RCTLogSourceJavaScript) : @"js"}; + NSDictionary *sourcesToString = @{@(RCTLogSourceNative) : @"native", @(RCTLogSourceJavaScript) : @"js"}; - return sourcesToString[@(source)]; + return sourcesToString[@(source)]; } static NSRegularExpression *nativeStackFrameRegex() @@ -218,7 +213,9 @@ static NSRegularExpression *nativeStackFrameRegex() static NSRegularExpression *_regex; dispatch_once(&onceToken, ^{ NSError *regexError; - _regex = [NSRegularExpression regularExpressionWithPattern:@"0x[0-9a-f]+ (.*) \\+ (\\d+)$" options:0 error:®exError]; + _regex = [NSRegularExpression regularExpressionWithPattern:@"0x[0-9a-f]+ (.*) \\+ (\\d+)$" + options:0 + error:®exError]; if (regexError) { RCTLogError(@"Failed to build regex: %@", [regexError localizedDescription]); } @@ -239,14 +236,14 @@ void _RCTLogNativeInternal(RCTLogLevel level, const char *fileName, int lineNumb // Call log function if (logFunction) { - logFunction(level, RCTLogSourceNative, fileName ? @(fileName) : nil, lineNumber > 0 ? @(lineNumber) : nil, message); + logFunction( + level, RCTLogSourceNative, fileName ? @(fileName) : nil, lineNumber > 0 ? @(lineNumber) : nil, message); } // Log to red box if one is configured. if (RCTSharedApplication() && RCTRedBoxGetEnabled() && level >= RCTLOG_REDBOX_LEVEL) { NSArray *stackSymbols = [NSThread callStackSymbols]; - NSMutableArray *stack = - [NSMutableArray arrayWithCapacity:(stackSymbols.count - 1)]; + NSMutableArray *stack = [NSMutableArray arrayWithCapacity:(stackSymbols.count - 1)]; [stackSymbols enumerateObjectsUsingBlock:^(NSString *frameSymbols, NSUInteger idx, __unused BOOL *stop) { if (idx == 0) { // don't include the current frame @@ -268,9 +265,9 @@ void _RCTLogNativeInternal(RCTLogLevel level, const char *fileName, int lineNumb if (idx == 1 && fileName) { NSString *file = [@(fileName) componentsSeparatedByString:@"/"].lastObject; - [stack addObject:@{@"methodName": methodName, @"file": file, @"lineNumber": @(lineNumber)}]; + [stack addObject:@{@"methodName" : methodName, @"file" : file, @"lineNumber" : @(lineNumber)}]; } else { - [stack addObject:@{@"methodName": methodName}]; + [stack addObject:@{@"methodName" : methodName}]; } }]; @@ -279,7 +276,8 @@ void _RCTLogNativeInternal(RCTLogLevel level, const char *fileName, int lineNumb // race condition that causes the module to be accessed before it has loaded id redbox = [[RCTBridge currentBridge] moduleForName:@"RedBox" lazilyLoadIfNecessary:YES]; if (redbox) { - void (*showErrorMessage)(id, SEL, NSString *, NSMutableArray *) = (__typeof__(showErrorMessage))objc_msgSend; + void (*showErrorMessage)(id, SEL, NSString *, NSMutableArray *) = + (__typeof__(showErrorMessage))objc_msgSend; SEL showErrorMessageSEL = NSSelectorFromString(@"showErrorMessage:withStack:"); if ([redbox respondsToSelector:showErrorMessageSEL]) { @@ -295,7 +293,6 @@ void _RCTLogNativeInternal(RCTLogLevel level, const char *fileName, int lineNumb [[RCTBridge currentBridge] logMessage:message level:level ? @(RCTLogLevels[level]) : @"info"]; } #endif - } } diff --git a/React/Base/RCTManagedPointer.h b/React/Base/RCTManagedPointer.h index 469f187fd8d..4ed6616f442 100644 --- a/React/Base/RCTManagedPointer.h +++ b/React/Base/RCTManagedPointer.h @@ -16,7 +16,7 @@ * to native method. */ -@interface RCTManagedPointer: NSObject +@interface RCTManagedPointer : NSObject @property (nonatomic, readonly) void *voidPointer; @@ -34,6 +34,7 @@ RCTManagedPointer *managedPointer(P initializer) return [[RCTManagedPointer alloc] initWithPointer:std::move(ptr)]; } -} } +} +} #endif diff --git a/React/Base/RCTManagedPointer.mm b/React/Base/RCTManagedPointer.mm index 96c7f266164..a79dde44517 100644 --- a/React/Base/RCTManagedPointer.mm +++ b/React/Base/RCTManagedPointer.mm @@ -11,14 +11,16 @@ std::shared_ptr _pointer; } -- (instancetype)initWithPointer:(std::shared_ptr)pointer { +- (instancetype)initWithPointer:(std::shared_ptr)pointer +{ if (self = [super init]) { _pointer = std::move(pointer); } return self; } -- (void *)voidPointer { +- (void *)voidPointer +{ return _pointer.get(); } diff --git a/React/Base/RCTModuleData.h b/React/Base/RCTModuleData.h index f21ccad1958..398c0a2b9f8 100644 --- a/React/Base/RCTModuleData.h +++ b/React/Base/RCTModuleData.h @@ -13,12 +13,11 @@ @protocol RCTBridgeModule; @class RCTBridge; -typedef id(^RCTBridgeModuleProvider)(void); +typedef id (^RCTBridgeModuleProvider)(void); @interface RCTModuleData : NSObject -- (instancetype)initWithModuleClass:(Class)moduleClass - bridge:(RCTBridge *)bridge; +- (instancetype)initWithModuleClass:(Class)moduleClass bridge:(RCTBridge *)bridge; - (instancetype)initWithModuleClass:(Class)moduleClass moduleProvider:(RCTBridgeModuleProvider)moduleProvider diff --git a/React/Base/RCTModuleData.mm b/React/Base/RCTModuleData.mm index 0ab4dab4c36..b4e48ae5e12 100644 --- a/React/Base/RCTModuleData.mm +++ b/React/Base/RCTModuleData.mm @@ -17,8 +17,7 @@ #import "RCTProfile.h" #import "RCTUtils.h" -@implementation RCTModuleData -{ +@implementation RCTModuleData { NSDictionary *_constantsToExport; NSString *_queueName; __weak RCTBridge *_bridge; @@ -53,7 +52,8 @@ // If a module overrides `init` then we must assume that it expects to be // initialized on the main thread, because it may need to access UIKit. - const BOOL hasCustomInit = !_instance && [_moduleClass instanceMethodForSelector:@selector(init)] != objectInitMethod; + const BOOL hasCustomInit = + !_instance && [_moduleClass instanceMethodForSelector:@selector(init)] != objectInitMethod; _requiresMainQueueSetup = _hasConstantsToExport || hasCustomInit; if (_requiresMainQueueSetup) { @@ -63,18 +63,22 @@ } else if (hasCustomInit) { methodName = "init"; } - RCTLogWarn(@"Module %@ requires main queue setup since it overrides `%s` but doesn't implement " - "`requiresMainQueueSetup`. In a future release React Native will default to initializing all native modules " - "on a background thread unless explicitly opted-out of.", _moduleClass, methodName); + RCTLogWarn( + @"Module %@ requires main queue setup since it overrides `%s` but doesn't implement " + "`requiresMainQueueSetup`. In a future release React Native will default to initializing all native modules " + "on a background thread unless explicitly opted-out of.", + _moduleClass, + methodName); } } } -- (instancetype)initWithModuleClass:(Class)moduleClass - bridge:(RCTBridge *)bridge +- (instancetype)initWithModuleClass:(Class)moduleClass bridge:(RCTBridge *)bridge { return [self initWithModuleClass:moduleClass - moduleProvider:^id{ return [moduleClass new]; } + moduleProvider:^id { + return [moduleClass new]; + } bridge:bridge]; } @@ -91,8 +95,7 @@ return self; } -- (instancetype)initWithModuleInstance:(id)instance - bridge:(RCTBridge *)bridge +- (instancetype)initWithModuleInstance:(id)instance bridge:(RCTBridge *)bridge { if (self = [super init]) { _bridge = bridge; @@ -103,15 +106,16 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)init); +RCT_NOT_IMPLEMENTED(-(instancetype)init); #pragma mark - private setup methods - (void)setUpInstanceAndBridge { - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"[RCTModuleData setUpInstanceAndBridge]", @{ - @"moduleClass": NSStringFromClass(_moduleClass) - }); + RCT_PROFILE_BEGIN_EVENT( + RCTProfileTagAlways, + @"[RCTModuleData setUpInstanceAndBridge]", + @{@"moduleClass" : NSStringFromClass(_moduleClass)}); { std::unique_lock lock(_instanceLock); @@ -128,9 +132,11 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init); // of the module is not supported, and it is supposed to be passed in to // the bridge constructor. Mark setup complete to avoid doing more work. _setupComplete = YES; - RCTLogWarn(@"The module %@ is returning nil from its constructor. You " - "may need to instantiate it yourself and pass it into the " - "bridge.", _moduleClass); + RCTLogWarn( + @"The module %@ is returning nil from its constructor. You " + "may need to instantiate it yourself and pass it into the " + "bridge.", + _moduleClass); } } @@ -173,11 +179,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init); RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"[RCTModuleData setBridgeForInstance]", nil); @try { [(id)_instance setValue:_bridge forKey:@"bridge"]; - } - @catch (NSException *exception) { - RCTLogError(@"%@ has no setter or ivar for its bridge, which is not " - "permitted. You must either @synthesize the bridge property, " - "or provide your own setter method.", self.name); + } @catch (NSException *exception) { + RCTLogError( + @"%@ has no setter or ivar for its bridge, which is not " + "permitted. You must either @synthesize the bridge property, " + "or provide your own setter method.", + self.name); } RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @""); } @@ -189,9 +196,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init); RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"[RCTModuleData finishSetupForInstance]", nil); _setupComplete = YES; [_bridge registerModuleForFrameUpdates:_instance withModuleData:self]; - [[NSNotificationCenter defaultCenter] postNotificationName:RCTDidInitializeModuleNotification - object:_bridge - userInfo:@{@"module": _instance, @"bridge": RCTNullIfNil(_bridge.parentBridge)}]; + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTDidInitializeModuleNotification + object:_bridge + userInfo:@{@"module" : _instance, @"bridge" : RCTNullIfNil(_bridge.parentBridge)}]; RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @""); } } @@ -213,12 +221,13 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init); if (implementsMethodQueue) { @try { [(id)_instance setValue:_methodQueue forKey:@"methodQueue"]; - } - @catch (NSException *exception) { - RCTLogError(@"%@ is returning nil for its methodQueue, which is not " - "permitted. You must either return a pre-initialized " - "queue, or @synthesize the methodQueue to let the bridge " - "create a queue for you.", self.name); + } @catch (NSException *exception) { + RCTLogError( + @"%@ is returning nil for its methodQueue, which is not " + "permitted. You must either return a pre-initialized " + "queue, or @synthesize the methodQueue to let the bridge " + "create a queue for you.", + self.name); } } } @@ -226,45 +235,45 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init); } } -- (void) calculateMethods +- (void)calculateMethods { - if (_methods && _methodsByName) { - return; + if (_methods && _methodsByName) { + return; + } + + NSMutableArray> *moduleMethods = [NSMutableArray new]; + NSMutableDictionary> *moduleMethodsByName = [NSMutableDictionary new]; + + if ([_moduleClass instancesRespondToSelector:@selector(methodsToExport)]) { + [moduleMethods addObjectsFromArray:[self.instance methodsToExport]]; + } + + unsigned int methodCount; + Class cls = _moduleClass; + while (cls && cls != [NSObject class] && cls != [NSProxy class]) { + Method *methods = class_copyMethodList(object_getClass(cls), &methodCount); + + for (unsigned int i = 0; i < methodCount; i++) { + Method method = methods[i]; + SEL selector = method_getName(method); + if ([NSStringFromSelector(selector) hasPrefix:@"__rct_export__"]) { + IMP imp = method_getImplementation(method); + auto exportedMethod = ((const RCTMethodInfo *(*)(id, SEL))imp)(_moduleClass, selector); + id moduleMethod = [[RCTModuleMethod alloc] initWithExportedMethod:exportedMethod + moduleClass:_moduleClass]; + + NSString *str = [NSString stringWithUTF8String:moduleMethod.JSMethodName]; + [moduleMethodsByName setValue:moduleMethod forKey:str]; + [moduleMethods addObject:moduleMethod]; + } } - NSMutableArray> *moduleMethods = [NSMutableArray new]; - NSMutableDictionary> *moduleMethodsByName = [NSMutableDictionary new]; + free(methods); + cls = class_getSuperclass(cls); + } - if ([_moduleClass instancesRespondToSelector:@selector(methodsToExport)]) { - [moduleMethods addObjectsFromArray:[self.instance methodsToExport]]; - } - - unsigned int methodCount; - Class cls = _moduleClass; - while (cls && cls != [NSObject class] && cls != [NSProxy class]) { - Method *methods = class_copyMethodList(object_getClass(cls), &methodCount); - - for (unsigned int i = 0; i < methodCount; i++) { - Method method = methods[i]; - SEL selector = method_getName(method); - if ([NSStringFromSelector(selector) hasPrefix:@"__rct_export__"]) { - IMP imp = method_getImplementation(method); - auto exportedMethod = ((const RCTMethodInfo *(*)(id, SEL))imp)(_moduleClass, selector); - id moduleMethod = [[RCTModuleMethod alloc] initWithExportedMethod:exportedMethod - moduleClass:_moduleClass]; - - NSString *str = [NSString stringWithUTF8String:moduleMethod.JSMethodName]; - [moduleMethodsByName setValue:moduleMethod forKey:str]; - [moduleMethods addObject:moduleMethod]; - } - } - - free(methods); - cls = class_getSuperclass(cls); - } - - _methods = [moduleMethods copy]; - _methodsByName = [moduleMethodsByName copy]; + _methods = [moduleMethods copy]; + _methodsByName = [moduleMethodsByName copy]; } #pragma mark - public getters @@ -278,7 +287,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init); - (id)instance { if (!_setupComplete) { - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, ([NSString stringWithFormat:@"[RCTModuleData instanceForClass:%@]", _moduleClass]), nil); + RCT_PROFILE_BEGIN_EVENT( + RCTProfileTagAlways, ([NSString stringWithFormat:@"[RCTModuleData instanceForClass:%@]", _moduleClass]), nil); if (_requiresMainQueueSetup) { // The chances of deadlock here are low, because module init very rarely // calls out to other threads, however we can't control when a module might @@ -309,20 +319,21 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init); - (NSArray> *)methods { - [self calculateMethods]; - return _methods; + [self calculateMethods]; + return _methods; } - (NSDictionary> *)methodsByName { - [self calculateMethods]; - return _methodsByName; + [self calculateMethods]; + return _methodsByName; } - (void)gatherConstants { if (_hasConstantsToExport && !_constantsToExport) { - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, ([NSString stringWithFormat:@"[RCTModuleData gatherConstants] %@", _moduleClass]), nil); + RCT_PROFILE_BEGIN_EVENT( + RCTProfileTagAlways, ([NSString stringWithFormat:@"[RCTModuleData gatherConstants] %@", _moduleClass]), nil); (void)[self instance]; if (_requiresMainQueueSetup) { if (!RCTIsMainQueue()) { @@ -351,8 +362,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init); { if (_bridge.valid) { id instance = self.instance; - RCTAssert(_methodQueue != nullptr, @"Module %@ has no methodQueue (instance: %@)", - self, instance); + RCTAssert(_methodQueue != nullptr, @"Module %@ has no methodQueue (instance: %@)", self, instance); } return _methodQueue; } diff --git a/React/Base/RCTModuleMethod.mm b/React/Base/RCTModuleMethod.mm index ef463df2a15..ff89838a75e 100644 --- a/React/Base/RCTModuleMethod.mm +++ b/React/Base/RCTModuleMethod.mm @@ -33,9 +33,7 @@ static SEL selectorForType(NSString *type) @implementation RCTMethodArgument -- (instancetype)initWithType:(NSString *)type - nullability:(RCTNullability)nullability - unused:(BOOL)unused +- (instancetype)initWithType:(NSString *)type nullability:(RCTNullability)nullability unused:(BOOL)unused { if (self = [super init]) { _type = [type copy]; @@ -47,8 +45,7 @@ static SEL selectorForType(NSString *type) @end -@implementation RCTModuleMethod -{ +@implementation RCTModuleMethod { Class _moduleClass; const RCTMethodInfo *_methodInfo; NSString *_JSMethodName; @@ -59,15 +56,18 @@ static SEL selectorForType(NSString *type) NSMutableArray *_retainedObjects; } -static void RCTLogArgumentError(RCTModuleMethod *method, NSUInteger index, - id valueOrType, const char *issue) +static void RCTLogArgumentError(RCTModuleMethod *method, NSUInteger index, id valueOrType, const char *issue) { - RCTLogError(@"Argument %tu (%@) of %@.%s %s", index, valueOrType, - RCTBridgeModuleNameForClass(method->_moduleClass), - method.JSMethodName, issue); + RCTLogError( + @"Argument %tu (%@) of %@.%s %s", + index, + valueOrType, + RCTBridgeModuleNameForClass(method->_moduleClass), + method.JSMethodName, + issue); } -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) RCT_EXTERN_C_BEGIN @@ -90,9 +90,8 @@ static BOOL RCTParseSelectorPart(const char **input, NSMutableString *selector) static BOOL RCTParseUnused(const char **input) { - return RCTReadString(input, "__attribute__((unused))") || - RCTReadString(input, "__attribute__((__unused__))") || - RCTReadString(input, "__unused"); + return RCTReadString(input, "__attribute__((unused))") || RCTReadString(input, "__attribute__((__unused__))") || + RCTReadString(input, "__unused"); } static RCTNullability RCTParseNullability(const char **input) @@ -107,11 +106,9 @@ static RCTNullability RCTParseNullability(const char **input) static RCTNullability RCTParseNullabilityPostfix(const char **input) { - if (RCTReadString(input, "_Nullable") || - RCTReadString(input, "__nullable")) { + if (RCTReadString(input, "_Nullable") || RCTReadString(input, "__nullable")) { return RCTNullable; - } else if (RCTReadString(input, "_Nonnull") || - RCTReadString(input, "__nonnull")) { + } else if (RCTReadString(input, "_Nonnull") || RCTReadString(input, "__nonnull")) { return RCTNonnullable; } return RCTNullabilityUnspecified; @@ -119,13 +116,15 @@ static RCTNullability RCTParseNullabilityPostfix(const char **input) // returns YES if execution is safe to proceed (enqueue callback invocation), NO if callback has already been invoked #if RCT_DEBUG -static BOOL checkCallbackMultipleInvocations(BOOL *didInvoke) { +static BOOL checkCallbackMultipleInvocations(BOOL *didInvoke) +{ if (*didInvoke) { - RCTFatal(RCTErrorWithMessage(@"Illegal callback invocation from native module. This callback type only permits a single invocation from native code.")); - return NO; + RCTFatal(RCTErrorWithMessage( + @"Illegal callback invocation from native module. This callback type only permits a single invocation from native code.")); + return NO; } else { - *didInvoke = YES; - return YES; + *didInvoke = YES; + return YES; } } #endif @@ -144,20 +143,20 @@ NSString *RCTParseMethodSignature(const char *input, NSArray *argumentBlocks = - [[NSMutableArray alloc] initWithCapacity:numberOfArguments - 2]; + NSMutableArray *argumentBlocks = [[NSMutableArray alloc] initWithCapacity:numberOfArguments - 2]; #if RCT_DEBUG __weak RCTModuleMethod *weakSelf = self; #endif -#define RCT_RETAINED_ARG_BLOCK(_logic) \ -[argumentBlocks addObject:^(__unused __weak RCTBridge *bridge, NSUInteger index, id json) { \ - _logic \ - [invocation setArgument:&value atIndex:(index) + 2]; \ - if (value) { \ - [retainedObjects addObject:value]; \ - } \ - return YES; \ -}] +#define RCT_RETAINED_ARG_BLOCK(_logic) \ + [argumentBlocks addObject:^(__unused __weak RCTBridge * bridge, NSUInteger index, id json) { \ + _logic [invocation setArgument:&value atIndex:(index) + 2]; \ + if (value) { \ + [retainedObjects addObject:value]; \ + } \ + return YES; \ + }] -#define __PRIMITIVE_CASE(_type, _nullable) { \ - isNullableType = _nullable; \ - _type (*convert)(id, SEL, id) = (__typeof__(convert))objc_msgSend; \ - [argumentBlocks addObject:^(__unused RCTBridge *bridge, NSUInteger index, id json) { \ - _type value = convert([RCTConvert class], selector, json); \ - [invocation setArgument:&value atIndex:(index) + 2]; \ - return YES; \ - }]; \ - break; \ -} +#define __PRIMITIVE_CASE(_type, _nullable) \ + { \ + isNullableType = _nullable; \ + _type (*convert)(id, SEL, id) = (__typeof__(convert))objc_msgSend; \ + [argumentBlocks addObject:^(__unused RCTBridge * bridge, NSUInteger index, id json) { \ + _type value = convert([RCTConvert class], selector, json); \ + [invocation setArgument:&value atIndex:(index) + 2]; \ + return YES; \ + }]; \ + break; \ + } #define PRIMITIVE_CASE(_type) __PRIMITIVE_CASE(_type, NO) #define NULLABLE_PRIMITIVE_CASE(_type) __PRIMITIVE_CASE(_type, YES) @@ -260,22 +253,22 @@ RCT_EXTERN_C_END id value = [block copy]; \ if (value) { \ [retainedObjects addObject:value]; \ - } \ + } #if RCT_DEBUG -#define BLOCK_CASE(_block_args, _block) RCT_RETAINED_ARG_BLOCK( \ - if (json && ![json isKindOfClass:[NSNumber class]]) { \ - RCTLogArgumentError(weakSelf, index, json, "should be a function"); \ - return NO; \ - } \ - __block BOOL didInvoke = NO; \ - __COPY_BLOCK(^_block_args { \ - if (checkCallbackMultipleInvocations(&didInvoke)) _block \ - }); \ -) +#define BLOCK_CASE(_block_args, _block) \ + RCT_RETAINED_ARG_BLOCK(if (json && ![json isKindOfClass:[NSNumber class]]) { \ + RCTLogArgumentError(weakSelf, index, json, "should be a function"); \ + return NO; \ + } __block BOOL didInvoke = NO; \ + __COPY_BLOCK(^_block_args { \ + if (checkCallbackMultipleInvocations(&didInvoke)) \ + _block \ + });) #else -#define BLOCK_CASE(_block_args, _block) \ - RCT_RETAINED_ARG_BLOCK( __COPY_BLOCK(^_block_args { _block }); ) +#define BLOCK_CASE(_block_args, _block) \ + RCT_RETAINED_ARG_BLOCK(__COPY_BLOCK(^_block_args{ \ + _block});) #endif for (NSUInteger i = 2; i < numberOfArguments; i++) { @@ -287,29 +280,43 @@ RCT_EXTERN_C_END if ([RCTConvert respondsToSelector:selector]) { switch (objcType[0]) { // Primitives - case _C_CHR: PRIMITIVE_CASE(char) - case _C_UCHR: PRIMITIVE_CASE(unsigned char) - case _C_SHT: PRIMITIVE_CASE(short) - case _C_USHT: PRIMITIVE_CASE(unsigned short) - case _C_INT: PRIMITIVE_CASE(int) - case _C_UINT: PRIMITIVE_CASE(unsigned int) - case _C_LNG: PRIMITIVE_CASE(long) - case _C_ULNG: PRIMITIVE_CASE(unsigned long) - case _C_LNG_LNG: PRIMITIVE_CASE(long long) - case _C_ULNG_LNG: PRIMITIVE_CASE(unsigned long long) - case _C_FLT: PRIMITIVE_CASE(float) - case _C_DBL: PRIMITIVE_CASE(double) - case _C_BOOL: PRIMITIVE_CASE(BOOL) - case _C_SEL: NULLABLE_PRIMITIVE_CASE(SEL) - case _C_CHARPTR: NULLABLE_PRIMITIVE_CASE(const char *) - case _C_PTR: NULLABLE_PRIMITIVE_CASE(void *) + case _C_CHR: + PRIMITIVE_CASE(char) + case _C_UCHR: + PRIMITIVE_CASE(unsigned char) + case _C_SHT: + PRIMITIVE_CASE(short) + case _C_USHT: + PRIMITIVE_CASE(unsigned short) + case _C_INT: + PRIMITIVE_CASE(int) + case _C_UINT: + PRIMITIVE_CASE(unsigned int) + case _C_LNG: + PRIMITIVE_CASE(long) + case _C_ULNG: + PRIMITIVE_CASE(unsigned long) + case _C_LNG_LNG: + PRIMITIVE_CASE(long long) + case _C_ULNG_LNG: + PRIMITIVE_CASE(unsigned long long) + case _C_FLT: + PRIMITIVE_CASE(float) + case _C_DBL: + PRIMITIVE_CASE(double) + case _C_BOOL: + PRIMITIVE_CASE(BOOL) + case _C_SEL: + NULLABLE_PRIMITIVE_CASE(SEL) + case _C_CHARPTR: + NULLABLE_PRIMITIVE_CASE(const char *) + case _C_PTR: + NULLABLE_PRIMITIVE_CASE(void *) case _C_ID: { isNullableType = YES; id (*convert)(id, SEL, id) = (__typeof__(convert))objc_msgSend; - RCT_RETAINED_ARG_BLOCK( - id value = convert([RCTConvert class], selector, json); - ); + RCT_RETAINED_ARG_BLOCK(id value = convert([RCTConvert class], selector, json);); break; } @@ -338,44 +345,35 @@ RCT_EXTERN_C_END } default: { - static const char *blockType = @encode(__typeof__(^{})); + static const char *blockType = @encode(__typeof__(^{ + })); if (!strcmp(objcType, blockType)) { - BLOCK_CASE((NSArray *args), { - [bridge enqueueCallback:json args:args]; - }); + BLOCK_CASE((NSArray * args), { [bridge enqueueCallback:json args:args]; }); } else { - RCTLogError(@"Unsupported argument type '%@' in method %@.", - typeName, [self methodName]); + RCTLogError(@"Unsupported argument type '%@' in method %@.", typeName, [self methodName]); } } } } else if ([typeName isEqualToString:@"RCTResponseSenderBlock"]) { - BLOCK_CASE((NSArray *args), { - [bridge enqueueCallback:json args:args]; - }); + BLOCK_CASE((NSArray * args), { [bridge enqueueCallback:json args:args]; }); } else if ([typeName isEqualToString:@"RCTResponseErrorBlock"]) { - BLOCK_CASE((NSError *error), { - [bridge enqueueCallback:json args:@[RCTJSErrorFromNSError(error)]]; - }); + BLOCK_CASE((NSError * error), { [bridge enqueueCallback:json args:@[ RCTJSErrorFromNSError(error) ]]; }); } else if ([typeName isEqualToString:@"RCTPromiseResolveBlock"]) { - RCTAssert(i == numberOfArguments - 2, - @"The RCTPromiseResolveBlock must be the second to last parameter in %@", - [self methodName]); - BLOCK_CASE((id result), { - [bridge enqueueCallback:json args:result ? @[result] : @[]]; - }); + RCTAssert( + i == numberOfArguments - 2, + @"The RCTPromiseResolveBlock must be the second to last parameter in %@", + [self methodName]); + BLOCK_CASE((id result), { [bridge enqueueCallback:json args:result ? @[ result ] : @[]]; }); } else if ([typeName isEqualToString:@"RCTPromiseRejectBlock"]) { - RCTAssert(i == numberOfArguments - 1, - @"The RCTPromiseRejectBlock must be the last parameter in %@", - [self methodName]); - BLOCK_CASE((NSString *code, NSString *message, NSError *error), { + RCTAssert( + i == numberOfArguments - 1, @"The RCTPromiseRejectBlock must be the last parameter in %@", [self methodName]); + BLOCK_CASE((NSString * code, NSString * message, NSError * error), { NSDictionary *errorJSON = RCTJSErrorFromCodeMessageAndNSError(code, message, error); - [bridge enqueueCallback:json args:@[errorJSON]]; + [bridge enqueueCallback:json args:@[ errorJSON ]]; }); } else if ([typeName hasPrefix:@"JS::"]) { NSString *selectorNameForCxxType = - [[typeName stringByReplacingOccurrencesOfString:@"::" withString:@"_"] - stringByAppendingString:@":"]; + [[typeName stringByReplacingOccurrencesOfString:@"::" withString:@"_"] stringByAppendingString:@":"]; selector = NSSelectorFromString(selectorNameForCxxType); [argumentBlocks addObject:^(__unused RCTBridge *bridge, NSUInteger index, id json) { @@ -390,16 +388,22 @@ RCT_EXTERN_C_END }]; } else { // Unknown argument type - RCTLogError(@"Unknown argument type '%@' in method %@. Extend RCTConvert to support this type.", - typeName, [self methodName]); + RCTLogError( + @"Unknown argument type '%@' in method %@. Extend RCTConvert to support this type.", + typeName, + [self methodName]); } #if RCT_DEBUG RCTNullability nullability = argument.nullability; if (!isNullableType) { if (nullability == RCTNullable) { - RCTLogArgumentError(weakSelf, i - 2, typeName, "is marked as " - "nullable, but is not a nullable type."); + RCTLogArgumentError( + weakSelf, + i - 2, + typeName, + "is marked as " + "nullable, but is not a nullable type."); } nullability = RCTNonnullable; } @@ -411,11 +415,15 @@ RCT_EXTERN_C_END if ([typeName isEqualToString:@"NSNumber"]) { BOOL unspecified = (nullability == RCTNullabilityUnspecified); if (!argument.unused && (nullability == RCTNullable || unspecified)) { - RCTLogArgumentError(weakSelf, i - 2, typeName, - [unspecified ? @"has unspecified nullability" : @"is marked as nullable" - stringByAppendingString: @" but React requires that all NSNumber " - "arguments are explicitly marked as `nonnull` to ensure " - "compatibility with Android."].UTF8String); + RCTLogArgumentError( + weakSelf, + i - 2, + typeName, + [unspecified ? @"has unspecified nullability" : @"is marked as nullable" + stringByAppendingString:@" but React requires that all NSNumber " + "arguments are explicitly marked as `nonnull` to ensure " + "compatibility with Android."] + .UTF8String); } nullability = RCTNonnullable; } @@ -448,8 +456,10 @@ RCT_EXTERN_C_END #if RCT_DEBUG const char *objcType = _invocation.methodSignature.methodReturnType; if (_methodInfo->isSync && objcType[0] != _C_ID) { - RCTLogError(@"Return type of %@.%s should be (id) as the method is \"sync\"", - RCTBridgeModuleNameForClass(_moduleClass), self.JSMethodName); + RCTLogError( + @"Return type of %@.%s should be (id) as the method is \"sync\"", + RCTBridgeModuleNameForClass(_moduleClass), + self.JSMethodName); } #endif @@ -459,8 +469,10 @@ RCT_EXTERN_C_END - (SEL)selector { if (_selector == NULL) { - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"", (@{ @"module": NSStringFromClass(_moduleClass), - @"method": @(_methodInfo->objcName) })); + RCT_PROFILE_BEGIN_EVENT( + RCTProfileTagAlways, + @"", + (@{@"module" : NSStringFromClass(_moduleClass), @"method" : @(_methodInfo->objcName)})); [self processMethodSignature]; RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @""); } @@ -481,8 +493,11 @@ RCT_EXTERN_C_END methodName = [methodName substringToIndex:colonRange.location]; } methodName = [methodName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - RCTAssert(methodName.length, @"%s is not a valid JS function name, please" - " supply an alternative using RCT_REMAP_METHOD()", _methodInfo->objcName); + RCTAssert( + methodName.length, + @"%s is not a valid JS function name, please" + " supply an alternative using RCT_REMAP_METHOD()", + _methodInfo->objcName); } _JSMethodName = methodName; } @@ -501,9 +516,7 @@ RCT_EXTERN_C_END } } -- (id)invokeWithBridge:(RCTBridge *)bridge - module:(id)module - arguments:(NSArray *)arguments +- (id)invokeWithBridge:(RCTBridge *)bridge module:(id)module arguments:(NSArray *)arguments { if (_argumentBlocks == nil) { [self processMethodSignature]; @@ -525,12 +538,15 @@ RCT_EXTERN_C_END expectedCount -= 2; } - RCTLogError(@"%@.%s was called with %lld arguments but expects %lld arguments. " - @"If you haven\'t changed this method yourself, this usually means that " - @"your versions of the native code and JavaScript code are out of sync. " - @"Updating both should make this error go away.", - RCTBridgeModuleNameForClass(_moduleClass), self.JSMethodName, - (long long)actualCount, (long long)expectedCount); + RCTLogError( + @"%@.%s was called with %lld arguments but expects %lld arguments. " + @"If you haven\'t changed this method yourself, this usually means that " + @"your versions of the native code and JavaScript code are out of sync. " + @"Updating both should make this error go away.", + RCTBridgeModuleNameForClass(_moduleClass), + self.JSMethodName, + (long long)actualCount, + (long long)expectedCount); return nil; } #endif @@ -555,12 +571,11 @@ RCT_EXTERN_C_END CFTimeInterval duration = CACurrentMediaTime() - start; if (duration > RCT_MAIN_THREAD_WATCH_DOG_THRESHOLD) { RCTLogWarn( - @"Main Thread Watchdog: Invocation of %@ blocked the main thread for %dms. " - "Consider using background-threaded modules and asynchronous calls " - "to spend less time on the main thread and keep the app's UI responsive.", - [self methodName], - (int)(duration * 1000) - ); + @"Main Thread Watchdog: Invocation of %@ blocked the main thread for %dms. " + "Consider using background-threaded modules and asynchronous calls " + "to spend less time on the main thread and keep the app's UI responsive.", + [self methodName], + (int)(duration * 1000)); } } else { [_invocation invokeWithTarget:module]; @@ -590,7 +605,11 @@ RCT_EXTERN_C_END - (NSString *)description { return [NSString stringWithFormat:@"<%@: %p; exports %@ as %s(); type: %s>", - [self class], self, [self methodName], self.JSMethodName, RCTFunctionDescriptorFromType(self.functionType)]; + [self class], + self, + [self methodName], + self.JSMethodName, + RCTFunctionDescriptorFromType(self.functionType)]; } @end diff --git a/React/Base/RCTMultipartDataTask.h b/React/Base/RCTMultipartDataTask.h index 51dde3dd269..bcf0c5701b4 100644 --- a/React/Base/RCTMultipartDataTask.h +++ b/React/Base/RCTMultipartDataTask.h @@ -9,7 +9,12 @@ #import -typedef void (^RCTMultipartDataTaskCallback)(NSInteger statusCode, NSDictionary *headers, NSData *content, NSError *error, BOOL done); +typedef void (^RCTMultipartDataTaskCallback)( + NSInteger statusCode, + NSDictionary *headers, + NSData *content, + NSError *error, + BOOL done); @interface RCTMultipartDataTask : NSObject diff --git a/React/Base/RCTMultipartDataTask.m b/React/Base/RCTMultipartDataTask.m index bee7b7ca0e2..d7b547a3a7d 100644 --- a/React/Base/RCTMultipartDataTask.m +++ b/React/Base/RCTMultipartDataTask.m @@ -36,7 +36,8 @@ - (void)startTask { NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] - delegate:self delegateQueue:nil]; + delegate:self + delegateQueue:nil]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url]; [request addValue:@"multipart/mixed" forHTTPHeaderField:@"Accept"]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request]; @@ -45,9 +46,9 @@ } - (void)URLSession:(__unused NSURLSession *)session - dataTask:(__unused NSURLSessionDataTask *)dataTask -didReceiveResponse:(NSURLResponse *)response - completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; @@ -62,8 +63,13 @@ didReceiveResponse:(NSURLResponse *)response } } - NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"multipart/mixed;.*boundary=\"([^\"]+)\"" options:0 error:nil]; - NSTextCheckingResult *match = [regex firstMatchInString:contentType options:0 range:NSMakeRange(0, contentType.length)]; + NSRegularExpression *regex = + [NSRegularExpression regularExpressionWithPattern:@"multipart/mixed;.*boundary=\"([^\"]+)\"" + options:0 + error:nil]; + NSTextCheckingResult *match = [regex firstMatchInString:contentType + options:0 + range:NSMakeRange(0, contentType.length)]; if (match) { _boundary = [contentType substringWithRange:[match rangeAtIndex:1]]; completionHandler(NSURLSessionResponseBecomeStream); @@ -76,40 +82,49 @@ didReceiveResponse:(NSURLResponse *)response completionHandler(NSURLSessionResponseAllow); } -- (void)URLSession:(__unused NSURLSession *)session task:(__unused NSURLSessionTask *)task didCompleteWithError:(NSError *)error +- (void)URLSession:(__unused NSURLSession *)session + task:(__unused NSURLSessionTask *)task + didCompleteWithError:(NSError *)error { if (_partHandler) { _partHandler(_statusCode, _headers, _data, error, YES); } } -- (void)URLSession:(__unused NSURLSession *)session dataTask:(__unused NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data { [_data appendData:data]; } -- (void)URLSession:(__unused NSURLSession *)session dataTask:(__unused NSURLSessionDataTask *)dataTask didBecomeStreamTask:(NSURLSessionStreamTask *)streamTask +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didBecomeStreamTask:(NSURLSessionStreamTask *)streamTask { [streamTask captureStreams]; } - (void)URLSession:(__unused NSURLSession *)session - streamTask:(__unused NSURLSessionStreamTask *)streamTask -didBecomeInputStream:(NSInputStream *)inputStream - outputStream:(__unused NSOutputStream *)outputStream + streamTask:(__unused NSURLSessionStreamTask *)streamTask + didBecomeInputStream:(NSInputStream *)inputStream + outputStream:(__unused NSOutputStream *)outputStream { - RCTMultipartStreamReader *reader = [[RCTMultipartStreamReader alloc] initWithInputStream:inputStream boundary:_boundary]; + RCTMultipartStreamReader *reader = [[RCTMultipartStreamReader alloc] initWithInputStream:inputStream + boundary:_boundary]; RCTMultipartDataTaskCallback partHandler = _partHandler; _partHandler = nil; NSInteger statusCode = _statusCode; - BOOL completed = [reader readAllPartsWithCompletionCallback:^(NSDictionary *headers, NSData *content, BOOL done) { - partHandler(statusCode, headers, content, nil, done); - } progressCallback:_progressHandler]; + BOOL completed = [reader + readAllPartsWithCompletionCallback:^(NSDictionary *headers, NSData *content, BOOL done) { + partHandler(statusCode, headers, content, nil, done); + } + progressCallback:_progressHandler]; if (!completed) { - partHandler(statusCode, nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil], YES); + partHandler( + statusCode, nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil], YES); } } - @end diff --git a/React/Base/RCTMultipartStreamReader.h b/React/Base/RCTMultipartStreamReader.h index ea5871bc3c2..5ef5b61daa6 100644 --- a/React/Base/RCTMultipartStreamReader.h +++ b/React/Base/RCTMultipartStreamReader.h @@ -10,7 +10,6 @@ typedef void (^RCTMultipartCallback)(NSDictionary *headers, NSData *content, BOOL done); typedef void (^RCTMultipartProgressCallback)(NSDictionary *headers, NSNumber *loaded, NSNumber *total); - // RCTMultipartStreamReader can be used to parse responses with Content-Type: multipart/mixed // See https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html @interface RCTMultipartStreamReader : NSObject diff --git a/React/Base/RCTMultipartStreamReader.m b/React/Base/RCTMultipartStreamReader.m index 9fb4ab49e52..efbbdf5bdd1 100644 --- a/React/Base/RCTMultipartStreamReader.m +++ b/React/Base/RCTMultipartStreamReader.m @@ -38,7 +38,8 @@ continue; } NSString *key = [line substringToIndex:location]; - NSString *value = [[line substringFromIndex:location + 1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + NSString *value = [[line substringFromIndex:location + 1] + stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [headers setValue:value forKey:key]; } return headers; @@ -87,8 +88,10 @@ NSInteger chunkStart = 0; NSInteger bytesSeen = 0; - NSData *delimiter = [[NSString stringWithFormat:@"%@--%@%@", CRLF, _boundary, CRLF] dataUsingEncoding:NSUTF8StringEncoding]; - NSData *closeDelimiter = [[NSString stringWithFormat:@"%@--%@--%@", CRLF, _boundary, CRLF] dataUsingEncoding:NSUTF8StringEncoding]; + NSData *delimiter = + [[NSString stringWithFormat:@"%@--%@%@", CRLF, _boundary, CRLF] dataUsingEncoding:NSUTF8StringEncoding]; + NSData *closeDelimiter = + [[NSString stringWithFormat:@"%@--%@--%@", CRLF, _boundary, CRLF] dataUsingEncoding:NSUTF8StringEncoding]; NSMutableData *content = [[NSMutableData alloc] initWithCapacity:1]; NSDictionary *currentHeaders = nil; NSUInteger currentHeadersLength = 0; diff --git a/React/Base/RCTParserUtils.m b/React/Base/RCTParserUtils.m index a8c59d87f5e..64cabd532b6 100644 --- a/React/Base/RCTParserUtils.m +++ b/React/Base/RCTParserUtils.m @@ -63,13 +63,11 @@ BOOL RCTParseArgumentIdentifier(const char **input, NSString **string) (*input)++; } - // allow namespace resolution operator + // allow namespace resolution operator } while (RCTReadString(input, "::")); if (string) { - *string = [[NSString alloc] initWithBytes:start - length:(NSInteger)(*input - start) - encoding:NSASCIIStringEncoding]; + *string = [[NSString alloc] initWithBytes:start length:(NSInteger)(*input - start) encoding:NSASCIIStringEncoding]; } return YES; } @@ -85,9 +83,7 @@ BOOL RCTParseSelectorIdentifier(const char **input, NSString **string) (*input)++; } if (string) { - *string = [[NSString alloc] initWithBytes:start - length:(NSInteger)(*input - start) - encoding:NSASCIIStringEncoding]; + *string = [[NSString alloc] initWithBytes:start length:(NSInteger)(*input - start) encoding:NSASCIIStringEncoding]; } return YES; } @@ -97,8 +93,7 @@ static BOOL RCTIsCollectionType(NSString *type) static NSSet *collectionTypes; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - collectionTypes = [[NSSet alloc] initWithObjects: - @"NSArray", @"NSSet", @"NSDictionary", nil]; + collectionTypes = [[NSSet alloc] initWithObjects:@"NSArray", @"NSSet", @"NSDictionary", nil]; }); return [collectionTypes containsObject:type]; } @@ -124,8 +119,7 @@ NSString *RCTParseType(const char **input) subtype = RCTParseType(input); } if (![subtype isEqualToString:@"id"]) { - type = [type stringByReplacingCharactersInRange:(NSRange){0, 2 /* "NS" */} - withString:subtype]; + type = [type stringByReplacingCharactersInRange:(NSRange){0, 2 /* "NS" */} withString:subtype]; } } else { // It's a protocol rather than a generic collection - ignore it diff --git a/React/Base/RCTPerformanceLogger.m b/React/Base/RCTPerformanceLogger.m index fafe3ccc29e..ea4c5d407aa 100644 --- a/React/Base/RCTPerformanceLogger.m +++ b/React/Base/RCTPerformanceLogger.m @@ -7,13 +7,12 @@ #import -#import "RCTPerformanceLogger.h" -#import "RCTRootView.h" #import "RCTLog.h" +#import "RCTPerformanceLogger.h" #import "RCTProfile.h" +#import "RCTRootView.h" -@interface RCTPerformanceLogger () -{ +@interface RCTPerformanceLogger () { int64_t _data[RCTPLSize][2]; NSUInteger _cookies[RCTPLSize]; } @@ -64,12 +63,11 @@ _data[tag][1] = 0; } - - (void)markStopForTag:(RCTPLTag)tag { #if RCT_PROFILE if (RCTProfileIsProfiling()) { - NSString *label =_labelsForTags[tag]; + NSString *label = _labelsForTags[tag]; RCTProfileEndAsyncEvent(RCTProfileTagAlways, @"native", _cookies[tag], label, @"RCTPerformanceLogger"); } #endif diff --git a/React/Base/RCTRedBoxSetEnabled.h b/React/Base/RCTRedBoxSetEnabled.h index 5d65d7f89ae..fd53eb7e11e 100644 --- a/React/Base/RCTRedBoxSetEnabled.h +++ b/React/Base/RCTRedBoxSetEnabled.h @@ -7,7 +7,8 @@ #import -// In debug builds, the red box is enabled by default but it is further customizable using this method. -// However, this method only has an effect in builds where RCTRedBox is actually compiled in. +// In debug builds, the red box is enabled by default but it is further +// customizable using this method. However, this method only has an effect in +// builds where RCTRedBox is actually compiled in. RCT_EXTERN void RCTRedBoxSetEnabled(BOOL enabled); RCT_EXTERN BOOL RCTRedBoxGetEnabled(void); diff --git a/React/Base/RCTRedBoxSetEnabled.m b/React/Base/RCTRedBoxSetEnabled.m index 4d6a701df9f..503e16fe972 100644 --- a/React/Base/RCTRedBoxSetEnabled.m +++ b/React/Base/RCTRedBoxSetEnabled.m @@ -13,10 +13,12 @@ static BOOL redBoxEnabled = YES; static BOOL redBoxEnabled = NO; #endif -void RCTRedBoxSetEnabled(BOOL enabled) { +void RCTRedBoxSetEnabled(BOOL enabled) +{ redBoxEnabled = enabled; } -BOOL RCTRedBoxGetEnabled() { +BOOL RCTRedBoxGetEnabled() +{ return redBoxEnabled; } diff --git a/React/Base/RCTReloadCommand.m b/React/Base/RCTReloadCommand.m index 43faf6e0bf1..6c0e41f4889 100644 --- a/React/Base/RCTReloadCommand.m +++ b/React/Base/RCTReloadCommand.m @@ -34,10 +34,9 @@ void RCTRegisterReloadCommandListener(id listener) dispatch_once(&onceToken, ^{ [[RCTKeyCommands sharedInstance] registerKeyCommandWithInput:@"r" modifierFlags:UIKeyModifierCommand - action: - ^(__unused UIKeyCommand *command) { - RCTTriggerReloadCommandListeners(@"Command + R"); - }]; + action:^(__unused UIKeyCommand *command) { + RCTTriggerReloadCommandListeners(@"Command + R"); + }]; }); #endif [listeners addObject:listener]; @@ -49,8 +48,9 @@ void RCTTriggerReloadCommandListeners(NSString *reason) [listenersLock lock]; [[NSNotificationCenter defaultCenter] postNotificationName:RCTTriggerReloadCommandNotification object:nil - userInfo:@{RCTTriggerReloadCommandReasonKey: RCTNullIfNil(reason), - RCTTriggerReloadCommandBundleURLKey: RCTNullIfNil(bundleURL) + userInfo:@{ + RCTTriggerReloadCommandReasonKey : RCTNullIfNil(reason), + RCTTriggerReloadCommandBundleURLKey : RCTNullIfNil(bundleURL) }]; for (id l in [listeners allObjects]) { diff --git a/React/Base/RCTRootContentView.m b/React/Base/RCTRootContentView.m index a2231c4b1e9..18612faad5d 100644 --- a/React/Base/RCTRootContentView.m +++ b/React/Base/RCTRootContentView.m @@ -33,8 +33,8 @@ return self; } -RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame:(CGRect)frame) -RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder:(nonnull NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (nonnull NSCoder *)aDecoder) - (void)layoutSubviews { @@ -49,8 +49,7 @@ RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder:(nonnull NSCoder *)aDecoder) dispatch_async(dispatch_get_main_queue(), ^{ if (!self->_contentHasAppeared) { self->_contentHasAppeared = YES; - [[NSNotificationCenter defaultCenter] postNotificationName:RCTContentDidAppearNotification - object:self.superview]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTContentDidAppearNotification object:self.superview]; } }); } @@ -70,8 +69,7 @@ RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder:(nonnull NSCoder *)aDecoder) CGSize size = self.bounds.size; return CGSizeMake( _sizeFlexibility & RCTRootViewSizeFlexibilityWidth ? INFINITY : size.width, - _sizeFlexibility & RCTRootViewSizeFlexibilityHeight ? INFINITY : size.height - ); + _sizeFlexibility & RCTRootViewSizeFlexibilityHeight ? INFINITY : size.height); } - (void)updateAvailableSize @@ -101,7 +99,7 @@ RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder:(nonnull NSCoder *)aDecoder) [_bridge enqueueJSCall:@"AppRegistry" method:@"unmountApplicationComponentAtRootTag" - args:@[self.reactTag] + args:@[ self.reactTag ] completion:NULL]; } } diff --git a/React/Base/RCTRootView.h b/React/Base/RCTRootView.h index 23b11408893..f6ad79d78ad 100644 --- a/React/Base/RCTRootView.h +++ b/React/Base/RCTRootView.h @@ -19,9 +19,9 @@ * rootViewDidChangeIntrinsicSize method of the RCTRootViewDelegate will be called. */ typedef NS_ENUM(NSInteger, RCTRootViewSizeFlexibility) { - RCTRootViewSizeFlexibilityNone = 0, - RCTRootViewSizeFlexibilityWidth = 1 << 0, - RCTRootViewSizeFlexibilityHeight = 1 << 1, + RCTRootViewSizeFlexibilityNone = 0, + RCTRootViewSizeFlexibilityWidth = 1 << 0, + RCTRootViewSizeFlexibilityHeight = 1 << 1, RCTRootViewSizeFlexibilityWidthAndHeight = RCTRootViewSizeFlexibilityWidth | RCTRootViewSizeFlexibilityHeight, }; @@ -36,9 +36,9 @@ extern "C" extern #endif -NS_ASSUME_NONNULL_BEGIN + NS_ASSUME_NONNULL_BEGIN -NSString *const RCTContentDidAppearNotification; + NSString *const RCTContentDidAppearNotification; /** * Native view used to host React-managed views within the app. Can be used just @@ -66,7 +66,6 @@ NSString *const RCTContentDidAppearNotification; initialProperties:(nullable NSDictionary *)initialProperties launchOptions:(nullable NSDictionary *)launchOptions; - /** * The name of the JavaScript module to execute within the * specified scriptURL (required). Setting this will not have @@ -146,8 +145,7 @@ NSString *const RCTContentDidAppearNotification; * This property is deprecated and will be removed in next releases. * Use UIKit `intrinsicContentSize` property instead. */ -@property (readonly, nonatomic, assign) CGSize intrinsicSize -__deprecated_msg("Use `intrinsicContentSize` instead."); +@property (readonly, nonatomic, assign) CGSize intrinsicSize __deprecated_msg("Use `intrinsicContentSize` instead."); /** * This methods is deprecated and will be removed soon. diff --git a/React/Base/RCTRootView.m b/React/Base/RCTRootView.m index 841f9fe7310..5f7d5cddadc 100644 --- a/React/Base/RCTRootView.m +++ b/React/Base/RCTRootView.m @@ -12,8 +12,8 @@ #import #import "RCTAssert.h" -#import "RCTBridge.h" #import "RCTBridge+Private.h" +#import "RCTBridge.h" #import "RCTConstants.h" #import "RCTEventDispatcher.h" #import "RCTKeyCommands.h" @@ -29,8 +29,8 @@ #import "UIView+React.h" #if TARGET_OS_TV -#import "RCTTVRemoteHandler.h" #import "RCTTVNavigationEventEmitter.h" +#import "RCTTVRemoteHandler.h" #endif NSString *const RCTContentDidAppearNotification = @"RCTContentDidAppearNotification"; @@ -41,8 +41,7 @@ NSString *const RCTContentDidAppearNotification = @"RCTContentDidAppearNotificat @end -@implementation RCTRootView -{ +@implementation RCTRootView { RCTBridge *_bridge; NSString *_moduleName; RCTRootContentView *_contentView; @@ -112,15 +111,13 @@ NSString *const RCTContentDidAppearNotification = @"RCTContentDidAppearNotificat initialProperties:(NSDictionary *)initialProperties launchOptions:(NSDictionary *)launchOptions { - RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:bundleURL - moduleProvider:nil - launchOptions:launchOptions]; + RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:bundleURL moduleProvider:nil launchOptions:launchOptions]; return [self initWithBridge:bridge moduleName:moduleName initialProperties:initialProperties]; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) #if TARGET_OS_TV - (UIView *)preferredFocusedView @@ -155,14 +152,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) // Following the current `size` and current `sizeFlexibility` policy. fitSize = CGSizeMake( _sizeFlexibility & RCTRootViewSizeFlexibilityWidth ? fitSize.width : currentSize.width, - _sizeFlexibility & RCTRootViewSizeFlexibilityHeight ? fitSize.height : currentSize.height - ); + _sizeFlexibility & RCTRootViewSizeFlexibilityHeight ? fitSize.height : currentSize.height); // Following the given size constraints. - fitSize = CGSizeMake( - MIN(size.width, fitSize.width), - MIN(size.height, fitSize.height) - ); + fitSize = CGSizeMake(MIN(size.width, fitSize.width), MIN(size.height, fitSize.height)); return fitSize; } @@ -171,10 +164,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) { [super layoutSubviews]; _contentView.frame = self.bounds; - _loadingView.center = (CGPoint){ - CGRectGetMidX(self.bounds), - CGRectGetMidY(self.bounds) - }; + _loadingView.center = (CGPoint){CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)}; } - (UIViewController *)reactViewController @@ -207,18 +197,20 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) { if (_loadingView.superview == self && _contentView.contentHasAppeared) { if (_loadingViewFadeDuration > 0) { - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_loadingViewFadeDelay * NSEC_PER_SEC)), - dispatch_get_main_queue(), ^{ - - [UIView transitionWithView:self - duration:self->_loadingViewFadeDuration - options:UIViewAnimationOptionTransitionCrossDissolve - animations:^{ - self->_loadingView.hidden = YES; - } completion:^(__unused BOOL finished) { - [self->_loadingView removeFromSuperview]; - }]; - }); + dispatch_after( + dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_loadingViewFadeDelay * NSEC_PER_SEC)), + dispatch_get_main_queue(), + ^{ + [UIView transitionWithView:self + duration:self->_loadingViewFadeDuration + options:UIViewAnimationOptionTransitionCrossDissolve + animations:^{ + self->_loadingView.hidden = YES; + } + completion:^(__unused BOOL finished) { + [self->_loadingView removeFromSuperview]; + }]; + }); } else { _loadingView.hidden = YES; [_loadingView removeFromSuperview]; @@ -287,15 +279,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) { NSString *moduleName = _moduleName ?: @""; NSDictionary *appParameters = @{ - @"rootTag": _contentView.reactTag, - @"initialProps": _appProperties ?: @{}, + @"rootTag" : _contentView.reactTag, + @"initialProps" : _appProperties ?: @{}, }; RCTLogInfo(@"Running application %@ (%@)", moduleName, appParameters); - [bridge enqueueJSCall:@"AppRegistry" - method:@"runApplication" - args:@[moduleName, appParameters] - completion:NULL]; + [bridge enqueueJSCall:@"AppRegistry" method:@"runApplication" args:@[ moduleName, appParameters ] completion:NULL]; } - (void)setSizeFlexibility:(RCTRootViewSizeFlexibility)sizeFlexibility @@ -371,11 +360,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) { [super traitCollectionDidChange:previousTraitCollection]; - [[NSNotificationCenter defaultCenter] postNotificationName:RCTUserInterfaceStyleDidChangeNotification - object:self - userInfo:@{ - RCTUserInterfaceStyleDidChangeNotificationTraitCollectionKey: self.traitCollection, - }]; + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTUserInterfaceStyleDidChangeNotification + object:self + userInfo:@{ + RCTUserInterfaceStyleDidChangeNotificationTraitCollectionKey : self.traitCollection, + }]; } - (void)dealloc diff --git a/React/Base/RCTTVRemoteHandler.h b/React/Base/RCTTVRemoteHandler.h index 1cc7215f7c5..10d56906901 100644 --- a/React/Base/RCTTVRemoteHandler.h +++ b/React/Base/RCTTVRemoteHandler.h @@ -7,7 +7,6 @@ #import - extern NSString *const RCTTVRemoteEventMenu; extern NSString *const RCTTVRemoteEventPlayPause; extern NSString *const RCTTVRemoteEventSelect; diff --git a/React/Base/RCTTVRemoteHandler.m b/React/Base/RCTTVRemoteHandler.m index fabed196e04..aadbacec4b7 100644 --- a/React/Base/RCTTVRemoteHandler.m +++ b/React/Base/RCTTVRemoteHandler.m @@ -41,7 +41,6 @@ NSString *const RCTTVRemoteEventSwipeRight = @"swipeRight"; NSString *const RCTTVRemoteEventSwipeUp = @"swipeUp"; NSString *const RCTTVRemoteEventSwipeDown = @"swipeDown"; - @implementation RCTTVRemoteHandler { NSMutableDictionary *_tvRemoteGestureRecognizers; } @@ -120,7 +119,6 @@ NSString *const RCTTVRemoteEventSwipeDown = @"swipeDown"; [self addSwipeGestureRecognizerWithSelector:@selector(swipedRight:) direction:UISwipeGestureRecognizerDirectionRight name:RCTTVRemoteEventSwipeRight]; - } return self; @@ -198,10 +196,12 @@ NSString *const RCTTVRemoteEventSwipeDown = @"swipeDown"; #pragma mark - -- (void)addLongPressGestureRecognizerWithSelector:(nonnull SEL)selector pressType:(UIPressType)pressType name:(NSString *)name +- (void)addLongPressGestureRecognizerWithSelector:(nonnull SEL)selector + pressType:(UIPressType)pressType + name:(NSString *)name { UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:selector]; - recognizer.allowedPressTypes = @[@(pressType)]; + recognizer.allowedPressTypes = @[ @(pressType) ]; _tvRemoteGestureRecognizers[name] = recognizer; } @@ -209,12 +209,14 @@ NSString *const RCTTVRemoteEventSwipeDown = @"swipeDown"; - (void)addTapGestureRecognizerWithSelector:(nonnull SEL)selector pressType:(UIPressType)pressType name:(NSString *)name { UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:selector]; - recognizer.allowedPressTypes = @[@(pressType)]; + recognizer.allowedPressTypes = @[ @(pressType) ]; _tvRemoteGestureRecognizers[name] = recognizer; } -- (void)addSwipeGestureRecognizerWithSelector:(nonnull SEL)selector direction:(UISwipeGestureRecognizerDirection)direction name:(NSString *)name +- (void)addSwipeGestureRecognizerWithSelector:(nonnull SEL)selector + direction:(UISwipeGestureRecognizerDirection)direction + name:(NSString *)name { UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:selector]; recognizer.direction = direction; @@ -225,8 +227,7 @@ NSString *const RCTTVRemoteEventSwipeDown = @"swipeDown"; - (void)sendAppleTVEvent:(NSString *)eventType toView:(__unused UIView *)v { [[NSNotificationCenter defaultCenter] postNotificationName:RCTTVNavigationEventNotification - object:@{@"eventType":eventType}]; + object:@{@"eventType" : eventType}]; } - @end diff --git a/React/Base/RCTTouchEvent.m b/React/Base/RCTTouchEvent.m index 4c1199526eb..3fcc8d71ae8 100644 --- a/React/Base/RCTTouchEvent.m +++ b/React/Base/RCTTouchEvent.m @@ -9,8 +9,7 @@ #import "RCTAssert.h" -@implementation RCTTouchEvent -{ +@implementation RCTTouchEvent { NSArray *_reactTouches; NSArray *_changedIndexes; uint16_t _coalescingKey; @@ -35,7 +34,7 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) #pragma mark - RCTEvent @@ -44,27 +43,43 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) return [_eventName isEqual:@"touchMove"]; } -// We coalesce only move events, while holding some assumptions that seem reasonable but there are no explicit guarantees about them. +// We coalesce only move events, while holding some assumptions that seem reasonable but there are no explicit +// guarantees about them. - (id)coalesceWithEvent:(id)newEvent { - RCTAssert([newEvent isKindOfClass:[RCTTouchEvent class]], @"Touch event cannot be coalesced with any other type of event, such as provided %@", newEvent); + RCTAssert( + [newEvent isKindOfClass:[RCTTouchEvent class]], + @"Touch event cannot be coalesced with any other type of event, such as provided %@", + newEvent); RCTTouchEvent *newTouchEvent = (RCTTouchEvent *)newEvent; - RCTAssert([_reactTouches count] == [newTouchEvent->_reactTouches count], @"Touch events have different number of touches. %@ %@", self, newEvent); + RCTAssert( + [_reactTouches count] == [newTouchEvent->_reactTouches count], + @"Touch events have different number of touches. %@ %@", + self, + newEvent); BOOL newEventIsMoreRecent = NO; BOOL oldEventIsMoreRecent = NO; NSInteger count = _reactTouches.count; - for (int i = 0; i_reactTouches[i]; - RCTAssert([touch[@"identifier"] isEqual:newTouch[@"identifier"]], @"Touch events doesn't have touches in the same order. %@ %@", touch, newTouch); + RCTAssert( + [touch[@"identifier"] isEqual:newTouch[@"identifier"]], + @"Touch events doesn't have touches in the same order. %@ %@", + touch, + newTouch); if ([touch[@"timestamp"] doubleValue] > [newTouch[@"timestamp"] doubleValue]) { oldEventIsMoreRecent = YES; } else { newEventIsMoreRecent = YES; } } - RCTAssert(!(oldEventIsMoreRecent && newEventIsMoreRecent), @"Neither touch event is exclusively more recent than the other one. %@ %@", _reactTouches, newTouchEvent->_reactTouches); + RCTAssert( + !(oldEventIsMoreRecent && newEventIsMoreRecent), + @"Neither touch event is exclusively more recent than the other one. %@ %@", + _reactTouches, + newTouchEvent->_reactTouches); return newEventIsMoreRecent ? newEvent : self; } @@ -75,7 +90,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (NSArray *)arguments { - return @[RCTNormalizeInputEventName(_eventName), _reactTouches, _changedIndexes]; + return @[ RCTNormalizeInputEventName(_eventName), _reactTouches, _changedIndexes ]; } - (uint16_t)coalescingKey @@ -85,7 +100,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p; name = %@; coalescing key = %hu>", [self class], self, _eventName, _coalescingKey]; + return [NSString + stringWithFormat:@"<%@: %p; name = %@; coalescing key = %hu>", [self class], self, _eventName, _coalescingKey]; } @end diff --git a/React/Base/RCTTouchHandler.m b/React/Base/RCTTouchHandler.m index 9d38dbbd6e4..8361fdf55c7 100644 --- a/React/Base/RCTTouchHandler.m +++ b/React/Base/RCTTouchHandler.m @@ -24,8 +24,7 @@ // TODO: this class behaves a lot like a module, and could be implemented as a // module if we were to assume that modules and RootViews had a 1:1 relationship -@implementation RCTTouchHandler -{ +@implementation RCTTouchHandler { __weak RCTEventDispatcher *_eventDispatcher; /** @@ -67,7 +66,7 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithTarget:(id)target action:(SEL)action) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithTarget : (id)target action : (SEL)action) - (void)attachToView:(UIView *)view { @@ -89,9 +88,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithTarget:(id)target action:(SEL)action - (void)_recordNewTouches:(NSSet *)touches { for (UITouch *touch in touches) { - - RCTAssert(![_nativeTouches containsObject:touch], - @"Touch is already recorded. This is a critical bug."); + RCTAssert(![_nativeTouches containsObject:touch], @"Touch is already recorded. This is a critical bug."); // Find closest React-managed touchable view UIView *targetView = touch.view; @@ -114,7 +111,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithTarget:(id)target action:(SEL)action NSInteger usedID = [reactTouch[@"identifier"] integerValue]; if (usedID == touchID) { // ID has already been used, try next value - touchID ++; + touchID++; } else if (usedID > touchID) { // If usedID > touchID, touchID must be unique, so we can stop looking break; @@ -162,7 +159,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithTarget:(id)target action:(SEL)action reactTouch[@"pageY"] = @(RCTSanitizeNaNValue(rootViewLocation.y, @"touchEvent.pageY")); reactTouch[@"locationX"] = @(RCTSanitizeNaNValue(touchViewLocation.x, @"touchEvent.locationX")); reactTouch[@"locationY"] = @(RCTSanitizeNaNValue(touchViewLocation.y, @"touchEvent.locationY")); - reactTouch[@"timestamp"] = @(nativeTouch.timestamp * 1000); // in ms, for JS + reactTouch[@"timestamp"] = @(nativeTouch.timestamp * 1000); // in ms, for JS // TODO: force for a 'normal' touch is usually 1.0; // should we expose a `normalTouchForce` constant somewhere (which would @@ -183,8 +180,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithTarget:(id)target action:(SEL)action * (start/end/move/cancel) and the indices that represent "changed" `Touch`es * from that array. */ -- (void)_updateAndDispatchTouches:(NSSet *)touches - eventName:(NSString *)eventName +- (void)_updateAndDispatchTouches:(NSSet *)touches eventName:(NSString *)eventName { // Update touches NSMutableArray *changedIndexes = [NSMutableArray new]; @@ -204,8 +200,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithTarget:(id)target action:(SEL)action // Deep copy the touches because they will be accessed from another thread // TODO: would it be safer to do this in the bridge or executor, rather than trusting caller? - NSMutableArray *reactTouches = - [[NSMutableArray alloc] initWithCapacity:_reactTouches.count]; + NSMutableArray *reactTouches = [[NSMutableArray alloc] initWithCapacity:_reactTouches.count]; for (NSDictionary *touch in _reactTouches) { [reactTouches addObject:[touch copy]]; } @@ -258,9 +253,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithTarget:(id)target action:(SEL)action static BOOL RCTAllTouchesAreCancelledOrEnded(NSSet *touches) { for (UITouch *touch in touches) { - if (touch.phase == UITouchPhaseBegan || - touch.phase == UITouchPhaseMoved || - touch.phase == UITouchPhaseStationary) { + if (touch.phase == UITouchPhaseBegan || touch.phase == UITouchPhaseMoved || touch.phase == UITouchPhaseStationary) { return NO; } } @@ -270,8 +263,7 @@ static BOOL RCTAllTouchesAreCancelledOrEnded(NSSet *touches) static BOOL RCTAnyTouchesChanged(NSSet *touches) { for (UITouch *touch in touches) { - if (touch.phase == UITouchPhaseBegan || - touch.phase == UITouchPhaseMoved) { + if (touch.phase == UITouchPhaseBegan || touch.phase == UITouchPhaseMoved) { return YES; } } @@ -372,7 +364,8 @@ static BOOL RCTAnyTouchesChanged(NSSet *touches) #pragma mark - UIGestureRecognizerDelegate -- (BOOL)gestureRecognizer:(__unused UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer +- (BOOL)gestureRecognizer:(__unused UIGestureRecognizer *)gestureRecognizer + shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { // Same condition for `failure of` as for `be prevented by`. return [self canBePreventedByGestureRecognizer:otherGestureRecognizer]; diff --git a/React/Base/RCTURLRequestHandler.h b/React/Base/RCTURLRequestHandler.h index c244eb773a4..89f48f5e3b5 100644 --- a/React/Base/RCTURLRequestHandler.h +++ b/React/Base/RCTURLRequestHandler.h @@ -29,8 +29,7 @@ * delegate methods, or the delegate won't recognize the token. * Following common Objective-C pattern, `delegate` will not be retained. */ -- (id)sendRequest:(NSURLRequest *)request - withDelegate:(id)delegate; +- (id)sendRequest:(NSURLRequest *)request withDelegate:(id)delegate; @optional diff --git a/React/Base/RCTUtils.h b/React/Base/RCTUtils.h index 9159d3d820e..9d90ffc6303 100644 --- a/React/Base/RCTUtils.h +++ b/React/Base/RCTUtils.h @@ -61,10 +61,13 @@ RCT_EXTERN BOOL RCTClassOverridesClassMethod(Class cls, SEL selector); RCT_EXTERN BOOL RCTClassOverridesInstanceMethod(Class cls, SEL selector); // Creates a standardized error object to return in callbacks -RCT_EXTERN NSDictionary *RCTMakeError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); -RCT_EXTERN NSDictionary *RCTMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); +RCT_EXTERN NSDictionary + *RCTMakeError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); +RCT_EXTERN NSDictionary * +RCTMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); RCT_EXTERN NSDictionary *RCTJSErrorFromNSError(NSError *error); -RCT_EXTERN NSDictionary *RCTJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error); +RCT_EXTERN NSDictionary + *RCTJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error); // The default error code to use as the `code` property for callback error objects RCT_EXTERN NSString *const RCTErrorUnspecified; @@ -94,8 +97,11 @@ RCT_EXTERN NSError *RCTErrorWithMessage(NSString *message); // Convert nil values to NSNull, and vice-versa #define RCTNullIfNil(value) ((value) ?: (id)kCFNull) -#define RCTNilIfNull(value) \ - ({ __typeof__(value) t = (value); (id)t == (id)kCFNull ? (__typeof(value))nil : t; }) +#define RCTNilIfNull(value) \ + ({ \ + __typeof__(value) t = (value); \ + (id) t == (id)kCFNull ? (__typeof(value))nil : t; \ + }) // Convert NaN or infinite values to zero, as these aren't JSON-safe RCT_EXTERN double RCTZeroIfNaN(double value); @@ -155,13 +161,20 @@ RCT_EXTERN NSString *RCTHumanReadableType(NSObject *obj); // URL manipulation RCT_EXTERN NSString *__nullable RCTGetURLQueryParam(NSURL *__nullable URL, NSString *param); -RCT_EXTERN NSURL *__nullable RCTURLByReplacingQueryParam(NSURL *__nullable URL, NSString *param, NSString *__nullable value); +RCT_EXTERN NSURL *__nullable +RCTURLByReplacingQueryParam(NSURL *__nullable URL, NSString *param, NSString *__nullable value); // Given a string, drop common RN prefixes (RCT, RK, etc.) RCT_EXTERN NSString *RCTDropReactPrefixes(NSString *s); RCT_EXTERN BOOL RCTUIManagerTypeForTagIsFabric(NSNumber *reactTag); -RCT_EXTERN BOOL RCTValidateTypeOfViewCommandArgument(NSObject *obj, id expectedClass, NSString const * expectedType, NSString const *componentName, NSString const * commandName, NSString const * argPos); +RCT_EXTERN BOOL RCTValidateTypeOfViewCommandArgument( + NSObject *obj, + id expectedClass, + NSString const *expectedType, + NSString const *componentName, + NSString const *commandName, + NSString const *argPos); NS_ASSUME_NONNULL_END diff --git a/React/Base/RCTUtils.m b/React/Base/RCTUtils.m index c5fd2d8e1ce..13aeadac4d3 100644 --- a/React/Base/RCTUtils.m +++ b/React/Base/RCTUtils.m @@ -17,9 +17,9 @@ #import +#import #import "RCTAssert.h" #import "RCTLog.h" -#import NSString *const RCTErrorUnspecified = @"EUNSPECIFIED"; @@ -46,33 +46,32 @@ static NSString *__nullable _RCTJSONStringifyNoRetry(id __nullable jsonObject, N SEL selector = NSSelectorFromString(@"JSONStringWithOptions:error:"); if ([NSDictionary instancesRespondToSelector:selector]) { JSONKitSelector = selector; - collectionTypes = [NSSet setWithObjects: - [NSArray class], [NSMutableArray class], - [NSDictionary class], [NSMutableDictionary class], nil]; + collectionTypes = [NSSet setWithObjects:[NSArray class], + [NSMutableArray class], + [NSDictionary class], + [NSMutableDictionary class], + nil]; } }); @try { - // Use JSONKit if available and object is not a fragment if (JSONKitSelector && [collectionTypes containsObject:[jsonObject classForCoder]]) { - return ((NSString *(*)(id, SEL, int, NSError **))objc_msgSend)(jsonObject, JSONKitSelector, 0, error); + return ((NSString * (*)(id, SEL, int, NSError **)) objc_msgSend)(jsonObject, JSONKitSelector, 0, error); } // Use Foundation JSON method - NSData *jsonData = [NSJSONSerialization - dataWithJSONObject:jsonObject options:(NSJSONWritingOptions)NSJSONReadingAllowFragments - error:error]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject + options:(NSJSONWritingOptions)NSJSONReadingAllowFragments + error:error]; return jsonData ? [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] : nil; - } - @catch (NSException *exception) { - + } @catch (NSException *exception) { // Convert exception to error if (error) { - *error = [NSError errorWithDomain:RCTErrorDomain code:0 userInfo:@{ - NSLocalizedDescriptionKey: exception.description ?: @"" - }]; + *error = [NSError errorWithDomain:RCTErrorDomain + code:0 + userInfo:@{NSLocalizedDescriptionKey : exception.description ?: @""}]; } return nil; } @@ -86,8 +85,7 @@ NSString *__nullable RCTJSONStringify(id __nullable jsonObject, NSError **error) NSError *localError; NSString *json = _RCTJSONStringifyNoRetry(jsonObject, &localError); if (localError) { - RCTLogError(@"RCTJSONStringify() encountered the following error: %@", - localError.localizedDescription); + RCTLogError(@"RCTJSONStringify() encountered the following error: %@", localError.localizedDescription); // Sanitize the data, then retry. This is slow, but it prevents uncaught // data issues from crashing in production return _RCTJSONStringifyNoRetry(RCTJSONClean(jsonObject), NULL); @@ -110,7 +108,6 @@ static id __nullable _RCTJSONParse(NSString *__nullable jsonString, BOOL mutable }); if (jsonString) { - // Use JSONKit if available and string is not a fragment if (JSONKitSelector) { NSInteger length = jsonString.length; @@ -119,7 +116,7 @@ static id __nullable _RCTJSONParse(NSString *__nullable jsonString, BOOL mutable if (strchr("{[", c)) { static const int options = (1 << 2); // loose unicode SEL selector = mutable ? JSONKitMutableSelector : JSONKitSelector; - return ((id (*)(id, SEL, int, NSError **))objc_msgSend)(jsonString, selector, options, error); + return ((id(*)(id, SEL, int, NSError **))objc_msgSend)(jsonString, selector, options, error); } if (!strchr(" \r\n\t", c)) { break; @@ -132,8 +129,10 @@ static id __nullable _RCTJSONParse(NSString *__nullable jsonString, BOOL mutable if (!jsonData) { jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; if (jsonData) { - RCTLogWarn(@"RCTJSONParse received the following string, which could " - "not be losslessly converted to UTF8 data: '%@'", jsonString); + RCTLogWarn( + @"RCTJSONParse received the following string, which could " + "not be losslessly converted to UTF8 data: '%@'", + jsonString); } else { NSString *errorMessage = @"RCTJSONParse received invalid UTF8 data"; if (error) { @@ -148,9 +147,7 @@ static id __nullable _RCTJSONParse(NSString *__nullable jsonString, BOOL mutable if (mutable) { options |= NSJSONReadingMutableContainers; } - return [NSJSONSerialization JSONObjectWithData:jsonData - options:options - error:error]; + return [NSJSONSerialization JSONObjectWithData:jsonData options:options error:error]; } return nil; } @@ -170,12 +167,8 @@ id RCTJSONClean(id object) static dispatch_once_t onceToken; static NSSet *validLeafTypes; dispatch_once(&onceToken, ^{ - validLeafTypes = [[NSSet alloc] initWithArray:@[ - [NSString class], - [NSMutableString class], - [NSNumber class], - [NSNull class], - ]]; + validLeafTypes = + [[NSSet alloc] initWithArray:@ [[NSString class], [NSMutableString class], [NSNumber class], [NSNull class], ]]; }); if ([validLeafTypes containsObject:[object classForCoder]]) { @@ -231,11 +224,22 @@ NSString *RCTMD5Hash(NSString *string) CC_MD5(str, (CC_LONG)strlen(str), result); return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - result[0], result[1], result[2], result[3], - result[4], result[5], result[6], result[7], - result[8], result[9], result[10], result[11], - result[12], result[13], result[14], result[15] - ]; + result[0], + result[1], + result[2], + result[3], + result[4], + result[5], + result[6], + result[7], + result[8], + result[9], + result[10], + result[11], + result[12], + result[13], + result[14], + result[15]]; } BOOL RCTIsMainQueue() @@ -243,8 +247,7 @@ BOOL RCTIsMainQueue() static void *mainQueueKey = &mainQueueKey; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - dispatch_queue_set_specific(dispatch_get_main_queue(), - mainQueueKey, mainQueueKey, NULL); + dispatch_queue_set_specific(dispatch_get_main_queue(), mainQueueKey, mainQueueKey, NULL); }); return dispatch_get_specific(mainQueueKey) == mainQueueKey; } @@ -339,8 +342,8 @@ CGFloat RCTFloorPixelValue(CGFloat value) CGSize RCTSizeInPixels(CGSize pointSize, CGFloat scale) { return (CGSize){ - ceil(pointSize.width * scale), - ceil(pointSize.height * scale), + ceil(pointSize.width * scale), + ceil(pointSize.height * scale), }; } @@ -397,9 +400,8 @@ BOOL RCTClassOverridesInstanceMethod(Class cls, SEL selector) return NO; } -NSDictionary *RCTMakeError(NSString *message, - id __nullable toStringify, - NSDictionary *__nullable extraData) +NSDictionary + *RCTMakeError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData) { if (toStringify) { message = [message stringByAppendingString:[toStringify description]]; @@ -410,9 +412,8 @@ NSDictionary *RCTMakeError(NSString *message, return error; } -NSDictionary *RCTMakeAndLogError(NSString *message, - id __nullable toStringify, - NSDictionary *__nullable extraData) +NSDictionary * +RCTMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData) { NSDictionary *error = RCTMakeError(message, toStringify, extraData); RCTLogError(@"\nError: %@", error); @@ -421,22 +422,20 @@ NSDictionary *RCTMakeAndLogError(NSString *message, NSDictionary *RCTJSErrorFromNSError(NSError *error) { - NSString *codeWithDomain = [NSString stringWithFormat:@"E%@%lld", error.domain.uppercaseString, (long long)error.code]; - return RCTJSErrorFromCodeMessageAndNSError(codeWithDomain, - error.localizedDescription, - error); + NSString *codeWithDomain = + [NSString stringWithFormat:@"E%@%lld", error.domain.uppercaseString, (long long)error.code]; + return RCTJSErrorFromCodeMessageAndNSError(codeWithDomain, error.localizedDescription, error); } // TODO: Can we just replace RCTMakeError with this function instead? -NSDictionary *RCTJSErrorFromCodeMessageAndNSError(NSString *code, - NSString *message, - NSError *__nullable error) +NSDictionary + *RCTJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error) { NSString *errorMessage; NSArray *stackTrace = [NSThread callStackSymbols]; NSMutableDictionary *userInfo; - NSMutableDictionary *errorInfo = - [NSMutableDictionary dictionaryWithObject:stackTrace forKey:@"nativeStackIOS"]; + NSMutableDictionary *errorInfo = [NSMutableDictionary dictionaryWithObject:stackTrace + forKey:@"nativeStackIOS"]; if (error) { errorMessage = error.localizedDescription ?: @"Unknown error from a native module"; @@ -446,7 +445,8 @@ NSDictionary *RCTJSErrorFromCodeMessageAndNSError(NSString *code if (userInfo != nil && userInfo[NSUnderlyingErrorKey] != nil) { NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey]; NSString *underlyingCode = [NSString stringWithFormat:@"%d", (int)underlyingError.code]; - userInfo[NSUnderlyingErrorKey] = RCTJSErrorFromCodeMessageAndNSError(underlyingCode, @"underlying error", underlyingError); + userInfo[NSUnderlyingErrorKey] = + RCTJSErrorFromCodeMessageAndNSError(underlyingCode, @"underlying error", underlyingError); } } } else { @@ -469,10 +469,8 @@ BOOL RCTRunningInTestEnvironment(void) static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSDictionary *environment = [[NSProcessInfo processInfo] environment]; - isTestEnvironment = objc_lookUpClass("SenTestCase") || - objc_lookUpClass("XCTest") || - objc_lookUpClass("SnapshotTestAppDelegate") || - [environment[@"IS_TESTING"] boolValue]; + isTestEnvironment = objc_lookUpClass("SenTestCase") || objc_lookUpClass("XCTest") || + objc_lookUpClass("SnapshotTestAppDelegate") || [environment[@"IS_TESTING"] boolValue]; }); return isTestEnvironment; } @@ -526,17 +524,17 @@ BOOL RCTForceTouchAvailable(void) static BOOL forceSupported; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - forceSupported = [UITraitCollection class] && - [UITraitCollection instancesRespondToSelector:@selector(forceTouchCapability)]; + forceSupported = + [UITraitCollection class] && [UITraitCollection instancesRespondToSelector:@selector(forceTouchCapability)]; }); return forceSupported && - (RCTKeyWindow() ?: [UIView new]).traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable; + (RCTKeyWindow() ?: [UIView new]).traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable; } NSError *RCTErrorWithMessage(NSString *message) { - NSDictionary *errorInfo = @{NSLocalizedDescriptionKey: message}; + NSDictionary *errorInfo = @{NSLocalizedDescriptionKey : message}; return [[NSError alloc] initWithDomain:RCTErrorDomain code:0 userInfo:errorInfo]; } @@ -557,9 +555,10 @@ double RCTSanitizeNaNValue(double value, NSString *property) NSURL *RCTDataURL(NSString *mimeType, NSData *data) { - return [NSURL URLWithString: - [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, - [data base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]]]; + return [NSURL + URLWithString:[NSString stringWithFormat:@"data:%@;base64,%@", + mimeType, + [data base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]]]; } BOOL RCTIsGzippedData(NSData *__nullable); // exposed for unit testing purposes @@ -592,7 +591,7 @@ NSData *__nullable RCTGzipData(NSData *__nullable input, float level) static const NSUInteger RCTGZipChunkSize = 16384; NSMutableData *output = nil; - int compression = (level < 0.0f)? Z_DEFAULT_COMPRESSION: (int)(roundf(level * 9)); + int compression = (level < 0.0f) ? Z_DEFAULT_COMPRESSION : (int)(roundf(level * 9)); if (deflateInit2(&stream, compression, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK) { output = [NSMutableData dataWithLength:RCTGZipChunkSize]; while (stream.avail_out == 0) { @@ -632,12 +631,12 @@ static NSString *RCTRelativePathForURL(NSString *basePath, NSURL *__nullable URL NSString *__nullable RCTLibraryPath(void) { - static NSString *libraryPath = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]; - }); - return libraryPath; + static NSString *libraryPath = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]; + }); + return libraryPath; } NSString *__nullable RCTHomePath(void) @@ -653,7 +652,6 @@ NSString *__nullable RCTHomePath(void) NSString *__nullable RCTBundlePathForURL(NSURL *__nullable URL) { return RCTRelativePathForURL([[NSBundle mainBundle] resourcePath], URL); - } NSString *__nullable RCTLibraryPathForURL(NSURL *__nullable URL) @@ -731,7 +729,8 @@ UIImage *__nullable RCTImageFromLocalBundleAssetURL(NSURL *imageURL) // Get the bundle URL, and add the image URL // Note that we have to add both host and path, since host is the first "assets" part // while path is the rest of the URL - NSURL *bundleImageUrl = [[[NSBundle mainBundle] bundleURL] URLByAppendingPathComponent:[imageURL.host stringByAppendingString:imageURL.path]]; + NSURL *bundleImageUrl = [[[NSBundle mainBundle] bundleURL] + URLByAppendingPathComponent:[imageURL.host stringByAppendingString:imageURL.path]]; return RCTImageFromLocalAssetURL(bundleImageUrl); } @@ -759,7 +758,7 @@ UIImage *__nullable RCTImageFromLocalAssetURL(NSURL *imageURL) if (!image) { // Attempt to load from the file system - const char* fileSystemCString = [imageURL fileSystemRepresentation]; + const char *fileSystemCString = [imageURL fileSystemRepresentation]; if (fileSystemCString != NULL) { NSString *filePath = [NSString stringWithUTF8String:fileSystemCString]; if (filePath.pathExtension.length == 0) { @@ -771,10 +770,11 @@ UIImage *__nullable RCTImageFromLocalAssetURL(NSURL *imageURL) if (!image && !bundle) { // We did not find the image in the mainBundle, check in other shipped frameworks. - NSArray *possibleFrameworks = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[[NSBundle mainBundle] privateFrameworksURL] - includingPropertiesForKeys:@[] - options:0 - error:nil]; + NSArray *possibleFrameworks = + [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[[NSBundle mainBundle] privateFrameworksURL] + includingPropertiesForKeys:@[] + options:0 + error:nil]; for (NSURL *frameworkURL in possibleFrameworks) { bundle = [NSBundle bundleWithURL:frameworkURL]; image = [UIImage imageNamed:imageName inBundle:bundle compatibleWithTraitCollection:nil]; @@ -836,18 +836,15 @@ RCT_EXTERN void RCTGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color)); const CGFloat *components = CGColorGetComponents(color); - switch (model) - { - case kCGColorSpaceModelMonochrome: - { + switch (model) { + case kCGColorSpaceModelMonochrome: { rgba[0] = components[0]; rgba[1] = components[0]; rgba[2] = components[0]; rgba[3] = components[1]; break; } - case kCGColorSpaceModelRGB: - { + case kCGColorSpaceModelRGB: { rgba[0] = components[0]; rgba[1] = components[1]; rgba[2] = components[2]; @@ -861,11 +858,9 @@ RCT_EXTERN void RCTGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) case kCGColorSpaceModelPattern: case kCGColorSpaceModelUnknown: // TODO: kCGColorSpaceModelXYZ should be added sometime after Xcode 10 release. - default: - { - + default: { #if RCT_DEBUG - //unsupported format + // unsupported format RCTLogError(@"Unsupported color model: %i", model); #endif @@ -882,10 +877,10 @@ NSString *RCTColorToHexString(CGColorRef color) { CGFloat rgba[4]; RCTGetRGBAColorComponents(color, rgba); - uint8_t r = rgba[0]*255; - uint8_t g = rgba[1]*255; - uint8_t b = rgba[2]*255; - uint8_t a = rgba[3]*255; + uint8_t r = rgba[0] * 255; + uint8_t g = rgba[1] * 255; + uint8_t b = rgba[2] * 255; + uint8_t a = rgba[3] * 255; if (a < 255) { return [NSString stringWithFormat:@"#%02x%02x%02x%02x", r, g, b, a]; } else { @@ -900,13 +895,13 @@ NSString *RCTUIKitLocalizedString(NSString *string) return UIKitBundle ? [UIKitBundle localizedStringForKey:string value:string table:nil] : string; } -NSString *RCTHumanReadableType(NSObject *obj) +NSString *RCTHumanReadableType(NSObject *obj) { if ([obj isKindOfClass:[NSString class]]) { return @"string"; } else if ([obj isKindOfClass:[NSNumber class]]) { int intVal = [(NSNumber *)obj intValue]; - if(intVal == 0 || intVal == 1) { + if (intVal == 0 || intVal == 1) { return @"boolean or number"; } @@ -923,8 +918,7 @@ NSString *__nullable RCTGetURLQueryParam(NSURL *__nullable URL, NSString *param) return nil; } - NSURLComponents *components = [NSURLComponents componentsWithURL:URL - resolvingAgainstBaseURL:YES]; + NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:YES]; for (NSURLQueryItem *queryItem in [components.queryItems reverseObjectEnumerator]) { if ([queryItem.name isEqualToString:param]) { return queryItem.value; @@ -941,26 +935,24 @@ NSURL *__nullable RCTURLByReplacingQueryParam(NSURL *__nullable URL, NSString *p return nil; } - NSURLComponents *components = [NSURLComponents componentsWithURL:URL - resolvingAgainstBaseURL:YES]; + NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:YES]; __block NSInteger paramIndex = NSNotFound; NSMutableArray *queryItems = [components.queryItems mutableCopy]; - [queryItems enumerateObjectsWithOptions:NSEnumerationReverse usingBlock: - ^(NSURLQueryItem *item, NSUInteger i, BOOL *stop) { - if ([item.name isEqualToString:param]) { - paramIndex = i; - *stop = YES; - } - }]; + [queryItems enumerateObjectsWithOptions:NSEnumerationReverse + usingBlock:^(NSURLQueryItem *item, NSUInteger i, BOOL *stop) { + if ([item.name isEqualToString:param]) { + paramIndex = i; + *stop = YES; + } + }]; if (!value) { if (paramIndex != NSNotFound) { [queryItems removeObjectAtIndex:paramIndex]; } } else { - NSURLQueryItem *newItem = [NSURLQueryItem queryItemWithName:param - value:value]; + NSURLQueryItem *newItem = [NSURLQueryItem queryItemWithName:param value:value]; if (paramIndex == NSNotFound) { [queryItems addObject:newItem]; } else { @@ -988,18 +980,24 @@ RCT_EXTERN BOOL RCTUIManagerTypeForTagIsFabric(NSNumber *reactTag) return [reactTag integerValue] % 2 == 0; } -RCT_EXTERN BOOL RCTValidateTypeOfViewCommandArgument(NSObject *obj, id expectedClass, NSString const * expectedType, NSString const *componentName, NSString const * commandName, NSString const * argPos) +RCT_EXTERN BOOL RCTValidateTypeOfViewCommandArgument( + NSObject *obj, + id expectedClass, + NSString const *expectedType, + NSString const *componentName, + NSString const *commandName, + NSString const *argPos) { if (![obj isKindOfClass:expectedClass]) { NSString *kindOfClass = RCTHumanReadableType(obj); RCTLogError( - @"%@ command %@ received %@ argument of type %@, expected %@.", - componentName, - commandName, - argPos, - kindOfClass, - expectedType); + @"%@ command %@ received %@ argument of type %@, expected %@.", + componentName, + commandName, + argPos, + kindOfClass, + expectedType); return false; } diff --git a/React/Base/RCTVersion.h b/React/Base/RCTVersion.h index b136fd4dba3..5bc858ddf7b 100644 --- a/React/Base/RCTVersion.h +++ b/React/Base/RCTVersion.h @@ -5,14 +5,13 @@ * LICENSE file in the root directory of this source tree. */ - #import #import -RCT_EXTERN NSString* const RCTVersionMajor; -RCT_EXTERN NSString* const RCTVersionMinor; -RCT_EXTERN NSString* const RCTVersionPatch; -RCT_EXTERN NSString* const RCTVersionPrerelease; +RCT_EXTERN NSString *const RCTVersionMajor; +RCT_EXTERN NSString *const RCTVersionMinor; +RCT_EXTERN NSString *const RCTVersionPatch; +RCT_EXTERN NSString *const RCTVersionPrerelease; -RCT_EXTERN NSDictionary* RCTGetReactNativeVersion(void); +RCT_EXTERN NSDictionary *RCTGetReactNativeVersion(void); diff --git a/React/Base/Surface/RCTSurface.h b/React/Base/Surface/RCTSurface.h index 5d459697817..a236bc45447 100644 --- a/React/Base/Surface/RCTSurface.h +++ b/React/Base/Surface/RCTSurface.h @@ -66,8 +66,7 @@ NS_ASSUME_NONNULL_BEGIN /** * Sets `minimumSize` and `maximumSize` layout constraints for the Surface. */ -- (void)setMinimumSize:(CGSize)minimumSize - maximumSize:(CGSize)maximumSize; +- (void)setMinimumSize:(CGSize)minimumSize maximumSize:(CGSize)maximumSize; /** * Previously set `minimumSize` layout constraint. @@ -92,8 +91,7 @@ NS_ASSUME_NONNULL_BEGIN * Measures the Surface with given constraints. * This method does not cause any side effects on the surface object. */ -- (CGSize)sizeThatFitsMinimumSize:(CGSize)minimumSize - maximumSize:(CGSize)maximumSize; +- (CGSize)sizeThatFitsMinimumSize:(CGSize)minimumSize maximumSize:(CGSize)maximumSize; /** * Return the current size of the root view based on (but not clamp by) current @@ -129,7 +127,9 @@ NS_ASSUME_NONNULL_BEGIN * Mount the React component specified by the given moduleName. This is typically * calling runApplication.js from the native side. */ -- (void)mountReactComponentWithBridge:(RCTBridge *)bridge moduleName:(NSString *)moduleName params:(NSDictionary *)params; +- (void)mountReactComponentWithBridge:(RCTBridge *)bridge + moduleName:(NSString *)moduleName + params:(NSDictionary *)params; /** * Unmount the React component specified by the given rootViewTag, called from native. diff --git a/React/Base/Surface/RCTSurface.mm b/React/Base/Surface/RCTSurface.mm index 17897ba3728..0aa7653b9bc 100644 --- a/React/Base/Surface/RCTSurface.mm +++ b/React/Base/Surface/RCTSurface.mm @@ -9,6 +9,7 @@ #import "RCTSurfaceView+Internal.h" #import + #import #import "RCTAssert.h" @@ -57,7 +58,6 @@ atomic_bool _waitingForMountingStageOnMainQueue; } - - (instancetype)initWithBridge:(RCTBridge *)bridge moduleName:(NSString *)moduleName initialProperties:(NSDictionary *)initialProperties @@ -165,14 +165,14 @@ return; } - RCTSurfaceRootView *rootView = - (RCTSurfaceRootView *)[self._uiManager viewForReactTag:self->_rootViewTag]; + RCTSurfaceRootView *rootView = (RCTSurfaceRootView *)[self._uiManager viewForReactTag:self->_rootViewTag]; if (!rootView) { return; } - RCTAssert([rootView isKindOfClass:[RCTSurfaceRootView class]], - @"Received root view is not an instance of `RCTSurfaceRootView`."); + RCTAssert( + [rootView isKindOfClass:[RCTSurfaceRootView class]], + @"Received root view is not an instance of `RCTSurfaceRootView`."); if (rootView.superview != view) { view.rootView = rootView; @@ -297,11 +297,10 @@ return; } - NSDictionary *applicationParameters = - @{ - @"rootTag": _rootViewTag, - @"initialProps": properties, - }; + NSDictionary *applicationParameters = @{ + @"rootTag" : _rootViewTag, + @"initialProps" : properties, + }; RCTLogInfo(@"Running surface %@ (%@)", _moduleName, applicationParameters); @@ -336,33 +335,32 @@ [uiManager registerRootViewTag:self->_rootViewTag]; RCTSurfaceRootShadowView *rootShadowView = - (RCTSurfaceRootShadowView *)[uiManager shadowViewForReactTag:self->_rootViewTag]; - RCTAssert([rootShadowView isKindOfClass:[RCTSurfaceRootShadowView class]], - @"Received shadow view is not an instance of `RCTSurfaceRootShadowView`."); + (RCTSurfaceRootShadowView *)[uiManager shadowViewForReactTag:self->_rootViewTag]; + RCTAssert( + [rootShadowView isKindOfClass:[RCTSurfaceRootShadowView class]], + @"Received shadow view is not an instance of `RCTSurfaceRootShadowView`."); - [rootShadowView setMinimumSize:minimumSize - maximumSize:maximumSize]; + [rootShadowView setMinimumSize:minimumSize maximumSize:maximumSize]; rootShadowView.delegate = self; }); } #pragma mark - Layout -- (CGSize)sizeThatFitsMinimumSize:(CGSize)minimumSize - maximumSize:(CGSize)maximumSize +- (CGSize)sizeThatFitsMinimumSize:(CGSize)minimumSize maximumSize:(CGSize)maximumSize { RCTUIManager *uiManager = self._uiManager; __block CGSize fittingSize; RCTUnsafeExecuteOnUIManagerQueueSync(^{ RCTSurfaceRootShadowView *rootShadowView = - (RCTSurfaceRootShadowView *)[uiManager shadowViewForReactTag:self->_rootViewTag]; + (RCTSurfaceRootShadowView *)[uiManager shadowViewForReactTag:self->_rootViewTag]; - RCTAssert([rootShadowView isKindOfClass:[RCTSurfaceRootShadowView class]], - @"Received shadow view is not an instance of `RCTSurfaceRootShadowView`."); + RCTAssert( + [rootShadowView isKindOfClass:[RCTSurfaceRootShadowView class]], + @"Received shadow view is not an instance of `RCTSurfaceRootShadowView`."); - fittingSize = [rootShadowView sizeThatFitsMinimumSize:minimumSize - maximumSize:maximumSize]; + fittingSize = [rootShadowView sizeThatFitsMinimumSize:minimumSize maximumSize:maximumSize]; }); return fittingSize; @@ -375,13 +373,11 @@ [self setMinimumSize:size maximumSize:size]; } -- (void)setMinimumSize:(CGSize)minimumSize - maximumSize:(CGSize)maximumSize +- (void)setMinimumSize:(CGSize)minimumSize maximumSize:(CGSize)maximumSize { { std::lock_guard lock(_mutex); - if (CGSizeEqualToSize(minimumSize, _minimumSize) && - CGSizeEqualToSize(maximumSize, _maximumSize)) { + if (CGSizeEqualToSize(minimumSize, _minimumSize) && CGSizeEqualToSize(maximumSize, _maximumSize)) { return; } @@ -393,9 +389,10 @@ RCTUnsafeExecuteOnUIManagerQueueSync(^{ RCTSurfaceRootShadowView *rootShadowView = - (RCTSurfaceRootShadowView *)[uiManager shadowViewForReactTag:self->_rootViewTag]; - RCTAssert([rootShadowView isKindOfClass:[RCTSurfaceRootShadowView class]], - @"Received shadow view is not an instance of `RCTSurfaceRootShadowView`."); + (RCTSurfaceRootShadowView *)[uiManager shadowViewForReactTag:self->_rootViewTag]; + RCTAssert( + [rootShadowView isKindOfClass:[RCTSurfaceRootShadowView class]], + @"Received shadow view is not an instance of `RCTSurfaceRootShadowView`."); [rootShadowView setMinimumSize:minimumSize maximumSize:maximumSize]; [uiManager setNeedsLayout]; @@ -470,7 +467,9 @@ semaphore = _uiManagerDidPerformMountingSemaphore; break; default: - RCTAssert(NO, @"Only waiting for `RCTSurfaceStageSurfaceDidInitialRendering`, `RCTSurfaceStageSurfaceDidInitialLayout` and `RCTSurfaceStageSurfaceDidInitialMounting` stages are supported."); + RCTAssert( + NO, + @"Only waiting for `RCTSurfaceStageSurfaceDidInitialRendering`, `RCTSurfaceStageSurfaceDidInitialLayout` and `RCTSurfaceStageSurfaceDidInitialMounting` stages are supported."); } BOOL timeoutOccurred = dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC)); @@ -530,7 +529,7 @@ #pragma mark - RCTUIManagerObserver -- (BOOL)uiManager:(__unused RCTUIManager *) manager performMountingWithBlock:(RCTUIManagerMountingBlock)block +- (BOOL)uiManager:(__unused RCTUIManager *)manager performMountingWithBlock:(RCTUIManagerMountingBlock)block { if (atomic_load(&_waitingForMountingStageOnMainQueue) && (self.stage & RCTSurfaceStageSurfaceDidInitialLayout)) { // Atomic equivalent of `_waitingForMountingStageOnMainQueue = NO;`. @@ -575,14 +574,19 @@ #pragma mark - Mounting/Unmounting of React components -- (void)mountReactComponentWithBridge:(RCTBridge *)bridge moduleName:(NSString *)moduleName params:(NSDictionary *)params +- (void)mountReactComponentWithBridge:(RCTBridge *)bridge + moduleName:(NSString *)moduleName + params:(NSDictionary *)params { - [bridge enqueueJSCall:@"AppRegistry" method:@"runApplication" args:@[moduleName, params] completion:NULL]; + [bridge enqueueJSCall:@"AppRegistry" method:@"runApplication" args:@[ moduleName, params ] completion:NULL]; } - (void)unmountReactComponentWithBridge:(RCTBridge *)bridge rootViewTag:(NSNumber *)rootViewTag { - [bridge enqueueJSCall:@"AppRegistry" method:@"unmountApplicationComponentAtRootTag" args:@[rootViewTag] completion:NULL]; + [bridge enqueueJSCall:@"AppRegistry" + method:@"unmountApplicationComponentAtRootTag" + args:@[ rootViewTag ] + completion:NULL]; } @end diff --git a/React/Base/Surface/RCTSurfaceRootShadowView.m b/React/Base/Surface/RCTSurfaceRootShadowView.m index f69c8be7db9..97525cba479 100644 --- a/React/Base/Surface/RCTSurfaceRootShadowView.m +++ b/React/Base/Surface/RCTSurfaceRootShadowView.m @@ -65,8 +65,7 @@ - (void)setMinimumSize:(CGSize)minimumSize maximumSize:(CGSize)maximumSize { - if (CGSizeEqualToSize(minimumSize, _minimumSize) && - CGSizeEqualToSize(maximumSize, _maximumSize)) { + if (CGSizeEqualToSize(minimumSize, _minimumSize) && CGSizeEqualToSize(maximumSize, _maximumSize)) { return; } diff --git a/React/Base/Surface/RCTSurfaceRootView.mm b/React/Base/Surface/RCTSurfaceRootView.mm index da7bdfe7273..c1b929cd8ae 100644 --- a/React/Base/Surface/RCTSurfaceRootView.mm +++ b/React/Base/Surface/RCTSurfaceRootView.mm @@ -11,6 +11,6 @@ @implementation RCTSurfaceRootView -RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder) +RCT_NOT_IMPLEMENTED(-(nullable instancetype)initWithCoder : (NSCoder *)coder) @end diff --git a/React/Base/Surface/RCTSurfaceStage.h b/React/Base/Surface/RCTSurfaceStage.h index d1e3476b1bd..e48bcef6cfc 100644 --- a/React/Base/Surface/RCTSurfaceStage.h +++ b/React/Base/Surface/RCTSurfaceStage.h @@ -13,14 +13,14 @@ * The stage of the Surface */ typedef NS_OPTIONS(NSInteger, RCTSurfaceStage) { - RCTSurfaceStageSurfaceDidInitialize = 1 << 0, // Surface object was created - RCTSurfaceStageBridgeDidLoad = 1 << 1, // Bridge was loaded - RCTSurfaceStageModuleDidLoad = 1 << 2, // Module (JavaScript code) was loaded - RCTSurfaceStageSurfaceDidRun = 1 << 3, // Module (JavaScript code) was run - RCTSurfaceStageSurfaceDidInitialRendering = 1 << 4, // UIManager created the first shadow views - RCTSurfaceStageSurfaceDidInitialLayout = 1 << 5, // UIManager completed the first layout pass - RCTSurfaceStageSurfaceDidInitialMounting = 1 << 6, // UIManager completed the first mounting pass - RCTSurfaceStageSurfaceDidStop = 1 << 7, // Surface stopped + RCTSurfaceStageSurfaceDidInitialize = 1 << 0, // Surface object was created + RCTSurfaceStageBridgeDidLoad = 1 << 1, // Bridge was loaded + RCTSurfaceStageModuleDidLoad = 1 << 2, // Module (JavaScript code) was loaded + RCTSurfaceStageSurfaceDidRun = 1 << 3, // Module (JavaScript code) was run + RCTSurfaceStageSurfaceDidInitialRendering = 1 << 4, // UIManager created the first shadow views + RCTSurfaceStageSurfaceDidInitialLayout = 1 << 5, // UIManager completed the first layout pass + RCTSurfaceStageSurfaceDidInitialMounting = 1 << 6, // UIManager completed the first mounting pass + RCTSurfaceStageSurfaceDidStop = 1 << 7, // Surface stopped // Most of the previously existed stages make no sense in the new architecture; // now Surface exposes only three simple stages: @@ -30,7 +30,8 @@ typedef NS_OPTIONS(NSInteger, RCTSurfaceStage) { // Surface was started. RCTSurfaceStageStarted = 1 << 8, // All off-main-thread work is done; we are ready to mount the UI. - RCTSurfaceStagePrepared = RCTSurfaceStageBridgeDidLoad | RCTSurfaceStageModuleDidLoad | RCTSurfaceStageSurfaceDidRun | RCTSurfaceStageSurfaceDidInitialRendering | RCTSurfaceStageSurfaceDidInitialLayout, + RCTSurfaceStagePrepared = RCTSurfaceStageBridgeDidLoad | RCTSurfaceStageModuleDidLoad | RCTSurfaceStageSurfaceDidRun | + RCTSurfaceStageSurfaceDidInitialRendering | RCTSurfaceStageSurfaceDidInitialLayout, // All main-thread work is done, the UI was mounted. RCTSurfaceStageMounted = RCTSurfaceStageSurfaceDidInitialMounting, }; diff --git a/React/Base/Surface/RCTSurfaceStage.m b/React/Base/Surface/RCTSurfaceStage.m index b5f879a099b..d9760a1e1fe 100644 --- a/React/Base/Surface/RCTSurfaceStage.m +++ b/React/Base/Surface/RCTSurfaceStage.m @@ -7,14 +7,12 @@ #import "RCTSurfaceStage.h" -BOOL RCTSurfaceStageIsRunning(RCTSurfaceStage stage) { - return - (stage & RCTSurfaceStageSurfaceDidInitialLayout) && - !(stage & RCTSurfaceStageSurfaceDidStop); +BOOL RCTSurfaceStageIsRunning(RCTSurfaceStage stage) +{ + return (stage & RCTSurfaceStageSurfaceDidInitialLayout) && !(stage & RCTSurfaceStageSurfaceDidStop); } -BOOL RCTSurfaceStageIsPreparing(RCTSurfaceStage stage) { - return - !(stage & RCTSurfaceStageSurfaceDidInitialLayout) && - !(stage & RCTSurfaceStageSurfaceDidStop); +BOOL RCTSurfaceStageIsPreparing(RCTSurfaceStage stage) +{ + return !(stage & RCTSurfaceStageSurfaceDidInitialLayout) && !(stage & RCTSurfaceStageSurfaceDidStop); } diff --git a/React/Base/Surface/RCTSurfaceView.mm b/React/Base/Surface/RCTSurfaceView.mm index 38c60dc4162..4a5e35a4754 100644 --- a/React/Base/Surface/RCTSurfaceView.mm +++ b/React/Base/Surface/RCTSurfaceView.mm @@ -17,9 +17,9 @@ RCTSurfaceStage _stage; } -RCT_NOT_IMPLEMENTED(- (instancetype)init) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) -RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder) +RCT_NOT_IMPLEMENTED(-(instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +RCT_NOT_IMPLEMENTED(-(nullable instancetype)initWithCoder : (NSCoder *)coder) - (instancetype)initWithSurface:(RCTSurface *)surface { @@ -75,8 +75,7 @@ RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder) if (_rootView.superview != self) { [self addSubview:_rootView]; } - } - else { + } else { [_rootView removeFromSuperview]; } } diff --git a/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingProxyRootView.h b/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingProxyRootView.h index d9860699c29..15b1cd07bf0 100644 --- a/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingProxyRootView.h +++ b/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingProxyRootView.h @@ -46,12 +46,10 @@ NS_ASSUME_NONNULL_BEGIN launchOptions:(NSDictionary *)launchOptions; - (instancetype)initWithSurface:(RCTSurface *)surface - sizeMeasureMode:(RCTSurfaceSizeMeasureMode)sizeMeasureMode - NS_UNAVAILABLE; + sizeMeasureMode:(RCTSurfaceSizeMeasureMode)sizeMeasureMode NS_UNAVAILABLE; - (void)cancelTouches; @end NS_ASSUME_NONNULL_END - diff --git a/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingProxyRootView.mm b/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingProxyRootView.mm index bf7e9e4fa91..5db63e44b95 100644 --- a/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingProxyRootView.mm +++ b/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingProxyRootView.mm @@ -19,7 +19,8 @@ #import "RCTSurface.h" #import "UIView+React.h" -static RCTSurfaceSizeMeasureMode convertToSurfaceSizeMeasureMode(RCTRootViewSizeFlexibility sizeFlexibility) { +static RCTSurfaceSizeMeasureMode convertToSurfaceSizeMeasureMode(RCTRootViewSizeFlexibility sizeFlexibility) +{ switch (sizeFlexibility) { case RCTRootViewSizeFlexibilityWidthAndHeight: return RCTSurfaceSizeMeasureModeWidthUndefined | RCTSurfaceSizeMeasureModeHeightUndefined; @@ -32,7 +33,8 @@ static RCTSurfaceSizeMeasureMode convertToSurfaceSizeMeasureMode(RCTRootViewSize } } -static RCTRootViewSizeFlexibility convertToRootViewSizeFlexibility(RCTSurfaceSizeMeasureMode sizeMeasureMode) { +static RCTRootViewSizeFlexibility convertToRootViewSizeFlexibility(RCTSurfaceSizeMeasureMode sizeMeasureMode) +{ switch (sizeMeasureMode) { case RCTSurfaceSizeMeasureModeWidthUndefined | RCTSurfaceSizeMeasureModeHeightUndefined: return RCTRootViewSizeFlexibilityWidthAndHeight; @@ -67,7 +69,9 @@ static RCTRootViewSizeFlexibility convertToRootViewSizeFlexibility(RCTSurfaceSiz // `RCTRootViewSizeFlexibilityNone` is the RCTRootView's default. RCTSurfaceSizeMeasureMode sizeMeasureMode = convertToSurfaceSizeMeasureMode(RCTRootViewSizeFlexibilityNone); - RCTSurface *surface = [[self class] createSurfaceWithBridge:bridge moduleName:moduleName initialProperties:initialProperties]; + RCTSurface *surface = [[self class] createSurfaceWithBridge:bridge + moduleName:moduleName + initialProperties:initialProperties]; [surface start]; if (self = [super initWithSurface:surface sizeMeasureMode:sizeMeasureMode]) { self.backgroundColor = [UIColor whiteColor]; @@ -83,17 +87,15 @@ static RCTRootViewSizeFlexibility convertToRootViewSizeFlexibility(RCTSurfaceSiz initialProperties:(NSDictionary *)initialProperties launchOptions:(NSDictionary *)launchOptions { - RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:bundleURL - moduleProvider:nil - launchOptions:launchOptions]; + RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:bundleURL moduleProvider:nil launchOptions:launchOptions]; return [self initWithBridge:bridge moduleName:moduleName initialProperties:initialProperties]; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) -# pragma mark proxy methods to RCTSurfaceHostingView +#pragma mark proxy methods to RCTSurfaceHostingView - (NSString *)moduleName { @@ -137,7 +139,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) - (void)setLoadingView:(UIView *)loadingView { - super.activityIndicatorViewFactory = ^UIView *(void) { + super.activityIndicatorViewFactory = ^UIView *(void) + { return loadingView; }; } @@ -150,8 +153,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) if (RCTSurfaceStageIsRunning(stage)) { [_bridge.performanceLogger markStopForTag:RCTPLTTI]; dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:RCTContentDidAppearNotification - object:self]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTContentDidAppearNotification object:self]; }); } } @@ -178,4 +180,3 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) } @end - diff --git a/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.h b/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.h index b402d708df8..a2681a802ba 100644 --- a/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.h +++ b/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.h @@ -14,7 +14,7 @@ @class RCTBridge; @class RCTSurface; -typedef UIView *_Nullable(^RCTSurfaceHostingViewActivityIndicatorViewFactory)(void); +typedef UIView *_Nullable (^RCTSurfaceHostingViewActivityIndicatorViewFactory)(void); NS_ASSUME_NONNULL_BEGIN diff --git a/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.mm b/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.mm index 4b131ce0f63..c90fbb301f4 100644 --- a/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.mm +++ b/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.mm @@ -34,16 +34,18 @@ return [[RCTSurface alloc] initWithBridge:bridge moduleName:moduleName initialProperties:initialProperties]; } -RCT_NOT_IMPLEMENTED(- (instancetype)init) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) -RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder) +RCT_NOT_IMPLEMENTED(-(instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +RCT_NOT_IMPLEMENTED(-(nullable instancetype)initWithCoder : (NSCoder *)coder) - (instancetype)initWithBridge:(RCTBridge *)bridge moduleName:(NSString *)moduleName initialProperties:(NSDictionary *)initialProperties sizeMeasureMode:(RCTSurfaceSizeMeasureMode)sizeMeasureMode { - RCTSurface *surface = [[self class] createSurfaceWithBridge:bridge moduleName:moduleName initialProperties:initialProperties]; + RCTSurface *surface = [[self class] createSurfaceWithBridge:bridge + moduleName:moduleName + initialProperties:initialProperties]; [surface start]; return [self initWithSurface:surface sizeMeasureMode:sizeMeasureMode]; } @@ -75,14 +77,9 @@ RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder) CGSize maximumSize; RCTSurfaceMinimumSizeAndMaximumSizeFromSizeAndSizeMeasureMode( - self.bounds.size, - _sizeMeasureMode, - &minimumSize, - &maximumSize - ); + self.bounds.size, _sizeMeasureMode, &minimumSize, &maximumSize); - [_surface setMinimumSize:minimumSize - maximumSize:maximumSize]; + [_surface setMinimumSize:minimumSize maximumSize:maximumSize]; } - (CGSize)intrinsicContentSize @@ -111,15 +108,9 @@ RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder) CGSize minimumSize; CGSize maximumSize; - RCTSurfaceMinimumSizeAndMaximumSizeFromSizeAndSizeMeasureMode( - size, - _sizeMeasureMode, - &minimumSize, - &maximumSize - ); + RCTSurfaceMinimumSizeAndMaximumSizeFromSizeAndSizeMeasureMode(size, _sizeMeasureMode, &minimumSize, &maximumSize); - return [_surface sizeThatFitsMinimumSize:minimumSize - maximumSize:maximumSize]; + return [_surface sizeThatFitsMinimumSize:minimumSize maximumSize:maximumSize]; } - (void)setStage:(RCTSurfaceStage)stage @@ -128,9 +119,8 @@ RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder) return; } - BOOL shouldInvalidateLayout = - RCTSurfaceStageIsRunning(stage) != RCTSurfaceStageIsRunning(_stage) || - RCTSurfaceStageIsPreparing(stage) != RCTSurfaceStageIsPreparing(_stage); + BOOL shouldInvalidateLayout = RCTSurfaceStageIsRunning(stage) != RCTSurfaceStageIsRunning(_stage) || + RCTSurfaceStageIsPreparing(stage) != RCTSurfaceStageIsPreparing(_stage); _stage = stage; @@ -210,11 +200,12 @@ RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder) - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { [super traitCollectionDidChange:previousTraitCollection]; - [[NSNotificationCenter defaultCenter] postNotificationName:RCTUserInterfaceStyleDidChangeNotification - object:self - userInfo:@{ - RCTUserInterfaceStyleDidChangeNotificationTraitCollectionKey: self.traitCollection, - }]; + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTUserInterfaceStyleDidChangeNotification + object:self + userInfo:@{ + RCTUserInterfaceStyleDidChangeNotificationTraitCollectionKey : self.traitCollection, + }]; } #pragma mark - Private stuff diff --git a/React/Base/Surface/SurfaceHostingView/RCTSurfaceSizeMeasureMode.h b/React/Base/Surface/SurfaceHostingView/RCTSurfaceSizeMeasureMode.h index 43c8b8627c6..0ca27cd0944 100644 --- a/React/Base/Surface/SurfaceHostingView/RCTSurfaceSizeMeasureMode.h +++ b/React/Base/Surface/SurfaceHostingView/RCTSurfaceSizeMeasureMode.h @@ -14,20 +14,19 @@ * are translated to `-[RCTSurface sizeThatFitsMinimumSize:maximumSize:]`. */ typedef NS_OPTIONS(NSInteger, RCTSurfaceSizeMeasureMode) { - RCTSurfaceSizeMeasureModeWidthUndefined = 0 << 0, - RCTSurfaceSizeMeasureModeWidthExact = 1 << 0, - RCTSurfaceSizeMeasureModeWidthAtMost = 2 << 0, - RCTSurfaceSizeMeasureModeHeightUndefined = 0 << 2, - RCTSurfaceSizeMeasureModeHeightExact = 1 << 2, - RCTSurfaceSizeMeasureModeHeightAtMost = 2 << 2, + RCTSurfaceSizeMeasureModeWidthUndefined = 0 << 0, + RCTSurfaceSizeMeasureModeWidthExact = 1 << 0, + RCTSurfaceSizeMeasureModeWidthAtMost = 2 << 0, + RCTSurfaceSizeMeasureModeHeightUndefined = 0 << 2, + RCTSurfaceSizeMeasureModeHeightExact = 1 << 2, + RCTSurfaceSizeMeasureModeHeightAtMost = 2 << 2, }; /** * Returns size constraints based on `size` and `sizeMeasureMode`. */ RCT_EXTERN void RCTSurfaceMinimumSizeAndMaximumSizeFromSizeAndSizeMeasureMode( - CGSize size, - RCTSurfaceSizeMeasureMode sizeMeasureMode, - CGSize *minimumSize, - CGSize *maximumSize -); + CGSize size, + RCTSurfaceSizeMeasureMode sizeMeasureMode, + CGSize *minimumSize, + CGSize *maximumSize); diff --git a/React/Base/Surface/SurfaceHostingView/RCTSurfaceSizeMeasureMode.mm b/React/Base/Surface/SurfaceHostingView/RCTSurfaceSizeMeasureMode.mm index fc212b321cc..0a88f4db7fe 100644 --- a/React/Base/Surface/SurfaceHostingView/RCTSurfaceSizeMeasureMode.mm +++ b/React/Base/Surface/SurfaceHostingView/RCTSurfaceSizeMeasureMode.mm @@ -10,27 +10,25 @@ #import "RCTSurfaceSizeMeasureMode.h" void RCTSurfaceMinimumSizeAndMaximumSizeFromSizeAndSizeMeasureMode( - CGSize size, - RCTSurfaceSizeMeasureMode sizeMeasureMode, - CGSize *minimumSize, - CGSize *maximumSize -) { + CGSize size, + RCTSurfaceSizeMeasureMode sizeMeasureMode, + CGSize *minimumSize, + CGSize *maximumSize) +{ *minimumSize = CGSizeZero; *maximumSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX); if (sizeMeasureMode & RCTSurfaceSizeMeasureModeWidthExact) { minimumSize->width = size.width; maximumSize->width = size.width; - } - else if (sizeMeasureMode & RCTSurfaceSizeMeasureModeWidthAtMost) { + } else if (sizeMeasureMode & RCTSurfaceSizeMeasureModeWidthAtMost) { maximumSize->width = size.width; } if (sizeMeasureMode & RCTSurfaceSizeMeasureModeHeightExact) { minimumSize->height = size.height; maximumSize->height = size.height; - } - else if (sizeMeasureMode & RCTSurfaceSizeMeasureModeHeightAtMost) { + } else if (sizeMeasureMode & RCTSurfaceSizeMeasureModeHeightAtMost) { maximumSize->height = size.height; } } diff --git a/React/CoreModules/RCTAccessibilityManager.mm b/React/CoreModules/RCTAccessibilityManager.mm index bd25db4ce89..e7c6e15c256 100644 --- a/React/CoreModules/RCTAccessibilityManager.mm +++ b/React/CoreModules/RCTAccessibilityManager.mm @@ -8,15 +8,16 @@ #import "RCTAccessibilityManager.h" #import -#import #import #import #import #import +#import #import "CoreModulesPlugins.h" -NSString *const RCTAccessibilityManagerDidUpdateMultiplierNotification = @"RCTAccessibilityManagerDidUpdateMultiplierNotification"; +NSString *const RCTAccessibilityManagerDidUpdateMultiplierNotification = + @"RCTAccessibilityManagerDidUpdateMultiplierNotification"; @interface RCTAccessibilityManager () @@ -103,13 +104,14 @@ RCT_EXPORT_MODULE() { NSDictionary *userInfo = notification.userInfo; // Response dictionary to populate the event with. - NSDictionary *response = @{@"announcement": userInfo[UIAccessibilityAnnouncementKeyStringValue], - @"success": userInfo[UIAccessibilityAnnouncementKeyWasSuccessful]}; + NSDictionary *response = @{ + @"announcement" : userInfo[UIAccessibilityAnnouncementKeyStringValue], + @"success" : userInfo[UIAccessibilityAnnouncementKeyWasSuccessful] + }; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"announcementFinished" - body:response]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"announcementFinished" body:response]; #pragma clang diagnostic pop } @@ -120,8 +122,7 @@ RCT_EXPORT_MODULE() _isBoldTextEnabled = newBoldTextEnabled; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"boldTextChanged" - body:@(_isBoldTextEnabled)]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"boldTextChanged" body:@(_isBoldTextEnabled)]; #pragma clang diagnostic pop } } @@ -133,8 +134,7 @@ RCT_EXPORT_MODULE() _isGrayscaleEnabled = newGrayscaleEnabled; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"grayscaleChanged" - body:@(_isGrayscaleEnabled)]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"grayscaleChanged" body:@(_isGrayscaleEnabled)]; #pragma clang diagnostic pop } } @@ -146,8 +146,7 @@ RCT_EXPORT_MODULE() _isInvertColorsEnabled = newInvertColorsEnabled; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"invertColorsChanged" - body:@(_isInvertColorsEnabled)]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"invertColorsChanged" body:@(_isInvertColorsEnabled)]; #pragma clang diagnostic pop } } @@ -159,8 +158,7 @@ RCT_EXPORT_MODULE() _isReduceMotionEnabled = newReduceMotionEnabled; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"reduceMotionChanged" - body:@(_isReduceMotionEnabled)]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"reduceMotionChanged" body:@(_isReduceMotionEnabled)]; #pragma clang diagnostic pop } } @@ -172,8 +170,7 @@ RCT_EXPORT_MODULE() _isReduceTransparencyEnabled = newReduceTransparencyEnabled; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"reduceTransparencyChanged" - body:@(_isReduceTransparencyEnabled)]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"reduceTransparencyChanged" body:@(_isReduceTransparencyEnabled)]; #pragma clang diagnostic pop } } @@ -185,8 +182,7 @@ RCT_EXPORT_MODULE() _isVoiceOverEnabled = newIsVoiceOverEnabled; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"screenReaderChanged" - body:@(_isVoiceOverEnabled)]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"screenReaderChanged" body:@(_isVoiceOverEnabled)]; #pragma clang diagnostic pop } } @@ -202,7 +198,8 @@ RCT_EXPORT_MODULE() - (void)invalidateMultiplier { self.multiplier = [self multiplierForContentSizeCategory:_contentSizeCategory]; - [[NSNotificationCenter defaultCenter] postNotificationName:RCTAccessibilityManagerDidUpdateMultiplierNotification object:self]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTAccessibilityManagerDidUpdateMultiplierNotification + object:self]; } - (CGFloat)multiplierForContentSizeCategory:(NSString *)category @@ -226,23 +223,27 @@ RCT_EXPORT_MODULE() - (NSDictionary *)multipliers { if (_multipliers == nil) { - _multipliers = @{UIContentSizeCategoryExtraSmall: @0.823, - UIContentSizeCategorySmall: @0.882, - UIContentSizeCategoryMedium: @0.941, - UIContentSizeCategoryLarge: @1.0, - UIContentSizeCategoryExtraLarge: @1.118, - UIContentSizeCategoryExtraExtraLarge: @1.235, - UIContentSizeCategoryExtraExtraExtraLarge: @1.353, - UIContentSizeCategoryAccessibilityMedium: @1.786, - UIContentSizeCategoryAccessibilityLarge: @2.143, - UIContentSizeCategoryAccessibilityExtraLarge: @2.643, - UIContentSizeCategoryAccessibilityExtraExtraLarge: @3.143, - UIContentSizeCategoryAccessibilityExtraExtraExtraLarge: @3.571}; + _multipliers = @{ + UIContentSizeCategoryExtraSmall : @0.823, + UIContentSizeCategorySmall : @0.882, + UIContentSizeCategoryMedium : @0.941, + UIContentSizeCategoryLarge : @1.0, + UIContentSizeCategoryExtraLarge : @1.118, + UIContentSizeCategoryExtraExtraLarge : @1.235, + UIContentSizeCategoryExtraExtraExtraLarge : @1.353, + UIContentSizeCategoryAccessibilityMedium : @1.786, + UIContentSizeCategoryAccessibilityLarge : @2.143, + UIContentSizeCategoryAccessibilityExtraLarge : @2.643, + UIContentSizeCategoryAccessibilityExtraExtraLarge : @3.143, + UIContentSizeCategoryAccessibilityExtraExtraExtraLarge : @3.571 + }; } return _multipliers; } -RCT_EXPORT_METHOD(setAccessibilityContentSizeMultipliers:(JS::NativeAccessibilityManager::SpecSetAccessibilityContentSizeMultipliersJSMultipliers &)JSMultipliers) +RCT_EXPORT_METHOD(setAccessibilityContentSizeMultipliers + : (JS::NativeAccessibilityManager::SpecSetAccessibilityContentSizeMultipliersJSMultipliers &) + JSMultipliers) { NSMutableDictionary *multipliers = [NSMutableDictionary new]; setMultipliers(multipliers, UIContentSizeCategoryExtraSmall, JSMultipliers.extraSmall()); @@ -255,23 +256,26 @@ RCT_EXPORT_METHOD(setAccessibilityContentSizeMultipliers:(JS::NativeAccessibilit setMultipliers(multipliers, UIContentSizeCategoryAccessibilityMedium, JSMultipliers.accessibilityMedium()); setMultipliers(multipliers, UIContentSizeCategoryAccessibilityLarge, JSMultipliers.accessibilityLarge()); setMultipliers(multipliers, UIContentSizeCategoryAccessibilityExtraLarge, JSMultipliers.accessibilityExtraLarge()); - setMultipliers(multipliers, UIContentSizeCategoryAccessibilityExtraExtraLarge, - JSMultipliers.accessibilityExtraExtraLarge()); - setMultipliers(multipliers, UIContentSizeCategoryAccessibilityExtraExtraExtraLarge, - JSMultipliers.accessibilityExtraExtraExtraLarge()); + setMultipliers( + multipliers, UIContentSizeCategoryAccessibilityExtraExtraLarge, JSMultipliers.accessibilityExtraExtraLarge()); + setMultipliers( + multipliers, + UIContentSizeCategoryAccessibilityExtraExtraExtraLarge, + JSMultipliers.accessibilityExtraExtraExtraLarge()); self.multipliers = multipliers; } -static void setMultipliers(NSMutableDictionary *multipliers, - NSString *key, - folly::Optional optionalDouble) +static void setMultipliers( + NSMutableDictionary *multipliers, + NSString *key, + folly::Optional optionalDouble) { if (optionalDouble.hasValue()) { multipliers[key] = @(optionalDouble.value()); } } -RCT_EXPORT_METHOD(setAccessibilityFocus:(double)reactTag) +RCT_EXPORT_METHOD(setAccessibilityFocus : (double)reactTag) { dispatch_async(dispatch_get_main_queue(), ^{ UIView *view = [self.bridge.uiManager viewForReactTag:@(reactTag)]; @@ -279,57 +283,62 @@ RCT_EXPORT_METHOD(setAccessibilityFocus:(double)reactTag) }); } -RCT_EXPORT_METHOD(announceForAccessibility:(NSString *)announcement) +RCT_EXPORT_METHOD(announceForAccessibility : (NSString *)announcement) { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, announcement); } -RCT_EXPORT_METHOD(getMultiplier:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(getMultiplier : (RCTResponseSenderBlock)callback) { if (callback) { callback(@[ @(self.multiplier) ]); } } -RCT_EXPORT_METHOD(getCurrentBoldTextState:(RCTResponseSenderBlock)onSuccess - onError:(__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD(getCurrentBoldTextState + : (RCTResponseSenderBlock)onSuccess onError + : (__unused RCTResponseSenderBlock)onError) { - onSuccess(@[@(_isBoldTextEnabled)]); + onSuccess(@[ @(_isBoldTextEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentGrayscaleState:(RCTResponseSenderBlock)onSuccess - onError:(__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD(getCurrentGrayscaleState + : (RCTResponseSenderBlock)onSuccess onError + : (__unused RCTResponseSenderBlock)onError) { - onSuccess(@[@(_isGrayscaleEnabled)]); + onSuccess(@[ @(_isGrayscaleEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentInvertColorsState:(RCTResponseSenderBlock)onSuccess - onError:(__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD(getCurrentInvertColorsState + : (RCTResponseSenderBlock)onSuccess onError + : (__unused RCTResponseSenderBlock)onError) { - onSuccess(@[@(_isInvertColorsEnabled)]); + onSuccess(@[ @(_isInvertColorsEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentReduceMotionState:(RCTResponseSenderBlock)onSuccess - onError:(__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD(getCurrentReduceMotionState + : (RCTResponseSenderBlock)onSuccess onError + : (__unused RCTResponseSenderBlock)onError) { - onSuccess(@[@(_isReduceMotionEnabled)]); + onSuccess(@[ @(_isReduceMotionEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentReduceTransparencyState:(RCTResponseSenderBlock)onSuccess - onError:(__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD(getCurrentReduceTransparencyState + : (RCTResponseSenderBlock)onSuccess onError + : (__unused RCTResponseSenderBlock)onError) { - onSuccess(@[@(_isReduceTransparencyEnabled)]); + onSuccess(@[ @(_isReduceTransparencyEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentVoiceOverState:(RCTResponseSenderBlock)onSuccess - onError:(__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD(getCurrentVoiceOverState + : (RCTResponseSenderBlock)onSuccess onError + : (__unused RCTResponseSenderBlock)onError) { - onSuccess(@[@(_isVoiceOverEnabled)]); + onSuccess(@[ @(_isVoiceOverEnabled) ]); } - - (std::shared_ptr)getTurboModuleWithJsInvoker: -(std::shared_ptr)jsInvoker + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } diff --git a/React/CoreModules/RCTActionSheetManager.mm b/React/CoreModules/RCTActionSheetManager.mm index 9ca746a40b6..9a88c68153b 100644 --- a/React/CoreModules/RCTActionSheetManager.mm +++ b/React/CoreModules/RCTActionSheetManager.mm @@ -23,8 +23,7 @@ using namespace facebook::react; @interface RCTActionSheetManager () @end -@implementation RCTActionSheetManager -{ +@implementation RCTActionSheetManager { // Use NSMapTable, as UIAlertViews do not implement // which is required for NSDictionary keys NSMapTable *_callbacks; @@ -56,8 +55,9 @@ RCT_EXPORT_MODULE() [parentViewController presentViewController:alertController animated:YES completion:nil]; } -RCT_EXPORT_METHOD(showActionSheetWithOptions:(JS::NativeActionSheetManager::SpecShowActionSheetWithOptionsOptions &)options - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(showActionSheetWithOptions + : (JS::NativeActionSheetManager::SpecShowActionSheetWithOptionsOptions &)options callback + : (RCTResponseSenderBlock)callback) { if (RCTRunningInAppExtension()) { RCTLogError(@"Unable to show action sheet from app extension"); @@ -70,14 +70,19 @@ RCT_EXPORT_METHOD(showActionSheetWithOptions:(JS::NativeActionSheetManager::Spec NSString *title = options.title(); NSString *message = options.message(); - NSArray *buttons = RCTConvertOptionalVecToArray(options.options(), ^id(NSString *element) { return element; }); - NSInteger cancelButtonIndex = options.cancelButtonIndex() ? [RCTConvert NSInteger:@(*options.cancelButtonIndex())] : -1; + NSArray *buttons = RCTConvertOptionalVecToArray(options.options(), ^id(NSString *element) { + return element; + }); + NSInteger cancelButtonIndex = + options.cancelButtonIndex() ? [RCTConvert NSInteger:@(*options.cancelButtonIndex())] : -1; NSArray *destructiveButtonIndices; if (options.destructiveButtonIndices()) { - destructiveButtonIndices = RCTConvertVecToArray(*options.destructiveButtonIndices(), ^id(double element) { return @(element); }); + destructiveButtonIndices = RCTConvertVecToArray(*options.destructiveButtonIndices(), ^id(double element) { + return @(element); + }); } else { NSNumber *destructiveButtonIndex = @-1; - destructiveButtonIndices = @[destructiveButtonIndex]; + destructiveButtonIndices = @[ destructiveButtonIndex ]; } UIViewController *controller = RCTPresentedViewController(); @@ -86,13 +91,13 @@ RCT_EXPORT_METHOD(showActionSheetWithOptions:(JS::NativeActionSheetManager::Spec if (controller == nil) { RCTLogError(@"Tried to display action sheet but there is no application window. options: %@", @{ - @"title": title, - @"message": message, - @"options": buttons, - @"cancelButtonIndex": @(cancelButtonIndex), - @"destructiveButtonIndices": destructiveButtonIndices, - @"anchor": anchor, - @"tintColor": tintColor, + @"title" : title, + @"message" : message, + @"options" : buttons, + @"cancelButtonIndex" : @(cancelButtonIndex), + @"destructiveButtonIndices" : destructiveButtonIndices, + @"anchor" : anchor, + @"tintColor" : tintColor, }); return; } @@ -104,10 +109,9 @@ RCT_EXPORT_METHOD(showActionSheetWithOptions:(JS::NativeActionSheetManager::Spec */ NSNumber *anchorViewTag = anchor; - UIAlertController *alertController = - [UIAlertController alertControllerWithTitle:title - message:message - preferredStyle:UIAlertControllerStyleActionSheet]; + UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title + message:message + preferredStyle:UIAlertControllerStyleActionSheet]; NSInteger index = 0; for (NSString *option in buttons) { @@ -121,16 +125,16 @@ RCT_EXPORT_METHOD(showActionSheetWithOptions:(JS::NativeActionSheetManager::Spec NSInteger localIndex = index; [alertController addAction:[UIAlertAction actionWithTitle:option style:style - handler:^(__unused UIAlertAction *action){ - callback(@[@(localIndex)]); - }]]; + handler:^(__unused UIAlertAction *action) { + callback(@[ @(localIndex) ]); + }]]; index++; } alertController.view.tintColor = tintColor; #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ -__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 + __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 if (@available(iOS 13.0, *)) { NSString *userInterfaceStyle = [RCTConvert NSString:options.userInterfaceStyle()]; @@ -147,9 +151,10 @@ __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 [self presentViewController:alertController onParentViewController:controller anchorViewTag:anchorViewTag]; } -RCT_EXPORT_METHOD(showShareActionSheetWithOptions:(JS::NativeActionSheetManager::SpecShowShareActionSheetWithOptionsOptions &)options - failureCallback:(RCTResponseSenderBlock)failureCallback - successCallback:(RCTResponseSenderBlock)successCallback) +RCT_EXPORT_METHOD(showShareActionSheetWithOptions + : (JS::NativeActionSheetManager::SpecShowShareActionSheetWithOptionsOptions &)options failureCallback + : (RCTResponseSenderBlock)failureCallback successCallback + : (RCTResponseSenderBlock)successCallback) { if (RCTRunningInAppExtension()) { RCTLogError(@"Unable to show action sheet from app extension"); @@ -165,11 +170,9 @@ RCT_EXPORT_METHOD(showShareActionSheetWithOptions:(JS::NativeActionSheetManager: if (URL) { if ([URL.scheme.lowercaseString isEqualToString:@"data"]) { NSError *error; - NSData *data = [NSData dataWithContentsOfURL:URL - options:(NSDataReadingOptions)0 - error:&error]; + NSData *data = [NSData dataWithContentsOfURL:URL options:(NSDataReadingOptions)0 error:&error]; if (!data) { - failureCallback(@[RCTJSErrorFromNSError(error)]); + failureCallback(@[ RCTJSErrorFromNSError(error) ]); return; } [items addObject:data]; @@ -182,32 +185,37 @@ RCT_EXPORT_METHOD(showShareActionSheetWithOptions:(JS::NativeActionSheetManager: return; } - UIActivityViewController *shareController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil]; + UIActivityViewController *shareController = [[UIActivityViewController alloc] initWithActivityItems:items + applicationActivities:nil]; NSString *subject = options.subject(); if (subject) { [shareController setValue:subject forKey:@"subject"]; } - NSArray *excludedActivityTypes = RCTConvertOptionalVecToArray(options.excludedActivityTypes(), ^id(NSString *element) { return element; }); + NSArray *excludedActivityTypes = + RCTConvertOptionalVecToArray(options.excludedActivityTypes(), ^id(NSString *element) { + return element; + }); if (excludedActivityTypes) { shareController.excludedActivityTypes = excludedActivityTypes; } UIViewController *controller = RCTPresentedViewController(); - shareController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, __unused NSArray *returnedItems, NSError *activityError) { - if (activityError) { - failureCallback(@[RCTJSErrorFromNSError(activityError)]); - } else if (completed || activityType == nil) { - successCallback(@[@(completed), RCTNullIfNil(activityType)]); - } - }; + shareController.completionWithItemsHandler = + ^(NSString *activityType, BOOL completed, __unused NSArray *returnedItems, NSError *activityError) { + if (activityError) { + failureCallback(@[ RCTJSErrorFromNSError(activityError) ]); + } else if (completed || activityType == nil) { + successCallback(@[ @(completed), RCTNullIfNil(activityType) ]); + } + }; NSNumber *anchorViewTag = [RCTConvert NSNumber:options.anchor() ? @(*options.anchor()) : nil]; shareController.view.tintColor = [RCTConvert UIColor:options.tintColor() ? @(*options.tintColor()) : nil]; #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ -__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 + __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 if (@available(iOS 13.0, *)) { NSString *userInterfaceStyle = [RCTConvert NSString:options.userInterfaceStyle()]; @@ -231,6 +239,7 @@ __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 @end -Class RCTActionSheetManagerCls(void) { +Class RCTActionSheetManagerCls(void) +{ return RCTActionSheetManager.class; } diff --git a/React/CoreModules/RCTAlertManager.h b/React/CoreModules/RCTAlertManager.h index dd49e88de1e..8ea1d9b0204 100644 --- a/React/CoreModules/RCTAlertManager.h +++ b/React/CoreModules/RCTAlertManager.h @@ -17,7 +17,6 @@ typedef NS_ENUM(NSInteger, RCTAlertViewStyle) { RCTAlertViewStyleLoginAndPasswordInput }; - @interface RCTAlertManager : NSObject @end diff --git a/React/CoreModules/RCTAlertManager.mm b/React/CoreModules/RCTAlertManager.mm index 91c236a6da1..ef26c83d8a6 100644 --- a/React/CoreModules/RCTAlertManager.mm +++ b/React/CoreModules/RCTAlertManager.mm @@ -18,21 +18,24 @@ @implementation RCTConvert (UIAlertViewStyle) -RCT_ENUM_CONVERTER(RCTAlertViewStyle, (@{ - @"default": @(RCTAlertViewStyleDefault), - @"secure-text": @(RCTAlertViewStyleSecureTextInput), - @"plain-text": @(RCTAlertViewStylePlainTextInput), - @"login-password": @(RCTAlertViewStyleLoginAndPasswordInput), -}), RCTAlertViewStyleDefault, integerValue) +RCT_ENUM_CONVERTER( + RCTAlertViewStyle, + (@{ + @"default" : @(RCTAlertViewStyleDefault), + @"secure-text" : @(RCTAlertViewStyleSecureTextInput), + @"plain-text" : @(RCTAlertViewStylePlainTextInput), + @"login-password" : @(RCTAlertViewStyleLoginAndPasswordInput), + }), + RCTAlertViewStyleDefault, + integerValue) @end -@interface RCTAlertManager() +@interface RCTAlertManager () @end -@implementation RCTAlertManager -{ +@implementation RCTAlertManager { NSHashTable *_alertControllers; } @@ -64,13 +67,15 @@ RCT_EXPORT_MODULE() * The key from the `buttons` dictionary is passed back in the callback on click. * Buttons are displayed in the order they are specified. */ -RCT_EXPORT_METHOD(alertWithArgs:(JS::NativeAlertManager::Args &)args - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(alertWithArgs : (JS::NativeAlertManager::Args &)args callback : (RCTResponseSenderBlock)callback) { NSString *title = [RCTConvert NSString:args.title()]; NSString *message = [RCTConvert NSString:args.message()]; RCTAlertViewStyle type = [RCTConvert RCTAlertViewStyle:args.type()]; - NSArray *buttons = [RCTConvert NSDictionaryArray:RCTConvertOptionalVecToArray(args.buttons(), ^id(id element) { return element; })]; + NSArray *buttons = + [RCTConvert NSDictionaryArray:RCTConvertOptionalVecToArray(args.buttons(), ^id(id element) { + return element; + })]; NSString *defaultValue = [RCTConvert NSString:args.defaultValue()]; NSString *cancelButtonKey = [RCTConvert NSString:args.cancelButtonKey()]; NSString *destructiveButtonKey = [RCTConvert NSString:args.destructiveButtonKey()]; @@ -83,12 +88,12 @@ RCT_EXPORT_METHOD(alertWithArgs:(JS::NativeAlertManager::Args &)args if (buttons.count == 0) { if (type == RCTAlertViewStyleDefault) { - buttons = @[@{@"0": RCTUIKitLocalizedString(@"OK")}]; + buttons = @[ @{@"0" : RCTUIKitLocalizedString(@"OK")} ]; cancelButtonKey = @"0"; } else { buttons = @[ - @{@"0": RCTUIKitLocalizedString(@"OK")}, - @{@"1": RCTUIKitLocalizedString(@"Cancel")}, + @{@"0" : RCTUIKitLocalizedString(@"OK")}, + @{@"1" : RCTUIKitLocalizedString(@"Cancel")}, ]; cancelButtonKey = @"1"; } @@ -97,22 +102,26 @@ RCT_EXPORT_METHOD(alertWithArgs:(JS::NativeAlertManager::Args &)args UIViewController *presentingController = RCTPresentedViewController(); if (presentingController == nil) { RCTLogError(@"Tried to display alert view but there is no application window. args: %@", @{ - @"title": args.title() ?: [NSNull null], - @"message": args.message() ?: [NSNull null], - @"buttons": RCTConvertOptionalVecToArray(args.buttons(), ^id(id element) { return element; }) ?: [NSNull null], - @"type": args.type() ?: [NSNull null], - @"defaultValue": args.defaultValue() ?: [NSNull null], - @"cancelButtonKey": args.cancelButtonKey() ?: [NSNull null], - @"destructiveButtonKey": args.destructiveButtonKey() ?: [NSNull null], - @"keyboardType": args.keyboardType() ?: [NSNull null], + @"title" : args.title() ?: [NSNull null], + @"message" : args.message() ?: [NSNull null], + @"buttons" : RCTConvertOptionalVecToArray( + args.buttons(), + ^id(id element) { + return element; + }) + ?: [NSNull null], + @"type" : args.type() ?: [NSNull null], + @"defaultValue" : args.defaultValue() ?: [NSNull null], + @"cancelButtonKey" : args.cancelButtonKey() ?: [NSNull null], + @"destructiveButtonKey" : args.destructiveButtonKey() ?: [NSNull null], + @"keyboardType" : args.keyboardType() ?: [NSNull null], }); return; } - UIAlertController *alertController = [UIAlertController - alertControllerWithTitle:title - message:nil - preferredStyle:UIAlertControllerStyleAlert]; + UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title + message:nil + preferredStyle:UIAlertControllerStyleAlert]; switch (type) { case RCTAlertViewStylePlainTextInput: { [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) { @@ -162,27 +171,29 @@ RCT_EXPORT_METHOD(alertWithArgs:(JS::NativeAlertManager::Args &)args buttonStyle = UIAlertActionStyleDestructive; } __weak UIAlertController *weakAlertController = alertController; - [alertController addAction:[UIAlertAction actionWithTitle:buttonTitle - style:buttonStyle - handler:^(__unused UIAlertAction *action) { - switch (type) { - case RCTAlertViewStylePlainTextInput: - case RCTAlertViewStyleSecureTextInput: - callback(@[buttonKey, [weakAlertController.textFields.firstObject text]]); - break; - case RCTAlertViewStyleLoginAndPasswordInput: { - NSDictionary *loginCredentials = @{ - @"login": [weakAlertController.textFields.firstObject text], - @"password": [weakAlertController.textFields.lastObject text] - }; - callback(@[buttonKey, loginCredentials]); - break; - } - case RCTAlertViewStyleDefault: - callback(@[buttonKey]); - break; - } - }]]; + [alertController + addAction:[UIAlertAction + actionWithTitle:buttonTitle + style:buttonStyle + handler:^(__unused UIAlertAction *action) { + switch (type) { + case RCTAlertViewStylePlainTextInput: + case RCTAlertViewStyleSecureTextInput: + callback(@[ buttonKey, [weakAlertController.textFields.firstObject text] ]); + break; + case RCTAlertViewStyleLoginAndPasswordInput: { + NSDictionary *loginCredentials = @{ + @"login" : [weakAlertController.textFields.firstObject text], + @"password" : [weakAlertController.textFields.lastObject text] + }; + callback(@[ buttonKey, loginCredentials ]); + break; + } + case RCTAlertViewStyleDefault: + callback(@[ buttonKey ]); + break; + } + }]]; } if (!_alertControllers) { @@ -195,13 +206,15 @@ RCT_EXPORT_METHOD(alertWithArgs:(JS::NativeAlertManager::Args &)args }); } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @end -Class RCTAlertManagerCls(void) { +Class RCTAlertManagerCls(void) +{ return RCTAlertManager.class; } diff --git a/React/CoreModules/RCTAppState.mm b/React/CoreModules/RCTAppState.mm index c4321675eef..8eca483c8f2 100644 --- a/React/CoreModules/RCTAppState.mm +++ b/React/CoreModules/RCTAppState.mm @@ -20,10 +20,7 @@ static NSString *RCTCurrentAppState() static NSDictionary *states; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - states = @{ - @(UIApplicationStateActive): @"active", - @(UIApplicationStateBackground): @"background" - }; + states = @{@(UIApplicationStateActive) : @"active", @(UIApplicationStateBackground) : @"background"}; }); if (RCTRunningInAppExtension()) { @@ -33,11 +30,10 @@ static NSString *RCTCurrentAppState() return states[@(RCTSharedApplication().applicationState)] ?: @"unknown"; } -@interface RCTAppState() +@interface RCTAppState () @end -@implementation RCTAppState -{ +@implementation RCTAppState { NSString *_lastKnownState; } @@ -61,7 +57,7 @@ RCT_EXPORT_MODULE() - (facebook::react::ModuleConstants)getConstants { return facebook::react::typedConstants({ - .initialAppState = RCTCurrentAppState(), + .initialAppState = RCTCurrentAppState(), }); } @@ -69,17 +65,18 @@ RCT_EXPORT_MODULE() - (NSArray *)supportedEvents { - return @[@"appStateDidChange", @"memoryWarning"]; + return @[ @"appStateDidChange", @"memoryWarning" ]; } - (void)startObserving { - for (NSString *name in @[UIApplicationDidBecomeActiveNotification, - UIApplicationDidEnterBackgroundNotification, - UIApplicationDidFinishLaunchingNotification, - UIApplicationWillResignActiveNotification, - UIApplicationWillEnterForegroundNotification]) { - + for (NSString *name in @[ + UIApplicationDidBecomeActiveNotification, + UIApplicationDidEnterBackgroundNotification, + UIApplicationDidFinishLaunchingNotification, + UIApplicationWillResignActiveNotification, + UIApplicationWillEnterForegroundNotification + ]) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAppStateDidChange:) name:name @@ -126,8 +123,7 @@ RCT_EXPORT_MODULE() if (![newState isEqualToString:_lastKnownState]) { _lastKnownState = newState; if (self.bridge) { - [self sendEventWithName:@"appStateDidChange" - body:@{@"app_state": _lastKnownState}]; + [self sendEventWithName:@"appStateDidChange" body:@{@"app_state" : _lastKnownState}]; } } } @@ -137,19 +133,20 @@ RCT_EXPORT_MODULE() /** * Get the current background/foreground state of the app */ -RCT_EXPORT_METHOD(getCurrentAppState:(RCTResponseSenderBlock)callback - error:(__unused RCTResponseSenderBlock)error) +RCT_EXPORT_METHOD(getCurrentAppState : (RCTResponseSenderBlock)callback error : (__unused RCTResponseSenderBlock)error) { - callback(@[@{@"app_state": RCTCurrentAppState()}]); + callback(@[ @{@"app_state" : RCTCurrentAppState()} ]); } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @end -Class RCTAppStateCls(void) { +Class RCTAppStateCls(void) +{ return RCTAppState.class; } diff --git a/React/CoreModules/RCTAppearance.mm b/React/CoreModules/RCTAppearance.mm index 344603323c1..cb36f393364 100644 --- a/React/CoreModules/RCTAppearance.mm +++ b/React/CoreModules/RCTAppearance.mm @@ -19,18 +19,21 @@ NSString *const RCTAppearanceColorSchemeLight = @"light"; NSString *const RCTAppearanceColorSchemeDark = @"dark"; static BOOL sAppearancePreferenceEnabled = YES; -void RCTEnableAppearancePreference(BOOL enabled) { +void RCTEnableAppearancePreference(BOOL enabled) +{ sAppearancePreferenceEnabled = enabled; } static NSString *sColorSchemeOverride = nil; -void RCTOverrideAppearancePreference(NSString *const colorSchemeOverride) { +void RCTOverrideAppearancePreference(NSString *const colorSchemeOverride) +{ sColorSchemeOverride = colorSchemeOverride; } static NSString *RCTColorSchemePreference(UITraitCollection *traitCollection) { -#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 +#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 if (@available(iOS 13.0, *)) { static NSDictionary *appearances; static dispatch_once_t onceToken; @@ -41,9 +44,9 @@ static NSString *RCTColorSchemePreference(UITraitCollection *traitCollection) dispatch_once(&onceToken, ^{ appearances = @{ - @(UIUserInterfaceStyleLight): RCTAppearanceColorSchemeLight, - @(UIUserInterfaceStyleDark): RCTAppearanceColorSchemeDark - }; + @(UIUserInterfaceStyleLight) : RCTAppearanceColorSchemeLight, + @(UIUserInterfaceStyleDark) : RCTAppearanceColorSchemeDark + }; }); if (!sAppearancePreferenceEnabled) { @@ -63,8 +66,7 @@ static NSString *RCTColorSchemePreference(UITraitCollection *traitCollection) @interface RCTAppearance () @end -@implementation RCTAppearance -{ +@implementation RCTAppearance { NSString *_currentColorScheme; } @@ -87,7 +89,7 @@ RCT_EXPORT_MODULE(Appearance) RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSString *, getColorScheme) { - _currentColorScheme = RCTColorSchemePreference(nil); + _currentColorScheme = RCTColorSchemePreference(nil); return _currentColorScheme; } @@ -101,7 +103,7 @@ RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSString *, getColorScheme) NSString *newColorScheme = RCTColorSchemePreference(traitCollection); if (![_currentColorScheme isEqualToString:newColorScheme]) { _currentColorScheme = newColorScheme; - [self sendEventWithName:@"appearanceChanged" body:@{@"colorScheme": newColorScheme}]; + [self sendEventWithName:@"appearanceChanged" body:@{@"colorScheme" : newColorScheme}]; } } @@ -109,7 +111,7 @@ RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSString *, getColorScheme) - (NSArray *)supportedEvents { - return @[@"appearanceChanged"]; + return @[ @"appearanceChanged" ]; } - (void)startObserving @@ -131,6 +133,7 @@ RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSString *, getColorScheme) @end -Class RCTAppearanceCls(void) { +Class RCTAppearanceCls(void) +{ return RCTAppearance.class; } diff --git a/React/CoreModules/RCTAsyncLocalStorage.h b/React/CoreModules/RCTAsyncLocalStorage.h index 24fc9280235..d43281cd10e 100644 --- a/React/CoreModules/RCTAsyncLocalStorage.h +++ b/React/CoreModules/RCTAsyncLocalStorage.h @@ -19,7 +19,7 @@ * * Keys and values must always be strings or an error is returned. */ -@interface RCTAsyncLocalStorage : NSObject +@interface RCTAsyncLocalStorage : NSObject @property (nonatomic, assign) BOOL clearOnInvalidate; @@ -31,11 +31,11 @@ // For clearing data when the bridge may not exist, e.g. when logging out. + (void)clearAllData; -// Grab data from the cache. ResponseBlock result array will have an error at position 0, and an array of arrays at position 1. +// Grab data from the cache. ResponseBlock result array will have an error at position 0, and an array of arrays at +// position 1. - (void)multiGet:(NSArray *)keys callback:(RCTResponseSenderBlock)callback; // Add multiple key value pairs to the cache. - (void)multiSet:(NSArray *> *)kvPairs callback:(RCTResponseSenderBlock)callback; - @end diff --git a/React/CoreModules/RCTAsyncLocalStorage.mm b/React/CoreModules/RCTAsyncLocalStorage.mm index 9e3fb2765d2..77738aba08d 100644 --- a/React/CoreModules/RCTAsyncLocalStorage.mm +++ b/React/CoreModules/RCTAsyncLocalStorage.mm @@ -9,9 +9,9 @@ #import -#import #import #import +#import #import #import @@ -28,9 +28,9 @@ static const NSUInteger RCTInlineValueThreshold = 1024; static NSDictionary *RCTErrorForKey(NSString *key) { if (![key isKindOfClass:[NSString class]]) { - return RCTMakeAndLogError(@"Invalid key - must be a string. Key: ", key, @{@"key": key}); + return RCTMakeAndLogError(@"Invalid key - must be a string. Key: ", key, @{@"key" : key}); } else if (key.length < 1) { - return RCTMakeAndLogError(@"Invalid key - must be at least one character. Key: ", key, @{@"key": key}); + return RCTMakeAndLogError(@"Invalid key - must be at least one character. Key: ", key, @{@"key" : key}); } else { return nil; } @@ -52,15 +52,17 @@ static NSString *RCTReadFile(NSString *filePath, NSString *key, NSDictionary **e NSError *error; NSStringEncoding encoding; NSString *entryString = [NSString stringWithContentsOfFile:filePath usedEncoding:&encoding error:&error]; - NSDictionary *extraData = @{@"key": RCTNullIfNil(key)}; + NSDictionary *extraData = @{@"key" : RCTNullIfNil(key)}; if (error) { - if (errorOut) *errorOut = RCTMakeError(@"Failed to read storage file.", error, extraData); + if (errorOut) + *errorOut = RCTMakeError(@"Failed to read storage file.", error, extraData); return nil; } if (encoding != NSUTF8StringEncoding) { - if (errorOut) *errorOut = RCTMakeError(@"Incorrect encoding of storage file: ", @(encoding), extraData); + if (errorOut) + *errorOut = RCTMakeError(@"Incorrect encoding of storage file: ", @(encoding), extraData); return nil; } return entryString; @@ -143,9 +145,12 @@ static NSCache *RCTGetCache() cache.totalCostLimit = 2 * 1024 * 1024; // 2MB // Clear cache in the event of a memory warning - [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:nil usingBlock:^(__unused NSNotification *note) { - [cache removeAllObjects]; - }]; + [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification + object:nil + queue:nil + usingBlock:^(__unused NSNotification *note) { + [cache removeAllObjects]; + }]; }); return cache; } @@ -161,11 +166,10 @@ static NSDictionary *RCTDeleteStorageDirectory() #pragma mark - RCTAsyncLocalStorage -@interface RCTAsyncLocalStorage() +@interface RCTAsyncLocalStorage () @end -@implementation RCTAsyncLocalStorage -{ +@implementation RCTAsyncLocalStorage { BOOL _haveSetup; // The manifest is a dictionary of all keys with small values inlined. Null values indicate values that are stored // in separate files (as opposed to nil values which don't exist). The manifest is read off disk at startup, and @@ -269,15 +273,14 @@ RCT_EXPORT_MODULE() return errorOut; } -- (NSDictionary *)_appendItemForKey:(NSString *)key - toArray:(NSMutableArray *> *)result +- (NSDictionary *)_appendItemForKey:(NSString *)key toArray:(NSMutableArray *> *)result { NSDictionary *errorOut = RCTErrorForKey(key); if (errorOut) { return errorOut; } NSString *value = [self _getValueForKey:key errorOut:&errorOut]; - [result addObject:@[key, RCTNullIfNil(value)]]; // Insert null if missing or failure. + [result addObject:@[ key, RCTNullIfNil(value) ]]; // Insert null if missing or failure. return errorOut; } @@ -327,7 +330,7 @@ RCT_EXPORT_MODULE() [value writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; [RCTGetCache() setObject:value forKey:key cost:value.length]; if (error) { - errorOut = RCTMakeError(@"Failed to write value.", error, @{@"key": key}); + errorOut = RCTMakeError(@"Failed to write value.", error, @{@"key" : key}); } else if (_manifest[key] != (id)kCFNull) { *changedManifest = YES; _manifest[key] = (id)kCFNull; @@ -337,12 +340,11 @@ RCT_EXPORT_MODULE() #pragma mark - Exported JS Functions -RCT_EXPORT_METHOD(multiGet:(NSArray *)keys - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(multiGet : (NSArray *)keys callback : (RCTResponseSenderBlock)callback) { NSDictionary *errorOut = [self _ensureSetup]; if (errorOut) { - callback(@[@[errorOut], (id)kCFNull]); + callback(@[ @[ errorOut ], (id)kCFNull ]); return; } NSMutableArray *errors; @@ -350,18 +352,17 @@ RCT_EXPORT_METHOD(multiGet:(NSArray *)keys for (NSString *key in keys) { id keyError; id value = [self _getValueForKey:key errorOut:&keyError]; - [result addObject:@[key, RCTNullIfNil(value)]]; + [result addObject:@[ key, RCTNullIfNil(value) ]]; RCTAppendError(keyError, &errors); } - callback(@[RCTNullIfNil(errors), result]); + callback(@[ RCTNullIfNil(errors), result ]); } -RCT_EXPORT_METHOD(multiSet:(NSArray *> *)kvPairs - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(multiSet : (NSArray *> *)kvPairs callback : (RCTResponseSenderBlock)callback) { NSDictionary *errorOut = [self _ensureSetup]; if (errorOut) { - callback(@[@[errorOut]]); + callback(@[ @[ errorOut ] ]); return; } BOOL changedManifest = NO; @@ -373,15 +374,14 @@ RCT_EXPORT_METHOD(multiSet:(NSArray *> *)kvPairs if (changedManifest) { [self _writeManifest:&errors]; } - callback(@[RCTNullIfNil(errors)]); + callback(@[ RCTNullIfNil(errors) ]); } -RCT_EXPORT_METHOD(multiMerge:(NSArray *> *)kvPairs - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(multiMerge : (NSArray *> *)kvPairs callback : (RCTResponseSenderBlock)callback) { NSDictionary *errorOut = [self _ensureSetup]; if (errorOut) { - callback(@[@[errorOut]]); + callback(@[ @[ errorOut ] ]); return; } BOOL changedManifest = NO; @@ -394,7 +394,7 @@ RCT_EXPORT_METHOD(multiMerge:(NSArray *> *)kvPairs NSError *jsonError; NSMutableDictionary *mergedVal = RCTJSONParseMutable(value, &jsonError); if (RCTMergeRecursive(mergedVal, RCTJSONParse(entry[1], &jsonError))) { - entry = @[entry[0], RCTNullIfNil(RCTJSONStringify(mergedVal, NULL))]; + entry = @[ entry[0], RCTNullIfNil(RCTJSONStringify(mergedVal, NULL)) ]; } if (jsonError) { keyError = RCTJSErrorFromNSError(jsonError); @@ -409,15 +409,14 @@ RCT_EXPORT_METHOD(multiMerge:(NSArray *> *)kvPairs if (changedManifest) { [self _writeManifest:&errors]; } - callback(@[RCTNullIfNil(errors)]); + callback(@[ RCTNullIfNil(errors) ]); } -RCT_EXPORT_METHOD(multiRemove:(NSArray *)keys - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(multiRemove : (NSArray *)keys callback : (RCTResponseSenderBlock)callback) { NSDictionary *errorOut = [self _ensureSetup]; if (errorOut) { - callback(@[@[errorOut]]); + callback(@[ @[ errorOut ] ]); return; } NSMutableArray *errors; @@ -440,34 +439,36 @@ RCT_EXPORT_METHOD(multiRemove:(NSArray *)keys if (changedManifest) { [self _writeManifest:&errors]; } - callback(@[RCTNullIfNil(errors)]); + callback(@[ RCTNullIfNil(errors) ]); } -RCT_EXPORT_METHOD(clear:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(clear : (RCTResponseSenderBlock)callback) { [_manifest removeAllObjects]; [RCTGetCache() removeAllObjects]; NSDictionary *error = RCTDeleteStorageDirectory(); - callback(@[RCTNullIfNil(error)]); + callback(@[ RCTNullIfNil(error) ]); } -RCT_EXPORT_METHOD(getAllKeys:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(getAllKeys : (RCTResponseSenderBlock)callback) { NSDictionary *errorOut = [self _ensureSetup]; if (errorOut) { - callback(@[errorOut, (id)kCFNull]); + callback(@[ errorOut, (id)kCFNull ]); } else { - callback(@[(id)kCFNull, _manifest.allKeys]); + callback(@[ (id)kCFNull, _manifest.allKeys ]); } } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @end -Class RCTAsyncLocalStorageCls(void) { +Class RCTAsyncLocalStorageCls(void) +{ return RCTAsyncLocalStorage.class; } diff --git a/React/CoreModules/RCTClipboard.mm b/React/CoreModules/RCTClipboard.mm index c7ed682735e..846882a4f93 100644 --- a/React/CoreModules/RCTClipboard.mm +++ b/React/CoreModules/RCTClipboard.mm @@ -26,18 +26,16 @@ RCT_EXPORT_MODULE() return dispatch_get_main_queue(); } - -RCT_EXPORT_METHOD(setString:(NSString *)content) +RCT_EXPORT_METHOD(setString : (NSString *)content) { UIPasteboard *clipboard = [UIPasteboard generalPasteboard]; - clipboard.string = (content ? : @""); + clipboard.string = (content ?: @""); } -RCT_EXPORT_METHOD(getString:(RCTPromiseResolveBlock)resolve - reject:(__unused RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD(getString : (RCTPromiseResolveBlock)resolve reject : (__unused RCTPromiseRejectBlock)reject) { UIPasteboard *clipboard = [UIPasteboard generalPasteboard]; - resolve((clipboard.string ? : @"")); + resolve((clipboard.string ?: @"")); } - (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker @@ -47,6 +45,7 @@ RCT_EXPORT_METHOD(getString:(RCTPromiseResolveBlock)resolve @end -Class RCTClipboardCls(void) { +Class RCTClipboardCls(void) +{ return RCTClipboard.class; } diff --git a/React/CoreModules/RCTDevLoadingView.h b/React/CoreModules/RCTDevLoadingView.h index d2fb7e60358..da5ad2d5e8e 100644 --- a/React/CoreModules/RCTDevLoadingView.h +++ b/React/CoreModules/RCTDevLoadingView.h @@ -5,9 +5,9 @@ * LICENSE file in the root directory of this source tree. */ -#import #import #import +#import @interface RCTDevLoadingView : NSObject @end diff --git a/React/CoreModules/RCTDevLoadingView.mm b/React/CoreModules/RCTDevLoadingView.mm index b159dfa93b7..4995477eb93 100644 --- a/React/CoreModules/RCTDevLoadingView.mm +++ b/React/CoreModules/RCTDevLoadingView.mm @@ -9,13 +9,13 @@ #import +#import #import #import #import #import #import #import -#import #import "CoreModulesPlugins.h" @@ -26,8 +26,7 @@ using namespace facebook::react; #if RCT_DEV | RCT_ENABLE_LOADING_VIEW -@implementation RCTDevLoadingView -{ +@implementation RCTDevLoadingView { UIWindow *_window; UILabel *_label; NSDate *_showDate; @@ -65,7 +64,7 @@ RCT_EXPORT_MODULE() } } --(void)showMessage:(NSString *)message color:(UIColor *)color backgroundColor:(UIColor *)backgroundColor +- (void)showMessage:(NSString *)message color:(UIColor *)color backgroundColor:(UIColor *)backgroundColor { if (!RCTDevLoadingViewGetEnabled()) { return; @@ -78,7 +77,8 @@ RCT_EXPORT_MODULE() if (@available(iOS 11.0, *)) { UIWindow *window = RCTSharedApplication().keyWindow; - self->_window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, window.safeAreaInsets.top + 30)]; + self->_window = + [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, window.safeAreaInsets.top + 30)]; self->_label = [[UILabel alloc] initWithFrame:CGRectMake(0, window.safeAreaInsets.top, screenSize.width, 30)]; } else { self->_window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, 22)]; @@ -93,8 +93,7 @@ RCT_EXPORT_MODULE() // set a root VC so rotation is supported self->_window.rootViewController = [UIViewController new]; - self->_label.font = [UIFont monospacedDigitSystemFontOfSize:12.0 - weight:UIFontWeightRegular]; + self->_label.font = [UIFont monospacedDigitSystemFontOfSize:12.0 weight:UIFontWeightRegular]; self->_label.textAlignment = NSTextAlignmentCenter; } @@ -104,7 +103,7 @@ RCT_EXPORT_MODULE() self->_window.hidden = NO; #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ -__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 + __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 if (@available(iOS 13.0, *)) { UIWindowScene *scene = (UIWindowScene *)RCTSharedApplication().connectedScenes.anyObject; self->_window.windowScene = scene; @@ -113,7 +112,10 @@ __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 }); } -RCT_EXPORT_METHOD(showMessage:(NSString *)message withColor:(NSNumber * __nonnull)color withBackgroundColor:(NSNumber * __nonnull)backgroundColor) +RCT_EXPORT_METHOD(showMessage + : (NSString *)message withColor + : (NSNumber *__nonnull)color withBackgroundColor + : (NSNumber *__nonnull)backgroundColor) { [self showMessage:message color:[RCTConvert UIColor:color] backgroundColor:[RCTConvert UIColor:backgroundColor]]; } @@ -130,15 +132,16 @@ RCT_EXPORT_METHOD(hide) NSTimeInterval delay = MAX(0, MIN_PRESENTED_TIME - presentedTime); CGRect windowFrame = self->_window.frame; [UIView animateWithDuration:0.25 - delay:delay - options:0 - animations:^{ - self->_window.frame = CGRectOffset(windowFrame, 0, -windowFrame.size.height); - } completion:^(__unused BOOL finished) { - self->_window.frame = windowFrame; - self->_window.hidden = YES; - self->_window = nil; - }]; + delay:delay + options:0 + animations:^{ + self->_window.frame = CGRectOffset(windowFrame, 0, -windowFrame.size.height); + } + completion:^(__unused BOOL finished) { + self->_window.frame = windowFrame; + self->_window.hidden = YES; + self->_window = nil; + }]; }); } @@ -154,16 +157,14 @@ RCT_EXPORT_METHOD(hide) #endif color = [UIColor whiteColor]; backgroundColor = [UIColor blackColor]; - message = [NSString stringWithFormat:@"Connect to %@ to develop JavaScript.", RCT_PACKAGER_NAME]; + message = [NSString stringWithFormat:@"Connect to %@ to develop JavaScript.", RCT_PACKAGER_NAME]; } else { color = [UIColor whiteColor]; - backgroundColor = [UIColor colorWithHue:1./3 saturation:1 brightness:.35 alpha:1]; + backgroundColor = [UIColor colorWithHue:1. / 3 saturation:1 brightness:.35 alpha:1]; message = [NSString stringWithFormat:@"Loading from %@:%@...", URL.host, URL.port]; } - [self showMessage:message - color:color - backgroundColor:backgroundColor]; + [self showMessage:message color:color backgroundColor:backgroundColor]; } - (void)updateProgress:(RCTLoadingProgress *)progress @@ -187,13 +188,28 @@ RCT_EXPORT_METHOD(hide) @implementation RCTDevLoadingView -+ (NSString *)moduleName { return nil; } -+ (void)setEnabled:(BOOL)enabled { } -- (void)showMessage:(NSString *)message color:(UIColor *)color backgroundColor:(UIColor *)backgroundColor { } -- (void)showMessage:(NSString *)message withColor:(NSNumber *)color withBackgroundColor:(NSNumber *)backgroundColor{ } -- (void)showWithURL:(NSURL *)URL { } -- (void)updateProgress:(RCTLoadingProgress *)progress { } -- (void)hide { } ++ (NSString *)moduleName +{ + return nil; +} ++ (void)setEnabled:(BOOL)enabled +{ +} +- (void)showMessage:(NSString *)message color:(UIColor *)color backgroundColor:(UIColor *)backgroundColor +{ +} +- (void)showMessage:(NSString *)message withColor:(NSNumber *)color withBackgroundColor:(NSNumber *)backgroundColor +{ +} +- (void)showWithURL:(NSURL *)URL +{ +} +- (void)updateProgress:(RCTLoadingProgress *)progress +{ +} +- (void)hide +{ +} - (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); @@ -203,6 +219,7 @@ RCT_EXPORT_METHOD(hide) #endif -Class RCTDevLoadingViewCls(void) { +Class RCTDevLoadingViewCls(void) +{ return RCTDevLoadingView.class; } diff --git a/React/CoreModules/RCTDevMenu.h b/React/CoreModules/RCTDevMenu.h index 4808a7f2992..338815357c6 100644 --- a/React/CoreModules/RCTDevMenu.h +++ b/React/CoreModules/RCTDevMenu.h @@ -17,7 +17,6 @@ RCT_EXTERN NSString *const RCTShowDevMenuNotification; #endif - @class RCTDevMenuItem; /** @@ -68,8 +67,7 @@ RCT_EXTERN NSString *const RCTShowDevMenuNotification; /** * Deprecated. Use the `-addItem:` method instead. */ -- (void)addItem:(NSString *)title - handler:(void(^)(void))handler DEPRECATED_ATTRIBUTE; +- (void)addItem:(NSString *)title handler:(void (^)(void))handler DEPRECATED_ATTRIBUTE; /** * Add custom item to the development menu. The handler will be called @@ -79,7 +77,7 @@ RCT_EXTERN NSString *const RCTShowDevMenuNotification; @end -typedef NSString *(^RCTDevMenuItemTitleBlock)(void); +typedef NSString * (^RCTDevMenuItemTitleBlock)(void); /** * Developer menu item, used to expose additional functionality via the menu. @@ -90,16 +88,14 @@ typedef NSString *(^RCTDevMenuItemTitleBlock)(void); * This creates an item with a simple push-button interface, used to trigger an * action. */ -+ (instancetype)buttonItemWithTitle:(NSString *)title - handler:(dispatch_block_t)handler; ++ (instancetype)buttonItemWithTitle:(NSString *)title handler:(dispatch_block_t)handler; /** * This creates an item with a simple push-button interface, used to trigger an * action. getTitleForPresentation is called each time the item is about to be * presented, and should return the item's title. */ -+ (instancetype)buttonItemWithTitleBlock:(RCTDevMenuItemTitleBlock)titleBlock - handler:(dispatch_block_t)handler; ++ (instancetype)buttonItemWithTitleBlock:(RCTDevMenuItemTitleBlock)titleBlock handler:(dispatch_block_t)handler; @end diff --git a/React/CoreModules/RCTDevMenu.mm b/React/CoreModules/RCTDevMenu.mm index 69ff839faa7..c88026f9955 100644 --- a/React/CoreModules/RCTDevMenu.mm +++ b/React/CoreModules/RCTDevMenu.mm @@ -160,7 +160,8 @@ RCT_EXPORT_MODULE() { _presentedItems = nil; [_actionSheet dismissViewControllerAnimated:YES - completion:^(void){}]; + completion:^(void){ + }]; } - (void)showOnShake @@ -427,10 +428,7 @@ RCT_EXPORT_METHOD(show) _presentedItems = items; [RCTPresentedViewController() presentViewController:_actionSheet animated:YES completion:nil]; - [_bridge enqueueJSCall:@"RCTNativeAppEventEmitter" - method:@"emit" - args:@[@"RCTDevMenuShown"] - completion:NULL]; + [_bridge enqueueJSCall:@"RCTNativeAppEventEmitter" method:@"emit" args:@[ @"RCTDevMenuShown" ] completion:NULL]; } - (RCTDevMenuAlertActionHandler)alertActionHandlerForDevItem:(RCTDevMenuItem *__nullable)item @@ -493,7 +491,8 @@ RCT_EXPORT_METHOD(setHotLoadingEnabled : (BOOL)enabled) return _bridge.devSettings.isHotLoadingEnabled; } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -502,7 +501,7 @@ RCT_EXPORT_METHOD(setHotLoadingEnabled : (BOOL)enabled) #else // Unavailable when not in dev mode -@interface RCTDevMenu() +@interface RCTDevMenu () @end @implementation RCTDevMenu @@ -520,7 +519,7 @@ RCT_EXPORT_METHOD(setHotLoadingEnabled : (BOOL)enabled) { } -- (void)debugRemotely : (BOOL)enableDebug +- (void)debugRemotely:(BOOL)enableDebug { } @@ -533,7 +532,8 @@ RCT_EXPORT_METHOD(setHotLoadingEnabled : (BOOL)enabled) return @"DevMenu"; } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -568,6 +568,7 @@ RCT_EXPORT_METHOD(setHotLoadingEnabled : (BOOL)enabled) @end -Class RCTDevMenuCls(void) { +Class RCTDevMenuCls(void) +{ return RCTDevMenu.class; } diff --git a/React/CoreModules/RCTDevSettings.mm b/React/CoreModules/RCTDevSettings.mm index 3d8fa89dbd2..8778c6f81f9 100644 --- a/React/CoreModules/RCTDevSettings.mm +++ b/React/CoreModules/RCTDevSettings.mm @@ -47,7 +47,8 @@ static BOOL devSettingsMenuEnabled = YES; static BOOL devSettingsMenuEnabled = NO; #endif -void RCTDevSettingsSetEnabled(BOOL enabled) { +void RCTDevSettingsSetEnabled(BOOL enabled) +{ devSettingsMenuEnabled = enabled; } @@ -208,7 +209,7 @@ RCT_EXPORT_MODULE() - (NSArray *)supportedEvents { - return @[@"didPressMenuItem"]; + return @[ @"didPressMenuItem" ]; } - (void)_updateSettingWithValue:(id)value forKey:(NSString *)key @@ -249,14 +250,14 @@ RCT_EXPORT_METHOD(reload) RCTTriggerReloadCommandListeners(@"Unknown From JS"); } -RCT_EXPORT_METHOD(reloadWithReason : (NSString *) reason) +RCT_EXPORT_METHOD(reloadWithReason : (NSString *)reason) { RCTTriggerReloadCommandListeners(reason); } RCT_EXPORT_METHOD(onFastRefresh) { - [self.bridge onFastRefresh]; + [self.bridge onFastRefresh]; } RCT_EXPORT_METHOD(setIsShakeToShowDevMenuEnabled : (BOOL)enabled) @@ -353,12 +354,14 @@ RCT_EXPORT_METHOD(toggleElementInspector) } } -RCT_EXPORT_METHOD(addMenuItem:(NSString *)title) +RCT_EXPORT_METHOD(addMenuItem : (NSString *)title) { __weak __typeof(self) weakSelf = self; - [self.bridge.devMenu addItem:[RCTDevMenuItem buttonItemWithTitle:title handler:^{ - [weakSelf sendEventWithName:@"didPressMenuItem" body:@{@"title": title}]; - }]]; + [self.bridge.devMenu addItem:[RCTDevMenuItem buttonItemWithTitle:title + handler:^{ + [weakSelf sendEventWithName:@"didPressMenuItem" + body:@{@"title" : title}]; + }]]; } - (BOOL)isElementInspectorShown @@ -409,10 +412,10 @@ RCT_EXPORT_METHOD(addMenuItem:(NSString *)title) if (self.bridge) { [self.bridge enqueueJSCall:@"HMRClient" method:@"setup" - args:@[@"ios", path, host, RCTNullIfNil(port), @(YES)] + args:@[ @"ios", path, host, RCTNullIfNil(port), @(YES) ] completion:NULL]; } else { - self.invokeJS(@"HMRClient", @"setup", @[@"ios", path, host, RCTNullIfNil(port), @(YES)]); + self.invokeJS(@"HMRClient", @"setup", @[ @"ios", path, host, RCTNullIfNil(port), @(YES) ]); } } } @@ -450,7 +453,8 @@ RCT_EXPORT_METHOD(addMenuItem:(NSString *)title) }); } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -515,7 +519,8 @@ RCT_EXPORT_METHOD(addMenuItem:(NSString *)title) { } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -537,6 +542,7 @@ RCT_EXPORT_METHOD(addMenuItem:(NSString *)title) @end -Class RCTDevSettingsCls(void) { +Class RCTDevSettingsCls(void) +{ return RCTDevSettings.class; } diff --git a/React/CoreModules/RCTDeviceInfo.mm b/React/CoreModules/RCTDeviceInfo.mm index 182dafab5f7..8750f7ff288 100644 --- a/React/CoreModules/RCTDeviceInfo.mm +++ b/React/CoreModules/RCTDeviceInfo.mm @@ -62,19 +62,20 @@ RCT_EXPORT_MODULE() _currentInterfaceDimensions = RCTExportedDimensions(_bridge); [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(interfaceFrameDidChange) - name:UIApplicationDidBecomeActiveNotification - object:nil]; + selector:@selector(interfaceFrameDidChange) + name:UIApplicationDidBecomeActiveNotification + object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(interfaceFrameDidChange) - name:RCTUserInterfaceStyleDidChangeNotification - object:nil]; + selector:@selector(interfaceFrameDidChange) + name:RCTUserInterfaceStyleDidChangeNotification + object:nil]; #endif } -static BOOL RCTIsIPhoneX() { +static BOOL RCTIsIPhoneX() +{ static BOOL isIPhoneX = NO; static dispatch_once_t onceToken; @@ -86,10 +87,8 @@ static BOOL RCTIsIPhoneX() { CGSize iPhoneXMaxScreenSize = CGSizeMake(1242, 2688); CGSize iPhoneXRScreenSize = CGSizeMake(828, 1792); - isIPhoneX = - CGSizeEqualToSize(screenSize, iPhoneXScreenSize) || - CGSizeEqualToSize(screenSize, iPhoneXMaxScreenSize) || - CGSizeEqualToSize(screenSize, iPhoneXRScreenSize); + isIPhoneX = CGSizeEqualToSize(screenSize, iPhoneXScreenSize) || + CGSizeEqualToSize(screenSize, iPhoneXMaxScreenSize) || CGSizeEqualToSize(screenSize, iPhoneXRScreenSize); }); return isIPhoneX; @@ -99,24 +98,21 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge) { RCTAssertMainQueue(); RCTDimensions dimensions = RCTGetDimensions(bridge.accessibilityManager.multiplier); - __typeof (dimensions.window) window = dimensions.window; + __typeof(dimensions.window) window = dimensions.window; NSDictionary *dimsWindow = @{ - @"width": @(window.width), - @"height": @(window.height), - @"scale": @(window.scale), - @"fontScale": @(window.fontScale) + @"width" : @(window.width), + @"height" : @(window.height), + @"scale" : @(window.scale), + @"fontScale" : @(window.fontScale) }; __typeof(dimensions.screen) screen = dimensions.screen; NSDictionary *dimsScreen = @{ - @"width": @(screen.width), - @"height": @(screen.height), - @"scale": @(screen.scale), - @"fontScale": @(screen.fontScale) - }; - return @{ - @"window": dimsWindow, - @"screen": dimsScreen + @"width" : @(screen.width), + @"height" : @(screen.height), + @"scale" : @(screen.scale), + @"fontScale" : @(screen.fontScale) }; + return @{@"window" : dimsWindow, @"screen" : dimsScreen}; } - (NSDictionary *)constantsToExport @@ -127,12 +123,12 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge) - (NSDictionary *)getConstants { return @{ - @"Dimensions": RCTExportedDimensions(_bridge), + @"Dimensions" : RCTExportedDimensions(_bridge), // Note: // This prop is deprecated and will be removed in a future release. // Please use this only for a quick and temporary solution. // Use instead. - @"isIPhoneX_deprecated": @(RCTIsIPhoneX()), + @"isIPhoneX_deprecated" : @(RCTIsIPhoneX()), }; } @@ -140,11 +136,10 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge) { RCTBridge *bridge = _bridge; RCTExecuteOnMainQueue(^{ - // Report the event across the bridge. + // Report the event across the bridge. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateDimensions" - body:RCTExportedDimensions(bridge)]; + [bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateDimensions" body:RCTExportedDimensions(bridge)]; #pragma clang diagnostic pop }); } @@ -159,7 +154,6 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge) }); } - - (void)_interfaceOrientationDidChange { UIInterfaceOrientation nextOrientation = [RCTSharedApplication() statusBarOrientation]; @@ -171,15 +165,13 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge) !UIInterfaceOrientationIsLandscape(nextOrientation))) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateDimensions" - body:RCTExportedDimensions(_bridge)]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateDimensions" body:RCTExportedDimensions(_bridge)]; #pragma clang diagnostic pop - } + } _currentInterfaceOrientation = nextOrientation; } - - (void)interfaceFrameDidChange { __weak __typeof(self) weakSelf = self; @@ -188,7 +180,6 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge) }); } - - (void)_interfaceFrameDidChange { NSDictionary *nextInterfaceDimensions = RCTExportedDimensions(_bridge); @@ -196,8 +187,7 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge) if (!([nextInterfaceDimensions isEqual:_currentInterfaceDimensions])) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateDimensions" - body:nextInterfaceDimensions]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateDimensions" body:nextInterfaceDimensions]; #pragma clang diagnostic pop } @@ -213,6 +203,7 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge) @end -Class RCTDeviceInfoCls(void) { +Class RCTDeviceInfoCls(void) +{ return RCTDeviceInfo.class; } diff --git a/React/CoreModules/RCTExceptionsManager.h b/React/CoreModules/RCTExceptionsManager.h index ce9faf1f10e..28ae105ef48 100644 --- a/React/CoreModules/RCTExceptionsManager.h +++ b/React/CoreModules/RCTExceptionsManager.h @@ -13,11 +13,17 @@ NS_ASSUME_NONNULL_BEGIN @protocol RCTExceptionsManagerDelegate -- (void)handleSoftJSExceptionWithMessage:(nullable NSString *)message stack:(nullable NSArray *)stack exceptionId:(NSNumber *)exceptionId; -- (void)handleFatalJSExceptionWithMessage:(nullable NSString *)message stack:(nullable NSArray *)stack exceptionId:(NSNumber *)exceptionId; +- (void)handleSoftJSExceptionWithMessage:(nullable NSString *)message + stack:(nullable NSArray *)stack + exceptionId:(NSNumber *)exceptionId; +- (void)handleFatalJSExceptionWithMessage:(nullable NSString *)message + stack:(nullable NSArray *)stack + exceptionId:(NSNumber *)exceptionId; @optional -- (void)updateJSExceptionWithMessage:(nullable NSString *)message stack:(nullable NSArray *)stack exceptionId:(NSNumber *)exceptionId; +- (void)updateJSExceptionWithMessage:(nullable NSString *)message + stack:(nullable NSArray *)stack + exceptionId:(NSNumber *)exceptionId; @end @@ -25,8 +31,12 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)initWithDelegate:(id)delegate; -- (void)reportSoftException:(nullable NSString *)message stack:(nullable NSArray *)stack exceptionId:(double)exceptionId; -- (void)reportFatalException:(nullable NSString *)message stack:(nullable NSArray *)stack exceptionId:(double)exceptionId; +- (void)reportSoftException:(nullable NSString *)message + stack:(nullable NSArray *)stack + exceptionId:(double)exceptionId; +- (void)reportFatalException:(nullable NSString *)message + stack:(nullable NSArray *)stack + exceptionId:(double)exceptionId; @property (nonatomic, weak) id delegate; diff --git a/React/CoreModules/RCTExceptionsManager.mm b/React/CoreModules/RCTExceptionsManager.mm index 3954b5cabf9..a6697b2fdb4 100644 --- a/React/CoreModules/RCTExceptionsManager.mm +++ b/React/CoreModules/RCTExceptionsManager.mm @@ -17,7 +17,7 @@ #import "CoreModulesPlugins.h" -@interface RCTExceptionsManager() +@interface RCTExceptionsManager () @end @@ -35,54 +35,68 @@ RCT_EXPORT_MODULE() return self; } -- (void)reportSoft: (NSString *)message stack:(NSArray *)stack exceptionId:(double)exceptionId suppressRedBox: (BOOL) suppressRedBox { - if (!suppressRedBox) { - [_bridge.redBox showErrorMessage:message withStack:stack errorCookie:((int)exceptionId)]; - } +- (void)reportSoft:(NSString *)message + stack:(NSArray *)stack + exceptionId:(double)exceptionId + suppressRedBox:(BOOL)suppressRedBox +{ + if (!suppressRedBox) { + [_bridge.redBox showErrorMessage:message withStack:stack errorCookie:((int)exceptionId)]; + } - if (_delegate) { - [_delegate handleSoftJSExceptionWithMessage:message stack:stack exceptionId:[NSNumber numberWithDouble:exceptionId]]; - } + if (_delegate) { + [_delegate handleSoftJSExceptionWithMessage:message + stack:stack + exceptionId:[NSNumber numberWithDouble:exceptionId]]; + } } -- (void)reportFatal: (NSString *)message stack:(NSArray *)stack exceptionId:(double)exceptionId suppressRedBox: (BOOL) suppressRedBox { - if (!suppressRedBox) { - [_bridge.redBox showErrorMessage:message withStack:stack errorCookie:((int)exceptionId)]; - } +- (void)reportFatal:(NSString *)message + stack:(NSArray *)stack + exceptionId:(double)exceptionId + suppressRedBox:(BOOL)suppressRedBox +{ + if (!suppressRedBox) { + [_bridge.redBox showErrorMessage:message withStack:stack errorCookie:((int)exceptionId)]; + } - if (_delegate) { - [_delegate handleFatalJSExceptionWithMessage:message stack:stack exceptionId:[NSNumber numberWithDouble:exceptionId]]; - } + if (_delegate) { + [_delegate handleFatalJSExceptionWithMessage:message + stack:stack + exceptionId:[NSNumber numberWithDouble:exceptionId]]; + } - static NSUInteger reloadRetries = 0; - if (!RCT_DEBUG && reloadRetries < _maxReloadAttempts) { - reloadRetries++; - RCTTriggerReloadCommandListeners(@"JS Crash Reload"); - } else if (!RCT_DEV || !suppressRedBox) { - NSString *description = [@"Unhandled JS Exception: " stringByAppendingString:message]; - NSDictionary *errorInfo = @{ NSLocalizedDescriptionKey: description, RCTJSStackTraceKey: stack }; - RCTFatal([NSError errorWithDomain:RCTErrorDomain code:0 userInfo:errorInfo]); - } + static NSUInteger reloadRetries = 0; + if (!RCT_DEBUG && reloadRetries < _maxReloadAttempts) { + reloadRetries++; + RCTTriggerReloadCommandListeners(@"JS Crash Reload"); + } else if (!RCT_DEV || !suppressRedBox) { + NSString *description = [@"Unhandled JS Exception: " stringByAppendingString:message]; + NSDictionary *errorInfo = @{NSLocalizedDescriptionKey : description, RCTJSStackTraceKey : stack}; + RCTFatal([NSError errorWithDomain:RCTErrorDomain code:0 userInfo:errorInfo]); + } } - -RCT_EXPORT_METHOD(reportSoftException:(NSString *)message - stack:(NSArray *)stack - exceptionId:(double)exceptionId) +RCT_EXPORT_METHOD(reportSoftException + : (NSString *)message stack + : (NSArray *)stack exceptionId + : (double)exceptionId) { [self reportSoft:message stack:stack exceptionId:exceptionId suppressRedBox:NO]; } -RCT_EXPORT_METHOD(reportFatalException:(NSString *)message - stack:(NSArray *)stack - exceptionId:(double) exceptionId) +RCT_EXPORT_METHOD(reportFatalException + : (NSString *)message stack + : (NSArray *)stack exceptionId + : (double)exceptionId) { [self reportFatal:message stack:stack exceptionId:exceptionId suppressRedBox:NO]; } -RCT_EXPORT_METHOD(updateExceptionMessage:(NSString *)message - stack:(NSArray *)stack - exceptionId:(double)exceptionId) +RCT_EXPORT_METHOD(updateExceptionMessage + : (NSString *)message stack + : (NSArray *)stack exceptionId + : (double)exceptionId) { [_bridge.redBox updateErrorMessage:message withStack:stack errorCookie:((int)exceptionId)]; @@ -92,18 +106,14 @@ RCT_EXPORT_METHOD(updateExceptionMessage:(NSString *)message } // Deprecated. Use reportFatalException directly instead. -RCT_EXPORT_METHOD(reportUnhandledException:(NSString *)message - stack:(NSArray *)stack) +RCT_EXPORT_METHOD(reportUnhandledException : (NSString *)message stack : (NSArray *)stack) { [self reportFatalException:message stack:stack exceptionId:-1]; } -RCT_EXPORT_METHOD(dismissRedbox) -{ +RCT_EXPORT_METHOD(dismissRedbox) {} -} - -RCT_EXPORT_METHOD(reportException:(JS::NativeExceptionsManager::ExceptionData &)data) +RCT_EXPORT_METHOD(reportException : (JS::NativeExceptionsManager::ExceptionData &)data) { NSString *message = data.message(); double exceptionId = data.id_(); @@ -113,23 +123,23 @@ RCT_EXPORT_METHOD(reportException:(JS::NativeExceptionsManager::ExceptionData &) // TODO: (moti) T53588496 Replace `(NSArray *)stack` in // reportFatalException etc with a typed interface. NSMutableArray *stackArray = [NSMutableArray new]; - for (auto frame: data.stack()) { - NSMutableDictionary * frameDict = [NSMutableDictionary new]; + for (auto frame : data.stack()) { + NSMutableDictionary *frameDict = [NSMutableDictionary new]; if (frame.column().hasValue()) { frameDict[@"column"] = @(frame.column().value()); } frameDict[@"file"] = frame.file(); if (frame.lineNumber().hasValue()) { - frameDict[@"lineNumber"] = @(frame.lineNumber().value()); + frameDict[@"lineNumber"] = @(frame.lineNumber().value()); } frameDict[@"methodName"] = frame.methodName(); if (frame.collapse().hasValue()) { - frameDict[@"collapse"] = @(frame.collapse().value()); + frameDict[@"collapse"] = @(frame.collapse().value()); } [stackArray addObject:frameDict]; } NSDictionary *dict = (NSDictionary *)extraData; - BOOL suppressRedBox = [[dict objectForKey:@"suppressRedBox"] boolValue]; + BOOL suppressRedBox = [[dict objectForKey:@"suppressRedBox"] boolValue]; if (data.isFatal()) { [self reportFatal:message stack:stackArray exceptionId:exceptionId suppressRedBox:suppressRedBox]; @@ -139,7 +149,7 @@ RCT_EXPORT_METHOD(reportException:(JS::NativeExceptionsManager::ExceptionData &) } - (std::shared_ptr)getTurboModuleWithJsInvoker: -(std::shared_ptr)jsInvoker + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } diff --git a/React/CoreModules/RCTFPSGraph.h b/React/CoreModules/RCTFPSGraph.h index 9ccf27bcb2e..73dd6bd96ae 100644 --- a/React/CoreModules/RCTFPSGraph.h +++ b/React/CoreModules/RCTFPSGraph.h @@ -17,8 +17,7 @@ @property (nonatomic, assign, readonly) NSUInteger maxFPS; @property (nonatomic, assign, readonly) NSUInteger minFPS; -- (instancetype)initWithFrame:(CGRect)frame - color:(UIColor *)color NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithFrame:(CGRect)frame color:(UIColor *)color NS_DESIGNATED_INITIALIZER; - (void)onTick:(NSTimeInterval)timestamp; diff --git a/React/CoreModules/RCTFPSGraph.m b/React/CoreModules/RCTFPSGraph.m index 0274548a1d8..bee27f32946 100644 --- a/React/CoreModules/RCTFPSGraph.m +++ b/React/CoreModules/RCTFPSGraph.m @@ -11,15 +11,14 @@ #if RCT_DEV -@interface RCTFPSGraph() +@interface RCTFPSGraph () @property (nonatomic, strong, readonly) CAShapeLayer *graph; @property (nonatomic, strong, readonly) UILabel *label; @end -@implementation RCTFPSGraph -{ +@implementation RCTFPSGraph { CAShapeLayer *_graph; UILabel *_label; @@ -58,8 +57,8 @@ free(_frames); } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) - (CAShapeLayer *)graph { diff --git a/React/CoreModules/RCTI18nManager.mm b/React/CoreModules/RCTI18nManager.mm index 3d6b9815a62..74a75d9c9f1 100644 --- a/React/CoreModules/RCTI18nManager.mm +++ b/React/CoreModules/RCTI18nManager.mm @@ -7,8 +7,8 @@ #import -#import "RCTI18nManager.h" #import +#import "RCTI18nManager.h" #import "CoreModulesPlugins.h" @@ -26,17 +26,17 @@ RCT_EXPORT_MODULE() return NO; } -RCT_EXPORT_METHOD(allowRTL:(BOOL)value) +RCT_EXPORT_METHOD(allowRTL : (BOOL)value) { [[RCTI18nUtil sharedInstance] allowRTL:value]; } -RCT_EXPORT_METHOD(forceRTL:(BOOL)value) +RCT_EXPORT_METHOD(forceRTL : (BOOL)value) { [[RCTI18nUtil sharedInstance] forceRTL:value]; } -RCT_EXPORT_METHOD(swapLeftAndRightInRTL:(BOOL)value) +RCT_EXPORT_METHOD(swapLeftAndRightInRTL : (BOOL)value) { [[RCTI18nUtil sharedInstance] swapLeftAndRightInRTL:value]; } @@ -49,8 +49,8 @@ RCT_EXPORT_METHOD(swapLeftAndRightInRTL:(BOOL)value) - (NSDictionary *)getConstants { return @{ - @"isRTL": @([[RCTI18nUtil sharedInstance] isRTL]), - @"doLeftAndRightSwapInRTL": @([[RCTI18nUtil sharedInstance] doLeftAndRightSwapInRTL]) + @"isRTL" : @([[RCTI18nUtil sharedInstance] isRTL]), + @"doLeftAndRightSwapInRTL" : @([[RCTI18nUtil sharedInstance] doLeftAndRightSwapInRTL]) }; } @@ -61,6 +61,7 @@ RCT_EXPORT_METHOD(swapLeftAndRightInRTL:(BOOL)value) @end -Class RCTI18nManagerCls(void) { +Class RCTI18nManagerCls(void) +{ return RCTI18nManager.class; } diff --git a/React/CoreModules/RCTKeyboardObserver.mm b/React/CoreModules/RCTKeyboardObserver.mm index 603bd84628d..11ec4d4972f 100644 --- a/React/CoreModules/RCTKeyboardObserver.mm +++ b/React/CoreModules/RCTKeyboardObserver.mm @@ -14,7 +14,7 @@ static NSDictionary *RCTParseKeyboardNotification(NSNotification *notification); -@interface RCTKeyboardObserver() +@interface RCTKeyboardObserver () @end @implementation RCTKeyboardObserver @@ -27,8 +27,7 @@ RCT_EXPORT_MODULE() NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; -#define ADD_KEYBOARD_HANDLER(NAME, SELECTOR) \ - [nc addObserver:self selector:@selector(SELECTOR:) name:NAME object:nil] +#define ADD_KEYBOARD_HANDLER(NAME, SELECTOR) [nc addObserver:self selector:@selector(SELECTOR:) name:NAME object:nil] ADD_KEYBOARD_HANDLER(UIKeyboardWillShowNotification, keyboardWillShow); ADD_KEYBOARD_HANDLER(UIKeyboardDidShowNotification, keyboardDidShow); @@ -40,17 +39,18 @@ RCT_EXPORT_MODULE() #undef ADD_KEYBOARD_HANDLER #endif - } - (NSArray *)supportedEvents { - return @[@"keyboardWillShow", - @"keyboardDidShow", - @"keyboardWillHide", - @"keyboardDidHide", - @"keyboardWillChangeFrame", - @"keyboardDidChangeFrame"]; + return @[ + @"keyboardWillShow", + @"keyboardDidShow", + @"keyboardWillHide", + @"keyboardDidHide", + @"keyboardWillChangeFrame", + @"keyboardDidChangeFrame" + ]; } - (void)stopObserving @@ -61,15 +61,14 @@ RCT_EXPORT_MODULE() // Bridge might be already invalidated by the time the keyboard is about to be dismissed. // This might happen, for example, when reload from the packager is performed. // Thus we need to check against nil here. -#define IMPLEMENT_KEYBOARD_HANDLER(EVENT) \ -- (void)EVENT:(NSNotification *)notification \ -{ \ - if (!self.bridge) { \ - return; \ - } \ - [self sendEventWithName:@#EVENT \ - body:RCTParseKeyboardNotification(notification)]; \ -} +#define IMPLEMENT_KEYBOARD_HANDLER(EVENT) \ + -(void)EVENT : (NSNotification *)notification \ + { \ + if (!self.bridge) { \ + return; \ + } \ + [self sendEventWithName:@ #EVENT body:RCTParseKeyboardNotification(notification)]; \ + } IMPLEMENT_KEYBOARD_HANDLER(keyboardWillShow) IMPLEMENT_KEYBOARD_HANDLER(keyboardDidShow) @@ -78,7 +77,8 @@ IMPLEMENT_KEYBOARD_HANDLER(keyboardDidHide) IMPLEMENT_KEYBOARD_HANDLER(keyboardWillChangeFrame) IMPLEMENT_KEYBOARD_HANDLER(keyboardDidChangeFrame) -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -88,10 +88,10 @@ IMPLEMENT_KEYBOARD_HANDLER(keyboardDidChangeFrame) NS_INLINE NSDictionary *RCTRectDictionaryValue(CGRect rect) { return @{ - @"screenX": @(rect.origin.x), - @"screenY": @(rect.origin.y), - @"width": @(rect.size.width), - @"height": @(rect.size.height), + @"screenX" : @(rect.origin.x), + @"screenY" : @(rect.origin.y), + @"width" : @(rect.size.width), + @"height" : @(rect.size.height), }; } @@ -120,19 +120,21 @@ static NSDictionary *RCTParseKeyboardNotification(NSNotification *notification) CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue]; CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; - UIViewAnimationCurve curve = static_cast([userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]); + UIViewAnimationCurve curve = + static_cast([userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]); NSInteger isLocalUserInfoKey = [userInfo[UIKeyboardIsLocalUserInfoKey] integerValue]; return @{ - @"startCoordinates": RCTRectDictionaryValue(beginFrame), - @"endCoordinates": RCTRectDictionaryValue(endFrame), - @"duration": @(duration * 1000.0), // ms - @"easing": RCTAnimationNameForCurve(curve), - @"isEventFromThisApp": isLocalUserInfoKey == 1 ? @YES : @NO, + @"startCoordinates" : RCTRectDictionaryValue(beginFrame), + @"endCoordinates" : RCTRectDictionaryValue(endFrame), + @"duration" : @(duration * 1000.0), // ms + @"easing" : RCTAnimationNameForCurve(curve), + @"isEventFromThisApp" : isLocalUserInfoKey == 1 ? @YES : @NO, }; #endif } -Class RCTKeyboardObserverCls(void) { +Class RCTKeyboardObserverCls(void) +{ return RCTKeyboardObserver.class; } diff --git a/React/CoreModules/RCTLogBox.mm b/React/CoreModules/RCTLogBox.mm index 1e89ce1c849..9bb70f8d596 100644 --- a/React/CoreModules/RCTLogBox.mm +++ b/React/CoreModules/RCTLogBox.mm @@ -9,7 +9,6 @@ #import #import -#import #import #import #import @@ -17,7 +16,7 @@ #import #import #import -#import +#import #import #import @@ -32,8 +31,7 @@ @interface RCTLogBoxView : UIWindow @end -@implementation RCTLogBoxView -{ +@implementation RCTLogBoxView { RCTSurface *_surface; } @@ -77,8 +75,7 @@ @interface RCTLogBox () @end -@implementation RCTLogBox -{ +@implementation RCTLogBox { RCTLogBoxView *_view; } @@ -96,7 +93,7 @@ RCT_EXPORT_METHOD(show) if (RCTRedBoxGetEnabled()) { dispatch_async(dispatch_get_main_queue(), ^{ if (!self->_view) { - self->_view = [[RCTLogBoxView alloc] initWithFrame:[UIScreen mainScreen].bounds bridge: self->_bridge]; + self->_view = [[RCTLogBoxView alloc] initWithFrame:[UIScreen mainScreen].bounds bridge:self->_bridge]; } [self->_view show]; }); @@ -112,7 +109,8 @@ RCT_EXPORT_METHOD(hide) } } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -121,7 +119,7 @@ RCT_EXPORT_METHOD(hide) #else // Disabled -@interface RCTLogBox() +@interface RCTLogBox () @end @implementation RCTLogBox @@ -131,15 +129,18 @@ RCT_EXPORT_METHOD(hide) return nil; } -- (void)show { +- (void)show +{ // noop } -- (void)hide { +- (void)hide +{ // noop } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -147,6 +148,7 @@ RCT_EXPORT_METHOD(hide) #endif -Class RCTLogBoxCls(void) { +Class RCTLogBoxCls(void) +{ return RCTLogBox.class; } diff --git a/React/CoreModules/RCTPerfMonitor.mm b/React/CoreModules/RCTPerfMonitor.mm index 62e8d711ace..68116fd10ef 100644 --- a/React/CoreModules/RCTPerfMonitor.mm +++ b/React/CoreModules/RCTPerfMonitor.mm @@ -17,6 +17,7 @@ #import +#import #import #import #import @@ -24,7 +25,6 @@ #import #import #import -#import #import #import @@ -66,17 +66,18 @@ static BOOL RCTJSCSetOption(const char *option) static vm_size_t RCTGetResidentMemorySize(void) { - vm_size_t memoryUsageInByte = 0; - task_vm_info_data_t vmInfo; - mach_msg_type_number_t count = TASK_VM_INFO_COUNT; - kern_return_t kernelReturn = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &vmInfo, &count); - if(kernelReturn == KERN_SUCCESS) { - memoryUsageInByte = (vm_size_t) vmInfo.phys_footprint; - } - return memoryUsageInByte; + vm_size_t memoryUsageInByte = 0; + task_vm_info_data_t vmInfo; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + kern_return_t kernelReturn = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&vmInfo, &count); + if (kernelReturn == KERN_SUCCESS) { + memoryUsageInByte = (vm_size_t)vmInfo.phys_footprint; + } + return memoryUsageInByte; } -@interface RCTPerfMonitor : NSObject +@interface RCTPerfMonitor + : NSObject #if __has_include() @property (nonatomic, strong, readonly) RCTDevMenuItem *devMenuItem; @@ -163,20 +164,19 @@ RCT_EXPORT_MODULE() if (devSettings.isPerfMonitorShown) { [weakSelf show]; } - _devMenuItem = - [RCTDevMenuItem buttonItemWithTitleBlock:^NSString *{ - return (devSettings.isPerfMonitorShown) ? - @"Hide Perf Monitor" : - @"Show Perf Monitor"; - } handler:^{ - if (devSettings.isPerfMonitorShown) { - [weakSelf hide]; - devSettings.isPerfMonitorShown = NO; - } else { - [weakSelf show]; - devSettings.isPerfMonitorShown = YES; - } - }]; + _devMenuItem = [RCTDevMenuItem + buttonItemWithTitleBlock:^NSString * { + return (devSettings.isPerfMonitorShown) ? @"Hide Perf Monitor" : @"Show Perf Monitor"; + } + handler:^{ + if (devSettings.isPerfMonitorShown) { + [weakSelf hide]; + devSettings.isPerfMonitorShown = NO; + } else { + [weakSelf show]; + devSettings.isPerfMonitorShown = YES; + } + }]; } return _devMenuItem; @@ -186,8 +186,7 @@ RCT_EXPORT_MODULE() - (UIPanGestureRecognizer *)gestureRecognizer { if (!_gestureRecognizer) { - _gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self - action:@selector(gesture:)]; + _gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)]; } return _gestureRecognizer; @@ -200,16 +199,15 @@ RCT_EXPORT_MODULE() _container.layer.borderWidth = 2; _container.layer.borderColor = [UIColor lightGrayColor].CGColor; [_container addGestureRecognizer:self.gestureRecognizer]; - [_container addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self - action:@selector(tap)]]; - + [_container addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)]]; + _container.backgroundColor = [UIColor whiteColor]; - #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ +#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 if (@available(iOS 13.0, *)) { _container.backgroundColor = [UIColor systemBackgroundColor]; } - #endif +#endif } return _container; @@ -254,8 +252,7 @@ RCT_EXPORT_MODULE() - (RCTFPSGraph *)uiGraph { if (!_uiGraph) { - _uiGraph = [[RCTFPSGraph alloc] initWithFrame:CGRectMake(134, 14, 40, 30) - color:[UIColor lightGrayColor]]; + _uiGraph = [[RCTFPSGraph alloc] initWithFrame:CGRectMake(134, 14, 40, 30) color:[UIColor lightGrayColor]]; } return _uiGraph; } @@ -263,8 +260,7 @@ RCT_EXPORT_MODULE() - (RCTFPSGraph *)jsGraph { if (!_jsGraph) { - _jsGraph = [[RCTFPSGraph alloc] initWithFrame:CGRectMake(178, 14, 40, 30) - color:[UIColor lightGrayColor]]; + _jsGraph = [[RCTFPSGraph alloc] initWithFrame:CGRectMake(178, 14, 40, 30) color:[UIColor lightGrayColor]]; } return _jsGraph; } @@ -297,11 +293,10 @@ RCT_EXPORT_MODULE() { if (!_metrics) { _metrics = [[UITableView alloc] initWithFrame:CGRectMake( - 0, - RCTPerfMonitorBarHeight, - self.container.frame.size.width, - self.container.frame.size.height - RCTPerfMonitorBarHeight - )]; + 0, + RCTPerfMonitorBarHeight, + self.container.frame.size.width, + self.container.frame.size.height - RCTPerfMonitorBarHeight)]; _metrics.dataSource = self; _metrics.delegate = self; _metrics.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; @@ -332,27 +327,20 @@ RCT_EXPORT_MODULE() UIWindow *window = RCTSharedApplication().delegate.window; [window addSubview:self.container]; + _uiDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(threadUpdate:)]; + [_uiDisplayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; - _uiDisplayLink = [CADisplayLink displayLinkWithTarget:self - selector:@selector(threadUpdate:)]; - [_uiDisplayLink addToRunLoop:[NSRunLoop mainRunLoop] - forMode:NSRunLoopCommonModes]; - - self.container.frame = (CGRect) { - self.container.frame.origin, { - self.container.frame.size.width + 44, - self.container.frame.size.height - } - }; + self.container.frame = + (CGRect){self.container.frame.origin, {self.container.frame.size.width + 44, self.container.frame.size.height}}; [self.container addSubview:self.jsGraph]; [self.container addSubview:self.jsGraphLabel]; - [_bridge dispatchBlock:^{ - self->_jsDisplayLink = [CADisplayLink displayLinkWithTarget:self - selector:@selector(threadUpdate:)]; - [self->_jsDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] - forMode:NSRunLoopCommonModes]; - } queue:RCTJSThread]; + [_bridge + dispatchBlock:^{ + self->_jsDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(threadUpdate:)]; + [self->_jsDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + } + queue:RCTJSThread]; } - (void)hide @@ -391,40 +379,28 @@ RCT_EXPORT_MODULE() __weak __typeof__(self) weakSelf = self; _queue = dispatch_queue_create("com.facebook.react.RCTPerfMonitor", DISPATCH_QUEUE_SERIAL); _io = dispatch_io_create( - DISPATCH_IO_STREAM, - _pipe[0], - _queue, - ^(__unused int error) {}); + DISPATCH_IO_STREAM, + _pipe[0], + _queue, + ^(__unused int error){ + }); dispatch_io_set_low_water(_io, 20); - dispatch_io_read( - _io, - 0, - SIZE_MAX, - _queue, - ^(__unused bool done, dispatch_data_t data, __unused int error) { - if (!data) { - return; + dispatch_io_read(_io, 0, SIZE_MAX, _queue, ^(__unused bool done, dispatch_data_t data, __unused int error) { + if (!data) { + return; } - dispatch_data_apply( - data, - ^bool( - __unused dispatch_data_t region, - __unused size_t offset, - const void *buffer, - size_t size - ) { + dispatch_data_apply( + data, ^bool(__unused dispatch_data_t region, __unused size_t offset, const void *buffer, size_t size) { write(self->_stderr, buffer, size); - NSString *log = [[NSString alloc] initWithBytes:buffer - length:size - encoding:NSUTF8StringEncoding]; + NSString *log = [[NSString alloc] initWithBytes:buffer length:size encoding:NSUTF8StringEncoding]; [weakSelf parse:log]; return true; }); - }); + }); } - (void)stopLogs @@ -438,10 +414,9 @@ RCT_EXPORT_MODULE() static NSRegularExpression *GCRegex; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - NSString *pattern = @"\\[GC: [\\d\\.]+ \\wb => (Eden|Full)Collection, (?:Skipped copying|Did copy), ([\\d\\.]+) \\wb, [\\d.]+ \\ws\\]"; - GCRegex = [NSRegularExpression regularExpressionWithPattern:pattern - options:0 - error:nil]; + NSString *pattern = + @"\\[GC: [\\d\\.]+ \\wb => (Eden|Full)Collection, (?:Skipped copying|Did copy), ([\\d\\.]+) \\wb, [\\d.]+ \\ws\\]"; + GCRegex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil]; }); if (_remaining) { @@ -476,31 +451,25 @@ RCT_EXPORT_MODULE() } double mem = (double)RCTGetResidentMemorySize() / 1024 / 1024; - self.memory.text =[NSString stringWithFormat:@"RAM\n%.2lf\nMB", mem]; + self.memory.text = [NSString stringWithFormat:@"RAM\n%.2lf\nMB", mem]; self.heap.text = [NSString stringWithFormat:@"JSC\n%.2lf\nMB", (double)_heapSize / 1024]; - self.views.text = [NSString stringWithFormat:@"Views\n%lu\n%lu", (unsigned long)visibleViewCount, (unsigned long)viewCount]; + self.views.text = + [NSString stringWithFormat:@"Views\n%lu\n%lu", (unsigned long)visibleViewCount, (unsigned long)viewCount]; __weak __typeof__(self) weakSelf = self; - dispatch_after( - dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), - dispatch_get_main_queue(), - ^{ - __strong __typeof__(weakSelf) strongSelf = weakSelf; - if (strongSelf && strongSelf->_container.superview) { - [strongSelf updateStats]; - } - }); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + __strong __typeof__(weakSelf) strongSelf = weakSelf; + if (strongSelf && strongSelf->_container.superview) { + [strongSelf updateStats]; + } + }); } - (void)gesture:(UIPanGestureRecognizer *)gestureRecognizer { CGPoint translation = [gestureRecognizer translationInView:self.container.superview]; - self.container.center = CGPointMake( - self.container.center.x + translation.x, - self.container.center.y + translation.y - ); - [gestureRecognizer setTranslation:CGPointMake(0, 0) - inView:self.container.superview]; + self.container.center = CGPointMake(self.container.center.x + translation.x, self.container.center.y + translation.y); + [gestureRecognizer setTranslation:CGPointMake(0, 0) inView:self.container.superview]; } - (void)tap @@ -513,11 +482,12 @@ RCT_EXPORT_MODULE() [_metrics reloadData]; } - [UIView animateWithDuration:.25 animations:^{ - CGRect tmp = self.container.frame; - self.container.frame = self->_storedMonitorFrame; - self->_storedMonitorFrame = tmp; - }]; + [UIView animateWithDuration:.25 + animations:^{ + CGRect tmp = self.container.frame; + self.container.frame = self->_storedMonitorFrame; + self->_storedMonitorFrame = tmp; + }]; } - (void)threadUpdate:(CADisplayLink *)displayLink @@ -533,7 +503,7 @@ RCT_EXPORT_MODULE() RCTPerformanceLogger *performanceLogger = [_bridge performanceLogger]; NSArray *values = [performanceLogger valuesForTags]; for (NSString *label in [performanceLogger labelsForTags]) { - long long value = values[i+1].longLongValue - values[i].longLongValue; + long long value = values[i + 1].longLongValue - values[i].longLongValue; NSString *unit = @"ms"; if ([label hasSuffix:@"Size"]) { unit = @"b"; @@ -553,14 +523,12 @@ RCT_EXPORT_MODULE() return 1; } -- (NSInteger)tableView:(__unused UITableView *)tableView - numberOfRowsInSection:(__unused NSInteger)section +- (NSInteger)tableView:(__unused UITableView *)tableView numberOfRowsInSection:(__unused NSInteger)section { return _perfLoggerMarks.count; } -- (UITableViewCell *)tableView:(UITableView *)tableView - cellForRowAtIndexPath:(NSIndexPath *)indexPath +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RCTPerfMonitorCellIdentifier forIndexPath:indexPath]; @@ -578,8 +546,7 @@ RCT_EXPORT_MODULE() #pragma mark - UITableViewDelegate -- (CGFloat)tableView:(__unused UITableView *)tableView -heightForRowAtIndexPath:(__unused NSIndexPath *)indexPath +- (CGFloat)tableView:(__unused UITableView *)tableView heightForRowAtIndexPath:(__unused NSIndexPath *)indexPath { return 20; } @@ -588,7 +555,8 @@ heightForRowAtIndexPath:(__unused NSIndexPath *)indexPath #endif -Class RCTPerfMonitorCls(void) { +Class RCTPerfMonitorCls(void) +{ #if RCT_DEV return RCTPerfMonitor.class; #else diff --git a/React/CoreModules/RCTPlatform.mm b/React/CoreModules/RCTPlatform.mm index c298fd6f890..9975ca6f819 100644 --- a/React/CoreModules/RCTPlatform.mm +++ b/React/CoreModules/RCTPlatform.mm @@ -17,8 +17,9 @@ using namespace facebook::react; -static NSString *interfaceIdiom(UIUserInterfaceIdiom idiom) { - switch(idiom) { +static NSString *interfaceIdiom(UIUserInterfaceIdiom idiom) +{ + switch (idiom) { case UIUserInterfaceIdiomPhone: return @"phone"; case UIUserInterfaceIdiomPad: @@ -60,17 +61,18 @@ RCT_EXPORT_MODULE(PlatformConstants) UIDevice *device = [UIDevice currentDevice]; auto versions = RCTGetReactNativeVersion(); return typedConstants({ - .forceTouchAvailable = RCTForceTouchAvailable() ? true : false, - .osVersion = [device systemVersion], - .systemName = [device systemName], - .interfaceIdiom = interfaceIdiom([device userInterfaceIdiom]), - .isTesting = RCTRunningInTestEnvironment() ? true : false, - .reactNativeVersion = JS::NativePlatformConstantsIOS::ConstantsReactNativeVersion::Builder({ - .minor = [versions[@"minor"] doubleValue], - .major = [versions[@"major"] doubleValue], - .patch = [versions[@"patch"] doubleValue], - .prerelease = [versions[@"prerelease"] isKindOfClass: [NSNull class]] ? folly::Optional{} : [versions[@"prerelease"] doubleValue] - }), + .forceTouchAvailable = RCTForceTouchAvailable() ? true : false, + .osVersion = [device systemVersion], + .systemName = [device systemName], + .interfaceIdiom = interfaceIdiom([device userInterfaceIdiom]), + .isTesting = RCTRunningInTestEnvironment() ? true : false, + .reactNativeVersion = JS::NativePlatformConstantsIOS::ConstantsReactNativeVersion::Builder( + {.minor = [versions[@"minor"] doubleValue], + .major = [versions[@"major"] doubleValue], + .patch = [versions[@"patch"] doubleValue], + .prerelease = [versions[@"prerelease"] isKindOfClass:[NSNull class]] + ? folly::Optional{} + : [versions[@"prerelease"] doubleValue]}), }); } @@ -81,6 +83,7 @@ RCT_EXPORT_MODULE(PlatformConstants) @end -Class RCTPlatformCls(void) { +Class RCTPlatformCls(void) +{ return RCTPlatform.class; } diff --git a/React/CoreModules/RCTRedBox.h b/React/CoreModules/RCTRedBox.h index 943a9ffacf8..d468f449fcc 100644 --- a/React/CoreModules/RCTRedBox.h +++ b/React/CoreModules/RCTRedBox.h @@ -29,8 +29,12 @@ typedef void (^RCTRedBoxButtonPressHandler)(void); - (void)updateErrorMessage:(NSString *)message withStack:(NSArray *)stack errorCookie:(int)errorCookie; - (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack; - (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack; -- (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack errorCookie:(int)errorCookie; -- (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack errorCookie:(int)errorCookie; +- (void)showErrorMessage:(NSString *)message + withParsedStack:(NSArray *)stack + errorCookie:(int)errorCookie; +- (void)updateErrorMessage:(NSString *)message + withParsedStack:(NSArray *)stack + errorCookie:(int)errorCookie; - (void)dismiss; diff --git a/React/CoreModules/RCTRedBox.mm b/React/CoreModules/RCTRedBox.mm index c7133ac5522..badf0cd74c3 100644 --- a/React/CoreModules/RCTRedBox.mm +++ b/React/CoreModules/RCTRedBox.mm @@ -75,96 +75,116 @@ @property (nonatomic, weak) id actionDelegate; @end -@implementation RCTRedBoxWindow -{ - UITableView *_stackTraceTableView; - NSString *_lastErrorMessage; - NSArray *_lastStackTrace; - int _lastErrorCookie; +@implementation RCTRedBoxWindow { + UITableView *_stackTraceTableView; + NSString *_lastErrorMessage; + NSArray *_lastStackTrace; + int _lastErrorCookie; } - (instancetype)initWithFrame:(CGRect)frame - customButtonTitles:(NSArray*)customButtonTitles + customButtonTitles:(NSArray *)customButtonTitles customButtonHandlers:(NSArray *)customButtonHandlers { - if (self = [super init]) { - _lastErrorCookie = -1; + if (self = [super init]) { + _lastErrorCookie = -1; - _rootViewController = [UIViewController new]; - UIView *rootView = _rootViewController.view; - rootView.frame = frame; - rootView.backgroundColor = [UIColor blackColor]; + _rootViewController = [UIViewController new]; + UIView *rootView = _rootViewController.view; + rootView.frame = frame; + rootView.backgroundColor = [UIColor blackColor]; - const CGFloat buttonHeight = 60; + const CGFloat buttonHeight = 60; - CGRect detailsFrame = rootView.bounds; - detailsFrame.size.height -= buttonHeight + [self bottomSafeViewHeight]; + CGRect detailsFrame = rootView.bounds; + detailsFrame.size.height -= buttonHeight + [self bottomSafeViewHeight]; - _stackTraceTableView = [[UITableView alloc] initWithFrame:detailsFrame style:UITableViewStylePlain]; - _stackTraceTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; - _stackTraceTableView.delegate = self; - _stackTraceTableView.dataSource = self; - _stackTraceTableView.backgroundColor = [UIColor clearColor]; + _stackTraceTableView = [[UITableView alloc] initWithFrame:detailsFrame style:UITableViewStylePlain]; + _stackTraceTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + _stackTraceTableView.delegate = self; + _stackTraceTableView.dataSource = self; + _stackTraceTableView.backgroundColor = [UIColor clearColor]; #if !TARGET_OS_TV - _stackTraceTableView.separatorColor = [UIColor colorWithWhite:1 alpha:0.3]; - _stackTraceTableView.separatorStyle = UITableViewCellSeparatorStyleNone; + _stackTraceTableView.separatorColor = [UIColor colorWithWhite:1 alpha:0.3]; + _stackTraceTableView.separatorStyle = UITableViewCellSeparatorStyleNone; #endif - _stackTraceTableView.indicatorStyle = UIScrollViewIndicatorStyleWhite; - [rootView addSubview:_stackTraceTableView]; + _stackTraceTableView.indicatorStyle = UIScrollViewIndicatorStyleWhite; + [rootView addSubview:_stackTraceTableView]; #if TARGET_OS_SIMULATOR || TARGET_OS_MACCATALYST - NSString *reloadText = @"Reload\n(\u2318R)"; - NSString *dismissText = @"Dismiss\n(ESC)"; - NSString *copyText = @"Copy\n(\u2325\u2318C)"; - NSString *extraText = @"Extra Info\n(\u2318E)"; + NSString *reloadText = @"Reload\n(\u2318R)"; + NSString *dismissText = @"Dismiss\n(ESC)"; + NSString *copyText = @"Copy\n(\u2325\u2318C)"; + NSString *extraText = @"Extra Info\n(\u2318E)"; #else - NSString *reloadText = @"Reload JS"; - NSString *dismissText = @"Dismiss"; - NSString *copyText = @"Copy"; - NSString *extraText = @"Extra Info"; + NSString *reloadText = @"Reload JS"; + NSString *dismissText = @"Dismiss"; + NSString *copyText = @"Copy"; + NSString *extraText = @"Extra Info"; #endif - UIButton *dismissButton = [self redBoxButton:dismissText accessibilityIdentifier:@"redbox-dismiss" selector:@selector(dismiss) block:nil]; - UIButton *reloadButton = [self redBoxButton:reloadText accessibilityIdentifier:@"redbox-reload" selector:@selector(reload) block:nil]; - UIButton *copyButton = [self redBoxButton:copyText accessibilityIdentifier:@"redbox-copy" selector:@selector(copyStack) block:nil]; - UIButton *extraButton = [self redBoxButton:extraText accessibilityIdentifier:@"redbox-extra" selector:@selector(showExtraDataViewController) block:nil]; + UIButton *dismissButton = [self redBoxButton:dismissText + accessibilityIdentifier:@"redbox-dismiss" + selector:@selector(dismiss) + block:nil]; + UIButton *reloadButton = [self redBoxButton:reloadText + accessibilityIdentifier:@"redbox-reload" + selector:@selector(reload) + block:nil]; + UIButton *copyButton = [self redBoxButton:copyText + accessibilityIdentifier:@"redbox-copy" + selector:@selector(copyStack) + block:nil]; + UIButton *extraButton = [self redBoxButton:extraText + accessibilityIdentifier:@"redbox-extra" + selector:@selector(showExtraDataViewController) + block:nil]; - CGFloat buttonWidth = frame.size.width / (4 + [customButtonTitles count]); - CGFloat bottomButtonHeight = frame.size.height - buttonHeight - [self bottomSafeViewHeight]; - dismissButton.frame = CGRectMake(0, bottomButtonHeight, buttonWidth, buttonHeight); - reloadButton.frame = CGRectMake(buttonWidth, bottomButtonHeight, buttonWidth, buttonHeight); - copyButton.frame = CGRectMake(buttonWidth * 2, bottomButtonHeight, buttonWidth, buttonHeight); - extraButton.frame = CGRectMake(buttonWidth * 3, bottomButtonHeight, buttonWidth, buttonHeight); + CGFloat buttonWidth = frame.size.width / (4 + [customButtonTitles count]); + CGFloat bottomButtonHeight = frame.size.height - buttonHeight - [self bottomSafeViewHeight]; + dismissButton.frame = CGRectMake(0, bottomButtonHeight, buttonWidth, buttonHeight); + reloadButton.frame = CGRectMake(buttonWidth, bottomButtonHeight, buttonWidth, buttonHeight); + copyButton.frame = CGRectMake(buttonWidth * 2, bottomButtonHeight, buttonWidth, buttonHeight); + extraButton.frame = CGRectMake(buttonWidth * 3, bottomButtonHeight, buttonWidth, buttonHeight); - [rootView addSubview:dismissButton]; - [rootView addSubview:reloadButton]; - [rootView addSubview:copyButton]; - [rootView addSubview:extraButton]; + [rootView addSubview:dismissButton]; + [rootView addSubview:reloadButton]; + [rootView addSubview:copyButton]; + [rootView addSubview:extraButton]; - for (NSUInteger i = 0; i < [customButtonTitles count]; i++) { - UIButton *button = [self redBoxButton:customButtonTitles[i] accessibilityIdentifier:@"" selector:nil block:customButtonHandlers[i]]; - button.frame = CGRectMake(buttonWidth * (4 + i), bottomButtonHeight, buttonWidth, buttonHeight); - [rootView addSubview:button]; - } - - UIView *topBorder = [[UIView alloc] initWithFrame:CGRectMake(0, bottomButtonHeight + 1, rootView.frame.size.width, 1)]; - topBorder.backgroundColor = [UIColor colorWithRed:0.70 green:0.70 blue:0.70 alpha:1.0]; - - [rootView addSubview:topBorder]; - - UIView *bottomSafeView = [UIView new]; - bottomSafeView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1]; - bottomSafeView.frame = CGRectMake(0, frame.size.height - [self bottomSafeViewHeight], frame.size.width, [self bottomSafeViewHeight]); - - [rootView addSubview:bottomSafeView]; + for (NSUInteger i = 0; i < [customButtonTitles count]; i++) { + UIButton *button = [self redBoxButton:customButtonTitles[i] + accessibilityIdentifier:@"" + selector:nil + block:customButtonHandlers[i]]; + button.frame = CGRectMake(buttonWidth * (4 + i), bottomButtonHeight, buttonWidth, buttonHeight); + [rootView addSubview:button]; } - return self; + + UIView *topBorder = + [[UIView alloc] initWithFrame:CGRectMake(0, bottomButtonHeight + 1, rootView.frame.size.width, 1)]; + topBorder.backgroundColor = [UIColor colorWithRed:0.70 green:0.70 blue:0.70 alpha:1.0]; + + [rootView addSubview:topBorder]; + + UIView *bottomSafeView = [UIView new]; + bottomSafeView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1]; + bottomSafeView.frame = + CGRectMake(0, frame.size.height - [self bottomSafeViewHeight], frame.size.width, [self bottomSafeViewHeight]); + + [rootView addSubview:bottomSafeView]; + } + return self; } -- (UIButton *)redBoxButton:(NSString *)title accessibilityIdentifier:(NSString *)accessibilityIdentifier selector:(SEL)selector block:(RCTRedBoxButtonPressHandler)block +- (UIButton *)redBoxButton:(NSString *)title + accessibilityIdentifier:(NSString *)accessibilityIdentifier + selector:(SEL)selector + block:(RCTRedBoxButtonPressHandler)block { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; - button.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin; + button.autoresizingMask = + UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin; button.accessibilityIdentifier = accessibilityIdentifier; button.titleLabel.font = [UIFont systemFontOfSize:13]; button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping; @@ -183,26 +203,28 @@ - (NSInteger)bottomSafeViewHeight { - if (@available(iOS 11.0, *)) { - return RCTSharedApplication().delegate.window.safeAreaInsets.bottom; - } else { - return 0; - } + if (@available(iOS 11.0, *)) { + return RCTSharedApplication().delegate.window.safeAreaInsets.bottom; + } else { + return 0; + } } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) - (void)dealloc { - _stackTraceTableView.dataSource = nil; - _stackTraceTableView.delegate = nil; + _stackTraceTableView.dataSource = nil; + _stackTraceTableView.delegate = nil; } - (NSString *)stripAnsi:(NSString *)text { - NSError *error = nil; - NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\x1b\\[[0-9;]*m" options:NSRegularExpressionCaseInsensitive error:&error]; - return [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@""]; + NSError *error = nil; + NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\x1b\\[[0-9;]*m" + options:NSRegularExpressionCaseInsensitive + error:&error]; + return [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@""]; } - (void)showErrorMessage:(NSString *)message @@ -210,234 +232,229 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) isUpdate:(BOOL)isUpdate errorCookie:(int)errorCookie { - // Remove ANSI color codes from the message - NSString *messageWithoutAnsi = [self stripAnsi:message]; + // Remove ANSI color codes from the message + NSString *messageWithoutAnsi = [self stripAnsi:message]; - // Show if this is a new message, or if we're updating the previous message - BOOL isNew = !self.rootViewController.isBeingPresented && !isUpdate; - BOOL isUpdateForSameMessage = !isNew && ( - self.rootViewController.isBeingPresented && isUpdate && ( - (errorCookie == -1 && [_lastErrorMessage isEqualToString:messageWithoutAnsi]) || - (errorCookie == _lastErrorCookie) - ) - ); - if (isNew || isUpdateForSameMessage) { - _lastStackTrace = stack; - // message is displayed using UILabel, which is unable to render text of - // unlimited length, so we truncate it - _lastErrorMessage = [messageWithoutAnsi substringToIndex:MIN((NSUInteger)10000, messageWithoutAnsi.length)]; - _lastErrorCookie = errorCookie; + // Show if this is a new message, or if we're updating the previous message + BOOL isNew = !self.rootViewController.isBeingPresented && !isUpdate; + BOOL isUpdateForSameMessage = !isNew && + (self.rootViewController.isBeingPresented && isUpdate && + ((errorCookie == -1 && [_lastErrorMessage isEqualToString:messageWithoutAnsi]) || + (errorCookie == _lastErrorCookie))); + if (isNew || isUpdateForSameMessage) { + _lastStackTrace = stack; + // message is displayed using UILabel, which is unable to render text of + // unlimited length, so we truncate it + _lastErrorMessage = [messageWithoutAnsi substringToIndex:MIN((NSUInteger)10000, messageWithoutAnsi.length)]; + _lastErrorCookie = errorCookie; - [_stackTraceTableView reloadData]; + [_stackTraceTableView reloadData]; - if (!self.rootViewController.isBeingPresented) { - [_stackTraceTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] - atScrollPosition:UITableViewScrollPositionTop - animated:NO]; - [RCTKeyWindow().rootViewController presentViewController:self.rootViewController - animated:YES - completion:nil]; - } + if (!self.rootViewController.isBeingPresented) { + [_stackTraceTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] + atScrollPosition:UITableViewScrollPositionTop + animated:NO]; + [RCTKeyWindow().rootViewController presentViewController:self.rootViewController animated:YES completion:nil]; } + } } - (void)dismiss { - [self.rootViewController dismissViewControllerAnimated:YES completion:nil]; + [self.rootViewController dismissViewControllerAnimated:YES completion:nil]; } - (void)reload { - [_actionDelegate reloadFromRedBoxWindow:self]; + [_actionDelegate reloadFromRedBoxWindow:self]; } - (void)showExtraDataViewController { - [_actionDelegate loadExtraDataViewController]; + [_actionDelegate loadExtraDataViewController]; } - (void)copyStack { - NSMutableString *fullStackTrace; + NSMutableString *fullStackTrace; - if (_lastErrorMessage != nil) { - fullStackTrace = [_lastErrorMessage mutableCopy]; - [fullStackTrace appendString:@"\n\n"]; - } - else { - fullStackTrace = [NSMutableString string]; - } + if (_lastErrorMessage != nil) { + fullStackTrace = [_lastErrorMessage mutableCopy]; + [fullStackTrace appendString:@"\n\n"]; + } else { + fullStackTrace = [NSMutableString string]; + } - for (RCTJSStackFrame *stackFrame in _lastStackTrace) { - [fullStackTrace appendString:[NSString stringWithFormat:@"%@\n", stackFrame.methodName]]; - if (stackFrame.file) { - [fullStackTrace appendFormat:@" %@\n", [self formatFrameSource:stackFrame]]; - } + for (RCTJSStackFrame *stackFrame in _lastStackTrace) { + [fullStackTrace appendString:[NSString stringWithFormat:@"%@\n", stackFrame.methodName]]; + if (stackFrame.file) { + [fullStackTrace appendFormat:@" %@\n", [self formatFrameSource:stackFrame]]; } + } #if !TARGET_OS_TV - UIPasteboard *pb = [UIPasteboard generalPasteboard]; - [pb setString:fullStackTrace]; + UIPasteboard *pb = [UIPasteboard generalPasteboard]; + [pb setString:fullStackTrace]; #endif } - (NSString *)formatFrameSource:(RCTJSStackFrame *)stackFrame { - NSString *fileName = RCTNilIfNull(stackFrame.file) ? [stackFrame.file lastPathComponent] : @""; - NSString *lineInfo = [NSString stringWithFormat:@"%@:%lld", - fileName, - (long long)stackFrame.lineNumber]; + NSString *fileName = RCTNilIfNull(stackFrame.file) ? [stackFrame.file lastPathComponent] : @""; + NSString *lineInfo = [NSString stringWithFormat:@"%@:%lld", fileName, (long long)stackFrame.lineNumber]; - if (stackFrame.column != 0) { - lineInfo = [lineInfo stringByAppendingFormat:@":%lld", (long long)stackFrame.column]; - } - return lineInfo; + if (stackFrame.column != 0) { + lineInfo = [lineInfo stringByAppendingFormat:@":%lld", (long long)stackFrame.column]; + } + return lineInfo; } #pragma mark - TableView - (NSInteger)numberOfSectionsInTableView:(__unused UITableView *)tableView { - return 2; + return 2; } - (NSInteger)tableView:(__unused UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - return section == 0 ? 1 : _lastStackTrace.count; + return section == 0 ? 1 : _lastStackTrace.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - if (indexPath.section == 0) { - UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"msg-cell"]; - return [self reuseCell:cell forErrorMessage:_lastErrorMessage]; - } - UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; - NSUInteger index = indexPath.row; - RCTJSStackFrame *stackFrame = _lastStackTrace[index]; - return [self reuseCell:cell forStackFrame:stackFrame]; + if (indexPath.section == 0) { + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"msg-cell"]; + return [self reuseCell:cell forErrorMessage:_lastErrorMessage]; + } + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; + NSUInteger index = indexPath.row; + RCTJSStackFrame *stackFrame = _lastStackTrace[index]; + return [self reuseCell:cell forStackFrame:stackFrame]; } - (UITableViewCell *)reuseCell:(UITableViewCell *)cell forErrorMessage:(NSString *)message { - if (!cell) { - cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"msg-cell"]; - cell.textLabel.accessibilityIdentifier = @"redbox-error"; - cell.textLabel.textColor = [UIColor whiteColor]; - cell.textLabel.font = [UIFont boldSystemFontOfSize:16]; - cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping; - cell.textLabel.numberOfLines = 0; - cell.detailTextLabel.textColor = [UIColor whiteColor]; - cell.backgroundColor = [UIColor colorWithRed:0.82 green:0.10 blue:0.15 alpha:1.0]; - cell.selectionStyle = UITableViewCellSelectionStyleNone; - } + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"msg-cell"]; + cell.textLabel.accessibilityIdentifier = @"redbox-error"; + cell.textLabel.textColor = [UIColor whiteColor]; + cell.textLabel.font = [UIFont boldSystemFontOfSize:16]; + cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping; + cell.textLabel.numberOfLines = 0; + cell.detailTextLabel.textColor = [UIColor whiteColor]; + cell.backgroundColor = [UIColor colorWithRed:0.82 green:0.10 blue:0.15 alpha:1.0]; + cell.selectionStyle = UITableViewCellSelectionStyleNone; + } - cell.textLabel.text = message; + cell.textLabel.text = message; - return cell; + return cell; } - (UITableViewCell *)reuseCell:(UITableViewCell *)cell forStackFrame:(RCTJSStackFrame *)stackFrame { - if (!cell) { - cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"]; - cell.textLabel.font = [UIFont fontWithName:@"Menlo-Regular" size:14]; - cell.textLabel.lineBreakMode = NSLineBreakByCharWrapping; - cell.textLabel.numberOfLines = 2; - cell.detailTextLabel.textColor = [UIColor colorWithRed:0.70 green:0.70 blue:0.70 alpha:1.0]; - cell.detailTextLabel.font = [UIFont fontWithName:@"Menlo-Regular" size:11]; - cell.detailTextLabel.lineBreakMode = NSLineBreakByTruncatingMiddle; - cell.backgroundColor = [UIColor clearColor]; - cell.selectedBackgroundView = [UIView new]; - cell.selectedBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2]; - } + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"]; + cell.textLabel.font = [UIFont fontWithName:@"Menlo-Regular" size:14]; + cell.textLabel.lineBreakMode = NSLineBreakByCharWrapping; + cell.textLabel.numberOfLines = 2; + cell.detailTextLabel.textColor = [UIColor colorWithRed:0.70 green:0.70 blue:0.70 alpha:1.0]; + cell.detailTextLabel.font = [UIFont fontWithName:@"Menlo-Regular" size:11]; + cell.detailTextLabel.lineBreakMode = NSLineBreakByTruncatingMiddle; + cell.backgroundColor = [UIColor clearColor]; + cell.selectedBackgroundView = [UIView new]; + cell.selectedBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2]; + } - cell.textLabel.text = stackFrame.methodName ?: @"(unnamed method)"; - if (stackFrame.file) { - cell.detailTextLabel.text = [self formatFrameSource:stackFrame]; - } else { - cell.detailTextLabel.text = @""; - } - cell.textLabel.textColor = stackFrame.collapse ? [UIColor lightGrayColor] : [UIColor whiteColor]; - cell.detailTextLabel.textColor = stackFrame.collapse ? - [UIColor colorWithRed:0.50 green:0.50 blue:0.50 alpha:1.0] : - [UIColor colorWithRed:0.70 green:0.70 blue:0.70 alpha:1.0]; - return cell; + cell.textLabel.text = stackFrame.methodName ?: @"(unnamed method)"; + if (stackFrame.file) { + cell.detailTextLabel.text = [self formatFrameSource:stackFrame]; + } else { + cell.detailTextLabel.text = @""; + } + cell.textLabel.textColor = stackFrame.collapse ? [UIColor lightGrayColor] : [UIColor whiteColor]; + cell.detailTextLabel.textColor = stackFrame.collapse ? [UIColor colorWithRed:0.50 green:0.50 blue:0.50 alpha:1.0] + : [UIColor colorWithRed:0.70 green:0.70 blue:0.70 alpha:1.0]; + return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { - if (indexPath.section == 0) { - NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; - paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; + if (indexPath.section == 0) { + NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; + paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; - NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:16], - NSParagraphStyleAttributeName: paragraphStyle}; - CGRect boundingRect = [_lastErrorMessage boundingRectWithSize:CGSizeMake(tableView.frame.size.width - 30, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil]; - return ceil(boundingRect.size.height) + 40; - } else { - return 50; - } + NSDictionary *attributes = + @{NSFontAttributeName : [UIFont boldSystemFontOfSize:16], NSParagraphStyleAttributeName : paragraphStyle}; + CGRect boundingRect = + [_lastErrorMessage boundingRectWithSize:CGSizeMake(tableView.frame.size.width - 30, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin + attributes:attributes + context:nil]; + return ceil(boundingRect.size.height) + 40; + } else { + return 50; + } } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - if (indexPath.section == 1) { - NSUInteger row = indexPath.row; - RCTJSStackFrame *stackFrame = _lastStackTrace[row]; - [_actionDelegate redBoxWindow:self openStackFrameInEditor:stackFrame]; - } - [tableView deselectRowAtIndexPath:indexPath animated:YES]; + if (indexPath.section == 1) { + NSUInteger row = indexPath.row; + RCTJSStackFrame *stackFrame = _lastStackTrace[row]; + [_actionDelegate redBoxWindow:self openStackFrameInEditor:stackFrame]; + } + [tableView deselectRowAtIndexPath:indexPath animated:YES]; } #pragma mark - Key commands - (NSArray *)keyCommands { - // NOTE: We could use RCTKeyCommands for this, but since - // we control this window, we can use the standard, non-hacky - // mechanism instead + // NOTE: We could use RCTKeyCommands for this, but since + // we control this window, we can use the standard, non-hacky + // mechanism instead - return @[ - // Dismiss red box - [UIKeyCommand keyCommandWithInput:UIKeyInputEscape - modifierFlags:0 - action:@selector(dismiss)], + return @[ + // Dismiss red box + [UIKeyCommand keyCommandWithInput:UIKeyInputEscape modifierFlags:0 action:@selector(dismiss)], - // Reload - [UIKeyCommand keyCommandWithInput:@"r" - modifierFlags:UIKeyModifierCommand - action:@selector(reload)], + // Reload + [UIKeyCommand keyCommandWithInput:@"r" modifierFlags:UIKeyModifierCommand action:@selector(reload)], - // Copy = Cmd-Option C since Cmd-C in the simulator copies the pasteboard from - // the simulator to the desktop pasteboard. - [UIKeyCommand keyCommandWithInput:@"c" - modifierFlags:UIKeyModifierCommand | UIKeyModifierAlternate - action:@selector(copyStack)], + // Copy = Cmd-Option C since Cmd-C in the simulator copies the pasteboard from + // the simulator to the desktop pasteboard. + [UIKeyCommand keyCommandWithInput:@"c" + modifierFlags:UIKeyModifierCommand | UIKeyModifierAlternate + action:@selector(copyStack)], - // Extra data - [UIKeyCommand keyCommandWithInput:@"e" - modifierFlags:UIKeyModifierCommand - action:@selector(showExtraDataViewController)] - ]; + // Extra data + [UIKeyCommand keyCommandWithInput:@"e" + modifierFlags:UIKeyModifierCommand + action:@selector(showExtraDataViewController)] + ]; } - (BOOL)canBecomeFirstResponder { - return YES; + return YES; } @end -@interface RCTRedBox () +@interface RCTRedBox () < + RCTInvalidating, + RCTRedBoxWindowActionDelegate, + RCTRedBoxExtraDataActionDelegate, + NativeRedBoxSpec> @end -@implementation RCTRedBox -{ - RCTRedBoxWindow *_window; - NSMutableArray> *_errorCustomizers; - RCTRedBoxExtraDataViewController *_extraDataViewController; - NSMutableArray *_customButtonTitles; - NSMutableArray *_customButtonHandlers; +@implementation RCTRedBox { + RCTRedBoxWindow *_window; + NSMutableArray> *_errorCustomizers; + RCTRedBoxExtraDataViewController *_extraDataViewController; + NSMutableArray *_customButtonTitles; + NSMutableArray *_customButtonHandlers; } @synthesize bridge = _bridge; @@ -446,196 +463,218 @@ RCT_EXPORT_MODULE() - (void)registerErrorCustomizer:(id)errorCustomizer { - dispatch_async(dispatch_get_main_queue(), ^{ - if (!self->_errorCustomizers) { - self->_errorCustomizers = [NSMutableArray array]; - } - if (![self->_errorCustomizers containsObject:errorCustomizer]) { - [self->_errorCustomizers addObject:errorCustomizer]; - } - }); + dispatch_async(dispatch_get_main_queue(), ^{ + if (!self->_errorCustomizers) { + self->_errorCustomizers = [NSMutableArray array]; + } + if (![self->_errorCustomizers containsObject:errorCustomizer]) { + [self->_errorCustomizers addObject:errorCustomizer]; + } + }); } // WARNING: Should only be called from the main thread/dispatch queue. - (RCTErrorInfo *)_customizeError:(RCTErrorInfo *)error { - RCTAssertMainQueue(); - if (!self->_errorCustomizers) { - return error; - } - for (id customizer in self->_errorCustomizers) { - RCTErrorInfo *newInfo = [customizer customizeErrorInfo:error]; - if (newInfo) { - error = newInfo; - } - } + RCTAssertMainQueue(); + if (!self->_errorCustomizers) { return error; + } + for (id customizer in self->_errorCustomizers) { + RCTErrorInfo *newInfo = [customizer customizeErrorInfo:error]; + if (newInfo) { + error = newInfo; + } + } + return error; } - (void)showError:(NSError *)error { - [self showErrorMessage:error.localizedDescription - withDetails:error.localizedFailureReason - stack:error.userInfo[RCTJSStackTraceKey] - errorCookie:-1]; + [self showErrorMessage:error.localizedDescription + withDetails:error.localizedFailureReason + stack:error.userInfo[RCTJSStackTraceKey] + errorCookie:-1]; } - (void)showErrorMessage:(NSString *)message { - [self showErrorMessage:message withParsedStack:nil isUpdate:NO errorCookie:-1]; + [self showErrorMessage:message withParsedStack:nil isUpdate:NO errorCookie:-1]; } - (void)showErrorMessage:(NSString *)message withDetails:(NSString *)details { - [self showErrorMessage:message withDetails:details stack:nil errorCookie:-1]; + [self showErrorMessage:message withDetails:details stack:nil errorCookie:-1]; } -- (void)showErrorMessage:(NSString *)message withDetails:(NSString *)details stack:(NSArray *)stack errorCookie:(int)errorCookie { - NSString *combinedMessage = message; - if (details) { - combinedMessage = [NSString stringWithFormat:@"%@\n\n%@", message, details]; - } - [self showErrorMessage:combinedMessage withParsedStack:stack isUpdate:NO errorCookie:errorCookie]; +- (void)showErrorMessage:(NSString *)message + withDetails:(NSString *)details + stack:(NSArray *)stack + errorCookie:(int)errorCookie +{ + NSString *combinedMessage = message; + if (details) { + combinedMessage = [NSString stringWithFormat:@"%@\n\n%@", message, details]; + } + [self showErrorMessage:combinedMessage withParsedStack:stack isUpdate:NO errorCookie:errorCookie]; } - (void)showErrorMessage:(NSString *)message withRawStack:(NSString *)rawStack { - [self showErrorMessage:message withRawStack:rawStack errorCookie:-1]; + [self showErrorMessage:message withRawStack:rawStack errorCookie:-1]; } - (void)showErrorMessage:(NSString *)message withRawStack:(NSString *)rawStack errorCookie:(int)errorCookie { - NSArray *stack = [RCTJSStackFrame stackFramesWithLines:rawStack]; - [self showErrorMessage:message withParsedStack:stack isUpdate:NO errorCookie:errorCookie]; + NSArray *stack = [RCTJSStackFrame stackFramesWithLines:rawStack]; + [self showErrorMessage:message withParsedStack:stack isUpdate:NO errorCookie:errorCookie]; } - (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack { - [self showErrorMessage:message withStack:stack errorCookie:-1]; + [self showErrorMessage:message withStack:stack errorCookie:-1]; } - (void)updateErrorMessage:(NSString *)message withStack:(NSArray *)stack { - [self updateErrorMessage:message withStack:stack errorCookie:-1]; + [self updateErrorMessage:message withStack:stack errorCookie:-1]; } - (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack errorCookie:(int)errorCookie { - [self showErrorMessage:message withParsedStack:[RCTJSStackFrame stackFramesWithDictionaries:stack] isUpdate:NO errorCookie:errorCookie]; + [self showErrorMessage:message + withParsedStack:[RCTJSStackFrame stackFramesWithDictionaries:stack] + isUpdate:NO + errorCookie:errorCookie]; } - (void)updateErrorMessage:(NSString *)message withStack:(NSArray *)stack errorCookie:(int)errorCookie { - [self showErrorMessage:message withParsedStack:[RCTJSStackFrame stackFramesWithDictionaries:stack] isUpdate:YES errorCookie:errorCookie]; + [self showErrorMessage:message + withParsedStack:[RCTJSStackFrame stackFramesWithDictionaries:stack] + isUpdate:YES + errorCookie:errorCookie]; } - (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack { - [self showErrorMessage:message withParsedStack:stack errorCookie:-1]; + [self showErrorMessage:message withParsedStack:stack errorCookie:-1]; } - (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack { - [self updateErrorMessage:message withParsedStack:stack errorCookie:-1]; + [self updateErrorMessage:message withParsedStack:stack errorCookie:-1]; } -- (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack errorCookie:(int)errorCookie +- (void)showErrorMessage:(NSString *)message + withParsedStack:(NSArray *)stack + errorCookie:(int)errorCookie { - [self showErrorMessage:message withParsedStack:stack isUpdate:NO errorCookie:errorCookie]; + [self showErrorMessage:message withParsedStack:stack isUpdate:NO errorCookie:errorCookie]; } -- (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack errorCookie:(int)errorCookie +- (void)updateErrorMessage:(NSString *)message + withParsedStack:(NSArray *)stack + errorCookie:(int)errorCookie { - [self showErrorMessage:message withParsedStack:stack isUpdate:YES errorCookie:errorCookie]; + [self showErrorMessage:message withParsedStack:stack isUpdate:YES errorCookie:errorCookie]; } -- (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack isUpdate:(BOOL)isUpdate errorCookie:(int)errorCookie +- (void)showErrorMessage:(NSString *)message + withParsedStack:(NSArray *)stack + isUpdate:(BOOL)isUpdate + errorCookie:(int)errorCookie { - dispatch_async(dispatch_get_main_queue(), ^{ - if (self->_extraDataViewController == nil) { - self->_extraDataViewController = [RCTRedBoxExtraDataViewController new]; - self->_extraDataViewController.actionDelegate = self; - } + dispatch_async(dispatch_get_main_queue(), ^{ + if (self->_extraDataViewController == nil) { + self->_extraDataViewController = [RCTRedBoxExtraDataViewController new]; + self->_extraDataViewController.actionDelegate = self; + } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [self->_bridge.eventDispatcher sendDeviceEventWithName:@"collectRedBoxExtraData" body:nil]; + [self->_bridge.eventDispatcher sendDeviceEventWithName:@"collectRedBoxExtraData" body:nil]; #pragma clang diagnostic pop - if (!self->_window) { - self->_window = [[RCTRedBoxWindow alloc] initWithFrame:[UIScreen mainScreen].bounds customButtonTitles:self->_customButtonTitles customButtonHandlers:self->_customButtonHandlers]; - self->_window.actionDelegate = self; - } + if (!self->_window) { + self->_window = [[RCTRedBoxWindow alloc] initWithFrame:[UIScreen mainScreen].bounds + customButtonTitles:self->_customButtonTitles + customButtonHandlers:self->_customButtonHandlers]; + self->_window.actionDelegate = self; + } - RCTErrorInfo *errorInfo = [[RCTErrorInfo alloc] initWithErrorMessage:message - stack:stack]; - errorInfo = [self _customizeError:errorInfo]; - [self->_window showErrorMessage:errorInfo.errorMessage - withStack:errorInfo.stack - isUpdate:isUpdate - errorCookie:errorCookie]; - }); + RCTErrorInfo *errorInfo = [[RCTErrorInfo alloc] initWithErrorMessage:message stack:stack]; + errorInfo = [self _customizeError:errorInfo]; + [self->_window showErrorMessage:errorInfo.errorMessage + withStack:errorInfo.stack + isUpdate:isUpdate + errorCookie:errorCookie]; + }); } -- (void)loadExtraDataViewController { - dispatch_async(dispatch_get_main_queue(), ^{ - // Make sure the CMD+E shortcut doesn't call this twice - if (self->_extraDataViewController != nil && ![self->_window.rootViewController presentedViewController]) { - [self->_window.rootViewController presentViewController:self->_extraDataViewController animated:YES completion:nil]; - } - }); +- (void)loadExtraDataViewController +{ + dispatch_async(dispatch_get_main_queue(), ^{ + // Make sure the CMD+E shortcut doesn't call this twice + if (self->_extraDataViewController != nil && ![self->_window.rootViewController presentedViewController]) { + [self->_window.rootViewController presentViewController:self->_extraDataViewController + animated:YES + completion:nil]; + } + }); } -RCT_EXPORT_METHOD(setExtraData:(NSDictionary *)extraData forIdentifier:(NSString *)identifier) { - [_extraDataViewController addExtraData:extraData forIdentifier:identifier]; +RCT_EXPORT_METHOD(setExtraData : (NSDictionary *)extraData forIdentifier : (NSString *)identifier) +{ + [_extraDataViewController addExtraData:extraData forIdentifier:identifier]; } RCT_EXPORT_METHOD(dismiss) { - dispatch_async(dispatch_get_main_queue(), ^{ - [self->_window dismiss]; - }); + dispatch_async(dispatch_get_main_queue(), ^{ + [self->_window dismiss]; + }); } - (void)invalidate { - [self dismiss]; + [self dismiss]; } - (void)redBoxWindow:(__unused RCTRedBoxWindow *)redBoxWindow openStackFrameInEditor:(RCTJSStackFrame *)stackFrame { - NSURL *const bundleURL = _overrideBundleURL ?: _bridge.bundleURL; - if (![bundleURL.scheme hasPrefix:@"http"]) { - RCTLogWarn(@"Cannot open stack frame in editor because you're not connected to the packager."); - return; - } + NSURL *const bundleURL = _overrideBundleURL ?: _bridge.bundleURL; + if (![bundleURL.scheme hasPrefix:@"http"]) { + RCTLogWarn(@"Cannot open stack frame in editor because you're not connected to the packager."); + return; + } - NSData *stackFrameJSON = [RCTJSONStringify([stackFrame toDictionary], NULL) dataUsingEncoding:NSUTF8StringEncoding]; - NSString *postLength = [NSString stringWithFormat:@"%tu", stackFrameJSON.length]; - NSMutableURLRequest *request = [NSMutableURLRequest new]; - request.URL = [NSURL URLWithString:@"/open-stack-frame" relativeToURL:bundleURL]; - request.HTTPMethod = @"POST"; - request.HTTPBody = stackFrameJSON; - [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; - [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + NSData *stackFrameJSON = [RCTJSONStringify([stackFrame toDictionary], NULL) dataUsingEncoding:NSUTF8StringEncoding]; + NSString *postLength = [NSString stringWithFormat:@"%tu", stackFrameJSON.length]; + NSMutableURLRequest *request = [NSMutableURLRequest new]; + request.URL = [NSURL URLWithString:@"/open-stack-frame" relativeToURL:bundleURL]; + request.HTTPMethod = @"POST"; + request.HTTPBody = stackFrameJSON; + [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; + [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - [[[NSURLSession sharedSession] dataTaskWithRequest:request] resume]; + [[[NSURLSession sharedSession] dataTaskWithRequest:request] resume]; } - (void)reload { - // Window is not used and can be nil - [self reloadFromRedBoxWindow:nil]; + // Window is not used and can be nil + [self reloadFromRedBoxWindow:nil]; } - (void)reloadFromRedBoxWindow:(__unused RCTRedBoxWindow *)redBoxWindow { - if (_overrideReloadAction) { - _overrideReloadAction(); - } else { - RCTTriggerReloadCommandListeners(@"Redbox"); - } - [self dismiss]; + if (_overrideReloadAction) { + _overrideReloadAction(); + } else { + RCTTriggerReloadCommandListeners(@"Redbox"); + } + [self dismiss]; } - (void)addCustomButton:(NSString *)title onPressHandler:(RCTRedBoxButtonPressHandler)handler @@ -649,7 +688,8 @@ RCT_EXPORT_METHOD(dismiss) [_customButtonHandlers addObject:handler]; } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -667,32 +707,74 @@ RCT_EXPORT_METHOD(dismiss) #else // Disabled -@interface RCTRedBox() +@interface RCTRedBox () @end @implementation RCTRedBox -+ (NSString *)moduleName { return nil; } -- (void)registerErrorCustomizer:(id)errorCustomizer {} -- (void)showError:(NSError *)error {} -- (void)showErrorMessage:(NSString *)message {} -- (void)showErrorMessage:(NSString *)message withDetails:(NSString *)details {} -- (void)showErrorMessage:(NSString *)message withRawStack:(NSString *)rawStack {} -- (void)showErrorMessage:(NSString *)message withRawStack:(NSString *)rawStack errorCookie:(int)errorCookie {} -- (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack {} -- (void)updateErrorMessage:(NSString *)message withStack:(NSArray *)stack {} -- (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack errorCookie:(int)errorCookie {} -- (void)updateErrorMessage:(NSString *)message withStack:(NSArray *)stack errorCookie:(int)errorCookie {} -- (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack {} -- (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack {} -- (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack errorCookie:(int)errorCookie {} -- (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack errorCookie:(int)errorCookie {} -- (void)setExtraData:(NSDictionary *)extraData forIdentifier:(NSString *)identifier {} ++ (NSString *)moduleName +{ + return nil; +} +- (void)registerErrorCustomizer:(id)errorCustomizer +{ +} +- (void)showError:(NSError *)error +{ +} +- (void)showErrorMessage:(NSString *)message +{ +} +- (void)showErrorMessage:(NSString *)message withDetails:(NSString *)details +{ +} +- (void)showErrorMessage:(NSString *)message withRawStack:(NSString *)rawStack +{ +} +- (void)showErrorMessage:(NSString *)message withRawStack:(NSString *)rawStack errorCookie:(int)errorCookie +{ +} +- (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack +{ +} +- (void)updateErrorMessage:(NSString *)message withStack:(NSArray *)stack +{ +} +- (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack errorCookie:(int)errorCookie +{ +} +- (void)updateErrorMessage:(NSString *)message withStack:(NSArray *)stack errorCookie:(int)errorCookie +{ +} +- (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack +{ +} +- (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray *)stack +{ +} +- (void)showErrorMessage:(NSString *)message + withParsedStack:(NSArray *)stack + errorCookie:(int)errorCookie +{ +} +- (void)updateErrorMessage:(NSString *)message + withParsedStack:(NSArray *)stack + errorCookie:(int)errorCookie +{ +} +- (void)setExtraData:(NSDictionary *)extraData forIdentifier:(NSString *)identifier +{ +} -- (void)dismiss {} +- (void)dismiss +{ +} -- (void)addCustomButton:(NSString *)title onPressHandler:(RCTRedBoxButtonPressHandler)handler {} -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (void)addCustomButton:(NSString *)title onPressHandler:(RCTRedBoxButtonPressHandler)handler +{ +} +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -701,12 +783,16 @@ RCT_EXPORT_METHOD(dismiss) @implementation RCTBridge (RCTRedBox) -- (RCTRedBox *)redBox { return nil; } +- (RCTRedBox *)redBox +{ + return nil; +} @end #endif -Class RCTRedBoxCls(void) { +Class RCTRedBoxCls(void) +{ return RCTRedBox.class; } diff --git a/React/CoreModules/RCTSourceCode.mm b/React/CoreModules/RCTSourceCode.mm index 761016f7d94..21c88c19c3c 100644 --- a/React/CoreModules/RCTSourceCode.mm +++ b/React/CoreModules/RCTSourceCode.mm @@ -37,7 +37,7 @@ RCT_EXPORT_MODULE() - (NSDictionary *)getConstants { return @{ - @"scriptURL": self.bridge.bundleURL.absoluteString ?: @"", + @"scriptURL" : self.bridge.bundleURL.absoluteString ?: @"", }; } @@ -48,6 +48,7 @@ RCT_EXPORT_MODULE() @end -Class RCTSourceCodeCls(void) { +Class RCTSourceCodeCls(void) +{ return RCTSourceCode.class; } diff --git a/React/CoreModules/RCTStatusBarManager.mm b/React/CoreModules/RCTStatusBarManager.mm index 2f74040625c..c2816db822e 100644 --- a/React/CoreModules/RCTStatusBarManager.mm +++ b/React/CoreModules/RCTStatusBarManager.mm @@ -43,7 +43,8 @@ } }); return _RCT_CAST( - UIStatusBarStyle, [RCTConvertEnumValue("UIStatusBarStyle", mapping, @(UIStatusBarStyleDefault), json) integerValue]); + UIStatusBarStyle, + [RCTConvertEnumValue("UIStatusBarStyle", mapping, @(UIStatusBarStyleDefault), json) integerValue]); } RCT_ENUM_CONVERTER( @@ -61,7 +62,7 @@ RCT_ENUM_CONVERTER( #if !TARGET_OS_TV -@interface RCTStatusBarManager() +@interface RCTStatusBarManager () @end #endif @@ -185,8 +186,8 @@ RCT_EXPORT_METHOD(setNetworkActivityIndicatorVisible : (BOOL)visible) - (facebook::react::ModuleConstants)getConstants { return facebook::react::typedConstants({ - .HEIGHT = RCTSharedApplication().statusBarFrame.size.height, - .DEFAULT_BACKGROUND_COLOR = folly::none, + .HEIGHT = RCTSharedApplication().statusBarFrame.size.height, + .DEFAULT_BACKGROUND_COLOR = folly::none, }); } @@ -195,7 +196,8 @@ RCT_EXPORT_METHOD(setNetworkActivityIndicatorVisible : (BOOL)visible) return (facebook::react::ModuleConstants)[self getConstants]; } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -204,6 +206,7 @@ RCT_EXPORT_METHOD(setNetworkActivityIndicatorVisible : (BOOL)visible) @end -Class RCTStatusBarManagerCls(void) { +Class RCTStatusBarManagerCls(void) +{ return RCTStatusBarManager.class; } diff --git a/React/CoreModules/RCTTVNavigationEventEmitter.mm b/React/CoreModules/RCTTVNavigationEventEmitter.mm index c38bf68a835..fad555bb55c 100644 --- a/React/CoreModules/RCTTVNavigationEventEmitter.mm +++ b/React/CoreModules/RCTTVNavigationEventEmitter.mm @@ -14,7 +14,7 @@ NSString *const RCTTVNavigationEventNotification = @"RCTTVNavigationEventNotific static NSString *const TVNavigationEventName = @"onHWKeyEvent"; -@interface RCTTVNavigationEventEmitter() +@interface RCTTVNavigationEventEmitter () @end @implementation RCTTVNavigationEventEmitter @@ -33,14 +33,13 @@ RCT_EXPORT_MODULE() selector:@selector(handleTVNavigationEventNotification:) name:RCTTVNavigationEventNotification object:nil]; - } return self; } - (NSArray *)supportedEvents { - return @[TVNavigationEventName]; + return @[ TVNavigationEventName ]; } - (void)handleTVNavigationEventNotification:(NSNotification *)notif @@ -50,13 +49,15 @@ RCT_EXPORT_MODULE() } } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @end -Class RCTTVNavigationEventEmitterCls(void) { +Class RCTTVNavigationEventEmitterCls(void) +{ return RCTTVNavigationEventEmitter.class; } diff --git a/React/CoreModules/RCTTiming.h b/React/CoreModules/RCTTiming.h index f004bd302f6..4776f85e2b7 100644 --- a/React/CoreModules/RCTTiming.h +++ b/React/CoreModules/RCTTiming.h @@ -21,7 +21,7 @@ @interface RCTTiming : NSObject -- (instancetype)initWithDelegate:(id) delegate; +- (instancetype)initWithDelegate:(id)delegate; - (void)createTimerForNextFrame:(nonnull NSNumber *)callbackID duration:(NSTimeInterval)jsDuration jsSchedulingTime:(NSDate *)jsSchedulingTime @@ -29,4 +29,3 @@ - (void)deleteTimer:(double)timerID; @end - diff --git a/React/CoreModules/RCTWebSocketExecutor.mm b/React/CoreModules/RCTWebSocketExecutor.mm index f1225e21fd7..3422cf049f6 100644 --- a/React/CoreModules/RCTWebSocketExecutor.mm +++ b/React/CoreModules/RCTWebSocketExecutor.mm @@ -12,8 +12,8 @@ #import #import #import -#import #import +#import #import @@ -27,8 +27,7 @@ typedef void (^RCTWSMessageCallback)(NSError *error, NSDictionary *_callbacks; @@ -57,7 +56,8 @@ RCT_EXPORT_MODULE() if (!_url) { NSInteger port = [[[_bridge bundleURL] port] integerValue] ?: RCT_METRO_PORT; NSString *host = [[_bridge bundleURL] host] ?: @"localhost"; - NSString *URLString = [NSString stringWithFormat:@"http://%@:%lld/debugger-proxy?role=client", host, (long long)port]; + NSString *URLString = + [NSString stringWithFormat:@"http://%@:%lld/debugger-proxy?role=client", host, (long long)port]; _url = [RCTConvert NSURL:URLString]; } @@ -71,14 +71,18 @@ RCT_EXPORT_MODULE() NSURL *startDevToolsURL = [NSURL URLWithString:@"/launch-js-devtools" relativeToURL:_url]; NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:[NSURLRequest requestWithURL:startDevToolsURL] - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){}]; + NSURLSessionDataTask *dataTask = + [session dataTaskWithRequest:[NSURLRequest requestWithURL:startDevToolsURL] + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){ + }]; [dataTask resume]; if (![self connectToProxy]) { [self invalidate]; - NSString *error = [NSString stringWithFormat:@"Connection to %@ timed out. Are you " - "running node proxy? If you are running on the device, check if " - "you have the right IP address in `RCTWebSocketExecutor.m`.", _url]; + NSString *error = [NSString stringWithFormat: + @"Connection to %@ timed out. Are you " + "running node proxy? If you are running on the device, check if " + "you have the right IP address in `RCTWebSocketExecutor.m`.", + _url]; _setupError = RCTErrorWithMessage(error); RCTFatal(_setupError); return; @@ -92,10 +96,11 @@ RCT_EXPORT_MODULE() } if (!runtimeIsReady) { [self invalidate]; - NSString *error = @"Runtime is not ready for debugging.\n " - "- Make sure Packager server is running.\n" - "- Make sure the JavaScript Debugger is running and not paused on a " - "breakpoint or exception and try reloading again."; + NSString *error = + @"Runtime is not ready for debugging.\n " + "- Make sure Packager server is running.\n" + "- Make sure the JavaScript Debugger is running and not paused on a " + "breakpoint or exception and try reloading again."; _setupError = RCTErrorWithMessage(error); RCTFatal(_setupError); return; @@ -114,10 +119,11 @@ RCT_EXPORT_MODULE() { __block NSError *initError; dispatch_semaphore_t s = dispatch_semaphore_create(0); - [self sendMessage:@{@"method": @"prepareJSRuntime"} onReply:^(NSError *error, NSDictionary *reply) { - initError = error; - dispatch_semaphore_signal(s); - }]; + [self sendMessage:@{@"method" : @"prepareJSRuntime"} + onReply:^(NSError *error, NSDictionary *reply) { + initError = error; + dispatch_semaphore_signal(s); + }]; long runtimeIsReady = dispatch_semaphore_wait(s, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 10)); if (initError) { RCTLogInfo(@"Websocket runtime setup failed: %@", initError); @@ -171,7 +177,9 @@ RCT_EXPORT_MODULE() }); } -- (void)executeApplicationScript:(NSData *)script sourceURL:(NSURL *)URL onComplete:(RCTJavaScriptCompleteBlock)onComplete +- (void)executeApplicationScript:(NSData *)script + sourceURL:(NSURL *)URL + onComplete:(RCTJavaScriptCompleteBlock)onComplete { // Hack: the bridge transitions out of loading state as soon as this method returns, which prevents us // from completely invalidating the bridge and preventing an endless barage of RCTLog.logIfNoNativeHook @@ -179,19 +187,20 @@ RCT_EXPORT_MODULE() dispatch_semaphore_t scriptSem = dispatch_semaphore_create(0); NSDictionary *message = @{ - @"method": @"executeApplicationScript", - @"url": RCTNullIfNil(URL.absoluteString), - @"inject": _injectedObjects, + @"method" : @"executeApplicationScript", + @"url" : RCTNullIfNil(URL.absoluteString), + @"inject" : _injectedObjects, }; - [self sendMessage:message onReply:^(NSError *socketError, NSDictionary *reply) { - if (socketError) { - onComplete(socketError); - } else { - NSString *error = reply[@"error"]; - onComplete(error ? RCTErrorWithMessage(error) : nil); - } - dispatch_semaphore_signal(scriptSem); - }]; + [self sendMessage:message + onReply:^(NSError *socketError, NSDictionary *reply) { + if (socketError) { + onComplete(socketError); + } else { + NSString *error = reply[@"error"]; + onComplete(error ? RCTErrorWithMessage(error) : nil); + } + dispatch_semaphore_signal(scriptSem); + }]; dispatch_semaphore_wait(scriptSem, DISPATCH_TIME_FOREVER); } @@ -206,37 +215,35 @@ RCT_EXPORT_MODULE() arguments:(NSArray *)args callback:(RCTJavaScriptCallback)onComplete { - [self _executeJSCall:@"callFunctionReturnFlushedQueue" arguments:@[module, method, args] callback:onComplete]; + [self _executeJSCall:@"callFunctionReturnFlushedQueue" arguments:@[ module, method, args ] callback:onComplete]; } -- (void)invokeCallbackID:(NSNumber *)cbID - arguments:(NSArray *)args - callback:(RCTJavaScriptCallback)onComplete +- (void)invokeCallbackID:(NSNumber *)cbID arguments:(NSArray *)args callback:(RCTJavaScriptCallback)onComplete { - [self _executeJSCall:@"invokeCallbackAndReturnFlushedQueue" arguments:@[cbID, args] callback:onComplete]; + [self _executeJSCall:@"invokeCallbackAndReturnFlushedQueue" arguments:@[ cbID, args ] callback:onComplete]; } - (void)_executeJSCall:(NSString *)method arguments:(NSArray *)arguments callback:(RCTJavaScriptCallback)onComplete { RCTAssert(onComplete != nil, @"callback was missing for exec JS call"); - NSDictionary *message = @{ - @"method": method, - @"arguments": arguments - }; - [self sendMessage:message onReply:^(NSError *socketError, NSDictionary *reply) { - if (socketError) { - onComplete(nil, socketError); - return; - } + NSDictionary *message = @{@"method" : method, @"arguments" : arguments}; + [self sendMessage:message + onReply:^(NSError *socketError, NSDictionary *reply) { + if (socketError) { + onComplete(nil, socketError); + return; + } - NSError *jsonError; - id result = RCTJSONParse(reply[@"result"], &jsonError); - NSString *error = reply[@"error"]; - onComplete(result, error ? RCTErrorWithMessage(error) : jsonError); - }]; + NSError *jsonError; + id result = RCTJSONParse(reply[@"result"], &jsonError); + NSString *error = reply[@"error"]; + onComplete(result, error ? RCTErrorWithMessage(error) : jsonError); + }]; } -- (void)injectJSONText:(NSString *)script asGlobalObjectNamed:(NSString *)objectName callback:(RCTJavaScriptCompleteBlock)onComplete +- (void)injectJSONText:(NSString *)script + asGlobalObjectNamed:(NSString *)objectName + callback:(RCTJavaScriptCompleteBlock)onComplete { dispatch_async(_jsQueue, ^{ self->_injectedObjects[objectName] = script; @@ -275,7 +282,8 @@ RCT_EXPORT_MODULE() #endif -Class RCTWebSocketExecutorCls(void) { +Class RCTWebSocketExecutorCls(void) +{ #if RCT_DEV return RCTWebSocketExecutor.class; #else diff --git a/React/CoreModules/RCTWebSocketModule.mm b/React/CoreModules/RCTWebSocketModule.mm index 06734d324cc..0eb45855688 100644 --- a/React/CoreModules/RCTWebSocketModule.mm +++ b/React/CoreModules/RCTWebSocketModule.mm @@ -11,8 +11,8 @@ #import #import -#import #import +#import #import "CoreModulesPlugins.h" @@ -34,8 +34,7 @@ @end -@implementation RCTWebSocketModule -{ +@implementation RCTWebSocketModule { NSMutableDictionary *_sockets; NSMutableDictionary> *_contentHandlers; } @@ -49,10 +48,7 @@ RCT_EXPORT_MODULE() - (NSArray *)supportedEvents { - return @[@"websocketMessage", - @"websocketOpen", - @"websocketFailed", - @"websocketClosed"]; + return @[ @"websocketMessage", @"websocketOpen", @"websocketFailed", @"websocketClosed" ]; } - (void)invalidate @@ -64,7 +60,11 @@ RCT_EXPORT_MODULE() } } -RCT_EXPORT_METHOD(connect:(NSURL *)URL protocols:(NSArray *)protocols options:(JS::NativeWebSocketModule::SpecConnectOptions &)options socketID:(double)socketID) +RCT_EXPORT_METHOD(connect + : (NSURL *)URL protocols + : (NSArray *)protocols options + : (JS::NativeWebSocketModule::SpecConnectOptions &)options socketID + : (double)socketID) { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; @@ -99,27 +99,27 @@ RCT_EXPORT_METHOD(connect:(NSURL *)URL protocols:(NSArray *)protocols options:(J [webSocket open]; } -RCT_EXPORT_METHOD(send:(NSString *)message forSocketID:(double)socketID) +RCT_EXPORT_METHOD(send : (NSString *)message forSocketID : (double)socketID) { [_sockets[@(socketID)] send:message]; } -RCT_EXPORT_METHOD(sendBinary:(NSString *)base64String forSocketID:(double)socketID) +RCT_EXPORT_METHOD(sendBinary : (NSString *)base64String forSocketID : (double)socketID) { [self sendData:[[NSData alloc] initWithBase64EncodedString:base64String options:0] forSocketID:@(socketID)]; } -- (void)sendData:(NSData *)data forSocketID:(NSNumber * __nonnull)socketID +- (void)sendData:(NSData *)data forSocketID:(NSNumber *__nonnull)socketID { [_sockets[socketID] send:data]; } -RCT_EXPORT_METHOD(ping:(double)socketID) +RCT_EXPORT_METHOD(ping : (double)socketID) { [_sockets[@(socketID)] sendPing:NULL]; } -RCT_EXPORT_METHOD(close:(double)code reason:(NSString *)reason socketID:(double)socketID) +RCT_EXPORT_METHOD(close : (double)code reason : (NSString *)reason socketID : (double)socketID) { [_sockets[@(socketID)] closeWithCode:code reason:reason]; [_sockets removeObjectForKey:@(socketID)]; @@ -152,19 +152,13 @@ RCT_EXPORT_METHOD(close:(double)code reason:(NSString *)reason socketID:(double) } } - [self sendEventWithName:@"websocketMessage" body:@{ - @"data": message, - @"type": type, - @"id": webSocket.reactTag - }]; + [self sendEventWithName:@"websocketMessage" body:@{@"data" : message, @"type" : type, @"id" : webSocket.reactTag}]; } - (void)webSocketDidOpen:(RCTSRWebSocket *)webSocket { - [self sendEventWithName:@"websocketOpen" body:@{ - @"id": webSocket.reactTag, - @"protocol": webSocket.protocol ? webSocket.protocol : @"" - }]; + [self sendEventWithName:@"websocketOpen" + body:@{@"id" : webSocket.reactTag, @"protocol" : webSocket.protocol ? webSocket.protocol : @""}]; } - (void)webSocket:(RCTSRWebSocket *)webSocket didFailWithError:(NSError *)error @@ -172,29 +166,28 @@ RCT_EXPORT_METHOD(close:(double)code reason:(NSString *)reason socketID:(double) NSNumber *socketID = [webSocket reactTag]; _contentHandlers[socketID] = nil; _sockets[socketID] = nil; - [self sendEventWithName:@"websocketFailed" body:@{ - @"message": error.localizedDescription, - @"id": socketID - }]; + [self sendEventWithName:@"websocketFailed" body:@{@"message" : error.localizedDescription, @"id" : socketID}]; } - (void)webSocket:(RCTSRWebSocket *)webSocket - didCloseWithCode:(NSInteger)code - reason:(NSString *)reason - wasClean:(BOOL)wasClean + didCloseWithCode:(NSInteger)code + reason:(NSString *)reason + wasClean:(BOOL)wasClean { NSNumber *socketID = [webSocket reactTag]; _contentHandlers[socketID] = nil; _sockets[socketID] = nil; - [self sendEventWithName:@"websocketClosed" body:@{ - @"code": @(code), - @"reason": RCTNullIfNil(reason), - @"clean": @(wasClean), - @"id": socketID - }]; + [self sendEventWithName:@"websocketClosed" + body:@{ + @"code" : @(code), + @"reason" : RCTNullIfNil(reason), + @"clean" : @(wasClean), + @"id" : socketID + }]; } -- (std::shared_ptr)getTurboModuleWithJsInvoker:(std::shared_ptr)jsInvoker +- (std::shared_ptr)getTurboModuleWithJsInvoker: + (std::shared_ptr)jsInvoker { return std::make_shared(self, jsInvoker); } @@ -210,6 +203,7 @@ RCT_EXPORT_METHOD(close:(double)code reason:(NSString *)reason socketID:(double) @end -Class RCTWebSocketModuleCls(void) { +Class RCTWebSocketModuleCls(void) +{ return RCTWebSocketModule.class; } diff --git a/React/CxxBridge/JSCExecutorFactory.h b/React/CxxBridge/JSCExecutorFactory.h index d75af7ff719..27296f88f74 100644 --- a/React/CxxBridge/JSCExecutorFactory.h +++ b/React/CxxBridge/JSCExecutorFactory.h @@ -13,16 +13,15 @@ namespace facebook { namespace react { class JSCExecutorFactory : public JSExecutorFactory { -public: - explicit JSCExecutorFactory( - JSIExecutor::RuntimeInstaller runtimeInstaller) + public: + explicit JSCExecutorFactory(JSIExecutor::RuntimeInstaller runtimeInstaller) : runtimeInstaller_(std::move(runtimeInstaller)) {} std::unique_ptr createJSExecutor( std::shared_ptr delegate, std::shared_ptr jsQueue) override; -private: + private: JSIExecutor::RuntimeInstaller runtimeInstaller_; }; diff --git a/React/CxxBridge/JSCExecutorFactory.mm b/React/CxxBridge/JSCExecutorFactory.mm index 12d96eb5c16..411a083dc35 100644 --- a/React/CxxBridge/JSCExecutorFactory.mm +++ b/React/CxxBridge/JSCExecutorFactory.mm @@ -10,19 +10,18 @@ #import #import -#import +#import namespace facebook { namespace react { std::unique_ptr JSCExecutorFactory::createJSExecutor( std::shared_ptr delegate, - std::shared_ptr __unused jsQueue) { - auto installBindings = [runtimeInstaller=runtimeInstaller_](jsi::Runtime &runtime) { + std::shared_ptr __unused jsQueue) +{ + auto installBindings = [runtimeInstaller = runtimeInstaller_](jsi::Runtime &runtime) { react::Logger iosLoggingBinder = [](const std::string &message, unsigned int logLevel) { - _RCTLogJavaScriptInternal( - static_cast(logLevel), - [NSString stringWithUTF8String:message.c_str()]); + _RCTLogJavaScriptInternal(static_cast(logLevel), [NSString stringWithUTF8String:message.c_str()]); }; react::bindNativeLogger(runtime, iosLoggingBinder); // Wrap over the original runtimeInstaller @@ -31,10 +30,7 @@ std::unique_ptr JSCExecutorFactory::createJSExecutor( } }; return std::make_unique( - facebook::jsc::makeJSCRuntime(), - delegate, - JSIExecutor::defaultTimeoutInvoker, - std::move(installBindings)); + facebook::jsc::makeJSCRuntime(), delegate, JSIExecutor::defaultTimeoutInvoker, std::move(installBindings)); } } // namespace react diff --git a/React/CxxBridge/NSDataBigString.h b/React/CxxBridge/NSDataBigString.h index b6dabbf5365..8bf0706d278 100644 --- a/React/CxxBridge/NSDataBigString.h +++ b/React/CxxBridge/NSDataBigString.h @@ -13,26 +13,30 @@ namespace facebook { namespace react { class NSDataBigString : public JSBigString { -public: + public: // The NSData passed in must be be null-terminated. NSDataBigString(NSData *data); // The ASCII optimization is not enabled on iOS - bool isAscii() const override { + bool isAscii() const override + { return false; } - const char *c_str() const override { + const char *c_str() const override + { return (const char *)[m_data bytes]; } - size_t size() const override { + size_t size() const override + { return m_length; } -private: + private: NSData *m_data; size_t m_length; }; -} } +} +} diff --git a/React/CxxBridge/NSDataBigString.mm b/React/CxxBridge/NSDataBigString.mm index bec684ce26f..b31daabac89 100644 --- a/React/CxxBridge/NSDataBigString.mm +++ b/React/CxxBridge/NSDataBigString.mm @@ -39,4 +39,5 @@ NSDataBigString::NSDataBigString(NSData *data) m_data = ensureNullTerminated(data); } -} } +} +} diff --git a/React/CxxBridge/RCTCxxBridge.mm b/React/CxxBridge/RCTCxxBridge.mm index 31455a5da90..31353856afe 100644 --- a/React/CxxBridge/RCTCxxBridge.mm +++ b/React/CxxBridge/RCTCxxBridge.mm @@ -18,6 +18,7 @@ #import #import #import +#import #import #import #import @@ -26,7 +27,6 @@ #import #import #import -#import #import #import #import @@ -69,47 +69,52 @@ typedef NS_ENUM(NSUInteger, RCTBridgeFields) { namespace { class GetDescAdapter : public JSExecutorFactory { -public: - GetDescAdapter(RCTCxxBridge *bridge, std::shared_ptr factory) - : bridge_(bridge) - , factory_(factory) {} + public: + GetDescAdapter(RCTCxxBridge *bridge, std::shared_ptr factory) : bridge_(bridge), factory_(factory) + { + } std::unique_ptr createJSExecutor( std::shared_ptr delegate, - std::shared_ptr jsQueue) override { + std::shared_ptr jsQueue) override + { auto ret = factory_->createJSExecutor(delegate, jsQueue); bridge_.bridgeDescription = @(ret->getDescription().c_str()); return ret; } -private: + private: RCTCxxBridge *bridge_; std::shared_ptr factory_; }; } -static bool isRAMBundle(NSData *script) { +static bool isRAMBundle(NSData *script) +{ BundleHeader header; [script getBytes:&header length:sizeof(header)]; return parseTypeFromHeader(header) == ScriptTag::RAMBundle; } -static void notifyAboutModuleSetup(RCTPerformanceLogger *performanceLogger, const char *tag) { +static void notifyAboutModuleSetup(RCTPerformanceLogger *performanceLogger, const char *tag) +{ NSString *moduleName = [[NSString alloc] initWithUTF8String:tag]; if (moduleName) { int64_t setupTime = [performanceLogger durationForTag:RCTPLNativeModuleSetup]; [[NSNotificationCenter defaultCenter] postNotificationName:RCTDidSetupModuleNotification object:nil userInfo:@{ - RCTDidSetupModuleNotificationModuleNameKey: moduleName, - RCTDidSetupModuleNotificationSetupTimeKey: @(setupTime) - }]; + RCTDidSetupModuleNotificationModuleNameKey : moduleName, + RCTDidSetupModuleNotificationSetupTimeKey : @(setupTime) + }]; } } -static void registerPerformanceLoggerHooks(RCTPerformanceLogger *performanceLogger) { +static void registerPerformanceLoggerHooks(RCTPerformanceLogger *performanceLogger) +{ __weak RCTPerformanceLogger *weakPerformanceLogger = performanceLogger; - ReactMarker::logTaggedMarker = [weakPerformanceLogger](const ReactMarker::ReactMarkerId markerId, const char *__unused tag) { + ReactMarker::logTaggedMarker = [weakPerformanceLogger]( + const ReactMarker::ReactMarkerId markerId, const char *__unused tag) { switch (markerId) { case ReactMarker::RUN_JS_BUNDLE_START: [weakPerformanceLogger markStartForTag:RCTPLScriptExecution]; @@ -155,16 +160,16 @@ static void registerPerformanceLoggerHooks(RCTPerformanceLogger *performanceLogg struct RCTInstanceCallback : public InstanceCallback { __weak RCTCxxBridge *bridge_; - RCTInstanceCallback(RCTCxxBridge *bridge): bridge_(bridge) {}; - void onBatchComplete() override { + RCTInstanceCallback(RCTCxxBridge *bridge) : bridge_(bridge){}; + void onBatchComplete() override + { // There's no interface to call this per partial batch [bridge_ partialBatchDidFlush]; [bridge_ batchDidComplete]; } }; -@implementation RCTCxxBridge -{ +@implementation RCTCxxBridge { BOOL _didInvalidate; BOOL _moduleRegistryCreated; @@ -195,7 +200,7 @@ struct RCTInstanceCallback : public InstanceCallback { @synthesize performanceLogger = _performanceLogger; @synthesize valid = _valid; -- (void) setRCTTurboModuleLookupDelegate:(id)turboModuleLookupDelegate +- (void)setRCTTurboModuleLookupDelegate:(id)turboModuleLookupDelegate { _turboModuleLookupDelegate = turboModuleLookupDelegate; } @@ -262,7 +267,9 @@ struct RCTInstanceCallback : public InstanceCallback { RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @""); // run the run loop - while (kCFRunLoopRunStopped != CFRunLoopRunInMode(kCFRunLoopDefaultMode, ((NSDate *)[NSDate distantFuture]).timeIntervalSinceReferenceDate, NO)) { + while (kCFRunLoopRunStopped != + CFRunLoopRunInMode( + kCFRunLoopDefaultMode, ((NSDate *)[NSDate distantFuture]).timeIntervalSinceReferenceDate, NO)) { RCTAssert(NO, @"not reached assertion"); // runloop spun. that's bad. } } @@ -292,10 +299,7 @@ struct RCTInstanceCallback : public InstanceCallback { if ([NSThread currentThread] == _jsThread) { [self _tryAndHandleError:block]; } else { - [self performSelector:@selector(_tryAndHandleError:) - onThread:_jsThread - withObject:block - waitUntilDone:NO]; + [self performSelector:@selector(_tryAndHandleError:) onThread:_jsThread withObject:block waitUntilDone:NO]; } } @@ -303,14 +307,12 @@ struct RCTInstanceCallback : public InstanceCallback { { RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[RCTCxxBridge start]", nil); - [[NSNotificationCenter defaultCenter] - postNotificationName:RCTJavaScriptWillStartLoadingNotification - object:_parentBridge userInfo:@{@"bridge": self}]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptWillStartLoadingNotification + object:_parentBridge + userInfo:@{@"bridge" : self}]; // Set up the JS thread early - _jsThread = [[NSThread alloc] initWithTarget:[self class] - selector:@selector(runRunLoop) - object:nil]; + _jsThread = [[NSThread alloc] initWithTarget:[self class] selector:@selector(runRunLoop) object:nil]; _jsThread.name = RCTJSThreadName; _jsThread.qualityOfService = NSOperationQualityOfServiceUserInteractive; #if RCT_DEBUG @@ -338,7 +340,7 @@ struct RCTInstanceCallback : public InstanceCallback { std::shared_ptr executorFactory; if (!self.executorClass) { if ([self.delegate conformsToProtocol:@protocol(RCTCxxBridgeDelegate)]) { - id cxxDelegate = (id) self.delegate; + id cxxDelegate = (id)self.delegate; executorFactory = [cxxDelegate jsExecutorFactoryForBridge:self]; } if (!executorFactory) { @@ -364,20 +366,22 @@ struct RCTInstanceCallback : public InstanceCallback { // Load the source asynchronously, then store it for later execution. dispatch_group_enter(prepareBridge); __block NSData *sourceCode; - [self loadSource:^(NSError *error, RCTSource *source) { - if (error) { - [weakSelf handleError:error]; - } + [self + loadSource:^(NSError *error, RCTSource *source) { + if (error) { + [weakSelf handleError:error]; + } - sourceCode = source.data; - dispatch_group_leave(prepareBridge); - } onProgress:^(RCTLoadingProgress *progressData) { + sourceCode = source.data; + dispatch_group_leave(prepareBridge); + } + onProgress:^(RCTLoadingProgress *progressData) { #if (RCT_DEV | RCT_ENABLE_LOADING_VIEW) && __has_include() - // Note: RCTDevLoadingView should have been loaded at this point, so no need to allow lazy loading. - id loadingView = [weakSelf moduleForName:@"DevLoadingView" lazilyLoadIfNecessary:NO]; - [loadingView updateProgress:progressData]; + // Note: RCTDevLoadingView should have been loaded at this point, so no need to allow lazy loading. + id loadingView = [weakSelf moduleForName:@"DevLoadingView" lazilyLoadIfNecessary:NO]; + [loadingView updateProgress:progressData]; #endif - }]; + }]; // Wait for both the modules and source code to have finished loading dispatch_group_notify(prepareBridge, dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{ @@ -406,8 +410,8 @@ struct RCTInstanceCallback : public InstanceCallback { [performanceLogger setValue:source.length forTag:RCTPLBundleSize]; NSDictionary *userInfo = @{ - RCTBridgeDidDownloadScriptNotificationSourceKey: source ?: [NSNull null], - RCTBridgeDidDownloadScriptNotificationBridgeDescriptionKey: self->_bridgeDescription ?: [NSNull null], + RCTBridgeDidDownloadScriptNotificationSourceKey : source ?: [NSNull null], + RCTBridgeDidDownloadScriptNotificationBridgeDescriptionKey : self->_bridgeDescription ?: [NSNull null], }; [center postNotificationName:RCTBridgeDidDownloadScriptNotification object:self->_parentBridge userInfo:userInfo]; @@ -420,26 +424,30 @@ struct RCTInstanceCallback : public InstanceCallback { } else if ([self.delegate respondsToSelector:@selector(loadSourceForBridge:withBlock:)]) { [self.delegate loadSourceForBridge:_parentBridge withBlock:onSourceLoad]; } else if (!self.bundleURL) { - NSError *error = RCTErrorWithMessage(@"No bundle URL present.\n\nMake sure you're running a packager " \ - "server or have included a .jsbundle file in your application bundle."); + NSError *error = RCTErrorWithMessage( + @"No bundle URL present.\n\nMake sure you're running a packager " + "server or have included a .jsbundle file in your application bundle."); onSourceLoad(error, nil); } else { __weak RCTCxxBridge *weakSelf = self; - [RCTJavaScriptLoader loadBundleAtURL:self.bundleURL onProgress:onProgress onComplete:^(NSError *error, RCTSource *source) { - if (error) { - [weakSelf handleError:error]; - return; - } - onSourceLoad(error, source); - }]; + [RCTJavaScriptLoader loadBundleAtURL:self.bundleURL + onProgress:onProgress + onComplete:^(NSError *error, RCTSource *source) { + if (error) { + [weakSelf handleError:error]; + return; + } + onSourceLoad(error, source); + }]; } } - (NSArray *)moduleClasses { if (RCT_DEBUG && _valid && _moduleClassesByID == nil) { - RCTLogError(@"Bridge modules have not yet been initialized. You may be " - "trying to access a module too early in the startup procedure."); + RCTLogError( + @"Bridge modules have not yet been initialized. You may be " + "trying to access a module too early in the startup procedure."); } return _moduleClassesByID; } @@ -460,7 +468,7 @@ struct RCTInstanceCallback : public InstanceCallback { - (id)moduleForName:(NSString *)moduleName lazilyLoadIfNecessary:(BOOL)lazilyLoad { if (RCTTurboModuleEnabled() && _turboModuleLookupDelegate) { - const char* moduleNameCStr = [moduleName UTF8String]; + const char *moduleNameCStr = [moduleName UTF8String]; if (lazilyLoad || [_turboModuleLookupDelegate moduleIsInitialized:moduleNameCStr]) { id module = [_turboModuleLookupDelegate moduleForName:moduleNameCStr warnOnLookupFailure:NO]; if (module != nil) { @@ -486,12 +494,12 @@ struct RCTInstanceCallback : public InstanceCallback { // Module may not be loaded yet, so attempt to force load it here. const BOOL result = [self.delegate respondsToSelector:@selector(bridge:didNotFindModule:)] && - [self.delegate bridge:self didNotFindModule:moduleName]; + [self.delegate bridge:self didNotFindModule:moduleName]; if (result) { // Try again. moduleData = _moduleDataByName[moduleName]; #if RCT_DEV - // If the `_moduleDataByName` is nil, it must have been cleared by the reload. + // If the `_moduleDataByName` is nil, it must have been cleared by the reload. } else if (_moduleDataByName != nil) { RCTLogError(@"Unable to find module for %@", moduleName); } @@ -506,7 +514,7 @@ struct RCTInstanceCallback : public InstanceCallback { - (BOOL)moduleIsInitialized:(Class)moduleClass { - NSString* moduleName = RCTBridgeModuleNameForClass(moduleClass); + NSString *moduleName = RCTBridgeModuleNameForClass(moduleClass); if (_moduleDataByName[moduleName].hasInstance) { return YES; } @@ -536,12 +544,11 @@ struct RCTInstanceCallback : public InstanceCallback { ModuleRegistry::ModuleNotFoundCallback moduleNotFoundCallback = ^bool(const std::string &name) { __strong __typeof(weakSelf) strongSelf = weakSelf; return [strongSelf.delegate respondsToSelector:@selector(bridge:didNotFindModule:)] && - [strongSelf.delegate bridge:strongSelf didNotFindModule:@(name.c_str())]; + [strongSelf.delegate bridge:strongSelf didNotFindModule:@(name.c_str())]; }; auto registry = std::make_shared( - createNativeModules(_moduleDataByID, self, _reactInstance), - moduleNotFoundCallback); + createNativeModules(_moduleDataByID, self, _reactInstance), moduleNotFoundCallback); [_performanceLogger markStopForTag:RCTPLNativeModulePrepareConfig]; RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @""); @@ -573,9 +580,7 @@ struct RCTInstanceCallback : public InstanceCallback { #if RCT_PROFILE if (RCTProfileIsProfiling()) { - _reactInstance->setGlobalVariable( - "__RCTProfileIsProfiling", - std::make_unique("true")); + _reactInstance->setGlobalVariable("__RCTProfileIsProfiling", std::make_unique("true")); } #endif } @@ -589,10 +594,10 @@ struct RCTInstanceCallback : public InstanceCallback { // This is async, but any calls into JS are blocked by the m_syncReady CV in Instance _reactInstance->initializeBridge( - std::make_unique(self), - executorFactory, - _jsMessageThread, - [self _buildModuleRegistryUnlocked]); + std::make_unique(self), + executorFactory, + _jsMessageThread, + [self _buildModuleRegistryUnlocked]); _moduleRegistryCreated = YES; } @@ -615,8 +620,8 @@ struct RCTInstanceCallback : public InstanceCallback { - (NSArray *)_registerModulesForClasses:(NSArray *)moduleClasses lazilyDiscovered:(BOOL)lazilyDiscovered { - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, - @"-[RCTCxxBridge initModulesWithDispatchGroup:] autoexported moduleData", nil); + RCT_PROFILE_BEGIN_EVENT( + RCTProfileTagAlways, @"-[RCTCxxBridge initModulesWithDispatchGroup:] autoexported moduleData", nil); NSArray *moduleClassesCopy = [moduleClasses copy]; NSMutableArray *moduleDataByID = [NSMutableArray arrayWithCapacity:moduleClassesCopy.count]; @@ -637,9 +642,12 @@ struct RCTInstanceCallback : public InstanceCallback { continue; } else if ([moduleData.moduleClass new] != nil) { // Both modules were non-nil, so it's unclear which should take precedence - RCTLogWarn(@"Attempted to register RCTBridgeModule class %@ for the " - "name '%@', but name was already registered by class %@", - moduleClass, moduleName, moduleData.moduleClass); + RCTLogWarn( + @"Attempted to register RCTBridgeModule class %@ for the " + "name '%@', but name was already registered by class %@", + moduleClass, + moduleName, + moduleData.moduleClass); } } @@ -660,8 +668,7 @@ struct RCTInstanceCallback : public InstanceCallback { - (void)registerExtraModules { - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, - @"-[RCTCxxBridge initModulesWithDispatchGroup:] extraModules", nil); + RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[RCTCxxBridge initModulesWithDispatchGroup:] extraModules", nil); NSArray> *extraModules = nil; if ([self.delegate respondsToSelector:@selector(extraModulesForBridge:)]) { @@ -679,8 +686,8 @@ struct RCTInstanceCallback : public InstanceCallback { }); #endif - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, - @"-[RCTCxxBridge initModulesWithDispatchGroup:] preinitialized moduleData", nil); + RCT_PROFILE_BEGIN_EVENT( + RCTProfileTagAlways, @"-[RCTCxxBridge initModulesWithDispatchGroup:] preinitialized moduleData", nil); // Set up moduleData for pre-initialized module instances for (id module in extraModules) { Class moduleClass = [module class]; @@ -690,9 +697,12 @@ struct RCTInstanceCallback : public InstanceCallback { // Check for name collisions between preregistered modules RCTModuleData *moduleData = _moduleDataByName[moduleName]; if (moduleData) { - RCTLogError(@"Attempted to register RCTBridgeModule class %@ for the " - "name '%@', but name was already registered by class %@", - moduleClass, moduleName, moduleData.moduleClass); + RCTLogError( + @"Attempted to register RCTBridgeModule class %@ for the " + "name '%@', but name was already registered by class %@", + moduleClass, + moduleName, + moduleData.moduleClass); continue; } } @@ -700,9 +710,11 @@ struct RCTInstanceCallback : public InstanceCallback { if (RCTTurboModuleEnabled() && [module conformsToProtocol:@protocol(RCTTurboModule)]) { #if RCT_DEBUG // TODO: don't ask for extra module for when TurboModule is enabled. - RCTLogError(@"NativeModule '%@' was marked as TurboModule, but provided as an extra NativeModule " - "by the class '%@', ignoring.", - moduleName, moduleClass); + RCTLogError( + @"NativeModule '%@' was marked as TurboModule, but provided as an extra NativeModule " + "by the class '%@', ignoring.", + moduleName, + moduleClass); #endif continue; } @@ -770,7 +782,8 @@ struct RCTInstanceCallback : public InstanceCallback { lazilyDiscovered:(BOOL)lazilyDiscovered { // Set up moduleData for automatically-exported modules - NSArray *moduleDataById = [self _registerModulesForClasses:modules lazilyDiscovered:lazilyDiscovered]; + NSArray *moduleDataById = [self _registerModulesForClasses:modules + lazilyDiscovered:lazilyDiscovered]; if (lazilyDiscovered) { #if RCT_DEBUG @@ -778,13 +791,15 @@ struct RCTInstanceCallback : public InstanceCallback { // as they are not allowed to have pre-instantiated instance // and must not require the main queue. for (RCTModuleData *moduleData in moduleDataById) { - RCTAssert(!(moduleData.requiresMainQueueSetup || moduleData.hasInstance), - @"Module \'%@\' requires initialization on the Main Queue or has pre-instantiated, which is not supported for the lazily discovered modules.", moduleData.name); + RCTAssert( + !(moduleData.requiresMainQueueSetup || moduleData.hasInstance), + @"Module \'%@\' requires initialization on the Main Queue or has pre-instantiated, which is not supported for the lazily discovered modules.", + moduleData.name); } #endif } else { - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, - @"-[RCTCxxBridge initModulesWithDispatchGroup:] moduleData.hasInstance", nil); + RCT_PROFILE_BEGIN_EVENT( + RCTProfileTagAlways, @"-[RCTCxxBridge initModulesWithDispatchGroup:] moduleData.hasInstance", nil); // Dispatch module init onto main thread for those modules that require it // For non-lazily discovered modules we run through the entire set of modules // that we have, otherwise some modules coming from the delegate @@ -821,8 +836,11 @@ struct RCTInstanceCallback : public InstanceCallback { { std::lock_guard guard(_moduleRegistryLock); if (_moduleRegistryCreated) { - NSArray *newModules = [self _initializeModules:modules withDispatchGroup:NULL lazilyDiscovered:YES]; - assert(_reactInstance); // at this point you must have reactInstance as you already called reactInstance->initialzeBridge + NSArray *newModules = [self _initializeModules:modules + withDispatchGroup:NULL + lazilyDiscovered:YES]; + assert(_reactInstance); // at this point you must have reactInstance as you already called + // reactInstance->initialzeBridge _reactInstance->getModuleRegistry().registerModules(createNativeModules(newModules, self, _reactInstance)); } else { [self registerModulesForClasses:modules]; @@ -876,8 +894,7 @@ struct RCTInstanceCallback : public InstanceCallback { RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @""); } -- (void)registerModuleForFrameUpdates:(id)module - withModuleData:(RCTModuleData *)moduleData +- (void)registerModuleForFrameUpdates:(id)module withModuleData:(RCTModuleData *)moduleData { [_displayLink registerModuleForFrameUpdates:module withModuleData:moduleData]; } @@ -894,9 +911,9 @@ struct RCTInstanceCallback : public InstanceCallback { // Perform the state update and notification on the main thread, so we can't run into // timing issues with RCTRootView dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] - postNotificationName:RCTJavaScriptDidLoadNotification - object:self->_parentBridge userInfo:@{@"bridge": self}]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidLoadNotification + object:self->_parentBridge + userInfo:@{@"bridge" : self}]; // Starting the display link is not critical to startup, so do it last [self ensureOnJavaScriptThread:^{ @@ -935,8 +952,7 @@ struct RCTInstanceCallback : public InstanceCallback { if (self->_valid && !self->_loading) { if ([error userInfo][RCTJSRawStackTraceKey]) { - [self.redBox showErrorMessage:[error localizedDescription] - withRawStack:[error userInfo][RCTJSRawStackTraceKey]]; + [self.redBox showErrorMessage:[error localizedDescription] withRawStack:[error userInfo][RCTJSRawStackTraceKey]]; } RCTFatal(error); @@ -966,37 +982,42 @@ struct RCTInstanceCallback : public InstanceCallback { self->_reactInstance.reset(); self->_jsMessageThread.reset(); - [[NSNotificationCenter defaultCenter] - postNotificationName:RCTJavaScriptDidFailToLoadNotification - object:self->_parentBridge userInfo:@{@"bridge": self, @"error": error}]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidFailToLoadNotification + object:self->_parentBridge + userInfo:@{@"bridge" : self, @"error" : error}]; if ([error userInfo][RCTJSRawStackTraceKey]) { - [redBox showErrorMessage:[error localizedDescription] - withRawStack:[error userInfo][RCTJSRawStackTraceKey]]; + [redBox showErrorMessage:[error localizedDescription] withRawStack:[error userInfo][RCTJSRawStackTraceKey]]; } RCTFatal(error); }); } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithDelegate:(__unused id)delegate - bundleURL:(__unused NSURL *)bundleURL - moduleProvider:(__unused RCTBridgeModuleListProvider)block - launchOptions:(__unused NSDictionary *)launchOptions) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithDelegate + : (__unused id)delegate bundleURL + : (__unused NSURL *)bundleURL moduleProvider + : (__unused RCTBridgeModuleListProvider)block launchOptions + : (__unused NSDictionary *)launchOptions) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleURL - moduleProvider:(__unused RCTBridgeModuleListProvider)block - launchOptions:(__unused NSDictionary *)launchOptions) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithBundleURL + : (__unused NSURL *)bundleURL moduleProvider + : (__unused RCTBridgeModuleListProvider)block launchOptions + : (__unused NSDictionary *)launchOptions) /** * Prevent super from calling setUp (that'd create another batchedBridge) */ -- (void)setUp {} +- (void)setUp +{ +} - (void)reload { if (!_valid) { - RCTLogWarn(@"Attempting to reload bridge before it's valid: %@. Try restarting the development server if connected.", self); + RCTLogWarn( + @"Attempting to reload bridge before it's valid: %@. Try restarting the development server if connected.", + self); } RCTTriggerReloadCommandListeners(@"Unknown from cxx bridge"); } @@ -1004,7 +1025,9 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR - (void)reloadWithReason:(NSString *)reason { if (!_valid) { - RCTLogWarn(@"Attempting to reload bridge before it's valid: %@. Try restarting the development server if connected.", self); + RCTLogWarn( + @"Attempting to reload bridge before it's valid: %@. Try restarting the development server if connected.", + self); } RCTTriggerReloadCommandListeners(reason); } @@ -1036,8 +1059,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR return _parentBridge.delegate; } -- (void)dispatchBlock:(dispatch_block_t)block - queue:(dispatch_queue_t)queue +- (void)dispatchBlock:(dispatch_block_t)block queue:(dispatch_queue_t)queue { if (queue == RCTJSThread) { [self ensureOnJavaScriptThread:block]; @@ -1079,7 +1101,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR [[NSNotificationCenter defaultCenter] postNotificationName:RCTBridgeWillInvalidateModulesNotification object:self->_parentBridge - userInfo:@{@"bridge": self}]; + userInfo:@{@"bridge" : self}]; // We're on the JS thread (which we'll be suspending soon), so no new calls will be made to native modules after // this completes. We must ensure all previous calls were dispatched before deallocating the instance (and module @@ -1094,10 +1116,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR if ([moduleData.instance respondsToSelector:@selector(invalidate)]) { dispatch_group_enter(moduleInvalidation); - [self dispatchBlock:^{ - [(id)moduleData.instance invalidate]; - dispatch_group_leave(moduleInvalidation); - } queue:moduleData.methodQueue]; + [self + dispatchBlock:^{ + [(id)moduleData.instance invalidate]; + dispatch_group_leave(moduleInvalidation); + } + queue:moduleData.methodQueue]; } [moduleData invalidate]; } @@ -1108,7 +1132,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR [[NSNotificationCenter defaultCenter] postNotificationName:RCTBridgeDidInvalidateModulesNotification object:self->_parentBridge - userInfo:@{@"bridge": self}]; + userInfo:@{@"bridge" : self}]; self->_reactInstance.reset(); self->_jsMessageThread.reset(); @@ -1127,10 +1151,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR - (void)logMessage:(NSString *)message level:(NSString *)level { if (RCT_DEBUG && _valid) { - [self enqueueJSCall:@"RCTLog" - method:@"logIfNoNativeHook" - args:@[level, message] - completion:NULL]; + [self enqueueJSCall:@"RCTLog" method:@"logIfNoNativeHook" args:@[ level, message ] completion:NULL]; } } @@ -1188,7 +1209,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR - (void)_flushPendingCalls { - RCT_PROFILE_BEGIN_EVENT(0, @"Processing pendingCalls", @{ @"count": [@(_pendingCalls.count) stringValue] }); + RCT_PROFILE_BEGIN_EVENT(0, @"Processing pendingCalls", @{@"count" : [@(_pendingCalls.count) stringValue]}); // Phase B: _flushPendingCalls happens. Each block in _pendingCalls is // executed, adding work to the queue, and _pendingCount is decremented. // loading is set to NO. @@ -1205,7 +1226,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR /** * Public. Can be invoked from any thread. */ -- (void)enqueueJSCall:(NSString *)module method:(NSString *)method args:(NSArray *)args completion:(dispatch_block_t)completion +- (void)enqueueJSCall:(NSString *)module + method:(NSString *)method + args:(NSArray *)args + completion:(dispatch_block_t)completion { if (!self.valid) { return; @@ -1218,7 +1242,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR RCTProfileBeginFlowEvent(); __weak __typeof(self) weakSelf = self; - [self _runAfterLoad:^(){ + [self _runAfterLoad:^() { RCTProfileEndFlowEvent(); __strong __typeof(weakSelf) strongSelf = weakSelf; if (!strongSelf) { @@ -1226,8 +1250,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR } if (strongSelf->_reactInstance) { - strongSelf->_reactInstance->callJSFunction([module UTF8String], [method UTF8String], - convertIdToFollyDynamic(args ?: @[])); + strongSelf->_reactInstance->callJSFunction( + [module UTF8String], [method UTF8String], convertIdToFollyDynamic(args ?: @[])); // ensureOnJavaScriptThread may execute immediately, so use jsMessageThread, to make sure // the block is invoked after callJSFunction @@ -1259,7 +1283,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR RCTProfileBeginFlowEvent(); __weak __typeof(self) weakSelf = self; - [self _runAfterLoad:^(){ + [self _runAfterLoad:^() { RCTProfileEndFlowEvent(); __strong __typeof(weakSelf) strongSelf = weakSelf; if (!strongSelf) { @@ -1278,14 +1302,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR - (void)_immediatelyCallTimer:(NSNumber *)timer { if (_reactInstance) { - _reactInstance->callJSFunction("JSTimers", "callTimers", - folly::dynamic::array(folly::dynamic::array([timer doubleValue]))); + _reactInstance->callJSFunction( + "JSTimers", "callTimers", folly::dynamic::array(folly::dynamic::array([timer doubleValue]))); } } -- (void)enqueueApplicationScript:(NSData *)script - url:(NSURL *)url - onComplete:(dispatch_block_t)onComplete +- (void)enqueueApplicationScript:(NSData *)script url:(NSURL *)url onComplete:(dispatch_block_t)onComplete { RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[RCTCxxBridge enqueueApplicationScript]", nil); @@ -1305,15 +1327,13 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR [self executeApplicationScript:script url:url async:NO]; } -- (void)executeApplicationScript:(NSData *)script - url:(NSURL *)url - async:(BOOL)async +- (void)executeApplicationScript:(NSData *)script url:(NSURL *)url async:(BOOL)async { [self _tryAndHandleError:^{ NSString *sourceUrlStr = deriveSourceURL(url); - [[NSNotificationCenter defaultCenter] - postNotificationName:RCTJavaScriptWillStartExecutingNotification - object:self->_parentBridge userInfo:@{@"bridge": self}]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptWillStartExecutingNotification + object:self->_parentBridge + userInfo:@{@"bridge" : self}]; if (isRAMBundle(script)) { [self->_performanceLogger markStartForTag:RCTPLRAMBundleLoad]; auto ramBundle = std::make_unique(sourceUrlStr.UTF8String); @@ -1321,13 +1341,13 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR [self->_performanceLogger markStopForTag:RCTPLRAMBundleLoad]; [self->_performanceLogger setValue:scriptStr->size() forTag:RCTPLRAMStartupCodeSize]; if (self->_reactInstance) { - auto registry = RAMBundleRegistry::multipleBundlesRegistry(std::move(ramBundle), JSIndexedRAMBundle::buildFactory()); - self->_reactInstance->loadRAMBundle(std::move(registry), std::move(scriptStr), - sourceUrlStr.UTF8String, !async); + auto registry = + RAMBundleRegistry::multipleBundlesRegistry(std::move(ramBundle), JSIndexedRAMBundle::buildFactory()); + self->_reactInstance->loadRAMBundle(std::move(registry), std::move(scriptStr), sourceUrlStr.UTF8String, !async); } } else if (self->_reactInstance) { - self->_reactInstance->loadScriptFromString(std::make_unique(script), - sourceUrlStr.UTF8String, !async); + self->_reactInstance->loadScriptFromString( + std::make_unique(script), sourceUrlStr.UTF8String, !async); } else { std::string methodName = async ? "loadApplicationScript" : "loadApplicationScriptSync"; throw std::logic_error("Attempt to call " + methodName + ": on uninitialized bridge"); @@ -1348,9 +1368,11 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR { for (RCTModuleData *moduleData in _moduleDataByID) { if (moduleData.implementsPartialBatchDidFlush) { - [self dispatchBlock:^{ - [moduleData.instance partialBatchDidFlush]; - } queue:moduleData.methodQueue]; + [self + dispatchBlock:^{ + [moduleData.instance partialBatchDidFlush]; + } + queue:moduleData.methodQueue]; } } } @@ -1361,9 +1383,11 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR // can we eliminate this special case? for (RCTModuleData *moduleData in _moduleDataByID) { if (moduleData.implementsBatchDidComplete) { - [self dispatchBlock:^{ - [moduleData.instance batchDidComplete]; - } queue:moduleData.methodQueue]; + [self + dispatchBlock:^{ + [moduleData.instance batchDidComplete]; + } + queue:moduleData.methodQueue]; } } } @@ -1373,12 +1397,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR RCTAssertMainQueue(); [self ensureOnJavaScriptThread:^{ - #if WITH_FBSYSTRACE +#if WITH_FBSYSTRACE [RCTFBSystrace registerCallbacks]; - #endif +#endif RCTProfileInit(self); - [self enqueueJSCall:@"Systrace" method:@"setEnabled" args:@[@YES] completion:NULL]; + [self enqueueJSCall:@"Systrace" method:@"setEnabled" args:@[ @YES ] completion:NULL]; }]; } @@ -1387,17 +1411,18 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR RCTAssertMainQueue(); [self ensureOnJavaScriptThread:^{ - [self enqueueJSCall:@"Systrace" method:@"setEnabled" args:@[@NO] completion:NULL]; + [self enqueueJSCall:@"Systrace" method:@"setEnabled" args:@[ @NO ] completion:NULL]; RCTProfileEnd(self, ^(NSString *log) { NSData *logData = [log dataUsingEncoding:NSUTF8StringEncoding]; callback(logData); - #if WITH_FBSYSTRACE +#if WITH_FBSYSTRACE if (![RCTFBSystrace verifyTraceSize:logData.length]) { - RCTLogWarn(@"Your FBSystrace trace might be truncated, try to bump up the buffer size" - " in RCTFBSystrace.m or capture a shorter trace"); + RCTLogWarn( + @"Your FBSystrace trace might be truncated, try to bump up the buffer size" + " in RCTFBSystrace.m or capture a shorter trace"); } [RCTFBSystrace unregisterCallbacks]; - #endif +#endif }); }]; } @@ -1416,7 +1441,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithBundleURL:(__unused NSURL *)bundleUR return _reactInstance->getJavaScriptContext(); } -- (void)invokeAsync:(std::function&&)func +- (void)invokeAsync:(std::function &&)func { __block auto retainedFunc = std::move(func); __weak __typeof(self) weakSelf = self; diff --git a/React/CxxBridge/RCTMessageThread.h b/React/CxxBridge/RCTMessageThread.h index 150a877a4ae..ecdee6d6cc7 100644 --- a/React/CxxBridge/RCTMessageThread.h +++ b/React/CxxBridge/RCTMessageThread.h @@ -19,13 +19,13 @@ class RCTMessageThread : public MessageQueueThread { public: RCTMessageThread(NSRunLoop *runLoop, RCTJavaScriptCompleteBlock errorBlock); ~RCTMessageThread() override; - void runOnQueue(std::function&&) override; - void runOnQueueSync(std::function&&) override; + void runOnQueue(std::function &&) override; + void runOnQueueSync(std::function &&) override; void quitSynchronous() override; void setRunLoop(NSRunLoop *runLoop); private: - void tryFunc(const std::function& func); + void tryFunc(const std::function &func); void runAsync(std::function func); void runSync(std::function func); @@ -34,5 +34,5 @@ class RCTMessageThread : public MessageQueueThread { std::atomic_bool m_shutdown; }; -} -} +} // namespace react +} // namespace facebook diff --git a/React/CxxBridge/RCTMessageThread.mm b/React/CxxBridge/RCTMessageThread.mm index a510b9942e0..f29e47dd032 100644 --- a/React/CxxBridge/RCTMessageThread.mm +++ b/React/CxxBridge/RCTMessageThread.mm @@ -24,20 +24,22 @@ namespace facebook { namespace react { RCTMessageThread::RCTMessageThread(NSRunLoop *runLoop, RCTJavaScriptCompleteBlock errorBlock) - : m_cfRunLoop([runLoop getCFRunLoop]) - , m_errorBlock(errorBlock) - , m_shutdown(false) { + : m_cfRunLoop([runLoop getCFRunLoop]), m_errorBlock(errorBlock), m_shutdown(false) +{ CFRetain(m_cfRunLoop); } -RCTMessageThread::~RCTMessageThread() { +RCTMessageThread::~RCTMessageThread() +{ CFRelease(m_cfRunLoop); } // This is analogous to dispatch_async -void RCTMessageThread::runAsync(std::function func) { +void RCTMessageThread::runAsync(std::function func) +{ CFRunLoopPerformBlock(m_cfRunLoop, kCFRunLoopCommonModes, ^{ - // Create an autorelease pool each run loop to prevent memory footprint from growing too large, which can lead to performance problems. + // Create an autorelease pool each run loop to prevent memory footprint from growing too large, which can lead to + // performance problems. @autoreleasepool { func(); } @@ -46,57 +48,63 @@ void RCTMessageThread::runAsync(std::function func) { } // This is analogous to dispatch_sync -void RCTMessageThread::runSync(std::function func) { +void RCTMessageThread::runSync(std::function func) +{ if (m_cfRunLoop == CFRunLoopGetCurrent()) { func(); return; } dispatch_semaphore_t sema = dispatch_semaphore_create(0); - runAsync([func=std::make_shared>(std::move(func)), &sema] { + runAsync([func = std::make_shared>(std::move(func)), &sema] { (*func)(); dispatch_semaphore_signal(sema); }); dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); } -void RCTMessageThread::tryFunc(const std::function& func) { +void RCTMessageThread::tryFunc(const std::function &func) +{ NSError *error = tryAndReturnError(func); if (error) { m_errorBlock(error); } } -void RCTMessageThread::runOnQueue(std::function&& func) { +void RCTMessageThread::runOnQueue(std::function &&func) +{ if (m_shutdown) { return; } - runAsync([this, func=std::make_shared>(std::move(func))] { + runAsync([this, func = std::make_shared>(std::move(func))] { if (!m_shutdown) { tryFunc(*func); } }); } -void RCTMessageThread::runOnQueueSync(std::function&& func) { +void RCTMessageThread::runOnQueueSync(std::function &&func) +{ if (m_shutdown) { return; } - runSync([this, func=std::move(func)] { + runSync([this, func = std::move(func)] { if (!m_shutdown) { tryFunc(func); } }); } -void RCTMessageThread::quitSynchronous() { +void RCTMessageThread::quitSynchronous() +{ m_shutdown = true; - runSync([]{}); + runSync([] {}); CFRunLoopStop(m_cfRunLoop); } -void RCTMessageThread::setRunLoop(NSRunLoop *runLoop) { +void RCTMessageThread::setRunLoop(NSRunLoop *runLoop) +{ CFRelease(m_cfRunLoop); m_cfRunLoop = [runLoop getCFRunLoop]; CFRetain(m_cfRunLoop); diff --git a/React/CxxBridge/RCTObjcExecutor.h b/React/CxxBridge/RCTObjcExecutor.h index 79278ec8d73..49f21de2c0c 100644 --- a/React/CxxBridge/RCTObjcExecutor.h +++ b/React/CxxBridge/RCTObjcExecutor.h @@ -16,16 +16,18 @@ namespace facebook { namespace react { class RCTObjcExecutorFactory : public JSExecutorFactory { -public: - RCTObjcExecutorFactory(id jse, RCTJavaScriptCompleteBlock errorBlock); + public: + RCTObjcExecutorFactory( + id jse, + RCTJavaScriptCompleteBlock errorBlock); std::unique_ptr createJSExecutor( - std::shared_ptr delegate, - std::shared_ptr jsQueue) override; + std::shared_ptr delegate, + std::shared_ptr jsQueue) override; -private: + private: id m_jse; RCTJavaScriptCompleteBlock m_errorBlock; }; -} -} +} // namespace react +} // namespace facebook diff --git a/React/CxxBridge/RCTObjcExecutor.mm b/React/CxxBridge/RCTObjcExecutor.mm index ead98eb7fd0..47d5787aa18 100644 --- a/React/CxxBridge/RCTObjcExecutor.mm +++ b/React/CxxBridge/RCTObjcExecutor.mm @@ -26,21 +26,18 @@ namespace react { namespace { class JSEException : public std::runtime_error { -public: - JSEException(NSError *error) - : runtime_error([[error description] UTF8String]) {} + public: + JSEException(NSError *error) : runtime_error([[error description] UTF8String]) {} }; class RCTObjcExecutor : public JSExecutor { -public: - RCTObjcExecutor(id jse, - RCTJavaScriptCompleteBlock errorBlock, - std::shared_ptr jsThread, - std::shared_ptr delegate) - : m_jse(jse) - , m_errorBlock(errorBlock) - , m_delegate(std::move(delegate)) - , m_jsThread(std::move(jsThread)) + public: + RCTObjcExecutor( + id jse, + RCTJavaScriptCompleteBlock errorBlock, + std::shared_ptr jsThread, + std::shared_ptr delegate) + : m_jse(jse), m_errorBlock(errorBlock), m_delegate(std::move(delegate)), m_jsThread(std::move(jsThread)) { m_jsCallback = ^(id json, NSError *error) { if (error) { @@ -51,9 +48,8 @@ public: return; } - m_jsThread->runOnQueue([this, json]{ - m_delegate->callNativeModules(*this, convertIdToFollyDynamic(json), true); - }); + m_jsThread->runOnQueue( + [this, json] { m_delegate->callNativeModules(*this, convertIdToFollyDynamic(json), true); }); }; // Synchronously initialize the executor @@ -66,68 +62,62 @@ public: nativeModuleConfig.push_back(config ? config->config : nullptr); } - folly::dynamic config = - folly::dynamic::object("remoteModuleConfig", std::move(nativeModuleConfig)); + folly::dynamic config = folly::dynamic::object("remoteModuleConfig", std::move(nativeModuleConfig)); - setGlobalVariable( - "__fbBatchedBridgeConfig", - std::make_unique(folly::toJson(config))); + setGlobalVariable("__fbBatchedBridgeConfig", std::make_unique(folly::toJson(config))); } - void loadApplicationScript( - std::unique_ptr script, - std::string sourceURL) override { + void loadApplicationScript(std::unique_ptr script, std::string sourceURL) override + { RCTProfileBeginFlowEvent(); [m_jse executeApplicationScript:[NSData dataWithBytes:script->c_str() length:script->size()] - sourceURL:[[NSURL alloc] - initWithString:@(sourceURL.c_str())] - onComplete:^(NSError *error) { - RCTProfileEndFlowEvent(); + sourceURL:[[NSURL alloc] initWithString:@(sourceURL.c_str())] + onComplete:^(NSError *error) { + RCTProfileEndFlowEvent(); - if (error) { - m_errorBlock(error); - return; - } + if (error) { + m_errorBlock(error); + return; + } - [m_jse flushedQueue:m_jsCallback]; - }]; + [m_jse flushedQueue:m_jsCallback]; + }]; } - void setBundleRegistry(std::unique_ptr) override { + void setBundleRegistry(std::unique_ptr) override + { RCTAssert(NO, @"RAM bundles are not supported in RCTObjcExecutor"); } - void registerBundle(uint32_t __unused bundleId, const std::string __unused &bundlePath) override { + void registerBundle(uint32_t __unused bundleId, const std::string __unused &bundlePath) override + { RCTAssert(NO, @"RAM bundles are not supported in RCTObjcExecutor"); } - void callFunction(const std::string &module, const std::string &method, - const folly::dynamic &arguments) override { + void callFunction(const std::string &module, const std::string &method, const folly::dynamic &arguments) override + { [m_jse callFunctionOnModule:@(module.c_str()) - method:@(method.c_str()) - arguments:convertFollyDynamicToId(arguments) - callback:m_jsCallback]; + method:@(method.c_str()) + arguments:convertFollyDynamicToId(arguments) + callback:m_jsCallback]; } - void invokeCallback(double callbackId, const folly::dynamic &arguments) override { - [m_jse invokeCallbackID:@(callbackId) - arguments:convertFollyDynamicToId(arguments) - callback:m_jsCallback]; + void invokeCallback(double callbackId, const folly::dynamic &arguments) override + { + [m_jse invokeCallbackID:@(callbackId) arguments:convertFollyDynamicToId(arguments) callback:m_jsCallback]; } - virtual void setGlobalVariable( - std::string propName, - std::unique_ptr jsonValue) override { - [m_jse injectJSONText:@(jsonValue->c_str()) - asGlobalObjectNamed:@(propName.c_str()) - callback:m_errorBlock]; + virtual void setGlobalVariable(std::string propName, std::unique_ptr jsonValue) override + { + [m_jse injectJSONText:@(jsonValue->c_str()) asGlobalObjectNamed:@(propName.c_str()) callback:m_errorBlock]; } - virtual std::string getDescription() override { + virtual std::string getDescription() override + { return [NSStringFromClass([m_jse class]) UTF8String]; } -private: + private: id m_jse; RCTJavaScriptCompleteBlock m_errorBlock; std::shared_ptr m_delegate; @@ -137,16 +127,16 @@ private: } -RCTObjcExecutorFactory::RCTObjcExecutorFactory( - id jse, RCTJavaScriptCompleteBlock errorBlock) - : m_jse(jse) - , m_errorBlock(errorBlock) {} +RCTObjcExecutorFactory::RCTObjcExecutorFactory(id jse, RCTJavaScriptCompleteBlock errorBlock) + : m_jse(jse), m_errorBlock(errorBlock) +{ +} std::unique_ptr RCTObjcExecutorFactory::createJSExecutor( std::shared_ptr delegate, - std::shared_ptr jsQueue) { - return std::unique_ptr( - new RCTObjcExecutor(m_jse, m_errorBlock, jsQueue, delegate)); + std::shared_ptr jsQueue) +{ + return std::unique_ptr(new RCTObjcExecutor(m_jse, m_errorBlock, jsQueue, delegate)); } } diff --git a/React/CxxModule/DispatchMessageQueueThread.h b/React/CxxModule/DispatchMessageQueueThread.h index 0064a0e8459..b6ca75a3de7 100644 --- a/React/CxxModule/DispatchMessageQueueThread.h +++ b/React/CxxModule/DispatchMessageQueueThread.h @@ -18,27 +18,30 @@ namespace react { // adapter does the work. class DispatchMessageQueueThread : public MessageQueueThread { -public: - DispatchMessageQueueThread(RCTModuleData *moduleData) - : moduleData_(moduleData) {} + public: + DispatchMessageQueueThread(RCTModuleData *moduleData) : moduleData_(moduleData) {} - void runOnQueue(std::function&& func) override { + void runOnQueue(std::function &&func) override + { dispatch_queue_t queue = moduleData_.methodQueue; - dispatch_block_t block = [func=std::move(func)] { func(); }; + dispatch_block_t block = [func = std::move(func)] { func(); }; RCTAssert(block != nullptr, @"Invalid block generated in call to %@", moduleData_); if (queue && block) { dispatch_async(queue, block); } } - void runOnQueueSync(std::function&& __unused func) override { + void runOnQueueSync(std::function &&__unused func) override + { LOG(FATAL) << "Unsupported operation"; } - void quitSynchronous() override { + void quitSynchronous() override + { LOG(FATAL) << "Unsupported operation"; } -private: + private: RCTModuleData *moduleData_; }; -} } +} +} diff --git a/React/CxxModule/RCTCxxMethod.mm b/React/CxxModule/RCTCxxMethod.mm index 40d6be72c4a..7ae1419a5a5 100644 --- a/React/CxxModule/RCTCxxMethod.mm +++ b/React/CxxModule/RCTCxxMethod.mm @@ -20,8 +20,7 @@ using facebook::xplat::module::CxxModule; using namespace facebook::react; -@implementation RCTCxxMethod -{ +@implementation RCTCxxMethod { std::unique_ptr _method; } @@ -50,9 +49,7 @@ using namespace facebook::react; } } -- (id)invokeWithBridge:(RCTBridge *)bridge - module:(id)module - arguments:(NSArray *)arguments +- (id)invokeWithBridge:(RCTBridge *)bridge module:(id)module arguments:(NSArray *)arguments { // module is unused except for printing errors. The C++ object it represents // is also baked into _method. @@ -65,26 +62,35 @@ using namespace facebook::react; CxxModule::Callback second; if (arguments.count < _method->callbacks) { - RCTLogError(@"Method %@.%s expects at least %zu arguments, but got %tu", - RCTBridgeModuleNameForClass([module class]), _method->name.c_str(), - _method->callbacks, arguments.count); + RCTLogError( + @"Method %@.%s expects at least %zu arguments, but got %tu", + RCTBridgeModuleNameForClass([module class]), + _method->name.c_str(), + _method->callbacks, + arguments.count); return nil; } if (_method->callbacks >= 1) { if (![arguments[arguments.count - 1] isKindOfClass:[NSNumber class]]) { - RCTLogError(@"Argument %tu (%@) of %@.%s should be a function", - arguments.count - 1, arguments[arguments.count - 1], - RCTBridgeModuleNameForClass([module class]), _method->name.c_str()); + RCTLogError( + @"Argument %tu (%@) of %@.%s should be a function", + arguments.count - 1, + arguments[arguments.count - 1], + RCTBridgeModuleNameForClass([module class]), + _method->name.c_str()); return nil; } NSNumber *id1; if (_method->callbacks == 2) { if (![arguments[arguments.count - 2] isKindOfClass:[NSNumber class]]) { - RCTLogError(@"Argument %tu (%@) of %@.%s should be a function", - arguments.count - 2, arguments[arguments.count - 2], - RCTBridgeModuleNameForClass([module class]), _method->name.c_str()); + RCTLogError( + @"Argument %tu (%@) of %@.%s should be a function", + arguments.count - 2, + arguments[arguments.count - 2], + RCTBridgeModuleNameForClass([module class]), + _method->name.c_str()); return nil; } @@ -116,9 +122,11 @@ using namespace facebook::react; return convertFollyDynamicToId(result); } } catch (const facebook::xplat::JsArgumentException &ex) { - RCTLogError(@"Method %@.%s argument error: %s", - RCTBridgeModuleNameForClass([module class]), _method->name.c_str(), - ex.what()); + RCTLogError( + @"Method %@.%s argument error: %s", + RCTBridgeModuleNameForClass([module class]), + _method->name.c_str(), + ex.what()); return nil; } } diff --git a/React/CxxModule/RCTCxxModule.mm b/React/CxxModule/RCTCxxModule.mm index 9e6d59b0e70..dd90009d417 100644 --- a/React/CxxModule/RCTCxxModule.mm +++ b/React/CxxModule/RCTCxxModule.mm @@ -16,8 +16,7 @@ using namespace facebook::react; -@implementation RCTCxxModule -{ +@implementation RCTCxxModule { std::unique_ptr _module; } @@ -37,9 +36,11 @@ using namespace facebook::react; _module = [self createModule]; if (_module) { - RCTAssert([RCTBridgeModuleNameForClass([self class]) isEqualToString:@(_module->getName().c_str())], - @"CxxModule class name %@ does not match runtime name %s", - RCTBridgeModuleNameForClass([self class]), _module->getName().c_str()); + RCTAssert( + [RCTBridgeModuleNameForClass([self class]) isEqualToString:@(_module->getName().c_str())], + @"CxxModule class name %@ does not match runtime name %s", + RCTBridgeModuleNameForClass([self class]), + _module->getName().c_str()); } } } diff --git a/React/CxxModule/RCTCxxUtils.h b/React/CxxModule/RCTCxxUtils.h index a9219dddc4b..caf584f35e4 100644 --- a/React/CxxModule/RCTCxxUtils.h +++ b/React/CxxModule/RCTCxxUtils.h @@ -19,9 +19,11 @@ namespace react { class Instance; class NativeModule; -std::vector> createNativeModules(NSArray *modules, RCTBridge *bridge, const std::shared_ptr &instance); +std::vector> +createNativeModules(NSArray *modules, RCTBridge *bridge, const std::shared_ptr &instance); -NSError *tryAndReturnError(const std::function& func); +NSError *tryAndReturnError(const std::function &func); NSString *deriveSourceURL(NSURL *url); -} } +} +} diff --git a/React/CxxModule/RCTCxxUtils.mm b/React/CxxModule/RCTCxxUtils.mm index 6f538dda5d2..a25328fac75 100644 --- a/React/CxxModule/RCTCxxUtils.mm +++ b/React/CxxModule/RCTCxxUtils.mm @@ -22,16 +22,17 @@ namespace react { using facebook::jsi::JSError; -std::vector> createNativeModules(NSArray *modules, RCTBridge *bridge, const std::shared_ptr &instance) +std::vector> +createNativeModules(NSArray *modules, RCTBridge *bridge, const std::shared_ptr &instance) { std::vector> nativeModules; for (RCTModuleData *moduleData in modules) { if ([moduleData.moduleClass isSubclassOfClass:[RCTCxxModule class]]) { nativeModules.emplace_back(std::make_unique( - instance, - [moduleData.name UTF8String], - [moduleData] { return [(RCTCxxModule *)(moduleData.instance) createModule]; }, - std::make_shared(moduleData))); + instance, + [moduleData.name UTF8String], + [moduleData] { return [(RCTCxxModule *)(moduleData.instance) createModule]; }, + std::make_shared(moduleData))); } else { nativeModules.emplace_back(std::make_unique(bridge, moduleData)); } @@ -44,7 +45,7 @@ static NSError *errorWithException(const std::exception &e) NSString *msg = @(e.what()); NSMutableDictionary *errorInfo = [NSMutableDictionary dictionary]; - const auto *jsError = dynamic_cast(&e); + const auto *jsError = dynamic_cast(&e); if (jsError) { errorInfo[RCTJSRawStackTraceKey] = @(jsError->getStack().c_str()); msg = [@"Unhandled JS Exception: " stringByAppendingString:msg]; @@ -53,9 +54,10 @@ static NSError *errorWithException(const std::exception &e) NSError *nestedError; try { std::rethrow_if_nested(e); - } catch(const std::exception &e) { + } catch (const std::exception &e) { nestedError = errorWithException(e); - } catch(...) {} + } catch (...) { + } if (nestedError) { msg = [NSString stringWithFormat:@"%@\n\n%@", msg, [nestedError localizedDescription]]; @@ -65,19 +67,16 @@ static NSError *errorWithException(const std::exception &e) return [NSError errorWithDomain:RCTErrorDomain code:1 userInfo:errorInfo]; } -NSError *tryAndReturnError(const std::function& func) +NSError *tryAndReturnError(const std::function &func) { try { @try { func(); return nil; - } - @catch (NSException *exception) { - NSString *message = - [NSString stringWithFormat:@"Exception '%@' was thrown from JS thread", exception]; + } @catch (NSException *exception) { + NSString *message = [NSString stringWithFormat:@"Exception '%@' was thrown from JS thread", exception]; return RCTErrorWithMessage(message); - } - @catch (id exception) { + } @catch (id exception) { // This will catch any other ObjC exception, but no C++ exceptions return RCTErrorWithMessage(@"non-std ObjC Exception"); } @@ -103,4 +102,5 @@ NSString *deriveSourceURL(NSURL *url) return sourceUrl ?: @""; } -} } +} +} diff --git a/React/CxxModule/RCTNativeModule.h b/React/CxxModule/RCTNativeModule.h index d22e21efe77..c73cf5f4ab7 100644 --- a/React/CxxModule/RCTNativeModule.h +++ b/React/CxxModule/RCTNativeModule.h @@ -18,13 +18,16 @@ class RCTNativeModule : public NativeModule { std::string getName() override; std::vector getMethods() override; folly::dynamic getConstants() override; - void invoke(unsigned int methodId, folly::dynamic &¶ms, int callId) override; - MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic &¶ms) override; + void invoke(unsigned int methodId, folly::dynamic &¶ms, int callId) + override; + MethodCallResult callSerializableNativeHook( + unsigned int reactMethodId, + folly::dynamic &¶ms) override; private: __weak RCTBridge *m_bridge; RCTModuleData *m_moduleData; }; -} -} +} // namespace react +} // namespace facebook diff --git a/React/CxxModule/RCTNativeModule.mm b/React/CxxModule/RCTNativeModule.mm index 4fbbc7123c5..00737371518 100644 --- a/React/CxxModule/RCTNativeModule.mm +++ b/React/CxxModule/RCTNativeModule.mm @@ -23,53 +23,55 @@ namespace facebook { namespace react { -static MethodCallResult invokeInner(RCTBridge *bridge, RCTModuleData *moduleData, unsigned int methodId, const folly::dynamic ¶ms); +static MethodCallResult +invokeInner(RCTBridge *bridge, RCTModuleData *moduleData, unsigned int methodId, const folly::dynamic ¶ms); RCTNativeModule::RCTNativeModule(RCTBridge *bridge, RCTModuleData *moduleData) - : m_bridge(bridge) - , m_moduleData(moduleData) {} + : m_bridge(bridge), m_moduleData(moduleData) +{ +} -std::string RCTNativeModule::getName() { +std::string RCTNativeModule::getName() +{ return [m_moduleData.name UTF8String]; } -std::vector RCTNativeModule::getMethods() { +std::vector RCTNativeModule::getMethods() +{ std::vector descs; for (id method in m_moduleData.methods) { - descs.emplace_back( - method.JSMethodName, - RCTFunctionDescriptorFromType(method.functionType) - ); + descs.emplace_back(method.JSMethodName, RCTFunctionDescriptorFromType(method.functionType)); } return descs; } -folly::dynamic RCTNativeModule::getConstants() { - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, - @"[RCTNativeModule getConstants] moduleData.exportedConstants", nil); +folly::dynamic RCTNativeModule::getConstants() +{ + RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"[RCTNativeModule getConstants] moduleData.exportedConstants", nil); NSDictionary *constants = m_moduleData.exportedConstants; folly::dynamic ret = convertIdToFollyDynamic(constants); RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @""); return ret; } -void RCTNativeModule::invoke(unsigned int methodId, folly::dynamic &¶ms, int callId) { +void RCTNativeModule::invoke(unsigned int methodId, folly::dynamic &¶ms, int callId) +{ // capture by weak pointer so that we can safely use these variables in a callback __weak RCTBridge *weakBridge = m_bridge; __weak RCTModuleData *weakModuleData = m_moduleData; // The BatchedBridge version of this buckets all the callbacks by thread, and // queues one block on each. This is much simpler; we'll see how it goes and // iterate. - dispatch_block_t block = [weakBridge, weakModuleData, methodId, params=std::move(params), callId] { - #ifdef WITH_FBSYSTRACE + dispatch_block_t block = [weakBridge, weakModuleData, methodId, params = std::move(params), callId] { +#ifdef WITH_FBSYSTRACE if (callId != -1) { fbsystrace_end_async_flow(TRACE_TAG_REACT_APPS, "native", callId); } - #else +#else (void)(callId); - #endif +#endif invokeInner(weakBridge, weakModuleData, methodId, std::move(params)); }; @@ -80,44 +82,51 @@ void RCTNativeModule::invoke(unsigned int methodId, folly::dynamic &¶ms, int dispatch_async(queue, block); } - #ifdef RCT_DEV +#ifdef RCT_DEV if (!queue) { - RCTLog(@"Attempted to invoke `%u` (method ID) on `%@` (NativeModule name) without a method queue.", - methodId, m_moduleData.name); + RCTLog( + @"Attempted to invoke `%u` (method ID) on `%@` (NativeModule name) without a method queue.", + methodId, + m_moduleData.name); } - #endif +#endif } -MethodCallResult RCTNativeModule::callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic &¶ms) { +MethodCallResult RCTNativeModule::callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic &¶ms) +{ return invokeInner(m_bridge, m_moduleData, reactMethodId, params); } -static MethodCallResult invokeInner(RCTBridge *bridge, RCTModuleData *moduleData, unsigned int methodId, const folly::dynamic ¶ms) { +static MethodCallResult +invokeInner(RCTBridge *bridge, RCTModuleData *moduleData, unsigned int methodId, const folly::dynamic ¶ms) +{ if (!bridge || !bridge.valid || !moduleData) { return folly::none; } id method = moduleData.methods[methodId]; if (RCT_DEBUG && !method) { - RCTLogError(@"Unknown methodID: %ud for module: %@", - methodId, moduleData.name); + RCTLogError(@"Unknown methodID: %ud for module: %@", methodId, moduleData.name); } NSArray *objcParams = convertFollyDynamicToId(params); @try { id result = [method invokeWithBridge:bridge module:moduleData.instance arguments:objcParams]; return convertIdToFollyDynamic(result); - } - @catch (NSException *exception) { + } @catch (NSException *exception) { // Pass on JS exceptions if ([exception.name hasPrefix:RCTFatalExceptionName]) { @throw exception; } #if RCT_DEBUG - NSString *message = [NSString stringWithFormat: - @"Exception '%@' was thrown while invoking %s on target %@ with params %@\ncallstack: %@", - exception, method.JSMethodName, moduleData.name, objcParams, exception.callStackSymbols]; + NSString *message = [NSString + stringWithFormat:@"Exception '%@' was thrown while invoking %s on target %@ with params %@\ncallstack: %@", + exception, + method.JSMethodName, + moduleData.name, + objcParams, + exception.callStackSymbols]; RCTFatal(RCTErrorWithMessage(message)); #else RCTFatalException(exception); diff --git a/React/CxxUtils/RCTFollyConvert.h b/React/CxxUtils/RCTFollyConvert.h index 2be033c7058..cd87ddcb594 100644 --- a/React/CxxUtils/RCTFollyConvert.h +++ b/React/CxxUtils/RCTFollyConvert.h @@ -15,4 +15,5 @@ namespace react { folly::dynamic convertIdToFollyDynamic(id json); id convertFollyDynamicToId(const folly::dynamic &dyn); -} } +} // namespace react +} // namespace facebook diff --git a/React/CxxUtils/RCTFollyConvert.mm b/React/CxxUtils/RCTFollyConvert.mm index ca1264e32c9..59f10e321db 100644 --- a/React/CxxUtils/RCTFollyConvert.mm +++ b/React/CxxUtils/RCTFollyConvert.mm @@ -12,7 +12,8 @@ namespace facebook { namespace react { -id convertFollyDynamicToId(const folly::dynamic &dyn) { +id convertFollyDynamicToId(const folly::dynamic &dyn) +{ // I could imagine an implementation which avoids copies by wrapping the // dynamic in a derived class of NSDictionary. We can do that if profiling // implies it will help. @@ -27,8 +28,7 @@ id convertFollyDynamicToId(const folly::dynamic &dyn) { case folly::dynamic::DOUBLE: return @(dyn.getDouble()); case folly::dynamic::STRING: - return [[NSString alloc] initWithBytes:dyn.c_str() length:dyn.size() - encoding:NSUTF8StringEncoding]; + return [[NSString alloc] initWithBytes:dyn.c_str() length:dyn.size() encoding:NSUTF8StringEncoding]; case folly::dynamic::ARRAY: { NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:dyn.size()]; for (auto &elem : dyn) { @@ -55,14 +55,14 @@ folly::dynamic convertIdToFollyDynamic(id json) switch (objCType[0]) { // This is a c++ bool or C99 _Bool. On some platforms, BOOL is a bool. case _C_BOOL: - return (bool) [json boolValue]; + return (bool)[json boolValue]; case _C_CHR: // On some platforms, objc BOOL is a signed char, but it // might also be a small number. Use the same hack JSC uses // to distinguish them: // https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbobjc/xplat/third-party/jsc/safari-600-1-4-17/JavaScriptCore/API/JSValue.mm;b8ee03916489f8b12143cd5c0bca546da5014fc9$901 if ([json isKindOfClass:[@YES class]]) { - return (bool) [json boolValue]; + return (bool)[json boolValue]; } else { return [json longLongValue]; } @@ -81,13 +81,12 @@ folly::dynamic convertIdToFollyDynamic(id json) case _C_DBL: return [json doubleValue]; - // default: - // fall through + // default: + // fall through } } else if ([json isKindOfClass:[NSString class]]) { NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding]; - return std::string(reinterpret_cast(data.bytes), - data.length); + return std::string(reinterpret_cast(data.bytes), data.length); } else if ([json isKindOfClass:[NSArray class]]) { folly::dynamic array = folly::dynamic::array; for (id element in json) { @@ -98,9 +97,8 @@ folly::dynamic convertIdToFollyDynamic(id json) __block folly::dynamic object = folly::dynamic::object(); [json enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, __unused BOOL *stop) { - object.insert(convertIdToFollyDynamic(key), - convertIdToFollyDynamic(value)); - }]; + object.insert(convertIdToFollyDynamic(key), convertIdToFollyDynamic(value)); + }]; return object; } @@ -108,4 +106,5 @@ folly::dynamic convertIdToFollyDynamic(id json) return nil; } -} } +} +} diff --git a/React/DevSupport/RCTDevLoadingViewProtocol.h b/React/DevSupport/RCTDevLoadingViewProtocol.h index dbd86fbe4b0..001a18e13f9 100644 --- a/React/DevSupport/RCTDevLoadingViewProtocol.h +++ b/React/DevSupport/RCTDevLoadingViewProtocol.h @@ -9,7 +9,7 @@ @class RCTLoadingProgress; -@protocol RCTDevLoadingViewProtocol +@protocol RCTDevLoadingViewProtocol + (void)setEnabled:(BOOL)enabled; - (void)showMessage:(NSString *)message color:(UIColor *)color backgroundColor:(UIColor *)backgroundColor; - (void)showWithURL:(NSURL *)URL; diff --git a/React/DevSupport/RCTDevLoadingViewSetEnabled.m b/React/DevSupport/RCTDevLoadingViewSetEnabled.m index 90a5ff15f43..0c90e663852 100644 --- a/React/DevSupport/RCTDevLoadingViewSetEnabled.m +++ b/React/DevSupport/RCTDevLoadingViewSetEnabled.m @@ -13,10 +13,12 @@ static BOOL isDevLoadingViewEnabled = YES; static BOOL isDevLoadingViewEnabled = NO; #endif -void RCTDevLoadingViewSetEnabled(BOOL enabled) { +void RCTDevLoadingViewSetEnabled(BOOL enabled) +{ isDevLoadingViewEnabled = enabled; } -BOOL RCTDevLoadingViewGetEnabled() { +BOOL RCTDevLoadingViewGetEnabled() +{ return isDevLoadingViewEnabled; } diff --git a/React/DevSupport/RCTInspectorDevServerHelper.h b/React/DevSupport/RCTInspectorDevServerHelper.h index 0315d6c9808..9cf04a5bdf5 100644 --- a/React/DevSupport/RCTInspectorDevServerHelper.h +++ b/React/DevSupport/RCTInspectorDevServerHelper.h @@ -17,9 +17,7 @@ + (RCTInspectorPackagerConnection *)connectWithBundleURL:(NSURL *)bundleURL; + (void)disableDebugger; -+ (void)attachDebugger:(NSString *)owner - withBundleURL:(NSURL *)bundleURL - withView:(UIViewController *)view; ++ (void)attachDebugger:(NSString *)owner withBundleURL:(NSURL *)bundleURL withView:(UIViewController *)view; @end #endif diff --git a/React/DevSupport/RCTPackagerClient.m b/React/DevSupport/RCTPackagerClient.m index 2e138d798c1..1cd9a07a576 100644 --- a/React/DevSupport/RCTPackagerClient.m +++ b/React/DevSupport/RCTPackagerClient.m @@ -32,10 +32,10 @@ const int RCT_PACKAGER_CLIENT_PROTOCOL_VERSION = 2; - (void)respondWithResult:(id)result { NSDictionary *msg = @{ - @"version": @(RCT_PACKAGER_CLIENT_PROTOCOL_VERSION), - @"id": _msgId, - @"result": result, - }; + @"version" : @(RCT_PACKAGER_CLIENT_PROTOCOL_VERSION), + @"id" : _msgId, + @"result" : result, + }; NSError *jsError = nil; NSString *message = RCTJSONStringify(msg, &jsError); if (jsError) { @@ -48,10 +48,10 @@ const int RCT_PACKAGER_CLIENT_PROTOCOL_VERSION = 2; - (void)respondWithError:(id)error { NSDictionary *msg = @{ - @"version": @(RCT_PACKAGER_CLIENT_PROTOCOL_VERSION), - @"id": _msgId, - @"error": error, - }; + @"version" : @(RCT_PACKAGER_CLIENT_PROTOCOL_VERSION), + @"id" : _msgId, + @"error" : error, + }; NSError *jsError = nil; NSString *message = RCTJSONStringify(msg, &jsError); if (jsError) { diff --git a/React/DevSupport/RCTPackagerConnection.h b/React/DevSupport/RCTPackagerConnection.h index e774572ec44..7f1bbd1d0ea 100644 --- a/React/DevSupport/RCTPackagerConnection.h +++ b/React/DevSupport/RCTPackagerConnection.h @@ -51,8 +51,7 @@ typedef void (^RCTConnectedHandler)(void); * packager has been established. The handler will be dispatched immediately * if the connection is already established. */ -- (RCTHandlerToken)addConnectedHandler:(RCTConnectedHandler)handler - queue:(dispatch_queue_t)queue; +- (RCTHandlerToken)addConnectedHandler:(RCTConnectedHandler)handler queue:(dispatch_queue_t)queue; /** Removes a handler. Silently does nothing if the token is not valid. */ - (void)removeHandler:(RCTHandlerToken)token; diff --git a/React/DevSupport/RCTPackagerConnection.mm b/React/DevSupport/RCTPackagerConnection.mm index 7d0966dca63..0586680570d 100644 --- a/React/DevSupport/RCTPackagerConnection.mm +++ b/React/DevSupport/RCTPackagerConnection.mm @@ -7,8 +7,8 @@ #import -#import #import +#import #import #import @@ -69,13 +69,12 @@ struct Registration { RCTPackagerConnection *const __weak weakSelf = self; _bundleURLChangeObserver = - [[NSNotificationCenter defaultCenter] - addObserverForName:RCTBundleURLProviderUpdatedNotification - object:nil - queue:[NSOperationQueue mainQueue] - usingBlock:^(NSNotification *_Nonnull __unused note) { - [weakSelf bundleURLSettingsChanged]; - }]; + [[NSNotificationCenter defaultCenter] addObserverForName:RCTBundleURLProviderUpdatedNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification *_Nonnull __unused note) { + [weakSelf bundleURLSettingsChanged]; + }]; } return self; } @@ -87,7 +86,7 @@ static RCTReconnectingWebSocket *socketForLocation(NSString *const jsLocation) components.scheme = @"http"; components.port = @(kRCTBundleURLProviderDefaultPort); components.path = @"/message"; - components.queryItems = @[[NSURLQueryItem queryItemWithName:@"role" value:@"ios"]]; + components.queryItems = @[ [NSURLQueryItem queryItemWithName:@"role" value:@"ios"] ]; static dispatch_queue_t queue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -132,7 +131,9 @@ static RCTReconnectingWebSocket *socketForLocation(NSString *const jsLocation) [_socket start]; } -- (RCTHandlerToken)addNotificationHandler:(RCTNotificationHandler)handler queue:(dispatch_queue_t)queue forMethod:(NSString *)method +- (RCTHandlerToken)addNotificationHandler:(RCTNotificationHandler)handler + queue:(dispatch_queue_t)queue + forMethod:(NSString *)method { std::lock_guard l(_mutex); const auto token = _nextToken++; @@ -140,7 +141,9 @@ static RCTReconnectingWebSocket *socketForLocation(NSString *const jsLocation) return token; } -- (RCTHandlerToken)addRequestHandler:(RCTRequestHandler)handler queue:(dispatch_queue_t)queue forMethod:(NSString *)method +- (RCTHandlerToken)addRequestHandler:(RCTRequestHandler)handler + queue:(dispatch_queue_t)queue + forMethod:(NSString *)method { std::lock_guard l(_mutex); const auto token = _nextToken++; @@ -174,22 +177,29 @@ static RCTReconnectingWebSocket *socketForLocation(NSString *const jsLocation) template static void eraseRegistrationsWithToken(std::vector> ®istrations, RCTHandlerToken token) { - registrations.erase(std::remove_if(registrations.begin(), registrations.end(), - [&token](const auto ®) { return reg.token == token; }), - registrations.end()); + registrations.erase( + std::remove_if( + registrations.begin(), registrations.end(), [&token](const auto ®) { return reg.token == token; }), + registrations.end()); } - (void)addHandler:(id)handler forMethod:(NSString *)method { - dispatch_queue_t queue = [handler respondsToSelector:@selector(methodQueue)] - ? [handler methodQueue] : dispatch_get_main_queue(); + dispatch_queue_t queue = + [handler respondsToSelector:@selector(methodQueue)] ? [handler methodQueue] : dispatch_get_main_queue(); - [self addNotificationHandler:^(NSDictionary *notification) { - [handler handleNotification:notification]; - } queue:queue forMethod:method]; - [self addRequestHandler:^(NSDictionary *request, RCTPackagerClientResponder *responder) { - [handler handleRequest:request withResponder:responder]; - } queue:queue forMethod:method]; + [self + addNotificationHandler:^(NSDictionary *notification) { + [handler handleNotification:notification]; + } + queue:queue + forMethod:method]; + [self + addRequestHandler:^(NSDictionary *request, RCTPackagerClientResponder *responder) { + [handler handleRequest:request withResponder:responder]; + } + queue:queue + forMethod:method]; } static BOOL isSupportedVersion(NSNumber *version) @@ -212,7 +222,9 @@ static BOOL isSupportedVersion(NSNumber *version) for (const auto ®istration : registrations) { // Beware: don't capture the reference to handler in a dispatched block! RCTConnectedHandler handler = registration.handler; - dispatch_async(registration.queue, ^{ handler(); }); + dispatch_async(registration.queue, ^{ + handler(); + }); } } @@ -236,13 +248,12 @@ static BOOL isSupportedVersion(NSNumber *version) id messageId = msg[@"id"]; if (messageId) { // Request - const std::vector> registrations(registrationsWithMethod(_mutex, _requestRegistrations, method)); + const std::vector> registrations( + registrationsWithMethod(_mutex, _requestRegistrations, method)); if (registrations.empty()) { RCTLogError(@"No handler found for packager method %@", msg[@"method"]); - [[[RCTPackagerClientResponder alloc] initWithId:messageId - socket:webSocket] - respondWithError: - [NSString stringWithFormat:@"No handler found for packager method %@", msg[@"method"]]]; + [[[RCTPackagerClientResponder alloc] initWithId:messageId socket:webSocket] + respondWithError:[NSString stringWithFormat:@"No handler found for packager method %@", msg[@"method"]]]; } else { // If there are multiple matching request registrations, only one can win; // otherwise the packager would get multiple responses. Choose the last one. @@ -252,11 +263,14 @@ static BOOL isSupportedVersion(NSNumber *version) }); } } else { // Notification - const std::vector> registrations(registrationsWithMethod(_mutex, _notificationRegistrations, method)); + const std::vector> registrations( + registrationsWithMethod(_mutex, _notificationRegistrations, method)); for (const auto ®istration : registrations) { // Beware: don't capture the reference to handler in a dispatched block! RCTNotificationHandler handler = registration.handler; - dispatch_async(registration.queue, ^{ handler(params); }); + dispatch_async(registration.queue, ^{ + handler(params); + }); } } } @@ -268,7 +282,8 @@ static BOOL isSupportedVersion(NSNumber *version) } template -static std::vector> registrationsWithMethod(std::mutex &mutex, const std::vector> ®istrations, NSString *method) +static std::vector> +registrationsWithMethod(std::mutex &mutex, const std::vector> ®istrations, NSString *method) { std::lock_guard l(mutex); // Scope lock acquisition to prevent deadlock when calling out std::vector> matches; diff --git a/React/Inspector/RCTInspector.mm b/React/Inspector/RCTInspector.mm index 571f7f94256..1f10fd8db86 100644 --- a/React/Inspector/RCTInspector.mm +++ b/React/Inspector/RCTInspector.mm @@ -25,18 +25,20 @@ using namespace facebook::react; // please keep consistent :) class RemoteConnection : public IRemoteConnection { -public: -RemoteConnection(RCTInspectorRemoteConnection *connection) : - _connection(connection) {} + public: + RemoteConnection(RCTInspectorRemoteConnection *connection) : _connection(connection) {} - virtual void onMessage(std::string message) override { + virtual void onMessage(std::string message) override + { [_connection onMessage:@(message.c_str())]; } - virtual void onDisconnect() override { + virtual void onDisconnect() override + { [_connection onDisconnect]; } -private: + + private: const RCTInspectorRemoteConnection *_connection; }; @@ -45,9 +47,7 @@ private: NSString *_title; NSString *_vm; } -- (instancetype)initWithId:(NSInteger)id - title:(NSString *)title - vm:(NSString *)vm; +- (instancetype)initWithId:(NSInteger)id title:(NSString *)title vm:(NSString *)vm; @end @interface RCTInspectorLocalConnection () { @@ -63,7 +63,7 @@ static IInspector *getInstance() @implementation RCTInspector -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) + (NSArray *)pages { @@ -72,9 +72,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) for (size_t i = 0; i < pages.size(); i++) { RCTInspectorPage *pageWrapper = [[RCTInspectorPage alloc] initWithId:pages[i].id title:@(pages[i].title.c_str()) - vm:@(pages[i].vm.c_str())]; + vm:@(pages[i].vm.c_str())]; [array addObject:pageWrapper]; - } return array; } @@ -90,11 +89,9 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) @implementation RCTInspectorPage -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) -- (instancetype)initWithId:(NSInteger)id - title:(NSString *)title - vm:(NSString *)vm +- (instancetype)initWithId:(NSInteger)id title:(NSString *)title vm:(NSString *)vm { if (self = [super init]) { _id = id; @@ -108,7 +105,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) @implementation RCTInspectorLocalConnection -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (instancetype)initWithConnection:(std::unique_ptr)connection { diff --git a/React/Inspector/RCTInspectorPackagerConnection.h b/React/Inspector/RCTInspectorPackagerConnection.h index e30858b1c53..de086945e5a 100644 --- a/React/Inspector/RCTInspectorPackagerConnection.h +++ b/React/Inspector/RCTInspectorPackagerConnection.h @@ -15,7 +15,7 @@ @property (atomic, assign) NSTimeInterval bundleUpdateTimestamp; @end -typedef RCTBundleStatus *(^RCTBundleStatusProvider)(void); +typedef RCTBundleStatus * (^RCTBundleStatusProvider)(void); @interface RCTInspectorPackagerConnection : NSObject - (instancetype)initWithURL:(NSURL *)url; diff --git a/React/Inspector/RCTInspectorPackagerConnection.m b/React/Inspector/RCTInspectorPackagerConnection.m index 001e25a13e2..33febedb9f2 100644 --- a/React/Inspector/RCTInspectorPackagerConnection.m +++ b/React/Inspector/RCTInspectorPackagerConnection.m @@ -45,12 +45,12 @@ const int RECONNECT_DELAY_MS = 2000; static NSDictionary *makePageIdPayload(NSString *pageId) { - return @{ @"pageId": pageId }; + return @{@"pageId" : pageId}; } @implementation RCTInspectorPackagerConnection -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (instancetype)initWithURL:(NSURL *)url { @@ -93,7 +93,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (void)closeAllConnections { - for (NSString *pageId in _inspectorConnections){ + for (NSString *pageId in _inspectorConnections) { [[_inspectorConnections objectForKey:pageId] disconnect]; } [_inspectorConnections removeAllObjects]; @@ -111,8 +111,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) } RCTInspectorRemoteConnection *remoteConnection = - [[RCTInspectorRemoteConnection alloc] initWithPackagerConnection:self - pageId:pageId]; + [[RCTInspectorRemoteConnection alloc] initWithPackagerConnection:self pageId:pageId]; RCTInspectorLocalConnection *inspectorConnection = [RCTInspector connectPage:[pageId integerValue] forRemoteConnection:remoteConnection]; @@ -140,10 +139,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) NSString *wrappedEvent = payload[@"wrappedEvent"]; RCTInspectorLocalConnection *inspectorConnection = _inspectorConnections[pageId]; if (!inspectorConnection) { - RCTLogWarn( - @"Not connected to page: %@ , failed trying to handle event: %@", - pageId, - wrappedEvent); + RCTLogWarn(@"Not connected to page: %@ , failed trying to handle event: %@", pageId, wrappedEvent); return; } [inspectorConnection sendMessage:wrappedEvent]; @@ -155,34 +151,29 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) NSMutableArray *array = [NSMutableArray arrayWithCapacity:pages.count]; RCTBundleStatusProvider statusProvider = _bundleStatusProvider; - RCTBundleStatus *bundleStatus = statusProvider == nil - ? nil - : statusProvider(); + RCTBundleStatus *bundleStatus = statusProvider == nil ? nil : statusProvider(); for (RCTInspectorPage *page in pages) { NSDictionary *jsonPage = @{ - @"id": [@(page.id) stringValue], - @"title": page.title, - @"app": [[NSBundle mainBundle] bundleIdentifier], - @"vm": page.vm, - @"isLastBundleDownloadSuccess": bundleStatus == nil - ? [NSNull null] - : @(bundleStatus.isLastBundleDownloadSuccess), - @"bundleUpdateTimestamp": bundleStatus == nil - ? [NSNull null] - : @((long)bundleStatus.bundleUpdateTimestamp * 1000), + @"id" : [@(page.id) stringValue], + @"title" : page.title, + @"app" : [[NSBundle mainBundle] bundleIdentifier], + @"vm" : page.vm, + @"isLastBundleDownloadSuccess" : bundleStatus == nil ? [NSNull null] + : @(bundleStatus.isLastBundleDownloadSuccess), + @"bundleUpdateTimestamp" : bundleStatus == nil ? [NSNull null] + : @((long)bundleStatus.bundleUpdateTimestamp * 1000), }; [array addObject:jsonPage]; } return array; } -- (void)sendWrappedEvent:(NSString *)pageId - message:(NSString *)message +- (void)sendWrappedEvent:(NSString *)pageId message:(NSString *)message { NSDictionary *payload = @{ - @"pageId": pageId, - @"wrappedEvent": message, + @"pageId" : pageId, + @"wrappedEvent" : message, }; [self sendEvent:@"wrappedEvent" payload:payload]; } @@ -190,8 +181,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (void)sendEvent:(NSString *)name payload:(id)payload { NSDictionary *jsonMessage = @{ - @"event": name, - @"payload": payload, + @"event" : name, + @"payload" : payload, }; [self sendToPackager:jsonMessage]; } @@ -200,8 +191,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (void)webSocket:(__unused RCTSRWebSocket *)webSocket didFailWithError:(NSError *)error { if (_webSocket) { - [self abort:@"Websocket exception" - withCause:error]; + [self abort:@"Websocket exception" withCause:error]; } if (!_closed && [error code] != ECONNREFUSED) { [self reconnect]; @@ -221,8 +211,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) NSError *error = nil; id parsedJSON = RCTJSONParse(messageText, &error); if (error) { - RCTLogWarn(@"Unrecognized inspector message, string was not valid JSON: %@", - messageText); + RCTLogWarn(@"Unrecognized inspector message, string was not valid JSON: %@", messageText); return; } @@ -230,9 +219,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) } // analogous to InspectorPackagerConnection.Connection.onClosed(...) -- (void)webSocket:(__unused RCTSRWebSocket *)webSocket didCloseWithCode:(__unused NSInteger)code - reason:(__unused NSString *)reason - wasClean:(__unused BOOL)wasClean +- (void)webSocket:(__unused RCTSRWebSocket *)webSocket + didCloseWithCode:(__unused NSInteger)code + reason:(__unused NSString *)reason + wasClean:(__unused BOOL)wasClean { _webSocket = nil; [self closeAllConnections]; @@ -275,13 +265,11 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) } __weak RCTInspectorPackagerConnection *weakSelf = self; - dispatch_after( - dispatch_time(DISPATCH_TIME_NOW, RECONNECT_DELAY_MS *NSEC_PER_MSEC), - dispatch_get_main_queue(), ^{ - RCTInspectorPackagerConnection *strongSelf = weakSelf; - if (strongSelf && !strongSelf->_closed) { - [strongSelf connect]; - } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, RECONNECT_DELAY_MS * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ + RCTInspectorPackagerConnection *strongSelf = weakSelf; + if (strongSelf && !strongSelf->_closed) { + [strongSelf connect]; + } }); } @@ -308,8 +296,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) }); } -- (void)abort:(NSString *)message - withCause:(NSError *)cause +- (void)abort:(NSString *)message withCause:(NSError *)cause { // Don't log ECONNREFUSED at all; it's expected in cases where the server isn't listening. if (![cause.domain isEqual:NSPOSIXErrorDomain] || cause.code != ECONNREFUSED) { @@ -323,8 +310,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (void)disposeWebSocket { if (_webSocket) { - [_webSocket closeWithCode:1000 - reason:@"End of session"]; + [_webSocket closeWithCode:1000 reason:@"End of session"]; _webSocket.delegate = nil; _webSocket = nil; } @@ -334,7 +320,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) @implementation RCTInspectorRemoteConnection -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (instancetype)initWithPackagerConnection:(RCTInspectorPackagerConnection *)owningPackagerConnection pageId:(NSString *)pageId @@ -348,8 +334,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (void)onMessage:(NSString *)message { - [_owningPackagerConnection sendWrappedEvent:_pageId - message:message]; + [_owningPackagerConnection sendWrappedEvent:_pageId message:message]; } - (void)onDisconnect @@ -357,8 +342,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) RCTInspectorPackagerConnection *owningPackagerConnectionStrong = _owningPackagerConnection; if (owningPackagerConnectionStrong) { [owningPackagerConnectionStrong removeConnectionForPage:_pageId]; - [owningPackagerConnectionStrong sendEvent:@"disconnect" - payload:makePageIdPayload(_pageId)]; + [owningPackagerConnectionStrong sendEvent:@"disconnect" payload:makePageIdPayload(_pageId)]; } } diff --git a/React/Modules/RCTEventEmitter.m b/React/Modules/RCTEventEmitter.m index 421b55439f1..7717ddbdcac 100644 --- a/React/Modules/RCTEventEmitter.m +++ b/React/Modules/RCTEventEmitter.m @@ -7,11 +7,10 @@ #import "RCTEventEmitter.h" #import "RCTAssert.h" -#import "RCTUtils.h" #import "RCTLog.h" +#import "RCTUtils.h" -@implementation RCTEventEmitter -{ +@implementation RCTEventEmitter { NSInteger _listenerCount; } @@ -26,8 +25,10 @@ { [super initialize]; if (self != [RCTEventEmitter class]) { - RCTAssert(RCTClassOverridesInstanceMethod(self, @selector(supportedEvents)), - @"You must override the `supportedEvents` method of %@", self); + RCTAssert( + RCTClassOverridesInstanceMethod(self, @selector(supportedEvents)), + @"You must override the `supportedEvents` method of %@", + self); } } @@ -38,22 +39,30 @@ - (void)sendEventWithName:(NSString *)eventName body:(id)body { - RCTAssert(_bridge != nil || _invokeJS != nil, @"Error when sending event: %@ with body: %@. " - "Bridge is not set. This is probably because you've " - "explicitly synthesized the bridge in %@, even though it's inherited " - "from RCTEventEmitter.", eventName, body, [self class]); + RCTAssert( + _bridge != nil || _invokeJS != nil, + @"Error when sending event: %@ with body: %@. " + "Bridge is not set. This is probably because you've " + "explicitly synthesized the bridge in %@, even though it's inherited " + "from RCTEventEmitter.", + eventName, + body, + [self class]); if (RCT_DEBUG && ![[self supportedEvents] containsObject:eventName]) { - RCTLogError(@"`%@` is not a supported event type for %@. Supported events are: `%@`", - eventName, [self class], [[self supportedEvents] componentsJoinedByString:@"`, `"]); + RCTLogError( + @"`%@` is not a supported event type for %@. Supported events are: `%@`", + eventName, + [self class], + [[self supportedEvents] componentsJoinedByString:@"`, `"]); } if (_listenerCount > 0 && _bridge) { [_bridge enqueueJSCall:@"RCTDeviceEventEmitter" method:@"emit" - args:body ? @[eventName, body] : @[eventName] + args:body ? @[ eventName, body ] : @[ eventName ] completion:NULL]; } else if (_listenerCount > 0 && _invokeJS) { - _invokeJS(@"RCTDeviceEventEmitter", @"emit", body ? @[eventName, body] : @[eventName]); + _invokeJS(@"RCTDeviceEventEmitter", @"emit", body ? @[ eventName, body ] : @[ eventName ]); } else { RCTLogWarn(@"Sending `%@` with no listeners registered.", eventName); } @@ -76,11 +85,14 @@ } } -RCT_EXPORT_METHOD(addListener:(NSString *)eventName) +RCT_EXPORT_METHOD(addListener : (NSString *)eventName) { if (RCT_DEBUG && ![[self supportedEvents] containsObject:eventName]) { - RCTLogError(@"`%@` is not a supported event type for %@. Supported events are: `%@`", - eventName, [self class], [[self supportedEvents] componentsJoinedByString:@"`, `"]); + RCTLogError( + @"`%@` is not a supported event type for %@. Supported events are: `%@`", + eventName, + [self class], + [[self supportedEvents] componentsJoinedByString:@"`, `"]); } _listenerCount++; if (_listenerCount == 1) { @@ -88,7 +100,7 @@ RCT_EXPORT_METHOD(addListener:(NSString *)eventName) } } -RCT_EXPORT_METHOD(removeListeners:(double)count) +RCT_EXPORT_METHOD(removeListeners : (double)count) { int currentCount = (int)count; if (RCT_DEBUG && currentCount > _listenerCount) { diff --git a/React/Modules/RCTI18nUtil.m b/React/Modules/RCTI18nUtil.m index 11b7ead8599..eb26f7fe23e 100644 --- a/React/Modules/RCTI18nUtil.m +++ b/React/Modules/RCTI18nUtil.m @@ -17,9 +17,9 @@ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [self new]; - [sharedInstance swapLeftAndRightInRTL: true]; + [sharedInstance swapLeftAndRightInRTL:true]; }); - + return sharedInstance; } @@ -66,8 +66,7 @@ */ - (BOOL)isRTLForced { - BOOL rtlStatus = [[NSUserDefaults standardUserDefaults] - boolForKey:@"RCTI18nUtil_forceRTL"]; + BOOL rtlStatus = [[NSUserDefaults standardUserDefaults] boolForKey:@"RCTI18nUtil_forceRTL"]; return rtlStatus; } @@ -91,7 +90,8 @@ // Check if the current device language is RTL - (BOOL)isDevicePreferredLanguageRTL { - NSLocaleLanguageDirection direction = [NSLocale characterDirectionForLanguage:[[NSLocale preferredLanguages] objectAtIndex:0]]; + NSLocaleLanguageDirection direction = + [NSLocale characterDirectionForLanguage:[[NSLocale preferredLanguages] objectAtIndex:0]]; return direction == NSLocaleLanguageDirectionRightToLeft; } diff --git a/React/Modules/RCTLayoutAnimation.h b/React/Modules/RCTLayoutAnimation.h index c4df85a02ae..e907a997d7b 100644 --- a/React/Modules/RCTLayoutAnimation.h +++ b/React/Modules/RCTLayoutAnimation.h @@ -13,7 +13,7 @@ @property (nonatomic, readonly) NSTimeInterval duration; @property (nonatomic, readonly) NSTimeInterval delay; -@property (nonatomic, readonly, copy) NSString *property; +@property (nonatomic, readonly, copy) NSString *property ; @property (nonatomic, readonly) CGFloat springDamping; @property (nonatomic, readonly) CGFloat initialVelocity; @property (nonatomic, readonly) RCTAnimationType animationType; @@ -27,10 +27,8 @@ initialVelocity:(CGFloat)initialVelocity animationType:(RCTAnimationType)animationType; -- (instancetype)initWithDuration:(NSTimeInterval)duration - config:(NSDictionary *)config; +- (instancetype)initWithDuration:(NSTimeInterval)duration config:(NSDictionary *)config; -- (void)performAnimations:(void (^)(void))animations - withCompletionBlock:(void (^)(BOOL completed))completionBlock; +- (void)performAnimations:(void (^)(void))animations withCompletionBlock:(void (^)(BOOL completed))completionBlock; @end diff --git a/React/Modules/RCTLayoutAnimation.m b/React/Modules/RCTLayoutAnimation.m index b90eb4f61b9..7ad88992d9e 100644 --- a/React/Modules/RCTLayoutAnimation.m +++ b/React/Modules/RCTLayoutAnimation.m @@ -77,8 +77,7 @@ static UIViewAnimationOptions UIViewAnimationOptionsFromRCTAnimationType(RCTAnim return self; } -- (instancetype)initWithDuration:(NSTimeInterval)duration - config:(NSDictionary *)config +- (instancetype)initWithDuration:(NSTimeInterval)duration config:(NSDictionary *)config { if (!config) { return nil; @@ -109,8 +108,7 @@ static UIViewAnimationOptions UIViewAnimationOptionsFromRCTAnimationType(RCTAnim return self; } -- (void)performAnimations:(void (^)(void))animations - withCompletionBlock:(void (^)(BOOL completed))completionBlock +- (void)performAnimations:(void (^)(void))animations withCompletionBlock:(void (^)(BOOL completed))completionBlock { if (_animationType == RCTAnimationTypeSpring) { [UIView animateWithDuration:_duration @@ -122,8 +120,7 @@ static UIViewAnimationOptions UIViewAnimationOptionsFromRCTAnimationType(RCTAnim completion:completionBlock]; } else { UIViewAnimationOptions options = - UIViewAnimationOptionBeginFromCurrentState | - UIViewAnimationOptionsFromRCTAnimationType(_animationType); + UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionsFromRCTAnimationType(_animationType); [UIView animateWithDuration:_duration delay:_delay @@ -135,19 +132,25 @@ static UIViewAnimationOptions UIViewAnimationOptionsFromRCTAnimationType(RCTAnim - (BOOL)isEqual:(RCTLayoutAnimation *)animation { - return - _duration == animation.duration && - _delay == animation.delay && - (_property == animation.property || [_property isEqualToString:animation.property]) && - _springDamping == animation.springDamping && - _initialVelocity == animation.initialVelocity && - _animationType == animation.animationType; + return _duration == animation.duration && _delay == animation.delay && + (_property == animation.property || [_property isEqualToString:animation.property]) && + _springDamping == animation.springDamping && _initialVelocity == animation.initialVelocity && + _animationType == animation.animationType; } - (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p; duration: %f; delay: %f; property: %@; springDamping: %f; initialVelocity: %f; animationType: %li;>", - NSStringFromClass([self class]), self, _duration, _delay, _property, _springDamping, _initialVelocity, (long)_animationType]; + return [NSString + stringWithFormat: + @"<%@: %p; duration: %f; delay: %f; property: %@; springDamping: %f; initialVelocity: %f; animationType: %li;>", + NSStringFromClass([self class]), + self, + _duration, + _delay, + _property, + _springDamping, + _initialVelocity, + (long)_animationType]; } @end diff --git a/React/Modules/RCTLayoutAnimationGroup.h b/React/Modules/RCTLayoutAnimationGroup.h index a137d3c0da7..f13d046f61e 100644 --- a/React/Modules/RCTLayoutAnimationGroup.h +++ b/React/Modules/RCTLayoutAnimationGroup.h @@ -24,7 +24,6 @@ deletingLayoutAnimation:(RCTLayoutAnimation *)deletingLayoutAnimation callback:(RCTResponseSenderBlock)callback; -- (instancetype)initWithConfig:(NSDictionary *)config - callback:(RCTResponseSenderBlock)callback; +- (instancetype)initWithConfig:(NSDictionary *)config callback:(RCTResponseSenderBlock)callback; @end diff --git a/React/Modules/RCTLayoutAnimationGroup.m b/React/Modules/RCTLayoutAnimationGroup.m index 21453836b38..bffa0332859 100644 --- a/React/Modules/RCTLayoutAnimationGroup.m +++ b/React/Modules/RCTLayoutAnimationGroup.m @@ -7,8 +7,8 @@ #import "RCTLayoutAnimationGroup.h" -#import "RCTLayoutAnimation.h" #import "RCTConvert.h" +#import "RCTLayoutAnimation.h" @implementation RCTLayoutAnimationGroup @@ -27,8 +27,7 @@ return self; } -- (instancetype)initWithConfig:(NSDictionary *)config - callback:(RCTResponseSenderBlock)callback +- (instancetype)initWithConfig:(NSDictionary *)config callback:(RCTResponseSenderBlock)callback { if (!config) { return nil; @@ -57,16 +56,24 @@ RCTLayoutAnimation *updatingLayoutAnimation = layoutAnimation.updatingLayoutAnimation; RCTLayoutAnimation *deletingLayoutAnimation = layoutAnimation.deletingLayoutAnimation; - return - (_creatingLayoutAnimation == creatingLayoutAnimation || [_creatingLayoutAnimation isEqual:creatingLayoutAnimation]) && - (_updatingLayoutAnimation == updatingLayoutAnimation || [_updatingLayoutAnimation isEqual:updatingLayoutAnimation]) && - (_deletingLayoutAnimation == deletingLayoutAnimation || [_deletingLayoutAnimation isEqual:deletingLayoutAnimation]); + return (_creatingLayoutAnimation == creatingLayoutAnimation || + [_creatingLayoutAnimation isEqual:creatingLayoutAnimation]) && + (_updatingLayoutAnimation == updatingLayoutAnimation || + [_updatingLayoutAnimation isEqual:updatingLayoutAnimation]) && + (_deletingLayoutAnimation == deletingLayoutAnimation || + [_deletingLayoutAnimation isEqual:deletingLayoutAnimation]); } - (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p; creatingLayoutAnimation: %@; updatingLayoutAnimation: %@; deletingLayoutAnimation: %@>", - NSStringFromClass([self class]), self, [_creatingLayoutAnimation description], [_updatingLayoutAnimation description], [_deletingLayoutAnimation description]]; + return + [NSString stringWithFormat: + @"<%@: %p; creatingLayoutAnimation: %@; updatingLayoutAnimation: %@; deletingLayoutAnimation: %@>", + NSStringFromClass([self class]), + self, + [_creatingLayoutAnimation description], + [_updatingLayoutAnimation description], + [_deletingLayoutAnimation description]]; } @end diff --git a/React/Modules/RCTRedBoxExtraDataViewController.m b/React/Modules/RCTRedBoxExtraDataViewController.m index 05da05daa54..240aa5e9b03 100644 --- a/React/Modules/RCTRedBoxExtraDataViewController.m +++ b/React/Modules/RCTRedBoxExtraDataViewController.m @@ -16,58 +16,44 @@ @implementation RCTRedBoxExtraDataCell -- (instancetype)initWithStyle:(UITableViewCellStyle)style - reuseIdentifier:(NSString *)reuseIdentifier +- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { - self.backgroundColor = [UIColor colorWithRed:0.8 - green:0 blue:0 - alpha:1]; - UILayoutGuide *contentLayout = self.contentView.layoutMarginsGuide; + if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { + self.backgroundColor = [UIColor colorWithRed:0.8 green:0 blue:0 alpha:1]; + UILayoutGuide *contentLayout = self.contentView.layoutMarginsGuide; - self.keyLabel = [UILabel new]; - [self.contentView addSubview:self.keyLabel]; + self.keyLabel = [UILabel new]; + [self.contentView addSubview:self.keyLabel]; - self.keyLabel.translatesAutoresizingMaskIntoConstraints = NO; - [self.keyLabel.leadingAnchor - constraintEqualToAnchor:contentLayout.leadingAnchor].active = YES; - [self.keyLabel.topAnchor - constraintEqualToAnchor:contentLayout.topAnchor].active = YES; - [self.keyLabel.bottomAnchor - constraintEqualToAnchor:contentLayout.bottomAnchor].active = YES; - [self.keyLabel.widthAnchor - constraintEqualToAnchor:contentLayout.widthAnchor - multiplier:0.3].active = YES; + self.keyLabel.translatesAutoresizingMaskIntoConstraints = NO; + [self.keyLabel.leadingAnchor constraintEqualToAnchor:contentLayout.leadingAnchor].active = YES; + [self.keyLabel.topAnchor constraintEqualToAnchor:contentLayout.topAnchor].active = YES; + [self.keyLabel.bottomAnchor constraintEqualToAnchor:contentLayout.bottomAnchor].active = YES; + [self.keyLabel.widthAnchor constraintEqualToAnchor:contentLayout.widthAnchor multiplier:0.3].active = YES; - - self.keyLabel.textColor = [UIColor whiteColor]; - self.keyLabel.numberOfLines = 0; + self.keyLabel.textColor = [UIColor whiteColor]; + self.keyLabel.numberOfLines = 0; #if !TARGET_OS_TV - self.keyLabel.lineBreakMode = NSLineBreakByWordWrapping; - self.keyLabel.font = [UIFont fontWithName:@"Menlo-Regular" size:12.0f]; + self.keyLabel.lineBreakMode = NSLineBreakByWordWrapping; + self.keyLabel.font = [UIFont fontWithName:@"Menlo-Regular" size:12.0f]; #endif - self.valueLabel = [UILabel new]; - [self.contentView addSubview:self.valueLabel]; + self.valueLabel = [UILabel new]; + [self.contentView addSubview:self.valueLabel]; - self.valueLabel.translatesAutoresizingMaskIntoConstraints = NO; - [self.valueLabel.leadingAnchor - constraintEqualToAnchor:self.keyLabel.trailingAnchor - constant:10.f].active = YES; - [self.valueLabel.trailingAnchor - constraintEqualToAnchor:contentLayout.trailingAnchor].active = YES; - [self.valueLabel.topAnchor - constraintEqualToAnchor:contentLayout.topAnchor].active = YES; - [self.valueLabel.bottomAnchor - constraintEqualToAnchor:contentLayout.bottomAnchor].active = YES; + self.valueLabel.translatesAutoresizingMaskIntoConstraints = NO; + [self.valueLabel.leadingAnchor constraintEqualToAnchor:self.keyLabel.trailingAnchor constant:10.f].active = YES; + [self.valueLabel.trailingAnchor constraintEqualToAnchor:contentLayout.trailingAnchor].active = YES; + [self.valueLabel.topAnchor constraintEqualToAnchor:contentLayout.topAnchor].active = YES; + [self.valueLabel.bottomAnchor constraintEqualToAnchor:contentLayout.bottomAnchor].active = YES; - self.valueLabel.textColor = [UIColor whiteColor]; - self.valueLabel.numberOfLines = 0; + self.valueLabel.textColor = [UIColor whiteColor]; + self.valueLabel.numberOfLines = 0; #if !TARGET_OS_TV - self.valueLabel.lineBreakMode = NSLineBreakByWordWrapping; - self.valueLabel.font = [UIFont fontWithName:@"Menlo-Regular" size:12.0f]; + self.valueLabel.lineBreakMode = NSLineBreakByWordWrapping; + self.valueLabel.font = [UIFont fontWithName:@"Menlo-Regular" size:12.0f]; #endif - } - return self; + } + return self; } @end @@ -76,217 +62,192 @@ @end -@implementation RCTRedBoxExtraDataViewController -{ - UITableView *_tableView; - NSMutableArray *_extraDataTitle; - NSMutableArray *_extraData; +@implementation RCTRedBoxExtraDataViewController { + UITableView *_tableView; + NSMutableArray *_extraDataTitle; + NSMutableArray *_extraData; } @synthesize actionDelegate = _actionDelegate; - (instancetype)init { - if (self = [super init]) { - _extraData = [NSMutableArray new]; - _extraDataTitle = [NSMutableArray new]; - self.view.backgroundColor = [UIColor colorWithRed:0.8 - green:0 - blue:0 - alpha:1]; + if (self = [super init]) { + _extraData = [NSMutableArray new]; + _extraDataTitle = [NSMutableArray new]; + self.view.backgroundColor = [UIColor colorWithRed:0.8 green:0 blue:0 alpha:1]; - _tableView = [UITableView new]; - _tableView.delegate = self; - _tableView.dataSource = self; - _tableView.backgroundColor = [UIColor clearColor]; - _tableView.estimatedRowHeight = 200; + _tableView = [UITableView new]; + _tableView.delegate = self; + _tableView.dataSource = self; + _tableView.backgroundColor = [UIColor clearColor]; + _tableView.estimatedRowHeight = 200; #if !TARGET_OS_TV - _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; + _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; #endif - _tableView.rowHeight = UITableViewAutomaticDimension; - _tableView.allowsSelection = NO; + _tableView.rowHeight = UITableViewAutomaticDimension; + _tableView.allowsSelection = NO; #if TARGET_OS_SIMULATOR || TARGET_OS_MACCATALYST - NSString *reloadText = @"Reload JS (\u2318R)"; - NSString *dismissText = @"Dismiss (ESC)"; + NSString *reloadText = @"Reload JS (\u2318R)"; + NSString *dismissText = @"Dismiss (ESC)"; #else - NSString *reloadText = @"Reload JS"; - NSString *dismissText = @"Dismiss"; + NSString *reloadText = @"Reload JS"; + NSString *dismissText = @"Dismiss"; #endif - UIButton *dismissButton = [UIButton buttonWithType:UIButtonTypeCustom]; - dismissButton.translatesAutoresizingMaskIntoConstraints = NO; - dismissButton.accessibilityIdentifier = @"redbox-extra-data-dismiss"; - dismissButton.titleLabel.font = [UIFont systemFontOfSize:13]; - [dismissButton setTitle:dismissText forState:UIControlStateNormal]; - [dismissButton setTitleColor:[UIColor colorWithWhite:1 alpha:0.5] - forState:UIControlStateNormal]; - [dismissButton setTitleColor:[UIColor whiteColor] - forState:UIControlStateHighlighted]; - [dismissButton addTarget:self - action:@selector(dismiss) - forControlEvents:UIControlEventTouchUpInside]; + UIButton *dismissButton = [UIButton buttonWithType:UIButtonTypeCustom]; + dismissButton.translatesAutoresizingMaskIntoConstraints = NO; + dismissButton.accessibilityIdentifier = @"redbox-extra-data-dismiss"; + dismissButton.titleLabel.font = [UIFont systemFontOfSize:13]; + [dismissButton setTitle:dismissText forState:UIControlStateNormal]; + [dismissButton setTitleColor:[UIColor colorWithWhite:1 alpha:0.5] forState:UIControlStateNormal]; + [dismissButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted]; + [dismissButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside]; - UIButton *reloadButton = [UIButton buttonWithType:UIButtonTypeCustom]; - reloadButton.accessibilityIdentifier = @"redbox-reload"; - reloadButton.titleLabel.font = [UIFont systemFontOfSize:13]; - [reloadButton setTitle:reloadText forState:UIControlStateNormal]; - [reloadButton setTitleColor:[UIColor colorWithWhite:1 alpha:0.5] - forState:UIControlStateNormal]; - [reloadButton setTitleColor:[UIColor whiteColor] - forState:UIControlStateHighlighted]; - [reloadButton addTarget:self - action:@selector(reload) - forControlEvents:UIControlEventTouchUpInside]; + UIButton *reloadButton = [UIButton buttonWithType:UIButtonTypeCustom]; + reloadButton.accessibilityIdentifier = @"redbox-reload"; + reloadButton.titleLabel.font = [UIFont systemFontOfSize:13]; + [reloadButton setTitle:reloadText forState:UIControlStateNormal]; + [reloadButton setTitleColor:[UIColor colorWithWhite:1 alpha:0.5] forState:UIControlStateNormal]; + [reloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted]; + [reloadButton addTarget:self action:@selector(reload) forControlEvents:UIControlEventTouchUpInside]; - UIStackView *buttonStackView = [UIStackView new]; - buttonStackView.axis = UILayoutConstraintAxisHorizontal; - buttonStackView.distribution = UIStackViewDistributionEqualSpacing; - buttonStackView.alignment = UIStackViewAlignmentFill; - buttonStackView.spacing = 20; + UIStackView *buttonStackView = [UIStackView new]; + buttonStackView.axis = UILayoutConstraintAxisHorizontal; + buttonStackView.distribution = UIStackViewDistributionEqualSpacing; + buttonStackView.alignment = UIStackViewAlignmentFill; + buttonStackView.spacing = 20; - [buttonStackView addArrangedSubview:dismissButton]; - [buttonStackView addArrangedSubview:reloadButton]; - buttonStackView.translatesAutoresizingMaskIntoConstraints = NO; + [buttonStackView addArrangedSubview:dismissButton]; + [buttonStackView addArrangedSubview:reloadButton]; + buttonStackView.translatesAutoresizingMaskIntoConstraints = NO; - UIStackView *mainStackView = [UIStackView new]; - mainStackView.axis = UILayoutConstraintAxisVertical; - mainStackView.backgroundColor = [UIColor colorWithRed:0.8 - green:0 blue:0 - alpha:1]; - [mainStackView addArrangedSubview:_tableView]; - [mainStackView addArrangedSubview:buttonStackView]; - mainStackView.translatesAutoresizingMaskIntoConstraints = NO; + UIStackView *mainStackView = [UIStackView new]; + mainStackView.axis = UILayoutConstraintAxisVertical; + mainStackView.backgroundColor = [UIColor colorWithRed:0.8 green:0 blue:0 alpha:1]; + [mainStackView addArrangedSubview:_tableView]; + [mainStackView addArrangedSubview:buttonStackView]; + mainStackView.translatesAutoresizingMaskIntoConstraints = NO; - [self.view addSubview:mainStackView]; + [self.view addSubview:mainStackView]; - CGFloat tableHeight = self.view.bounds.size.height - 60.f; - [_tableView.heightAnchor constraintEqualToConstant:tableHeight].active = YES; - [_tableView.widthAnchor constraintEqualToAnchor:self.view.widthAnchor].active = YES; + CGFloat tableHeight = self.view.bounds.size.height - 60.f; + [_tableView.heightAnchor constraintEqualToConstant:tableHeight].active = YES; + [_tableView.widthAnchor constraintEqualToAnchor:self.view.widthAnchor].active = YES; - CGFloat buttonWidth = self.view.bounds.size.width / 4; - [dismissButton.heightAnchor constraintEqualToConstant:60].active = YES; - [dismissButton.widthAnchor - constraintEqualToConstant:buttonWidth].active = YES; - [reloadButton.heightAnchor constraintEqualToConstant:60].active = YES; - [reloadButton.widthAnchor - constraintEqualToConstant:buttonWidth].active = YES; - } - return self; + CGFloat buttonWidth = self.view.bounds.size.width / 4; + [dismissButton.heightAnchor constraintEqualToConstant:60].active = YES; + [dismissButton.widthAnchor constraintEqualToConstant:buttonWidth].active = YES; + [reloadButton.heightAnchor constraintEqualToConstant:60].active = YES; + [reloadButton.widthAnchor constraintEqualToConstant:buttonWidth].active = YES; + } + return self; } - (void)viewDidAppear:(BOOL)animated { - [super viewDidAppear:animated]; - [_tableView reloadData]; + [super viewDidAppear:animated]; + [_tableView reloadData]; } - (NSInteger)tableView:(__unused UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - return [[_extraData objectAtIndex:section] count]; + return [[_extraData objectAtIndex:section] count]; } - (CGFloat)tableView:(__unused UITableView *)tableView heightForHeaderInSection:(__unused NSInteger)section { - return 40; + return 40; } - (UIView *)tableView:(__unused UITableView *)tableView viewForHeaderInSection:(NSInteger)section { - UIView *view = [UIView new]; - view.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:1]; + UIView *view = [UIView new]; + view.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:1]; - UILabel *header = [UILabel new]; - [view addSubview:header]; + UILabel *header = [UILabel new]; + [view addSubview:header]; - header.translatesAutoresizingMaskIntoConstraints = NO; - [header.leadingAnchor - constraintEqualToAnchor:view.leadingAnchor constant:5].active = YES; - [header.trailingAnchor - constraintEqualToAnchor:view.trailingAnchor].active = YES; - [header.topAnchor - constraintEqualToAnchor:view.topAnchor].active = YES; - [header.bottomAnchor - constraintEqualToAnchor:view.bottomAnchor].active = YES; + header.translatesAutoresizingMaskIntoConstraints = NO; + [header.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:5].active = YES; + [header.trailingAnchor constraintEqualToAnchor:view.trailingAnchor].active = YES; + [header.topAnchor constraintEqualToAnchor:view.topAnchor].active = YES; + [header.bottomAnchor constraintEqualToAnchor:view.bottomAnchor].active = YES; - header.textColor = [UIColor whiteColor]; - header.font = [UIFont fontWithName:@"Menlo-Bold" size:14.0f]; - header.text = [_extraDataTitle[section] uppercaseString]; + header.textColor = [UIColor whiteColor]; + header.font = [UIFont fontWithName:@"Menlo-Bold" size:14.0f]; + header.text = [_extraDataTitle[section] uppercaseString]; - return view; + return view; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *reuseIdentifier = @"RedBoxExtraData"; + static NSString *reuseIdentifier = @"RedBoxExtraData"; - RCTRedBoxExtraDataCell *cell = - (RCTRedBoxExtraDataCell *)[tableView - dequeueReusableCellWithIdentifier:reuseIdentifier]; + RCTRedBoxExtraDataCell *cell = + (RCTRedBoxExtraDataCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; - if (cell == nil) { - cell = [[RCTRedBoxExtraDataCell alloc] - initWithStyle:UITableViewCellStyleDefault - reuseIdentifier:reuseIdentifier]; - } + if (cell == nil) { + cell = [[RCTRedBoxExtraDataCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]; + } - NSArray *dataKVPair = _extraData[indexPath.section][indexPath.row]; - cell.keyLabel.text = dataKVPair[0]; - cell.valueLabel.text = dataKVPair[1]; + NSArray *dataKVPair = _extraData[indexPath.section][indexPath.row]; + cell.keyLabel.text = dataKVPair[0]; + cell.valueLabel.text = dataKVPair[1]; - return cell; + return cell; } - (NSInteger)numberOfSectionsInTableView:(__unused UITableView *)tableView { - return _extraDataTitle.count; + return _extraDataTitle.count; } - (void)addExtraData:(NSDictionary *)data forIdentifier:(NSString *)identifier { - dispatch_async(dispatch_get_main_queue(), ^{ - NSMutableArray *newData = [NSMutableArray new]; - for (id key in data) { - [newData addObject:@[[NSString stringWithFormat:@"%@", key], - [NSString stringWithFormat:@"%@", [data objectForKey:key]]]]; - } + dispatch_async(dispatch_get_main_queue(), ^{ + NSMutableArray *newData = [NSMutableArray new]; + for (id key in data) { + [newData addObject:@[ + [NSString stringWithFormat:@"%@", key], + [NSString stringWithFormat:@"%@", [data objectForKey:key]] + ]]; + } - NSInteger idx = [self->_extraDataTitle indexOfObject:identifier]; - if (idx == NSNotFound) { - [self->_extraDataTitle addObject:identifier]; - [self->_extraData addObject:newData]; - } else { - [self->_extraData replaceObjectAtIndex:idx withObject:newData]; - } + NSInteger idx = [self->_extraDataTitle indexOfObject:identifier]; + if (idx == NSNotFound) { + [self->_extraDataTitle addObject:identifier]; + [self->_extraData addObject:newData]; + } else { + [self->_extraData replaceObjectAtIndex:idx withObject:newData]; + } - [self->_tableView reloadData]; - }); + [self->_tableView reloadData]; + }); } - (void)dismiss { - [self dismissViewControllerAnimated:YES completion:nil]; + [self dismissViewControllerAnimated:YES completion:nil]; } - (void)reload { - [_actionDelegate reload]; + [_actionDelegate reload]; } #pragma mark - Key commands - (NSArray *)keyCommands { - return @[ - // Dismiss - [UIKeyCommand keyCommandWithInput:UIKeyInputEscape - modifierFlags:0 - action:@selector(dismiss)], - // Reload - [UIKeyCommand keyCommandWithInput:@"r" - modifierFlags:UIKeyModifierCommand - action:@selector(reload)] - ]; + return @[ + // Dismiss + [UIKeyCommand keyCommandWithInput:UIKeyInputEscape modifierFlags:0 action:@selector(dismiss)], + // Reload + [UIKeyCommand keyCommandWithInput:@"r" modifierFlags:UIKeyModifierCommand action:@selector(reload)] + ]; } @end diff --git a/React/Modules/RCTSurfacePresenterStub.h b/React/Modules/RCTSurfacePresenterStub.h index 9b03d7f328b..402453e1bbb 100644 --- a/React/Modules/RCTSurfacePresenterStub.h +++ b/React/Modules/RCTSurfacePresenterStub.h @@ -15,7 +15,6 @@ NS_ASSUME_NONNULL_BEGIN // that pulls in all of fabric which doesn't compile in open source yet, so we mirror the protocol // and duplicate the category here for now. - @protocol RCTSurfacePresenterObserver @optional diff --git a/React/Modules/RCTUIManager.m b/React/Modules/RCTUIManager.m index da7b76e0bf9..f0f6ca916e9 100644 --- a/React/Modules/RCTUIManager.m +++ b/React/Modules/RCTUIManager.m @@ -57,10 +57,10 @@ static NSString *RCTNativeIDRegistryKey(NSString *nativeID, NSNumber *rootTag) return [NSString stringWithFormat:@"%@-%@", rootTag, nativeID]; } -NSString *const RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification = @"RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification"; +NSString *const RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification = + @"RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification"; -@implementation RCTUIManager -{ +@implementation RCTUIManager { // Root views are only mutated on the shadow queue NSMutableSet *_rootViewTags; NSMutableArray *_pendingUIBlocks; @@ -165,8 +165,7 @@ RCT_EXPORT_MODULE() _componentDataByName = [NSMutableDictionary new]; for (Class moduleClass in _bridge.moduleClasses) { if ([moduleClass isSubclassOfClass:[RCTViewManager class]]) { - RCTComponentData *componentData = [[RCTComponentData alloc] initWithManagerClass:moduleClass - bridge:_bridge]; + RCTComponentData *componentData = [[RCTComponentData alloc] initWithManagerClass:moduleClass bridge:_bridge]; _componentDataByName[componentData.name] = componentData; } } @@ -198,14 +197,14 @@ RCT_EXPORT_MODULE() id multiplier = [[self->_bridge moduleForName:@"AccessibilityManager" lazilyLoadIfNecessary:YES] valueForKey:@"multiplier"]; if (multiplier) { - [_bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateContentSizeMultiplier" - body:multiplier]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"didUpdateContentSizeMultiplier" body:multiplier]; } #pragma clang diagnostic pop RCTExecuteOnUIManagerQueue(^{ - [[NSNotificationCenter defaultCenter] postNotificationName:RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification - object:self]; + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification + object:self]; [self setNeedsLayout]; }); } @@ -219,7 +218,7 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) NSString *name; NSNumber *degrees = @0; BOOL isLandscape = NO; - switch(orientation) { + switch (orientation) { case UIDeviceOrientationPortrait: name = @"portrait-primary"; break; @@ -244,9 +243,9 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) return nil; } return @{ - @"name": name, - @"rotationDegrees": degrees, - @"isLandscape": @(isLandscape), + @"name" : name, + @"rotationDegrees" : degrees, + @"isLandscape" : @(isLandscape), }; } @@ -259,8 +258,7 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [_bridge.eventDispatcher sendDeviceEventWithName:@"namedOrientationDidChange" - body:orientationEvent]; + [_bridge.eventDispatcher sendDeviceEventWithName:@"namedOrientationDidChange" body:orientationEvent]; #pragma clang diagnostic pop } #endif @@ -274,11 +272,12 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) { RCTAssertUIManagerQueue(); - RCTAssert(RCTIsReactRootView(rootTag), - @"Attempt to register rootTag (%@) which is not actually root tag.", rootTag); + RCTAssert(RCTIsReactRootView(rootTag), @"Attempt to register rootTag (%@) which is not actually root tag.", rootTag); - RCTAssert(![_rootViewTags containsObject:rootTag], - @"Attempt to register rootTag (%@) which was already registered.", rootTag); + RCTAssert( + ![_rootViewTags containsObject:rootTag], + @"Attempt to register rootTag (%@) which was already registered.", + rootTag); [_rootViewTags addObject:rootTag]; @@ -300,12 +299,13 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) RCTAssertMainQueue(); NSNumber *reactTag = rootView.reactTag; - RCTAssert(RCTIsReactRootView(reactTag), - @"View %@ with tag #%@ is not a root view", rootView, reactTag); + RCTAssert(RCTIsReactRootView(reactTag), @"View %@ with tag #%@ is not a root view", rootView, reactTag); UIView *existingView = _viewRegistry[reactTag]; - RCTAssert(existingView == nil || existingView == rootView, - @"Expect all root views to have unique tag. Added %@ twice", reactTag); + RCTAssert( + existingView == nil || existingView == rootView, + @"Expect all root views to have unique tag. Added %@ twice", + reactTag); CGSize availableSize = rootView.availableSize; @@ -371,7 +371,9 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) RCTShadowView *shadowView = self->_shadowViewRegistry[tag]; if (shadowView == nil) { - RCTLogInfo(@"Could not locate shadow view with tag #%@, this is probably caused by a temporary inconsistency between native views and shadow views.", tag); + RCTLogInfo( + @"Could not locate shadow view with tag #%@, this is probably caused by a temporary inconsistency between native views and shadow views.", + tag); return; } @@ -382,27 +384,32 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) - (void)setAvailableSize:(CGSize)availableSize forRootView:(UIView *)rootView { RCTAssertMainQueue(); - [self _executeBlockWithShadowView:^(RCTShadowView *shadowView) { - RCTAssert([shadowView isKindOfClass:[RCTRootShadowView class]], @"Located shadow view is actually not root view."); + [self + _executeBlockWithShadowView:^(RCTShadowView *shadowView) { + RCTAssert( + [shadowView isKindOfClass:[RCTRootShadowView class]], @"Located shadow view is actually not root view."); - RCTRootShadowView *rootShadowView = (RCTRootShadowView *)shadowView; + RCTRootShadowView *rootShadowView = (RCTRootShadowView *)shadowView; - if (CGSizeEqualToSize(availableSize, rootShadowView.availableSize)) { - return; - } + if (CGSizeEqualToSize(availableSize, rootShadowView.availableSize)) { + return; + } - rootShadowView.availableSize = availableSize; - [self setNeedsLayout]; - } forTag:rootView.reactTag]; + rootShadowView.availableSize = availableSize; + [self setNeedsLayout]; + } + forTag:rootView.reactTag]; } - (void)setLocalData:(NSObject *)localData forView:(UIView *)view { RCTAssertMainQueue(); - [self _executeBlockWithShadowView:^(RCTShadowView *shadowView) { - shadowView.localData = localData; - [self setNeedsLayout]; - } forTag:view.reactTag]; + [self + _executeBlockWithShadowView:^(RCTShadowView *shadowView) { + shadowView.localData = localData; + [self setNeedsLayout]; + } + forTag:view.reactTag]; } - (UIView *)viewForNativeID:(NSString *)nativeID withRootTag:(NSNumber *)rootTag @@ -434,27 +441,31 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) - (void)setSize:(CGSize)size forView:(UIView *)view { RCTAssertMainQueue(); - [self _executeBlockWithShadowView:^(RCTShadowView *shadowView) { - if (CGSizeEqualToSize(size, shadowView.size)) { - return; - } + [self + _executeBlockWithShadowView:^(RCTShadowView *shadowView) { + if (CGSizeEqualToSize(size, shadowView.size)) { + return; + } - shadowView.size = size; - [self setNeedsLayout]; - } forTag:view.reactTag]; + shadowView.size = size; + [self setNeedsLayout]; + } + forTag:view.reactTag]; } - (void)setIntrinsicContentSize:(CGSize)intrinsicContentSize forView:(UIView *)view { RCTAssertMainQueue(); - [self _executeBlockWithShadowView:^(RCTShadowView *shadowView) { - if (CGSizeEqualToSize(shadowView.intrinsicContentSize, intrinsicContentSize)) { - return; - } + [self + _executeBlockWithShadowView:^(RCTShadowView *shadowView) { + if (CGSizeEqualToSize(shadowView.intrinsicContentSize, intrinsicContentSize)) { + return; + } - shadowView.intrinsicContentSize = intrinsicContentSize; - [self setNeedsLayout]; - } forTag:view.reactTag]; + shadowView.intrinsicContentSize = intrinsicContentSize; + [self setNeedsLayout]; + } + forTag:view.reactTag]; } /** @@ -501,9 +512,10 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) RCTAssertMainQueue(); if (_layoutAnimationGroup && ![_layoutAnimationGroup isEqual:layoutAnimationGroup]) { - RCTLogWarn(@"Warning: Overriding previous layout animation with new one before the first began:\n%@ -> %@.", - [_layoutAnimationGroup description], - [layoutAnimationGroup description]); + RCTLogWarn( + @"Warning: Overriding previous layout animation with new one before the first began:\n%@ -> %@.", + [_layoutAnimationGroup description], + [layoutAnimationGroup description]); } _layoutAnimationGroup = layoutAnimationGroup; @@ -539,18 +551,15 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) for (RCTShadowView *shadowView in affectedShadowViews) { reactTags[index] = shadowView.reactTag; RCTLayoutMetrics layoutMetrics = shadowView.layoutMetrics; - frameDataArray[index++] = (RCTFrameData){ - layoutMetrics.frame, - layoutMetrics.layoutDirection, - shadowView.isNewView, - shadowView.superview.isNewView, - layoutMetrics.displayType - }; + frameDataArray[index++] = (RCTFrameData){layoutMetrics.frame, + layoutMetrics.layoutDirection, + shadowView.isNewView, + shadowView.superview.isNewView, + layoutMetrics.displayType}; } } for (RCTShadowView *shadowView in affectedShadowViews) { - // We have to do this after we build the parentsAreNew array. shadowView.newView = NO; @@ -559,19 +568,16 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) if (shadowView.onLayout) { CGRect frame = shadowView.layoutMetrics.frame; shadowView.onLayout(@{ - @"layout": @{ - @"x": @(frame.origin.x), - @"y": @(frame.origin.y), - @"width": @(frame.size.width), - @"height": @(frame.size.height), + @"layout" : @{ + @"x" : @(frame.origin.x), + @"y" : @(frame.origin.y), + @"width" : @(frame.size.width), + @"height" : @(frame.size.height), }, }); } - if ( - RCTIsReactRootView(reactTag) && - [shadowView isKindOfClass:[RCTRootShadowView class]] - ) { + if (RCTIsReactRootView(reactTag) && [shadowView isKindOfClass:[RCTRootShadowView class]]) { CGSize contentSize = shadowView.layoutMetrics.frame.size; RCTExecuteOnMainQueue(^{ @@ -588,7 +594,6 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) // Perform layout (possibly animated) return ^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { - const RCTFrameData *frameDataArray = (const RCTFrameData *)framesData.bytes; RCTLayoutAnimationGroup *layoutAnimationGroup = uiManager->_layoutAnimationGroup; @@ -605,13 +610,14 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) BOOL isNew = frameData.isNew; RCTLayoutAnimation *updatingLayoutAnimation = isNew ? nil : layoutAnimationGroup.updatingLayoutAnimation; BOOL shouldAnimateCreation = isNew && !frameData.parentIsNew; - RCTLayoutAnimation *creatingLayoutAnimation = shouldAnimateCreation ? layoutAnimationGroup.creatingLayoutAnimation : nil; + RCTLayoutAnimation *creatingLayoutAnimation = + shouldAnimateCreation ? layoutAnimationGroup.creatingLayoutAnimation : nil; BOOL isHidden = frameData.displayType == RCTDisplayTypeNone; void (^completion)(BOOL) = ^(BOOL finished) { completionsCalled++; if (layoutAnimationGroup.callback && completionsCalled == count) { - layoutAnimationGroup.callback(@[@(finished)]); + layoutAnimationGroup.callback(@[ @(finished) ]); // It's unsafe to call this callback more than once, so we nil it out here // to make sure that doesn't happen. @@ -628,7 +634,6 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) } if (creatingLayoutAnimation) { - // Animate view creation [view reactSetFrame:frame]; @@ -639,37 +644,35 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) if ([property isEqualToString:@"scaleXY"]) { view.layer.transform = CATransform3DMakeScale(0, 0, 0); } else if ([property isEqualToString:@"scaleX"]) { - view.layer.transform = CATransform3DMakeScale(0, 1, 0); + view.layer.transform = CATransform3DMakeScale(0, 1, 0); } else if ([property isEqualToString:@"scaleY"]) { - view.layer.transform = CATransform3DMakeScale(1, 0, 0); + view.layer.transform = CATransform3DMakeScale(1, 0, 0); } else if ([property isEqualToString:@"opacity"]) { view.layer.opacity = 0.0; } else { - RCTLogError(@"Unsupported layout animation createConfig property %@", - creatingLayoutAnimation.property); + RCTLogError(@"Unsupported layout animation createConfig property %@", creatingLayoutAnimation.property); } - [creatingLayoutAnimation performAnimations:^{ - if ( - [property isEqualToString:@"scaleX"] || - [property isEqualToString:@"scaleY"] || - [property isEqualToString:@"scaleXY"] - ) { - view.layer.transform = finalTransform; - } else if ([property isEqualToString:@"opacity"]) { - view.layer.opacity = finalOpacity; - } - } withCompletionBlock:completion]; + [creatingLayoutAnimation + performAnimations:^{ + if ([property isEqualToString:@"scaleX"] || [property isEqualToString:@"scaleY"] || + [property isEqualToString:@"scaleXY"]) { + view.layer.transform = finalTransform; + } else if ([property isEqualToString:@"opacity"]) { + view.layer.opacity = finalOpacity; + } + } + withCompletionBlock:completion]; } else if (updatingLayoutAnimation) { - // Animate view update - [updatingLayoutAnimation performAnimations:^{ - [view reactSetFrame:frame]; - } withCompletionBlock:completion]; + [updatingLayoutAnimation + performAnimations:^{ + [view reactSetFrame:frame]; + } + withCompletionBlock:completion]; } else { - // Update without animation [view reactSetFrame:frame]; completion(YES); @@ -685,9 +688,10 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) * A method to be called from JS, which takes a container ID and then releases * all subviews for that container upon receipt. */ -RCT_EXPORT_METHOD(removeSubviewsFromContainerWithID:(nonnull NSNumber *)containerID) +RCT_EXPORT_METHOD(removeSubviewsFromContainerWithID : (nonnull NSNumber *)containerID) { - RCTLogWarn(@"RCTUIManager.removeSubviewsFromContainerWithID method is deprecated and it will not be implemented in newer versions of RN (Fabric) - T47686450"); + RCTLogWarn( + @"RCTUIManager.removeSubviewsFromContainerWithID method is deprecated and it will not be implemented in newer versions of RN (Fabric) - T47686450"); id container = _shadowViewRegistry[containerID]; RCTAssert(container != nil, @"container view (for ID %@) not found", containerID); @@ -698,11 +702,11 @@ RCT_EXPORT_METHOD(removeSubviewsFromContainerWithID:(nonnull NSNumber *)containe } [self manageChildren:containerID - moveFromIndices:nil - moveToIndices:nil - addChildReactTags:nil - addAtIndices:nil - removeAtIndices:indices]; + moveFromIndices:nil + moveToIndices:nil + addChildReactTags:nil + addAtIndices:nil + removeAtIndices:indices]; } /** @@ -730,14 +734,14 @@ RCT_EXPORT_METHOD(removeSubviewsFromContainerWithID:(nonnull NSNumber *)containe } if (removedChildren.count != atIndices.count) { NSString *message = [NSString stringWithFormat:@"removedChildren count (%tu) was not what we expected (%tu)", - removedChildren.count, atIndices.count]; + removedChildren.count, + atIndices.count]; RCTFatal(RCTErrorWithMessage(message)); } return removedChildren; } -- (void)_removeChildren:(NSArray> *)children - fromContainer:(id)container +- (void)_removeChildren:(NSArray> *)children fromContainer:(id)container { for (id removedChild in children) { [container removeReactSubview:removedChild]; @@ -756,14 +760,13 @@ RCT_EXPORT_METHOD(removeSubviewsFromContainerWithID:(nonnull NSNumber *)containe __block NSUInteger completionsCalled = 0; for (UIView *removedChild in children) { - void (^completion)(BOOL) = ^(BOOL finished) { completionsCalled++; [removedChild removeFromSuperview]; if (animation.callback && completionsCalled == children.count) { - animation.callback(@[@(finished)]); + animation.callback(@[ @(finished) ]); // It's unsafe to call this callback more than once, so we nil it out here // to make sure that doesn't happen. @@ -775,9 +778,9 @@ RCT_EXPORT_METHOD(removeSubviewsFromContainerWithID:(nonnull NSNumber *)containe // First one: We want to delete the view from view hierarchy. // Second one: We want to animate this view, which implies the existence of this view in the hierarchy. // So, we have to remove this view from React's view hierarchy but postpone removing from UIKit's hierarchy. - // Here the problem: the default implementation of `-[UIView removeReactSubview:]` also removes the view from UIKit's hierarchy. - // So, let's temporary restore the view back after removing. - // To do so, we have to memorize original `superview` (which can differ from `container`) and an index of removed view. + // Here the problem: the default implementation of `-[UIView removeReactSubview:]` also removes the view from + // UIKit's hierarchy. So, let's temporary restore the view back after removing. To do so, we have to memorize + // original `superview` (which can differ from `container`) and an index of removed view. UIView *originalSuperview = removedChild.superview; NSUInteger originalIndex = [originalSuperview.subviews indexOfObjectIdenticalTo:removedChild]; [container removeReactSubview:removedChild]; @@ -787,25 +790,25 @@ RCT_EXPORT_METHOD(removeSubviewsFromContainerWithID:(nonnull NSNumber *)containe [originalSuperview insertSubview:removedChild atIndex:originalIndex]; NSString *property = deletingLayoutAnimation.property; - [deletingLayoutAnimation performAnimations:^{ - if ([property isEqualToString:@"scaleXY"]) { - removedChild.layer.transform = CATransform3DMakeScale(0.001, 0.001, 0.001); - } else if ([property isEqualToString:@"scaleX"]) { - removedChild.layer.transform = CATransform3DMakeScale(0.001, 1, 0.001); - } else if ([property isEqualToString:@"scaleY"]) { - removedChild.layer.transform = CATransform3DMakeScale(1, 0.001, 0.001); - } else if ([property isEqualToString:@"opacity"]) { - removedChild.layer.opacity = 0.0; - } else { - RCTLogError(@"Unsupported layout animation createConfig property %@", - deletingLayoutAnimation.property); - } - } withCompletionBlock:completion]; + [deletingLayoutAnimation + performAnimations:^{ + if ([property isEqualToString:@"scaleXY"]) { + removedChild.layer.transform = CATransform3DMakeScale(0.001, 0.001, 0.001); + } else if ([property isEqualToString:@"scaleX"]) { + removedChild.layer.transform = CATransform3DMakeScale(0.001, 1, 0.001); + } else if ([property isEqualToString:@"scaleY"]) { + removedChild.layer.transform = CATransform3DMakeScale(1, 0.001, 0.001); + } else if ([property isEqualToString:@"opacity"]) { + removedChild.layer.opacity = 0.0; + } else { + RCTLogError(@"Unsupported layout animation createConfig property %@", deletingLayoutAnimation.property); + } + } + withCompletionBlock:completion]; } } - -RCT_EXPORT_METHOD(removeRootView:(nonnull NSNumber *)rootReactTag) +RCT_EXPORT_METHOD(removeRootView : (nonnull NSNumber *)rootReactTag) { RCTShadowView *rootShadowView = _shadowViewRegistry[rootReactTag]; RCTAssert(rootShadowView.superview == nil, @"root view cannot have superview (ID %@)", rootReactTag); @@ -814,7 +817,7 @@ RCT_EXPORT_METHOD(removeRootView:(nonnull NSNumber *)rootReactTag) [_shadowViewRegistry removeObjectForKey:rootReactTag]; [_rootViewTags removeObject:rootReactTag]; - [self addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry){ + [self addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry) { RCTAssertMainQueue(); UIView *rootView = viewRegistry[rootReactTag]; [uiManager _purgeChildren:(NSArray> *)rootView.reactSubviews @@ -823,10 +826,10 @@ RCT_EXPORT_METHOD(removeRootView:(nonnull NSNumber *)rootReactTag) }]; } -RCT_EXPORT_METHOD(replaceExistingNonRootView:(nonnull NSNumber *)reactTag - withView:(nonnull NSNumber *)newReactTag) +RCT_EXPORT_METHOD(replaceExistingNonRootView : (nonnull NSNumber *)reactTag withView : (nonnull NSNumber *)newReactTag) { - RCTLogWarn(@"RCTUIManager.replaceExistingNonRootView method is deprecated and it will not be implemented in newer versions of RN (Fabric) - T47686450"); + RCTLogWarn( + @"RCTUIManager.replaceExistingNonRootView method is deprecated and it will not be implemented in newer versions of RN (Fabric) - T47686450"); RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTAssert(shadowView != nil, @"shadowView (for ID %@) not found", reactTag); @@ -838,34 +841,31 @@ RCT_EXPORT_METHOD(replaceExistingNonRootView:(nonnull NSNumber *)reactTag NSUInteger indexOfView = [superShadowView.reactSubviews indexOfObjectIdenticalTo:shadowView]; RCTAssert(indexOfView != NSNotFound, @"View's superview doesn't claim it as subview (id %@)", reactTag); - NSArray *removeAtIndices = @[@(indexOfView)]; - NSArray *addTags = @[newReactTag]; + NSArray *removeAtIndices = @[ @(indexOfView) ]; + NSArray *addTags = @[ newReactTag ]; [self manageChildren:superShadowView.reactTag - moveFromIndices:nil - moveToIndices:nil - addChildReactTags:addTags - addAtIndices:removeAtIndices - removeAtIndices:removeAtIndices]; + moveFromIndices:nil + moveToIndices:nil + addChildReactTags:addTags + addAtIndices:removeAtIndices + removeAtIndices:removeAtIndices]; } -RCT_EXPORT_METHOD(setChildren:(nonnull NSNumber *)containerTag - reactTags:(NSArray *)reactTags) +RCT_EXPORT_METHOD(setChildren : (nonnull NSNumber *)containerTag reactTags : (NSArray *)reactTags) { - RCTSetChildren(containerTag, reactTags, - (NSDictionary> *)_shadowViewRegistry); + RCTSetChildren(containerTag, reactTags, (NSDictionary> *)_shadowViewRegistry); - [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry){ - - RCTSetChildren(containerTag, reactTags, - (NSDictionary> *)viewRegistry); + [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + RCTSetChildren(containerTag, reactTags, (NSDictionary> *)viewRegistry); }]; [self _shadowViewDidReceiveUpdatedChildren:_shadowViewRegistry[containerTag]]; } -static void RCTSetChildren(NSNumber *containerTag, - NSArray *reactTags, - NSDictionary> *registry) +static void RCTSetChildren( + NSNumber *containerTag, + NSArray *reactTags, + NSDictionary> *registry) { id container = registry[containerTag]; NSInteger index = 0; @@ -877,12 +877,13 @@ static void RCTSetChildren(NSNumber *containerTag, } } -RCT_EXPORT_METHOD(manageChildren:(nonnull NSNumber *)containerTag - moveFromIndices:(NSArray *)moveFromIndices - moveToIndices:(NSArray *)moveToIndices - addChildReactTags:(NSArray *)addChildReactTags - addAtIndices:(NSArray *)addAtIndices - removeAtIndices:(NSArray *)removeAtIndices) +RCT_EXPORT_METHOD(manageChildren + : (nonnull NSNumber *)containerTag moveFromIndices + : (NSArray *)moveFromIndices moveToIndices + : (NSArray *)moveToIndices addChildReactTags + : (NSArray *)addChildReactTags addAtIndices + : (NSArray *)addAtIndices removeAtIndices + : (NSArray *)removeAtIndices) { [self _manageChildren:containerTag moveFromIndices:moveFromIndices @@ -892,7 +893,7 @@ RCT_EXPORT_METHOD(manageChildren:(nonnull NSNumber *)containerTag removeAtIndices:removeAtIndices registry:(NSMutableDictionary> *)_shadowViewRegistry]; - [self addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry){ + [self addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry) { [uiManager _manageChildren:containerTag moveFromIndices:moveFromIndices moveToIndices:moveToIndices @@ -914,14 +915,18 @@ RCT_EXPORT_METHOD(manageChildren:(nonnull NSNumber *)containerTag registry:(NSMutableDictionary> *)registry { id container = registry[containerTag]; - RCTAssert(moveFromIndices.count == moveToIndices.count, @"moveFromIndices had size %tu, moveToIndices had size %tu", moveFromIndices.count, moveToIndices.count); + RCTAssert( + moveFromIndices.count == moveToIndices.count, + @"moveFromIndices had size %tu, moveToIndices had size %tu", + moveFromIndices.count, + moveToIndices.count); RCTAssert(addChildReactTags.count == addAtIndices.count, @"there should be at least one React child to add"); // Removes (both permanent and temporary moves) are using "before" indices - NSArray> *permanentlyRemovedChildren = - [self _childrenToRemoveFromContainer:container atIndices:removeAtIndices]; - NSArray> *temporarilyRemovedChildren = - [self _childrenToRemoveFromContainer:container atIndices:moveFromIndices]; + NSArray> *permanentlyRemovedChildren = [self _childrenToRemoveFromContainer:container + atIndices:removeAtIndices]; + NSArray> *temporarilyRemovedChildren = [self _childrenToRemoveFromContainer:container + atIndices:moveFromIndices]; BOOL isUIViewRegistry = ((id)registry == (id)_viewRegistry); if (isUIViewRegistry && _layoutAnimationGroup.deletingLayoutAnimation) { @@ -949,17 +954,17 @@ RCT_EXPORT_METHOD(manageChildren:(nonnull NSNumber *)containerTag } NSArray *sortedIndices = - [destinationsToChildrenToAdd.allKeys sortedArrayUsingSelector:@selector(compare:)]; + [destinationsToChildrenToAdd.allKeys sortedArrayUsingSelector:@selector(compare:)]; for (NSNumber *reactIndex in sortedIndices) { - [container insertReactSubview:destinationsToChildrenToAdd[reactIndex] - atIndex:reactIndex.integerValue]; + [container insertReactSubview:destinationsToChildrenToAdd[reactIndex] atIndex:reactIndex.integerValue]; } } -RCT_EXPORT_METHOD(createView:(nonnull NSNumber *)reactTag - viewName:(NSString *)viewName - rootTag:(nonnull NSNumber *)rootTag - props:(NSDictionary *)props) +RCT_EXPORT_METHOD(createView + : (nonnull NSNumber *)reactTag viewName + : (NSString *)viewName rootTag + : (nonnull NSNumber *)rootTag props + : (NSDictionary *)props) { RCTComponentData *componentData = _componentDataByName[viewName]; if (componentData == nil) { @@ -972,9 +977,10 @@ RCT_EXPORT_METHOD(createView:(nonnull NSNumber *)reactTag [componentData setProps:props forShadowView:shadowView]; _shadowViewRegistry[reactTag] = shadowView; RCTShadowView *rootView = _shadowViewRegistry[rootTag]; - RCTAssert([rootView isKindOfClass:[RCTRootShadowView class]] || - [rootView isKindOfClass:[RCTSurfaceRootShadowView class]], - @"Given `rootTag` (%@) does not correspond to a valid root shadow view instance.", rootTag); + RCTAssert( + [rootView isKindOfClass:[RCTRootShadowView class]] || [rootView isKindOfClass:[RCTSurfaceRootShadowView class]], + @"Given `rootTag` (%@) does not correspond to a valid root shadow view instance.", + rootTag); shadowView.rootView = (RCTRootShadowView *)rootView; } @@ -1015,9 +1021,11 @@ RCT_EXPORT_METHOD(createView:(nonnull NSNumber *)reactTag [self _shadowView:shadowView didReceiveUpdatedProps:[props allKeys]]; } -RCT_EXPORT_METHOD(updateView:(nonnull NSNumber *)reactTag - viewName:(NSString *)viewName // not always reliable, use shadowView.viewName if available - props:(NSDictionary *)props) +RCT_EXPORT_METHOD(updateView + : (nonnull NSNumber *)reactTag viewName + : (NSString *)viewName // not always reliable, use shadowView.viewName if available + props + : (NSDictionary *)props) { RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTComponentData *componentData = _componentDataByName[shadowView.viewName ?: viewName]; @@ -1031,9 +1039,7 @@ RCT_EXPORT_METHOD(updateView:(nonnull NSNumber *)reactTag [self _shadowView:shadowView didReceiveUpdatedProps:[props allKeys]]; } -- (void)synchronouslyUpdateViewOnUIThread:(NSNumber *)reactTag - viewName:(NSString *)viewName - props:(NSDictionary *)props +- (void)synchronouslyUpdateViewOnUIThread:(NSNumber *)reactTag viewName:(NSString *)viewName props:(NSDictionary *)props { RCTAssertMainQueue(); RCTComponentData *componentData = _componentDataByName[viewName]; @@ -1041,7 +1047,7 @@ RCT_EXPORT_METHOD(updateView:(nonnull NSNumber *)reactTag [componentData setProps:props forView:view]; } -RCT_EXPORT_METHOD(focus:(nonnull NSNumber *)reactTag) +RCT_EXPORT_METHOD(focus : (nonnull NSNumber *)reactTag) { [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { UIView *newResponder = viewRegistry[reactTag]; @@ -1049,15 +1055,18 @@ RCT_EXPORT_METHOD(focus:(nonnull NSNumber *)reactTag) }]; } -RCT_EXPORT_METHOD(blur:(nonnull NSNumber *)reactTag) +RCT_EXPORT_METHOD(blur : (nonnull NSNumber *)reactTag) { - [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry){ + [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { UIView *currentResponder = viewRegistry[reactTag]; [currentResponder reactBlur]; }]; } -RCT_EXPORT_METHOD(findSubviewIn:(nonnull NSNumber *)reactTag atPoint:(CGPoint)point callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(findSubviewIn + : (nonnull NSNumber *)reactTag atPoint + : (CGPoint)point callback + : (RCTResponseSenderBlock)callback) { [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[reactTag]; @@ -1078,17 +1087,18 @@ RCT_EXPORT_METHOD(findSubviewIn:(nonnull NSNumber *)reactTag atPoint:(CGPoint)po }]; } -RCT_EXPORT_METHOD(dispatchViewManagerCommand:(nonnull NSNumber *)reactTag - commandID:(id /*(NSString or NSNumber) */)commandID - commandArgs:(NSArray *)commandArgs) +RCT_EXPORT_METHOD(dispatchViewManagerCommand + : (nonnull NSNumber *)reactTag commandID + : (id /*(NSString or NSNumber) */)commandID commandArgs + : (NSArray *)commandArgs) { RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTComponentData *componentData = _componentDataByName[shadowView.viewName]; // Achtung! Achtung! // This is a remarkably hacky and ugly workaround. - // We need this only temporary for some testing. We need this hack until Fabric fully implements command-execution pipeline. - // This does not affect non-Fabric apps. + // We need this only temporary for some testing. We need this hack until Fabric fully implements command-execution + // pipeline. This does not affect non-Fabric apps. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wundeclared-selector" if (!componentData) { @@ -1109,7 +1119,7 @@ RCT_EXPORT_METHOD(dispatchViewManagerCommand:(nonnull NSNumber *)reactTag id method; if ([commandID isKindOfClass:[NSNumber class]]) { method = moduleData.methods[[commandID intValue]]; - } else if([commandID isKindOfClass:[NSString class]]) { + } else if ([commandID isKindOfClass:[NSString class]]) { method = moduleData.methodsByName[commandID]; if (method == nil) { RCTLogError(@"No command found with name \"%@\"", commandID); @@ -1119,7 +1129,7 @@ RCT_EXPORT_METHOD(dispatchViewManagerCommand:(nonnull NSNumber *)reactTag return; } - NSArray *args = [@[reactTag] arrayByAddingObjectsFromArray:commandArgs]; + NSArray *args = [@[ reactTag ] arrayByAddingObjectsFromArray:commandArgs]; [method invokeWithBridge:_bridge module:componentData.manager arguments:args]; } @@ -1171,15 +1181,14 @@ RCT_EXPORT_METHOD(dispatchViewManagerCommand:(nonnull NSNumber *)reactTag __weak typeof(self) weakSelf = self; - void (^mountingBlock)(void) = ^{ + void (^mountingBlock)(void) = ^{ typeof(self) strongSelf = weakSelf; @try { for (RCTViewManagerUIBlock block in previousPendingUIBlocks) { block(strongSelf, strongSelf->_viewRegistry); } - } - @catch (NSException *exception) { + } @catch (NSException *exception) { RCTLogError(@"Exception thrown while executing UI block: %@", exception); } }; @@ -1194,8 +1203,8 @@ RCT_EXPORT_METHOD(dispatchViewManagerCommand:(nonnull NSNumber *)reactTag RCTExecuteOnMainQueue(^{ RCTProfileEndFlowEvent(); RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[UIManager flushUIBlocks]", (@{ - @"count": [@(previousPendingUIBlocks.count) stringValue], - })); + @"count" : [@(previousPendingUIBlocks.count) stringValue], + })); mountingBlock(); @@ -1283,8 +1292,7 @@ RCT_EXPORT_METHOD(dispatchViewManagerCommand:(nonnull NSNumber *)reactTag }]; } -RCT_EXPORT_METHOD(measure:(nonnull NSNumber *)reactTag - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(measure : (nonnull NSNumber *)reactTag callback : (RCTResponseSenderBlock)callback) { [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[reactTag]; @@ -1317,8 +1325,7 @@ RCT_EXPORT_METHOD(measure:(nonnull NSNumber *)reactTag }]; } -RCT_EXPORT_METHOD(measureInWindow:(nonnull NSNumber *)reactTag - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(measureInWindow : (nonnull NSNumber *)reactTag callback : (RCTResponseSenderBlock)callback) { [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[reactTag]; @@ -1344,9 +1351,10 @@ RCT_EXPORT_METHOD(measureInWindow:(nonnull NSNumber *)reactTag * Returns if the shadow view provided has the `ancestor` shadow view as * an actual ancestor. */ -RCT_EXPORT_METHOD(viewIsDescendantOf:(nonnull NSNumber *)reactTag - ancestor:(nonnull NSNumber *)ancestorReactTag - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(viewIsDescendantOf + : (nonnull NSNumber *)reactTag ancestor + : (nonnull NSNumber *)ancestorReactTag callback + : (RCTResponseSenderBlock)callback) { RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTShadowView *ancestorShadowView = _shadowViewRegistry[ancestorReactTag]; @@ -1357,12 +1365,10 @@ RCT_EXPORT_METHOD(viewIsDescendantOf:(nonnull NSNumber *)reactTag return; } BOOL viewIsAncestor = [shadowView viewIsDescendantOf:ancestorShadowView]; - callback(@[@(viewIsAncestor)]); + callback(@[ @(viewIsAncestor) ]); } -static void RCTMeasureLayout(RCTShadowView *view, - RCTShadowView *ancestor, - RCTResponseSenderBlock callback) +static void RCTMeasureLayout(RCTShadowView *view, RCTShadowView *ancestor, RCTResponseSenderBlock callback) { if (!view) { return; @@ -1372,8 +1378,8 @@ static void RCTMeasureLayout(RCTShadowView *view, } CGRect result = [view measureLayoutRelativeToAncestor:ancestor]; if (CGRectIsNull(result)) { - RCTLogError(@"view %@ (tag #%@) is not a descendant of %@ (tag #%@)", - view, view.reactTag, ancestor, ancestor.reactTag); + RCTLogError( + @"view %@ (tag #%@) is not a descendant of %@ (tag #%@)", view, view.reactTag, ancestor, ancestor.reactTag); return; } CGFloat leftOffset = result.origin.x; @@ -1384,7 +1390,7 @@ static void RCTMeasureLayout(RCTShadowView *view, RCTLogError(@"Attempted to measure layout but offset or dimensions were NaN"); return; } - callback(@[@(leftOffset), @(topOffset), @(width), @(height)]); + callback(@[ @(leftOffset), @(topOffset), @(width), @(height) ]); } /** @@ -1394,10 +1400,11 @@ static void RCTMeasureLayout(RCTShadowView *view, * anything on the main UI thread. Invokes supplied callback with (x, y, width, * height). */ -RCT_EXPORT_METHOD(measureLayout:(nonnull NSNumber *)reactTag - relativeTo:(nonnull NSNumber *)ancestorReactTag - errorCallback:(__unused RCTResponseSenderBlock)errorCallback - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(measureLayout + : (nonnull NSNumber *)reactTag relativeTo + : (nonnull NSNumber *)ancestorReactTag errorCallback + : (__unused RCTResponseSenderBlock)errorCallback callback + : (RCTResponseSenderBlock)callback) { RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTShadowView *ancestorShadowView = _shadowViewRegistry[ancestorReactTag]; @@ -1411,11 +1418,13 @@ RCT_EXPORT_METHOD(measureLayout:(nonnull NSNumber *)reactTag * anything on the main UI thread. Invokes supplied callback with (x, y, width, * height). */ -RCT_EXPORT_METHOD(measureLayoutRelativeToParent:(nonnull NSNumber *)reactTag - errorCallback:(__unused RCTResponseSenderBlock)errorCallback - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(measureLayoutRelativeToParent + : (nonnull NSNumber *)reactTag errorCallback + : (__unused RCTResponseSenderBlock)errorCallback callback + : (RCTResponseSenderBlock)callback) { - RCTLogWarn(@"RCTUIManager.measureLayoutRelativeToParent method is deprecated and it will not be implemented in newer versions of RN (Fabric) - T47686450"); + RCTLogWarn( + @"RCTUIManager.measureLayoutRelativeToParent method is deprecated and it will not be implemented in newer versions of RN (Fabric) - T47686450"); RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTMeasureLayout(shadowView, shadowView.reactSuperview, callback); } @@ -1424,8 +1433,9 @@ RCT_EXPORT_METHOD(measureLayoutRelativeToParent:(nonnull NSNumber *)reactTag * JS sets what *it* considers to be the responder. Later, scroll views can use * this in order to determine if scrolling is appropriate. */ -RCT_EXPORT_METHOD(setJSResponder:(nonnull NSNumber *)reactTag - blockNativeResponder:(__unused BOOL)blockNativeResponder) +RCT_EXPORT_METHOD(setJSResponder + : (nonnull NSNumber *)reactTag blockNativeResponder + : (__unused BOOL)blockNativeResponder) { [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { _jsResponder = viewRegistry[reactTag]; @@ -1445,7 +1455,8 @@ RCT_EXPORT_METHOD(clearJSResponder) static NSMutableDictionary *moduleConstantsForComponent( NSMutableDictionary *directEvents, NSMutableDictionary *bubblingEvents, - RCTComponentData *componentData) { + RCTComponentData *componentData) +{ NSMutableDictionary *moduleConstants = [NSMutableDictionary new]; // Register which event-types this view dispatches. @@ -1467,13 +1478,16 @@ static NSMutableDictionary *moduleConstantsForComponent( for (NSString *eventName in viewConfig[@"directEvents"]) { if (!directEvents[eventName]) { directEvents[eventName] = @{ - @"registrationName": [eventName stringByReplacingCharactersInRange:(NSRange){0, 3} withString:@"on"], - }; + @"registrationName" : [eventName stringByReplacingCharactersInRange:(NSRange){0, 3} withString:@"on"], + }; } directEventTypes[eventName] = directEvents[eventName]; if (RCT_DEBUG && bubblingEvents[eventName]) { - RCTLogError(@"Component '%@' re-registered bubbling event '%@' as a " - "direct event", componentData.name, eventName); + RCTLogError( + @"Component '%@' re-registered bubbling event '%@' as a " + "direct event", + componentData.name, + eventName); } } @@ -1482,16 +1496,19 @@ static NSMutableDictionary *moduleConstantsForComponent( if (!bubblingEvents[eventName]) { NSString *bubbleName = [eventName stringByReplacingCharactersInRange:(NSRange){0, 3} withString:@"on"]; bubblingEvents[eventName] = @{ - @"phasedRegistrationNames": @{ - @"bubbled": bubbleName, - @"captured": [bubbleName stringByAppendingString:@"Capture"], - } - }; + @"phasedRegistrationNames" : @{ + @"bubbled" : bubbleName, + @"captured" : [bubbleName stringByAppendingString:@"Capture"], + } + }; } bubblingEventTypes[eventName] = bubblingEvents[eventName]; if (RCT_DEBUG && directEvents[eventName]) { - RCTLogError(@"Component '%@' re-registered direct event '%@' as a " - "bubbling event", componentData.name, eventName); + RCTLogError( + @"Component '%@' re-registered direct event '%@' as a " + "bubbling event", + componentData.name, + eventName); } } @@ -1509,16 +1526,18 @@ static NSMutableDictionary *moduleConstantsForComponent( NSMutableDictionary *directEvents = [NSMutableDictionary new]; NSMutableDictionary *bubblingEvents = [NSMutableDictionary new]; - [_componentDataByName enumerateKeysAndObjectsUsingBlock:^(NSString *name, RCTComponentData *componentData, __unused BOOL *stop) { - RCTAssert(!constants[name], @"UIManager already has constants for %@", componentData.name); - NSMutableDictionary *moduleConstants = moduleConstantsForComponent(directEvents, bubblingEvents, componentData); - constants[name] = moduleConstants; - }]; + [_componentDataByName + enumerateKeysAndObjectsUsingBlock:^(NSString *name, RCTComponentData *componentData, __unused BOOL *stop) { + RCTAssert(!constants[name], @"UIManager already has constants for %@", componentData.name); + NSMutableDictionary *moduleConstants = + moduleConstantsForComponent(directEvents, bubblingEvents, componentData); + constants[name] = moduleConstants; + }]; return constants; } -RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(lazilyLoadView:(NSString *)name) +RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(lazilyLoadView : (NSString *)name) { if (_componentDataByName[name]) { return @{}; @@ -1556,20 +1575,20 @@ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(lazilyLoadView:(NSString *)name) _componentDataByName[componentData.name] = componentData; NSMutableDictionary *directEvents = [NSMutableDictionary new]; NSMutableDictionary *bubblingEvents = [NSMutableDictionary new]; - NSMutableDictionary *moduleConstants = moduleConstantsForComponent(directEvents, bubblingEvents, componentData); - return - @{ - @"viewConfig": moduleConstants, - }; + NSMutableDictionary *moduleConstants = + moduleConstantsForComponent(directEvents, bubblingEvents, componentData); + return @{ + @"viewConfig" : moduleConstants, + }; } -RCT_EXPORT_METHOD(configureNextLayoutAnimation:(NSDictionary *)config - withCallback:(RCTResponseSenderBlock)callback - errorCallback:(__unused RCTResponseSenderBlock)errorCallback) +RCT_EXPORT_METHOD(configureNextLayoutAnimation + : (NSDictionary *)config withCallback + : (RCTResponseSenderBlock)callback errorCallback + : (__unused RCTResponseSenderBlock)errorCallback) { - RCTLayoutAnimationGroup *layoutAnimationGroup = - [[RCTLayoutAnimationGroup alloc] initWithConfig:config - callback:callback]; + RCTLayoutAnimationGroup *layoutAnimationGroup = [[RCTLayoutAnimationGroup alloc] initWithConfig:config + callback:callback]; [self addUIBlock:^(RCTUIManager *uiManager, __unused NSDictionary *viewRegistry) { [uiManager setNextLayoutAnimationGroup:layoutAnimationGroup]; diff --git a/React/Modules/RCTUIManagerObserverCoordinator.mm b/React/Modules/RCTUIManagerObserverCoordinator.mm index e44f13ebbbe..389bedab3fb 100644 --- a/React/Modules/RCTUIManagerObserverCoordinator.mm +++ b/React/Modules/RCTUIManagerObserverCoordinator.mm @@ -97,5 +97,4 @@ } } - @end diff --git a/React/Modules/RCTUIManagerUtils.h b/React/Modules/RCTUIManagerUtils.h index b7365444e37..2bf9f57d204 100644 --- a/React/Modules/RCTUIManagerUtils.h +++ b/React/Modules/RCTUIManagerUtils.h @@ -95,8 +95,9 @@ RCT_EXTERN void RCTUnsafeExecuteOnUIManagerQueueSync(dispatch_block_t block); /** * Convenience macro for asserting that we're running on UIManager queue. */ -#define RCTAssertUIManagerQueue() RCTAssert(RCTIsUIManagerQueue() || RCTIsPseudoUIManagerQueue(), \ -@"This function must be called on the UIManager queue") +#define RCTAssertUIManagerQueue() \ + RCTAssert( \ + RCTIsUIManagerQueue() || RCTIsPseudoUIManagerQueue(), @"This function must be called on the UIManager queue") /** * Returns new unique root view tag. diff --git a/React/Modules/RCTUIManagerUtils.m b/React/Modules/RCTUIManagerUtils.m index 8f03240f6bd..54f77f67a6e 100644 --- a/React/Modules/RCTUIManagerUtils.m +++ b/React/Modules/RCTUIManagerUtils.m @@ -21,7 +21,8 @@ dispatch_queue_t RCTGetUIManagerQueue(void) static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if ([NSOperation instancesRespondToSelector:@selector(qualityOfService)]) { - dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0); + dispatch_queue_attr_t attr = + dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0); shadowQueue = dispatch_queue_create(RCTUIManagerQueueName, attr); } else { shadowQueue = dispatch_queue_create(RCTUIManagerQueueName, DISPATCH_QUEUE_SERIAL); diff --git a/React/Profiler/RCTProfile.h b/React/Profiler/RCTProfile.h index 5d601fddb04..7c6dec159c8 100644 --- a/React/Profiler/RCTProfile.h +++ b/React/Profiler/RCTProfile.h @@ -28,14 +28,12 @@ RCT_EXTERN const uint64_t RCTProfileTagAlways; @class RCTBridge; -#define RCTProfileBeginFlowEvent() \ -_Pragma("clang diagnostic push") \ -_Pragma("clang diagnostic ignored \"-Wshadow\"") \ -NSUInteger __rct_profile_flow_id = _RCTProfileBeginFlowEvent(); \ -_Pragma("clang diagnostic pop") +#define RCTProfileBeginFlowEvent() \ + _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wshadow\"") NSUInteger __rct_profile_flow_id = \ + _RCTProfileBeginFlowEvent(); \ + _Pragma("clang diagnostic pop") -#define RCTProfileEndFlowEvent() \ -_RCTProfileEndFlowEvent(__rct_profile_flow_id) +#define RCTProfileEndFlowEvent() _RCTProfileEndFlowEvent(__rct_profile_flow_id) RCT_EXTERN dispatch_queue_t RCTProfileGetQueue(void); @@ -62,66 +60,61 @@ RCT_EXTERN void RCTProfileEnd(RCTBridge *, void (^)(NSString *)); /** * Collects the initial event information for the event and returns a reference ID */ -RCT_EXTERN void _RCTProfileBeginEvent(NSThread *calleeThread, - NSTimeInterval time, - uint64_t tag, - NSString *name, - NSDictionary *args); -#define RCT_PROFILE_BEGIN_EVENT(tag, name, args) \ - do { \ - if (RCTProfileIsProfiling()) { \ - NSThread *__calleeThread = [NSThread currentThread]; \ - NSTimeInterval __time = CACurrentMediaTime(); \ +RCT_EXTERN void _RCTProfileBeginEvent( + NSThread *calleeThread, + NSTimeInterval time, + uint64_t tag, + NSString *name, + NSDictionary *args); +#define RCT_PROFILE_BEGIN_EVENT(tag, name, args) \ + do { \ + if (RCTProfileIsProfiling()) { \ + NSThread *__calleeThread = [NSThread currentThread]; \ + NSTimeInterval __time = CACurrentMediaTime(); \ _RCTProfileBeginEvent(__calleeThread, __time, tag, name, args); \ - } \ - } while(0) + } \ + } while (0) /** * The ID returned by BeginEvent should then be passed into EndEvent, with the * rest of the event information. Just at this point the event will actually be * registered */ -RCT_EXTERN void _RCTProfileEndEvent(NSThread *calleeThread, - NSString *threadName, - NSTimeInterval time, - uint64_t tag, - NSString *category); +RCT_EXTERN void _RCTProfileEndEvent( + NSThread *calleeThread, + NSString *threadName, + NSTimeInterval time, + uint64_t tag, + NSString *category); -#define RCT_PROFILE_END_EVENT(tag, category) \ - do { \ - if (RCTProfileIsProfiling()) { \ - NSThread *__calleeThread = [NSThread currentThread]; \ - NSString *__threadName = RCTCurrentThreadName(); \ - NSTimeInterval __time = CACurrentMediaTime(); \ +#define RCT_PROFILE_END_EVENT(tag, category) \ + do { \ + if (RCTProfileIsProfiling()) { \ + NSThread *__calleeThread = [NSThread currentThread]; \ + NSString *__threadName = RCTCurrentThreadName(); \ + NSTimeInterval __time = CACurrentMediaTime(); \ _RCTProfileEndEvent(__calleeThread, __threadName, __time, tag, category); \ - } \ - } while(0) + } \ + } while (0) /** * Collects the initial event information for the event and returns a reference ID */ -RCT_EXTERN NSUInteger RCTProfileBeginAsyncEvent(uint64_t tag, - NSString *name, - NSDictionary *args); +RCT_EXTERN NSUInteger +RCTProfileBeginAsyncEvent(uint64_t tag, NSString *name, NSDictionary *args); /** * The ID returned by BeginEvent should then be passed into EndEvent, with the * rest of the event information. Just at this point the event will actually be * registered */ -RCT_EXTERN void RCTProfileEndAsyncEvent(uint64_t tag, - NSString *category, - NSUInteger cookie, - NSString *name, - NSString *threadName); +RCT_EXTERN void +RCTProfileEndAsyncEvent(uint64_t tag, NSString *category, NSUInteger cookie, NSString *name, NSString *threadName); /** * An event that doesn't have a duration (i.e. Notification, VSync, etc) */ -RCT_EXTERN void RCTProfileImmediateEvent(uint64_t tag, - NSString *name, - NSTimeInterval time, - char scope); +RCT_EXTERN void RCTProfileImmediateEvent(uint64_t tag, NSString *name, NSTimeInterval time, char scope); /** * Helper to profile the duration of the execution of a block. This method uses @@ -131,12 +124,12 @@ RCT_EXTERN void RCTProfileImmediateEvent(uint64_t tag, * * DEPRECATED: this approach breaks debugging and stepping through instrumented block functions */ -#define RCTProfileBlock(block, tag, category, arguments) \ -^{ \ - RCT_PROFILE_BEGIN_EVENT(tag, @(__PRETTY_FUNCTION__), nil); \ - block(); \ - RCT_PROFILE_END_EVENT(tag, category, arguments); \ -} +#define RCTProfileBlock(block, tag, category, arguments) \ + ^{ \ + RCT_PROFILE_BEGIN_EVENT(tag, @(__PRETTY_FUNCTION__), nil); \ + block(); \ + RCT_PROFILE_END_EVENT(tag, category, arguments); \ + } /** * Hook into a bridge instance to log all bridge module's method calls diff --git a/React/Profiler/RCTProfile.m b/React/Profiler/RCTProfile.m index d201f86a184..12d42000e3c 100644 --- a/React/Profiler/RCTProfile.m +++ b/React/Profiler/RCTProfile.m @@ -54,15 +54,12 @@ static UIWindow *RCTProfileControlsWindow; #pragma mark - Macros #define RCTProfileAddEvent(type, props...) \ -[RCTProfileInfo[type] addObject:@{ \ - @"pid": @([[NSProcessInfo processInfo] processIdentifier]), \ - props \ -}]; + [RCTProfileInfo[type] addObject:@{@"pid" : @([[NSProcessInfo processInfo] processIdentifier]), props}]; -#define CHECK(...) \ -if (!RCTProfileIsProfiling()) { \ - return __VA_ARGS__; \ -} +#define CHECK(...) \ + if (!RCTProfileIsProfiling()) { \ + return __VA_ARGS__; \ + } #pragma mark - systrace glue code @@ -116,15 +113,12 @@ static NSDictionary *RCTProfileGetMemoryUsage(void) { struct task_basic_info info; mach_msg_type_number_t size = sizeof(info); - kern_return_t kerr = task_info(mach_task_self(), - TASK_BASIC_INFO, - (task_info_t)&info, - &size); - if ( kerr == KERN_SUCCESS ) { + kern_return_t kerr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size); + if (kerr == KERN_SUCCESS) { return @{ - @"suspend_count": @(info.suspend_count), - @"virtual_size": RCTProfileMemory(info.virtual_size), - @"resident_size": RCTProfileMemory(info.resident_size), + @"suspend_count" : @(info.suspend_count), + @"virtual_size" : RCTProfileMemory(info.virtual_size), + @"resident_size" : RCTProfileMemory(info.resident_size), }; } else { return @{}; @@ -182,14 +176,11 @@ IMP RCTProfileGetImplementation(id obj, SEL cmd) * The implementation can be found in RCTProfileTrampoline-.s where arch * is one of: i386, x86_64, arm, arm64. */ -#if defined(__i386__) || \ - defined(__x86_64__) || \ - defined(__arm__) || \ - defined(__arm64__) +#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__) - RCT_EXTERN void RCTProfileTrampoline(void); +RCT_EXTERN void RCTProfileTrampoline(void); #else - static void *RCTProfileTrampoline = NULL; +static void *RCTProfileTrampoline = NULL; #endif RCT_EXTERN void RCTProfileTrampolineStart(id, SEL); @@ -200,7 +191,8 @@ void RCTProfileTrampolineStart(id self, SEL cmd) * block. */ Class klass = [self class]; - RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, ([NSString stringWithFormat:@"-[%s %s]", class_getName(klass), sel_getName(cmd)]), nil); + RCT_PROFILE_BEGIN_EVENT( + RCTProfileTagAlways, ([NSString stringWithFormat:@"-[%s %s]", class_getName(klass), sel_getName(cmd)]), nil); } RCT_EXTERN void RCTProfileTrampolineEnd(void); @@ -280,7 +272,8 @@ void RCTProfileHookInstance(id instance) * Avoid hooking into NSObject methods, methods generated by React Native * and special methods that start `.` (e.g. .cxx_destruct) */ - if ([NSStringFromSelector(selector) hasPrefix:@"rct"] || [NSObject instancesRespondToSelector:selector] || sel_getName(selector)[0] == '.' || returnsStruct) { + if ([NSStringFromSelector(selector) hasPrefix:@"rct"] || [NSObject instancesRespondToSelector:selector] || + sel_getName(selector)[0] == '.' || returnsStruct) { continue; } @@ -289,11 +282,22 @@ void RCTProfileHookInstance(id instance) } free(methods); - class_replaceMethod(object_getClass(proxyClass), @selector(initialize), imp_implementationWithBlock(^{}), "v@:"); + class_replaceMethod( + object_getClass(proxyClass), + @selector(initialize), + imp_implementationWithBlock(^{ + }), + "v@:"); - for (Class cls in @[proxyClass, object_getClass(proxyClass)]) { + for (Class cls in @[ proxyClass, object_getClass(proxyClass) ]) { Method oldImp = class_getInstanceMethod(cls, @selector(class)); - class_replaceMethod(cls, @selector(class), imp_implementationWithBlock(^{ return moduleClass; }), method_getTypeEncoding(oldImp)); + class_replaceMethod( + cls, + @selector(class), + imp_implementationWithBlock(^{ + return moduleClass; + }), + method_getTypeEncoding(oldImp)); } objc_registerClassPair(proxyClass); @@ -319,9 +323,11 @@ void RCTProfileHookModules(RCTBridge *bridge) for (RCTModuleData *moduleData in [bridge valueForKey:@"moduleDataByID"]) { // Only hook modules with an instance, to prevent initializing everything if ([moduleData hasInstance]) { - [bridge dispatchBlock:^{ - RCTProfileHookInstance(moduleData.instance); - } queue:moduleData.methodQueue]; + [bridge + dispatchBlock:^{ + RCTProfileHookInstance(moduleData.instance); + } + queue:moduleData.methodQueue]; } } RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @""); @@ -380,30 +386,28 @@ void RCTProfileUnhookModules(RCTBridge *bridge) BOOL isProfiling = RCTProfileIsProfiling(); // Start and Stop are switched here, since we're going to toggle isProfiling - [target setTitle:isProfiling ? @"Start" : @"Stop" - forState:UIControlStateNormal]; + [target setTitle:isProfiling ? @"Start" : @"Stop" forState:UIControlStateNormal]; if (isProfiling) { RCTProfileEnd(RCTProfilingBridge(), ^(NSString *result) { NSString *outFile = [NSTemporaryDirectory() stringByAppendingString:@"tmp_trace.json"]; - [result writeToFile:outFile - atomically:YES - encoding:NSUTF8StringEncoding - error:nil]; + [result writeToFile:outFile atomically:YES encoding:NSUTF8StringEncoding error:nil]; #if !TARGET_OS_TV - UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[[NSURL fileURLWithPath:outFile]] - applicationActivities:nil]; - activityViewController.completionWithItemsHandler = ^(__unused UIActivityType activityType, - __unused BOOL completed, - __unused NSArray *items, - __unused NSError *error) { - RCTProfileControlsWindow.hidden = NO; - }; + UIActivityViewController *activityViewController = + [[UIActivityViewController alloc] initWithActivityItems:@[ [NSURL fileURLWithPath:outFile] ] + applicationActivities:nil]; + activityViewController.completionWithItemsHandler = + ^(__unused UIActivityType activityType, + __unused BOOL completed, + __unused NSArray *items, + __unused NSError *error) { + RCTProfileControlsWindow.hidden = NO; + }; RCTProfileControlsWindow.hidden = YES; dispatch_async(dispatch_get_main_queue(), ^{ [[[[RCTSharedApplication() delegate] window] rootViewController] presentViewController:activityViewController - animated:YES - completion:nil]; + animated:YES + completion:nil]; }); #endif }); @@ -415,12 +419,9 @@ void RCTProfileUnhookModules(RCTBridge *bridge) + (void)drag:(UIPanGestureRecognizer *)gestureRecognizer { CGPoint translation = [gestureRecognizer translationInView:RCTProfileControlsWindow]; - RCTProfileControlsWindow.center = CGPointMake( - RCTProfileControlsWindow.center.x + translation.x, - RCTProfileControlsWindow.center.y + translation.y - ); - [gestureRecognizer setTranslation:CGPointMake(0, 0) - inView:RCTProfileControlsWindow]; + RCTProfileControlsWindow.center = + CGPointMake(RCTProfileControlsWindow.center.x + translation.x, RCTProfileControlsWindow.center.y + translation.y); + [gestureRecognizer setTranslation:CGPointMake(0, 0) inView:RCTProfileControlsWindow]; } @end @@ -458,35 +459,34 @@ void RCTProfileInit(RCTBridge *bridge) RCTProfileStartTime = time; RCTProfileOngoingEvents = [NSMutableDictionary new]; RCTProfileInfo = @{ - kProfileTraceEvents: [NSMutableArray new], - kProfileSamples: [NSMutableArray new], + kProfileTraceEvents : [NSMutableArray new], + kProfileSamples : [NSMutableArray new], }; }); } // Set up thread ordering dispatch_async(RCTProfileGetQueue(), ^{ - NSArray *orderedThreads = @[@"JS async", @"RCTPerformanceLogger", @"com.facebook.react.JavaScript", - @(RCTUIManagerQueueName), @"main"]; + NSArray *orderedThreads = + @[ @"JS async", @"RCTPerformanceLogger", @"com.facebook.react.JavaScript", @(RCTUIManagerQueueName), @"main" ]; [orderedThreads enumerateObjectsUsingBlock:^(NSString *thread, NSUInteger idx, __unused BOOL *stop) { RCTProfileAddEvent(kProfileTraceEvents, - @"ph": @"M", // metadata event - @"name": @"thread_sort_index", - @"tid": thread, - @"args": @{ @"sort_index": @(-1000 + (NSInteger)idx) } - ); + @"ph" + : @"M", // metadata event + @"name" + : @"thread_sort_index", @"tid" + : thread, @"args" + : + @{@"sort_index" : @(-1000 + (NSInteger)idx)}); }]; }); RCTProfileHookModules(bridge); - RCTProfileDisplayLink = [CADisplayLink displayLinkWithTarget:[RCTProfile class] - selector:@selector(vsync:)]; - [RCTProfileDisplayLink addToRunLoop:[NSRunLoop mainRunLoop] - forMode:NSRunLoopCommonModes]; + RCTProfileDisplayLink = [CADisplayLink displayLinkWithTarget:[RCTProfile class] selector:@selector(vsync:)]; + [RCTProfileDisplayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; - [[NSNotificationCenter defaultCenter] postNotificationName:RCTProfileDidStartProfiling - object:bridge]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTProfileDidStartProfiling object:bridge]; } void RCTProfileEnd(RCTBridge *bridge, void (^callback)(NSString *)) @@ -497,8 +497,7 @@ void RCTProfileEnd(RCTBridge *bridge, void (^callback)(NSString *)) return; } - [[NSNotificationCenter defaultCenter] postNotificationName:RCTProfileDidEndProfiling - object:bridge]; + [[NSNotificationCenter defaultCenter] postNotificationName:RCTProfileDidEndProfiling object:bridge]; [RCTProfileDisplayLink invalidate]; RCTProfileDisplayLink = nil; @@ -525,8 +524,7 @@ void RCTProfileEnd(RCTBridge *bridge, void (^callback)(NSString *)) static NSMutableArray *RCTProfileGetThreadEvents(NSThread *thread) { static NSString *const RCTProfileThreadEventsKey = @"RCTProfileThreadEventsKey"; - NSMutableArray *threadEvents = - thread.threadDictionary[RCTProfileThreadEventsKey]; + NSMutableArray *threadEvents = thread.threadDictionary[RCTProfileThreadEventsKey]; if (!threadEvents) { threadEvents = [NSMutableArray new]; thread.threadDictionary[RCTProfileThreadEventsKey] = threadEvents; @@ -535,12 +533,12 @@ static NSMutableArray *RCTProfileGetThreadEvents(NSThread *thread) } void _RCTProfileBeginEvent( - NSThread *calleeThread, - NSTimeInterval time, - uint64_t tag, - NSString *name, - NSDictionary *args -) { + NSThread *calleeThread, + NSTimeInterval time, + uint64_t tag, + NSString *name, + NSDictionary *args) +{ CHECK(); if (callbacks != NULL) { @@ -561,12 +559,12 @@ void _RCTProfileBeginEvent( } void _RCTProfileEndEvent( - NSThread *calleeThread, - NSString *threadName, - NSTimeInterval time, - uint64_t tag, - NSString *category -) { + NSThread *calleeThread, + NSString *threadName, + NSTimeInterval time, + uint64_t tag, + NSString *category) +{ CHECK(); if (callbacks != NULL) { @@ -584,23 +582,19 @@ void _RCTProfileEndEvent( } NSNumber *start = event[0]; - RCTProfileAddEvent(kProfileTraceEvents, - @"tid": threadName, - @"name": event[1], - @"cat": category, - @"ph": @"X", - @"ts": start, - @"dur": @(RCTProfileTimestamp(time).doubleValue - start.doubleValue), - @"args": event[2], - ); + RCTProfileAddEvent(kProfileTraceEvents, @"tid" + : threadName, @"name" + : event[1], @"cat" + : category, @"ph" + : @"X", @"ts" + : start, @"dur" + : @(RCTProfileTimestamp(time).doubleValue - start.doubleValue), @"args" + : event[2], ); }); } -NSUInteger RCTProfileBeginAsyncEvent( - uint64_t tag, - NSString *name, - NSDictionary *args -) { +NSUInteger RCTProfileBeginAsyncEvent(uint64_t tag, NSString *name, NSDictionary *args) +{ CHECK(0); static NSUInteger eventID = 0; @@ -625,13 +619,8 @@ NSUInteger RCTProfileBeginAsyncEvent( return currentEventID; } -void RCTProfileEndAsyncEvent( - uint64_t tag, - NSString *category, - NSUInteger cookie, - NSString *name, - NSString *threadName -) { +void RCTProfileEndAsyncEvent(uint64_t tag, NSString *category, NSUInteger cookie, NSString *name, NSString *threadName) +{ CHECK(); if (callbacks != NULL) { @@ -647,26 +636,21 @@ void RCTProfileEndAsyncEvent( if (event) { NSNumber *endTimestamp = RCTProfileTimestamp(time); - RCTProfileAddEvent(kProfileTraceEvents, - @"tid": threadName, - @"name": event[1], - @"cat": category, - @"ph": @"X", - @"ts": event[0], - @"dur": @(endTimestamp.doubleValue - [event[0] doubleValue]), - @"args": event[2], - ); + RCTProfileAddEvent(kProfileTraceEvents, @"tid" + : threadName, @"name" + : event[1], @"cat" + : category, @"ph" + : @"X", @"ts" + : event[0], @"dur" + : @(endTimestamp.doubleValue - [event[0] doubleValue]), @"args" + : event[2], ); [RCTProfileOngoingEvents removeObjectForKey:@(cookie)]; } }); } -void RCTProfileImmediateEvent( - uint64_t tag, - NSString *name, - NSTimeInterval time, - char scope -) { +void RCTProfileImmediateEvent(uint64_t tag, NSString *name, NSTimeInterval time, char scope) +{ CHECK(); if (callbacks != NULL) { @@ -677,14 +661,13 @@ void RCTProfileImmediateEvent( NSString *threadName = RCTCurrentThreadName(); dispatch_async(RCTProfileGetQueue(), ^{ - RCTProfileAddEvent(kProfileTraceEvents, - @"tid": threadName, - @"name": name, - @"ts": RCTProfileTimestamp(time), - @"scope": @(scope), - @"ph": @"i", - @"args": RCTProfileGetMemoryUsage(), - ); + RCTProfileAddEvent(kProfileTraceEvents, @"tid" + : threadName, @"name" + : name, @"ts" + : RCTProfileTimestamp(time), @"scope" + : @(scope), @"ph" + : @"i", @"args" + : RCTProfileGetMemoryUsage(), ); }); } @@ -704,15 +687,13 @@ NSUInteger _RCTProfileBeginFlowEvent(void) NSString *threadName = RCTCurrentThreadName(); dispatch_async(RCTProfileGetQueue(), ^{ - RCTProfileAddEvent(kProfileTraceEvents, - @"tid": threadName, - @"name": @"flow", - @"id": @(cookie), - @"cat": @"flow", - @"ph": @"s", - @"ts": RCTProfileTimestamp(time), - ); - + RCTProfileAddEvent(kProfileTraceEvents, @"tid" + : threadName, @"name" + : @"flow", @"id" + : @(cookie), @"cat" + : @"flow", @"ph" + : @"s", @"ts" + : RCTProfileTimestamp(time), ); }); return cookie; @@ -731,21 +712,21 @@ void _RCTProfileEndFlowEvent(NSUInteger cookie) NSString *threadName = RCTCurrentThreadName(); dispatch_async(RCTProfileGetQueue(), ^{ - RCTProfileAddEvent(kProfileTraceEvents, - @"tid": threadName, - @"name": @"flow", - @"id": @(cookie), - @"cat": @"flow", - @"ph": @"f", - @"ts": RCTProfileTimestamp(time), - ); + RCTProfileAddEvent(kProfileTraceEvents, @"tid" + : threadName, @"name" + : @"flow", @"id" + : @(cookie), @"cat" + : @"flow", @"ph" + : @"f", @"ts" + : RCTProfileTimestamp(time), ); }); } void RCTProfileSendResult(RCTBridge *bridge, NSString *route, NSData *data) { if (![bridge.bundleURL.scheme hasPrefix:@"http"]) { - RCTLogWarn(@"Cannot upload profile information because you're not connected to the packager. The profiling data is still saved in the app container."); + RCTLogWarn( + @"Cannot upload profile information because you're not connected to the packager. The profiling data is still saved in the app container."); return; } @@ -753,36 +734,33 @@ void RCTProfileSendResult(RCTBridge *bridge, NSString *route, NSData *data) NSMutableURLRequest *URLRequest = [NSMutableURLRequest requestWithURL:URL]; URLRequest.HTTPMethod = @"POST"; - [URLRequest setValue:@"application/json" - forHTTPHeaderField:@"Content-Type"]; + [URLRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - NSURLSessionTask *task = - [[NSURLSession sharedSession] uploadTaskWithRequest:URLRequest - fromData:data - completionHandler: - ^(NSData *responseData, __unused NSURLResponse *response, NSError *error) { - if (error) { - RCTLogError(@"%@", error.localizedDescription); - } else { - NSString *message = [[NSString alloc] initWithData:responseData - encoding:NSUTF8StringEncoding]; + NSURLSessionTask *task = [[NSURLSession sharedSession] + uploadTaskWithRequest:URLRequest + fromData:data + completionHandler:^(NSData *responseData, __unused NSURLResponse *response, NSError *error) { + if (error) { + RCTLogError(@"%@", error.localizedDescription); + } else { + NSString *message = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; - if (message.length) { + if (message.length) { #if !TARGET_OS_TV - dispatch_async(dispatch_get_main_queue(), ^{ - UIAlertController *alertController = [UIAlertController - alertControllerWithTitle:@"Profile" - message:message - preferredStyle:UIAlertControllerStyleAlert]; - [alertController addAction:[UIAlertAction actionWithTitle:@"OK" - style:UIAlertActionStyleCancel - handler:nil]]; - [RCTPresentedViewController() presentViewController:alertController animated:YES completion:nil]; - }); + dispatch_async(dispatch_get_main_queue(), ^{ + UIAlertController *alertController = + [UIAlertController alertControllerWithTitle:@"Profile" + message:message + preferredStyle:UIAlertControllerStyleAlert]; + [alertController addAction:[UIAlertAction actionWithTitle:@"OK" + style:UIAlertActionStyleCancel + handler:nil]]; + [RCTPresentedViewController() presentViewController:alertController animated:YES completion:nil]; + }); #endif - } - } - }]; + } + } + }]; [task resume]; } @@ -801,8 +779,7 @@ void RCTProfileShowControls(void) window.alpha = 0.8; UIButton *startOrStop = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, height)]; - [startOrStop setTitle:RCTProfileIsProfiling() ? @"Stop" : @"Start" - forState:UIControlStateNormal]; + [startOrStop setTitle:RCTProfileIsProfiling() ? @"Stop" : @"Start" forState:UIControlStateNormal]; [startOrStop addTarget:[RCTProfile class] action:@selector(toggle:) forControlEvents:UIControlEventTouchUpInside]; startOrStop.titleLabel.font = [UIFont systemFontOfSize:12]; diff --git a/React/UIUtils/RCTUIUtils.h b/React/UIUtils/RCTUIUtils.h index 8cecac3b89d..14fadee007a 100644 --- a/React/UIUtils/RCTUIUtils.h +++ b/React/UIUtils/RCTUIUtils.h @@ -21,12 +21,11 @@ typedef struct { CGFloat width, height, scale, fontScale; } window, screen; } RCTDimensions; -extern __attribute__((visibility("default"))) -RCTDimensions RCTGetDimensions(CGFloat fontScale); +extern __attribute__((visibility("default"))) RCTDimensions RCTGetDimensions(CGFloat fontScale); // Get font size multiplier for font base size (Large) by content size category -extern __attribute__((visibility("default"))) -CGFloat RCTGetMultiplierForContentSizeCategory(UIContentSizeCategory category); +extern __attribute__((visibility("default"))) CGFloat RCTGetMultiplierForContentSizeCategory( + UIContentSizeCategory category); #ifdef __cplusplus } diff --git a/React/UIUtils/RCTUIUtils.m b/React/UIUtils/RCTUIUtils.m index 64b97bffa4c..2d3243c5783 100644 --- a/React/UIUtils/RCTUIUtils.m +++ b/React/UIUtils/RCTUIUtils.m @@ -19,18 +19,10 @@ RCTDimensions RCTGetDimensions(CGFloat fontScale) CGSize windowSize = mainWindow.bounds.size; RCTDimensions result; - typeof (result.screen) dimsScreen = { - .width = screenSize.width, - .height = screenSize.height, - .scale = mainScreen.scale, - .fontScale = fontScale - }; - typeof (result.window) dimsWindow = { - .width = windowSize.width, - .height = windowSize.height, - .scale = mainScreen.scale, - .fontScale = fontScale - }; + typeof(result.screen) dimsScreen = { + .width = screenSize.width, .height = screenSize.height, .scale = mainScreen.scale, .fontScale = fontScale}; + typeof(result.window) dimsWindow = { + .width = windowSize.width, .height = windowSize.height, .scale = mainScreen.scale, .fontScale = fontScale}; result.screen = dimsScreen; result.window = dimsWindow; @@ -43,18 +35,18 @@ CGFloat RCTGetMultiplierForContentSizeCategory(UIContentSizeCategory category) static dispatch_once_t token; dispatch_once(&token, ^{ multipliers = @{ - UIContentSizeCategoryExtraSmall: @0.823, - UIContentSizeCategorySmall: @0.882, - UIContentSizeCategoryMedium: @0.941, - UIContentSizeCategoryLarge: @1.0, - UIContentSizeCategoryExtraLarge: @1.118, - UIContentSizeCategoryExtraExtraLarge: @1.235, - UIContentSizeCategoryExtraExtraExtraLarge: @1.353, - UIContentSizeCategoryAccessibilityMedium: @1.786, - UIContentSizeCategoryAccessibilityLarge: @2.143, - UIContentSizeCategoryAccessibilityExtraLarge: @2.643, - UIContentSizeCategoryAccessibilityExtraExtraLarge: @3.143, - UIContentSizeCategoryAccessibilityExtraExtraExtraLarge: @3.571 + UIContentSizeCategoryExtraSmall : @0.823, + UIContentSizeCategorySmall : @0.882, + UIContentSizeCategoryMedium : @0.941, + UIContentSizeCategoryLarge : @1.0, + UIContentSizeCategoryExtraLarge : @1.118, + UIContentSizeCategoryExtraExtraLarge : @1.235, + UIContentSizeCategoryExtraExtraExtraLarge : @1.353, + UIContentSizeCategoryAccessibilityMedium : @1.786, + UIContentSizeCategoryAccessibilityLarge : @2.143, + UIContentSizeCategoryAccessibilityExtraLarge : @2.643, + UIContentSizeCategoryAccessibilityExtraExtraLarge : @3.143, + UIContentSizeCategoryAccessibilityExtraExtraExtraLarge : @3.571 }; }); diff --git a/React/Views/RCTActivityIndicatorView.m b/React/Views/RCTActivityIndicatorView.m index 0a5d2806a2e..0a90bb0a5ea 100644 --- a/React/Views/RCTActivityIndicatorView.m +++ b/React/Views/RCTActivityIndicatorView.m @@ -13,9 +13,9 @@ - (void)setHidden:(BOOL)hidden { if ([self hidesWhenStopped] && ![self isAnimating]) { - [super setHidden: YES]; + [super setHidden:YES]; } else { - [super setHidden: hidden]; + [super setHidden:hidden]; } } diff --git a/React/Views/RCTActivityIndicatorViewManager.m b/React/Views/RCTActivityIndicatorViewManager.m index 4b0404c63ab..13f8b910310 100644 --- a/React/Views/RCTActivityIndicatorViewManager.m +++ b/React/Views/RCTActivityIndicatorViewManager.m @@ -15,10 +15,14 @@ // NOTE: It's pointless to support UIActivityIndicatorViewStyleGray // as we can set the color to any arbitrary value that we want to -RCT_ENUM_CONVERTER(UIActivityIndicatorViewStyle, (@{ - @"large": @(UIActivityIndicatorViewStyleWhiteLarge), - @"small": @(UIActivityIndicatorViewStyleWhite), -}), UIActivityIndicatorViewStyleWhiteLarge, integerValue) +RCT_ENUM_CONVERTER( + UIActivityIndicatorViewStyle, + (@{ + @"large" : @(UIActivityIndicatorViewStyleWhiteLarge), + @"small" : @(UIActivityIndicatorViewStyleWhite), + }), + UIActivityIndicatorViewStyleWhiteLarge, + integerValue) @end @@ -40,7 +44,8 @@ RCT_CUSTOM_VIEW_PROPERTY(size, UIActivityIndicatorViewStyle, UIActivityIndicator after setting the indicator style. */ UIColor *oldColor = view.color; - view.activityIndicatorViewStyle = json ? [RCTConvert UIActivityIndicatorViewStyle: json] : defaultView.activityIndicatorViewStyle; + view.activityIndicatorViewStyle = + json ? [RCTConvert UIActivityIndicatorViewStyle:json] : defaultView.activityIndicatorViewStyle; view.color = oldColor; } diff --git a/React/Views/RCTBorderDrawing.h b/React/Views/RCTBorderDrawing.h index b97bc0cff66..884aa79f4e8 100644 --- a/React/Views/RCTBorderDrawing.h +++ b/React/Views/RCTBorderDrawing.h @@ -42,16 +42,14 @@ RCT_EXTERN BOOL RCTBorderColorsAreEqual(RCTBorderColors borderColors); * Convert RCTCornerRadii to RCTCornerInsets by applying border insets. * Effectively, returns radius - inset, with a lower bound of 0.0. */ -RCT_EXTERN RCTCornerInsets RCTGetCornerInsets(RCTCornerRadii cornerRadii, - UIEdgeInsets borderInsets); +RCT_EXTERN RCTCornerInsets RCTGetCornerInsets(RCTCornerRadii cornerRadii, UIEdgeInsets borderInsets); /** * Create a CGPath representing a rounded rectangle with the specified bounds * and corner insets. Note that the CGPathRef must be released by the caller. */ -RCT_EXTERN CGPathRef RCTPathCreateWithRoundedRect(CGRect bounds, - RCTCornerInsets cornerInsets, - const CGAffineTransform *transform); +RCT_EXTERN CGPathRef +RCTPathCreateWithRoundedRect(CGRect bounds, RCTCornerInsets cornerInsets, const CGAffineTransform *transform); /** * Draw a CSS-compliant border as an image. You can determine if it's scalable @@ -59,10 +57,11 @@ RCT_EXTERN CGPathRef RCTPathCreateWithRoundedRect(CGRect bounds, * * `borderInsets` defines the border widths for each edge. */ -RCT_EXTERN UIImage *RCTGetBorderImage(RCTBorderStyle borderStyle, - CGSize viewSize, - RCTCornerRadii cornerRadii, - UIEdgeInsets borderInsets, - RCTBorderColors borderColors, - CGColorRef backgroundColor, - BOOL drawToEdge); +RCT_EXTERN UIImage *RCTGetBorderImage( + RCTBorderStyle borderStyle, + CGSize viewSize, + RCTCornerRadii cornerRadii, + UIEdgeInsets borderInsets, + RCTBorderColors borderColors, + CGColorRef backgroundColor, + BOOL drawToEdge); diff --git a/React/Views/RCTBorderDrawing.m b/React/Views/RCTBorderDrawing.m index 1a296935bb4..8d84b86c6da 100644 --- a/React/Views/RCTBorderDrawing.m +++ b/React/Views/RCTBorderDrawing.m @@ -12,67 +12,63 @@ static const CGFloat RCTViewBorderThreshold = 0.001; BOOL RCTBorderInsetsAreEqual(UIEdgeInsets borderInsets) { - return - ABS(borderInsets.left - borderInsets.right) < RCTViewBorderThreshold && - ABS(borderInsets.left - borderInsets.bottom) < RCTViewBorderThreshold && - ABS(borderInsets.left - borderInsets.top) < RCTViewBorderThreshold; + return ABS(borderInsets.left - borderInsets.right) < RCTViewBorderThreshold && + ABS(borderInsets.left - borderInsets.bottom) < RCTViewBorderThreshold && + ABS(borderInsets.left - borderInsets.top) < RCTViewBorderThreshold; } BOOL RCTCornerRadiiAreEqual(RCTCornerRadii cornerRadii) { - return - ABS(cornerRadii.topLeft - cornerRadii.topRight) < RCTViewBorderThreshold && - ABS(cornerRadii.topLeft - cornerRadii.bottomLeft) < RCTViewBorderThreshold && - ABS(cornerRadii.topLeft - cornerRadii.bottomRight) < RCTViewBorderThreshold; + return ABS(cornerRadii.topLeft - cornerRadii.topRight) < RCTViewBorderThreshold && + ABS(cornerRadii.topLeft - cornerRadii.bottomLeft) < RCTViewBorderThreshold && + ABS(cornerRadii.topLeft - cornerRadii.bottomRight) < RCTViewBorderThreshold; } BOOL RCTBorderColorsAreEqual(RCTBorderColors borderColors) { - return - CGColorEqualToColor(borderColors.left, borderColors.right) && - CGColorEqualToColor(borderColors.left, borderColors.top) && - CGColorEqualToColor(borderColors.left, borderColors.bottom); + return CGColorEqualToColor(borderColors.left, borderColors.right) && + CGColorEqualToColor(borderColors.left, borderColors.top) && + CGColorEqualToColor(borderColors.left, borderColors.bottom); } -RCTCornerInsets RCTGetCornerInsets(RCTCornerRadii cornerRadii, - UIEdgeInsets edgeInsets) +RCTCornerInsets RCTGetCornerInsets(RCTCornerRadii cornerRadii, UIEdgeInsets edgeInsets) { - return (RCTCornerInsets) { - { - MAX(0, cornerRadii.topLeft - edgeInsets.left), - MAX(0, cornerRadii.topLeft - edgeInsets.top), - }, - { - MAX(0, cornerRadii.topRight - edgeInsets.right), - MAX(0, cornerRadii.topRight - edgeInsets.top), - }, - { - MAX(0, cornerRadii.bottomLeft - edgeInsets.left), - MAX(0, cornerRadii.bottomLeft - edgeInsets.bottom), - }, - { - MAX(0, cornerRadii.bottomRight - edgeInsets.right), - MAX(0, cornerRadii.bottomRight - edgeInsets.bottom), - } - }; + return (RCTCornerInsets){{ + MAX(0, cornerRadii.topLeft - edgeInsets.left), + MAX(0, cornerRadii.topLeft - edgeInsets.top), + }, + { + MAX(0, cornerRadii.topRight - edgeInsets.right), + MAX(0, cornerRadii.topRight - edgeInsets.top), + }, + { + MAX(0, cornerRadii.bottomLeft - edgeInsets.left), + MAX(0, cornerRadii.bottomLeft - edgeInsets.bottom), + }, + { + MAX(0, cornerRadii.bottomRight - edgeInsets.right), + MAX(0, cornerRadii.bottomRight - edgeInsets.bottom), + }}; } -static UIEdgeInsets RCTRoundInsetsToPixel(UIEdgeInsets edgeInsets) { - edgeInsets.top = RCTRoundPixelValue(edgeInsets.top); - edgeInsets.bottom = RCTRoundPixelValue(edgeInsets.bottom); - edgeInsets.left = RCTRoundPixelValue(edgeInsets.left); - edgeInsets.right = RCTRoundPixelValue(edgeInsets.right); +static UIEdgeInsets RCTRoundInsetsToPixel(UIEdgeInsets edgeInsets) +{ + edgeInsets.top = RCTRoundPixelValue(edgeInsets.top); + edgeInsets.bottom = RCTRoundPixelValue(edgeInsets.bottom); + edgeInsets.left = RCTRoundPixelValue(edgeInsets.left); + edgeInsets.right = RCTRoundPixelValue(edgeInsets.right); - return edgeInsets; + return edgeInsets; } -static void RCTPathAddEllipticArc(CGMutablePathRef path, - const CGAffineTransform *m, - CGPoint origin, - CGSize size, - CGFloat startAngle, - CGFloat endAngle, - BOOL clockwise) +static void RCTPathAddEllipticArc( + CGMutablePathRef path, + const CGAffineTransform *m, + CGPoint origin, + CGSize size, + CGFloat startAngle, + CGFloat endAngle, + BOOL clockwise) { CGFloat xScale = 1, yScale = 1, radius = 0; if (size.width != 0) { @@ -94,9 +90,7 @@ static void RCTPathAddEllipticArc(CGMutablePathRef path, CGPathAddArc(path, &t, 0, 0, radius, startAngle, endAngle, clockwise); } -CGPathRef RCTPathCreateWithRoundedRect(CGRect bounds, - RCTCornerInsets cornerInsets, - const CGAffineTransform *transform) +CGPathRef RCTPathCreateWithRoundedRect(CGRect bounds, RCTCornerInsets cornerInsets, const CGAffineTransform *transform) { const CGFloat minX = CGRectGetMinX(bounds); const CGFloat minY = CGRectGetMinY(bounds); @@ -104,48 +98,39 @@ CGPathRef RCTPathCreateWithRoundedRect(CGRect bounds, const CGFloat maxY = CGRectGetMaxY(bounds); const CGSize topLeft = { - MAX(0, MIN(cornerInsets.topLeft.width, bounds.size.width - cornerInsets.topRight.width)), - MAX(0, MIN(cornerInsets.topLeft.height, bounds.size.height - cornerInsets.bottomLeft.height)), + MAX(0, MIN(cornerInsets.topLeft.width, bounds.size.width - cornerInsets.topRight.width)), + MAX(0, MIN(cornerInsets.topLeft.height, bounds.size.height - cornerInsets.bottomLeft.height)), }; const CGSize topRight = { - MAX(0, MIN(cornerInsets.topRight.width, bounds.size.width - cornerInsets.topLeft.width)), - MAX(0, MIN(cornerInsets.topRight.height, bounds.size.height - cornerInsets.bottomRight.height)), + MAX(0, MIN(cornerInsets.topRight.width, bounds.size.width - cornerInsets.topLeft.width)), + MAX(0, MIN(cornerInsets.topRight.height, bounds.size.height - cornerInsets.bottomRight.height)), }; const CGSize bottomLeft = { - MAX(0, MIN(cornerInsets.bottomLeft.width, bounds.size.width - cornerInsets.bottomRight.width)), - MAX(0, MIN(cornerInsets.bottomLeft.height, bounds.size.height - cornerInsets.topLeft.height)), + MAX(0, MIN(cornerInsets.bottomLeft.width, bounds.size.width - cornerInsets.bottomRight.width)), + MAX(0, MIN(cornerInsets.bottomLeft.height, bounds.size.height - cornerInsets.topLeft.height)), }; const CGSize bottomRight = { - MAX(0, MIN(cornerInsets.bottomRight.width, bounds.size.width - cornerInsets.bottomLeft.width)), - MAX(0, MIN(cornerInsets.bottomRight.height, bounds.size.height - cornerInsets.topRight.height)), + MAX(0, MIN(cornerInsets.bottomRight.width, bounds.size.width - cornerInsets.bottomLeft.width)), + MAX(0, MIN(cornerInsets.bottomRight.height, bounds.size.height - cornerInsets.topRight.height)), }; CGMutablePathRef path = CGPathCreateMutable(); - RCTPathAddEllipticArc(path, transform, (CGPoint){ - minX + topLeft.width, minY + topLeft.height - }, topLeft, M_PI, 3 * M_PI_2, NO); - RCTPathAddEllipticArc(path, transform, (CGPoint){ - maxX - topRight.width, minY + topRight.height - }, topRight, 3 * M_PI_2, 0, NO); - RCTPathAddEllipticArc(path, transform, (CGPoint){ - maxX - bottomRight.width, maxY - bottomRight.height - }, bottomRight, 0, M_PI_2, NO); - RCTPathAddEllipticArc(path, transform, (CGPoint){ - minX + bottomLeft.width, maxY - bottomLeft.height - }, bottomLeft, M_PI_2, M_PI, NO); + RCTPathAddEllipticArc( + path, transform, (CGPoint){minX + topLeft.width, minY + topLeft.height}, topLeft, M_PI, 3 * M_PI_2, NO); + RCTPathAddEllipticArc( + path, transform, (CGPoint){maxX - topRight.width, minY + topRight.height}, topRight, 3 * M_PI_2, 0, NO); + RCTPathAddEllipticArc( + path, transform, (CGPoint){maxX - bottomRight.width, maxY - bottomRight.height}, bottomRight, 0, M_PI_2, NO); + RCTPathAddEllipticArc( + path, transform, (CGPoint){minX + bottomLeft.width, maxY - bottomLeft.height}, bottomLeft, M_PI_2, M_PI, NO); CGPathCloseSubpath(path); return path; } -static void RCTEllipseGetIntersectionsWithLine(CGRect ellipseBounds, - CGPoint lineStart, - CGPoint lineEnd, - CGPoint intersections[2]) +static void +RCTEllipseGetIntersectionsWithLine(CGRect ellipseBounds, CGPoint lineStart, CGPoint lineEnd, CGPoint intersections[2]) { - const CGPoint ellipseCenter = { - CGRectGetMidX(ellipseBounds), - CGRectGetMidY(ellipseBounds) - }; + const CGPoint ellipseCenter = {CGRectGetMidX(ellipseBounds), CGRectGetMidY(ellipseBounds)}; lineStart.x -= ellipseCenter.x; lineStart.y -= ellipseCenter.y; @@ -170,14 +155,15 @@ static void RCTEllipseGetIntersectionsWithLine(CGRect ellipseBounds, intersections[1] = (CGPoint){x2 + ellipseCenter.x, y2 + ellipseCenter.y}; } -NS_INLINE BOOL RCTCornerRadiiAreAboveThreshold(RCTCornerRadii cornerRadii) { - return (cornerRadii.topLeft > RCTViewBorderThreshold || - cornerRadii.topRight > RCTViewBorderThreshold || - cornerRadii.bottomLeft > RCTViewBorderThreshold || - cornerRadii.bottomRight > RCTViewBorderThreshold); +NS_INLINE BOOL RCTCornerRadiiAreAboveThreshold(RCTCornerRadii cornerRadii) +{ + return ( + cornerRadii.topLeft > RCTViewBorderThreshold || cornerRadii.topRight > RCTViewBorderThreshold || + cornerRadii.bottomLeft > RCTViewBorderThreshold || cornerRadii.bottomRight > RCTViewBorderThreshold); } -static CGPathRef RCTPathCreateOuterOutline(BOOL drawToEdge, CGRect rect, RCTCornerRadii cornerRadii) { +static CGPathRef RCTPathCreateOuterOutline(BOOL drawToEdge, CGRect rect, RCTCornerRadii cornerRadii) +{ if (drawToEdge) { return CGPathCreateWithRect(rect, NULL); } @@ -185,19 +171,22 @@ static CGPathRef RCTPathCreateOuterOutline(BOOL drawToEdge, CGRect rect, RCTCorn return RCTPathCreateWithRoundedRect(rect, RCTGetCornerInsets(cornerRadii, UIEdgeInsetsZero), NULL); } -static CGContextRef RCTUIGraphicsBeginImageContext(CGSize size, CGColorRef backgroundColor, BOOL hasCornerRadii, BOOL drawToEdge) { +static CGContextRef +RCTUIGraphicsBeginImageContext(CGSize size, CGColorRef backgroundColor, BOOL hasCornerRadii, BOOL drawToEdge) +{ const CGFloat alpha = CGColorGetAlpha(backgroundColor); const BOOL opaque = (drawToEdge || !hasCornerRadii) && alpha == 1.0; UIGraphicsBeginImageContextWithOptions(size, opaque, 0.0); return UIGraphicsGetCurrentContext(); } -static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, - CGSize viewSize, - UIEdgeInsets borderInsets, - RCTBorderColors borderColors, - CGColorRef backgroundColor, - BOOL drawToEdge) +static UIImage *RCTGetSolidBorderImage( + RCTCornerRadii cornerRadii, + CGSize viewSize, + UIEdgeInsets borderInsets, + RCTBorderColors borderColors, + CGColorRef backgroundColor, + BOOL drawToEdge) { const BOOL hasCornerRadii = RCTCornerRadiiAreAboveThreshold(cornerRadii); const RCTCornerInsets cornerInsets = RCTGetCornerInsets(cornerRadii, borderInsets); @@ -208,29 +197,28 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, borderInsets = RCTRoundInsetsToPixel(borderInsets); const BOOL makeStretchable = - (borderInsets.left + cornerInsets.topLeft.width + - borderInsets.right + cornerInsets.bottomRight.width <= viewSize.width) && - (borderInsets.left + cornerInsets.bottomLeft.width + - borderInsets.right + cornerInsets.topRight.width <= viewSize.width) && - (borderInsets.top + cornerInsets.topLeft.height + - borderInsets.bottom + cornerInsets.bottomRight.height <= viewSize.height) && - (borderInsets.top + cornerInsets.topRight.height + - borderInsets.bottom + cornerInsets.bottomLeft.height <= viewSize.height); + (borderInsets.left + cornerInsets.topLeft.width + borderInsets.right + cornerInsets.bottomRight.width <= + viewSize.width) && + (borderInsets.left + cornerInsets.bottomLeft.width + borderInsets.right + cornerInsets.topRight.width <= + viewSize.width) && + (borderInsets.top + cornerInsets.topLeft.height + borderInsets.bottom + cornerInsets.bottomRight.height <= + viewSize.height) && + (borderInsets.top + cornerInsets.topRight.height + borderInsets.bottom + cornerInsets.bottomLeft.height <= + viewSize.height); - UIEdgeInsets edgeInsets = (UIEdgeInsets){ - borderInsets.top + MAX(cornerInsets.topLeft.height, cornerInsets.topRight.height), - borderInsets.left + MAX(cornerInsets.topLeft.width, cornerInsets.bottomLeft.width), - borderInsets.bottom + MAX(cornerInsets.bottomLeft.height, cornerInsets.bottomRight.height), - borderInsets.right + MAX(cornerInsets.bottomRight.width, cornerInsets.topRight.width) - }; + UIEdgeInsets edgeInsets = + (UIEdgeInsets){borderInsets.top + MAX(cornerInsets.topLeft.height, cornerInsets.topRight.height), + borderInsets.left + MAX(cornerInsets.topLeft.width, cornerInsets.bottomLeft.width), + borderInsets.bottom + MAX(cornerInsets.bottomLeft.height, cornerInsets.bottomRight.height), + borderInsets.right + MAX(cornerInsets.bottomRight.width, cornerInsets.topRight.width)}; if (hasCornerRadii) { // Asymmetrical edgeInsets cause strange artifacting on iOS 10 and earlier. edgeInsets = (UIEdgeInsets){ - MAX(edgeInsets.top, edgeInsets.bottom), - MAX(edgeInsets.left, edgeInsets.right), - MAX(edgeInsets.top, edgeInsets.bottom), - MAX(edgeInsets.left, edgeInsets.right), + MAX(edgeInsets.top, edgeInsets.bottom), + MAX(edgeInsets.left, edgeInsets.right), + MAX(edgeInsets.top, edgeInsets.bottom), + MAX(edgeInsets.left, edgeInsets.right), }; } @@ -260,20 +248,20 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, BOOL hasEqualColors = RCTBorderColorsAreEqual(borderColors); if ((drawToEdge || !hasCornerRadii) && hasEqualColors) { - CGContextSetFillColorWithColor(ctx, borderColors.left); CGContextAddRect(ctx, rect); CGContextAddPath(ctx, insetPath); CGContextEOFillPath(ctx); } else { - CGPoint topLeft = (CGPoint){borderInsets.left, borderInsets.top}; if (cornerInsets.topLeft.width > 0 && cornerInsets.topLeft.height > 0) { CGPoint points[2]; - RCTEllipseGetIntersectionsWithLine((CGRect){ - topLeft, {2 * cornerInsets.topLeft.width, 2 * cornerInsets.topLeft.height} - }, CGPointZero, topLeft, points); + RCTEllipseGetIntersectionsWithLine( + (CGRect){topLeft, {2 * cornerInsets.topLeft.width, 2 * cornerInsets.topLeft.height}}, + CGPointZero, + topLeft, + points); if (!isnan(points[1].x) && !isnan(points[1].y)) { topLeft = points[1]; } @@ -282,10 +270,12 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, CGPoint bottomLeft = (CGPoint){borderInsets.left, size.height - borderInsets.bottom}; if (cornerInsets.bottomLeft.width > 0 && cornerInsets.bottomLeft.height > 0) { CGPoint points[2]; - RCTEllipseGetIntersectionsWithLine((CGRect){ - {bottomLeft.x, bottomLeft.y - 2 * cornerInsets.bottomLeft.height}, - {2 * cornerInsets.bottomLeft.width, 2 * cornerInsets.bottomLeft.height} - }, (CGPoint){0, size.height}, bottomLeft, points); + RCTEllipseGetIntersectionsWithLine( + (CGRect){{bottomLeft.x, bottomLeft.y - 2 * cornerInsets.bottomLeft.height}, + {2 * cornerInsets.bottomLeft.width, 2 * cornerInsets.bottomLeft.height}}, + (CGPoint){0, size.height}, + bottomLeft, + points); if (!isnan(points[1].x) && !isnan(points[1].y)) { bottomLeft = points[1]; } @@ -294,10 +284,12 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, CGPoint topRight = (CGPoint){size.width - borderInsets.right, borderInsets.top}; if (cornerInsets.topRight.width > 0 && cornerInsets.topRight.height > 0) { CGPoint points[2]; - RCTEllipseGetIntersectionsWithLine((CGRect){ - {topRight.x - 2 * cornerInsets.topRight.width, topRight.y}, - {2 * cornerInsets.topRight.width, 2 * cornerInsets.topRight.height} - }, (CGPoint){size.width, 0}, topRight, points); + RCTEllipseGetIntersectionsWithLine( + (CGRect){{topRight.x - 2 * cornerInsets.topRight.width, topRight.y}, + {2 * cornerInsets.topRight.width, 2 * cornerInsets.topRight.height}}, + (CGPoint){size.width, 0}, + topRight, + points); if (!isnan(points[0].x) && !isnan(points[0].y)) { topRight = points[0]; } @@ -306,10 +298,13 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, CGPoint bottomRight = (CGPoint){size.width - borderInsets.right, size.height - borderInsets.bottom}; if (cornerInsets.bottomRight.width > 0 && cornerInsets.bottomRight.height > 0) { CGPoint points[2]; - RCTEllipseGetIntersectionsWithLine((CGRect){ - {bottomRight.x - 2 * cornerInsets.bottomRight.width, bottomRight.y - 2 * cornerInsets.bottomRight.height}, - {2 * cornerInsets.bottomRight.width, 2 * cornerInsets.bottomRight.height} - }, (CGPoint){size.width, size.height}, bottomRight, points); + RCTEllipseGetIntersectionsWithLine( + (CGRect){ + {bottomRight.x - 2 * cornerInsets.bottomRight.width, bottomRight.y - 2 * cornerInsets.bottomRight.height}, + {2 * cornerInsets.bottomRight.width, 2 * cornerInsets.bottomRight.height}}, + (CGPoint){size.width, size.height}, + bottomRight, + points); if (!isnan(points[0].x) && !isnan(points[0].y)) { bottomRight = points[0]; } @@ -319,26 +314,24 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, // RIGHT if (borderInsets.right > 0) { - const CGPoint points[] = { - (CGPoint){size.width, 0}, - topRight, - bottomRight, - (CGPoint){size.width, size.height}, + (CGPoint){size.width, 0}, + topRight, + bottomRight, + (CGPoint){size.width, size.height}, }; currentColor = borderColors.right; - CGContextAddLines(ctx, points, sizeof(points)/sizeof(*points)); + CGContextAddLines(ctx, points, sizeof(points) / sizeof(*points)); } // BOTTOM if (borderInsets.bottom > 0) { - const CGPoint points[] = { - (CGPoint){0, size.height}, - bottomLeft, - bottomRight, - (CGPoint){size.width, size.height}, + (CGPoint){0, size.height}, + bottomLeft, + bottomRight, + (CGPoint){size.width, size.height}, }; if (!CGColorEqualToColor(currentColor, borderColors.bottom)) { @@ -346,17 +339,16 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, CGContextFillPath(ctx); currentColor = borderColors.bottom; } - CGContextAddLines(ctx, points, sizeof(points)/sizeof(*points)); + CGContextAddLines(ctx, points, sizeof(points) / sizeof(*points)); } // LEFT if (borderInsets.left > 0) { - const CGPoint points[] = { - CGPointZero, - topLeft, - bottomLeft, - (CGPoint){0, size.height}, + CGPointZero, + topLeft, + bottomLeft, + (CGPoint){0, size.height}, }; if (!CGColorEqualToColor(currentColor, borderColors.left)) { @@ -364,17 +356,16 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, CGContextFillPath(ctx); currentColor = borderColors.left; } - CGContextAddLines(ctx, points, sizeof(points)/sizeof(*points)); + CGContextAddLines(ctx, points, sizeof(points) / sizeof(*points)); } // TOP if (borderInsets.top > 0) { - const CGPoint points[] = { - CGPointZero, - topLeft, - topRight, - (CGPoint){size.width, 0}, + CGPointZero, + topLeft, + topRight, + (CGPoint){size.width, 0}, }; if (!CGColorEqualToColor(currentColor, borderColors.top)) { @@ -382,7 +373,7 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, CGContextFillPath(ctx); currentColor = borderColors.top; } - CGContextAddLines(ctx, points, sizeof(points)/sizeof(*points)); + CGContextAddLines(ctx, points, sizeof(points) / sizeof(*points)); } CGContextSetFillColorWithColor(ctx, currentColor); @@ -461,13 +452,14 @@ static UIImage *RCTGetSolidBorderImage(RCTCornerRadii cornerRadii, // of gradients _along_ a path (NB: clipping a path and drawing a linear gradient // is _not_ equivalent). -static UIImage *RCTGetDashedOrDottedBorderImage(RCTBorderStyle borderStyle, - RCTCornerRadii cornerRadii, - CGSize viewSize, - UIEdgeInsets borderInsets, - RCTBorderColors borderColors, - CGColorRef backgroundColor, - BOOL drawToEdge) +static UIImage *RCTGetDashedOrDottedBorderImage( + RCTBorderStyle borderStyle, + RCTCornerRadii cornerRadii, + CGSize viewSize, + UIEdgeInsets borderInsets, + RCTBorderColors borderColors, + CGColorRef backgroundColor, + BOOL drawToEdge) { NSCParameterAssert(borderStyle == RCTBorderStyleDashed || borderStyle == RCTBorderStyleDotted); @@ -520,21 +512,22 @@ static UIImage *RCTGetDashedOrDottedBorderImage(RCTBorderStyle borderStyle, return image; } -UIImage *RCTGetBorderImage(RCTBorderStyle borderStyle, - CGSize viewSize, - RCTCornerRadii cornerRadii, - UIEdgeInsets borderInsets, - RCTBorderColors borderColors, - CGColorRef backgroundColor, - BOOL drawToEdge) +UIImage *RCTGetBorderImage( + RCTBorderStyle borderStyle, + CGSize viewSize, + RCTCornerRadii cornerRadii, + UIEdgeInsets borderInsets, + RCTBorderColors borderColors, + CGColorRef backgroundColor, + BOOL drawToEdge) { - switch (borderStyle) { case RCTBorderStyleSolid: return RCTGetSolidBorderImage(cornerRadii, viewSize, borderInsets, borderColors, backgroundColor, drawToEdge); case RCTBorderStyleDashed: case RCTBorderStyleDotted: - return RCTGetDashedOrDottedBorderImage(borderStyle, cornerRadii, viewSize, borderInsets, borderColors, backgroundColor, drawToEdge); + return RCTGetDashedOrDottedBorderImage( + borderStyle, cornerRadii, viewSize, borderInsets, borderColors, backgroundColor, drawToEdge); case RCTBorderStyleUnset: break; } diff --git a/React/Views/RCTComponentData.h b/React/Views/RCTComponentData.h index cf431d6bc17..b61dc4011e1 100644 --- a/React/Views/RCTComponentData.h +++ b/React/Views/RCTComponentData.h @@ -21,15 +21,15 @@ @property (nonatomic, copy, readonly) NSString *name; @property (nonatomic, weak, readonly) RCTViewManager *manager; -- (instancetype)initWithManagerClass:(Class)managerClass - bridge:(RCTBridge *)bridge NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithManagerClass:(Class)managerClass bridge:(RCTBridge *)bridge NS_DESIGNATED_INITIALIZER; - (UIView *)createViewWithTag:(NSNumber *)tag rootTag:(NSNumber *)rootTag; - (RCTShadowView *)createShadowViewWithTag:(NSNumber *)tag; - (void)setProps:(NSDictionary *)props forView:(id)view; - (void)setProps:(NSDictionary *)props forShadowView:(RCTShadowView *)shadowView; -@property (nonatomic, copy, nullable) void (^eventInterceptor)(NSString *eventName, NSDictionary *event, NSNumber *reactTag); +@property (nonatomic, copy, nullable) void (^eventInterceptor) + (NSString *eventName, NSDictionary *event, NSNumber *reactTag); - (NSDictionary *)viewConfig; diff --git a/React/Views/RCTComponentData.m b/React/Views/RCTComponentData.m index cb64e20deb6..f4ecbb1b042 100644 --- a/React/Views/RCTComponentData.m +++ b/React/Views/RCTComponentData.m @@ -31,9 +31,7 @@ static SEL selectorForType(NSString *type) return NSSelectorFromString([RCTParseType(&input) stringByAppendingString:@":"]); } - -@implementation RCTComponentData -{ +@implementation RCTComponentData { id _defaultView; // Only needed for RCT_CUSTOM_VIEW_PROPERTY RCTPropBlockDictionary *_viewPropBlocks; RCTPropBlockDictionary *_shadowPropBlocks; @@ -42,8 +40,7 @@ static SEL selectorForType(NSString *type) @synthesize manager = _manager; -- (instancetype)initWithManagerClass:(Class)managerClass - bridge:(RCTBridge *)bridge +- (instancetype)initWithManagerClass:(Class)managerClass bridge:(RCTBridge *)bridge { if ((self = [super init])) { _bridge = bridge; @@ -64,7 +61,7 @@ static SEL selectorForType(NSString *type) return _manager; } -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (UIView *)createViewWithTag:(NSNumber *)tag rootTag:(NSNumber *)rootTag { @@ -103,7 +100,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) } } -static RCTPropBlock createEventSetter(NSString *propName, SEL setter,InterceptorBlock eventInterceptor, RCTBridge *bridge) +static RCTPropBlock +createEventSetter(NSString *propName, SEL setter, InterceptorBlock eventInterceptor, RCTBridge *bridge) { __weak RCTBridge *weakBridge = bridge; return ^(id target, id json) { @@ -204,13 +202,15 @@ static RCTPropBlock createNSInvocationSetter(NSMethodSignature *typeSignature, S // Get type SEL type = NULL; NSString *keyPath = nil; - SEL selector = NSSelectorFromString([NSString stringWithFormat:@"propConfig%@_%@", isShadowView ? @"Shadow" : @"", name]); + SEL selector = + NSSelectorFromString([NSString stringWithFormat:@"propConfig%@_%@", isShadowView ? @"Shadow" : @"", name]); if ([_managerClass respondsToSelector:selector]) { - NSArray *typeAndKeyPath = ((NSArray *(*)(id, SEL))objc_msgSend)(_managerClass, selector); + NSArray *typeAndKeyPath = ((NSArray * (*)(id, SEL)) objc_msgSend)(_managerClass, selector); type = selectorForType(typeAndKeyPath[0]); keyPath = typeAndKeyPath.count > 1 ? typeAndKeyPath[1] : nil; } else { - return ^(__unused id view, __unused id json) {}; + return ^(__unused id view, __unused id json) { + }; } // Check for custom setter @@ -218,7 +218,8 @@ static RCTPropBlock createNSInvocationSetter(NSMethodSignature *typeSignature, S // Get custom setter. There is no default view in the shadow case, so the selector is different. NSString *selectorString; if (!isShadowView) { - selectorString = [NSString stringWithFormat:@"set_%@:for%@View:withDefaultView:", name, isShadowView ? @"Shadow" : @""]; + selectorString = + [NSString stringWithFormat:@"set_%@:for%@View:withDefaultView:", name, isShadowView ? @"Shadow" : @""]; } else { selectorString = [NSString stringWithFormat:@"set_%@:forShadowView:", name]; } @@ -241,9 +242,8 @@ static RCTPropBlock createNSInvocationSetter(NSMethodSignature *typeSignature, S SEL getter = NSSelectorFromString(key); // Get property setter - SEL setter = NSSelectorFromString([NSString stringWithFormat:@"set%@%@:", - [key substringToIndex:1].uppercaseString, - [key substringFromIndex:1]]); + SEL setter = NSSelectorFromString( + [NSString stringWithFormat:@"set%@%@:", [key substringToIndex:1].uppercaseString, [key substringFromIndex:1]]); // Build setter block void (^setterBlock)(id target, id json) = nil; @@ -256,10 +256,10 @@ static RCTPropBlock createNSInvocationSetter(NSMethodSignature *typeSignature, S NSMethodSignature *typeSignature = [[RCTConvert class] methodSignatureForSelector:type]; if (!typeSignature) { RCTLogError(@"No +[RCTConvert %@] function found.", NSStringFromSelector(type)); - return ^(__unused id view, __unused id json){}; + return ^(__unused id view, __unused id json) { + }; } switch (typeSignature.methodReturnType[0]) { - #define RCT_CASE(_value, _type) \ case _value: { \ __block BOOL setDefaultValue = NO; \ @@ -334,11 +334,13 @@ static RCTPropBlock createNSInvocationSetter(NSMethodSignature *typeSignature, S RCTPropBlock unwrappedBlock = propBlock; __weak __typeof(self) weakSelf = self; propBlock = ^(id view, id json) { - NSString *logPrefix = [NSString stringWithFormat:@"Error setting property '%@' of %@ with tag #%@: ", - name, weakSelf.name, view.reactTag]; - RCTPerformBlockWithLogPrefix(^{ - unwrappedBlock(view, json); - }, logPrefix); + NSString *logPrefix = [NSString + stringWithFormat:@"Error setting property '%@' of %@ with tag #%@: ", name, weakSelf.name, view.reactTag]; + RCTPerformBlockWithLogPrefix( + ^{ + unwrappedBlock(view, json); + }, + logPrefix); }; #endif propBlocks[name] = [propBlock copy]; @@ -400,10 +402,15 @@ static RCTPropBlock createNSInvocationSetter(NSMethodSignature *typeSignature, S } NSString *name = @(underscorePos + 1); - NSString *type = ((NSArray *(*)(id, SEL))objc_msgSend)(_managerClass, selector)[0]; + NSString *type = ((NSArray * (*)(id, SEL)) objc_msgSend)(_managerClass, selector)[0]; if (RCT_DEBUG && propTypes[name] && ![propTypes[name] isEqualToString:type]) { - RCTLogError(@"Property '%@' of component '%@' redefined from '%@' " - "to '%@'", name, _name, propTypes[name], type); + RCTLogError( + @"Property '%@' of component '%@' redefined from '%@' " + "to '%@'", + name, + _name, + propTypes[name], + type); } if ([type isEqualToString:@"RCTBubblingEventBlock"]) { @@ -421,19 +428,22 @@ static RCTPropBlock createNSInvocationSetter(NSMethodSignature *typeSignature, S #if RCT_DEBUG for (NSString *event in bubblingEvents) { if ([directEvents containsObject:event]) { - RCTLogError(@"Component '%@' registered '%@' as both a bubbling event " - "and a direct event", _name, event); + RCTLogError( + @"Component '%@' registered '%@' as both a bubbling event " + "and a direct event", + _name, + event); } } #endif - + Class superClass = [_managerClass superclass]; - + return @{ - @"propTypes": propTypes, - @"directEvents": directEvents, - @"bubblingEvents": bubblingEvents, - @"baseModuleName": superClass == [NSObject class] ? (id)kCFNull : moduleNameForClass(superClass), + @"propTypes" : propTypes, + @"directEvents" : directEvents, + @"bubblingEvents" : bubblingEvents, + @"baseModuleName" : superClass == [NSObject class] ? (id)kCFNull : moduleNameForClass(superClass), }; } @@ -453,9 +463,9 @@ static NSString *moduleNameForClass(Class managerClass) if ([name hasSuffix:@"Manager"]) { name = [name substringToIndex:name.length - @"Manager".length]; } - + RCTAssert(name.length, @"Invalid moduleName '%@'", name); - + return name; } diff --git a/React/Views/RCTConvert+CoreLocation.m b/React/Views/RCTConvert+CoreLocation.m index f15b0599608..95ec773d32f 100644 --- a/React/Views/RCTConvert+CoreLocation.m +++ b/React/Views/RCTConvert+CoreLocation.m @@ -7,7 +7,7 @@ #import "RCTConvert+CoreLocation.h" -@implementation RCTConvert(CoreLocation) +@implementation RCTConvert (CoreLocation) RCT_CONVERTER(CLLocationDegrees, CLLocationDegrees, doubleValue); RCT_CONVERTER(CLLocationDistance, CLLocationDistance, doubleValue); @@ -15,10 +15,8 @@ RCT_CONVERTER(CLLocationDistance, CLLocationDistance, doubleValue); + (CLLocationCoordinate2D)CLLocationCoordinate2D:(id)json { json = [self NSDictionary:json]; - return (CLLocationCoordinate2D){ - [self CLLocationDegrees:json[@"latitude"]], - [self CLLocationDegrees:json[@"longitude"]] - }; + return (CLLocationCoordinate2D){[self CLLocationDegrees:json[@"latitude"]], + [self CLLocationDegrees:json[@"longitude"]]}; } @end diff --git a/React/Views/RCTConvert+Transform.m b/React/Views/RCTConvert+Transform.m index 45262ef679a..94e5dcd6cd9 100644 --- a/React/Views/RCTConvert+Transform.m +++ b/React/Views/RCTConvert+Transform.m @@ -58,7 +58,8 @@ static const NSUInteger kMatrixArrayLength = 4 * 4; } // legacy matrix support if ([(NSArray *)json count] == kMatrixArrayLength && [json[0] isKindOfClass:[NSNumber class]]) { - RCTLogWarn(@"[RCTConvert CATransform3D:] has deprecated a matrix as input. Pass an array of configs (which can contain a matrix key) instead."); + RCTLogWarn( + @"[RCTConvert CATransform3D:] has deprecated a matrix as input. Pass an array of configs (which can contain a matrix key) instead."); return [self CATransform3DFromMatrix:json]; } diff --git a/React/Views/RCTDatePicker.m b/React/Views/RCTDatePicker.m index 7829fc06ad0..1a921c556a0 100644 --- a/React/Views/RCTDatePicker.m +++ b/React/Views/RCTDatePicker.m @@ -22,19 +22,18 @@ - (instancetype)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { - [self addTarget:self action:@selector(didChange) - forControlEvents:UIControlEventValueChanged]; + [self addTarget:self action:@selector(didChange) forControlEvents:UIControlEventValueChanged]; _reactMinuteInterval = 1; } return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) - (void)didChange { if (_onChange) { - _onChange(@{ @"timestamp": @(self.date.timeIntervalSince1970 * 1000.0) }); + _onChange(@{@"timestamp" : @(self.date.timeIntervalSince1970 * 1000.0)}); } } diff --git a/React/Views/RCTDatePickerManager.h b/React/Views/RCTDatePickerManager.h index d8da7051129..bd14cd3b7c8 100644 --- a/React/Views/RCTDatePickerManager.h +++ b/React/Views/RCTDatePickerManager.h @@ -8,7 +8,7 @@ #import #import -@interface RCTConvert(UIDatePicker) +@interface RCTConvert (UIDatePicker) + (UIDatePickerMode)UIDatePickerMode:(id)json; diff --git a/React/Views/RCTDatePickerManager.m b/React/Views/RCTDatePickerManager.m index a5c6ce1d6b4..1eca489f963 100644 --- a/React/Views/RCTDatePickerManager.m +++ b/React/Views/RCTDatePickerManager.m @@ -7,20 +7,24 @@ #import "RCTDatePickerManager.h" +#import #import "RCTBridge.h" #import "RCTDatePicker.h" #import "RCTEventDispatcher.h" #import "UIView+React.h" -#import -@implementation RCTConvert(UIDatePicker) +@implementation RCTConvert (UIDatePicker) -RCT_ENUM_CONVERTER(UIDatePickerMode, (@{ - @"time": @(UIDatePickerModeTime), - @"date": @(UIDatePickerModeDate), - @"datetime": @(UIDatePickerModeDateAndTime), - @"countdown": @(UIDatePickerModeCountDownTimer), // not supported yet -}), UIDatePickerModeTime, integerValue) +RCT_ENUM_CONVERTER( + UIDatePickerMode, + (@{ + @"time" : @(UIDatePickerModeTime), + @"date" : @(UIDatePickerModeDate), + @"datetime" : @(UIDatePickerModeDateAndTime), + @"countdown" : @(UIDatePickerModeCountDownTimer), // not supported yet + }), + UIDatePickerModeTime, + integerValue) @end diff --git a/React/Views/RCTFont.h b/React/Views/RCTFont.h index 284d1b21114..15437dd0889 100644 --- a/React/Views/RCTFont.h +++ b/React/Views/RCTFont.h @@ -9,7 +9,7 @@ #import -typedef UIFont *(^RCTFontHandler)(CGFloat fontSize, NSString *fontWeightDescription); +typedef UIFont * (^RCTFontHandler)(CGFloat fontSize, NSString *fontWeightDescription); /** * React Native will use the System font for rendering by default. If you want to diff --git a/React/Views/RCTFont.mm b/React/Views/RCTFont.mm index 375be702f44..93e1a803c7c 100644 --- a/React/Views/RCTFont.mm +++ b/React/Views/RCTFont.mm @@ -5,8 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -#import "RCTAssert.h" #import "RCTFont.h" +#import "RCTAssert.h" #import "RCTLog.h" #import @@ -80,11 +80,13 @@ static BOOL isCondensedFont(UIFont *font) static RCTFontHandler defaultFontHandler; -void RCTSetDefaultFontHandler(RCTFontHandler handler) { +void RCTSetDefaultFontHandler(RCTFontHandler handler) +{ defaultFontHandler = handler; } -BOOL RCTHasFontHandlerSet() { +BOOL RCTHasFontHandlerSet() +{ return defaultFontHandler != nil; } @@ -92,7 +94,8 @@ BOOL RCTHasFontHandlerSet() { // is not defined pre-iOS 8.2. // Furthermore, UIFontWeight's are lossy floats, so we must use an inexact compare to figure out // which one we actually have. -static inline BOOL CompareFontWeights(UIFontWeight firstWeight, UIFontWeight secondWeight) { +static inline BOOL CompareFontWeights(UIFontWeight firstWeight, UIFontWeight secondWeight) +{ #if CGFLOAT_IS_DOUBLE return fabs(firstWeight - secondWeight) < 0.01; #else @@ -171,26 +174,34 @@ static UIFont *cachedSystemFont(CGFloat size, RCTFontWeight weight) scaleMultiplier:1]; } -RCT_ENUM_CONVERTER(RCTFontWeight, (@{ - @"normal": @(UIFontWeightRegular), - @"bold": @(UIFontWeightBold), - @"100": @(UIFontWeightUltraLight), - @"200": @(UIFontWeightThin), - @"300": @(UIFontWeightLight), - @"400": @(UIFontWeightRegular), - @"500": @(UIFontWeightMedium), - @"600": @(UIFontWeightSemibold), - @"700": @(UIFontWeightBold), - @"800": @(UIFontWeightHeavy), - @"900": @(UIFontWeightBlack), - }), UIFontWeightRegular, doubleValue) +RCT_ENUM_CONVERTER( + RCTFontWeight, + (@{ + @"normal" : @(UIFontWeightRegular), + @"bold" : @(UIFontWeightBold), + @"100" : @(UIFontWeightUltraLight), + @"200" : @(UIFontWeightThin), + @"300" : @(UIFontWeightLight), + @"400" : @(UIFontWeightRegular), + @"500" : @(UIFontWeightMedium), + @"600" : @(UIFontWeightSemibold), + @"700" : @(UIFontWeightBold), + @"800" : @(UIFontWeightHeavy), + @"900" : @(UIFontWeightBlack), + }), + UIFontWeightRegular, + doubleValue) typedef BOOL RCTFontStyle; -RCT_ENUM_CONVERTER(RCTFontStyle, (@{ - @"normal": @NO, - @"italic": @YES, - @"oblique": @YES, - }), NO, boolValue) +RCT_ENUM_CONVERTER( + RCTFontStyle, + (@{ + @"normal" : @NO, + @"italic" : @YES, + @"oblique" : @YES, + }), + NO, + boolValue) typedef NSDictionary RCTFontVariantDescriptor; + (RCTFontVariantDescriptor *)RCTFontVariantDescriptor:(id)json @@ -199,32 +210,34 @@ typedef NSDictionary RCTFontVariantDescriptor; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ mapping = @{ - @"small-caps": @{ - UIFontFeatureTypeIdentifierKey: @(kLowerCaseType), - UIFontFeatureSelectorIdentifierKey: @(kLowerCaseSmallCapsSelector), - }, - @"oldstyle-nums": @{ - UIFontFeatureTypeIdentifierKey: @(kNumberCaseType), - UIFontFeatureSelectorIdentifierKey: @(kLowerCaseNumbersSelector), - }, - @"lining-nums": @{ - UIFontFeatureTypeIdentifierKey: @(kNumberCaseType), - UIFontFeatureSelectorIdentifierKey: @(kUpperCaseNumbersSelector), - }, - @"tabular-nums": @{ - UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType), - UIFontFeatureSelectorIdentifierKey: @(kMonospacedNumbersSelector), - }, - @"proportional-nums": @{ - UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType), - UIFontFeatureSelectorIdentifierKey: @(kProportionalNumbersSelector), - }, - }; + @"small-caps" : @{ + UIFontFeatureTypeIdentifierKey : @(kLowerCaseType), + UIFontFeatureSelectorIdentifierKey : @(kLowerCaseSmallCapsSelector), + }, + @"oldstyle-nums" : @{ + UIFontFeatureTypeIdentifierKey : @(kNumberCaseType), + UIFontFeatureSelectorIdentifierKey : @(kLowerCaseNumbersSelector), + }, + @"lining-nums" : @{ + UIFontFeatureTypeIdentifierKey : @(kNumberCaseType), + UIFontFeatureSelectorIdentifierKey : @(kUpperCaseNumbersSelector), + }, + @"tabular-nums" : @{ + UIFontFeatureTypeIdentifierKey : @(kNumberSpacingType), + UIFontFeatureSelectorIdentifierKey : @(kMonospacedNumbersSelector), + }, + @"proportional-nums" : @{ + UIFontFeatureTypeIdentifierKey : @(kNumberSpacingType), + UIFontFeatureSelectorIdentifierKey : @(kProportionalNumbersSelector), + }, + }; }); RCTFontVariantDescriptor *value = mapping[json]; if (RCT_DEBUG && !value && [json description].length > 0) { - RCTLogError(@"Invalid RCTFontVariantDescriptor '%@'. should be one of: %@", json, - [[mapping allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]); + RCTLogError( + @"Invalid RCTFontVariantDescriptor '%@'. should be one of: %@", + json, + [[mapping allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]); } return value; } @@ -328,8 +341,7 @@ RCT_ARRAY_CONVERTER(RCTFontVariantDescriptor) CGFloat closestWeight = INFINITY; for (NSString *name in [UIFont fontNamesForFamilyName:familyName]) { UIFont *match = [UIFont fontWithName:name size:fontSize]; - if (isItalic == isItalicFont(match) && - isCondensed == isCondensedFont(match)) { + if (isItalic == isItalicFont(match) && isCondensed == isCondensedFont(match)) { CGFloat testWeight = weightOfFont(match); if (ABS(testWeight - fontWeight) < ABS(closestWeight - fontWeight)) { font = match; @@ -350,9 +362,8 @@ RCT_ARRAY_CONVERTER(RCTFontVariantDescriptor) // Apply font variants to font object if (variant) { NSArray *fontFeatures = [RCTConvert RCTFontVariantDescriptorArray:variant]; - UIFontDescriptor *fontDescriptor = [font.fontDescriptor fontDescriptorByAddingAttributes:@{ - UIFontDescriptorFeatureSettingsAttribute: fontFeatures - }]; + UIFontDescriptor *fontDescriptor = [font.fontDescriptor + fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute : fontFeatures}]; font = [UIFont fontWithDescriptor:fontDescriptor size:fontSize]; } diff --git a/React/Views/RCTLayout.h b/React/Views/RCTLayout.h index 7bfeccee685..d83803284fc 100644 --- a/React/Views/RCTLayout.h +++ b/React/Views/RCTLayout.h @@ -38,12 +38,9 @@ typedef struct CG_BOXABLE RCTLayoutContext RCTLayoutContext; static inline BOOL RCTLayoutMetricsEqualToLayoutMetrics(RCTLayoutMetrics a, RCTLayoutMetrics b) { - return - CGRectEqualToRect(a.frame, b.frame) && - CGRectEqualToRect(a.contentFrame, b.contentFrame) && - UIEdgeInsetsEqualToEdgeInsets(a.borderWidth, b.borderWidth) && - a.displayType == b.displayType && - a.layoutDirection == b.layoutDirection; + return CGRectEqualToRect(a.frame, b.frame) && CGRectEqualToRect(a.contentFrame, b.contentFrame) && + UIEdgeInsetsEqualToEdgeInsets(a.borderWidth, b.borderWidth) && a.displayType == b.displayType && + a.layoutDirection == b.layoutDirection; } RCT_EXTERN RCTLayoutMetrics RCTLayoutMetricsFromYogaNode(YGNodeRef yogaNode); diff --git a/React/Views/RCTLayout.m b/React/Views/RCTLayout.m index 8f72bd43629..0ca11c7b8ea 100644 --- a/React/Views/RCTLayout.m +++ b/React/Views/RCTLayout.m @@ -14,37 +14,27 @@ RCTLayoutMetrics RCTLayoutMetricsFromYogaNode(YGNodeRef yogaNode) { RCTLayoutMetrics layoutMetrics; - CGRect frame = (CGRect){ - (CGPoint){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetLeft(yogaNode)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetTop(yogaNode)) - }, - (CGSize){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetWidth(yogaNode)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetHeight(yogaNode)) - } - }; + CGRect frame = (CGRect){(CGPoint){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetLeft(yogaNode)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetTop(yogaNode))}, + (CGSize){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetWidth(yogaNode)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetHeight(yogaNode))}}; - UIEdgeInsets padding = (UIEdgeInsets){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeTop)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeLeft)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeBottom)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeRight)) - }; + UIEdgeInsets padding = + (UIEdgeInsets){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeTop)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeLeft)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeBottom)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeRight))}; - UIEdgeInsets borderWidth = (UIEdgeInsets){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeTop)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeLeft)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeBottom)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeRight)) - }; + UIEdgeInsets borderWidth = + (UIEdgeInsets){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeTop)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeLeft)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeBottom)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeRight))}; - UIEdgeInsets compoundInsets = (UIEdgeInsets){ - borderWidth.top + padding.top, - borderWidth.left + padding.left, - borderWidth.bottom + padding.bottom, - borderWidth.right + padding.right - }; + UIEdgeInsets compoundInsets = (UIEdgeInsets){borderWidth.top + padding.top, + borderWidth.left + padding.left, + borderWidth.bottom + padding.bottom, + borderWidth.right + padding.right}; CGRect bounds = (CGRect){CGPointZero, frame.size}; CGRect contentFrame = UIEdgeInsetsInsetRect(bounds, compoundInsets); @@ -58,7 +48,6 @@ RCTLayoutMetrics RCTLayoutMetricsFromYogaNode(YGNodeRef yogaNode) return layoutMetrics; } - /** * Yoga and CoreGraphics have different opinions about how "infinity" value * should be represented. diff --git a/React/Views/RCTModalHostView.h b/React/Views/RCTModalHostView.h index e16dd222b50..4e61886dba5 100644 --- a/React/Views/RCTModalHostView.h +++ b/React/Views/RCTModalHostView.h @@ -43,7 +43,11 @@ @protocol RCTModalHostViewInteractor -- (void)presentModalHostView:(RCTModalHostView *)modalHostView withViewController:(RCTModalHostViewController *)viewController animated:(BOOL)animated; -- (void)dismissModalHostView:(RCTModalHostView *)modalHostView withViewController:(RCTModalHostViewController *)viewController animated:(BOOL)animated; +- (void)presentModalHostView:(RCTModalHostView *)modalHostView + withViewController:(RCTModalHostViewController *)viewController + animated:(BOOL)animated; +- (void)dismissModalHostView:(RCTModalHostView *)modalHostView + withViewController:(RCTModalHostViewController *)viewController + animated:(BOOL)animated; @end diff --git a/React/Views/RCTModalHostView.m b/React/Views/RCTModalHostView.m index 95d572bf3eb..6a153301038 100644 --- a/React/Views/RCTModalHostView.m +++ b/React/Views/RCTModalHostView.m @@ -20,8 +20,7 @@ #import "RCTTVRemoteHandler.h" #endif -@implementation RCTModalHostView -{ +@implementation RCTModalHostView { __weak RCTBridge *_bridge; BOOL _isPresented; RCTModalHostViewController *_modalViewController; @@ -32,11 +31,10 @@ #else UIInterfaceOrientation _lastKnownOrientation; #endif - } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:coder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : coder) - (instancetype)initWithBridge:(RCTBridge *)bridge { @@ -48,8 +46,9 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:coder) _modalViewController.view = containerView; _touchHandler = [[RCTTouchHandler alloc] initWithBridge:bridge]; #if TARGET_OS_TV - _menuButtonGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuButtonPressed:)]; - _menuButtonGestureRecognizer.allowedPressTypes = @[@(UIPressTypeMenu)]; + _menuButtonGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self + action:@selector(menuButtonPressed:)]; + _menuButtonGestureRecognizer.allowedPressTypes = @[ @(UIPressTypeMenu) ]; self.tvRemoteHandler = [RCTTVRemoteHandler new]; #endif _isPresented = NO; @@ -66,9 +65,9 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:coder) #if TARGET_OS_TV - (void)menuButtonPressed:(__unused UIGestureRecognizer *)gestureRecognizer { - if (_onRequestClose) { - _onRequestClose(nil); - } + if (_onRequestClose) { + _onRequestClose(nil); + } } - (void)setOnRequestClose:(RCTDirectEventBlock)onRequestClose @@ -105,11 +104,11 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:coder) } _lastKnownOrientation = currentOrientation; - BOOL isPortrait = currentOrientation == UIInterfaceOrientationPortrait || currentOrientation == UIInterfaceOrientationPortraitUpsideDown; - NSDictionary *eventPayload = - @{ - @"orientation": isPortrait ? @"portrait" : @"landscape", - }; + BOOL isPortrait = currentOrientation == UIInterfaceOrientationPortrait || + currentOrientation == UIInterfaceOrientationPortraitUpsideDown; + NSDictionary *eventPayload = @{ + @"orientation" : isPortrait ? @"portrait" : @"landscape", + }; _onOrientationChange(eventPayload); #endif } @@ -168,8 +167,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:coder) { [super didMoveToWindow]; - // In the case where there is a LayoutAnimation, we will be reinserted into the view hierarchy but only for aesthetic purposes. - // In such a case, we should NOT represent the . + // In the case where there is a LayoutAnimation, we will be reinserted into the view hierarchy but only for aesthetic + // purposes. In such a case, we should NOT represent the . if (!self.userInteractionEnabled && ![self.superview.reactSubviews containsObject:self]) { return; } @@ -225,7 +224,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:coder) return; } - _modalViewController.modalPresentationStyle = transparent ? UIModalPresentationOverFullScreen : UIModalPresentationFullScreen; + _modalViewController.modalPresentationStyle = + transparent ? UIModalPresentationOverFullScreen : UIModalPresentationFullScreen; } #if !TARGET_OS_TV diff --git a/React/Views/RCTModalHostViewController.m b/React/Views/RCTModalHostViewController.m index c76ad788b50..112bc17c4d8 100644 --- a/React/Views/RCTModalHostViewController.m +++ b/React/Views/RCTModalHostViewController.m @@ -10,8 +10,7 @@ #import "RCTLog.h" #import "RCTModalHostView.h" -@implementation RCTModalHostViewController -{ +@implementation RCTModalHostViewController { CGRect _lastViewFrame; #if !TARGET_OS_TV UIStatusBarStyle _preferredStatusBarStyle; @@ -26,7 +25,7 @@ } #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ -__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 + __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 if (@available(iOS 13.0, *)) { self.modalInPresentation = YES; } @@ -64,13 +63,15 @@ __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 #if RCT_DEV - (UIInterfaceOrientationMask)supportedInterfaceOrientations { - UIInterfaceOrientationMask appSupportedOrientationsMask = [RCTSharedApplication() supportedInterfaceOrientationsForWindow:[RCTSharedApplication() keyWindow]]; + UIInterfaceOrientationMask appSupportedOrientationsMask = + [RCTSharedApplication() supportedInterfaceOrientationsForWindow:[RCTSharedApplication() keyWindow]]; if (!(_supportedInterfaceOrientations & appSupportedOrientationsMask)) { - RCTLogError(@"Modal was presented with 0x%x orientations mask but the application only supports 0x%x." - @"Add more interface orientations to your app's Info.plist to fix this." - @"NOTE: This will crash in non-dev mode.", - (unsigned)_supportedInterfaceOrientations, - (unsigned)appSupportedOrientationsMask); + RCTLogError( + @"Modal was presented with 0x%x orientations mask but the application only supports 0x%x." + @"Add more interface orientations to your app's Info.plist to fix this." + @"NOTE: This will crash in non-dev mode.", + (unsigned)_supportedInterfaceOrientations, + (unsigned)appSupportedOrientationsMask); return UIInterfaceOrientationMaskAll; } @@ -79,5 +80,4 @@ __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 #endif // RCT_DEV #endif // !TARGET_OS_TV - @end diff --git a/React/Views/RCTModalHostViewManager.h b/React/Views/RCTModalHostViewManager.h index 608ca0901af..e5b08157128 100644 --- a/React/Views/RCTModalHostViewManager.h +++ b/React/Views/RCTModalHostViewManager.h @@ -5,9 +5,9 @@ * LICENSE file in the root directory of this source tree. */ +#import #import #import -#import @interface RCTConvert (RCTModalHostView) @@ -15,7 +15,11 @@ @end -typedef void (^RCTModalViewInteractionBlock)(UIViewController *reactViewController, UIViewController *viewController, BOOL animated, dispatch_block_t completionBlock); +typedef void (^RCTModalViewInteractionBlock)( + UIViewController *reactViewController, + UIViewController *viewController, + BOOL animated, + dispatch_block_t completionBlock); @interface RCTModalHostViewManager : RCTViewManager diff --git a/React/Views/RCTModalHostViewManager.m b/React/Views/RCTModalHostViewManager.m index 44f9ac9d2da..bafab9dff9f 100644 --- a/React/Views/RCTModalHostViewManager.m +++ b/React/Views/RCTModalHostViewManager.m @@ -15,14 +15,18 @@ @implementation RCTConvert (RCTModalHostView) -RCT_ENUM_CONVERTER(UIModalPresentationStyle, (@{ - @"fullScreen": @(UIModalPresentationFullScreen), +RCT_ENUM_CONVERTER( + UIModalPresentationStyle, + (@{ + @"fullScreen" : @(UIModalPresentationFullScreen), #if !TARGET_OS_TV - @"pageSheet": @(UIModalPresentationPageSheet), - @"formSheet": @(UIModalPresentationFormSheet), + @"pageSheet" : @(UIModalPresentationPageSheet), + @"formSheet" : @(UIModalPresentationFormSheet), #endif - @"overFullScreen": @(UIModalPresentationOverFullScreen), -}), UIModalPresentationFullScreen, integerValue) + @"overFullScreen" : @(UIModalPresentationOverFullScreen), + }), + UIModalPresentationFullScreen, + integerValue) @end @@ -46,8 +50,7 @@ RCT_ENUM_CONVERTER(UIModalPresentationStyle, (@{ @end -@implementation RCTModalHostViewManager -{ +@implementation RCTModalHostViewManager { NSPointerArray *_hostViews; } @@ -64,7 +67,9 @@ RCT_EXPORT_MODULE() return view; } -- (void)presentModalHostView:(RCTModalHostView *)modalHostView withViewController:(RCTModalHostViewController *)viewController animated:(BOOL)animated +- (void)presentModalHostView:(RCTModalHostView *)modalHostView + withViewController:(RCTModalHostViewController *)viewController + animated:(BOOL)animated { dispatch_block_t completionBlock = ^{ if (modalHostView.onShow) { @@ -74,11 +79,15 @@ RCT_EXPORT_MODULE() if (_presentationBlock) { _presentationBlock([modalHostView reactViewController], viewController, animated, completionBlock); } else { - [[modalHostView reactViewController] presentViewController:viewController animated:animated completion:completionBlock]; + [[modalHostView reactViewController] presentViewController:viewController + animated:animated + completion:completionBlock]; } } -- (void)dismissModalHostView:(RCTModalHostView *)modalHostView withViewController:(RCTModalHostViewController *)viewController animated:(BOOL)animated +- (void)dismissModalHostView:(RCTModalHostView *)modalHostView + withViewController:(RCTModalHostViewController *)viewController + animated:(BOOL)animated { if (_dismissalBlock) { _dismissalBlock([modalHostView reactViewController], viewController, animated, nil); @@ -87,7 +96,6 @@ RCT_EXPORT_MODULE() } } - - (RCTShadowView *)shadowView { return [RCTModalHostShadowView new]; diff --git a/React/Views/RCTPicker.m b/React/Views/RCTPicker.m index c8e4bba8610..774264f55f9 100644 --- a/React/Views/RCTPicker.m +++ b/React/Views/RCTPicker.m @@ -10,7 +10,7 @@ #import "RCTConvert.h" #import "RCTUtils.h" -@interface RCTPicker() +@interface RCTPicker () @end @implementation RCTPicker @@ -23,12 +23,15 @@ _selectedIndex = NSNotFound; _textAlign = NSTextAlignmentCenter; self.delegate = self; - [self selectRow:0 inComponent:0 animated:YES]; // Workaround for missing selection indicator lines (see https://stackoverflow.com/questions/39564660/uipickerview-selection-indicator-not-visible-in-ios10) + [self selectRow:0 inComponent:0 + animated: + YES]; // Workaround for missing selection indicator lines (see + // https://stackoverflow.com/questions/39564660/uipickerview-selection-indicator-not-visible-in-ios10) } return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) - (void)setItems:(NSArray *)items { @@ -54,8 +57,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) return 1; } -- (NSInteger)pickerView:(__unused UIPickerView *)pickerView -numberOfRowsInComponent:(__unused NSInteger)component +- (NSInteger)pickerView:(__unused UIPickerView *)pickerView numberOfRowsInComponent:(__unused NSInteger)component { return _items.count; } @@ -69,7 +71,8 @@ numberOfRowsInComponent:(__unused NSInteger)component return [RCTConvert NSString:_items[row][@"label"]]; } -- (CGFloat)pickerView:(__unused UIPickerView *)pickerView rowHeightForComponent:(NSInteger)__unused component { +- (CGFloat)pickerView:(__unused UIPickerView *)pickerView rowHeightForComponent:(NSInteger)__unused component +{ return _font.pointSize + 19; } @@ -79,13 +82,11 @@ numberOfRowsInComponent:(__unused NSInteger)component reusingView:(UILabel *)label { if (!label) { - label = [[UILabel alloc] initWithFrame:(CGRect){ - CGPointZero, - { - [pickerView rowSizeForComponent:component].width, - [pickerView rowSizeForComponent:component].height, - } - }]; + label = [[UILabel alloc] initWithFrame:(CGRect){CGPointZero, + { + [pickerView rowSizeForComponent:component].width, + [pickerView rowSizeForComponent:component].height, + }}]; } label.font = _font; @@ -98,21 +99,23 @@ numberOfRowsInComponent:(__unused NSInteger)component } - (void)pickerView:(__unused UIPickerView *)pickerView - didSelectRow:(NSInteger)row inComponent:(__unused NSInteger)component + didSelectRow:(NSInteger)row + inComponent:(__unused NSInteger)component { _selectedIndex = row; if (_onChange && _items.count > (NSUInteger)row) { _onChange(@{ - @"newIndex": @(row), - @"newValue": RCTNullIfNil(_items[row][@"value"]), + @"newIndex" : @(row), + @"newValue" : RCTNullIfNil(_items[row][@"value"]), }); } } #pragma mark - UIPickerViewAccessibilityDelegate protocol -- (NSString *)pickerView:(UIPickerView *)pickerView accessibilityLabelForComponent:(NSInteger)component{ - return super.accessibilityLabel; +- (NSString *)pickerView:(UIPickerView *)pickerView accessibilityLabelForComponent:(NSInteger)component +{ + return super.accessibilityLabel; } @end diff --git a/React/Views/RCTPickerManager.m b/React/Views/RCTPickerManager.m index 7585735d598..7127656cce4 100644 --- a/React/Views/RCTPickerManager.m +++ b/React/Views/RCTPickerManager.m @@ -7,10 +7,10 @@ #import "RCTPickerManager.h" -#import "RCTBridge.h" -#import "RCTPicker.h" -#import "RCTFont.h" #import +#import "RCTBridge.h" +#import "RCTFont.h" +#import "RCTPicker.h" @implementation RCTPickerManager diff --git a/React/Views/RCTProgressViewManager.m b/React/Views/RCTProgressViewManager.m index 8fb921005f8..887473cb1aa 100644 --- a/React/Views/RCTProgressViewManager.m +++ b/React/Views/RCTProgressViewManager.m @@ -11,12 +11,16 @@ @implementation RCTConvert (RCTProgressViewManager) -RCT_ENUM_CONVERTER(UIProgressViewStyle, (@{ - @"default": @(UIProgressViewStyleDefault), +RCT_ENUM_CONVERTER( + UIProgressViewStyle, + (@{ + @"default" : @(UIProgressViewStyleDefault), #if !TARGET_OS_TV - @"bar": @(UIProgressViewStyleBar), + @"bar" : @(UIProgressViewStyleBar), #endif -}), UIProgressViewStyleDefault, integerValue) + }), + UIProgressViewStyleDefault, + integerValue) @end diff --git a/React/Views/RCTSegmentedControl.m b/React/Views/RCTSegmentedControl.m index 6c1f1b9f47a..10c1c745a59 100644 --- a/React/Views/RCTSegmentedControl.m +++ b/React/Views/RCTSegmentedControl.m @@ -17,8 +17,7 @@ { if ((self = [super initWithFrame:frame])) { _selectedIndex = self.selectedSegmentIndex; - [self addTarget:self action:@selector(didChange) - forControlEvents:UIControlEventValueChanged]; + [self addTarget:self action:@selector(didChange) forControlEvents:UIControlEventValueChanged]; } return self; } @@ -41,23 +40,22 @@ - (void)setBackgroundColor:(UIColor *)backgroundColor { - #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ - __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 - if (@available(iOS 13.0, *)) { - [super setBackgroundColor:backgroundColor]; - } - #endif +#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 + if (@available(iOS 13.0, *)) { + [super setBackgroundColor:backgroundColor]; + } +#endif } - (void)setTextColor:(UIColor *)textColor { - #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ - __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 - if (@available(iOS 13.0, *)) { - [self setTitleTextAttributes:@{NSForegroundColorAttributeName: textColor} - forState:UIControlStateNormal]; - } - #endif +#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 + if (@available(iOS 13.0, *)) { + [self setTitleTextAttributes:@{NSForegroundColorAttributeName : textColor} forState:UIControlStateNormal]; + } +#endif } - (void)setTintColor:(UIColor *)tintColor @@ -67,10 +65,9 @@ __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 if (@available(iOS 13.0, *)) { [self setSelectedSegmentTintColor:tintColor]; - [self setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} + [self setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected]; - [self setTitleTextAttributes:@{NSForegroundColorAttributeName: tintColor} - forState:UIControlStateNormal]; + [self setTitleTextAttributes:@{NSForegroundColorAttributeName : tintColor} forState:UIControlStateNormal]; } #endif } @@ -79,10 +76,7 @@ { _selectedIndex = self.selectedSegmentIndex; if (_onChange) { - _onChange(@{ - @"value": [self titleForSegmentAtIndex:_selectedIndex], - @"selectedSegmentIndex": @(_selectedIndex) - }); + _onChange(@{@"value" : [self titleForSegmentAtIndex:_selectedIndex], @"selectedSegmentIndex" : @(_selectedIndex)}); } } diff --git a/React/Views/RCTShadowView+Internal.m b/React/Views/RCTShadowView+Internal.m index a5a93a08069..61676e7b124 100644 --- a/React/Views/RCTShadowView+Internal.m +++ b/React/Views/RCTShadowView+Internal.m @@ -7,8 +7,7 @@ #import "RCTShadowView+Layout.h" -@interface RCTShadowView () -{ +@interface RCTShadowView () { __weak RCTRootShadowView *_rootView; } diff --git a/React/Views/RCTShadowView+Layout.m b/React/Views/RCTShadowView+Layout.m index a04bae8327a..734f053fc56 100644 --- a/React/Views/RCTShadowView+Layout.m +++ b/React/Views/RCTShadowView+Layout.m @@ -18,23 +18,19 @@ - (UIEdgeInsets)paddingAsInsets { YGNodeRef yogaNode = self.yogaNode; - return (UIEdgeInsets){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeTop)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeLeft)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeBottom)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeRight)) - }; + return (UIEdgeInsets){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeTop)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeLeft)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeBottom)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeRight))}; } - (UIEdgeInsets)borderAsInsets { YGNodeRef yogaNode = self.yogaNode; - return (UIEdgeInsets){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeTop)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeLeft)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeBottom)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeRight)) - }; + return (UIEdgeInsets){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeTop)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeLeft)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeBottom)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeRight))}; } - (UIEdgeInsets)compoundInsets @@ -42,12 +38,10 @@ UIEdgeInsets borderAsInsets = self.borderAsInsets; UIEdgeInsets paddingAsInsets = self.paddingAsInsets; - return (UIEdgeInsets){ - borderAsInsets.top + paddingAsInsets.top, - borderAsInsets.left + paddingAsInsets.left, - borderAsInsets.bottom + paddingAsInsets.bottom, - borderAsInsets.right + paddingAsInsets.right - }; + return (UIEdgeInsets){borderAsInsets.top + paddingAsInsets.top, + borderAsInsets.left + paddingAsInsets.left, + borderAsInsets.bottom + paddingAsInsets.bottom, + borderAsInsets.right + paddingAsInsets.right}; } - (CGSize)availableSize diff --git a/React/Views/RCTShadowView.h b/React/Views/RCTShadowView.h index fa96000ca64..4696b142137 100644 --- a/React/Views/RCTShadowView.h +++ b/React/Views/RCTShadowView.h @@ -184,8 +184,7 @@ typedef void (^RCTApplierBlock)(NSDictionary *viewRegistry /** * Applies computed layout metrics to the view. */ -- (void)layoutWithMetrics:(RCTLayoutMetrics)layoutMetrics - layoutContext:(RCTLayoutContext)layoutContext; +- (void)layoutWithMetrics:(RCTLayoutMetrics)layoutMetrics layoutContext:(RCTLayoutContext)layoutContext; /** * Calculates (if needed) and applies layout to subviews. @@ -196,8 +195,7 @@ typedef void (^RCTApplierBlock)(NSDictionary *viewRegistry * Measures shadow view without side-effects. * Default implementation uses Yoga for measuring. */ -- (CGSize)sizeThatFitsMinimumSize:(CGSize)minimumSize - maximumSize:(CGSize)maximumSize; +- (CGSize)sizeThatFitsMinimumSize:(CGSize)minimumSize maximumSize:(CGSize)maximumSize; /** * Returns whether or not this view can have any subviews. diff --git a/React/Views/RCTShadowView.m b/React/Views/RCTShadowView.m index 56c149e50f4..61894cdd7b8 100644 --- a/React/Views/RCTShadowView.m +++ b/React/Views/RCTShadowView.m @@ -32,8 +32,7 @@ typedef NS_ENUM(unsigned int, meta_prop_t) { META_PROP_COUNT, }; -@implementation RCTShadowView -{ +@implementation RCTShadowView { NSDictionary *_lastParentProperties; NSMutableArray *_reactSubviews; BOOL _recomputePadding; @@ -67,45 +66,48 @@ static void RCTPrint(YGNodeRef node) printf("%s(%lld), ", shadowView.viewName.UTF8String, (long long)shadowView.reactTag.integerValue); } -#define RCT_SET_YGVALUE(ygvalue, setter, ...) \ -switch (ygvalue.unit) { \ - case YGUnitAuto: \ - case YGUnitUndefined: \ - setter(__VA_ARGS__, YGUndefined); \ - break; \ - case YGUnitPoint: \ - setter(__VA_ARGS__, ygvalue.value); \ - break; \ - case YGUnitPercent: \ - setter##Percent(__VA_ARGS__, ygvalue.value); \ - break; \ -} +#define RCT_SET_YGVALUE(ygvalue, setter, ...) \ + switch (ygvalue.unit) { \ + case YGUnitAuto: \ + case YGUnitUndefined: \ + setter(__VA_ARGS__, YGUndefined); \ + break; \ + case YGUnitPoint: \ + setter(__VA_ARGS__, ygvalue.value); \ + break; \ + case YGUnitPercent: \ + setter##Percent(__VA_ARGS__, ygvalue.value); \ + break; \ + } #define RCT_SET_YGVALUE_AUTO(ygvalue, setter, ...) \ -switch (ygvalue.unit) { \ - case YGUnitAuto: \ - setter##Auto(__VA_ARGS__); \ - break; \ - case YGUnitUndefined: \ - setter(__VA_ARGS__, YGUndefined); \ - break; \ - case YGUnitPoint: \ - setter(__VA_ARGS__, ygvalue.value); \ - break; \ - case YGUnitPercent: \ - setter##Percent(__VA_ARGS__, ygvalue.value); \ - break; \ -} + switch (ygvalue.unit) { \ + case YGUnitAuto: \ + setter##Auto(__VA_ARGS__); \ + break; \ + case YGUnitUndefined: \ + setter(__VA_ARGS__, YGUndefined); \ + break; \ + case YGUnitPoint: \ + setter(__VA_ARGS__, ygvalue.value); \ + break; \ + case YGUnitPercent: \ + setter##Percent(__VA_ARGS__, ygvalue.value); \ + break; \ + } -static void RCTProcessMetaPropsPadding(const YGValue metaProps[META_PROP_COUNT], YGNodeRef node) { +static void RCTProcessMetaPropsPadding(const YGValue metaProps[META_PROP_COUNT], YGNodeRef node) +{ if (![[RCTI18nUtil sharedInstance] doLeftAndRightSwapInRTL]) { RCT_SET_YGVALUE(metaProps[META_PROP_START], YGNodeStyleSetPadding, node, YGEdgeStart); RCT_SET_YGVALUE(metaProps[META_PROP_END], YGNodeStyleSetPadding, node, YGEdgeEnd); RCT_SET_YGVALUE(metaProps[META_PROP_LEFT], YGNodeStyleSetPadding, node, YGEdgeLeft); RCT_SET_YGVALUE(metaProps[META_PROP_RIGHT], YGNodeStyleSetPadding, node, YGEdgeRight); } else { - YGValue start = metaProps[META_PROP_START].unit == YGUnitUndefined ? metaProps[META_PROP_LEFT] : metaProps[META_PROP_START]; - YGValue end = metaProps[META_PROP_END].unit == YGUnitUndefined ? metaProps[META_PROP_RIGHT] : metaProps[META_PROP_END]; + YGValue start = + metaProps[META_PROP_START].unit == YGUnitUndefined ? metaProps[META_PROP_LEFT] : metaProps[META_PROP_START]; + YGValue end = + metaProps[META_PROP_END].unit == YGUnitUndefined ? metaProps[META_PROP_RIGHT] : metaProps[META_PROP_END]; RCT_SET_YGVALUE(start, YGNodeStyleSetPadding, node, YGEdgeStart); RCT_SET_YGVALUE(end, YGNodeStyleSetPadding, node, YGEdgeEnd); } @@ -116,15 +118,18 @@ static void RCTProcessMetaPropsPadding(const YGValue metaProps[META_PROP_COUNT], RCT_SET_YGVALUE(metaProps[META_PROP_ALL], YGNodeStyleSetPadding, node, YGEdgeAll); } -static void RCTProcessMetaPropsMargin(const YGValue metaProps[META_PROP_COUNT], YGNodeRef node) { +static void RCTProcessMetaPropsMargin(const YGValue metaProps[META_PROP_COUNT], YGNodeRef node) +{ if (![[RCTI18nUtil sharedInstance] doLeftAndRightSwapInRTL]) { RCT_SET_YGVALUE_AUTO(metaProps[META_PROP_START], YGNodeStyleSetMargin, node, YGEdgeStart); RCT_SET_YGVALUE_AUTO(metaProps[META_PROP_END], YGNodeStyleSetMargin, node, YGEdgeEnd); RCT_SET_YGVALUE_AUTO(metaProps[META_PROP_LEFT], YGNodeStyleSetMargin, node, YGEdgeLeft); RCT_SET_YGVALUE_AUTO(metaProps[META_PROP_RIGHT], YGNodeStyleSetMargin, node, YGEdgeRight); } else { - YGValue start = metaProps[META_PROP_START].unit == YGUnitUndefined ? metaProps[META_PROP_LEFT] : metaProps[META_PROP_START]; - YGValue end = metaProps[META_PROP_END].unit == YGUnitUndefined ? metaProps[META_PROP_RIGHT] : metaProps[META_PROP_END]; + YGValue start = + metaProps[META_PROP_START].unit == YGUnitUndefined ? metaProps[META_PROP_LEFT] : metaProps[META_PROP_START]; + YGValue end = + metaProps[META_PROP_END].unit == YGUnitUndefined ? metaProps[META_PROP_RIGHT] : metaProps[META_PROP_END]; RCT_SET_YGVALUE_AUTO(start, YGNodeStyleSetMargin, node, YGEdgeStart); RCT_SET_YGVALUE_AUTO(end, YGNodeStyleSetMargin, node, YGEdgeEnd); } @@ -135,15 +140,18 @@ static void RCTProcessMetaPropsMargin(const YGValue metaProps[META_PROP_COUNT], RCT_SET_YGVALUE_AUTO(metaProps[META_PROP_ALL], YGNodeStyleSetMargin, node, YGEdgeAll); } -static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], YGNodeRef node) { +static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], YGNodeRef node) +{ if (![[RCTI18nUtil sharedInstance] doLeftAndRightSwapInRTL]) { YGNodeStyleSetBorder(node, YGEdgeStart, metaProps[META_PROP_START].value); YGNodeStyleSetBorder(node, YGEdgeEnd, metaProps[META_PROP_END].value); YGNodeStyleSetBorder(node, YGEdgeLeft, metaProps[META_PROP_LEFT].value); YGNodeStyleSetBorder(node, YGEdgeRight, metaProps[META_PROP_RIGHT].value); } else { - const float start = YGFloatIsUndefined(metaProps[META_PROP_START].value) ? metaProps[META_PROP_LEFT].value : metaProps[META_PROP_START].value; - const float end = YGFloatIsUndefined(metaProps[META_PROP_END].value) ? metaProps[META_PROP_RIGHT].value : metaProps[META_PROP_END].value; + const float start = YGFloatIsUndefined(metaProps[META_PROP_START].value) ? metaProps[META_PROP_LEFT].value + : metaProps[META_PROP_START].value; + const float end = YGFloatIsUndefined(metaProps[META_PROP_END].value) ? metaProps[META_PROP_RIGHT].value + : metaProps[META_PROP_END].value; YGNodeStyleSetBorder(node, YGEdgeStart, start); YGNodeStyleSetBorder(node, YGEdgeEnd, end); } @@ -194,8 +202,8 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], _reactSubviews = [NSMutableArray array]; _yogaNode = YGNodeNewWithConfig([[self class] yogaConfig]); - YGNodeSetContext(_yogaNode, (__bridge void *)self); - YGNodeSetPrintFunc(_yogaNode, RCTPrint); + YGNodeSetContext(_yogaNode, (__bridge void *)self); + YGNodeSetPrintFunc(_yogaNode, RCTPrint); } return self; } @@ -259,10 +267,8 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], { YGNodeRef yogaNode = _yogaNode; - CGSize oldMinimumSize = (CGSize){ - RCTCoreGraphicsFloatFromYogaValue(YGNodeStyleGetMinWidth(yogaNode), 0.0), - RCTCoreGraphicsFloatFromYogaValue(YGNodeStyleGetMinHeight(yogaNode), 0.0) - }; + CGSize oldMinimumSize = (CGSize){RCTCoreGraphicsFloatFromYogaValue(YGNodeStyleGetMinWidth(yogaNode), 0.0), + RCTCoreGraphicsFloatFromYogaValue(YGNodeStyleGetMinHeight(yogaNode), 0.0)}; if (!CGSizeEqualToSize(oldMinimumSize, minimumSize)) { YGNodeStyleSetMinWidth(yogaNode, RCTYogaFloatFromCoreGraphicsFloat(minimumSize.width)); @@ -270,11 +276,10 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], } YGNodeCalculateLayout( - yogaNode, - RCTYogaFloatFromCoreGraphicsFloat(maximumSize.width), - RCTYogaFloatFromCoreGraphicsFloat(maximumSize.height), - RCTYogaLayoutDirectionFromUIKitLayoutDirection(layoutDirection) - ); + yogaNode, + RCTYogaFloatFromCoreGraphicsFloat(maximumSize.width), + RCTYogaFloatFromCoreGraphicsFloat(maximumSize.height), + RCTYogaLayoutDirectionFromUIKitLayoutDirection(layoutDirection)); RCTAssert(!YGNodeIsDirty(yogaNode), @"Attempt to get layout metrics from dirtied Yoga node."); @@ -289,14 +294,12 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], layoutContext.absolutePosition.x += layoutMetrics.frame.origin.x; layoutContext.absolutePosition.y += layoutMetrics.frame.origin.y; - [self layoutWithMetrics:layoutMetrics - layoutContext:layoutContext]; + [self layoutWithMetrics:layoutMetrics layoutContext:layoutContext]; [self layoutSubviewsWithContext:layoutContext]; } -- (void)layoutWithMetrics:(RCTLayoutMetrics)layoutMetrics - layoutContext:(RCTLayoutContext)layoutContext +- (void)layoutWithMetrics:(RCTLayoutMetrics)layoutMetrics layoutContext:(RCTLayoutContext)layoutContext { if (!RCTLayoutMetricsEqualToLayoutMetrics(self.layoutMetrics, layoutMetrics)) { self.layoutMetrics = layoutMetrics; @@ -328,8 +331,7 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], layoutContext.absolutePosition.x += childLayoutMetrics.frame.origin.x; layoutContext.absolutePosition.y += childLayoutMetrics.frame.origin.y; - [childShadowView layoutWithMetrics:childLayoutMetrics - layoutContext:layoutContext]; + [childShadowView layoutWithMetrics:childLayoutMetrics layoutContext:layoutContext]; // Recursive call. [childShadowView layoutSubviewsWithContext:layoutContext]; @@ -349,15 +351,14 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], YGNodeStyleSetMaxHeight(constraintYogaNode, RCTYogaFloatFromCoreGraphicsFloat(maximumSize.height)); YGNodeCalculateLayout( - constraintYogaNode, - YGUndefined, - YGUndefined, - RCTYogaLayoutDirectionFromUIKitLayoutDirection(self.layoutMetrics.layoutDirection) - ); + constraintYogaNode, + YGUndefined, + YGUndefined, + RCTYogaLayoutDirectionFromUIKitLayoutDirection(self.layoutMetrics.layoutDirection)); CGSize measuredSize = (CGSize){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetWidth(constraintYogaNode)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetHeight(constraintYogaNode)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetWidth(constraintYogaNode)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetHeight(constraintYogaNode)), }; YGNodeRemoveChild(constraintYogaNode, clonedYogaNode); @@ -384,7 +385,11 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], - (NSString *)description { NSString *description = super.description; - description = [[description substringToIndex:description.length - 1] stringByAppendingFormat:@"; viewName: %@; reactTag: %@; frame: %@>", self.viewName, self.reactTag, NSStringFromCGRect(self.layoutMetrics.frame)]; + description = [[description substringToIndex:description.length - 1] + stringByAppendingFormat:@"; viewName: %@; reactTag: %@; frame: %@>", + self.viewName, + self.reactTag, + NSStringFromCGRect(self.layoutMetrics.frame)]; return description; } @@ -411,16 +416,16 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], // Margin -#define RCT_MARGIN_PROPERTY(prop, metaProp) \ -- (void)setMargin##prop:(YGValue)value \ -{ \ - _marginMetaProps[META_PROP_##metaProp] = value; \ - _recomputeMargin = YES; \ -} \ -- (YGValue)margin##prop \ -{ \ - return _marginMetaProps[META_PROP_##metaProp]; \ -} +#define RCT_MARGIN_PROPERTY(prop, metaProp) \ + -(void)setMargin##prop : (YGValue)value \ + { \ + _marginMetaProps[META_PROP_##metaProp] = value; \ + _recomputeMargin = YES; \ + } \ + -(YGValue)margin##prop \ + { \ + return _marginMetaProps[META_PROP_##metaProp]; \ + } RCT_MARGIN_PROPERTY(, ALL) RCT_MARGIN_PROPERTY(Vertical, VERTICAL) @@ -434,16 +439,16 @@ RCT_MARGIN_PROPERTY(End, END) // Padding -#define RCT_PADDING_PROPERTY(prop, metaProp) \ -- (void)setPadding##prop:(YGValue)value \ -{ \ - _paddingMetaProps[META_PROP_##metaProp] = value; \ - _recomputePadding = YES; \ -} \ -- (YGValue)padding##prop \ -{ \ - return _paddingMetaProps[META_PROP_##metaProp]; \ -} +#define RCT_PADDING_PROPERTY(prop, metaProp) \ + -(void)setPadding##prop : (YGValue)value \ + { \ + _paddingMetaProps[META_PROP_##metaProp] = value; \ + _recomputePadding = YES; \ + } \ + -(YGValue)padding##prop \ + { \ + return _paddingMetaProps[META_PROP_##metaProp]; \ + } RCT_PADDING_PROPERTY(, ALL) RCT_PADDING_PROPERTY(Vertical, VERTICAL) @@ -457,16 +462,16 @@ RCT_PADDING_PROPERTY(End, END) // Border -#define RCT_BORDER_PROPERTY(prop, metaProp) \ -- (void)setBorder##prop##Width:(float)value \ -{ \ - _borderMetaProps[META_PROP_##metaProp].value = value; \ - _recomputeBorder = YES; \ -} \ -- (float)border##prop##Width \ -{ \ - return _borderMetaProps[META_PROP_##metaProp].value; \ -} +#define RCT_BORDER_PROPERTY(prop, metaProp) \ + -(void)setBorder##prop##Width : (float)value \ + { \ + _borderMetaProps[META_PROP_##metaProp].value = value; \ + _recomputeBorder = YES; \ + } \ + -(float)border##prop##Width \ + { \ + return _borderMetaProps[META_PROP_##metaProp].value; \ + } RCT_BORDER_PROPERTY(, ALL) RCT_BORDER_PROPERTY(Top, TOP) @@ -477,25 +482,25 @@ RCT_BORDER_PROPERTY(Start, START) RCT_BORDER_PROPERTY(End, END) // Dimensions -#define RCT_DIMENSION_PROPERTY(setProp, getProp, cssProp) \ -- (void)set##setProp:(YGValue)value \ -{ \ - RCT_SET_YGVALUE_AUTO(value, YGNodeStyleSet##cssProp, _yogaNode); \ -} \ -- (YGValue)getProp \ -{ \ - return YGNodeStyleGet##cssProp(_yogaNode); \ -} +#define RCT_DIMENSION_PROPERTY(setProp, getProp, cssProp) \ + -(void)set##setProp : (YGValue)value \ + { \ + RCT_SET_YGVALUE_AUTO(value, YGNodeStyleSet##cssProp, _yogaNode); \ + } \ + -(YGValue)getProp \ + { \ + return YGNodeStyleGet##cssProp(_yogaNode); \ + } -#define RCT_MIN_MAX_DIMENSION_PROPERTY(setProp, getProp, cssProp) \ -- (void)set##setProp:(YGValue)value \ -{ \ - RCT_SET_YGVALUE(value, YGNodeStyleSet##cssProp, _yogaNode); \ -} \ -- (YGValue)getProp \ -{ \ - return YGNodeStyleGet##cssProp(_yogaNode); \ -} +#define RCT_MIN_MAX_DIMENSION_PROPERTY(setProp, getProp, cssProp) \ + -(void)set##setProp : (YGValue)value \ + { \ + RCT_SET_YGVALUE(value, YGNodeStyleSet##cssProp, _yogaNode); \ + } \ + -(YGValue)getProp \ + { \ + return YGNodeStyleGet##cssProp(_yogaNode); \ + } RCT_DIMENSION_PROPERTY(Width, width, Width) RCT_DIMENSION_PROPERTY(Height, height, Height) @@ -506,16 +511,15 @@ RCT_MIN_MAX_DIMENSION_PROPERTY(MaxHeight, maxHeight, MaxHeight) // Position -#define RCT_POSITION_PROPERTY(setProp, getProp, edge) \ -- (void)set##setProp:(YGValue)value \ -{ \ - RCT_SET_YGVALUE(value, YGNodeStyleSetPosition, _yogaNode, edge); \ -} \ -- (YGValue)getProp \ -{ \ - return YGNodeStyleGetPosition(_yogaNode, edge); \ -} - +#define RCT_POSITION_PROPERTY(setProp, getProp, edge) \ + -(void)set##setProp : (YGValue)value \ + { \ + RCT_SET_YGVALUE(value, YGNodeStyleSetPosition, _yogaNode, edge); \ + } \ + -(YGValue)getProp \ + { \ + return YGNodeStyleGetPosition(_yogaNode, edge); \ + } RCT_POSITION_PROPERTY(Top, top, YGEdgeTop) RCT_POSITION_PROPERTY(Bottom, bottom, YGEdgeBottom) @@ -551,10 +555,7 @@ RCT_POSITION_PROPERTY(End, end, YGEdgeEnd) YGValue width = YGNodeStyleGetWidth(_yogaNode); YGValue height = YGNodeStyleGetHeight(_yogaNode); - return CGSizeMake( - width.unit == YGUnitPoint ? width.value : NAN, - height.unit == YGUnitPoint ? height.value : NAN - ); + return CGSizeMake(width.unit == YGUnitPoint ? width.value : NAN, height.unit == YGUnitPoint ? height.value : NAN); } - (void)setSize:(CGSize)size @@ -565,7 +566,8 @@ RCT_POSITION_PROPERTY(End, end, YGEdgeEnd) // IntrinsicContentSize -static inline YGSize RCTShadowViewMeasure(YGNodeRef node, float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode) +static inline YGSize +RCTShadowViewMeasure(YGNodeRef node, float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode) { RCTShadowView *shadowView = (__bridge RCTShadowView *)YGNodeGetContext(node); @@ -640,14 +642,14 @@ static inline YGSize RCTShadowViewMeasure(YGNodeRef node, float width, YGMeasure } #define RCT_STYLE_PROPERTY(setProp, getProp, cssProp, type) \ -- (void)set##setProp:(type)value \ -{ \ - YGNodeStyleSet##cssProp(_yogaNode, value); \ -} \ -- (type)getProp \ -{ \ - return YGNodeStyleGet##cssProp(_yogaNode); \ -} + -(void)set##setProp : (type)value \ + { \ + YGNodeStyleSet##cssProp(_yogaNode, value); \ + } \ + -(type)getProp \ + { \ + return YGNodeStyleGet##cssProp(_yogaNode); \ + } RCT_STYLE_PROPERTY(Flex, flex, Flex, float) RCT_STYLE_PROPERTY(FlexGrow, flexGrow, FlexGrow, float) diff --git a/React/Views/RCTSlider.h b/React/Views/RCTSlider.h index 4f7121cc39a..355cc362fcb 100644 --- a/React/Views/RCTSlider.h +++ b/React/Views/RCTSlider.h @@ -23,5 +23,4 @@ @property (nonatomic, strong) UIImage *thumbImage; - @end diff --git a/React/Views/RCTSlider.m b/React/Views/RCTSlider.m index 43d8663ef25..29918c7b889 100644 --- a/React/Views/RCTSlider.m +++ b/React/Views/RCTSlider.m @@ -7,8 +7,7 @@ #import "RCTSlider.h" -@implementation RCTSlider -{ +@implementation RCTSlider { float _unclippedValue; } @@ -35,12 +34,10 @@ if (trackImage != _trackImage) { _trackImage = trackImage; CGFloat width = trackImage.size.width / 2; - UIImage *minimumTrackImage = [trackImage resizableImageWithCapInsets:(UIEdgeInsets){ - 0, width, 0, width - } resizingMode:UIImageResizingModeStretch]; - UIImage *maximumTrackImage = [trackImage resizableImageWithCapInsets:(UIEdgeInsets){ - 0, width, 0, width - } resizingMode:UIImageResizingModeStretch]; + UIImage *minimumTrackImage = [trackImage resizableImageWithCapInsets:(UIEdgeInsets){0, width, 0, width} + resizingMode:UIImageResizingModeStretch]; + UIImage *maximumTrackImage = [trackImage resizableImageWithCapInsets:(UIEdgeInsets){0, width, 0, width} + resizingMode:UIImageResizingModeStretch]; [self setMinimumTrackImage:minimumTrackImage forState:UIControlStateNormal]; [self setMaximumTrackImage:maximumTrackImage forState:UIControlStateNormal]; } @@ -49,9 +46,9 @@ - (void)setMinimumTrackImage:(UIImage *)minimumTrackImage { _trackImage = nil; - minimumTrackImage = [minimumTrackImage resizableImageWithCapInsets:(UIEdgeInsets){ - 0, minimumTrackImage.size.width, 0, 0 - } resizingMode:UIImageResizingModeStretch]; + minimumTrackImage = + [minimumTrackImage resizableImageWithCapInsets:(UIEdgeInsets){0, minimumTrackImage.size.width, 0, 0} + resizingMode:UIImageResizingModeStretch]; [self setMinimumTrackImage:minimumTrackImage forState:UIControlStateNormal]; } @@ -63,9 +60,9 @@ - (void)setMaximumTrackImage:(UIImage *)maximumTrackImage { _trackImage = nil; - maximumTrackImage = [maximumTrackImage resizableImageWithCapInsets:(UIEdgeInsets){ - 0, 0, 0, maximumTrackImage.size.width - } resizingMode:UIImageResizingModeStretch]; + maximumTrackImage = + [maximumTrackImage resizableImageWithCapInsets:(UIEdgeInsets){0, 0, 0, maximumTrackImage.size.width} + resizingMode:UIImageResizingModeStretch]; [self setMaximumTrackImage:maximumTrackImage forState:UIControlStateNormal]; } @@ -89,7 +86,7 @@ [super accessibilityIncrement]; if (_onSlidingComplete) { _onSlidingComplete(@{ - @"value": @(self.value), + @"value" : @(self.value), }); } } @@ -99,7 +96,7 @@ [super accessibilityDecrement]; if (_onSlidingComplete) { _onSlidingComplete(@{ - @"value": @(self.value), + @"value" : @(self.value), }); } } diff --git a/React/Views/RCTSliderManager.m b/React/Views/RCTSliderManager.m index 51230e6df06..a3a67959575 100644 --- a/React/Views/RCTSliderManager.m +++ b/React/Views/RCTSliderManager.m @@ -19,12 +19,10 @@ RCT_EXPORT_MODULE() - (UIView *)view { RCTSlider *slider = [RCTSlider new]; - [slider addTarget:self action:@selector(sliderValueChanged:) - forControlEvents:UIControlEventValueChanged]; - [slider addTarget:self action:@selector(sliderTouchEnd:) - forControlEvents:(UIControlEventTouchUpInside | - UIControlEventTouchUpOutside | - UIControlEventTouchCancel)]; + [slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged]; + [slider addTarget:self + action:@selector(sliderTouchEnd:) + forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel)]; return slider; } @@ -32,15 +30,11 @@ static void RCTSendSliderEvent(RCTSlider *sender, BOOL continuous) { float value = sender.value; - if (sender.step > 0 && - sender.step <= (sender.maximumValue - sender.minimumValue)) { - + if (sender.step > 0 && sender.step <= (sender.maximumValue - sender.minimumValue)) { value = - MAX(sender.minimumValue, - MIN(sender.maximumValue, - sender.minimumValue + round((sender.value - sender.minimumValue) / sender.step) * sender.step - ) - ); + MAX(sender.minimumValue, + MIN(sender.maximumValue, + sender.minimumValue + round((sender.value - sender.minimumValue) / sender.step) * sender.step)); [sender setValue:value animated:YES]; } @@ -48,13 +42,13 @@ static void RCTSendSliderEvent(RCTSlider *sender, BOOL continuous) if (continuous) { if (sender.onValueChange && sender.lastValue != value) { sender.onValueChange(@{ - @"value": @(value), + @"value" : @(value), }); } } else { if (sender.onSlidingComplete) { sender.onSlidingComplete(@{ - @"value": @(value), + @"value" : @(value), }); } } diff --git a/React/Views/RCTSwitch.m b/React/Views/RCTSwitch.m index f0902f964a7..80475480d13 100644 --- a/React/Views/RCTSwitch.m +++ b/React/Views/RCTSwitch.m @@ -12,7 +12,8 @@ @implementation RCTSwitch -- (void)setOn:(BOOL)on animated:(BOOL)animated { +- (void)setOn:(BOOL)on animated:(BOOL)animated +{ _wasOn = on; [super setOn:on animated:animated]; } diff --git a/React/Views/RCTSwitchManager.m b/React/Views/RCTSwitchManager.m index 9aa758519b6..04f7006c74f 100644 --- a/React/Views/RCTSwitchManager.m +++ b/React/Views/RCTSwitchManager.m @@ -7,11 +7,11 @@ #import "RCTSwitchManager.h" +#import #import "RCTBridge.h" #import "RCTEventDispatcher.h" #import "RCTSwitch.h" #import "UIView+React.h" -#import @implementation RCTSwitchManager @@ -20,9 +20,7 @@ RCT_EXPORT_MODULE() - (UIView *)view { RCTSwitch *switcher = [RCTSwitch new]; - [switcher addTarget:self - action:@selector(onChange:) - forControlEvents:UIControlEventValueChanged]; + [switcher addTarget:self action:@selector(onChange:) forControlEvents:UIControlEventValueChanged]; return switcher; } @@ -30,7 +28,7 @@ RCT_EXPORT_MODULE() { if (sender.wasOn != sender.on) { if (sender.onChange) { - sender.onChange(@{ @"value": @(sender.on) }); + sender.onChange(@{@"value" : @(sender.on)}); } sender.wasOn = sender.on; } @@ -40,7 +38,7 @@ RCT_EXPORT_METHOD(setValue : (nonnull NSNumber *)viewTag toValue : (BOOL)value) { [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[viewTag]; - + if ([view isKindOfClass:[UISwitch class]]) { [(UISwitch *)view setOn:value animated:NO]; } else { diff --git a/React/Views/RCTTVView.m b/React/Views/RCTTVView.m index 2809714166a..6f06b9a1f41 100644 --- a/React/Views/RCTTVView.m +++ b/React/Views/RCTTVView.m @@ -19,8 +19,7 @@ #import "RCTView.h" #import "UIView+React.h" -@implementation RCTTVView -{ +@implementation RCTTVView { UITapGestureRecognizer *_selectRecognizer; } @@ -29,14 +28,14 @@ if (self = [super initWithFrame:frame]) { dispatch_once(&onceToken, ^{ defaultTVParallaxProperties = @{ - @"enabled": @YES, - @"shiftDistanceX": @2.0f, - @"shiftDistanceY": @2.0f, - @"tiltAngle": @0.05f, - @"magnification": @1.0f, - @"pressMagnification": @1.0f, - @"pressDuration": @0.3f, - @"pressDelay": @0.0f + @"enabled" : @YES, + @"shiftDistanceX" : @2.0f, + @"shiftDistanceY" : @2.0f, + @"tiltAngle" : @0.05f, + @"magnification" : @1.0f, + @"pressMagnification" : @1.0f, + @"pressDuration" : @0.3f, + @"pressDelay" : @0.0f }; }); self.tvParallaxProperties = defaultTVParallaxProperties; @@ -45,10 +44,11 @@ return self; } -static NSDictionary* defaultTVParallaxProperties = nil; +static NSDictionary *defaultTVParallaxProperties = nil; static dispatch_once_t onceToken; -- (void)setTvParallaxProperties:(NSDictionary *)tvParallaxProperties { +- (void)setTvParallaxProperties:(NSDictionary *)tvParallaxProperties +{ if (_tvParallaxProperties == nil) { _tvParallaxProperties = [defaultTVParallaxProperties copy]; return; @@ -63,19 +63,19 @@ static dispatch_once_t onceToken; _tvParallaxProperties = [newParallaxProperties copy]; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : unused) -- (void)setIsTVSelectable:(BOOL)isTVSelectable { +- (void)setIsTVSelectable:(BOOL)isTVSelectable +{ self->_isTVSelectable = isTVSelectable; if (isTVSelectable) { - UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] - initWithTarget:self - action:@selector(handleSelect:)]; - recognizer.allowedPressTypes = @[@(UIPressTypeSelect)]; + UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self + action:@selector(handleSelect:)]; + recognizer.allowedPressTypes = @[ @(UIPressTypeSelect) ]; _selectRecognizer = recognizer; [self addGestureRecognizer:_selectRecognizer]; } else { - if(_selectRecognizer) { + if (_selectRecognizer) { [self removeGestureRecognizer:_selectRecognizer]; } } @@ -83,37 +83,38 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) - (void)handleSelect:(__unused UIGestureRecognizer *)r { - if ([self.tvParallaxProperties[@"enabled"] boolValue] == YES) { + if ([self.tvParallaxProperties[@"enabled"] boolValue] == YES) { float magnification = [self.tvParallaxProperties[@"magnification"] floatValue]; float pressMagnification = [self.tvParallaxProperties[@"pressMagnification"] floatValue]; - - // Duration of press animation - float pressDuration = [self.tvParallaxProperties[@"pressDuration"] floatValue]; - - // Delay of press animation - float pressDelay = [self.tvParallaxProperties[@"pressDelay"] floatValue]; - + + // Duration of press animation + float pressDuration = [self.tvParallaxProperties[@"pressDuration"] floatValue]; + + // Delay of press animation + float pressDelay = [self.tvParallaxProperties[@"pressDelay"] floatValue]; + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:pressDelay]]; - - [UIView animateWithDuration:(pressDuration/2) - animations:^{ - self.transform = CGAffineTransformMakeScale(pressMagnification, pressMagnification); - } - completion:^(__unused BOOL finished1){ - [UIView animateWithDuration:(pressDuration/2) - animations:^{ - self.transform = CGAffineTransformMakeScale(magnification, magnification); - } - completion:^(__unused BOOL finished2) { - [[NSNotificationCenter defaultCenter] postNotificationName:RCTTVNavigationEventNotification - object:@{@"eventType":@"select",@"tag":self.reactTag}]; - }]; - }]; - - } else { - [[NSNotificationCenter defaultCenter] postNotificationName:RCTTVNavigationEventNotification - object:@{@"eventType":@"select",@"tag":self.reactTag}]; - } + + [UIView animateWithDuration:(pressDuration / 2) + animations:^{ + self.transform = CGAffineTransformMakeScale(pressMagnification, pressMagnification); + } + completion:^(__unused BOOL finished1) { + [UIView animateWithDuration:(pressDuration / 2) + animations:^{ + self.transform = CGAffineTransformMakeScale(magnification, magnification); + } + completion:^(__unused BOOL finished2) { + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTTVNavigationEventNotification + object:@{@"eventType" : @"select", @"tag" : self.reactTag}]; + }]; + }]; + + } else { + [[NSNotificationCenter defaultCenter] postNotificationName:RCTTVNavigationEventNotification + object:@{@"eventType" : @"select", @"tag" : self.reactTag}]; + } } - (BOOL)isUserInteractionEnabled @@ -133,26 +134,26 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) CGFloat const shiftDistanceY = [self.tvParallaxProperties[@"shiftDistanceY"] floatValue]; // Make horizontal movements shift the centre left and right - UIInterpolatingMotionEffect *xShift = [[UIInterpolatingMotionEffect alloc] - initWithKeyPath:@"center.x" - type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; - xShift.minimumRelativeValue = @( shiftDistanceX * -1.0f); - xShift.maximumRelativeValue = @( shiftDistanceX); + UIInterpolatingMotionEffect *xShift = + [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" + type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; + xShift.minimumRelativeValue = @(shiftDistanceX * -1.0f); + xShift.maximumRelativeValue = @(shiftDistanceX); // Make vertical movements shift the centre up and down - UIInterpolatingMotionEffect *yShift = [[UIInterpolatingMotionEffect alloc] - initWithKeyPath:@"center.y" - type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; - yShift.minimumRelativeValue = @( shiftDistanceY * -1.0f); - yShift.maximumRelativeValue = @( shiftDistanceY); + UIInterpolatingMotionEffect *yShift = + [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" + type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; + yShift.minimumRelativeValue = @(shiftDistanceY * -1.0f); + yShift.maximumRelativeValue = @(shiftDistanceY); // Size of tilt movements CGFloat const tiltAngle = [self.tvParallaxProperties[@"tiltAngle"] floatValue]; // Now make horizontal movements effect a rotation about the Y axis for side-to-side rotation. - UIInterpolatingMotionEffect *xTilt = [[UIInterpolatingMotionEffect alloc] - initWithKeyPath:@"layer.transform" - type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; + UIInterpolatingMotionEffect *xTilt = + [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"layer.transform" + type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; // CATransform3D value for minimumRelativeValue CATransform3D transMinimumTiltAboutY = CATransform3DIdentity; @@ -165,13 +166,13 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) transMaximumTiltAboutY = CATransform3DRotate(transMaximumTiltAboutY, tiltAngle, 0, 1, 0); // Set the transform property boundaries for the interpolation - xTilt.minimumRelativeValue = [NSValue valueWithCATransform3D: transMinimumTiltAboutY]; - xTilt.maximumRelativeValue = [NSValue valueWithCATransform3D: transMaximumTiltAboutY]; + xTilt.minimumRelativeValue = [NSValue valueWithCATransform3D:transMinimumTiltAboutY]; + xTilt.maximumRelativeValue = [NSValue valueWithCATransform3D:transMaximumTiltAboutY]; // Now make vertical movements effect a rotation about the X axis for up and down rotation. - UIInterpolatingMotionEffect *yTilt = [[UIInterpolatingMotionEffect alloc] - initWithKeyPath:@"layer.transform" - type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; + UIInterpolatingMotionEffect *yTilt = + [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"layer.transform" + type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; // CATransform3D value for minimumRelativeValue CATransform3D transMinimumTiltAboutX = CATransform3DIdentity; @@ -184,42 +185,52 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) transMaximumTiltAboutX = CATransform3DRotate(transMaximumTiltAboutX, tiltAngle, 1, 0, 0); // Set the transform property boundaries for the interpolation - yTilt.minimumRelativeValue = [NSValue valueWithCATransform3D: transMinimumTiltAboutX]; - yTilt.maximumRelativeValue = [NSValue valueWithCATransform3D: transMaximumTiltAboutX]; + yTilt.minimumRelativeValue = [NSValue valueWithCATransform3D:transMinimumTiltAboutX]; + yTilt.maximumRelativeValue = [NSValue valueWithCATransform3D:transMaximumTiltAboutX]; // Add all of the motion effects to this group - self.motionEffects = @[xShift, yShift, xTilt, yTilt]; + self.motionEffects = @[ xShift, yShift, xTilt, yTilt ]; float magnification = [self.tvParallaxProperties[@"magnification"] floatValue]; - [UIView animateWithDuration:0.2 animations:^{ - self.transform = CGAffineTransformMakeScale(magnification, magnification); - }]; + [UIView animateWithDuration:0.2 + animations:^{ + self.transform = CGAffineTransformMakeScale(magnification, magnification); + }]; } -- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator +- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context + withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator { - if (context.nextFocusedView == self && self.isTVSelectable ) { + if (context.nextFocusedView == self && self.isTVSelectable) { [self becomeFirstResponder]; - [coordinator addCoordinatedAnimations:^(void){ - if([self.tvParallaxProperties[@"enabled"] boolValue]) { - [self addParallaxMotionEffects]; - } - [[NSNotificationCenter defaultCenter] postNotificationName:RCTTVNavigationEventNotification - object:@{@"eventType":@"focus",@"tag":self.reactTag}]; - } completion:^(void){}]; + [coordinator + addCoordinatedAnimations:^(void) { + if ([self.tvParallaxProperties[@"enabled"] boolValue]) { + [self addParallaxMotionEffects]; + } + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTTVNavigationEventNotification + object:@{@"eventType" : @"focus", @"tag" : self.reactTag}]; + } + completion:^(void){ + }]; } else { - [coordinator addCoordinatedAnimations:^(void){ - [[NSNotificationCenter defaultCenter] postNotificationName:RCTTVNavigationEventNotification - object:@{@"eventType":@"blur",@"tag":self.reactTag}]; - [UIView animateWithDuration:0.2 animations:^{ - self.transform = CGAffineTransformMakeScale(1, 1); - }]; + [coordinator + addCoordinatedAnimations:^(void) { + [[NSNotificationCenter defaultCenter] postNotificationName:RCTTVNavigationEventNotification + object:@{@"eventType" : @"blur", @"tag" : self.reactTag}]; + [UIView animateWithDuration:0.2 + animations:^{ + self.transform = CGAffineTransformMakeScale(1, 1); + }]; - for (UIMotionEffect *effect in [self.motionEffects copy]){ - [self removeMotionEffect:effect]; - } - } completion:^(void){}]; + for (UIMotionEffect *effect in [self.motionEffects copy]) { + [self removeMotionEffect:effect]; + } + } + completion:^(void){ + }]; [self resignFirstResponder]; } } @@ -233,7 +244,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) while (![rootview isReactRootView] && rootview != nil) { rootview = [rootview superview]; } - if (rootview == nil) return; + if (rootview == nil) + return; rootview = [rootview superview]; diff --git a/React/Views/RCTView.m b/React/Views/RCTView.m index a4f992712d7..a5117bedf02 100644 --- a/React/Views/RCTView.m +++ b/React/Views/RCTView.m @@ -10,10 +10,10 @@ #import "RCTAutoInsetsProtocol.h" #import "RCTBorderDrawing.h" #import "RCTConvert.h" +#import "RCTI18nUtil.h" #import "RCTLog.h" #import "RCTUtils.h" #import "UIView+React.h" -#import "RCTI18nUtil.h" UIAccessibilityTraits const SwitchAccessibilityTrait = 0x20000000000001; @@ -98,8 +98,7 @@ static NSString *RCTRecursiveAccessibilityLabel(UIView *view) return str.length == 0 ? nil : str; } -@implementation RCTView -{ +@implementation RCTView { UIColor *_backgroundColor; NSMutableDictionary *accessibilityActionsNameMap; NSMutableDictionary *accessibilityActionsLabelMap; @@ -132,7 +131,7 @@ static NSString *RCTRecursiveAccessibilityLabel(UIView *view) return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : unused) - (void)setReactLayoutDirection:(UIUserInterfaceLayoutDirection)layoutDirection { @@ -142,10 +141,9 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) } if ([self respondsToSelector:@selector(setSemanticContentAttribute:)]) { - self.semanticContentAttribute = - layoutDirection == UIUserInterfaceLayoutDirectionLeftToRight ? - UISemanticContentAttributeForceLeftToRight : - UISemanticContentAttributeForceRightToLeft; + self.semanticContentAttribute = layoutDirection == UIUserInterfaceLayoutDirectionLeftToRight + ? UISemanticContentAttributeForceLeftToRight + : UISemanticContentAttributeForceRightToLeft; } } @@ -158,7 +156,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) return RCTRecursiveAccessibilityLabel(self); } -- (NSArray *)accessibilityCustomActions +- (NSArray *)accessibilityCustomActions { if (!self.accessibilityActions.count) { return nil; @@ -173,9 +171,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) } if (action[@"label"]) { accessibilityActionsLabelMap[action[@"label"]] = action; - [actions addObject:[[UIAccessibilityCustomAction alloc] initWithName:action[@"label"] - target:self - selector:@selector(didActivateAccessibilityCustomAction:)]]; + [actions addObject:[[UIAccessibilityCustomAction alloc] + initWithName:action[@"label"] + target:self + selector:@selector(didActivateAccessibilityCustomAction:)]]; } } @@ -188,14 +187,12 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) return NO; } - // iOS defines the name as the localized label, so use our map to convert this back to the non-localized action namne when passing to JS. This allows for standard action names across platforms. + // iOS defines the name as the localized label, so use our map to convert this back to the non-localized action namne + // when passing to JS. This allows for standard action names across platforms. NSDictionary *actionObject = accessibilityActionsLabelMap[action.name]; if (actionObject) { - _onAccessibilityAction(@{ - @"actionName": actionObject[@"name"], - @"actionTarget": self.reactTag - }); + _onAccessibilityAction(@{@"actionName" : actionObject[@"name"], @"actionTarget" : self.reactTag}); } return YES; } @@ -206,7 +203,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) static NSDictionary *rolesAndStatesDescription = nil; dispatch_once(&onceToken, ^{ - NSString *bundlePath = [[NSBundle mainBundle]pathForResource:@"AccessibilityResources" ofType:@"bundle"]; + NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"AccessibilityResources" ofType:@"bundle"]; NSBundle *bundle = [NSBundle bundleWithPath:bundlePath]; if (bundle) { @@ -221,30 +218,30 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) if (rolesAndStatesDescription == nil) { NSLog(@"Cannot load localized accessibility strings."); rolesAndStatesDescription = @{ - @"alert" : @"alert", - @"checkbox" : @"checkbox", - @"combobox" : @"combo box", - @"menu" : @"menu", - @"menubar" : @"menu bar", - @"menuitem" : @"menu item", - @"progressbar" : @"progress bar", - @"radio" : @"radio button", - @"radiogroup" : @"radio group", - @"scrollbar" : @"scroll bar", - @"spinbutton" : @"spin button", - @"switch" : @"switch", - @"tab" : @"tab", - @"tablist" : @"tab list", - @"timer" : @"timer", - @"toolbar" : @"tool bar", - @"checked" : @"checked", - @"unchecked" : @"not checked", - @"busy" : @"busy", - @"expanded" : @"expanded", - @"collapsed" : @"collapsed", - @"mixed": @"mixed", - }; - } + @"alert" : @"alert", + @"checkbox" : @"checkbox", + @"combobox" : @"combo box", + @"menu" : @"menu", + @"menubar" : @"menu bar", + @"menuitem" : @"menu item", + @"progressbar" : @"progress bar", + @"radio" : @"radio button", + @"radiogroup" : @"radio group", + @"scrollbar" : @"scroll bar", + @"spinbutton" : @"spin button", + @"switch" : @"switch", + @"tab" : @"tab", + @"tablist" : @"tab list", + @"timer" : @"timer", + @"toolbar" : @"tool bar", + @"checked" : @"checked", + @"unchecked" : @"not checked", + @"busy" : @"busy", + @"expanded" : @"expanded", + @"collapsed" : @"collapsed", + @"mixed" : @"mixed", + }; + } }); if ((self.accessibilityTraits & SwitchAccessibilityTrait) == SwitchAccessibilityTrait) { @@ -259,7 +256,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) } } NSMutableArray *valueComponents = [NSMutableArray new]; - NSString *roleDescription = self.accessibilityRole ? rolesAndStatesDescription[self.accessibilityRole]: nil; + NSString *roleDescription = self.accessibilityRole ? rolesAndStatesDescription[self.accessibilityRole] : nil; if (roleDescription) { [valueComponents addObject:roleDescription]; } @@ -282,7 +279,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) [valueComponents addObject:rolesAndStatesDescription[@"busy"]]; } } - + // handle accessibilityValue if (self.accessibilityValueInternal) { @@ -292,12 +289,11 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) id text = self.accessibilityValueInternal[@"text"]; if (text && [text isKindOfClass:[NSString class]]) { [valueComponents addObject:text]; - } else if ([min isKindOfClass:[NSNumber class]] && - [now isKindOfClass:[NSNumber class]] && - [max isKindOfClass:[NSNumber class]] && - ([min intValue] < [max intValue]) && + } else if ( + [min isKindOfClass:[NSNumber class]] && [now isKindOfClass:[NSNumber class]] && + [max isKindOfClass:[NSNumber class]] && ([min intValue] < [max intValue]) && ([min intValue] <= [now intValue] && [now intValue] <= [max intValue])) { - int val = ([now intValue]*100)/([max intValue]-[min intValue]); + int val = ([now intValue] * 100) / ([max intValue] - [min intValue]); [valueComponents addObject:[NSString stringWithFormat:@"%d percent", val]]; } } @@ -320,7 +316,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { BOOL canReceiveTouchEvents = ([self isUserInteractionEnabled] && ![self isHidden]); - if(!canReceiveTouchEvents) { + if (!canReceiveTouchEvents) { return nil; } @@ -388,13 +384,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) return NO; } -- (BOOL)performAccessibilityAction:(NSString *) name +- (BOOL)performAccessibilityAction:(NSString *)name { if (_onAccessibilityAction && accessibilityActionsNameMap[name]) { - _onAccessibilityAction(@{ - @"actionName" : name, - @"actionTarget" : self.reactTag - }); + _onAccessibilityAction(@{@"actionName" : name, @"actionTarget" : self.reactTag}); return YES; } return NO; @@ -492,10 +485,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) while (view) { UIViewController *controller = view.reactViewController; if (controller) { - return (UIEdgeInsets){ - controller.topLayoutGuide.length, 0, - controller.bottomLayoutGuide.length, 0 - }; + return (UIEdgeInsets){controller.topLayoutGuide.length, 0, controller.bottomLayoutGuide.length, 0}; } view = view.superview; } @@ -561,7 +551,6 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) } } else if (view.superview) { - // View is completely outside the clipRect, so unmount it [view removeFromSuperview]; } @@ -608,8 +597,9 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) } } -- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { - [super traitCollectionDidChange: previousTraitCollection]; +- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection +{ + [super traitCollectionDidChange:previousTraitCollection]; #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 if (@available(iOS 13.0, *)) { if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) { @@ -636,7 +626,8 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:unused) [self.layer setNeedsDisplay]; } -static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { +static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) +{ return x >= 0 ? x : defaultValue; }; @@ -652,22 +643,22 @@ static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { const CGFloat directionAwareBorderLeftWidth = isRTL ? borderEndWidth : borderStartWidth; const CGFloat directionAwareBorderRightWidth = isRTL ? borderStartWidth : borderEndWidth; - return (UIEdgeInsets) { - RCTDefaultIfNegativeTo(borderWidth, _borderTopWidth), - RCTDefaultIfNegativeTo(borderWidth, directionAwareBorderLeftWidth), - RCTDefaultIfNegativeTo(borderWidth, _borderBottomWidth), - RCTDefaultIfNegativeTo(borderWidth, directionAwareBorderRightWidth), + return (UIEdgeInsets){ + RCTDefaultIfNegativeTo(borderWidth, _borderTopWidth), + RCTDefaultIfNegativeTo(borderWidth, directionAwareBorderLeftWidth), + RCTDefaultIfNegativeTo(borderWidth, _borderBottomWidth), + RCTDefaultIfNegativeTo(borderWidth, directionAwareBorderRightWidth), }; } const CGFloat directionAwareBorderLeftWidth = isRTL ? _borderEndWidth : _borderStartWidth; const CGFloat directionAwareBorderRightWidth = isRTL ? _borderStartWidth : _borderEndWidth; - return (UIEdgeInsets) { - RCTDefaultIfNegativeTo(borderWidth, _borderTopWidth), - RCTDefaultIfNegativeTo(borderWidth, RCTDefaultIfNegativeTo(_borderLeftWidth, directionAwareBorderLeftWidth)), - RCTDefaultIfNegativeTo(borderWidth, _borderBottomWidth), - RCTDefaultIfNegativeTo(borderWidth, RCTDefaultIfNegativeTo(_borderRightWidth, directionAwareBorderRightWidth)), + return (UIEdgeInsets){ + RCTDefaultIfNegativeTo(borderWidth, _borderTopWidth), + RCTDefaultIfNegativeTo(borderWidth, RCTDefaultIfNegativeTo(_borderLeftWidth, directionAwareBorderLeftWidth)), + RCTDefaultIfNegativeTo(borderWidth, _borderBottomWidth), + RCTDefaultIfNegativeTo(borderWidth, RCTDefaultIfNegativeTo(_borderRightWidth, directionAwareBorderRightWidth)), }; } @@ -702,10 +693,14 @@ static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { const CGFloat directionAwareBottomLeftRadius = isRTL ? _borderBottomEndRadius : _borderBottomStartRadius; const CGFloat directionAwareBottomRightRadius = isRTL ? _borderBottomStartRadius : _borderBottomEndRadius; - topLeftRadius = RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderTopLeftRadius, directionAwareTopLeftRadius)); - topRightRadius = RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderTopRightRadius, directionAwareTopRightRadius)); - bottomLeftRadius = RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderBottomLeftRadius, directionAwareBottomLeftRadius)); - bottomRightRadius = RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderBottomRightRadius, directionAwareBottomRightRadius)); + topLeftRadius = + RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderTopLeftRadius, directionAwareTopLeftRadius)); + topRightRadius = + RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderTopRightRadius, directionAwareTopRightRadius)); + bottomLeftRadius = + RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderBottomLeftRadius, directionAwareBottomLeftRadius)); + bottomRightRadius = RCTDefaultIfNegativeTo( + radius, RCTDefaultIfNegativeTo(_borderBottomRightRadius, directionAwareBottomRightRadius)); } // Get scale factors required to prevent radii from overlapping @@ -717,10 +712,10 @@ static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { // Return scaled radii return (RCTCornerRadii){ - topLeftRadius * MIN(topScaleFactor, leftScaleFactor), - topRightRadius * MIN(topScaleFactor, rightScaleFactor), - bottomLeftRadius * MIN(bottomScaleFactor, leftScaleFactor), - bottomRightRadius * MIN(bottomScaleFactor, rightScaleFactor), + topLeftRadius * MIN(topScaleFactor, leftScaleFactor), + topRightRadius * MIN(topScaleFactor, rightScaleFactor), + bottomLeftRadius * MIN(bottomScaleFactor, leftScaleFactor), + bottomRightRadius * MIN(bottomScaleFactor, rightScaleFactor), }; } @@ -736,10 +731,10 @@ static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { const CGColorRef directionAwareBorderRightColor = isRTL ? borderStartColor : borderEndColor; return (RCTBorderColors){ - _borderTopColor ?: _borderColor, - directionAwareBorderLeftColor ?: _borderColor, - _borderBottomColor ?: _borderColor, - directionAwareBorderRightColor ?: _borderColor, + _borderTopColor ?: _borderColor, + directionAwareBorderLeftColor ?: _borderColor, + _borderBottomColor ?: _borderColor, + directionAwareBorderRightColor ?: _borderColor, }; } @@ -747,10 +742,10 @@ static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { const CGColorRef directionAwareBorderRightColor = isRTL ? _borderStartColor : _borderEndColor; return (RCTBorderColors){ - _borderTopColor ?: _borderColor, - directionAwareBorderLeftColor ?: _borderLeftColor ?: _borderColor, - _borderBottomColor ?: _borderColor, - directionAwareBorderRightColor ?: _borderRightColor ?: _borderColor, + _borderTopColor ?: _borderColor, + directionAwareBorderLeftColor ?: _borderLeftColor ?: _borderColor, + _borderBottomColor ?: _borderColor, + directionAwareBorderRightColor ?: _borderRightColor ?: _borderColor, }; } @@ -778,17 +773,14 @@ static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { const UIEdgeInsets borderInsets = [self bordersAsInsets]; const RCTBorderColors borderColors = [self borderColors]; - BOOL useIOSBorderRendering = - RCTCornerRadiiAreEqual(cornerRadii) && - RCTBorderInsetsAreEqual(borderInsets) && - RCTBorderColorsAreEqual(borderColors) && - _borderStyle == RCTBorderStyleSolid && + BOOL useIOSBorderRendering = RCTCornerRadiiAreEqual(cornerRadii) && RCTBorderInsetsAreEqual(borderInsets) && + RCTBorderColorsAreEqual(borderColors) && _borderStyle == RCTBorderStyleSolid && - // iOS draws borders in front of the content whereas CSS draws them behind - // the content. For this reason, only use iOS border drawing when clipping - // or when the border is hidden. + // iOS draws borders in front of the content whereas CSS draws them behind + // the content. For this reason, only use iOS border drawing when clipping + // or when the border is hidden. - (borderInsets.top == 0 || (borderColors.top && CGColorGetAlpha(borderColors.top) == 0) || self.clipsToBounds); + (borderInsets.top == 0 || (borderColors.top && CGColorGetAlpha(borderColors.top) == 0) || self.clipsToBounds); // iOS clips to the outside of the border, but CSS clips to the inside. To // solve this, we'll need to add a container view inside the main view to @@ -816,13 +808,8 @@ static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { return; } - UIImage *image = RCTGetBorderImage(_borderStyle, - layer.bounds.size, - cornerRadii, - borderInsets, - borderColors, - backgroundColor, - self.clipsToBounds); + UIImage *image = RCTGetBorderImage( + _borderStyle, layer.bounds.size, cornerRadii, borderInsets, borderColors, backgroundColor, self.clipsToBounds); layer.backgroundColor = NULL; @@ -836,11 +823,7 @@ static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x) { CGSize size = image.size; UIEdgeInsets insets = image.capInsets; CGRectMake( - insets.left / size.width, - insets.top / size.height, - (CGFloat)1.0 / size.width, - (CGFloat)1.0 / size.height - ); + insets.left / size.width, insets.top / size.height, (CGFloat)1.0 / size.width, (CGFloat)1.0 / size.height); }); layer.contents = (id)image.CGImage; @@ -867,7 +850,6 @@ static void RCTUpdateShadowPathForView(RCTView *view) { if (RCTLayerHasShadow(view.layer)) { if (CGColorGetAlpha(view.backgroundColor.CGColor) > 0.999) { - // If view has a solid background color, calculate shadow path from border const RCTCornerRadii cornerRadii = [view cornerRadii]; const RCTCornerInsets cornerInsets = RCTGetCornerInsets(cornerRadii, UIEdgeInsetsZero); @@ -876,14 +858,15 @@ static void RCTUpdateShadowPathForView(RCTView *view) CGPathRelease(shadowPath); } else { - // Can't accurately calculate box shadow, so fall back to pixel-based shadow view.layer.shadowPath = nil; - RCTLogAdvice(@"View #%@ of type %@ has a shadow set but cannot calculate " - "shadow efficiently. Consider setting a background color to " - "fix this, or apply the shadow to a more specific component.", - view.reactTag, [view class]); + RCTLogAdvice( + @"View #%@ of type %@ has a shadow set but cannot calculate " + "shadow efficiently. Consider setting a background color to " + "fix this, or apply the shadow to a more specific component.", + view.reactTag, + [view class]); } } } @@ -894,16 +877,14 @@ static void RCTUpdateShadowPathForView(RCTView *view) CGFloat cornerRadius = 0; if (self.clipsToBounds) { - const RCTCornerRadii cornerRadii = [self cornerRadii]; if (RCTCornerRadiiAreEqual(cornerRadii)) { - cornerRadius = cornerRadii.topLeft; } else { - CAShapeLayer *shapeLayer = [CAShapeLayer layer]; - CGPathRef path = RCTPathCreateWithRoundedRect(self.bounds, RCTGetCornerInsets(cornerRadii, UIEdgeInsetsZero), NULL); + CGPathRef path = + RCTPathCreateWithRoundedRect(self.bounds, RCTGetCornerInsets(cornerRadii, UIEdgeInsetsZero), NULL); shapeLayer.path = path; CGPathRelease(path); mask = shapeLayer; @@ -917,7 +898,7 @@ static void RCTUpdateShadowPathForView(RCTView *view) #pragma mark Border Color #define setBorderColor(side) \ - - (void)setBorder##side##Color:(CGColorRef)color \ + -(void)setBorder##side##Color : (CGColorRef)color \ { \ if (CGColorEqualToColor(_border##side##Color, color)) { \ return; \ @@ -927,71 +908,55 @@ static void RCTUpdateShadowPathForView(RCTView *view) [self.layer setNeedsDisplay]; \ } -setBorderColor() -setBorderColor(Top) -setBorderColor(Right) -setBorderColor(Bottom) -setBorderColor(Left) -setBorderColor(Start) -setBorderColor(End) +setBorderColor() setBorderColor(Top) setBorderColor(Right) setBorderColor(Bottom) setBorderColor(Left) + setBorderColor(Start) setBorderColor(End) #pragma mark - Border Width -#define setBorderWidth(side) \ - - (void)setBorder##side##Width:(CGFloat)width \ - { \ - if (_border##side##Width == width) { \ - return; \ - } \ - _border##side##Width = width; \ - [self.layer setNeedsDisplay]; \ +#define setBorderWidth(side) \ + -(void)setBorder##side##Width : (CGFloat)width \ + { \ + if (_border##side##Width == width) { \ + return; \ + } \ + _border##side##Width = width; \ + [self.layer setNeedsDisplay]; \ } -setBorderWidth() -setBorderWidth(Top) -setBorderWidth(Right) -setBorderWidth(Bottom) -setBorderWidth(Left) -setBorderWidth(Start) -setBorderWidth(End) + setBorderWidth() setBorderWidth(Top) setBorderWidth(Right) setBorderWidth(Bottom) setBorderWidth(Left) + setBorderWidth(Start) setBorderWidth(End) #pragma mark - Border Radius -#define setBorderRadius(side) \ - - (void)setBorder##side##Radius:(CGFloat)radius \ - { \ - if (_border##side##Radius == radius) { \ - return; \ - } \ - _border##side##Radius = radius; \ - [self.layer setNeedsDisplay]; \ +#define setBorderRadius(side) \ + -(void)setBorder##side##Radius : (CGFloat)radius \ + { \ + if (_border##side##Radius == radius) { \ + return; \ + } \ + _border##side##Radius = radius; \ + [self.layer setNeedsDisplay]; \ } -setBorderRadius() -setBorderRadius(TopLeft) -setBorderRadius(TopRight) -setBorderRadius(TopStart) -setBorderRadius(TopEnd) -setBorderRadius(BottomLeft) -setBorderRadius(BottomRight) -setBorderRadius(BottomStart) -setBorderRadius(BottomEnd) + setBorderRadius() setBorderRadius(TopLeft) setBorderRadius(TopRight) setBorderRadius(TopStart) + setBorderRadius(TopEnd) setBorderRadius(BottomLeft) setBorderRadius(BottomRight) + setBorderRadius(BottomStart) setBorderRadius(BottomEnd) #pragma mark - Border Style -#define setBorderStyle(side) \ - - (void)setBorder##side##Style:(RCTBorderStyle)style \ - { \ - if (_border##side##Style == style) { \ - return; \ - } \ - _border##side##Style = style; \ - [self.layer setNeedsDisplay]; \ +#define setBorderStyle(side) \ + -(void)setBorder##side##Style : (RCTBorderStyle)style \ + { \ + if (_border##side##Style == style) { \ + return; \ + } \ + _border##side##Style = style; \ + [self.layer setNeedsDisplay]; \ } -setBorderStyle() + setBorderStyle() -- (void)dealloc + - (void)dealloc { CGColorRelease(_borderColor); CGColorRelease(_borderTopColor); diff --git a/React/Views/RCTViewManager.h b/React/Views/RCTViewManager.h index 02d8aa2b1a4..b35ceb23f73 100644 --- a/React/Views/RCTViewManager.h +++ b/React/Views/RCTViewManager.h @@ -64,14 +64,20 @@ typedef void (^RCTViewManagerUIBlock)(RCTUIManager *uiManager, NSDictionary *)propConfig_##name RCT_DYNAMIC { return @[@#type]; } +#define RCT_EXPORT_VIEW_PROPERTY(name, type) \ + +(NSArray *)propConfig_##name RCT_DYNAMIC \ + { \ + return @[ @ #type ]; \ + } /** * This macro maps a named property to an arbitrary key path in the view. */ -#define RCT_REMAP_VIEW_PROPERTY(name, keyPath, type) \ -+ (NSArray *)propConfig_##name RCT_DYNAMIC { return @[@#type, @#keyPath]; } +#define RCT_REMAP_VIEW_PROPERTY(name, keyPath, type) \ + +(NSArray *)propConfig_##name RCT_DYNAMIC \ + { \ + return @[ @ #type, @ #keyPath ]; \ + } /** * This macro can be used when you need to provide custom logic for setting @@ -79,20 +85,26 @@ typedef void (^RCTViewManagerUIBlock)(RCTUIManager *uiManager, NSDictionary *)propConfigShadow_##name RCT_DYNAMIC { return @[@#type]; } +#define RCT_EXPORT_SHADOW_PROPERTY(name, type) \ + +(NSArray *)propConfigShadow_##name RCT_DYNAMIC \ + { \ + return @[ @ #type ]; \ + } /** * This macro maps a named property to an arbitrary key path in the shadow view. */ -#define RCT_REMAP_SHADOW_PROPERTY(name, keyPath, type) \ -+ (NSArray *)propConfigShadow_##name RCT_DYNAMIC { return @[@#type, @#keyPath]; } +#define RCT_REMAP_SHADOW_PROPERTY(name, keyPath, type) \ + +(NSArray *)propConfigShadow_##name RCT_DYNAMIC \ + { \ + return @[ @ #type, @ #keyPath ]; \ + } /** * This macro can be used when you need to provide custom logic for setting @@ -100,7 +112,7 @@ RCT_REMAP_VIEW_PROPERTY(name, __custom__, type) \ * refer to "json" and "view". */ #define RCT_CUSTOM_SHADOW_PROPERTY(name, type, viewClass) \ -RCT_REMAP_SHADOW_PROPERTY(name, __custom__, type) \ -- (void)set_##name:(id)json forShadowView:(viewClass *)view RCT_DYNAMIC + RCT_REMAP_SHADOW_PROPERTY(name, __custom__, type) \ + -(void)set_##name : (id)json forShadowView : (viewClass *)view RCT_DYNAMIC @end diff --git a/React/Views/RCTViewManager.m b/React/Views/RCTViewManager.m index 550759cabb2..8b948eb5eb9 100644 --- a/React/Views/RCTViewManager.m +++ b/React/Views/RCTViewManager.m @@ -9,6 +9,7 @@ #import "RCTBorderStyle.h" #import "RCTBridge.h" +#import "RCTConvert+Transform.h" #import "RCTConvert.h" #import "RCTEventDispatcher.h" #import "RCTLog.h" @@ -18,51 +19,54 @@ #import "RCTUtils.h" #import "RCTView.h" #import "UIView+React.h" -#import "RCTConvert+Transform.h" #if TARGET_OS_TV #import "RCTTVView.h" #endif -@implementation RCTConvert(UIAccessibilityTraits) +@implementation RCTConvert (UIAccessibilityTraits) -RCT_MULTI_ENUM_CONVERTER(UIAccessibilityTraits, (@{ - @"none": @(UIAccessibilityTraitNone), - @"button": @(UIAccessibilityTraitButton), - @"link": @(UIAccessibilityTraitLink), - @"header": @(UIAccessibilityTraitHeader), - @"search": @(UIAccessibilityTraitSearchField), - @"image": @(UIAccessibilityTraitImage), - @"imagebutton": @(UIAccessibilityTraitImage | UIAccessibilityTraitButton), - @"selected": @(UIAccessibilityTraitSelected), - @"plays": @(UIAccessibilityTraitPlaysSound), - @"key": @(UIAccessibilityTraitKeyboardKey), - @"keyboardkey": @(UIAccessibilityTraitKeyboardKey), - @"text": @(UIAccessibilityTraitStaticText), - @"summary": @(UIAccessibilityTraitSummaryElement), - @"disabled": @(UIAccessibilityTraitNotEnabled), - @"frequentUpdates": @(UIAccessibilityTraitUpdatesFrequently), - @"startsMedia": @(UIAccessibilityTraitStartsMediaSession), - @"adjustable": @(UIAccessibilityTraitAdjustable), - @"allowsDirectInteraction": @(UIAccessibilityTraitAllowsDirectInteraction), - @"pageTurn": @(UIAccessibilityTraitCausesPageTurn), - @"alert": @(UIAccessibilityTraitNone), - @"checkbox": @(UIAccessibilityTraitNone), - @"combobox": @(UIAccessibilityTraitNone), - @"menu": @(UIAccessibilityTraitNone), - @"menubar": @(UIAccessibilityTraitNone), - @"menuitem": @(UIAccessibilityTraitNone), - @"progressbar": @(UIAccessibilityTraitNone), - @"radio": @(UIAccessibilityTraitNone), - @"radiogroup": @(UIAccessibilityTraitNone), - @"scrollbar": @(UIAccessibilityTraitNone), - @"spinbutton": @(UIAccessibilityTraitNone), - @"switch": @(SwitchAccessibilityTrait), - @"tab": @(UIAccessibilityTraitNone), - @"tablist": @(UIAccessibilityTraitNone), - @"timer": @(UIAccessibilityTraitNone), - @"toolbar": @(UIAccessibilityTraitNone), -}), UIAccessibilityTraitNone, unsignedLongLongValue) +RCT_MULTI_ENUM_CONVERTER( + UIAccessibilityTraits, + (@{ + @"none" : @(UIAccessibilityTraitNone), + @"button" : @(UIAccessibilityTraitButton), + @"link" : @(UIAccessibilityTraitLink), + @"header" : @(UIAccessibilityTraitHeader), + @"search" : @(UIAccessibilityTraitSearchField), + @"image" : @(UIAccessibilityTraitImage), + @"imagebutton" : @(UIAccessibilityTraitImage | UIAccessibilityTraitButton), + @"selected" : @(UIAccessibilityTraitSelected), + @"plays" : @(UIAccessibilityTraitPlaysSound), + @"key" : @(UIAccessibilityTraitKeyboardKey), + @"keyboardkey" : @(UIAccessibilityTraitKeyboardKey), + @"text" : @(UIAccessibilityTraitStaticText), + @"summary" : @(UIAccessibilityTraitSummaryElement), + @"disabled" : @(UIAccessibilityTraitNotEnabled), + @"frequentUpdates" : @(UIAccessibilityTraitUpdatesFrequently), + @"startsMedia" : @(UIAccessibilityTraitStartsMediaSession), + @"adjustable" : @(UIAccessibilityTraitAdjustable), + @"allowsDirectInteraction" : @(UIAccessibilityTraitAllowsDirectInteraction), + @"pageTurn" : @(UIAccessibilityTraitCausesPageTurn), + @"alert" : @(UIAccessibilityTraitNone), + @"checkbox" : @(UIAccessibilityTraitNone), + @"combobox" : @(UIAccessibilityTraitNone), + @"menu" : @(UIAccessibilityTraitNone), + @"menubar" : @(UIAccessibilityTraitNone), + @"menuitem" : @(UIAccessibilityTraitNone), + @"progressbar" : @(UIAccessibilityTraitNone), + @"radio" : @(UIAccessibilityTraitNone), + @"radiogroup" : @(UIAccessibilityTraitNone), + @"scrollbar" : @(UIAccessibilityTraitNone), + @"spinbutton" : @(UIAccessibilityTraitNone), + @"switch" : @(SwitchAccessibilityTrait), + @"tab" : @(UIAccessibilityTraitNone), + @"tablist" : @(UIAccessibilityTraitNone), + @"timer" : @(UIAccessibilityTraitNone), + @"toolbar" : @(UIAccessibilityTraitNone), + }), + UIAccessibilityTraitNone, + unsignedLongLongValue) @end @@ -129,7 +133,10 @@ RCT_REMAP_VIEW_PROPERTY(accessibilityHint, reactAccessibilityElement.accessibili RCT_REMAP_VIEW_PROPERTY(accessibilityValue, reactAccessibilityElement.accessibilityValueInternal, NSDictionary) RCT_REMAP_VIEW_PROPERTY(accessibilityViewIsModal, reactAccessibilityElement.accessibilityViewIsModal, BOOL) RCT_REMAP_VIEW_PROPERTY(accessibilityElementsHidden, reactAccessibilityElement.accessibilityElementsHidden, BOOL) -RCT_REMAP_VIEW_PROPERTY(accessibilityIgnoresInvertColors, reactAccessibilityElement.shouldAccessibilityIgnoresInvertColors, BOOL) +RCT_REMAP_VIEW_PROPERTY( + accessibilityIgnoresInvertColors, + reactAccessibilityElement.shouldAccessibilityIgnoresInvertColors, + BOOL) RCT_REMAP_VIEW_PROPERTY(onAccessibilityAction, reactAccessibilityElement.onAccessibilityAction, RCTDirectEventBlock) RCT_REMAP_VIEW_PROPERTY(onAccessibilityTap, reactAccessibilityElement.onAccessibilityTap, RCTDirectEventBlock) RCT_REMAP_VIEW_PROPERTY(onMagicTap, reactAccessibilityElement.onMagicTap, RCTDirectEventBlock) @@ -155,7 +162,8 @@ RCT_CUSTOM_VIEW_PROPERTY(overflow, YGOverflow, RCTView) RCT_CUSTOM_VIEW_PROPERTY(shouldRasterizeIOS, BOOL, RCTView) { view.layer.shouldRasterize = json ? [RCTConvert BOOL:json] : defaultView.layer.shouldRasterize; - view.layer.rasterizationScale = view.layer.shouldRasterize ? [UIScreen mainScreen].scale : defaultView.layer.rasterizationScale; + view.layer.rasterizationScale = + view.layer.shouldRasterize ? [UIScreen mainScreen].scale : defaultView.layer.rasterizationScale; } RCT_CUSTOM_VIEW_PROPERTY(transform, CATransform3D, RCTView) @@ -167,8 +175,12 @@ RCT_CUSTOM_VIEW_PROPERTY(transform, CATransform3D, RCTView) RCT_CUSTOM_VIEW_PROPERTY(accessibilityRole, UIAccessibilityTraits, RCTView) { - const UIAccessibilityTraits AccessibilityRolesMask = UIAccessibilityTraitNone | UIAccessibilityTraitButton | UIAccessibilityTraitLink | UIAccessibilityTraitSearchField | UIAccessibilityTraitImage | UIAccessibilityTraitKeyboardKey | UIAccessibilityTraitStaticText | UIAccessibilityTraitAdjustable | UIAccessibilityTraitHeader | UIAccessibilityTraitSummaryElement | SwitchAccessibilityTrait; - view.reactAccessibilityElement.accessibilityTraits = view.reactAccessibilityElement.accessibilityTraits & ~AccessibilityRolesMask; + const UIAccessibilityTraits AccessibilityRolesMask = UIAccessibilityTraitNone | UIAccessibilityTraitButton | + UIAccessibilityTraitLink | UIAccessibilityTraitSearchField | UIAccessibilityTraitImage | + UIAccessibilityTraitKeyboardKey | UIAccessibilityTraitStaticText | UIAccessibilityTraitAdjustable | + UIAccessibilityTraitHeader | UIAccessibilityTraitSummaryElement | SwitchAccessibilityTrait; + view.reactAccessibilityElement.accessibilityTraits = + view.reactAccessibilityElement.accessibilityTraits & ~AccessibilityRolesMask; UIAccessibilityTraits newTraits = json ? [RCTConvert UIAccessibilityTraits:json] : defaultView.accessibilityTraits; if (newTraits != UIAccessibilityTraitNone) { UIAccessibilityTraits maskedTraits = newTraits & AccessibilityRolesMask; @@ -189,7 +201,8 @@ RCT_CUSTOM_VIEW_PROPERTY(accessibilityState, NSDictionary, RCTView) } const UIAccessibilityTraits AccessibilityStatesMask = UIAccessibilityTraitNotEnabled | UIAccessibilityTraitSelected; - view.reactAccessibilityElement.accessibilityTraits = view.reactAccessibilityElement.accessibilityTraits & ~AccessibilityStatesMask; + view.reactAccessibilityElement.accessibilityTraits = + view.reactAccessibilityElement.accessibilityTraits & ~AccessibilityStatesMask; for (NSString *s in state) { id val = [state objectForKey:s]; @@ -212,7 +225,6 @@ RCT_CUSTOM_VIEW_PROPERTY(accessibilityState, NSDictionary, RCTView) } else { view.reactAccessibilityElement.accessibilityState = nil; } - } RCT_CUSTOM_VIEW_PROPERTY(nativeID, NSString *, RCTView) @@ -254,7 +266,8 @@ RCT_CUSTOM_VIEW_PROPERTY(removeClippedSubviews, BOOL, RCTView) view.removeClippedSubviews = json ? [RCTConvert BOOL:json] : defaultView.removeClippedSubviews; } } -RCT_CUSTOM_VIEW_PROPERTY(borderRadius, CGFloat, RCTView) { +RCT_CUSTOM_VIEW_PROPERTY(borderRadius, CGFloat, RCTView) +{ if ([view respondsToSelector:@selector(setBorderRadius:)]) { view.borderRadius = json ? [RCTConvert CGFloat:json] : defaultView.borderRadius; } else { @@ -288,26 +301,27 @@ RCT_CUSTOM_VIEW_PROPERTY(hitSlop, UIEdgeInsets, RCTView) if ([view respondsToSelector:@selector(setHitTestEdgeInsets:)]) { if (json) { UIEdgeInsets hitSlopInsets = [RCTConvert UIEdgeInsets:json]; - view.hitTestEdgeInsets = UIEdgeInsetsMake(-hitSlopInsets.top, -hitSlopInsets.left, -hitSlopInsets.bottom, -hitSlopInsets.right); + view.hitTestEdgeInsets = + UIEdgeInsetsMake(-hitSlopInsets.top, -hitSlopInsets.left, -hitSlopInsets.bottom, -hitSlopInsets.right); } else { view.hitTestEdgeInsets = defaultView.hitTestEdgeInsets; } } } -#define RCT_VIEW_BORDER_PROPERTY(SIDE) \ -RCT_CUSTOM_VIEW_PROPERTY(border##SIDE##Width, float, RCTView) \ -{ \ - if ([view respondsToSelector:@selector(setBorder##SIDE##Width:)]) { \ - view.border##SIDE##Width = json ? [RCTConvert CGFloat:json] : defaultView.border##SIDE##Width; \ - } \ -} \ -RCT_CUSTOM_VIEW_PROPERTY(border##SIDE##Color, UIColor, RCTView) \ -{ \ - if ([view respondsToSelector:@selector(setBorder##SIDE##Color:)]) { \ - view.border##SIDE##Color = json ? [RCTConvert CGColor:json] : defaultView.border##SIDE##Color; \ - } \ -} +#define RCT_VIEW_BORDER_PROPERTY(SIDE) \ + RCT_CUSTOM_VIEW_PROPERTY(border##SIDE##Width, float, RCTView) \ + { \ + if ([view respondsToSelector:@selector(setBorder##SIDE##Width:)]) { \ + view.border##SIDE##Width = json ? [RCTConvert CGFloat:json] : defaultView.border##SIDE##Width; \ + } \ + } \ + RCT_CUSTOM_VIEW_PROPERTY(border##SIDE##Color, UIColor, RCTView) \ + { \ + if ([view respondsToSelector:@selector(setBorder##SIDE##Color:)]) { \ + view.border##SIDE##Color = json ? [RCTConvert CGColor:json] : defaultView.border##SIDE##Color; \ + } \ + } RCT_VIEW_BORDER_PROPERTY(Top) RCT_VIEW_BORDER_PROPERTY(Right) @@ -316,13 +330,13 @@ RCT_VIEW_BORDER_PROPERTY(Left) RCT_VIEW_BORDER_PROPERTY(Start) RCT_VIEW_BORDER_PROPERTY(End) -#define RCT_VIEW_BORDER_RADIUS_PROPERTY(SIDE) \ -RCT_CUSTOM_VIEW_PROPERTY(border##SIDE##Radius, CGFloat, RCTView) \ -{ \ - if ([view respondsToSelector:@selector(setBorder##SIDE##Radius:)]) { \ - view.border##SIDE##Radius = json ? [RCTConvert CGFloat:json] : defaultView.border##SIDE##Radius; \ - } \ -} \ +#define RCT_VIEW_BORDER_RADIUS_PROPERTY(SIDE) \ + RCT_CUSTOM_VIEW_PROPERTY(border##SIDE##Radius, CGFloat, RCTView) \ + { \ + if ([view respondsToSelector:@selector(setBorder##SIDE##Radius:)]) { \ + view.border##SIDE##Radius = json ? [RCTConvert CGFloat:json] : defaultView.border##SIDE##Radius; \ + } \ + } RCT_VIEW_BORDER_RADIUS_PROPERTY(TopLeft) RCT_VIEW_BORDER_RADIUS_PROPERTY(TopRight) diff --git a/React/Views/RCTWrapperViewController.m b/React/Views/RCTWrapperViewController.m index e647832a0d0..fc9eaa6c507 100644 --- a/React/Views/RCTWrapperViewController.m +++ b/React/Views/RCTWrapperViewController.m @@ -9,13 +9,12 @@ #import +#import "RCTAutoInsetsProtocol.h" #import "RCTEventDispatcher.h" #import "RCTUtils.h" #import "UIView+React.h" -#import "RCTAutoInsetsProtocol.h" -@implementation RCTWrapperViewController -{ +@implementation RCTWrapperViewController { UIView *_wrapperView; UIView *_contentView; RCTEventDispatcher *_eventDispatcher; @@ -37,8 +36,8 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithNibName:(NSString *)nn bundle:(NSBundle *)nb) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithNibName : (NSString *)nn bundle : (NSBundle *)nb) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) - (void)viewWillLayoutSubviews { @@ -51,7 +50,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) static BOOL RCTFindScrollViewAndRefreshContentInsetInView(UIView *view) { if ([view conformsToProtocol:@protocol(RCTAutoInsetsProtocol)]) { - [(id ) view refreshContentInset]; + [(id)view refreshContentInset]; return YES; } for (UIView *subview in view.subviews) { diff --git a/React/Views/RefreshControl/RCTRefreshControl.m b/React/Views/RefreshControl/RCTRefreshControl.m index a3ca0e1ed71..428a5e7fa40 100644 --- a/React/Views/RefreshControl/RCTRefreshControl.m +++ b/React/Views/RefreshControl/RCTRefreshControl.m @@ -35,7 +35,7 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) - (void)layoutSubviews { @@ -49,9 +49,9 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) // If the control is refreshing when mounted we need to call // beginRefreshing in layoutSubview or it doesn't work. - if (_currentRefreshingState && _isInitialRender) { + if (_currentRefreshingState && _isInitialRender) { [self beginRefreshingProgrammatically]; - } + } _isInitialRender = false; } @@ -68,16 +68,17 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) // `beginRefreshing` must be called after the animation is done. This is why it is impossible // to use `setContentOffset` with `animated:YES`. [UIView animateWithDuration:0.25 - delay:0 - options:UIViewAnimationOptionBeginFromCurrentState - animations:^(void) { - [scrollView setContentOffset:offset]; - } completion:^(__unused BOOL finished) { - if(beginRefreshingTimestamp == self->_currentRefreshingStateTimestamp) { - [super beginRefreshing]; - [self setCurrentRefreshingState:super.refreshing]; - } - }]; + delay:0 + options:UIViewAnimationOptionBeginFromCurrentState + animations:^(void) { + [scrollView setContentOffset:offset]; + } + completion:^(__unused BOOL finished) { + if (beginRefreshingTimestamp == self->_currentRefreshingStateTimestamp) { + [super beginRefreshing]; + [self setCurrentRefreshingState:super.refreshing]; + } + }]; } - (void)endRefreshingProgrammatically @@ -89,16 +90,17 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) UInt64 endRefreshingTimestamp = _currentRefreshingStateTimestamp; CGPoint offset = {scrollView.contentOffset.x, -scrollView.contentInset.top}; [UIView animateWithDuration:0.25 - delay:0 - options:UIViewAnimationOptionBeginFromCurrentState - animations:^(void) { - [scrollView setContentOffset:offset]; - } completion:^(__unused BOOL finished) { - if(endRefreshingTimestamp == self->_currentRefreshingStateTimestamp) { - [super endRefreshing]; - [self setCurrentRefreshingState:super.refreshing]; - } - }]; + delay:0 + options:UIViewAnimationOptionBeginFromCurrentState + animations:^(void) { + [scrollView setContentOffset:offset]; + } + completion:^(__unused BOOL finished) { + if (endRefreshingTimestamp == self->_currentRefreshingStateTimestamp) { + [super endRefreshing]; + [self setCurrentRefreshingState:super.refreshing]; + } + }]; } else { [super endRefreshing]; } diff --git a/React/Views/RefreshControl/RCTRefreshControlManager.m b/React/Views/RefreshControl/RCTRefreshControlManager.m index 2e6282c1d4c..3152b1c8069 100644 --- a/React/Views/RefreshControl/RCTRefreshControlManager.m +++ b/React/Views/RefreshControl/RCTRefreshControlManager.m @@ -7,9 +7,9 @@ #import +#import "RCTRefreshControl.h" #import "RCTRefreshControlManager.h" #import "RCTRefreshableProtocol.h" -#import "RCTRefreshControl.h" @implementation RCTRefreshControlManager @@ -32,7 +32,7 @@ RCT_EXPORT_METHOD(setNativeRefreshing : (nonnull NSNumber *)viewTag toRefreshing UIView *view = viewRegistry[viewTag]; if ([view conformsToProtocol:@protocol(RCTRefreshableProtocol)]) { - [(id)view setRefreshing: refreshing]; + [(id)view setRefreshing:refreshing]; } else { RCTLogError(@"view must conform to protocol RCTRefreshableProtocol"); } diff --git a/React/Views/RefreshControl/RCTRefreshableProtocol.h b/React/Views/RefreshControl/RCTRefreshableProtocol.h index 1f885d845eb..9271e2d853d 100644 --- a/React/Views/RefreshControl/RCTRefreshableProtocol.h +++ b/React/Views/RefreshControl/RCTRefreshableProtocol.h @@ -5,8 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -#import #import +#import /** * Protocol used to dispatch commands in `RCTRefreshControlManager.h`. diff --git a/React/Views/SafeAreaView/RCTSafeAreaShadowView.m b/React/Views/SafeAreaView/RCTSafeAreaShadowView.m index b6e37149b9e..ea6f1398bd8 100644 --- a/React/Views/SafeAreaView/RCTSafeAreaShadowView.m +++ b/React/Views/SafeAreaView/RCTSafeAreaShadowView.m @@ -16,8 +16,9 @@ - (void)setLocalData:(RCTSafeAreaViewLocalData *)localData { - RCTAssert([localData isKindOfClass:[RCTSafeAreaViewLocalData class]], - @"Local data object for `RCTSafeAreaShadowView` must be `RCTSafeAreaViewLocalData` instance."); + RCTAssert( + [localData isKindOfClass:[RCTSafeAreaViewLocalData class]], + @"Local data object for `RCTSafeAreaShadowView` must be `RCTSafeAreaViewLocalData` instance."); UIEdgeInsets insets = localData.insets; @@ -26,17 +27,27 @@ super.paddingTop = (YGValue){insets.top, YGUnitPoint}; super.paddingBottom = (YGValue){insets.bottom, YGUnitPoint}; - [self didSetProps:@[@"paddingLeft", @"paddingRight", @"paddingTop", @"paddingBottom"]]; + [self didSetProps:@[ @"paddingLeft", @"paddingRight", @"paddingTop", @"paddingBottom" ]]; } /** * Removing support for setting padding from any outside code * to prevent interferring this with local data. */ -- (void)setPadding:(__unused YGValue)value {} -- (void)setPaddingLeft:(__unused YGValue)value {} -- (void)setPaddingRight:(__unused YGValue)value {} -- (void)setPaddingTop:(__unused YGValue)value {} -- (void)setPaddingBottom:(__unused YGValue)value {} +- (void)setPadding:(__unused YGValue)value +{ +} +- (void)setPaddingLeft:(__unused YGValue)value +{ +} +- (void)setPaddingRight:(__unused YGValue)value +{ +} +- (void)setPaddingTop:(__unused YGValue)value +{ +} +- (void)setPaddingBottom:(__unused YGValue)value +{ +} @end diff --git a/React/Views/SafeAreaView/RCTSafeAreaView.m b/React/Views/SafeAreaView/RCTSafeAreaView.m index 34d3f7ac5a1..d8e1be97b90 100644 --- a/React/Views/SafeAreaView/RCTSafeAreaView.m +++ b/React/Views/SafeAreaView/RCTSafeAreaView.m @@ -27,8 +27,8 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)decoder) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)decoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) - (NSString *)description { @@ -40,9 +40,9 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) } return [NSString stringWithFormat:@"%@; safeAreaInsets = %@; appliedSafeAreaInsets = %@>", - superDescription, - NSStringFromUIEdgeInsets([self safeAreaInsetsIfSupportedAndEnabled]), - NSStringFromUIEdgeInsets(_currentSafeAreaInsets)]; + superDescription, + NSStringFromUIEdgeInsets([self safeAreaInsetsIfSupportedAndEnabled]), + NSStringFromUIEdgeInsets(_currentSafeAreaInsets)]; } - (BOOL)isSupportedByOS @@ -64,7 +64,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) - (UIEdgeInsets)emulatedSafeAreaInsets { - UIViewController* vc = self.reactViewController; + UIViewController *vc = self.reactViewController; if (!vc) { return UIEdgeInsetsZero; @@ -87,12 +87,10 @@ RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) return safeAreaInsets; } -static BOOL UIEdgeInsetsEqualToEdgeInsetsWithThreshold(UIEdgeInsets insets1, UIEdgeInsets insets2, CGFloat threshold) { - return - ABS(insets1.left - insets2.left) <= threshold && - ABS(insets1.right - insets2.right) <= threshold && - ABS(insets1.top - insets2.top) <= threshold && - ABS(insets1.bottom - insets2.bottom) <= threshold; +static BOOL UIEdgeInsetsEqualToEdgeInsetsWithThreshold(UIEdgeInsets insets1, UIEdgeInsets insets2, CGFloat threshold) +{ + return ABS(insets1.left - insets2.left) <= threshold && ABS(insets1.right - insets2.right) <= threshold && + ABS(insets1.top - insets2.top) <= threshold && ABS(insets1.bottom - insets2.bottom) <= threshold; } - (void)safeAreaInsetsDidChange @@ -133,7 +131,7 @@ static BOOL UIEdgeInsetsEqualToEdgeInsetsWithThreshold(UIEdgeInsets insets1, UIE } _emulateUnlessSupported = emulateUnlessSupported; - + if ([self isSupportedByOS]) { return; } diff --git a/React/Views/ScrollView/RCTScrollContentShadowView.m b/React/Views/ScrollView/RCTScrollContentShadowView.m index c27141fc7e4..bb27f2ab55f 100644 --- a/React/Views/ScrollView/RCTScrollContentShadowView.m +++ b/React/Views/ScrollView/RCTScrollContentShadowView.m @@ -13,8 +13,7 @@ @implementation RCTScrollContentShadowView -- (void)layoutWithMetrics:(RCTLayoutMetrics)layoutMetrics - layoutContext:(RCTLayoutContext)layoutContext +- (void)layoutWithMetrics:(RCTLayoutMetrics)layoutMetrics layoutContext:(RCTLayoutContext)layoutContext { if (layoutMetrics.layoutDirection == UIUserInterfaceLayoutDirectionRightToLeft) { // Motivation: diff --git a/React/Views/ScrollView/RCTScrollContentView.m b/React/Views/ScrollView/RCTScrollContentView.m index 5bdef8582a3..cf6a0b1f179 100644 --- a/React/Views/ScrollView/RCTScrollContentView.m +++ b/React/Views/ScrollView/RCTScrollContentView.m @@ -24,8 +24,7 @@ return; } - RCTAssert([scrollView isKindOfClass:[RCTScrollView class]], - @"Unexpected view hierarchy of RCTScrollView component."); + RCTAssert([scrollView isKindOfClass:[RCTScrollView class]], @"Unexpected view hierarchy of RCTScrollView component."); [scrollView updateContentOffsetIfNeeded]; } diff --git a/React/Views/ScrollView/RCTScrollEvent.m b/React/Views/ScrollView/RCTScrollEvent.m index 72e31ee8106..ce2a6b6971c 100644 --- a/React/Views/ScrollView/RCTScrollEvent.m +++ b/React/Views/ScrollView/RCTScrollEvent.m @@ -8,8 +8,7 @@ #import "RCTScrollEvent.h" #import -@implementation RCTScrollEvent -{ +@implementation RCTScrollEvent { CGPoint _scrollViewContentOffset; UIEdgeInsets _scrollViewContentInset; CGSize _scrollViewContentSize; @@ -33,7 +32,7 @@ coalescingKey:(uint16_t)coalescingKey { RCTAssertParam(reactTag); - + if ((self = [super init])) { _eventName = [eventName copy]; _viewTag = reactTag; @@ -48,7 +47,7 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)init) +RCT_NOT_IMPLEMENTED(-(instancetype)init) - (uint16_t)coalescingKey { @@ -58,33 +57,24 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (NSDictionary *)body { NSDictionary *body = @{ - @"contentOffset": @{ - @"x": @(_scrollViewContentOffset.x), - @"y": @(_scrollViewContentOffset.y) - }, - @"contentInset": @{ - @"top": @(_scrollViewContentInset.top), - @"left": @(_scrollViewContentInset.left), - @"bottom": @(_scrollViewContentInset.bottom), - @"right": @(_scrollViewContentInset.right) - }, - @"contentSize": @{ - @"width": @(_scrollViewContentSize.width), - @"height": @(_scrollViewContentSize.height) - }, - @"layoutMeasurement": @{ - @"width": @(_scrollViewFrame.size.width), - @"height": @(_scrollViewFrame.size.height) - }, - @"zoomScale": @(_scrollViewZoomScale ?: 1), - }; - + @"contentOffset" : @{@"x" : @(_scrollViewContentOffset.x), @"y" : @(_scrollViewContentOffset.y)}, + @"contentInset" : @{ + @"top" : @(_scrollViewContentInset.top), + @"left" : @(_scrollViewContentInset.left), + @"bottom" : @(_scrollViewContentInset.bottom), + @"right" : @(_scrollViewContentInset.right) + }, + @"contentSize" : @{@"width" : @(_scrollViewContentSize.width), @"height" : @(_scrollViewContentSize.height)}, + @"layoutMeasurement" : @{@"width" : @(_scrollViewFrame.size.width), @"height" : @(_scrollViewFrame.size.height)}, + @"zoomScale" : @(_scrollViewZoomScale ?: 1), + }; + if (_userData) { NSMutableDictionary *mutableBody = [body mutableCopy]; [mutableBody addEntriesFromDictionary:_userData]; body = mutableBody; } - + return body; } @@ -95,13 +85,14 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (RCTScrollEvent *)coalesceWithEvent:(RCTScrollEvent *)newEvent { - NSArray *updatedChildFrames = [_userData[@"updatedChildFrames"] arrayByAddingObjectsFromArray:newEvent->_userData[@"updatedChildFrames"]]; + NSArray *updatedChildFrames = + [_userData[@"updatedChildFrames"] arrayByAddingObjectsFromArray:newEvent->_userData[@"updatedChildFrames"]]; if (updatedChildFrames) { NSMutableDictionary *userData = [newEvent->_userData mutableCopy]; userData[@"updatedChildFrames"] = updatedChildFrames; newEvent->_userData = userData; } - + return newEvent; } @@ -112,7 +103,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (NSArray *)arguments { - return @[self.viewTag, RCTNormalizeInputEventName(self.eventName), [self body]]; + return @[ self.viewTag, RCTNormalizeInputEventName(self.eventName), [self body] ]; } @end diff --git a/React/Views/ScrollView/RCTScrollView.m b/React/Views/ScrollView/RCTScrollView.m index a307cfe69e7..56d63505b9e 100644 --- a/React/Views/ScrollView/RCTScrollView.m +++ b/React/Views/ScrollView/RCTScrollView.m @@ -11,13 +11,13 @@ #import "RCTConvert.h" #import "RCTLog.h" +#import "RCTScrollEvent.h" #import "RCTUIManager.h" #import "RCTUIManagerObserverCoordinator.h" #import "RCTUIManagerUtils.h" #import "RCTUtils.h" #import "UIView+Private.h" #import "UIView+React.h" -#import "RCTScrollEvent.h" #if !TARGET_OS_TV #import "RCTRefreshControl.h" @@ -28,7 +28,7 @@ * default UIKit behaviors such as textFields automatically scrolling * scroll views that contain them. */ -@interface RCTCustomScrollView : UIScrollView +@interface RCTCustomScrollView : UIScrollView @property (nonatomic, assign) BOOL centerContent; #if !TARGET_OS_TV @@ -52,9 +52,9 @@ self.semanticContentAttribute = UISemanticContentAttributeForceLeftToRight; } - #if !TARGET_OS_TV +#if !TARGET_OS_TV _pinchGestureEnabled = YES; - #endif +#endif } return self; } @@ -101,8 +101,8 @@ CGSize contentSize = self.contentSize; UIEdgeInsets contentInset = self.contentInset; CGSize fullSize = CGSizeMake( - contentSize.width + contentInset.left + contentInset.right, - contentSize.height + contentInset.top + contentInset.bottom); + contentSize.width + contentInset.left + contentInset.right, + contentSize.height + contentInset.top + contentInset.bottom); rect = CGRectIntersection((CGRect){CGPointZero, fullSize}, rect); if (CGRectIsNull(rect)) { @@ -157,11 +157,11 @@ - (BOOL)touchesShouldCancelInContentView:(__unused UIView *)view { BOOL shouldDisableScrollInteraction = [self _shouldDisableScrollInteraction]; - + if (shouldDisableScrollInteraction == NO) { [super touchesShouldCancelInContentView:view]; } - + return !shouldDisableScrollInteraction; } @@ -186,8 +186,8 @@ } super.contentOffset = CGPointMake( - RCTSanitizeNaNValue(contentOffset.x, @"scrollView.contentOffset.x"), - RCTSanitizeNaNValue(contentOffset.y, @"scrollView.contentOffset.y")); + RCTSanitizeNaNValue(contentOffset.x, @"scrollView.contentOffset.x"), + RCTSanitizeNaNValue(contentOffset.y, @"scrollView.contentOffset.y")); } - (void)setFrame:(CGRect)frame @@ -218,8 +218,8 @@ return; } self.contentOffset = CGPointMake( - MAX(-contentInset.left, MIN(xMaxOffset, originalOffset.x)), - MAX(-contentInset.top, MIN(yMaxOffset, originalOffset.y))); + MAX(-contentInset.left, MIN(xMaxOffset, originalOffset.x)), + MAX(-contentInset.top, MIN(yMaxOffset, originalOffset.y))); } } @@ -246,7 +246,7 @@ // in the setter gets overridden when the view loads. self.pinchGestureRecognizer.enabled = _pinchGestureEnabled; } -#endif //TARGET_OS_TV +#endif // TARGET_OS_TV - (BOOL)shouldGroupAccessibilityChildren { @@ -259,8 +259,7 @@ @end -@implementation RCTScrollView -{ +@implementation RCTScrollView { RCTEventDispatcher *_eventDispatcher; CGRect _prevFirstVisibleFrame; __weak UIView *_firstVisibleView; @@ -316,14 +315,15 @@ return self; } -RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) -RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) -static inline void RCTApplyTransformationAccordingLayoutDirection(UIView *view, UIUserInterfaceLayoutDirection layoutDirection) { - view.transform = - layoutDirection == UIUserInterfaceLayoutDirectionLeftToRight ? - CGAffineTransformIdentity : - CGAffineTransformMakeScale(-1, 1); +static inline void RCTApplyTransformationAccordingLayoutDirection( + UIView *view, + UIUserInterfaceLayoutDirection layoutDirection) +{ + view.transform = layoutDirection == UIUserInterfaceLayoutDirectionLeftToRight ? CGAffineTransformIdentity + : CGAffineTransformMakeScale(-1, 1); } - (void)setReactLayoutDirection:(UIUserInterfaceLayoutDirection)layoutDirection @@ -345,14 +345,16 @@ static inline void RCTApplyTransformationAccordingLayoutDirection(UIView *view, #if !TARGET_OS_TV if ([view conformsToProtocol:@protocol(RCTCustomRefreshContolProtocol)]) { [_scrollView setCustomRefreshControl:(UIView *)view]; - if (![view isKindOfClass:[UIRefreshControl class]] - && [view conformsToProtocol:@protocol(UIScrollViewDelegate)]) { + if (![view isKindOfClass:[UIRefreshControl class]] && [view conformsToProtocol:@protocol(UIScrollViewDelegate)]) { [self addScrollListener:(UIView *)view]; } } else #endif { - RCTAssert(_contentView == nil, @"RCTScrollView may only contain a single subview, the already set subview looks like: %@", [_contentView react_recursiveDescription]); + RCTAssert( + _contentView == nil, + @"RCTScrollView may only contain a single subview, the already set subview looks like: %@", + [_contentView react_recursiveDescription]); _contentView = view; RCTApplyTransformationAccordingLayoutDirection(_contentView, self.reactLayoutDirection); [_scrollView addSubview:view]; @@ -365,8 +367,8 @@ static inline void RCTApplyTransformationAccordingLayoutDirection(UIView *view, #if !TARGET_OS_TV if ([subview conformsToProtocol:@protocol(RCTCustomRefreshContolProtocol)]) { [_scrollView setCustomRefreshControl:nil]; - if (![subview isKindOfClass:[UIRefreshControl class]] - && [subview conformsToProtocol:@protocol(UIScrollViewDelegate)]) { + if (![subview isKindOfClass:[UIRefreshControl class]] && + [subview conformsToProtocol:@protocol(UIScrollViewDelegate)]) { [self removeScrollListener:(UIView *)subview]; } } else @@ -421,7 +423,8 @@ static inline void RCTApplyTransformationAccordingLayoutDirection(UIView *view, // Adjust the refresh control frame if the scrollview layout changes. UIView *refreshControl = _scrollView.customRefreshControl; if (refreshControl && refreshControl.isRefreshing) { - refreshControl.frame = (CGRect){_scrollView.contentOffset, {_scrollView.frame.size.width, refreshControl.frame.size.height}}; + refreshControl.frame = + (CGRect){_scrollView.contentOffset, {_scrollView.frame.size.width, refreshControl.frame.size.height}}; } #endif @@ -443,11 +446,11 @@ static inline void RCTApplyTransformationAccordingLayoutDirection(UIView *view, const BOOL scrollsHorizontally = contentSize.width > bounds.size.width; const BOOL scrollsVertically = contentSize.height > bounds.size.height; - const BOOL shouldClipAgain = - CGRectIsNull(_lastClippedToRect) || - !CGRectEqualToRect(_lastClippedToRect, bounds) || - (scrollsHorizontally && (bounds.size.width < leeway || fabs(_lastClippedToRect.origin.x - bounds.origin.x) >= leeway)) || - (scrollsVertically && (bounds.size.height < leeway || fabs(_lastClippedToRect.origin.y - bounds.origin.y) >= leeway)); + const BOOL shouldClipAgain = CGRectIsNull(_lastClippedToRect) || !CGRectEqualToRect(_lastClippedToRect, bounds) || + (scrollsHorizontally && + (bounds.size.width < leeway || fabs(_lastClippedToRect.origin.x - bounds.origin.x) >= leeway)) || + (scrollsVertically && + (bounds.size.height < leeway || fabs(_lastClippedToRect.origin.y - bounds.origin.y) >= leeway)); if (shouldClipAgain) { const CGRect clipRect = CGRectInset(clipView.bounds, -leeway, -leeway); @@ -465,9 +468,7 @@ static inline void RCTApplyTransformationAccordingLayoutDirection(UIView *view, CGPoint contentOffset = _scrollView.contentOffset; _contentInset = contentInset; - [RCTView autoAdjustInsetsForView:self - withScrollView:_scrollView - updateOffset:NO]; + [RCTView autoAdjustInsetsForView:self withScrollView:_scrollView updateOffset:NO]; _scrollView.contentOffset = contentOffset; } @@ -485,10 +486,17 @@ static inline void RCTApplyTransformationAccordingLayoutDirection(UIView *view, - (void)scrollToOffset:(CGPoint)offset animated:(BOOL)animated { if (!CGPointEqualToPoint(_scrollView.contentOffset, offset)) { - CGRect maxRect = CGRectMake(fmin(-_scrollView.contentInset.left, 0), - fmin(-_scrollView.contentInset.top, 0), - fmax(_scrollView.contentSize.width - _scrollView.bounds.size.width + _scrollView.contentInset.right + fmax(_scrollView.contentInset.left, 0), 0.01), - fmax(_scrollView.contentSize.height - _scrollView.bounds.size.height + _scrollView.contentInset.bottom + fmax(_scrollView.contentInset.top, 0), 0.01)); // Make width and height greater than 0 + CGRect maxRect = CGRectMake( + fmin(-_scrollView.contentInset.left, 0), + fmin(-_scrollView.contentInset.top, 0), + fmax( + _scrollView.contentSize.width - _scrollView.bounds.size.width + _scrollView.contentInset.right + + fmax(_scrollView.contentInset.left, 0), + 0.01), + fmax( + _scrollView.contentSize.height - _scrollView.bounds.size.height + _scrollView.contentInset.bottom + + fmax(_scrollView.contentInset.top, 0), + 0.01)); // Make width and height greater than 0 // Ensure at least one scroll event will fire _allowNextScrollNoMatterWhat = YES; if (!CGRectContainsPoint(maxRect, offset) && !self.scrollToOverflowEnabled) { @@ -531,31 +539,30 @@ static inline void RCTApplyTransformationAccordingLayoutDirection(UIView *view, - (void)refreshContentInset { - [RCTView autoAdjustInsetsForView:self - withScrollView:_scrollView - updateOffset:YES]; + [RCTView autoAdjustInsetsForView:self withScrollView:_scrollView updateOffset:YES]; } #pragma mark - ScrollView delegate -#define RCT_SEND_SCROLL_EVENT(_eventName, _userData) { \ - NSString *eventName = NSStringFromSelector(@selector(_eventName)); \ - [self sendScrollEventWithName:eventName scrollView:_scrollView userData:_userData]; \ -} +#define RCT_SEND_SCROLL_EVENT(_eventName, _userData) \ + { \ + NSString *eventName = NSStringFromSelector(@selector(_eventName)); \ + [self sendScrollEventWithName:eventName scrollView:_scrollView userData:_userData]; \ + } -#define RCT_FORWARD_SCROLL_EVENT(call) \ -for (NSObject *scrollViewListener in _scrollListeners) { \ - if ([scrollViewListener respondsToSelector:_cmd]) { \ - [scrollViewListener call]; \ - } \ -} +#define RCT_FORWARD_SCROLL_EVENT(call) \ + for (NSObject * scrollViewListener in _scrollListeners) { \ + if ([scrollViewListener respondsToSelector:_cmd]) { \ + [scrollViewListener call]; \ + } \ + } #define RCT_SCROLL_EVENT_HANDLER(delegateMethod, eventName) \ -- (void)delegateMethod:(UIScrollView *)scrollView \ -{ \ - RCT_SEND_SCROLL_EVENT(eventName, nil); \ - RCT_FORWARD_SCROLL_EVENT(delegateMethod:scrollView); \ -} + -(void)delegateMethod : (UIScrollView *)scrollView \ + { \ + RCT_SEND_SCROLL_EVENT(eventName, nil); \ + RCT_FORWARD_SCROLL_EVENT(delegateMethod : scrollView); \ + } RCT_SCROLL_EVENT_HANDLER(scrollViewWillBeginDecelerating, onMomentumScrollBegin) RCT_SCROLL_EVENT_HANDLER(scrollViewDidZoom, onScroll) @@ -586,10 +593,9 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) */ if (_allowNextScrollNoMatterWhat || (_scrollEventThrottle > 0 && _scrollEventThrottle < MAX(0.017, now - _lastScrollDispatchTime))) { - if (_DEPRECATED_sendUpdatedChildFrames) { // Calculate changed frames - RCT_SEND_SCROLL_EVENT(onScroll, (@{@"updatedChildFrames": [self calculateChildFramesData]})); + RCT_SEND_SCROLL_EVENT(onScroll, (@{@"updatedChildFrames" : [self calculateChildFramesData]})); } else { RCT_SEND_SCROLL_EVENT(onScroll, nil); } @@ -598,49 +604,49 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) _lastScrollDispatchTime = now; _allowNextScrollNoMatterWhat = NO; } - RCT_FORWARD_SCROLL_EVENT(scrollViewDidScroll:scrollView); + RCT_FORWARD_SCROLL_EVENT(scrollViewDidScroll : scrollView); } - (NSArray *)calculateChildFramesData { - NSMutableArray *updatedChildFrames = [NSMutableArray new]; - [[_contentView reactSubviews] enumerateObjectsUsingBlock: - ^(UIView *subview, NSUInteger idx, __unused BOOL *stop) { + NSMutableArray *updatedChildFrames = [NSMutableArray new]; + [[_contentView reactSubviews] enumerateObjectsUsingBlock:^(UIView *subview, NSUInteger idx, __unused BOOL *stop) { + // Check if new or changed + CGRect newFrame = subview.frame; + BOOL frameChanged = NO; + if (self->_cachedChildFrames.count <= idx) { + frameChanged = YES; + [self->_cachedChildFrames addObject:[NSValue valueWithCGRect:newFrame]]; + } else if (!CGRectEqualToRect(newFrame, [self->_cachedChildFrames[idx] CGRectValue])) { + frameChanged = YES; + self->_cachedChildFrames[idx] = [NSValue valueWithCGRect:newFrame]; + } - // Check if new or changed - CGRect newFrame = subview.frame; - BOOL frameChanged = NO; - if (self->_cachedChildFrames.count <= idx) { - frameChanged = YES; - [self->_cachedChildFrames addObject:[NSValue valueWithCGRect:newFrame]]; - } else if (!CGRectEqualToRect(newFrame, [self->_cachedChildFrames[idx] CGRectValue])) { - frameChanged = YES; - self->_cachedChildFrames[idx] = [NSValue valueWithCGRect:newFrame]; - } + // Create JS frame object + if (frameChanged) { + [updatedChildFrames addObject:@{ + @"index" : @(idx), + @"x" : @(newFrame.origin.x), + @"y" : @(newFrame.origin.y), + @"width" : @(newFrame.size.width), + @"height" : @(newFrame.size.height), + }]; + } + }]; - // Create JS frame object - if (frameChanged) { - [updatedChildFrames addObject: @{ - @"index": @(idx), - @"x": @(newFrame.origin.x), - @"y": @(newFrame.origin.y), - @"width": @(newFrame.size.width), - @"height": @(newFrame.size.height), - }]; - } - }]; - - return updatedChildFrames; + return updatedChildFrames; } - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { _allowNextScrollNoMatterWhat = YES; // Ensure next scroll event is recorded, regardless of throttle RCT_SEND_SCROLL_EVENT(onScrollBeginDrag, nil); - RCT_FORWARD_SCROLL_EVENT(scrollViewWillBeginDragging:scrollView); + RCT_FORWARD_SCROLL_EVENT(scrollViewWillBeginDragging : scrollView); } -- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset +- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView + withVelocity:(CGPoint)velocity + targetContentOffset:(inout CGPoint *)targetContentOffset { if (self.snapToOffsets) { // An alternative to enablePaging and snapToInterval which allows setting custom @@ -656,9 +662,8 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) // Calculate maximum content offset CGSize viewportSize = [self _calculateViewportSize]; - CGFloat maximumOffset = isHorizontal - ? MAX(0, _scrollView.contentSize.width - viewportSize.width) - : MAX(0, _scrollView.contentSize.height - viewportSize.height); + CGFloat maximumOffset = isHorizontal ? MAX(0, _scrollView.contentSize.width - viewportSize.width) + : MAX(0, _scrollView.contentSize.height - viewportSize.height); // Calculate the snap offsets adjacent to the initial offset target CGFloat targetOffset = isHorizontal ? targetContentOffset->x : targetContentOffset->y; @@ -682,9 +687,7 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) } // Calculate the nearest offset - CGFloat nearestOffset = targetOffset - smallerOffset < largerOffset - targetOffset - ? smallerOffset - : largerOffset; + CGFloat nearestOffset = targetOffset - smallerOffset < largerOffset - targetOffset ? smallerOffset : largerOffset; CGFloat firstOffset = [[self.snapToOffsets firstObject] floatValue]; CGFloat lastOffset = [[self.snapToOffsets lastObject] floatValue]; @@ -745,21 +748,18 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) // Offset based on desired alignment CGFloat frameLength = isHorizontal ? self.frame.size.width : self.frame.size.height; CGFloat alignmentOffset = 0.0f; - if ([self.snapToAlignment isEqualToString: @"center"]) { + if ([self.snapToAlignment isEqualToString:@"center"]) { alignmentOffset = (frameLength * 0.5f) + (snapToIntervalF * 0.5f); - } else if ([self.snapToAlignment isEqualToString: @"end"]) { + } else if ([self.snapToAlignment isEqualToString:@"end"]) { alignmentOffset = frameLength; } // Pick snap point based on direction and proximity CGFloat fractionalIndex = (targetContentOffsetAlongAxis + alignmentOffset) / snapToIntervalF; - NSInteger snapIndex = - velocityAlongAxis > 0.0 ? - ceil(fractionalIndex) : - velocityAlongAxis < 0.0 ? - floor(fractionalIndex) : - round(fractionalIndex); + NSInteger snapIndex = velocityAlongAxis > 0.0 + ? ceil(fractionalIndex) + : velocityAlongAxis < 0.0 ? floor(fractionalIndex) : round(fractionalIndex); CGFloat newTargetContentOffset = (snapIndex * snapToIntervalF) - alignmentOffset; // Set new targetContentOffset @@ -771,34 +771,31 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) } NSDictionary *userData = @{ - @"velocity": @{ - @"x": @(velocity.x), - @"y": @(velocity.y) - }, - @"targetContentOffset": @{ - @"x": @(targetContentOffset->x), - @"y": @(targetContentOffset->y) - } + @"velocity" : @{@"x" : @(velocity.x), @"y" : @(velocity.y)}, + @"targetContentOffset" : @{@"x" : @(targetContentOffset->x), @"y" : @(targetContentOffset->y)} }; RCT_SEND_SCROLL_EVENT(onScrollEndDrag, userData); - RCT_FORWARD_SCROLL_EVENT(scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset); + RCT_FORWARD_SCROLL_EVENT(scrollViewWillEndDragging + : scrollView withVelocity + : velocity targetContentOffset + : targetContentOffset); } - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { - RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndDragging:scrollView willDecelerate:decelerate); + RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndDragging : scrollView willDecelerate : decelerate); } - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view { RCT_SEND_SCROLL_EVENT(onScrollBeginDrag, nil); - RCT_FORWARD_SCROLL_EVENT(scrollViewWillBeginZooming:scrollView withView:view); + RCT_FORWARD_SCROLL_EVENT(scrollViewWillBeginZooming : scrollView withView : view); } - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale { RCT_SEND_SCROLL_EVENT(onScrollEndDrag, nil); - RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndZooming:scrollView withView:view atScale:scale); + RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndZooming : scrollView withView : view atScale : scale); } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView @@ -809,7 +806,7 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) // Fire the end deceleration event RCT_SEND_SCROLL_EVENT(onMomentumScrollEnd, nil); - RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndDecelerating:scrollView); + RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndDecelerating : scrollView); } - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView @@ -820,14 +817,13 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) // Fire the end deceleration event RCT_SEND_SCROLL_EVENT(onMomentumScrollEnd, nil); - RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndScrollingAnimation:scrollView); + RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndScrollingAnimation : scrollView); } - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView { for (NSObject *scrollListener in _scrollListeners) { - if ([scrollListener respondsToSelector:_cmd] && - ![scrollListener scrollViewShouldScrollToTop:scrollView]) { + if ([scrollListener respondsToSelector:_cmd] && ![scrollListener scrollViewShouldScrollToTop:scrollView]) { return NO; } } @@ -852,8 +848,9 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) CGSize viewportSize = self.bounds.size; if (_automaticallyAdjustContentInsets) { UIEdgeInsets contentInsets = [RCTView contentInsetsForView:self]; - viewportSize = CGSizeMake(self.bounds.size.width - contentInsets.left - contentInsets.right, - self.bounds.size.height - contentInsets.top - contentInsets.bottom); + viewportSize = CGSizeMake( + self.bounds.size.width - contentInsets.left - contentInsets.right, + self.bounds.size.height - contentInsets.top - contentInsets.bottom); } return viewportSize; } @@ -943,23 +940,23 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) - (void)uiManagerWillPerformMounting:(RCTUIManager *)manager { RCTAssertUIManagerQueue(); - [manager prependUIBlock:^(__unused RCTUIManager *uiManager, __unused NSDictionary *viewRegistry) { - BOOL horz = [self isHorizontal:self->_scrollView]; - NSUInteger minIdx = [self->_maintainVisibleContentPosition[@"minIndexForVisible"] integerValue]; - for (NSUInteger ii = minIdx; ii < self->_contentView.subviews.count; ++ii) { - // Find the first entirely visible view. This must be done after we update the content offset - // or it will tend to grab rows that were made visible by the shift in position - UIView *subview = self->_contentView.subviews[ii]; - if ((horz - ? subview.frame.origin.x >= self->_scrollView.contentOffset.x - : subview.frame.origin.y >= self->_scrollView.contentOffset.y) || - ii == self->_contentView.subviews.count - 1) { - self->_prevFirstVisibleFrame = subview.frame; - self->_firstVisibleView = subview; - break; - } - } - }]; + [manager + prependUIBlock:^(__unused RCTUIManager *uiManager, __unused NSDictionary *viewRegistry) { + BOOL horz = [self isHorizontal:self->_scrollView]; + NSUInteger minIdx = [self->_maintainVisibleContentPosition[@"minIndexForVisible"] integerValue]; + for (NSUInteger ii = minIdx; ii < self->_contentView.subviews.count; ++ii) { + // Find the first entirely visible view. This must be done after we update the content offset + // or it will tend to grab rows that were made visible by the shift in position + UIView *subview = self->_contentView.subviews[ii]; + if ((horz ? subview.frame.origin.x >= self->_scrollView.contentOffset.x + : subview.frame.origin.y >= self->_scrollView.contentOffset.y) || + ii == self->_contentView.subviews.count - 1) { + self->_prevFirstVisibleFrame = subview.frame; + self->_firstVisibleView = subview; + break; + } + } + }]; [manager addUIBlock:^(__unused RCTUIManager *uiManager, __unused NSDictionary *viewRegistry) { if (self->_maintainVisibleContentPosition == nil) { return; // The prop might have changed in the previous UIBlocks, so need to abort here. @@ -969,10 +966,8 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) if ([self isHorizontal:self->_scrollView]) { CGFloat deltaX = self->_firstVisibleView.frame.origin.x - self->_prevFirstVisibleFrame.origin.x; if (ABS(deltaX) > 0.1) { - self->_scrollView.contentOffset = CGPointMake( - self->_scrollView.contentOffset.x + deltaX, - self->_scrollView.contentOffset.y - ); + self->_scrollView.contentOffset = + CGPointMake(self->_scrollView.contentOffset.x + deltaX, self->_scrollView.contentOffset.y); if (autoscrollThreshold != nil) { // If the offset WAS within the threshold of the start, animate to the start. if (self->_scrollView.contentOffset.x - deltaX <= [autoscrollThreshold integerValue]) { @@ -984,10 +979,8 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) CGRect newFrame = self->_firstVisibleView.frame; CGFloat deltaY = newFrame.origin.y - self->_prevFirstVisibleFrame.origin.y; if (ABS(deltaY) > 0.1) { - self->_scrollView.contentOffset = CGPointMake( - self->_scrollView.contentOffset.x, - self->_scrollView.contentOffset.y + deltaY - ); + self->_scrollView.contentOffset = + CGPointMake(self->_scrollView.contentOffset.x, self->_scrollView.contentOffset.y + deltaY); if (autoscrollThreshold != nil) { // If the offset WAS within the threshold of the start, animate to the start. if (self->_scrollView.contentOffset.y - deltaY <= [autoscrollThreshold integerValue]) { @@ -1005,16 +998,16 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) // restore it after the property has been set. #define RCT_SET_AND_PRESERVE_OFFSET(setter, getter, type) \ -- (void)setter:(type)value \ -{ \ - CGPoint contentOffset = _scrollView.contentOffset; \ - [_scrollView setter:value]; \ - _scrollView.contentOffset = contentOffset; \ -} \ -- (type)getter \ -{ \ - return [_scrollView getter]; \ -} + -(void)setter : (type)value \ + { \ + CGPoint contentOffset = _scrollView.contentOffset; \ + [_scrollView setter:value]; \ + _scrollView.contentOffset = contentOffset; \ + } \ + -(type)getter \ + { \ + return [_scrollView getter]; \ + } RCT_SET_AND_PRESERVE_OFFSET(setAlwaysBounceHorizontal, alwaysBounceHorizontal, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setAlwaysBounceVertical, alwaysBounceVertical, BOOL) @@ -1038,8 +1031,8 @@ RCT_SET_AND_PRESERVE_OFFSET(setZoomScale, zoomScale, CGFloat); RCT_SET_AND_PRESERVE_OFFSET(setScrollIndicatorInsets, scrollIndicatorInsets, UIEdgeInsets); #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */ -- (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior -API_AVAILABLE(ios(11.0)){ +- (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior API_AVAILABLE(ios(11.0)) +{ // `contentInsetAdjustmentBehavior` is available since iOS 11. if ([_scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) { CGPoint contentOffset = _scrollView.contentOffset; diff --git a/React/Views/ScrollView/RCTScrollViewManager.m b/React/Views/ScrollView/RCTScrollViewManager.m index 06e5ff82a31..cb5700ca6de 100644 --- a/React/Views/ScrollView/RCTScrollViewManager.m +++ b/React/Views/ScrollView/RCTScrollViewManager.m @@ -20,29 +20,41 @@ @implementation RCTConvert (UIScrollView) -RCT_ENUM_CONVERTER(UIScrollViewKeyboardDismissMode, (@{ - @"none": @(UIScrollViewKeyboardDismissModeNone), - @"on-drag": @(UIScrollViewKeyboardDismissModeOnDrag), - @"interactive": @(UIScrollViewKeyboardDismissModeInteractive), - // Backwards compatibility - @"onDrag": @(UIScrollViewKeyboardDismissModeOnDrag), -}), UIScrollViewKeyboardDismissModeNone, integerValue) +RCT_ENUM_CONVERTER( + UIScrollViewKeyboardDismissMode, + (@{ + @"none" : @(UIScrollViewKeyboardDismissModeNone), + @"on-drag" : @(UIScrollViewKeyboardDismissModeOnDrag), + @"interactive" : @(UIScrollViewKeyboardDismissModeInteractive), + // Backwards compatibility + @"onDrag" : @(UIScrollViewKeyboardDismissModeOnDrag), + }), + UIScrollViewKeyboardDismissModeNone, + integerValue) -RCT_ENUM_CONVERTER(UIScrollViewIndicatorStyle, (@{ - @"default": @(UIScrollViewIndicatorStyleDefault), - @"black": @(UIScrollViewIndicatorStyleBlack), - @"white": @(UIScrollViewIndicatorStyleWhite), -}), UIScrollViewIndicatorStyleDefault, integerValue) +RCT_ENUM_CONVERTER( + UIScrollViewIndicatorStyle, + (@{ + @"default" : @(UIScrollViewIndicatorStyleDefault), + @"black" : @(UIScrollViewIndicatorStyleBlack), + @"white" : @(UIScrollViewIndicatorStyleWhite), + }), + UIScrollViewIndicatorStyleDefault, + integerValue) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */ -RCT_ENUM_CONVERTER(UIScrollViewContentInsetAdjustmentBehavior, (@{ - @"automatic": @(UIScrollViewContentInsetAdjustmentAutomatic), - @"scrollableAxes": @(UIScrollViewContentInsetAdjustmentScrollableAxes), - @"never": @(UIScrollViewContentInsetAdjustmentNever), - @"always": @(UIScrollViewContentInsetAdjustmentAlways), -}), UIScrollViewContentInsetAdjustmentNever, integerValue) +RCT_ENUM_CONVERTER( + UIScrollViewContentInsetAdjustmentBehavior, + (@{ + @"automatic" : @(UIScrollViewContentInsetAdjustmentAutomatic), + @"scrollableAxes" : @(UIScrollViewContentInsetAdjustmentScrollableAxes), + @"never" : @(UIScrollViewContentInsetAdjustmentNever), + @"always" : @(UIScrollViewContentInsetAdjustmentAlways), + }), + UIScrollViewContentInsetAdjustmentNever, + integerValue) #endif #pragma clang diagnostic pop @@ -108,111 +120,111 @@ RCT_EXPORT_VIEW_PROPERTY(contentInsetAdjustmentBehavior, UIScrollViewContentInse // is set to from js we want to clip drawing or not. This piece of code ensures // that css-layout is always treating the contents of a scroll container as // overflow: 'scroll'. -RCT_CUSTOM_SHADOW_PROPERTY(overflow, YGOverflow, RCTShadowView) { -#pragma unused (json) +RCT_CUSTOM_SHADOW_PROPERTY(overflow, YGOverflow, RCTShadowView) +{ +#pragma unused(json) view.overflow = YGOverflowScroll; } -RCT_EXPORT_METHOD(getContentSize:(nonnull NSNumber *)reactTag - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(getContentSize : (nonnull NSNumber *)reactTag callback : (RCTResponseSenderBlock)callback) { - [self.bridge.uiManager addUIBlock: - ^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + [self.bridge.uiManager + addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + RCTScrollView *view = viewRegistry[reactTag]; + if (!view || ![view isKindOfClass:[RCTScrollView class]]) { + RCTLogError(@"Cannot find RCTScrollView with tag #%@", reactTag); + return; + } - RCTScrollView *view = viewRegistry[reactTag]; - if (!view || ![view isKindOfClass:[RCTScrollView class]]) { - RCTLogError(@"Cannot find RCTScrollView with tag #%@", reactTag); - return; - } - - CGSize size = view.scrollView.contentSize; - callback(@[@{ - @"width" : @(size.width), - @"height" : @(size.height) - }]); - }]; + CGSize size = view.scrollView.contentSize; + callback(@[ @{@"width" : @(size.width), @"height" : @(size.height)} ]); + }]; } -RCT_EXPORT_METHOD(calculateChildFrames:(nonnull NSNumber *)reactTag - callback:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(calculateChildFrames : (nonnull NSNumber *)reactTag callback : (RCTResponseSenderBlock)callback) { - [self.bridge.uiManager addUIBlock: - ^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + [self.bridge.uiManager + addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + RCTScrollView *view = viewRegistry[reactTag]; + if (!view || ![view isKindOfClass:[RCTScrollView class]]) { + RCTLogError(@"Cannot find RCTScrollView with tag #%@", reactTag); + return; + } - RCTScrollView *view = viewRegistry[reactTag]; - if (!view || ![view isKindOfClass:[RCTScrollView class]]) { - RCTLogError(@"Cannot find RCTScrollView with tag #%@", reactTag); - return; - } - - NSArray *childFrames = [view calculateChildFramesData]; - if (childFrames) { - callback(@[childFrames]); - } - }]; + NSArray *childFrames = [view calculateChildFramesData]; + if (childFrames) { + callback(@[ childFrames ]); + } + }]; } -RCT_EXPORT_METHOD(scrollTo:(nonnull NSNumber *)reactTag - offsetX:(CGFloat)x - offsetY:(CGFloat)y - animated:(BOOL)animated) +RCT_EXPORT_METHOD(scrollTo + : (nonnull NSNumber *)reactTag offsetX + : (CGFloat)x offsetY + : (CGFloat)y animated + : (BOOL)animated) { - [self.bridge.uiManager addUIBlock: - ^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry){ - UIView *view = viewRegistry[reactTag]; - if ([view conformsToProtocol:@protocol(RCTScrollableProtocol)]) { - [(id)view scrollToOffset:(CGPoint){x, y} animated:animated]; - } else { - RCTLogError(@"tried to scrollTo: on non-RCTScrollableProtocol view %@ " - "with tag #%@", view, reactTag); - } - }]; + [self.bridge.uiManager + addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + UIView *view = viewRegistry[reactTag]; + if ([view conformsToProtocol:@protocol(RCTScrollableProtocol)]) { + [(id)view scrollToOffset:(CGPoint){x, y} animated:animated]; + } else { + RCTLogError( + @"tried to scrollTo: on non-RCTScrollableProtocol view %@ " + "with tag #%@", + view, + reactTag); + } + }]; } -RCT_EXPORT_METHOD(scrollToEnd:(nonnull NSNumber *)reactTag - animated:(BOOL)animated) +RCT_EXPORT_METHOD(scrollToEnd : (nonnull NSNumber *)reactTag animated : (BOOL)animated) { - [self.bridge.uiManager addUIBlock: - ^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry){ - UIView *view = viewRegistry[reactTag]; - if ([view conformsToProtocol:@protocol(RCTScrollableProtocol)]) { - [(id)view scrollToEnd:animated]; - } else { - RCTLogError(@"tried to scrollTo: on non-RCTScrollableProtocol view %@ " - "with tag #%@", view, reactTag); - } - }]; + [self.bridge.uiManager + addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + UIView *view = viewRegistry[reactTag]; + if ([view conformsToProtocol:@protocol(RCTScrollableProtocol)]) { + [(id)view scrollToEnd:animated]; + } else { + RCTLogError( + @"tried to scrollTo: on non-RCTScrollableProtocol view %@ " + "with tag #%@", + view, + reactTag); + } + }]; } -RCT_EXPORT_METHOD(zoomToRect:(nonnull NSNumber *)reactTag - withRect:(CGRect)rect - animated:(BOOL)animated) +RCT_EXPORT_METHOD(zoomToRect : (nonnull NSNumber *)reactTag withRect : (CGRect)rect animated : (BOOL)animated) { - [self.bridge.uiManager addUIBlock: - ^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry){ - UIView *view = viewRegistry[reactTag]; - if ([view conformsToProtocol:@protocol(RCTScrollableProtocol)]) { - [(id)view zoomToRect:rect animated:animated]; - } else { - RCTLogError(@"tried to zoomToRect: on non-RCTScrollableProtocol view %@ " - "with tag #%@", view, reactTag); - } - }]; + [self.bridge.uiManager + addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + UIView *view = viewRegistry[reactTag]; + if ([view conformsToProtocol:@protocol(RCTScrollableProtocol)]) { + [(id)view zoomToRect:rect animated:animated]; + } else { + RCTLogError( + @"tried to zoomToRect: on non-RCTScrollableProtocol view %@ " + "with tag #%@", + view, + reactTag); + } + }]; } -RCT_EXPORT_METHOD(flashScrollIndicators:(nonnull NSNumber *)reactTag) +RCT_EXPORT_METHOD(flashScrollIndicators : (nonnull NSNumber *)reactTag) { - [self.bridge.uiManager addUIBlock: - ^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry){ + [self.bridge.uiManager + addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { + RCTScrollView *view = viewRegistry[reactTag]; + if (!view || ![view isKindOfClass:[RCTScrollView class]]) { + RCTLogError(@"Cannot find RCTScrollView with tag #%@", reactTag); + return; + } - RCTScrollView *view = viewRegistry[reactTag]; - if (!view || ![view isKindOfClass:[RCTScrollView class]]) { - RCTLogError(@"Cannot find RCTScrollView with tag #%@", reactTag); - return; - } - - [view.scrollView flashScrollIndicators]; - }]; + [view.scrollView flashScrollIndicators]; + }]; } @end diff --git a/React/Views/ScrollView/RCTScrollableProtocol.h b/React/Views/ScrollView/RCTScrollableProtocol.h index 0ebb6f1339f..7800e796cc8 100644 --- a/React/Views/ScrollView/RCTScrollableProtocol.h +++ b/React/Views/ScrollView/RCTScrollableProtocol.h @@ -5,8 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -#import #import +#import /** * Contains any methods related to scrolling. Any `RCTView` that has scrolling diff --git a/React/Views/UIView+React.h b/React/Views/UIView+React.h index 7e38fba8382..67c665b2bc7 100644 --- a/React/Views/UIView+React.h +++ b/React/Views/UIView+React.h @@ -118,7 +118,7 @@ */ @property (nonatomic, copy) NSString *accessibilityRole; @property (nonatomic, copy) NSDictionary *accessibilityState; -@property (nonatomic, copy) NSArray *accessibilityActions; +@property (nonatomic, copy) NSArray *accessibilityActions; @property (nonatomic, copy) NSDictionary *accessibilityValueInternal; /** diff --git a/React/Views/UIView+React.m b/React/Views/UIView+React.m index fff3227c0ac..60b30d9a111 100644 --- a/React/Views/UIView+React.m +++ b/React/Views/UIView+React.m @@ -48,19 +48,19 @@ - (BOOL)shouldAccessibilityIgnoresInvertColors { #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */ - if (@available(iOS 11.0, *)) { - return self.accessibilityIgnoresInvertColors; - } + if (@available(iOS 11.0, *)) { + return self.accessibilityIgnoresInvertColors; + } #endif - return NO; + return NO; } - (void)setShouldAccessibilityIgnoresInvertColors:(BOOL)shouldAccessibilityIgnoresInvertColors { #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */ - if (@available(iOS 11.0, *)) { - self.accessibilityIgnoresInvertColors = shouldAccessibilityIgnoresInvertColors; - } + if (@available(iOS 11.0, *)) { + self.accessibilityIgnoresInvertColors = shouldAccessibilityIgnoresInvertColors; + } #endif } @@ -135,12 +135,12 @@ - (void)setReactLayoutDirection:(UIUserInterfaceLayoutDirection)layoutDirection { if ([self respondsToSelector:@selector(setSemanticContentAttribute:)]) { - self.semanticContentAttribute = - layoutDirection == UIUserInterfaceLayoutDirectionLeftToRight ? - UISemanticContentAttributeForceLeftToRight : - UISemanticContentAttributeForceRightToLeft; + self.semanticContentAttribute = layoutDirection == UIUserInterfaceLayoutDirectionLeftToRight + ? UISemanticContentAttributeForceLeftToRight + : UISemanticContentAttributeForceRightToLeft; } else { - objc_setAssociatedObject(self, @selector(reactLayoutDirection), @(layoutDirection), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject( + self, @selector(reactLayoutDirection), @(layoutDirection), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } } @@ -174,7 +174,8 @@ // that original order is preserved. return NSOrderedAscending; } - }] : self.subviews; + }] + : self.subviews; } - (void)didUpdateReactSubviews @@ -198,11 +199,14 @@ CGRect bounds = {CGPointZero, frame.size}; // Avoid crashes due to nan coords - if (isnan(position.x) || isnan(position.y) || - isnan(bounds.origin.x) || isnan(bounds.origin.y) || + if (isnan(position.x) || isnan(position.y) || isnan(bounds.origin.x) || isnan(bounds.origin.y) || isnan(bounds.size.width) || isnan(bounds.size.height)) { - RCTLogError(@"Invalid layout for (%@)%@. position: %@. bounds: %@", - self.reactTag, self, NSStringFromCGPoint(position), NSStringFromCGRect(bounds)); + RCTLogError( + @"Invalid layout for (%@)%@. position: %@. bounds: %@", + self.reactTag, + self, + NSStringFromCGPoint(position), + NSStringFromCGRect(bounds)); return; } @@ -251,13 +255,15 @@ objc_setAssociatedObject(self, @selector(reactIsFocusNeeded), @(isFocusNeeded), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } -- (void)reactFocus { +- (void)reactFocus +{ if (![self becomeFirstResponder]) { self.reactIsFocusNeeded = YES; } } -- (void)reactFocusIfNeeded { +- (void)reactFocusIfNeeded +{ if (self.reactIsFocusNeeded) { if ([self becomeFirstResponder]) { self.reactIsFocusNeeded = NO; @@ -265,7 +271,8 @@ } } -- (void)reactBlur { +- (void)reactBlur +{ [self resignFirstResponder]; } @@ -288,11 +295,10 @@ UIEdgeInsets paddingInsets = self.reactPaddingInsets; return UIEdgeInsetsMake( - borderInsets.top + paddingInsets.top, - borderInsets.left + paddingInsets.left, - borderInsets.bottom + paddingInsets.bottom, - borderInsets.right + paddingInsets.right - ); + borderInsets.top + paddingInsets.top, + borderInsets.left + paddingInsets.left, + borderInsets.bottom + paddingInsets.bottom, + borderInsets.right + paddingInsets.right); } - (CGRect)reactContentFrame @@ -314,7 +320,8 @@ - (void)setAccessibilityActions:(NSArray *)accessibilityActions { - objc_setAssociatedObject(self, @selector(accessibilityActions), accessibilityActions, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject( + self, @selector(accessibilityActions), accessibilityActions, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (NSString *)accessibilityRole @@ -343,7 +350,8 @@ } - (void)setAccessibilityValueInternal:(NSDictionary *)accessibilityValue { - objc_setAssociatedObject(self, @selector(accessibilityValueInternal), accessibilityValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject( + self, @selector(accessibilityValueInternal), accessibilityValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - Debug