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
This commit is contained in:
Valentin Shergin 2020-03-08 22:58:01 -07:00 коммит произвёл Facebook Github Bot
Родитель a426c8dc77
Коммит d0871d0a9a
198 изменённых файлов: 5524 добавлений и 5207 удалений

Просмотреть файл

@ -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<NSDictionary<NSString *, id> *> *stacktrace, NSUInteger maxMessageLength);
RCT_EXTERN NSString *
RCTFormatError(NSString *message, NSArray<NSDictionary<NSString *, id> *> *stacktrace, NSUInteger maxMessageLength);
/**
* Formats a JS stack trace for logging.
@ -145,20 +149,19 @@ RCT_EXTERN NSString *RCTFormatStackTrace(NSArray<NSDictionary<NSString *, id> *>
*/
#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

Просмотреть файл

@ -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: <underlying error description>
// reason: <underlying error description plus JS stack trace, truncated to 175 characters>
// userInfo: <underlying error userinfo, plus untruncated description plus JS stack trace>
@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<NSDictionary<NSString *, id> *> *stackTrace, NSUInteger maxMessageLength)
NSString *
RCTFormatError(NSString *message, NSArray<NSDictionary<NSString *, id> *> *stackTrace, NSUInteger maxMessageLength)
{
if (maxMessageLength > 0 && message.length > maxMessageLength) {
message = [[message substringToIndex:maxMessageLength] stringByAppendingString:@"..."];
@ -168,26 +169,31 @@ NSString *RCTFormatError(NSString *message, NSArray<NSDictionary<NSString *, id>
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<NSDictionary<NSString *, id> *> *stackTrace) {
NSString *RCTFormatStackTrace(NSArray<NSDictionary<NSString *, id> *> *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<NSString *, id> *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
}
}

Просмотреть файл

@ -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<RCTBridgeModule>)module
withModuleData:(RCTModuleData *)moduleData;
- (void)registerModuleForFrameUpdates:(id<RCTBridgeModule>)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

Просмотреть файл

@ -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<id<RCTBridgeModule>> *(^RCTBridgeModuleListProvider)(void);
typedef NSArray<id<RCTBridgeModule>> * (^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<RCTBridgeDelegate>)delegate
launchOptions:(NSDictionary *)launchOptions;
- (instancetype)initWithDelegate:(id<RCTBridgeDelegate>)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.

Просмотреть файл

@ -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 () <RCTReloadListener>
@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<RCTBridgeDelegate>)delegate
launchOptions:(NSDictionary *)launchOptions
- (instancetype)initWithDelegate:(id<RCTBridgeDelegate>)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<RCTBridgeDelegate>)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;

Просмотреть файл

@ -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.

Просмотреть файл

@ -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

Просмотреть файл

@ -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) <RCTBridgeModule> \
@end \
@implementation objc_name (RCTExternModule) \
objc_name: \
objc_supername @ \
end @interface objc_name(RCTExternModule)<RCTBridgeModule> \
@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 <NSObject>
- (id)moduleForName:(const char *)moduleName;
@protocol RCTTurboModuleLookupDelegate <NSObject>
- (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.

Просмотреть файл

@ -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

Просмотреть файл

@ -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;

Просмотреть файл

@ -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<RCTEvent>
@interface RCTComponentEvent : NSObject <RCTEvent>
- (instancetype)initWithName:(NSString *)name viewTag:(NSNumber *)viewTag body:(NSDictionary *)body;

Просмотреть файл

@ -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
{

Просмотреть файл

@ -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<type *> *)name##Array:(id)json RCT_DYNAMIC \
{ \
return RCTConvertArrayValue(@selector(name:), json); \
}
#define RCT_ARRAY_CONVERTER_NAMED(type, name) \
+(NSArray<type *> *)name##Array : (id)json RCT_DYNAMIC \
{ \
return RCTConvertArrayValue(@selector(name:), json); \
}
/**
* This macro is used for creating converter functions for typed arrays.

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -6,7 +6,7 @@
*/
#if __OBJC__
# import <Foundation/Foundation.h>
#import <Foundation/Foundation.h>
#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.

Просмотреть файл

@ -14,8 +14,7 @@
- (instancetype)init;
- (void)invalidate;
- (void)registerModuleForFrameUpdates:(id<RCTBridgeModule>)module
withModuleData:(RCTModuleData *)moduleData;
- (void)registerModuleForFrameUpdates:(id<RCTBridgeModule>)module withModuleData:(RCTModuleData *)moduleData;
- (void)addToRunLoop:(NSRunLoop *)runLoop;
@end

Просмотреть файл

@ -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<RCTModuleData *> *_frameUpdateObservers;
NSRunLoop *_runLoop;
@ -37,8 +35,7 @@
return self;
}
- (void)registerModuleForFrameUpdates:(id<RCTBridgeModule>)module
withModuleData:(RCTModuleData *)moduleData
- (void)registerModuleForFrameUpdates:(id<RCTBridgeModule>)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];
}

Просмотреть файл

@ -16,8 +16,6 @@
@property (nonatomic, copy, readonly) NSString *errorMessage;
@property (nonatomic, copy, readonly) NSArray<RCTJSStackFrame *> *stack;
- (instancetype)initWithErrorMessage:(NSString *)errorMessage
stack:(NSArray<RCTJSStackFrame *> *)stack;
- (instancetype)initWithErrorMessage:(NSString *)errorMessage stack:(NSArray<RCTJSStackFrame *> *)stack;
@end

Просмотреть файл

@ -11,8 +11,8 @@
@implementation RCTErrorInfo
- (instancetype)initWithErrorMessage:(NSString *)errorMessage
stack:(NSArray<RCTJSStackFrame *> *)stack {
- (instancetype)initWithErrorMessage:(NSString *)errorMessage stack:(NSArray<RCTJSStackFrame *> *)stack
{
self = [super init];
if (self) {
_errorMessage = [errorMessage copy];

Просмотреть файл

@ -9,8 +9,7 @@
#import <React/RCTBridge.h>
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.

Просмотреть файл

@ -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<NSNumber *, id<RCTEvent>> *_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<RCTEvent> 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];
}
}

Просмотреть файл

@ -13,7 +13,7 @@
@implementation RCTFrameUpdate
RCT_NOT_IMPLEMENTED(- (instancetype)init)
RCT_NOT_IMPLEMENTED(-(instancetype)init)
- (instancetype)initWithDisplayLink:(CADisplayLink *)displayLink
{

Просмотреть файл

@ -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.

Просмотреть файл

@ -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:@"<RCTImageSource: %p URL=%@, size=%@, scale=%0.f>",
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;
}

Просмотреть файл

@ -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);

Просмотреть файл

@ -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;

Просмотреть файл

@ -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:&regexError];
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

Просмотреть файл

@ -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`

Просмотреть файл

@ -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

Просмотреть файл

@ -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<NSDictionary *> *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

Просмотреть файл

@ -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

Просмотреть файл

@ -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;
}

Просмотреть файл

@ -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 *);

Просмотреть файл

@ -12,21 +12,21 @@
#import <objc/message.h>
#import <os/log.h>
#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:&regexError];
_regex = [NSRegularExpression regularExpressionWithPattern:@"0x[0-9a-f]+ (.*) \\+ (\\d+)$"
options:0
error:&regexError];
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<NSString *> *stackSymbols = [NSThread callStackSymbols];
NSMutableArray<NSDictionary *> *stack =
[NSMutableArray arrayWithCapacity:(stackSymbols.count - 1)];
NSMutableArray<NSDictionary *> *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<NSDictionary *> *) = (__typeof__(showErrorMessage))objc_msgSend;
void (*showErrorMessage)(id, SEL, NSString *, NSMutableArray<NSDictionary *> *) =
(__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
}
}

Просмотреть файл

@ -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

Просмотреть файл

@ -11,14 +11,16 @@
std::shared_ptr<void> _pointer;
}
- (instancetype)initWithPointer:(std::shared_ptr<void>)pointer {
- (instancetype)initWithPointer:(std::shared_ptr<void>)pointer
{
if (self = [super init]) {
_pointer = std::move(pointer);
}
return self;
}
- (void *)voidPointer {
- (void *)voidPointer
{
return _pointer.get();
}

Просмотреть файл

@ -13,12 +13,11 @@
@protocol RCTBridgeModule;
@class RCTBridge;
typedef id<RCTBridgeModule>(^RCTBridgeModuleProvider)(void);
typedef id<RCTBridgeModule> (^RCTBridgeModuleProvider)(void);
@interface RCTModuleData : NSObject <RCTInvalidating>
- (instancetype)initWithModuleClass:(Class)moduleClass
bridge:(RCTBridge *)bridge;
- (instancetype)initWithModuleClass:(Class)moduleClass bridge:(RCTBridge *)bridge;
- (instancetype)initWithModuleClass:(Class)moduleClass
moduleProvider:(RCTBridgeModuleProvider)moduleProvider

Просмотреть файл

@ -17,8 +17,7 @@
#import "RCTProfile.h"
#import "RCTUtils.h"
@implementation RCTModuleData
{
@implementation RCTModuleData {
NSDictionary<NSString *, id> *_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<RCTBridgeModule>{ return [moduleClass new]; }
moduleProvider:^id<RCTBridgeModule> {
return [moduleClass new];
}
bridge:bridge];
}
@ -91,8 +95,7 @@
return self;
}
- (instancetype)initWithModuleInstance:(id<RCTBridgeModule>)instance
bridge:(RCTBridge *)bridge
- (instancetype)initWithModuleInstance:(id<RCTBridgeModule>)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<std::mutex> 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<id<RCTBridgeMethod>> *moduleMethods = [NSMutableArray new];
NSMutableDictionary<NSString *, id<RCTBridgeMethod>> *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<RCTBridgeMethod> moduleMethod = [[RCTModuleMethod alloc] initWithExportedMethod:exportedMethod
moduleClass:_moduleClass];
NSString *str = [NSString stringWithUTF8String:moduleMethod.JSMethodName];
[moduleMethodsByName setValue:moduleMethod forKey:str];
[moduleMethods addObject:moduleMethod];
}
}
NSMutableArray<id<RCTBridgeMethod>> *moduleMethods = [NSMutableArray new];
NSMutableDictionary<NSString *, id<RCTBridgeMethod>> *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<RCTBridgeMethod> 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<RCTBridgeModule>)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<id<RCTBridgeMethod>> *)methods
{
[self calculateMethods];
return _methods;
[self calculateMethods];
return _methods;
}
- (NSDictionary<NSString *, id<RCTBridgeMethod>> *)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;
}

Просмотреть файл

@ -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<RCTMethodArgument *
// Parse type
if (RCTReadChar(&input, '(')) {
RCTSkipWhitespace(&input);
// 5 cases that both nullable and __unused exist
// 1: foo:(nullable __unused id)foo 2: foo:(nullable id __unused)foo
// 3: foo:(__unused id _Nullable)foo 4: foo:(id __unused _Nullable)foo
// 5: foo:(id _Nullable __unused)foo
RCTNullability nullability = RCTParseNullability(&input);
RCTSkipWhitespace(&input);
BOOL unused = RCTParseUnused(&input);
RCTSkipWhitespace(&input);
NSString *type = RCTParseType(&input);
RCTSkipWhitespace(&input);
if (nullability == RCTNullabilityUnspecified) {
nullability = RCTParseNullabilityPostfix(&input);
RCTSkipWhitespace(&input);
@ -173,17 +172,13 @@ NSString *RCTParseMethodSignature(const char *input, NSArray<RCTMethodArgument *
unused = RCTParseUnused(&input);
RCTSkipWhitespace(&input);
}
[args addObject:[[RCTMethodArgument alloc] initWithType:type
nullability:nullability
unused:unused]];
[args addObject:[[RCTMethodArgument alloc] initWithType:type nullability:nullability unused:unused]];
RCTSkipWhitespace(&input);
RCTReadChar(&input, ')');
RCTSkipWhitespace(&input);
} else {
// Type defaults to id if unspecified
[args addObject:[[RCTMethodArgument alloc] initWithType:@"id"
nullability:RCTNullable
unused:NO]];
[args addObject:[[RCTMethodArgument alloc] initWithType:@"id" nullability:RCTNullable unused:NO]];
}
// Argument name
@ -197,8 +192,7 @@ NSString *RCTParseMethodSignature(const char *input, NSArray<RCTMethodArgument *
RCT_EXTERN_C_END
- (instancetype)initWithExportedMethod:(const RCTMethodInfo *)exportedMethod
moduleClass:(Class)moduleClass
- (instancetype)initWithExportedMethod:(const RCTMethodInfo *)exportedMethod moduleClass:(Class)moduleClass
{
if (self = [super init]) {
_moduleClass = moduleClass;
@ -224,33 +218,32 @@ RCT_EXTERN_C_END
// Process arguments
NSUInteger numberOfArguments = methodSignature.numberOfArguments;
NSMutableArray<RCTArgumentBlock> *argumentBlocks =
[[NSMutableArray alloc] initWithCapacity:numberOfArguments - 2];
NSMutableArray<RCTArgumentBlock> *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

Просмотреть файл

@ -9,7 +9,12 @@
#import <React/RCTMultipartStreamReader.h>
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

Просмотреть файл

@ -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

Просмотреть файл

@ -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

Просмотреть файл

@ -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;

Просмотреть файл

@ -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

Просмотреть файл

@ -7,13 +7,12 @@
#import <QuartzCore/QuartzCore.h>
#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

Просмотреть файл

@ -7,7 +7,8 @@
#import <React/RCTDefines.h>
// 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);

Просмотреть файл

@ -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;
}

Просмотреть файл

@ -34,10 +34,9 @@ void RCTRegisterReloadCommandListener(id<RCTReloadListener> 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<RCTReloadListener> l in [listeners allObjects]) {

Просмотреть файл

@ -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];
}
}

Просмотреть файл

@ -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.

Просмотреть файл

@ -12,8 +12,8 @@
#import <objc/runtime.h>
#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

Просмотреть файл

@ -7,7 +7,6 @@
#import <UIKit/UIKit.h>
extern NSString *const RCTTVRemoteEventMenu;
extern NSString *const RCTTVRemoteEventPlayPause;
extern NSString *const RCTTVRemoteEventSelect;

Просмотреть файл

@ -41,7 +41,6 @@ NSString *const RCTTVRemoteEventSwipeRight = @"swipeRight";
NSString *const RCTTVRemoteEventSwipeUp = @"swipeUp";
NSString *const RCTTVRemoteEventSwipeDown = @"swipeDown";
@implementation RCTTVRemoteHandler {
NSMutableDictionary<NSString *, UIGestureRecognizer *> *_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

Просмотреть файл

@ -9,8 +9,7 @@
#import "RCTAssert.h"
@implementation RCTTouchEvent
{
@implementation RCTTouchEvent {
NSArray<NSDictionary *> *_reactTouches;
NSArray<NSNumber *> *_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<RCTEvent>)coalesceWithEvent:(id<RCTEvent>)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<count; i++) {
for (int i = 0; i < count; i++) {
NSDictionary *touch = _reactTouches[i];
NSDictionary *newTouch = newTouchEvent->_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

Просмотреть файл

@ -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<UITouch *> *)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<UITouch *> *)touches
eventName:(NSString *)eventName
- (void)_updateAndDispatchTouches:(NSSet<UITouch *> *)touches eventName:(NSString *)eventName
{
// Update touches
NSMutableArray<NSNumber *> *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<NSDictionary *> *reactTouches =
[[NSMutableArray alloc] initWithCapacity:_reactTouches.count];
NSMutableArray<NSDictionary *> *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<UITouch *> *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<UITouch *> *touches)
static BOOL RCTAnyTouchesChanged(NSSet<UITouch *> *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<UITouch *> *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];

Просмотреть файл

@ -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<RCTURLRequestDelegate>)delegate;
- (id)sendRequest:(NSURLRequest *)request withDelegate:(id<RCTURLRequestDelegate>)delegate;
@optional

Просмотреть файл

@ -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<NSString *, id> *RCTMakeError(NSString *message, id __nullable toStringify, NSDictionary<NSString *, id> *__nullable extraData);
RCT_EXTERN NSDictionary<NSString *, id> *RCTMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary<NSString *, id> *__nullable extraData);
RCT_EXTERN NSDictionary<NSString *, id>
*RCTMakeError(NSString *message, id __nullable toStringify, NSDictionary<NSString *, id> *__nullable extraData);
RCT_EXTERN NSDictionary<NSString *, id> *
RCTMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary<NSString *, id> *__nullable extraData);
RCT_EXTERN NSDictionary<NSString *, id> *RCTJSErrorFromNSError(NSError *error);
RCT_EXTERN NSDictionary<NSString *, id> *RCTJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error);
RCT_EXTERN NSDictionary<NSString *, id>
*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

Просмотреть файл

@ -17,9 +17,9 @@
#import <CommonCrypto/CommonCrypto.h>
#import <React/RCTUtilsUIOverride.h>
#import "RCTAssert.h"
#import "RCTLog.h"
#import <React/RCTUtilsUIOverride.h>
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<Class> *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<NSString *, id> *RCTMakeError(NSString *message,
id __nullable toStringify,
NSDictionary<NSString *, id> *__nullable extraData)
NSDictionary<NSString *, id>
*RCTMakeError(NSString *message, id __nullable toStringify, NSDictionary<NSString *, id> *__nullable extraData)
{
if (toStringify) {
message = [message stringByAppendingString:[toStringify description]];
@ -410,9 +412,8 @@ NSDictionary<NSString *, id> *RCTMakeError(NSString *message,
return error;
}
NSDictionary<NSString *, id> *RCTMakeAndLogError(NSString *message,
id __nullable toStringify,
NSDictionary<NSString *, id> *__nullable extraData)
NSDictionary<NSString *, id> *
RCTMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary<NSString *, id> *__nullable extraData)
{
NSDictionary<NSString *, id> *error = RCTMakeError(message, toStringify, extraData);
RCTLogError(@"\nError: %@", error);
@ -421,22 +422,20 @@ NSDictionary<NSString *, id> *RCTMakeAndLogError(NSString *message,
NSDictionary<NSString *, id> *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<NSString *, id> *RCTJSErrorFromCodeMessageAndNSError(NSString *code,
NSString *message,
NSError *__nullable error)
NSDictionary<NSString *, id>
*RCTJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error)
{
NSString *errorMessage;
NSArray<NSString *> *stackTrace = [NSThread callStackSymbols];
NSMutableDictionary *userInfo;
NSMutableDictionary<NSString *, id> *errorInfo =
[NSMutableDictionary dictionaryWithObject:stackTrace forKey:@"nativeStackIOS"];
NSMutableDictionary<NSString *, id> *errorInfo = [NSMutableDictionary dictionaryWithObject:stackTrace
forKey:@"nativeStackIOS"];
if (error) {
errorMessage = error.localizedDescription ?: @"Unknown error from a native module";
@ -446,7 +445,8 @@ NSDictionary<NSString *, id> *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<NSString *, id> *errorInfo = @{NSLocalizedDescriptionKey: message};
NSDictionary<NSString *, id> *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<NSURL *> *possibleFrameworks = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[[NSBundle mainBundle] privateFrameworksURL]
includingPropertiesForKeys:@[]
options:0
error:nil];
NSArray<NSURL *> *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<NSURLQueryItem *> *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;
}

Просмотреть файл

@ -5,14 +5,13 @@
* LICENSE file in the root directory of this source tree.
*/
#import <Foundation/Foundation.h>
#import <React/RCTDefines.h>
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);

Просмотреть файл

@ -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.

Просмотреть файл

@ -9,6 +9,7 @@
#import "RCTSurfaceView+Internal.h"
#import <mutex>
#import <stdatomic.h>
#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<std::mutex> 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

Просмотреть файл

@ -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;
}

Просмотреть файл

@ -11,6 +11,6 @@
@implementation RCTSurfaceRootView
RCT_NOT_IMPLEMENTED(- (nullable instancetype)initWithCoder:(NSCoder *)coder)
RCT_NOT_IMPLEMENTED(-(nullable instancetype)initWithCoder : (NSCoder *)coder)
@end

Просмотреть файл

@ -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,
};

Просмотреть файл

@ -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);
}

Просмотреть файл

@ -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];
}
}

Просмотреть файл

@ -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

Просмотреть файл

@ -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

Просмотреть файл

@ -14,7 +14,7 @@
@class RCTBridge;
@class RCTSurface;
typedef UIView *_Nullable(^RCTSurfaceHostingViewActivityIndicatorViewFactory)(void);
typedef UIView *_Nullable (^RCTSurfaceHostingViewActivityIndicatorViewFactory)(void);
NS_ASSUME_NONNULL_BEGIN

Просмотреть файл

@ -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

Просмотреть файл

@ -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);

Просмотреть файл

@ -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;
}
}

Просмотреть файл

@ -8,15 +8,16 @@
#import "RCTAccessibilityManager.h"
#import <FBReactNativeSpec/FBReactNativeSpec.h>
#import <React/RCTUIManager.h>
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTLog.h>
#import <React/RCTUIManager.h>
#import "CoreModulesPlugins.h"
NSString *const RCTAccessibilityManagerDidUpdateMultiplierNotification = @"RCTAccessibilityManagerDidUpdateMultiplierNotification";
NSString *const RCTAccessibilityManagerDidUpdateMultiplierNotification =
@"RCTAccessibilityManagerDidUpdateMultiplierNotification";
@interface RCTAccessibilityManager () <NativeAccessibilityManagerSpec>
@ -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<NSString *, NSNumber *> *)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<NSString *, NSNumber *> *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<NSString *, NSNumber *> *multipliers,
NSString *key,
folly::Optional<double> optionalDouble)
static void setMultipliers(
NSMutableDictionary<NSString *, NSNumber *> *multipliers,
NSString *key,
folly::Optional<double> 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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeAccessibilityManagerSpecJSI>(self, jsInvoker);
}

Просмотреть файл

@ -23,8 +23,7 @@ using namespace facebook::react;
@interface RCTActionSheetManager () <UIActionSheetDelegate, NativeActionSheetManagerSpec>
@end
@implementation RCTActionSheetManager
{
@implementation RCTActionSheetManager {
// Use NSMapTable, as UIAlertViews do not implement <NSCopying>
// 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<NSString *> *buttons = RCTConvertOptionalVecToArray(options.options(), ^id(NSString *element) { return element; });
NSInteger cancelButtonIndex = options.cancelButtonIndex() ? [RCTConvert NSInteger:@(*options.cancelButtonIndex())] : -1;
NSArray<NSString *> *buttons = RCTConvertOptionalVecToArray(options.options(), ^id(NSString *element) {
return element;
});
NSInteger cancelButtonIndex =
options.cancelButtonIndex() ? [RCTConvert NSInteger:@(*options.cancelButtonIndex())] : -1;
NSArray<NSNumber *> *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;
}

Просмотреть файл

@ -17,7 +17,6 @@ typedef NS_ENUM(NSInteger, RCTAlertViewStyle) {
RCTAlertViewStyleLoginAndPasswordInput
};
@interface RCTAlertManager : NSObject <RCTBridgeModule, RCTInvalidating>
@end

Просмотреть файл

@ -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() <NativeAlertManagerSpec>
@interface RCTAlertManager () <NativeAlertManagerSpec>
@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<NSDictionary *> *buttons = [RCTConvert NSDictionaryArray:RCTConvertOptionalVecToArray(args.buttons(), ^id(id<NSObject> element) { return element; })];
NSArray<NSDictionary *> *buttons =
[RCTConvert NSDictionaryArray:RCTConvertOptionalVecToArray(args.buttons(), ^id(id<NSObject> 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<NSObject> 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<NSObject> 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<NSString *, NSString *> *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<NSString *, NSString *> *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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeAlertManagerSpecJSI>(self, jsInvoker);
}
@end
Class RCTAlertManagerCls(void) {
Class RCTAlertManagerCls(void)
{
return RCTAlertManager.class;
}

Просмотреть файл

@ -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() <NativeAppStateSpec>
@interface RCTAppState () <NativeAppStateSpec>
@end
@implementation RCTAppState
{
@implementation RCTAppState {
NSString *_lastKnownState;
}
@ -61,7 +57,7 @@ RCT_EXPORT_MODULE()
- (facebook::react::ModuleConstants<JS::NativeAppState::Constants>)getConstants
{
return facebook::react::typedConstants<JS::NativeAppState::Constants>({
.initialAppState = RCTCurrentAppState(),
.initialAppState = RCTCurrentAppState(),
});
}
@ -69,17 +65,18 @@ RCT_EXPORT_MODULE()
- (NSArray<NSString *> *)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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeAppStateSpecJSI>(self, jsInvoker);
}
@end
Class RCTAppStateCls(void) {
Class RCTAppStateCls(void)
{
return RCTAppState.class;
}

Просмотреть файл

@ -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 () <NativeAppearanceSpec>
@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<NSString *> *)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;
}

Просмотреть файл

@ -19,7 +19,7 @@
*
* Keys and values must always be strings or an error is returned.
*/
@interface RCTAsyncLocalStorage : NSObject <RCTBridgeModule,RCTInvalidating>
@interface RCTAsyncLocalStorage : NSObject <RCTBridgeModule, RCTInvalidating>
@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<NSString *> *)keys callback:(RCTResponseSenderBlock)callback;
// Add multiple key value pairs to the cache.
- (void)multiSet:(NSArray<NSArray<NSString *> *> *)kvPairs callback:(RCTResponseSenderBlock)callback;
@end

Просмотреть файл

@ -9,9 +9,9 @@
#import <Foundation/Foundation.h>
#import <FBReactNativeSpec/FBReactNativeSpec.h>
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>
#import <FBReactNativeSpec/FBReactNativeSpec.h>
#import <React/RCTConvert.h>
#import <React/RCTLog.h>
@ -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() <NativeAsyncStorageSpec>
@interface RCTAsyncLocalStorage () <NativeAsyncStorageSpec>
@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<NSArray<NSString *> *> *)result
- (NSDictionary *)_appendItemForKey:(NSString *)key toArray:(NSMutableArray<NSArray<NSString *> *> *)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<NSString *> *)keys
callback:(RCTResponseSenderBlock)callback)
RCT_EXPORT_METHOD(multiGet : (NSArray<NSString *> *)keys callback : (RCTResponseSenderBlock)callback)
{
NSDictionary *errorOut = [self _ensureSetup];
if (errorOut) {
callback(@[@[errorOut], (id)kCFNull]);
callback(@[ @[ errorOut ], (id)kCFNull ]);
return;
}
NSMutableArray<NSDictionary *> *errors;
@ -350,18 +352,17 @@ RCT_EXPORT_METHOD(multiGet:(NSArray<NSString *> *)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<NSArray<NSString *> *> *)kvPairs
callback:(RCTResponseSenderBlock)callback)
RCT_EXPORT_METHOD(multiSet : (NSArray<NSArray<NSString *> *> *)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<NSArray<NSString *> *> *)kvPairs
if (changedManifest) {
[self _writeManifest:&errors];
}
callback(@[RCTNullIfNil(errors)]);
callback(@[ RCTNullIfNil(errors) ]);
}
RCT_EXPORT_METHOD(multiMerge:(NSArray<NSArray<NSString *> *> *)kvPairs
callback:(RCTResponseSenderBlock)callback)
RCT_EXPORT_METHOD(multiMerge : (NSArray<NSArray<NSString *> *> *)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<NSArray<NSString *> *> *)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<NSArray<NSString *> *> *)kvPairs
if (changedManifest) {
[self _writeManifest:&errors];
}
callback(@[RCTNullIfNil(errors)]);
callback(@[ RCTNullIfNil(errors) ]);
}
RCT_EXPORT_METHOD(multiRemove:(NSArray<NSString *> *)keys
callback:(RCTResponseSenderBlock)callback)
RCT_EXPORT_METHOD(multiRemove : (NSArray<NSString *> *)keys callback : (RCTResponseSenderBlock)callback)
{
NSDictionary *errorOut = [self _ensureSetup];
if (errorOut) {
callback(@[@[errorOut]]);
callback(@[ @[ errorOut ] ]);
return;
}
NSMutableArray<NSDictionary *> *errors;
@ -440,34 +439,36 @@ RCT_EXPORT_METHOD(multiRemove:(NSArray<NSString *> *)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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeAsyncStorageSpecJSI>(self, jsInvoker);
}
@end
Class RCTAsyncLocalStorageCls(void) {
Class RCTAsyncLocalStorageCls(void)
{
return RCTAsyncLocalStorage.class;
}

Просмотреть файл

@ -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<TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<CallInvoker>)jsInvoker
@ -47,6 +45,7 @@ RCT_EXPORT_METHOD(getString:(RCTPromiseResolveBlock)resolve
@end
Class RCTClipboardCls(void) {
Class RCTClipboardCls(void)
{
return RCTClipboard.class;
}

Просмотреть файл

@ -5,9 +5,9 @@
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTDevLoadingViewProtocol.h>
#import <UIKit/UIKit.h>
@interface RCTDevLoadingView : NSObject <RCTDevLoadingViewProtocol, RCTBridgeModule>
@end

Просмотреть файл

@ -9,13 +9,13 @@
#import <QuartzCore/QuartzCore.h>
#import <FBReactNativeSpec/FBReactNativeSpec.h>
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTDefines.h>
#import <React/RCTDevLoadingViewSetEnabled.h>
#import <React/RCTModalHostViewController.h>
#import <React/RCTUtils.h>
#import <FBReactNativeSpec/FBReactNativeSpec.h>
#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<TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<CallInvoker>)jsInvoker
{
return std::make_shared<NativeDevLoadingViewSpecJSI>(self, jsInvoker);
@ -203,6 +219,7 @@ RCT_EXPORT_METHOD(hide)
#endif
Class RCTDevLoadingViewCls(void) {
Class RCTDevLoadingViewCls(void)
{
return RCTDevLoadingView.class;
}

Просмотреть файл

@ -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

Просмотреть файл

@ -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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeDevMenuSpecJSI>(self, jsInvoker);
}
@ -502,7 +501,7 @@ RCT_EXPORT_METHOD(setHotLoadingEnabled : (BOOL)enabled)
#else // Unavailable when not in dev mode
@interface RCTDevMenu() <NativeDevMenuSpec>
@interface RCTDevMenu () <NativeDevMenuSpec>
@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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeDevMenuSpecJSI>(self, jsInvoker);
}
@ -568,6 +568,7 @@ RCT_EXPORT_METHOD(setHotLoadingEnabled : (BOOL)enabled)
@end
Class RCTDevMenuCls(void) {
Class RCTDevMenuCls(void)
{
return RCTDevMenu.class;
}

Просмотреть файл

@ -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<NSString *> *)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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeDevSettingsSpecJSI>(self, jsInvoker);
}
@ -515,7 +519,8 @@ RCT_EXPORT_METHOD(addMenuItem:(NSString *)title)
{
}
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeDevSettingsSpecJSI>(self, jsInvoker);
}
@ -537,6 +542,7 @@ RCT_EXPORT_METHOD(addMenuItem:(NSString *)title)
@end
Class RCTDevSettingsCls(void) {
Class RCTDevSettingsCls(void)
{
return RCTDevSettings.class;
}

Просмотреть файл

@ -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<NSString *, NSNumber *> *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<NSString *, NSNumber *> *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<NSString *, id> *)constantsToExport
@ -127,12 +123,12 @@ static NSDictionary *RCTExportedDimensions(RCTBridge *bridge)
- (NSDictionary<NSString *, id> *)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 <SafeAreaView> 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;
}

Просмотреть файл

@ -13,11 +13,17 @@ NS_ASSUME_NONNULL_BEGIN
@protocol RCTExceptionsManagerDelegate <NSObject>
- (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<RCTExceptionsManagerDelegate>)delegate;
- (void)reportSoftException:(nullable NSString *)message stack:(nullable NSArray<NSDictionary *> *)stack exceptionId:(double)exceptionId;
- (void)reportFatalException:(nullable NSString *)message stack:(nullable NSArray<NSDictionary *> *)stack exceptionId:(double)exceptionId;
- (void)reportSoftException:(nullable NSString *)message
stack:(nullable NSArray<NSDictionary *> *)stack
exceptionId:(double)exceptionId;
- (void)reportFatalException:(nullable NSString *)message
stack:(nullable NSArray<NSDictionary *> *)stack
exceptionId:(double)exceptionId;
@property (nonatomic, weak) id<RCTExceptionsManagerDelegate> delegate;

Просмотреть файл

@ -17,7 +17,7 @@
#import "CoreModulesPlugins.h"
@interface RCTExceptionsManager() <NativeExceptionsManagerSpec>
@interface RCTExceptionsManager () <NativeExceptionsManagerSpec>
@end
@ -35,54 +35,68 @@ RCT_EXPORT_MODULE()
return self;
}
- (void)reportSoft: (NSString *)message stack:(NSArray<NSDictionary *> *)stack exceptionId:(double)exceptionId suppressRedBox: (BOOL) suppressRedBox {
if (!suppressRedBox) {
[_bridge.redBox showErrorMessage:message withStack:stack errorCookie:((int)exceptionId)];
}
- (void)reportSoft:(NSString *)message
stack:(NSArray<NSDictionary *> *)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<NSDictionary *> *)stack exceptionId:(double)exceptionId suppressRedBox: (BOOL) suppressRedBox {
if (!suppressRedBox) {
[_bridge.redBox showErrorMessage:message withStack:stack errorCookie:((int)exceptionId)];
}
- (void)reportFatal:(NSString *)message
stack:(NSArray<NSDictionary *> *)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<NSDictionary *> *)stack
exceptionId:(double)exceptionId)
RCT_EXPORT_METHOD(reportSoftException
: (NSString *)message stack
: (NSArray<NSDictionary *> *)stack exceptionId
: (double)exceptionId)
{
[self reportSoft:message stack:stack exceptionId:exceptionId suppressRedBox:NO];
}
RCT_EXPORT_METHOD(reportFatalException:(NSString *)message
stack:(NSArray<NSDictionary *> *)stack
exceptionId:(double) exceptionId)
RCT_EXPORT_METHOD(reportFatalException
: (NSString *)message stack
: (NSArray<NSDictionary *> *)stack exceptionId
: (double)exceptionId)
{
[self reportFatal:message stack:stack exceptionId:exceptionId suppressRedBox:NO];
}
RCT_EXPORT_METHOD(updateExceptionMessage:(NSString *)message
stack:(NSArray<NSDictionary *> *)stack
exceptionId:(double)exceptionId)
RCT_EXPORT_METHOD(updateExceptionMessage
: (NSString *)message stack
: (NSArray<NSDictionary *> *)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<NSDictionary *> *)stack)
RCT_EXPORT_METHOD(reportUnhandledException : (NSString *)message stack : (NSArray<NSDictionary *> *)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<NSDictionary *> *)stack` in
// reportFatalException etc with a typed interface.
NSMutableArray<NSDictionary *> *stackArray = [NSMutableArray<NSDictionary *> 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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeExceptionsManagerSpecJSI>(self, jsInvoker);
}

Просмотреть файл

@ -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;

Просмотреть файл

@ -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
{

Просмотреть файл

@ -7,8 +7,8 @@
#import <FBReactNativeSpec/FBReactNativeSpec.h>
#import "RCTI18nManager.h"
#import <React/RCTI18nUtil.h>
#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;
}

Просмотреть файл

@ -14,7 +14,7 @@
static NSDictionary *RCTParseKeyboardNotification(NSNotification *notification);
@interface RCTKeyboardObserver() <NativeKeyboardObserverSpec>
@interface RCTKeyboardObserver () <NativeKeyboardObserverSpec>
@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<NSString *> *)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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeKeyboardObserverSpecJSI>(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<UIViewAnimationCurve>([userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]);
UIViewAnimationCurve curve =
static_cast<UIViewAnimationCurve>([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;
}

Просмотреть файл

@ -9,7 +9,6 @@
#import <FBReactNativeSpec/FBReactNativeSpec.h>
#import <React/RCTBridge.h>
#import <React/RCTRootView.h>
#import <React/RCTConvert.h>
#import <React/RCTDefines.h>
#import <React/RCTErrorInfo.h>
@ -17,7 +16,7 @@
#import <React/RCTJSStackFrame.h>
#import <React/RCTRedBoxSetEnabled.h>
#import <React/RCTReloadCommand.h>
#import <React/RCTRedBoxSetEnabled.h>
#import <React/RCTRootView.h>
#import <React/RCTSurface.h>
#import <React/RCTUtils.h>
@ -32,8 +31,7 @@
@interface RCTLogBoxView : UIWindow
@end
@implementation RCTLogBoxView
{
@implementation RCTLogBoxView {
RCTSurface *_surface;
}
@ -77,8 +75,7 @@
@interface RCTLogBox () <NativeLogBoxSpec>
@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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeLogBoxSpecJSI>(self, jsInvoker);
}
@ -121,7 +119,7 @@ RCT_EXPORT_METHOD(hide)
#else // Disabled
@interface RCTLogBox() <NativeLogBoxSpec>
@interface RCTLogBox () <NativeLogBoxSpec>
@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<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeLogBoxSpecJSI>(self, jsInvoker);
}
@ -147,6 +148,7 @@ RCT_EXPORT_METHOD(hide)
#endif
Class RCTLogBoxCls(void) {
Class RCTLogBoxCls(void)
{
return RCTLogBox.class;
}

Просмотреть файл

@ -17,6 +17,7 @@
#import <React/RCTDevSettings.h>
#import <React/RCTBridge+Private.h>
#import <React/RCTBridge.h>
#import <React/RCTFPSGraph.h>
#import <React/RCTInvalidating.h>
@ -24,7 +25,6 @@
#import <React/RCTPerformanceLogger.h>
#import <React/RCTRootView.h>
#import <React/RCTUIManager.h>
#import <React/RCTBridge+Private.h>
#import <React/RCTUtils.h>
#import <ReactCommon/RCTTurboModule.h>
@ -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 <RCTBridgeModule, RCTTurboModule, RCTInvalidating, UITableViewDataSource, UITableViewDelegate>
@interface RCTPerfMonitor
: NSObject <RCTBridgeModule, RCTTurboModule, RCTInvalidating, UITableViewDataSource, UITableViewDelegate>
#if __has_include(<React/RCTDevMenu.h>)
@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<NSNumber *> *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

Просмотреть файл

@ -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<JS::NativePlatformConstantsIOS::Constants>({
.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<double>{} : [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<double>{}
: [versions[@"prerelease"] doubleValue]}),
});
}
@ -81,6 +83,7 @@ RCT_EXPORT_MODULE(PlatformConstants)
@end
Class RCTPlatformCls(void) {
Class RCTPlatformCls(void)
{
return RCTPlatform.class;
}

Просмотреть файл

@ -29,8 +29,12 @@ typedef void (^RCTRedBoxButtonPressHandler)(void);
- (void)updateErrorMessage:(NSString *)message withStack:(NSArray<NSDictionary *> *)stack errorCookie:(int)errorCookie;
- (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray<RCTJSStackFrame *> *)stack;
- (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray<RCTJSStackFrame *> *)stack;
- (void)showErrorMessage:(NSString *)message withParsedStack:(NSArray<RCTJSStackFrame *> *)stack errorCookie:(int)errorCookie;
- (void)updateErrorMessage:(NSString *)message withParsedStack:(NSArray<RCTJSStackFrame *> *)stack errorCookie:(int)errorCookie;
- (void)showErrorMessage:(NSString *)message
withParsedStack:(NSArray<RCTJSStackFrame *> *)stack
errorCookie:(int)errorCookie;
- (void)updateErrorMessage:(NSString *)message
withParsedStack:(NSArray<RCTJSStackFrame *> *)stack
errorCookie:(int)errorCookie;
- (void)dismiss;

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -37,7 +37,7 @@ RCT_EXPORT_MODULE()
- (NSDictionary<NSString *, id> *)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;
}

Просмотреть файл

@ -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() <NativeStatusBarManagerIOSSpec>
@interface RCTStatusBarManager () <NativeStatusBarManagerIOSSpec>
@end
#endif
@ -185,8 +186,8 @@ RCT_EXPORT_METHOD(setNetworkActivityIndicatorVisible : (BOOL)visible)
- (facebook::react::ModuleConstants<JS::NativeStatusBarManagerIOS::Constants>)getConstants
{
return facebook::react::typedConstants<JS::NativeStatusBarManagerIOS::Constants>({
.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<JS::NativeStatusBarManagerIOS::Constants>)[self getConstants];
}
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModuleWithJsInvoker:
(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
return std::make_shared<facebook::react::NativeStatusBarManagerIOSSpecJSI>(self, jsInvoker);
}
@ -204,6 +206,7 @@ RCT_EXPORT_METHOD(setNetworkActivityIndicatorVisible : (BOOL)visible)
@end
Class RCTStatusBarManagerCls(void) {
Class RCTStatusBarManagerCls(void)
{
return RCTStatusBarManager.class;
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше